Repository Public License
1// MemoryEngine — the opt-in local index: own tables, FTS5, vectors, hybrid search, lifecycle.2import CryptoKit3import Foundation4import NavigatorCore5import Persistence67public struct MemoryConfiguration: Sendable, Hashable {8 public var chunkTargetCharacters = 9009 public var chunkOverlapCharacters = 15010 public var chunkMaximumCharacters = 1_40011 /// Text beyond this many chunks is not indexed (a very long page is truncated, and reported as such).12 public var maximumChunksPerDocument = 30013 public var maximumTitleCharacters = 30014 /// Constant of reciprocal rank fusion.15 public var fusionConstant: Double = 6016 /// How many candidates each ranker contributes before fusion.17 public var candidatePoolSize = 10018 /// Cosine similarity below which a vector hit is ignored. Chosen from a handful of sentences with Apple's19 /// English sentence embedding (related ≈ 0.19–0.46, unrelated ≤ 0.11); not tuned on a corpus (docs/MEMORY.md).20 public var minimumSimilarity: Float = 0.1521 public var snippetCharacters = 24022 /// Query vectors are computed for at most this many languages of the index (largest first).23 public var maximumQueryLanguages = 42425 public init() {}26}2728public struct MemoryIndexReport: Sendable, Hashable {29 public var chunks: Int30 public var embeddedChunks: Int31 public var language: String32 /// Identifier of the embedding model used, or `nil` when the language has none on this device: the33 /// document is then searchable by full text only.34 public var embeddingModel: String?35 public var wasTruncated: Bool36 /// Documents removed to stay under the storage cap (oldest first).37 public var evictedDocuments: Int38}3940public enum MemoryIndexOutcome: Sendable, Hashable {41 case indexed(MemoryIndexReport)42 /// The same content was already indexed for this item.43 case unchanged44 case skipped(MemorySkipReason)45}4647public struct MemoryFilter: Sendable, Hashable {48 public var kinds: Set<MemoryItemKind>?49 public var profileID: ProfileID?50 public var spaceID: SpaceID?51 /// Host and its subdomains.52 public var host: String?53 /// On the item's date (visit, note update, capture).54 public var dateRange: DateInterval?5556 public init(kinds: Set<MemoryItemKind>? = nil, profileID: ProfileID? = nil, spaceID: SpaceID? = nil, host: String? = nil,57 dateRange: DateInterval? = nil) {58 self.kinds = kinds; self.profileID = profileID; self.spaceID = spaceID; self.host = host; self.dateRange = dateRange59 }6061 var isEmpty: Bool { kinds == nil && profileID == nil && spaceID == nil && host == nil && dateRange == nil }62}6364public struct MemoryHit: Sendable, Hashable {65 public var kind: MemoryItemKind66 public var itemID: String67 public var profileID: ProfileID?68 public var spaceID: SpaceID?69 public var url: URL?70 public var title: String71 public var date: Date72 public var chunkOrdinal: Int73 public var snippet: MemorySnippet74 /// Fused score (reciprocal rank fusion); only meaningful for ordering.75 public var score: Double76 /// 1-based rank in the full-text results, when the chunk matched the words.77 public var fullTextRank: Int?78 /// 1-based rank in the vector results, when the chunk was semantically close.79 public var semanticRank: Int?80 public var similarity: Float?81}8283/// Whether semantic search took part in a query. The UI must not present results as "semantic" otherwise.84public enum MemorySemanticStatus: Sendable, Hashable {85 /// Vectors were searched with these models.86 case used(models: [String])87 /// Nothing in the index has a vector (no model for the indexed languages on this device).88 case noEmbeddingsInIndex89 /// The index has vectors but the query could not be embedded with their models.90 case queryNotEmbeddable91}9293public struct MemorySearchResponse: Sendable, Hashable {94 public var hits: [MemoryHit]95 public var isEnabled: Bool96 public var semantic: MemorySemanticStatus97 /// `true` when the ranking used full text only.98 public var isFullTextOnly: Bool { if case .used = semantic { return false } else { return true } }99}100101public struct MemoryStatistics: Sendable, Hashable {102 public var documents: Int103 public var chunks: Int104 public var embeddedChunks: Int105 /// Accounted size: UTF-8 bytes of the indexed text and titles plus the bytes of the vectors. The SQLite106 /// and FTS5 overhead is not included.107 public var bytes: Int64108 public var capBytes: Int64109 public var documentsByKind: [MemoryItemKind: Int]110 public var embeddingModels: [String: Int]111}112113public struct MemoryRebuildReport: Sendable, Hashable {114 public var chunks: Int115 public var embeddedChunks: Int116 public var languagesWithoutModel: [String]117}118119/// The local memory index.120///121/// Off by default: nothing is indexed until `setEnabled(true)`. The index lives in tables this module creates122/// itself (`memory_documents`, `memory_chunks`, `memory_fts`); Persistence's exports, capsules and sync never123/// read them. All work happens on this actor and on the database's queues, never on the main actor.124public actor MemoryIndex {125 public static let currentSchemaVersion = 1126127 private let database: NavigatorDatabase128 private let embedder: any MemoryEmbedder129 public let configuration: MemoryConfiguration130 private var isPrepared = false131 private var matrices: [String: MemoryVectorMatrix] = [:]132133 public init(database: NavigatorDatabase, embedder: any MemoryEmbedder = NLSentenceMemoryEmbedder(),134 configuration: MemoryConfiguration = MemoryConfiguration()) {135 self.database = database; self.embedder = embedder; self.configuration = configuration136 }137138 // MARK: Schema139140 /// Creates the module's tables if needed. Idempotent; called automatically.141 public func prepare() async throws {142 guard !isPrepared else { return }143 try await database.sqlite.transaction { connection in144 try connection.executeScript("""145 CREATE TABLE IF NOT EXISTS memory_documents (146 id INTEGER PRIMARY KEY,147 kind TEXT NOT NULL,148 item_id TEXT NOT NULL,149 profile_id TEXT,150 space_id TEXT,151 url TEXT,152 host TEXT,153 title TEXT NOT NULL,154 language TEXT NOT NULL,155 content_hash TEXT NOT NULL,156 source_date REAL NOT NULL,157 indexed_at REAL NOT NULL,158 byte_size INTEGER NOT NULL,159 chunk_count INTEGER NOT NULL,160 UNIQUE (kind, item_id)161 );162 CREATE INDEX IF NOT EXISTS memory_documents_host ON memory_documents (host);163 CREATE INDEX IF NOT EXISTS memory_documents_space ON memory_documents (space_id);164 CREATE INDEX IF NOT EXISTS memory_documents_date ON memory_documents (source_date);165 CREATE INDEX IF NOT EXISTS memory_documents_indexed ON memory_documents (indexed_at);166 CREATE TABLE IF NOT EXISTS memory_chunks (167 id INTEGER PRIMARY KEY,168 document_id INTEGER NOT NULL REFERENCES memory_documents (id) ON DELETE CASCADE,169 ordinal INTEGER NOT NULL,170 model TEXT,171 dimension INTEGER NOT NULL DEFAULT 0,172 embedding BLOB173 );174 CREATE INDEX IF NOT EXISTS memory_chunks_document ON memory_chunks (document_id);175 CREATE INDEX IF NOT EXISTS memory_chunks_model ON memory_chunks (model);176 CREATE VIRTUAL TABLE IF NOT EXISTS memory_fts USING fts5(body, title, tokenize = 'unicode61 remove_diacritics 2');177 """)178 // Ask FTS5 to overwrite deleted entries instead of leaving them until a merge (SQLite ≥ 3.42).179 _ = try? connection.execute("INSERT INTO memory_fts (memory_fts, rank) VALUES ('secure-delete', 1)")180 }181 if try await database.settings.value(MemorySettings.schemaVersion) < Self.currentSchemaVersion {182 try await database.settings.set(MemorySettings.schemaVersion, to: Self.currentSchemaVersion)183 }184 isPrepared = true185 }186187 // MARK: Opt-in and exclusions188189 public func isEnabled() async throws -> Bool { try await database.settings.value(MemorySettings.enabled) }190191 /// Turns the memory on or off. Turning it off stops indexing and searching; `purge` also deletes192 /// everything indexed so far.193 public func setEnabled(_ enabled: Bool, purge: Bool) async throws {194 try await database.settings.set(MemorySettings.enabled, to: enabled)195 if !enabled, purge { try await deleteEverything() }196 }197198 public func policy() async throws -> MemoryPolicy {199 MemoryPolicy(isEnabled: try await database.settings.value(MemorySettings.enabled),200 excludedHosts: try await database.settings.value(MemorySettings.excludedHosts).compactMap(MemoryHostPattern.init),201 allowedHosts: try await database.settings.value(MemorySettings.allowedHosts).compactMap(MemoryHostPattern.init),202 usesDefaultExclusions: try await database.settings.value(MemorySettings.usesDefaultExclusions))203 }204205 public func excludedHosts() async throws -> [String] { try await database.settings.value(MemorySettings.excludedHosts) }206207 /// Adds a host exclusion and deletes what was already indexed for it. Returns `false` for an invalid pattern.208 @discardableResult209 public func addExclusion(_ pattern: String) async throws -> Bool {210 guard let parsed = MemoryHostPattern(pattern) else { return false }211 var list = try await database.settings.value(MemorySettings.excludedHosts)212 if !list.contains(parsed.text) { list.append(parsed.text) }213 try await database.settings.set(MemorySettings.excludedHosts, to: list.sorted())214 try await prepare()215 let hosts = try await database.sqlite.read { connection in216 try connection.query("SELECT DISTINCT host FROM memory_documents WHERE host IS NOT NULL").map { try $0.get("host", as: String.self) }217 }218 for host in hosts where parsed.matches(host: host) { try await deleteDocuments(where: "host = ?", [host]) }219 return true220 }221222 public func removeExclusion(_ pattern: String) async throws {223 let text = MemoryHostPattern(pattern)?.text ?? pattern224 let list = try await database.settings.value(MemorySettings.excludedHosts).filter { $0 != text }225 try await database.settings.set(MemorySettings.excludedHosts, to: list)226 }227228 /// Exempts a host from the sensitive-page heuristics (a false positive the user wants indexed).229 @discardableResult230 public func setAllowed(_ pattern: String, _ allowed: Bool) async throws -> Bool {231 guard let parsed = MemoryHostPattern(pattern) else { return false }232 var list = try await database.settings.value(MemorySettings.allowedHosts).filter { $0 != parsed.text }233 if allowed { list.append(parsed.text) }234 try await database.settings.set(MemorySettings.allowedHosts, to: list.sorted())235 return true236 }237238 public func setUsesDefaultExclusions(_ value: Bool) async throws {239 try await database.settings.set(MemorySettings.usesDefaultExclusions, to: value)240 }241242 /// The embedding model this device would use for a language, if any.243 public nonisolated func embeddingModel(for language: String) -> MemoryEmbeddingModel? { embedder.model(for: language) }244245 // MARK: Indexing246247 /// Indexes (or re-indexes) one item, if the policy allows it. Re-indexing replaces the previous chunks.248 @discardableResult249 public func index(_ input: MemoryInput) async throws -> MemoryIndexOutcome {250 let policy = try await policy()251 var isGhost = false252 var profileIsStored: Bool?253 if policy.isEnabled {254 if let profile = input.profileID {255 isGhost = database.ghosts.contains(profile.raw)256 profileIsStored = try await database.profiles.profile(profile) != nil257 }258 if let space = input.spaceID, database.ghosts.contains(space.raw) { isGhost = true }259 }260 if let reason = policy.skipReason(for: input, profileIsStored: profileIsStored, isGhost: isGhost) { return .skipped(reason) }261 try await prepare()262263 let title = String(input.title.trimmingCharacters(in: .whitespacesAndNewlines).prefix(configuration.maximumTitleCharacters))264 var chunks = MemoryChunker.chunks(of: input.text, target: configuration.chunkTargetCharacters,265 overlap: configuration.chunkOverlapCharacters, maximum: configuration.chunkMaximumCharacters)266 guard !chunks.isEmpty else { return .skipped(.emptyText) }267 let wasTruncated = chunks.count > configuration.maximumChunksPerDocument268 if wasTruncated { chunks = Array(chunks.prefix(configuration.maximumChunksPerDocument)) }269270 let language = MemoryLanguage.detect(chunks.prefix(3).joined(separator: " "))271 let model = embedder.model(for: language)272 // The hash covers what search depends on, including the model: when a model appears for the language273 // the same text is indexed again, this time with vectors.274 var hasher = SHA256()275 for part in [input.kind.rawValue, title, model?.identifier ?? "-", input.spaceID?.string ?? "-", input.url?.absoluteString ?? "-"] + chunks {276 hasher.update(data: Data(part.utf8)); hasher.update(data: Data([0]))277 }278 let contentHash = hasher.finalize().map { String(format: "%02x", $0) }.joined()279 let kind = input.kind.rawValue, itemID = input.itemID280 let existing = try await database.sqlite.read { connection in281 try connection.scalar("SELECT content_hash FROM memory_documents WHERE kind = ? AND item_id = ?", [kind, itemID], as: String.self)282 }283 if existing == contentHash { return .unchanged }284285 var vectors: [[Float]?] = chunks.map { _ in nil }286 if let model {287 vectors = embedder.embed(chunks, language: language).map { vector in288 guard let vector, vector.count == model.dimension else { return nil }289 return MemoryVectorMatrix.normalised(vector)290 }291 }292 let blobs = vectors.map { $0.map(MemoryVectorMatrix.data) }293 let byteSize = Int64(chunks.reduce(title.utf8.count) { $0 + $1.utf8.count } + blobs.reduce(0) { $0 + ($1?.count ?? 0) })294 let cap = try await database.settings.value(MemorySettings.storageCapBytes)295 guard byteSize <= cap else { return .skipped(.tooLarge) }296297 let host = input.url?.host?.lowercased()298 let profile = input.profileID, space = input.spaceID, url = input.url, date = input.date299 let modelID = model?.identifier, dimension = model?.dimension ?? 0300 let stored = chunks301 try await database.sqlite.transaction { connection in302 try Self.delete(connection, where: "kind = ? AND item_id = ?", [kind, itemID])303 try connection.execute("""304 INSERT INTO memory_documents (kind, item_id, profile_id, space_id, url, host, title, language, content_hash,305 source_date, indexed_at, byte_size, chunk_count)306 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)307 """, [kind, itemID, profile, space, url, host, title, language, contentHash, date, Date.now, byteSize, stored.count])308 let documentID = connection.lastInsertRowID309 for (ordinal, text) in stored.enumerated() {310 let blob = blobs[ordinal]311 try connection.execute("INSERT INTO memory_chunks (document_id, ordinal, model, dimension, embedding) VALUES (?, ?, ?, ?, ?)",312 [documentID, ordinal, blob == nil ? nil : modelID, blob == nil ? 0 : dimension, blob])313 try connection.execute("INSERT INTO memory_fts (rowid, body, title) VALUES (?, ?, ?)", [connection.lastInsertRowID, text, title])314 }315 }316 matrices.removeAll()317 let evicted = try await enforceStorageCap()318 return .indexed(MemoryIndexReport(chunks: chunks.count, embeddedChunks: blobs.filter { $0 != nil }.count, language: language,319 embeddingModel: blobs.contains { $0 != nil } ? modelID : nil, wasTruncated: wasTruncated,320 evictedDocuments: evicted))321 }322323 /// Recomputes the vectors of everything indexed with the embedder as it is now (a language gained or lost324 /// its model, the OS shipped a new revision). The text is not re-chunked; to pick up changed text, index325 /// the item again.326 public func rebuildEmbeddings() async throws -> MemoryRebuildReport {327 try await prepare()328 let documents = try await database.sqlite.read { connection in329 try connection.query("SELECT id, language FROM memory_documents ORDER BY id").map {330 (id: try $0.get("id", as: Int64.self), language: try $0.get("language", as: String.self))331 }332 }333 var total = 0, embedded = 0334 var missing = Set<String>()335 for document in documents {336 let chunks = try await database.sqlite.read { connection in337 try connection.query("SELECT c.id, f.body FROM memory_chunks c JOIN memory_fts f ON f.rowid = c.id WHERE c.document_id = ? ORDER BY c.ordinal",338 [document.id]).map { (id: try $0.get("id", as: Int64.self), text: try $0.get("body", as: String.self)) }339 }340 total += chunks.count341 let model = embedder.model(for: document.language)342 if model == nil { missing.insert(document.language) }343 var vectors: [[Float]?] = chunks.map { _ in nil }344 if let model {345 vectors = embedder.embed(chunks.map(\.text), language: document.language).map { vector in346 guard let vector, vector.count == model.dimension else { return nil }347 return MemoryVectorMatrix.normalised(vector)348 }349 }350 let updates = zip(chunks, vectors).map { (id: $0.0.id, blob: $0.1.map(MemoryVectorMatrix.data), textBytes: $0.0.text.utf8.count) }351 embedded += updates.filter { $0.blob != nil }.count352 let modelID = model?.identifier, dimension = model?.dimension ?? 0, documentID = document.id353 try await database.sqlite.transaction { connection in354 var size = 0355 for update in updates {356 try connection.execute("UPDATE memory_chunks SET model = ?, dimension = ?, embedding = ? WHERE id = ?",357 [update.blob == nil ? nil : modelID, update.blob == nil ? 0 : dimension, update.blob, update.id])358 size += update.textBytes + (update.blob?.count ?? 0)359 }360 try connection.execute("UPDATE memory_documents SET byte_size = ? + length(CAST(title AS BLOB)) WHERE id = ?", [size, documentID])361 }362 }363 matrices.removeAll()364 _ = try await enforceStorageCap()365 return MemoryRebuildReport(chunks: total, embeddedChunks: embedded, languagesWithoutModel: missing.sorted())366 }367368 // MARK: Search369370 private static func filterSQL(_ filter: MemoryFilter, alias: String = "d") -> (sql: String, parameters: [(any SQLiteConvertible)?]) {371 var clauses: [String] = []372 var parameters: [(any SQLiteConvertible)?] = []373 if let kinds = filter.kinds {374 clauses.append("\(alias).kind IN (\(kinds.map { _ in "?" }.joined(separator: ", ").isEmpty ? "NULL" : kinds.map { _ in "?" }.joined(separator: ", ")))")375 parameters += kinds.map(\.rawValue).sorted()376 }377 if let profile = filter.profileID { clauses.append("\(alias).profile_id = ?"); parameters.append(profile) }378 if let space = filter.spaceID { clauses.append("\(alias).space_id = ?"); parameters.append(space) }379 if let host = filter.host?.lowercased() {380 clauses.append("(\(alias).host = ? OR \(alias).host LIKE ? ESCAPE '\\')")381 let escaped = host.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "%", with: "\\%").replacingOccurrences(of: "_", with: "\\_")382 parameters += [host, "%." + escaped]383 }384 if let range = filter.dateRange {385 clauses.append("\(alias).source_date >= ? AND \(alias).source_date < ?")386 parameters += [range.start, range.end]387 }388 return (clauses.isEmpty ? "1" : clauses.joined(separator: " AND "), parameters)389 }390391 private func matrix(for model: String) async throws -> MemoryVectorMatrix? {392 if let cached = matrices[model] { return cached }393 let loaded = try await database.sqlite.read { connection -> MemoryVectorMatrix? in394 let rows = try connection.query("SELECT id, document_id, dimension, embedding FROM memory_chunks WHERE model = ? AND embedding IS NOT NULL ORDER BY id", [model])395 guard let dimension = try rows.first?.get("dimension", as: Int.self), dimension > 0 else { return nil }396 var matrix = MemoryVectorMatrix(dimension: dimension, capacity: rows.count)397 for row in rows {398 guard let vector = MemoryVectorMatrix.vector(from: try row.get("embedding", as: Data.self), dimension: dimension) else { continue }399 matrix.append(chunkID: try row.get("id"), documentID: try row.get("document_id"), vector: vector)400 }401 return matrix402 }403 if let loaded { matrices[model] = loaded }404 return loaded405 }406407 /// Frees the in-memory copy of the vectors (memory pressure). The next semantic search reloads it.408 public func releaseVectorCache() { matrices.removeAll() }409410 /// Hybrid search: BM25 over FTS5 and exact cosine similarity over the stored vectors, fused by reciprocal411 /// rank. Arbitrary user text is safe: it never reaches the FTS5 query language. One hit per item (its best412 /// chunk). When no vector search is possible the response says so and the ranking is full-text only.413 public func search(_ query: String, filter: MemoryFilter = MemoryFilter(), limit: Int = 20) async throws -> MemorySearchResponse {414 guard try await isEnabled() else { return MemorySearchResponse(hits: [], isEnabled: false, semantic: .noEmbeddingsInIndex) }415 try await prepare()416 let limit = max(1, min(limit, 200))417 let pool = max(limit, configuration.candidatePoolSize)418 let words = FTSQuery.tokens(in: query, limit: 24)419 let trimmed = query.trimmingCharacters(in: .whitespacesAndNewlines)420 let (filterSQL, filterParameters) = Self.filterSQL(filter)421422 // Full text. Words are OR-ed: BM25 ranks chunks holding more (and rarer) words first, so a natural423 // question still finds text that lacks its filler words.424 var fullText: [Int64] = []425 if !words.isEmpty {426 let match = words.map { "\"\($0)\"" }.joined(separator: " OR ")427 fullText = try await database.sqlite.read { connection in428 try connection.query("""429 SELECT c.id FROM memory_fts JOIN memory_chunks c ON c.id = memory_fts.rowid JOIN memory_documents d ON d.id = c.document_id430 WHERE memory_fts MATCH ? AND \(filterSQL) ORDER BY bm25(memory_fts, 1.0, 2.0), c.id LIMIT ?431 """, [match] + filterParameters + [pool]).map { try $0.get("id", as: Int64.self) }432 }433 }434435 // Vectors, one scan per model present in the index.436 var semantic: [(chunkID: Int64, similarity: Float)] = []437 var status = MemorySemanticStatus.noEmbeddingsInIndex438 let maximumLanguages = configuration.maximumQueryLanguages439 let models = try await database.sqlite.read { connection in440 try connection.query("""441 SELECT c.model AS model, d.language AS language, count(*) AS n FROM memory_chunks c JOIN memory_documents d ON d.id = c.document_id442 WHERE c.model IS NOT NULL GROUP BY c.model, d.language ORDER BY n DESC, c.model LIMIT ?443 """, [maximumLanguages]).map { (model: try $0.get("model", as: String.self), language: try $0.get("language", as: String.self)) }444 }445 if !models.isEmpty, !trimmed.isEmpty {446 status = .queryNotEmbeddable447 var allowed: Set<Int64>?448 if !filter.isEmpty {449 allowed = Set(try await database.sqlite.read { connection in450 try connection.query("SELECT d.id FROM memory_documents d WHERE \(filterSQL)", filterParameters).map { try $0.get("id", as: Int64.self) }451 })452 }453 var used: [String] = []454 for entry in models {455 // Only compare the query with vectors of the very model that produced them.456 guard let model = embedder.model(for: entry.language), model.identifier == entry.model,457 let raw = embedder.embed([trimmed], language: entry.language).first ?? nil,458 let vector = MemoryVectorMatrix.normalised(raw), let matrix = try await matrix(for: entry.model),459 matrix.dimension == vector.count else { continue }460 used.append(entry.model)461 semantic += matrix.top(pool, query: vector, minimumSimilarity: model.similarityFloor ?? configuration.minimumSimilarity,462 allowedDocuments: allowed)463 .map { ($0.chunkID, $0.similarity) }464 }465 if !used.isEmpty { status = .used(models: used) }466 } else if !models.isEmpty {467 status = .queryNotEmbeddable468 }469 semantic.sort { ($0.similarity, -$0.chunkID) > ($1.similarity, -$1.chunkID) }470 let semanticIDs = Array(semantic.prefix(pool).map(\.chunkID))471472 let fused = MemoryRanking.fuse([fullText, semanticIDs], k: configuration.fusionConstant)473 guard !fused.isEmpty else { return MemorySearchResponse(hits: [], isEnabled: true, semantic: status) }474 let fullTextRank = Dictionary(fullText.enumerated().map { ($1, $0 + 1) }, uniquingKeysWith: min)475 let semanticRank = Dictionary(semanticIDs.enumerated().map { ($1, $0 + 1) }, uniquingKeysWith: min)476 let similarity = Dictionary(semantic.map { ($0.chunkID, $0.similarity) }, uniquingKeysWith: max)477478 let ids = fused.map(\.id)479 let snippetLength = configuration.snippetCharacters480 struct Row: Sendable {481 var documentID: Int64, kind: String, itemID: String, profile: ProfileID?, space: SpaceID?, url: URL?482 var title: String, date: Date, ordinal: Int, body: String483 }484 let rows = try await database.sqlite.read { connection -> [Int64: Row] in485 var result: [Int64: Row] = [:]486 for batch in stride(from: 0, to: ids.count, by: 400).map({ Array(ids[$0..<min($0 + 400, ids.count)]) }) {487 let placeholders = batch.map { _ in "?" }.joined(separator: ", ")488 for row in try connection.query("""489 SELECT c.id AS chunk_id, c.ordinal, d.id AS document_id, d.kind, d.item_id, d.profile_id, d.space_id, d.url, d.title, d.source_date, f.body490 FROM memory_chunks c JOIN memory_documents d ON d.id = c.document_id JOIN memory_fts f ON f.rowid = c.id491 WHERE c.id IN (\(placeholders))492 """, batch) {493 result[try row.get("chunk_id")] = Row(documentID: try row.get("document_id"), kind: try row.get("kind"), itemID: try row.get("item_id"),494 profile: try row.get("profile_id"), space: try row.get("space_id"),495 url: (try row.get("url", as: String?.self)).flatMap(URL.init(string:)),496 title: try row.get("title"), date: try row.get("source_date"),497 ordinal: try row.get("ordinal"), body: try row.get("body"))498 }499 }500 return result501 }502 var hits: [MemoryHit] = []503 var seenDocuments = Set<Int64>()504 for entry in fused {505 guard let row = rows[entry.id], let kind = MemoryItemKind(rawValue: row.kind), seenDocuments.insert(row.documentID).inserted else { continue }506 hits.append(MemoryHit(kind: kind, itemID: row.itemID, profileID: row.profile, spaceID: row.space, url: row.url, title: row.title,507 date: row.date, chunkOrdinal: row.ordinal,508 snippet: MemorySnippet.make(from: row.body, queryWords: words, length: snippetLength), score: entry.score,509 fullTextRank: fullTextRank[entry.id], semanticRank: semanticRank[entry.id], similarity: similarity[entry.id]))510 if hits.count == limit { break }511 }512 return MemorySearchResponse(hits: hits, isEnabled: true, semantic: status)513 }514515 // MARK: Deletion516517 @discardableResult518 private static func delete(_ connection: SQLiteConnection, where clause: String, _ parameters: [(any SQLiteConvertible)?]) throws -> Int {519 // FTS rows first (they are found through the chunks), then chunks and vectors, then the documents.520 try connection.execute("""521 DELETE FROM memory_fts WHERE rowid IN (522 SELECT id FROM memory_chunks WHERE document_id IN (SELECT id FROM memory_documents WHERE \(clause)))523 """, parameters)524 try connection.execute("DELETE FROM memory_chunks WHERE document_id IN (SELECT id FROM memory_documents WHERE \(clause))", parameters)525 return try connection.execute("DELETE FROM memory_documents WHERE \(clause)", parameters)526 }527528 @discardableResult529 private func deleteDocuments(where clause: String, _ parameters: [(any SQLiteConvertible)?]) async throws -> Int {530 try await prepare()531 let count = try await database.sqlite.transaction { connection in try Self.delete(connection, where: clause, parameters) }532 if count > 0 { matrices.removeAll() }533 return count534 }535536 /// Removes one item from the index. Call it when the note, archive or snapshot is deleted.537 @discardableResult538 public func delete(kind: MemoryItemKind, itemID: String) async throws -> Int {539 try await deleteDocuments(where: "kind = ? AND item_id = ?", [kind.rawValue, itemID])540 }541542 /// Removes every indexed version of a page URL (all profiles).543 @discardableResult544 public func delete(url: URL) async throws -> Int {545 try await deleteDocuments(where: "url = ?", [url.absoluteString])546 }547548 @discardableResult549 public func delete(host: String, includingSubdomains: Bool = true) async throws -> Int {550 let host = host.lowercased()551 guard includingSubdomains else { return try await deleteDocuments(where: "host = ?", [host]) }552 let escaped = host.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "%", with: "\\%").replacingOccurrences(of: "_", with: "\\_")553 return try await deleteDocuments(where: "(host = ? OR host LIKE ? ESCAPE '\\')", [host, "%." + escaped])554 }555556 /// Removes items whose date falls in the half-open interval (the same convention as history deletion).557 @discardableResult558 public func delete(in range: DateInterval) async throws -> Int {559 try await deleteDocuments(where: "source_date >= ? AND source_date < ?", [range.start, range.end])560 }561562 @discardableResult563 public func delete(space: SpaceID) async throws -> Int { try await deleteDocuments(where: "space_id = ?", [space]) }564565 @discardableResult566 public func delete(profile: ProfileID) async throws -> Int { try await deleteDocuments(where: "profile_id = ?", [profile]) }567568 /// Empties the index: every document, chunk, vector and full-text entry, then merges the FTS5 segments so569 /// no deleted term survives in them. The opt-in setting and the exclusions are kept.570 public func deleteEverything() async throws {571 try await prepare()572 try await database.sqlite.transaction { connection in573 try connection.execute("DELETE FROM memory_fts")574 try connection.execute("DELETE FROM memory_chunks")575 try connection.execute("DELETE FROM memory_documents")576 }577 try await database.sqlite.write { connection in578 try connection.execute("INSERT INTO memory_fts (memory_fts) VALUES ('optimize')")579 }580 matrices.removeAll()581 }582583 // MARK: Storage584585 public func statistics() async throws -> MemoryStatistics {586 try await prepare()587 let cap = try await database.settings.value(MemorySettings.storageCapBytes)588 return try await database.sqlite.read { connection in589 var kinds: [MemoryItemKind: Int] = [:]590 for row in try connection.query("SELECT kind, count(*) AS n FROM memory_documents GROUP BY kind") {591 if let kind = MemoryItemKind(rawValue: try row.get("kind")) { kinds[kind] = try row.get("n") }592 }593 var models: [String: Int] = [:]594 for row in try connection.query("SELECT model, count(*) AS n FROM memory_chunks WHERE model IS NOT NULL GROUP BY model") {595 models[try row.get("model")] = try row.get("n")596 }597 return MemoryStatistics(documents: try connection.scalar("SELECT count(*) FROM memory_documents", as: Int.self) ?? 0,598 chunks: try connection.scalar("SELECT count(*) FROM memory_chunks", as: Int.self) ?? 0,599 embeddedChunks: try connection.scalar("SELECT count(*) FROM memory_chunks WHERE embedding IS NOT NULL", as: Int.self) ?? 0,600 bytes: try connection.scalar("SELECT coalesce(sum(byte_size), 0) FROM memory_documents", as: Int64.self) ?? 0,601 capBytes: cap, documentsByKind: kinds, embeddingModels: models)602 }603 }604605 /// Sets the storage cap and evicts immediately if the index is over it.606 @discardableResult607 public func setStorageCap(bytes: Int64) async throws -> Int {608 try await database.settings.set(MemorySettings.storageCapBytes, to: max(0, bytes))609 return try await enforceStorageCap()610 }611612 /// Deletes the least recently indexed documents until the accounted size is within the cap.613 @discardableResult614 public func enforceStorageCap() async throws -> Int {615 try await prepare()616 let cap = try await database.settings.value(MemorySettings.storageCapBytes)617 let evicted = try await database.sqlite.transaction { connection -> Int in618 var total = try connection.scalar("SELECT coalesce(sum(byte_size), 0) FROM memory_documents", as: Int64.self) ?? 0619 guard total > cap else { return 0 }620 var count = 0621 for row in try connection.query("SELECT id, byte_size FROM memory_documents ORDER BY indexed_at, id") {622 guard total > cap else { break }623 let id: Int64 = try row.get("id")624 try Self.delete(connection, where: "memory_documents.id = ?", [id])625 total -= try row.get("byte_size", as: Int64.self)626 count += 1627 }628 return count629 }630 if evicted > 0 { matrices.removeAll() }631 return evicted632 }633}634