Repository Public License
1# Persistence23Storage layer of ORIX Navigator: `Packages/NavigatorKit/Sources/Persistence`. System SQLite, no third-party4library (rationale: [ADR 0002](adr/0002-sqlite-without-dependencies.md)).56## Using it78```swift9import Persistence1011// At launch (off the main actor by construction: every call is async and runs on the database's own queues).12let (database, recovery) = try await NavigatorDatabase.openRecovering(url: supportDirectory.appending(path: "Navigator.sqlite"))13if let recovery { /* tell the user: the damaged database was moved to recovery.quarantineDirectory */ }1415let launch = try await database.session.beginSession() // launch.recoveredFromCrash16let session = try await database.session.restore() // profiles, spaces, groups, windows, tabsByWindow1718// While running: batch UI changes (debounce in the caller), one transaction per batch.19try await database.session.apply([.touchTab(id: tab.id, url: url, title: title, lastActiveAt: .now)])2021// On normal termination.22try await database.session.markCleanShutdown()23```2425`NavigatorDatabase` vends one store per model: `profiles`, `spaces`, `windows`, `tabs`, `tabGroups`, `session`,26`history`, `bookmarks`, `downloads`, `permissions`, `archives`, `snapshots`, `notes`, `canvases`, `agentRuns`,27`workflows`, `sync`, `settings`, `lifecycle`. Tests and previews use `NavigatorDatabase.inMemory()`.2829Secrets are **not** in the database: `SecretStore` (protocol in NavigatorCore), `KeychainSecretStore`30(Persistence), `InMemorySecretStore` (NavigatorCore, for tests).3132## Architecture3334| Layer | Type | Role |35|---|---|---|36| Connection | `SQLiteConnection` | One SQLite handle. Prepared-statement cache (256 statements), typed binding and reading, `transaction { }` (`BEGIN IMMEDIATE`, rollback on throw, savepoints when nested), `SQLiteError` with code, extended code, message and statement text (never bound values). |37| Isolation | `ConnectionActor` | Actor with a private serial dispatch queue as executor: SQLite never runs on the main thread or on the Swift cooperative pool. |38| Database | `SQLiteDatabase` | One writer and three read-only connections (file databases). `read`, `write`, `transaction`. |39| Schema | `Migrator`, `Schema` | Versioned migrations. |40| Stores | `…Store` structs | Typed async API; all SQL lives here. |41| Façade | `NavigatorDatabase` | Opening, integrity check, recovery, file protection, stores. |4243Connection settings: `journal_mode = WAL`, `synchronous = NORMAL`, `foreign_keys = ON`, `busy_timeout = 5000`,44`secure_delete = ON`, `temp_store = MEMORY`, `journal_size_limit = 64 MiB`; readers add `query_only = ON`.4546Concurrency: in WAL mode readers never wait for the writer and the writer never waits for readers. Each `read`47runs inside one deferred transaction, so several statements of a read see one snapshot. A read started after a48write returned sees that write. Writes are serialised by the writer actor. An in-memory database has a single49connection (reads are serialised with writes).5051Durability: every store write is one committed transaction. With WAL + `synchronous = NORMAL` a commit survives52an application crash or force quit. A kernel panic or power loss can lose the most recent commits but cannot53corrupt the database.5455## Conventions5657- Identifiers: `TEXT`, UUID string (`ID.string`).58- Dates: `REAL`, seconds since 1970 (UTC). Dates inside JSON columns use the same unit. A `Date` round-trips to59 within a quarter of a microsecond (the 1970 offset costs one bit of the mantissa); whole seconds are exact.60- URLs: `TEXT`, `absoluteString`. Booleans: `INTEGER` 0/1. Enums: `TEXT` raw value.61- `order` in the models is the column `sort_order` (`ORDER` is a keyword).62- What is queried is a real column; nested value types are JSON `TEXT`: `spaces.focus`, `windows.frame`,63 `windows.split`, `archives.missing`, `canvas_documents.cards/connections/viewport`,64 `agent_runs.steps/citations/usage/budget`, `settings.value`.6566## Schema (version 2)6768| Table | Content | Notes |69|---|---|---|70| `schema_migrations` | applied versions | bookkeeping; the authoritative version is `PRAGMA user_version` |71| `app_state` | internal key/value | `session.clean_shutdown`, `sync.local_version` |72| `settings` | user settings | JSON value per key |73| `profiles` | `Profile` | `CHECK (kind = 'standard')`: a ghost profile cannot be inserted |74| `spaces` | `OrbitSpace` | FK profile, cascade |75| `windows` | `BrowserWindow` | FK space, cascade; `closed_at` = recently closed |76| `tab_groups` | `TabGroup` | FK space, cascade |77| `tabs` | `Tab` | FK window and space (cascade), group (set null), parent (set null, deferred); `session_state` BLOB; `closed_at` = recently closed |78| `history_urls` | one row per (profile, URL) | title, counters, `last_visited_at`, `host_key`, `frecency` |79| `history_visits` | `NavigationEntry` | FK `history_urls`, cascade |80| `history_fts` | FTS5 over `history_urls(title, url)` | external content, kept in sync by three triggers |81| `bookmarks`, `bookmark_tags` | `Bookmark` | tree through `parent_id` (cascade); tags ordered by `position` |82| `downloads` | `Download` | `resume_data` BLOB |83| `permissions` | `PermissionDecision` | unique (profile, scheme, host, port, kind); port −1 = default |84| `archives`, `page_snapshots` | `Archive`, `PageSnapshot` | snapshot → archive is set null |85| `notes`, `canvas_documents`, `agent_runs` | `Note`, `CanvasDocument`, `AgentRun` | optional space (set null when the space is deleted) |86| `workflows` | `Workflow` | not tied to a profile |87| `sync_records` | `SyncRecord` | unique (entity, entity_id); `deleted_at` = tombstone |8889Indexes follow the queries: tabs by (window, closed, order) and by space; closed tabs and windows by closing90time; visits by (profile, time) and by URL; URLs by (profile, last visit), (profile, host key) and91(profile, frecency); bookmarks by (profile, parent, order), by URL and a partial index on favourites; downloads by92(profile, start); sync records by version.9394## Migration rules95961. `Schema.migrations` is an ordered, **append-only** list. Adding a schema change is one new97 `Migration(version: n, name: …, sql: …)` entry (or a closure for data backfills). Versions are 1, 2, 3… without98 gaps (checked by a precondition).992. A shipped migration is never edited. Helpers a migration calls (`HistorySQL.recomputeFrecency`, `Frecency`)100 are part of its frozen behaviour: change them only together with a new migration that recomputes.1013. Each migration runs in its own `BEGIN IMMEDIATE … COMMIT` together with its `schema_migrations` row and102 `PRAGMA user_version`. A failure rolls the whole step back and stops; earlier steps stay applied.1034. Prefer additive changes (`ADD COLUMN` with a default, new tables and indexes). A table rebuild sets104 `disablesForeignKeys: true`; the migrator then turns foreign keys off around the transaction and refuses to105 commit if `PRAGMA foreign_key_check` reports a violation.1065. A database whose version is **higher** than `Schema.latestVersion` is not opened:107 `PersistenceError.databaseTooNew(found:supported:)`. The file is not modified and is not treated as corrupt.1086. Every new migration gets a test that builds the previous version with `Migrator.migrate(_, upTo:)`, inserts109 rows with that version's SQL and opens it with the current code (`MigrationTests`).110111Version history: **1** initial schema. **2** `history_urls.host_key` and `history_urls.frecency` with their112indexes, backfilled from the stored visits (added when the omnibox ranking was designed).113114## Session restoration and crash detection115116- `SessionStore.apply([SessionChange])` commits a batch of window/tab changes in one transaction. The caller117 debounces; what a crash can lose is its debounce window, nothing else. In a batch, a window must precede the118 tabs that reference it.119- `SessionStore.replaceOpenState(windows:tabs:groups:)` writes a full picture and deletes open windows/tabs that120 are no longer in it (recently closed items are kept).121- `SessionStore.restore()` reads profiles, spaces, groups, open windows and open tabs in one snapshot. Tabs come122 back `.dormant`. `includeSessionState: false` skips the WebKit blobs.123- Clean-shutdown flag (`app_state['session.clean_shutdown']`): `beginSession()` returns how the previous run124 ended and sets the flag to "not clean"; `markCleanShutdown()` sets it back and truncates the WAL. A crash, a125 kill or a power cut never reaches `markCleanShutdown()`, so the next `beginSession()` reports126 `recoveredFromCrash == true`.127- Recently closed: closing a tab or a window sets `closed_at`. `TabStore.recentlyClosed/reopen`,128 `WindowStore.recentlyClosed/reopen`, `SessionStore.pruneClosed(maxTabs:maxWindows:olderThan:)`.129130## History, search and suggestions131132- `recordVisit` upserts the URL row (title, counters, frecency) and inserts the visit in one transaction.133 `updateTitle` sets the title once the page has loaded.134- Full-text search (`HistoryStore.search`): FTS5, tokenizer `unicode61 remove_diacritics 2` (case and accents135 folded), prefix indexes for 1–3 characters. User text never reaches FTS5's query language: `FTSQuery` splits it136 into runs of letters and digits and quotes each run, so operators and quotes are plain text and no input can137 produce a syntax error. All words must match; the last one is a prefix.138 Limits: `ß` is not folded to `ss`; CJK text has no word segmentation (a run of ideographs is one token, matched139 from its start).140- Frecency (`Frecency`): each visit contributes `weight × 2^(−age / 30 days)` (typed 2, link/form 1, agent/other141 0.5, redirect/back-forward 0.25, reload/restore 0). The column stores `ln Σ weightᵢ·e^{λ(tᵢ − epoch)}`, which142 orders rows exactly like the decayed sum but does not change as time passes: no periodic recomputation, and143 adding a visit is one update. Deleting visits recomputes the affected URLs from their remaining visits.144- Suggestions (`HistoryStore.suggestions`): candidates are the FTS matches of the typed words; they are ordered145 by frecency plus a ×4 boost when the typed text is a prefix of the host (ignoring scheme and `www.`).146 The cost is proportional to the number of matching URLs, not to the table size.147148## Bookmarks and the Netscape HTML format149150`BookmarkStore.importHTML` / `exportHTML`, parser and writer in `NetscapeBookmarks`. The reader is a forgiving151scanner (unclosed `<DT>`, missing outer `<DL>` as in Safari, any attribute case and quoting, multi-kilobyte152`ICON` data URLs, `<DD>` descriptions, `<HR>`). It keeps folders, titles, URLs, `ADD_DATE` / `LAST_MODIFIED`153(seconds, milliseconds or microseconds), Firefox `TAGS`, and marks links directly inside the154`PERSONAL_TOOLBAR_FOLDER` as favourites. Links that are not `http`, `https`, `ftp` or `file` (bookmarklets,155`place:` queries, `chrome://`) are skipped and counted. Nesting is capped at 64 levels. The writer emits UTF-8 with156`TAGS` and a private `ORIX_FAVORITE` attribute. Safari has no dates and no tags in its export; Safari's favourites157folder is not flagged in the file and is imported as an ordinary folder.158159## Ghost (private) data160161A `.ghost` profile is never stored, and nothing that belongs to one can be stored:1621631. `ProfileStore.save` throws `PersistenceError.ghostWriteRejected` for a ghost profile (and the schema's164 `CHECK (kind = 'standard')` refuses it even through raw SQL).1652. Every other write verifies inside its transaction that its owner is stored — profile for history, bookmarks,166 downloads, permissions, archives and snapshots; space for windows, groups, notes, canvases and agent runs;167 window and space for tabs. A ghost profile is not stored, so the chain fails:168 `PersistenceError.ownerNotPersisted`.1693. `NavigatorDatabase.ghosts` (`GhostRegistry`) lets the app declare the ids of a ghost session (profile, spaces,170 windows); writes that reference them then fail with the explicit `ghostWriteRejected`.171172Not covered, by construction: a note, canvas or agent run saved with `spaceID == nil`, a workflow, a setting or a173sync record carries no owner, so the store cannot know it came from a ghost window. Callers must not persist174those from a ghost context.175176## Corruption and recovery177178- `NavigatorDatabase(url:)` throws `PersistenceError.corrupt(path:details:)` when SQLite reports `SQLITE_CORRUPT`179 or `SQLITE_NOTADB` while opening or migrating, or when `PRAGMA quick_check` fails. The quick check runs when180 the previous run did not shut down cleanly (`IntegrityCheckPolicy.afterUncleanShutdown`, the default), always181 (`.always`) or never. The file is left as it is.182- `NavigatorDatabase.openRecovering(url:)` is the recovery path: on `.corrupt` it **moves** the database, `-wal`183 and `-shm` files into `<name>.corrupt-<UTC timestamp>/` next to the database, creates a new empty database and184 returns a `RecoveryReport` (reason, quarantine directory, moved files). Nothing is deleted. The app must tell185 the user; the quarantined file can be examined with `sqlite3 Navigator.sqlite ".recover"`.186- "Too new" is not corruption and is never quarantined.187- `checkIntegrity(full:)` runs `quick_check` or `integrity_check` on demand.188189## Deletion, retention, export190191`database.lifecycle` (`DataLifecycle`):192193- `delete(DeletionRequest(types:profileID:range:))` — any subset of `UserDataType` (`history`, `bookmarks`,194 `downloads`, `permissions`, `archives`, `snapshots`, `notes`, `canvases`, `agentRuns`, `recentlyClosed`,195 `session`, `workflows`, `settings`, `syncRecords`), for one profile or all, in a half-open time range or all196 time; one transaction; returns per-type counts and the archive files to remove from disk. Types without a197 profile (`workflows`, `settings`, `syncRecords`) are skipped by a profile-scoped request.198- `deleteProfile(_:)` — the profile, everything cascading from it, and the notes, canvases and agent runs of its199 spaces. The caller deletes the profile's WebKit data store and the reported archive files.200- `deleteEverything()` — all rows of all profiles, settings and sync records, then FTS rebuild, `VACUUM` and WAL201 truncation. Only the schema and the sync version counter remain.202- `HistoryStore.deleteVisits(in:)`, `deleteHost(_:includingSubdomains:)`, `deleteURL`, `deleteVisit`, `deleteAll`.203- Retention: `applyHistoryRetention(days:now:)`; `applyStoredRetentionPolicy()` uses the setting204 `PersistenceSettings.historyRetentionDays` (0 = keep forever). The app calls it at launch and daily.205- Export: `exportBundle` / `exportJSON` produce a `UserDataBundle` (JSON, ISO 8601 dates). It contains no206 cookies or website storage (WebKit owns them; this module never reads them), no secrets (Keychain), no WebKit207 session blobs and no download resume data.208209Residue after deletion: `secure_delete = ON` zeroes freed pages in the main file. Deleted content can remain in210the WAL until the next checkpoint and in FTS5 segments until they are merged; `deleteEverything()` and211`compact()` remove both. Selective deletions do not compact automatically.212213## Encryption at rest214215Stated plainly:216217- **The SQLite database is not encrypted by the application.** History, bookmarks, tabs, notes and the rest are218 stored in clear SQLite pages.219- On **iOS and iPadOS** the database, WAL and shared-memory files carry220 `FileProtectionType.completeUntilFirstUserAuthentication` (open flag plus file attribute): encrypted by the221 system with a key that is unavailable from boot until the first unlock, available afterwards — including while222 the device is locked, which background downloads and sync require. It does not protect against someone holding223 the unlocked device or a backup.224- On **macOS** protection is FileVault (full-disk encryption, if the user enabled it) and the app sandbox225 container's permissions. Any process running as the user outside the sandbox can read the file.226- **Secrets** (API keys of AI providers) are only in the Keychain: generic-password items,227 `kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly`, not synchronised to iCloud, namespaced by service. They are228 not in the database, not in exports, and `SecretStoreError` carries a status code only.229- Ghost data is not written at all.230231## Tests232233`Tests/PersistenceTests` (Swift Testing): SQLite layer, migrations (v1 fixture → latest, rollback, too new),234corruption and recovery, round trips of every store, session and clean-shutdown flag, history (FTS with Unicode235and hostile input, frecency), bookmarks (tree, Netscape import/export), ghost rejection, lifecycle, secret stores.236Two tests print measurements (`[benchmark]` lines): session restoration and omnibox suggestions on 100 000 URLs.237238```239cd Packages/NavigatorKit240swift test --disable-keychain --scratch-path build/spm-persistence --filter PersistenceTests241ORIX_KEYCHAIN_TESTS=1 swift test … # also exercises KeychainSecretStore against the login keychain242```243