Sources/OrgIndex/IndexStore.swift

544 lines · 26966 bytes

  1import Foundation
  2import GRDB
  3import OrgCore
  4
  5/// What the index knows about a file without reading it.
  6public struct FileState: Sendable, Equatable {
  7    public let kind: FileKind
  8    public let size: Int
  9    public let mtime: Double
 10    public let hash: String
 11    public let settingsVersion: Int
 12}
 13
 14/// A heading as found by a query. `contentHash` is the hash of the text the offsets refer to,
 15/// so a caller can tell whether they still apply to an open buffer.
 16public struct IndexedHeading: Sendable, Hashable {
 17    public let location: HeadingLocation
 18    public let level: Int
 19    /// Titles from the top-level ancestor down to the heading itself.
 20    public let outlinePath: [String]
 21}
 22
 23public struct HeadingLocation: Sendable, Hashable {
 24    /// Locations are equal by where they are; the snippet is for showing them.
 25    public static func == (a: HeadingLocation, b: HeadingLocation) -> Bool {
 26        a.path == b.path && a.ordinal == b.ordinal && a.title == b.title && a.start == b.start && a.contentHash == b.contentHash
 27    }
 28
 29    public func hash(into hasher: inout Hasher) {
 30        hasher.combine(path)
 31        hasher.combine(ordinal)
 32        hasher.combine(start)
 33    }
 34
 35    public let path: String
 36    /// `fileOrdinal` for the file itself, before its first heading.
 37    public let ordinal: Int
 38    public let title: String
 39    public let start: Int
 40    public let contentHash: String
 41    /// The text around the match: a search's words, or a backlink's link.
 42    public var snippet: Snippet?
 43
 44    public init(path: String, ordinal: Int, title: String, start: Int, contentHash: String) {
 45        self.path = path
 46        self.ordinal = ordinal
 47        self.title = title
 48        self.start = start
 49        self.contentHash = contentHash
 50    }
 51
 52    public static let fileOrdinal = -1
 53
 54    /// The file before its first heading, titled by its name.
 55    public static func file(_ path: String, contentHash: String) -> HeadingLocation {
 56        HeadingLocation(path: path, ordinal: fileOrdinal, title: (path as NSString).lastPathComponent, start: 0, contentHash: contentHash)
 57    }
 58}
 59
 60/// One reconciliation's worth of changes, applied in a single transaction.
 61public struct IndexChange: Sendable {
 62    public var records: [FileRecord] = []
 63    /// Unchanged content with a new modification time.
 64    public var touches: [(path: String, mtime: Double)] = []
 65    /// Renamed files whose content didn't change.
 66    public var moves: [(from: String, to: String, mtime: Double)] = []
 67    public var removals: [String] = []
 68
 69    public init() {}
 70
 71    public var isEmpty: Bool { records.isEmpty && touches.isEmpty && moves.isEmpty && removals.isEmpty }
 72}
 73
 74/// The SQLite index. A cache: deleting it loses nothing that the files don't hold.
 75public final class IndexStore: Sendable {
 76    let database: DatabaseQueue
 77
 78    /// `path` nil opens an in-memory index.
 79    public init(path: String? = nil) throws {
 80        database = try path.map { try DatabaseQueue(path: $0) } ?? DatabaseQueue()
 81        try Self.migrator.migrate(database)
 82    }
 83
 84    static var migrator: DatabaseMigrator {
 85        var migrator = DatabaseMigrator()
 86        migrator.registerMigration("v1") { db in
 87            try db.execute(sql: """
 88                CREATE TABLE files (
 89                    id INTEGER PRIMARY KEY,
 90                    path TEXT NOT NULL UNIQUE,
 91                    root TEXT NOT NULL,
 92                    kind TEXT NOT NULL,
 93                    size INTEGER NOT NULL,
 94                    mtime REAL NOT NULL,
 95                    hash TEXT NOT NULL,
 96                    settings_version INTEGER NOT NULL,
 97                    parsed_at REAL NOT NULL
 98                );
 99                CREATE INDEX files_root ON files(root);
100                CREATE TABLE headings (
101                    id INTEGER PRIMARY KEY,
102                    file_id INTEGER NOT NULL REFERENCES files(id) ON DELETE CASCADE,
103                    ordinal INTEGER NOT NULL,
104                    parent_ordinal INTEGER,
105                    start_offset INTEGER NOT NULL,
106                    end_offset INTEGER NOT NULL,
107                    level INTEGER NOT NULL,
108                    todo TEXT,
109                    is_done INTEGER NOT NULL,
110                    priority TEXT,
111                    title TEXT NOT NULL,
112                    outline_path TEXT NOT NULL,
113                    org_id TEXT,
114                    archived INTEGER NOT NULL
115                );
116                CREATE INDEX headings_file ON headings(file_id);
117                CREATE INDEX headings_org_id ON headings(org_id);
118                CREATE TABLE tags (
119                    heading_id INTEGER NOT NULL REFERENCES headings(id) ON DELETE CASCADE,
120                    tag TEXT NOT NULL,
121                    inherited INTEGER NOT NULL
122                );
123                CREATE INDEX tags_heading ON tags(heading_id);
124                CREATE TABLE properties (
125                    heading_id INTEGER NOT NULL REFERENCES headings(id) ON DELETE CASCADE,
126                    key TEXT NOT NULL,
127                    value TEXT NOT NULL,
128                    inherited INTEGER NOT NULL
129                );
130                CREATE INDEX properties_heading ON properties(heading_id);
131                CREATE TABLE timestamps (
132                    heading_id INTEGER NOT NULL REFERENCES headings(id) ON DELETE CASCADE,
133                    kind TEXT NOT NULL,
134                    start_at TEXT NOT NULL,
135                    end_at TEXT,
136                    repeater TEXT,
137                    warning TEXT
138                );
139                CREATE INDEX timestamps_heading ON timestamps(heading_id);
140                CREATE TABLE clocks (
141                    heading_id INTEGER NOT NULL REFERENCES headings(id) ON DELETE CASCADE,
142                    start_at TEXT NOT NULL,
143                    end_at TEXT,
144                    minutes INTEGER
145                );
146                CREATE INDEX clocks_heading ON clocks(heading_id);
147                CREATE TABLE links (
148                    heading_id INTEGER NOT NULL REFERENCES headings(id) ON DELETE CASCADE,
149                    type TEXT NOT NULL,
150                    target TEXT NOT NULL
151                );
152                CREATE INDEX links_heading ON links(heading_id);
153                CREATE VIRTUAL TABLE headings_fts USING fts5(title, body, tokenize = 'unicode61 remove_diacritics 2');
154                CREATE TRIGGER headings_fts_delete AFTER DELETE ON headings BEGIN
155                    DELETE FROM headings_fts WHERE rowid = old.id;
156                END;
157                """)
158        }
159        migrator.registerMigration("v2") { db in
160            // Links before a file's first heading; files are read again to fill it.
161            try db.execute(sql: """
162                CREATE TABLE file_links (
163                    file_id INTEGER NOT NULL REFERENCES files(id) ON DELETE CASCADE,
164                    type TEXT NOT NULL,
165                    target TEXT NOT NULL
166                );
167                CREATE INDEX file_links_file ON file_links(file_id);
168                UPDATE files SET settings_version = -1;
169                """)
170        }
171        migrator.registerMigration("v3") { db in
172            // File-level IDs and titles, for org-roam file nodes; files are read again to fill them.
173            try db.execute(sql: """
174                ALTER TABLE files ADD COLUMN org_id TEXT;
175                ALTER TABLE files ADD COLUMN title TEXT;
176                CREATE INDEX files_org_id ON files(org_id);
177                UPDATE files SET settings_version = -1;
178                """)
179        }
180        migrator.registerMigration("v4") { db in
181            // Text before a file's first heading, searched as the file; files are read again to fill it.
182            try db.execute(sql: """
183                CREATE VIRTUAL TABLE files_fts USING fts5(body, tokenize = 'unicode61 remove_diacritics 2');
184                CREATE TRIGGER files_fts_delete AFTER DELETE ON files BEGIN
185                    DELETE FROM files_fts WHERE rowid = old.id;
186                END;
187                UPDATE files SET settings_version = -1;
188                """)
189        }
190        return migrator
191    }
192
193    // MARK: - Writing
194
195    public func write(_ record: FileRecord) throws {
196        var change = IndexChange()
197        change.records = [record]
198        try apply(change)
199    }
200
201    public func apply(_ change: IndexChange) throws {
202        guard !change.isEmpty else { return }
203        try database.write { db in
204            for path in change.removals {
205                try db.execute(sql: "DELETE FROM files WHERE path = ?", arguments: [path])
206            }
207            for move in change.moves {
208                try db.execute(sql: "UPDATE files SET path = ?, mtime = ? WHERE path = ?", arguments: [move.to, move.mtime, move.from])
209            }
210            for touch in change.touches {
211                try db.execute(sql: "UPDATE files SET mtime = ? WHERE path = ?", arguments: [touch.mtime, touch.path])
212            }
213            for record in change.records {
214                try insert(record, db)
215            }
216        }
217    }
218
219    private func insert(_ record: FileRecord, _ db: Database) throws {
220        try db.execute(sql: "DELETE FROM files WHERE path = ?", arguments: [record.path])
221        try db.execute(
222            sql: """
223                INSERT INTO files (path, root, kind, size, mtime, hash, settings_version, parsed_at, org_id, title)
224                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
225                """,
226            arguments: [record.path, record.root, record.kind.rawValue, record.size, record.mtime, record.hash,
227                        record.settingsVersion, Date().timeIntervalSince1970, record.fileID, record.title]
228        )
229        let fileID = db.lastInsertedRowID
230        if !record.preamble.allSatisfy(\.isWhitespace) {
231            try db.execute(sql: "INSERT INTO files_fts (rowid, body) VALUES (?, ?)", arguments: [fileID, record.preamble])
232        }
233        for link in record.links {
234            try db.execute(sql: "INSERT INTO file_links VALUES (?, ?, ?)", arguments: [fileID, link.type, link.target])
235        }
236        for heading in record.headings {
237            try db.execute(
238                sql: """
239                    INSERT INTO headings (file_id, ordinal, parent_ordinal, start_offset, end_offset, level, todo,
240                                          is_done, priority, title, outline_path, org_id, archived)
241                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
242                    """,
243                arguments: [fileID, heading.ordinal, heading.parent, heading.start, heading.end, heading.level, heading.todo,
244                            heading.isDone, heading.priority, heading.title, heading.outlinePath.joined(separator: "\u{1F}"),
245                            heading.orgID, heading.archived]
246            )
247            let id = db.lastInsertedRowID
248            try db.execute(sql: "INSERT INTO headings_fts (rowid, title, body) VALUES (?, ?, ?)", arguments: [id, heading.title, heading.body])
249            for tag in heading.tags {
250                try db.execute(sql: "INSERT INTO tags VALUES (?, ?, ?)", arguments: [id, tag.name, tag.inherited])
251            }
252            for property in heading.properties {
253                try db.execute(sql: "INSERT INTO properties VALUES (?, ?, ?, ?)", arguments: [id, property.key, property.value, property.inherited])
254            }
255            for stamp in heading.timestamps {
256                try db.execute(
257                    sql: "INSERT INTO timestamps VALUES (?, ?, ?, ?, ?, ?)",
258                    arguments: [id, stamp.kind.rawValue, stamp.start, stamp.end, stamp.repeater, stamp.warning]
259                )
260            }
261            for clock in heading.clocks {
262                try db.execute(sql: "INSERT INTO clocks VALUES (?, ?, ?, ?)", arguments: [id, clock.start, clock.end, clock.minutes])
263            }
264            for link in heading.links {
265                try db.execute(sql: "INSERT INTO links VALUES (?, ?, ?)", arguments: [id, link.type, link.target])
266            }
267        }
268    }
269
270    // MARK: - Reading
271
272    /// Indexed files under `root`, by path.
273    public func fileStates(root: String) throws -> [String: FileState] {
274        try database.read { db in
275            let rows = try Row.fetchAll(db, sql: "SELECT path, kind, size, mtime, hash, settings_version FROM files WHERE root = ?", arguments: [root])
276            var states: [String: FileState] = [:]
277            for row in rows {
278                states[row["path"]] = FileState(
279                    kind: FileKind(rawValue: row["kind"]) ?? .org,
280                    size: row["size"], mtime: row["mtime"], hash: row["hash"], settingsVersion: row["settings_version"]
281                )
282            }
283            return states
284        }
285    }
286
287    public func files() throws -> [(path: String, kind: FileKind)] {
288        try database.read { db in
289            try Row.fetchAll(db, sql: "SELECT path, kind FROM files ORDER BY path").map {
290                (path: $0["path"], kind: FileKind(rawValue: $0["kind"]) ?? .org)
291            }
292        }
293    }
294
295    // MARK: - Queries
296    //
297    // `overlay` holds records for open documents with unsaved edits, keyed by path. Their rows
298    // replace that file's indexed rows in every query.
299
300    /// Headings whose title or body contain every word of `query` as a word prefix, and files
301    /// whose text before the first heading does, best first, each with a snippet of the text
302    /// when the match is there.
303    public func search(_ query: String, overlay: [String: FileRecord] = [:], limit: Int = 50) throws -> [HeadingLocation] {
304        let terms = query.split(whereSeparator: \.isWhitespace).map(String.init)
305        guard !terms.isEmpty else { return [] }
306        let match = terms.map { "\"" + $0.replacingOccurrences(of: "\"", with: "\"\"") + "\"*" }.joined(separator: " ")
307        let prefixes = terms.flatMap(Self.words)
308        func withSnippet(_ location: HeadingLocation, _ body: String) -> HeadingLocation {
309            var location = location
310            location.snippet = Snippet(text: body, prefixes: prefixes)
311            return location
312        }
313        let indexed = try database.read { db in
314            let headings = try Row.fetchAll(
315                db,
316                sql: """
317                    SELECT f.path, f.hash, h.ordinal, h.title, h.start_offset, headings_fts.body, bm25(headings_fts) AS rank
318                    FROM headings_fts
319                    JOIN headings h ON h.id = headings_fts.rowid
320                    JOIN files f ON f.id = h.file_id
321                    WHERE headings_fts MATCH ?
322                    ORDER BY rank
323                    LIMIT ?
324                    """,
325                arguments: [match, limit + overlay.count * 10]
326            ).map { (location: withSnippet(location($0), $0["body"]), rank: $0["rank"] as Double) }
327            let files = try Row.fetchAll(
328                db,
329                sql: """
330                    SELECT f.path, f.hash, f.title, files_fts.body, bm25(files_fts) AS rank
331                    FROM files_fts
332                    JOIN files f ON f.id = files_fts.rowid
333                    WHERE files_fts MATCH ?
334                    ORDER BY rank
335                    LIMIT ?
336                    """,
337                arguments: [match, limit + overlay.count]
338            ).map { (location: withSnippet(fileLocation($0["path"], title: $0["title"], hash: $0["hash"]), $0["body"]), rank: $0["rank"] as Double) }
339            return (headings + files).sorted { $0.rank < $1.rank }.map(\.location)
340        }
341        // Unsaved buffers get the same word-prefix matching as the full-text index.
342        func matches(_ text: String) -> Bool {
343            let words = Self.words(text)
344            return prefixes.allSatisfy { prefix in words.contains { $0.hasPrefix(prefix) } }
345        }
346        let live = overlay.values.sorted { $0.path < $1.path }.flatMap { record in
347            let file = matches(record.preamble) ? [withSnippet(fileLocation(record.path, title: record.title, hash: record.hash), record.preamble)] : []
348            return file + record.headings.filter { matches($0.title + "\n" + $0.body) }.map { withSnippet(location(record, $0), $0.body) }
349        }
350        return Array((live + indexed.filter { overlay[$0.path] == nil }).prefix(limit))
351    }
352
353    /// The file before its first heading, titled by its `#+TITLE` or else its name.
354    private func fileLocation(_ path: String, title: String?, hash: String) -> HeadingLocation {
355        let file = HeadingLocation.file(path, contentHash: hash)
356        guard let title, !title.isEmpty else { return file }
357        return HeadingLocation(path: path, ordinal: file.ordinal, title: title, start: 0, contentHash: hash)
358    }
359
360    /// Headings down to `maxLevel` in org files (not archives or conflict copies), with their
361    /// levels and outline paths, in file order: refile targets.
362    public func outline(maxLevel: Int) throws -> [IndexedHeading] {
363        try database.read { db in
364            try Row.fetchAll(
365                db,
366                sql: """
367                    SELECT f.path, f.hash, h.ordinal, h.title, h.start_offset, h.level, h.outline_path
368                    FROM headings h JOIN files f ON f.id = h.file_id
369                    WHERE h.level <= ? AND f.kind = 'org' ORDER BY f.path, h.ordinal
370                    """,
371                arguments: [maxLevel]
372            ).map { row in
373                IndexedHeading(
374                    location: location(row), level: row["level"],
375                    outlinePath: (row["outline_path"] as String).split(separator: "\u{1F}", omittingEmptySubsequences: false).map(String.init)
376                )
377            }
378        }
379    }
380
381    /// Headings with `:ID: id`. More than one means the ID is duplicated.
382    /// Every tag a heading has, most used first.
383    public func tags() throws -> [String] {
384        try database.read { db in
385            try String.fetchAll(db, sql: "SELECT tag FROM tags WHERE inherited = 0 GROUP BY tag ORDER BY count(*) DESC, tag")
386        }
387    }
388
389    public func headings(withID id: String, overlay: [String: FileRecord] = [:]) throws -> [HeadingLocation] {
390        let indexed = try database.read { db in
391            try Row.fetchAll(
392                db,
393                sql: """
394                    SELECT f.path, f.hash, h.ordinal, h.title, h.start_offset
395                    FROM headings h JOIN files f ON f.id = h.file_id
396                    WHERE h.org_id = ? ORDER BY f.path, h.ordinal
397                    """,
398                arguments: [id]
399            ).map(location)
400        }
401        let files = try database.read { db in
402            try Row.fetchAll(db, sql: "SELECT path, hash FROM files WHERE org_id = ? ORDER BY path", arguments: [id])
403                .map { HeadingLocation.file($0["path"], contentHash: $0["hash"]) }
404        }
405        let live = overlay.values.sorted { $0.path < $1.path }.flatMap { record in
406            (record.fileID == id ? [HeadingLocation.file(record.path, contentHash: record.hash)] : [])
407                + record.headings.filter { $0.orgID == id }.map { location(record, $0) }
408        }
409        return (files + indexed).filter { overlay[$0.path] == nil } + live
410    }
411
412    /// A heading or file with an ID: an org-roam node.
413    public struct Node: Sendable, Hashable {
414        public let id: String
415        public let title: String
416        public let location: HeadingLocation
417    }
418
419    /// Every heading and file with an ID, files first, unsaved buffers' in place of their
420    /// files'. A file's title is its `#+TITLE`, else its name without `.org`.
421    public func nodes(overlay: [String: FileRecord] = [:]) throws -> [Node] {
422        func fileTitle(_ path: String, _ title: String?) -> String { title ?? ((path as NSString).lastPathComponent as NSString).deletingPathExtension }
423        let indexed = try database.read { db in
424            let files = try Row.fetchAll(db, sql: "SELECT path, hash, org_id, title FROM files WHERE org_id IS NOT NULL AND kind = 'org' ORDER BY path").map { row in
425                Node(id: row["org_id"], title: fileTitle(row["path"], row["title"]), location: .file(row["path"], contentHash: row["hash"]))
426            }
427            let headings = try Row.fetchAll(
428                db,
429                sql: """
430                    SELECT f.path, f.hash, h.ordinal, h.title, h.start_offset, h.org_id
431                    FROM headings h JOIN files f ON f.id = h.file_id
432                    WHERE h.org_id IS NOT NULL AND f.kind = 'org' ORDER BY f.path, h.ordinal
433                    """
434            ).map { Node(id: $0["org_id"], title: $0["title"], location: location($0)) }
435            return files + headings
436        }
437        let live = overlay.values.sorted { $0.path < $1.path }.flatMap { record in
438            (record.fileID.map { [Node(id: $0, title: fileTitle(record.path, record.title), location: .file(record.path, contentHash: record.hash))] } ?? [])
439                + record.headings.compactMap { heading in heading.orgID.map { Node(id: $0, title: heading.title, location: location(record, heading)) } }
440        }
441        return indexed.filter { overlay[$0.location.path] == nil } + live
442    }
443
444    /// Every Org file with a Denote identifier in its name, as a node with that identifier,
445    /// titled by its `#+TITLE`, else its name; unsaved buffers' titles in place of their files'.
446    public func denoteNodes(overlay: [String: FileRecord] = [:]) throws -> [Node] {
447        func node(_ path: String, _ title: String?, _ hash: String) -> Node? {
448            guard let id = Denote.identifier(ofFile: path) else { return nil }
449            return Node(id: id, title: title ?? ((path as NSString).lastPathComponent as NSString).deletingPathExtension, location: .file(path, contentHash: hash))
450        }
451        let indexed = try database.read { db in
452            try Row.fetchAll(db, sql: "SELECT path, hash, title FROM files WHERE kind = 'org' ORDER BY path").compactMap { node($0["path"], $0["title"], $0["hash"]) }
453        }
454        let live = overlay.values.sorted { $0.path < $1.path }.compactMap { node($0.path, $0.title, $0.hash) }
455        return indexed.filter { overlay[$0.location.path] == nil } + live
456    }
457
458    /// Every link and the heading it's in, or the file for links before its first heading,
459    /// unsaved buffers' in place of their files'.
460    public func links(overlay: [String: FileRecord] = [:]) throws -> [(source: HeadingLocation, target: String)] {
461        let indexed = try database.read { db in
462            try Row.fetchAll(
463                db,
464                sql: """
465                    SELECT f.path, f.hash, -1 AS ordinal, '' AS title, 0 AS start_offset, l.target
466                    FROM file_links l JOIN files f ON f.id = l.file_id WHERE f.kind = 'org'
467                    UNION ALL
468                    SELECT f.path, f.hash, h.ordinal, h.title, h.start_offset, l.target
469                    FROM links l JOIN headings h ON h.id = l.heading_id JOIN files f ON f.id = h.file_id
470                    WHERE f.kind = 'org' ORDER BY 1, 3
471                    """
472            ).map { row in
473                let location = location(row)
474                return (source: location.ordinal == HeadingLocation.fileOrdinal ? .file(location.path, contentHash: location.contentHash) : location,
475                        target: row["target"] as String)
476            }
477        }
478        let live = overlay.values.sorted { $0.path < $1.path }.flatMap { record in
479            record.links.map { (source: HeadingLocation.file(record.path, contentHash: record.hash), target: $0.target) }
480                + record.headings.flatMap { heading in heading.links.map { (source: location(record, heading), target: $0.target) } }
481        }
482        return indexed.filter { overlay[$0.source.path] == nil } + live
483    }
484
485    /// The text under a heading, or before a file's first heading, that a location from
486    /// `links` or `search` stands for.
487    public func text(of location: HeadingLocation, overlay: [String: FileRecord] = [:]) throws -> String? {
488        if let record = overlay[location.path] {
489            if location.ordinal == HeadingLocation.fileOrdinal { return record.preamble }
490            return record.headings.first { $0.ordinal == location.ordinal }?.body
491        }
492        return try database.read { db in
493            if location.ordinal == HeadingLocation.fileOrdinal {
494                return try String.fetchOne(db, sql: """
495                    SELECT files_fts.body FROM files_fts JOIN files f ON f.id = files_fts.rowid WHERE f.path = ?
496                    """, arguments: [location.path])
497            }
498            return try String.fetchOne(db, sql: """
499                SELECT headings_fts.body FROM headings_fts JOIN headings h ON h.id = headings_fts.rowid
500                JOIN files f ON f.id = h.file_id WHERE f.path = ? AND h.ordinal = ?
501                """, arguments: [location.path, location.ordinal])
502        }
503    }
504
505    /// IDs used by more than one heading.
506    public func duplicateIDs(overlay: [String: FileRecord] = [:]) throws -> [String: [HeadingLocation]] {
507        let indexed = try database.read { db in
508            try Row.fetchAll(
509                db,
510                sql: """
511                    SELECT h.org_id, f.path, f.hash, h.ordinal, h.title, h.start_offset
512                    FROM headings h JOIN files f ON f.id = h.file_id
513                    WHERE h.org_id IN (SELECT org_id FROM headings WHERE org_id IS NOT NULL GROUP BY org_id HAVING count(*) > 1)
514                       OR (h.org_id IS NOT NULL AND ? > 0)
515                    ORDER BY f.path, h.ordinal
516                    """,
517                arguments: [overlay.count]
518            ).map { (id: $0["org_id"] as String, location: location($0)) }
519        }
520        var byID: [String: [HeadingLocation]] = [:]
521        for row in indexed where overlay[row.location.path] == nil {
522            byID[row.id, default: []].append(row.location)
523        }
524        for record in overlay.values.sorted(by: { $0.path < $1.path }) {
525            for heading in record.headings {
526                if let id = heading.orgID { byID[id, default: []].append(location(record, heading)) }
527            }
528        }
529        return byID.filter { $0.value.count > 1 }
530    }
531
532    /// Lower-cased runs of letters and digits, as the unicode61 tokenizer splits them.
533    static func words(_ text: String) -> [String] {
534        text.lowercased().split { !$0.isLetter && !$0.isNumber }.map(String.init)
535    }
536
537    private func location(_ row: Row) -> HeadingLocation {
538        HeadingLocation(path: row["path"], ordinal: row["ordinal"], title: row["title"], start: row["start_offset"], contentHash: row["hash"])
539    }
540
541    private func location(_ record: FileRecord, _ heading: HeadingRecord) -> HeadingLocation {
542        HeadingLocation(path: record.path, ordinal: heading.ordinal, title: heading.title, start: heading.start, contentHash: record.hash)
543    }
544}