forked from osaurus-ai/osaurus
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMemoryDatabase.swift
More file actions
2699 lines (2525 loc) · 111 KB
/
Copy pathMemoryDatabase.swift
File metadata and controls
2699 lines (2525 loc) · 111 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// MemoryDatabase.swift
// osaurus
//
// SQLite database for the v2 memory system.
// WAL mode, serial queue, versioned migrations.
//
// Tables:
// identity — single row of stable user facts
// pinned_facts — promoted, salience-scored facts (replaces v1 memory_entries)
// episodes — per-session digests (replaces v1 conversation_summaries)
// transcript — raw conversation turns (renamed from v1 conversation_chunks)
// pending_signals — buffered turns awaiting end-of-session distillation
// processing_log — distillation/consolidation latency + status
//
// v5 migration carries forward identity, episodes, and transcript from
// the old schema. The noisy v1 working-memory entries, profile events,
// verification audit log, agent activity, embeddings cache, and graph
// tables are all dropped — `pinned_facts` rebuilds organically from new
// conversations and consolidator promotion.
//
import CryptoKit
import Foundation
import OsaurusSQLCipher
public enum MemoryDatabaseError: Error, LocalizedError {
case failedToOpen(String)
case failedToExecute(String)
case failedToPrepare(String)
case migrationFailed(String)
case databaseFromNewerVersion(found: Int, expected: Int)
case notOpen
public var errorDescription: String? {
switch self {
case .failedToOpen(let msg): return "Failed to open memory database: \(msg)"
case .failedToExecute(let msg): return "Failed to execute query: \(msg)"
case .failedToPrepare(let msg): return "Failed to prepare statement: \(msg)"
case .migrationFailed(let msg): return "Memory migration failed: \(msg)"
case .databaseFromNewerVersion(let found, let expected):
return
"Memory database is schema v\(found) but this build supports up to v\(expected). Refusing to open to avoid forward-version corruption."
case .notOpen: return "Memory database is not open"
}
}
}
public final class MemoryDatabase: @unchecked Sendable {
public static let shared = MemoryDatabase()
private static let schemaVersion = 9
nonisolated(unsafe) private static let iso8601Formatter: ISO8601DateFormatter = {
let f = ISO8601DateFormatter()
return f
}()
private static func iso8601Now() -> String {
iso8601Formatter.string(from: Date())
}
private var db: OpaquePointer?
private let queue = DispatchQueue(label: "ai.osaurus.memory.database")
private let stmtCache = PreparedStatementCache(capacity: 96)
/// Why the most recent `open()` failed (connection or migration),
/// kept for the diagnostics panel — `isOpen == false` alone gives the
/// user nothing actionable. Guarded by `queue`.
private var _lastOpenError: String?
public var isOpen: Bool {
queue.sync { db != nil }
}
public var lastOpenErrorDescription: String? {
queue.sync { _lastOpenError }
}
/// Schema version this build expects (`PRAGMA user_version` once all
/// migrations have run). Surfaced by diagnostics.
public static var expectedSchemaVersion: Int { latestSchemaVersion }
/// Current `PRAGMA user_version` of the open database, or nil when
/// closed. Surfaced by diagnostics.
public func schemaUserVersion() -> Int? {
queue.sync {
guard db != nil else { return nil }
return try? getSchemaVersion()
}
}
public static func waitForSharedOpen(
timeoutSeconds: TimeInterval,
pollInterval: TimeInterval = 0.1
) async -> Bool {
if shared.isOpen { return true }
let deadline = Date().addingTimeInterval(max(0, timeoutSeconds))
while Date() < deadline {
let nanos = UInt64(max(0.01, pollInterval) * 1_000_000_000)
try? await Task.sleep(nanoseconds: nanos)
if shared.isOpen { return true }
}
return shared.isOpen
}
init() {}
deinit { close() }
// MARK: - Lifecycle
public func open() throws {
// See `ChatHistoryDatabase.open()` for the gate rationale —
// every `*Database.open()` parks while a key rotation is in
// flight so we can't open a half-rekeyed file.
StorageMutationGate.blockingAwaitNotMutating()
try queue.sync {
guard db == nil else { return }
OsaurusPaths.ensureExistsSilent(OsaurusPaths.memory())
do {
try openConnection()
} catch {
_lastOpenError = error.localizedDescription
throw error
}
do {
try runMigrations()
_lastOpenError = nil
} catch {
// Close the half-opened connection before rethrowing.
// Leaving `db` set here turns every retry of `open()` into
// an instant no-op success (`guard db == nil`), so the app
// would run against the unmigrated schema and the migration
// failure would never surface anywhere.
_lastOpenError = "migration: \(error.localizedDescription)"
stmtCache.clear()
if let connection = db {
sqlite3_close(connection)
db = nil
}
throw error
}
}
OsaurusDatabaseHandle.register(maintenanceHandle)
}
private lazy var maintenanceHandle = OsaurusDatabaseHandle(
name: "memory",
exec: { [weak self] sql in
self?.queue.sync {
guard self?.db != nil else { return }
try? self?.executeRaw(sql)
}
},
closer: { [weak self] in self?.close() },
reopener: { [weak self] in try? self?.open() }
)
/// Open an in-memory database for testing. **Plaintext** — see
/// `SQLCipherIntegrationTests` for encrypted-DB coverage.
public func openInMemory() throws {
try queue.sync {
guard db == nil else { return }
db = try EncryptedSQLiteOpener.open(
path: ":memory:",
key: nil,
applyPerfPragmas: false
)
try runMigrations()
}
}
public func close() {
OsaurusDatabaseHandle.deregister(name: "memory")
queue.sync {
stmtCache.clear()
guard let connection = db else { return }
try? executeRaw("PRAGMA optimize")
sqlite3_close(connection)
db = nil
}
}
private func openConnection() throws {
let path = OsaurusPaths.memoryDatabaseFile().path
let key = try StorageKeyManager.shared.currentKey()
do {
db = try EncryptedSQLiteOpener.open(path: path, key: key)
} catch let error as EncryptedSQLiteError {
throw MemoryDatabaseError.failedToOpen(error.localizedDescription)
}
}
// MARK: - Schema & Migrations
/// Highest schema version this build knows how to produce. Opening a DB
/// stamped newer than this is refused (forward-version fail-fast).
private static let latestSchemaVersion = 9
private func runMigrations() throws {
let currentVersion = try getSchemaVersion()
// Refuse a database written by a newer build: reading its rows under
// the older schema would silently corrupt forward-version data.
if currentVersion > Self.latestSchemaVersion {
throw MemoryDatabaseError.databaseFromNewerVersion(
found: currentVersion,
expected: Self.latestSchemaVersion
)
}
// Each step is atomic (BEGIN/COMMIT). A failure mid-migration rolls
// back to the prior version instead of leaving a half-applied schema;
// the `setSchemaVersion` bump commits with the step.
if currentVersion < 5 {
try runMigrationStep(5) { try self.migrateToV5(from: currentVersion) }
}
if currentVersion < 6 {
try runMigrationStep(6, migrateToV6)
}
if currentVersion < 7 {
// `migrateToV7` owns its own BEGIN/COMMIT (table rebuild), so it
// must NOT be double-wrapped — a nested BEGIN traps SQLite.
try migrateToV7()
}
if currentVersion < 8 {
// Same self-managed BEGIN/COMMIT as v7 — do not double-wrap.
try migrateToV8()
}
if currentVersion < 9 {
// Same self-managed BEGIN/COMMIT as v7/v8 — do not double-wrap.
try migrateToV9()
}
}
/// Run one migration body atomically. Called only from `runMigrations`,
/// which already holds the database queue, so it uses raw
/// `BEGIN/COMMIT/ROLLBACK` (no nested `queue.sync`).
private func runMigrationStep(_ version: Int, _ body: () throws -> Void) throws {
try executeRaw("BEGIN TRANSACTION")
do {
try body()
try executeRaw("COMMIT")
} catch {
try? executeRaw("ROLLBACK")
throw MemoryDatabaseError.migrationFailed("v\(version): \(error.localizedDescription)")
}
}
private func getSchemaVersion() throws -> Int {
var version: Int = 0
try executeRaw("PRAGMA user_version") { stmt in
if sqlite3_step(stmt) == SQLITE_ROW {
version = Int(sqlite3_column_int(stmt, 0))
}
}
return version
}
private func setSchemaVersion(_ version: Int) throws {
try executeRaw("PRAGMA user_version = \(version)")
}
/// V5 migration: rebuild around the v2 schema. Carries forward
/// `user_profile` → `identity.content`, `user_edits` → `identity.overrides`,
/// `conversation_summaries` → `episodes`, and `conversation_chunks` → `transcript`.
/// Drops `memory_entries`, `profile_events`, `memory_events`, `agent_activity`,
/// `embeddings`, and the graph tables (`entities` / `relationships`).
private func migrateToV5(from previousVersion: Int) throws {
MemoryLogger.database.info("Running v5 migration (previous version: \(previousVersion))")
// Connections open with foreign_keys = ON, so the DROP TABLE sweep below
// would implicitly delete rows from each old table as it is dropped and
// fail with "FOREIGN KEY constraint failed" whenever a not-yet-dropped
// child still references a parent being dropped. Defer FK checks to the
// commit of this migration: unlike foreign_keys, defer_foreign_keys is
// settable inside a transaction and resets when it commits. By then every
// old table is gone and the v5 tables declare no FKs, so nothing is left
// to violate. Without this, v5 rolls back on affected installs and the
// whole migration chain (v6-v9) never runs.
try executeRaw("PRAGMA defer_foreign_keys = ON")
// Create v2 tables first so we can copy into them within the same migration.
try createV5Tables()
// Carry-over from v1-v4 if those tables exist.
if previousVersion >= 1 {
try carryOverIdentityFromV1()
try carryOverEpisodesFromV1()
try carryOverTranscriptFromV1()
}
// Drop everything we don't need anymore.
if previousVersion >= 1 {
for table in [
"memory_entries",
"memory_events",
"profile_events",
"user_profile",
"user_edits",
"conversation_summaries",
"conversation_chunks",
"conversations",
"agent_activity",
"embeddings",
"entities",
"relationships",
"schema_version",
] {
try executeRaw("DROP TABLE IF EXISTS \(table)")
}
}
try setSchemaVersion(5)
MemoryLogger.database.info("v5 migration completed")
}
/// V6 migration: add three FTS5 contentless-mirror virtual tables
/// + sync triggers so the LIKE-fallback search paths can use
/// `MATCH` instead of full-table-scan `LIKE '%foo%'`.
///
/// SQLCipher transparently encrypts the FTS5 shadow tables — we
/// don't have to do anything extra for at-rest protection. The
/// virtual tables use `content=…` external-content mode so the
/// authoritative text still lives in the existing tables; FTS5
/// only stores tokens.
///
/// Backfill is done in one INSERT … SELECT after the triggers are
/// in place so any concurrent insert doesn't race with the
/// migration.
private func migrateToV6() throws {
MemoryLogger.database.info("Running v6 migration (FTS5 indexes)")
// pinned_facts → fts_pinned (content column only)
try executeRaw(
"""
CREATE VIRTUAL TABLE IF NOT EXISTS fts_pinned USING fts5(
content,
content='pinned_facts',
content_rowid='rowid',
tokenize='unicode61 remove_diacritics 2'
)
"""
)
try executeRaw(
"""
CREATE TRIGGER IF NOT EXISTS pinned_facts_ai AFTER INSERT ON pinned_facts BEGIN
INSERT INTO fts_pinned(rowid, content) VALUES (new.rowid, new.content);
END
"""
)
try executeRaw(
"""
CREATE TRIGGER IF NOT EXISTS pinned_facts_ad AFTER DELETE ON pinned_facts BEGIN
INSERT INTO fts_pinned(fts_pinned, rowid, content) VALUES('delete', old.rowid, old.content);
END
"""
)
try executeRaw(
"""
CREATE TRIGGER IF NOT EXISTS pinned_facts_au AFTER UPDATE ON pinned_facts BEGIN
INSERT INTO fts_pinned(fts_pinned, rowid, content) VALUES('delete', old.rowid, old.content);
INSERT INTO fts_pinned(rowid, content) VALUES (new.rowid, new.content);
END
"""
)
// episodes → fts_episodes (summary + topics + entities)
try executeRaw(
"""
CREATE VIRTUAL TABLE IF NOT EXISTS fts_episodes USING fts5(
summary, topics_csv, entities_csv,
content='episodes',
content_rowid='id',
tokenize='unicode61 remove_diacritics 2'
)
"""
)
try executeRaw(
"""
CREATE TRIGGER IF NOT EXISTS episodes_ai AFTER INSERT ON episodes BEGIN
INSERT INTO fts_episodes(rowid, summary, topics_csv, entities_csv)
VALUES (new.id, new.summary, new.topics_csv, new.entities_csv);
END
"""
)
try executeRaw(
"""
CREATE TRIGGER IF NOT EXISTS episodes_ad AFTER DELETE ON episodes BEGIN
INSERT INTO fts_episodes(fts_episodes, rowid, summary, topics_csv, entities_csv)
VALUES('delete', old.id, old.summary, old.topics_csv, old.entities_csv);
END
"""
)
try executeRaw(
"""
CREATE TRIGGER IF NOT EXISTS episodes_au AFTER UPDATE ON episodes BEGIN
INSERT INTO fts_episodes(fts_episodes, rowid, summary, topics_csv, entities_csv)
VALUES('delete', old.id, old.summary, old.topics_csv, old.entities_csv);
INSERT INTO fts_episodes(rowid, summary, topics_csv, entities_csv)
VALUES (new.id, new.summary, new.topics_csv, new.entities_csv);
END
"""
)
// transcript → fts_transcript (content)
try executeRaw(
"""
CREATE VIRTUAL TABLE IF NOT EXISTS fts_transcript USING fts5(
content,
content='transcript',
content_rowid='id',
tokenize='unicode61 remove_diacritics 2'
)
"""
)
try executeRaw(
"""
CREATE TRIGGER IF NOT EXISTS transcript_ai AFTER INSERT ON transcript BEGIN
INSERT INTO fts_transcript(rowid, content) VALUES (new.id, new.content);
END
"""
)
try executeRaw(
"""
CREATE TRIGGER IF NOT EXISTS transcript_ad AFTER DELETE ON transcript BEGIN
INSERT INTO fts_transcript(fts_transcript, rowid, content) VALUES('delete', old.id, old.content);
END
"""
)
try executeRaw(
"""
CREATE TRIGGER IF NOT EXISTS transcript_au AFTER UPDATE ON transcript BEGIN
INSERT INTO fts_transcript(fts_transcript, rowid, content) VALUES('delete', old.id, old.content);
INSERT INTO fts_transcript(rowid, content) VALUES (new.id, new.content);
END
"""
)
// Backfill (idempotent — INSERT into FTS is safe even if
// triggers caught everything).
try executeRaw(
"INSERT INTO fts_pinned(rowid, content) SELECT rowid, content FROM pinned_facts"
)
try executeRaw(
"""
INSERT INTO fts_episodes(rowid, summary, topics_csv, entities_csv)
SELECT id, summary, topics_csv, entities_csv FROM episodes
"""
)
try executeRaw(
"INSERT INTO fts_transcript(rowid, content) SELECT id, content FROM transcript"
)
try setSchemaVersion(6)
MemoryLogger.database.info("v6 migration completed (FTS5 ready)")
}
/// V7 migration: drop the orphan `pending_signals.signal_type` column.
///
/// Some pre-shipping versions of the v5 schema declared an extra
/// `signal_type TEXT NOT NULL` column on `pending_signals` that was
/// later removed from the source. Users whose database was created
/// against that earlier schema kept the orphan column — and because
/// the runtime `INSERT INTO pending_signals (...)` doesn't bind it,
/// every buffer-turn write throws `SQLITE_CONSTRAINT_NOTNULL`
/// (extended code 1299). The pre-fix version of `executeUpdate`
/// silently swallowed the failure, so the bug was invisible until
/// the diagnostics panel started surfacing the underlying SQLite
/// error.
///
/// Fix: rebuild the table with the canonical schema and copy the
/// preserved columns over. Indexes are recreated by name. We
/// intentionally drop the `signal_type` *values* — the runtime never
/// reads them, and pending signals are short-lived (distilled within
/// the debounce window or purged within `episodeRetentionDays`).
/// Skipping the rebuild when the column is already absent makes the
/// migration a fast no-op for fresh installs.
private func migrateToV7() throws {
MemoryLogger.database.info("Running v7 migration (drop orphan pending_signals.signal_type)")
try dropOrphanSignalTypeColumnIfPresent()
try setSchemaVersion(7)
}
/// V8 migration: re-run the orphan `signal_type` drop.
///
/// `migrateToV7` is version-gated behind `currentVersion < 7`, so any
/// database that was stamped `user_version = 7` *while still carrying*
/// the orphan column (an intermediate pre-release build bumped the
/// version without effectively dropping it) never got repaired — and
/// because the runtime `INSERT INTO pending_signals` doesn't bind
/// `signal_type`, every buffer-turn write throws
/// `SQLITE_CONSTRAINT_NOTNULL` (extended code 1299), so no turn ever
/// reaches the database and no episodes are ever produced. Re-running
/// the same idempotent drop at v8 lets those stuck databases self-heal;
/// it's a fast no-op for everyone already canonical.
private func migrateToV8() throws {
MemoryLogger.database.info("Running v8 migration (re-check orphan pending_signals.signal_type)")
try dropOrphanSignalTypeColumnIfPresent()
try setSchemaVersion(8)
}
/// V9 migration: re-run the orphan `signal_type` drop, now rename-free.
///
/// The v7/v8 rebuild started with `ALTER TABLE ... RENAME`, which makes
/// SQLite re-parse every view and trigger in the database — a single
/// stale schema object left behind by an earlier build fails that
/// statement, and with it the whole migration, on every launch.
/// Combined with the old `open()` behavior (a failed migration left the
/// connection set, so retries no-opped into "success"), affected
/// installs kept running against the orphan schema with no visible
/// error and their `user_version` never advanced. The rebuild in
/// `dropOrphanSignalTypeColumnIfPresent` is now a copy-out/copy-back
/// through a scratch table that only ever parses `pending_signals`
/// itself, so unrelated schema debris can't block it. Re-running it at
/// v9 heals databases whose earlier repair attempts kept failing; it's
/// a fast no-op for everyone already canonical.
private func migrateToV9() throws {
MemoryLogger.database.info("Running v9 migration (rename-free orphan signal_type drop)")
try dropOrphanSignalTypeColumnIfPresent()
try setSchemaVersion(9)
}
/// Detect and drop the orphan `pending_signals.signal_type` column if it
/// is present, leaving the canonical schema behind. Idempotent: a no-op
/// when the column is already absent. Does **not** stamp the schema
/// version — the calling migration owns that.
private func dropOrphanSignalTypeColumnIfPresent() throws {
var hasOrphan = false
try executeRaw("PRAGMA table_info(pending_signals)") { stmt in
while sqlite3_step(stmt) == SQLITE_ROW {
let name = String(cString: sqlite3_column_text(stmt, 1))
if name == "signal_type" {
hasOrphan = true
break
}
}
}
guard hasOrphan else {
MemoryLogger.database.info("pending_signals already canonical, no orphan column to drop")
return
}
// Rebuild without `ALTER TABLE`: a RENAME makes SQLite re-parse
// every view and trigger in the database, so a single stale schema
// object from an earlier build fails the rebuild outright. A
// copy-out/copy-back through a scratch table only ever parses
// `pending_signals` itself. Wrap in a transaction so a crash
// mid-flight doesn't leave a half-rebuilt table.
try executeRaw("BEGIN TRANSACTION")
do {
// Scratch tables an interrupted earlier rebuild may have left
// behind; they only ever hold a stale duplicate of
// `pending_signals`, never the sole copy.
try executeRaw("DROP TABLE IF EXISTS pending_signals_v6")
try executeRaw("DROP TABLE IF EXISTS pending_signals_old")
try executeRaw("DROP TABLE IF EXISTS pending_signals_scratch")
try executeRaw(
"""
CREATE TABLE pending_signals_scratch AS
SELECT id, agent_id, conversation_id, user_message,
assistant_message, status, created_at
FROM pending_signals
"""
)
try executeRaw("DROP TABLE pending_signals")
try executeRaw(
"""
CREATE TABLE pending_signals (
id INTEGER PRIMARY KEY AUTOINCREMENT,
agent_id TEXT NOT NULL,
conversation_id TEXT NOT NULL,
user_message TEXT NOT NULL,
assistant_message TEXT,
status TEXT NOT NULL DEFAULT 'pending',
created_at TEXT NOT NULL DEFAULT (datetime('now'))
)
"""
)
try executeRaw(
"""
INSERT INTO pending_signals
(id, agent_id, conversation_id, user_message, assistant_message, status, created_at)
SELECT
id, agent_id, conversation_id, user_message, assistant_message, status, created_at
FROM pending_signals_scratch
"""
)
try executeRaw("DROP TABLE pending_signals_scratch")
// The indexes were dropped with the original table; recreate
// against the rebuilt one.
try executeRaw(
"CREATE INDEX IF NOT EXISTS idx_pending_conv_status ON pending_signals(conversation_id, status)"
)
try executeRaw(
"CREATE INDEX IF NOT EXISTS idx_pending_agent_status ON pending_signals(agent_id, status)"
)
try executeRaw("COMMIT")
} catch {
try? executeRaw("ROLLBACK")
throw error
}
MemoryLogger.database.info("rebuilt pending_signals without orphan signal_type column")
}
private func createV5Tables() throws {
try executeRaw(
"""
CREATE TABLE IF NOT EXISTS identity (
id INTEGER PRIMARY KEY CHECK (id = 1),
content TEXT NOT NULL DEFAULT '',
overrides TEXT NOT NULL DEFAULT '[]',
token_count INTEGER NOT NULL DEFAULT 0,
version INTEGER NOT NULL DEFAULT 0,
model TEXT NOT NULL DEFAULT '',
generated_at TEXT NOT NULL DEFAULT ''
)
"""
)
try executeRaw(
"""
CREATE TABLE IF NOT EXISTS pinned_facts (
id TEXT PRIMARY KEY,
agent_id TEXT NOT NULL,
content TEXT NOT NULL,
salience REAL NOT NULL DEFAULT 0.5,
source_count INTEGER NOT NULL DEFAULT 1,
source_episode_id INTEGER,
last_used TEXT NOT NULL DEFAULT (datetime('now')),
use_count INTEGER NOT NULL DEFAULT 0,
status TEXT NOT NULL DEFAULT 'active',
created_at TEXT NOT NULL DEFAULT (datetime('now')),
tags_csv TEXT
)
"""
)
try executeRaw(
"CREATE INDEX IF NOT EXISTS idx_pinned_agent_status ON pinned_facts(agent_id, status, salience DESC)"
)
try executeRaw(
"""
CREATE TABLE IF NOT EXISTS episodes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
agent_id TEXT NOT NULL,
conversation_id TEXT NOT NULL,
summary TEXT NOT NULL,
topics_csv TEXT NOT NULL DEFAULT '',
entities_csv TEXT NOT NULL DEFAULT '',
decisions TEXT NOT NULL DEFAULT '',
action_items TEXT NOT NULL DEFAULT '',
salience REAL NOT NULL DEFAULT 0.5,
token_count INTEGER NOT NULL DEFAULT 0,
model TEXT NOT NULL DEFAULT '',
conversation_at TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'active',
created_at TEXT NOT NULL DEFAULT (datetime('now'))
)
"""
)
try executeRaw(
"CREATE INDEX IF NOT EXISTS idx_episodes_agent_at ON episodes(agent_id, status, conversation_at DESC)"
)
try executeRaw(
"""
CREATE TABLE IF NOT EXISTS transcript (
id INTEGER PRIMARY KEY AUTOINCREMENT,
agent_id TEXT NOT NULL,
conversation_id TEXT NOT NULL,
chunk_index INTEGER NOT NULL,
role TEXT NOT NULL,
content TEXT NOT NULL,
token_count INTEGER NOT NULL,
title TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
)
"""
)
try executeRaw(
"CREATE INDEX IF NOT EXISTS idx_transcript_conv ON transcript(conversation_id, chunk_index)"
)
try executeRaw(
"CREATE INDEX IF NOT EXISTS idx_transcript_agent_created ON transcript(agent_id, created_at DESC)"
)
try executeRaw(
"""
CREATE TABLE IF NOT EXISTS pending_signals (
id INTEGER PRIMARY KEY AUTOINCREMENT,
agent_id TEXT NOT NULL,
conversation_id TEXT NOT NULL,
user_message TEXT NOT NULL,
assistant_message TEXT,
status TEXT NOT NULL DEFAULT 'pending',
created_at TEXT NOT NULL DEFAULT (datetime('now'))
)
"""
)
try executeRaw(
"CREATE INDEX IF NOT EXISTS idx_pending_conv_status ON pending_signals(conversation_id, status)"
)
try executeRaw(
"CREATE INDEX IF NOT EXISTS idx_pending_agent_status ON pending_signals(agent_id, status)"
)
try executeRaw(
"""
CREATE TABLE IF NOT EXISTS processing_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
agent_id TEXT NOT NULL,
task_type TEXT NOT NULL,
model TEXT,
status TEXT NOT NULL,
details TEXT,
input_tokens INTEGER,
output_tokens INTEGER,
duration_ms INTEGER,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
)
"""
)
try executeRaw("CREATE INDEX IF NOT EXISTS idx_processing_log_created ON processing_log(created_at)")
}
private func carryOverIdentityFromV1() throws {
guard try tableExists("user_profile") else { return }
var content = ""
var version = 0
var generatedAt = ""
var model = ""
try executeRaw(
"SELECT content, version, model, generated_at FROM user_profile WHERE id = 1"
) { stmt in
if sqlite3_step(stmt) == SQLITE_ROW {
content = String(cString: sqlite3_column_text(stmt, 0))
version = Int(sqlite3_column_int(stmt, 1))
model = String(cString: sqlite3_column_text(stmt, 2))
generatedAt = String(cString: sqlite3_column_text(stmt, 3))
}
}
var overrides: [String] = []
if try tableExists("user_edits") {
try executeRaw(
"SELECT content FROM user_edits WHERE deleted_at IS NULL ORDER BY created_at"
) { stmt in
while sqlite3_step(stmt) == SQLITE_ROW {
overrides.append(String(cString: sqlite3_column_text(stmt, 0)))
}
}
}
// Skip if both are empty — leave the row uninitialized so the
// Identity sheet shows a clean "no profile yet" state.
guard !content.isEmpty || !overrides.isEmpty else { return }
let overridesJSON =
(try? JSONEncoder().encode(overrides)).flatMap { String(data: $0, encoding: .utf8) } ?? "[]"
let tokenCount = max(0, content.count / MemoryConfiguration.charsPerToken)
try executeRaw("DELETE FROM identity WHERE id = 1")
try insertRow(
"""
INSERT INTO identity (id, content, overrides, token_count, version, model, generated_at)
VALUES (1, ?1, ?2, ?3, ?4, ?5, ?6)
"""
) { stmt in
Self.bindText(stmt, index: 1, value: content)
Self.bindText(stmt, index: 2, value: overridesJSON)
sqlite3_bind_int(stmt, 3, Int32(tokenCount))
sqlite3_bind_int(stmt, 4, Int32(version))
Self.bindText(stmt, index: 5, value: model.isEmpty ? "v1-import" : model)
Self.bindText(
stmt,
index: 6,
value: generatedAt.isEmpty ? Self.iso8601Now() : generatedAt
)
}
MemoryLogger.database.info(
"v5 migration: carried over identity (v\(version), \(overrides.count) overrides)"
)
}
private func carryOverEpisodesFromV1() throws {
guard try tableExists("conversation_summaries") else { return }
var copied = 0
try executeRaw(
"""
SELECT agent_id, conversation_id, summary, token_count, model, conversation_at, status, created_at
FROM conversation_summaries
"""
) { stmt in
while sqlite3_step(stmt) == SQLITE_ROW {
let agentId = String(cString: sqlite3_column_text(stmt, 0))
let conversationId = String(cString: sqlite3_column_text(stmt, 1))
let summary = String(cString: sqlite3_column_text(stmt, 2))
let tokenCount = Int(sqlite3_column_int(stmt, 3))
let model = String(cString: sqlite3_column_text(stmt, 4))
let conversationAt = String(cString: sqlite3_column_text(stmt, 5))
let status = String(cString: sqlite3_column_text(stmt, 6))
let createdAt = String(cString: sqlite3_column_text(stmt, 7))
do {
try insertRow(
"""
INSERT INTO episodes
(agent_id, conversation_id, summary, token_count, model,
conversation_at, status, created_at, salience)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, 0.5)
"""
) { ins in
Self.bindText(ins, index: 1, value: agentId)
Self.bindText(ins, index: 2, value: conversationId)
Self.bindText(ins, index: 3, value: summary)
sqlite3_bind_int(ins, 4, Int32(tokenCount))
Self.bindText(ins, index: 5, value: model)
Self.bindText(ins, index: 6, value: conversationAt)
Self.bindText(ins, index: 7, value: status)
Self.bindText(ins, index: 8, value: createdAt)
}
copied += 1
} catch {
MemoryLogger.database.warning("v5 migration: failed to carry over summary: \(error)")
}
}
}
if copied > 0 {
MemoryLogger.database.info("v5 migration: carried over \(copied) episodes from conversation_summaries")
}
}
private func carryOverTranscriptFromV1() throws {
guard try tableExists("conversation_chunks"), try tableExists("conversations") else { return }
var copied = 0
try executeRaw(
"""
SELECT cc.conversation_id, cc.chunk_index, cc.role, cc.content, cc.token_count, cc.created_at,
c.agent_id, c.title
FROM conversation_chunks cc
JOIN conversations c ON c.id = cc.conversation_id
"""
) { stmt in
while sqlite3_step(stmt) == SQLITE_ROW {
let conversationId = String(cString: sqlite3_column_text(stmt, 0))
let chunkIndex = Int(sqlite3_column_int(stmt, 1))
let role = String(cString: sqlite3_column_text(stmt, 2))
let content = String(cString: sqlite3_column_text(stmt, 3))
let tokenCount = Int(sqlite3_column_int(stmt, 4))
let createdAt = String(cString: sqlite3_column_text(stmt, 5))
let agentId = String(cString: sqlite3_column_text(stmt, 6))
let title = sqlite3_column_text(stmt, 7).map { String(cString: $0) }
do {
try insertRow(
"""
INSERT INTO transcript
(agent_id, conversation_id, chunk_index, role, content,
token_count, title, created_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)
"""
) { ins in
Self.bindText(ins, index: 1, value: agentId)
Self.bindText(ins, index: 2, value: conversationId)
sqlite3_bind_int(ins, 3, Int32(chunkIndex))
Self.bindText(ins, index: 4, value: role)
Self.bindText(ins, index: 5, value: content)
sqlite3_bind_int(ins, 6, Int32(tokenCount))
Self.bindText(ins, index: 7, value: title)
Self.bindText(ins, index: 8, value: createdAt)
}
copied += 1
} catch {
MemoryLogger.database.warning("v5 migration: failed to carry over chunk: \(error)")
}
}
}
if copied > 0 {
MemoryLogger.database.info("v5 migration: carried over \(copied) transcript turns")
}
}
private func tableExists(_ name: String) throws -> Bool {
var found = false
try executeRaw("SELECT name FROM sqlite_master WHERE type='table' AND name=?") { stmt in
Self.bindText(stmt, index: 1, value: name)
if sqlite3_step(stmt) == SQLITE_ROW {
found = true
}
}
return found
}
// MARK: - Query Execution
private func executeRaw(_ sql: String) throws {
guard let connection = db else { throw MemoryDatabaseError.notOpen }
var errorMessage: UnsafeMutablePointer<CChar>?
let result = sqlite3_exec(connection, sql, nil, nil, &errorMessage)
if result != SQLITE_OK {
let message = errorMessage.map { String(cString: $0) } ?? "Unknown error"
sqlite3_free(errorMessage)
throw MemoryDatabaseError.failedToExecute(message)
}
}
private func executeRaw(_ sql: String, handler: (OpaquePointer) throws -> Void) throws {
guard let connection = db else { throw MemoryDatabaseError.notOpen }
var stmt: OpaquePointer?
let prepareResult = sqlite3_prepare_v2(connection, sql, -1, &stmt, nil)
guard prepareResult == SQLITE_OK, let statement = stmt else {
let message = String(cString: sqlite3_errmsg(connection))
throw MemoryDatabaseError.failedToPrepare(message)
}
defer { sqlite3_finalize(statement) }
try handler(statement)
}
/// Execute a non-row-returning insert/update with bindings (must be on `queue`).
private func insertRow(_ sql: String, bind: (OpaquePointer) -> Void) throws {
guard let connection = db else { throw MemoryDatabaseError.notOpen }
var stmt: OpaquePointer?
guard sqlite3_prepare_v2(connection, sql, -1, &stmt, nil) == SQLITE_OK, let s = stmt else {
throw MemoryDatabaseError.failedToPrepare(String(cString: sqlite3_errmsg(connection)))
}
defer { sqlite3_finalize(s) }
bind(s)
let step = sqlite3_step(s)
guard step == SQLITE_DONE else {
throw MemoryDatabaseError.failedToExecute(
"INSERT step returned \(step): \(String(cString: sqlite3_errmsg(connection)))"
)
}
}
func execute<T>(_ operation: @escaping (OpaquePointer) throws -> T) throws -> T {
try queue.sync {
guard let connection = db else { throw MemoryDatabaseError.notOpen }
return try operation(connection)
}
}
/// Locking entry point. Acquires `queue.sync` and dispatches to
/// the unlocked core. Use this from regular call sites that
/// don't already hold the queue.
///
/// MUST NOT be called from inside an `inTransaction { ... }`
/// closure — that closure already runs on `queue`, and a
/// nested `queue.sync` traps with `EXC_BREAKPOINT` (libdispatch
/// re-entrant-sync deadlock detector). The runtime guard below
/// surfaces the misuse at the *call site* instead of inside
/// libdispatch where the stack is harder to read. Use
/// `prepareAndExecute(on:_:bind:process:)` from inside a
/// transaction.
func prepareAndExecute(
_ sql: String,
bind: (OpaquePointer) -> Void,
process: (OpaquePointer) throws -> Void
) throws {
dispatchPrecondition(condition: .notOnQueue(queue))
try queue.sync {
guard let connection = db else { throw MemoryDatabaseError.notOpen }
try Self.prepareAndExecute(
on: connection,
sql,
bind: bind,
process: process
)
}
}
/// Non-locking core. Caller MUST hold `queue` (i.e. be inside an
/// `inTransaction { ... }` closure). Performs the
/// prepare/bind/process/finalize dance against an already-open
/// connection.
static func prepareAndExecute(
on connection: OpaquePointer,
_ sql: String,
bind: (OpaquePointer) -> Void,
process: (OpaquePointer) throws -> Void
) throws {
var stmt: OpaquePointer?
let prepareResult = sqlite3_prepare_v2(connection, sql, -1, &stmt, nil)
guard prepareResult == SQLITE_OK, let statement = stmt else {
let message = String(cString: sqlite3_errmsg(connection))
throw MemoryDatabaseError.failedToPrepare(message)
}
defer { sqlite3_finalize(statement) }
bind(statement)