SPB Git

Repository Public License

MEMORY.md 11.5 KB 163 lines markdown

1# Memory (opt-in local index)23Module `MemoryEngine` (`Packages/NavigatorKit/Sources/MemoryEngine`): a local index of what the user read or wrote,4searchable by words and — where the device has a model for the language — by meaning. Everything runs on the device.5Imports: NavigatorCore, Persistence, Foundation, CryptoKit, NaturalLanguage, Accelerate.67## Privacy rules (enforced in code, covered by tests)891. **Off by default.** The setting `memory.enabled` is `false` until the user turns the memory on. While off,10   `index` returns `.skipped(.disabled)` without creating a table, and `search` returns no hit.112. **Never ghost.** An input is refused when the caller flags it private (`MemoryPageFacts.isPrivate`), when its12   profile or space is declared in `database.ghosts`, or when its profile is simply not stored (a ghost profile never13   is). Limit: a note or other item with neither profile nor space carries no owner — the caller must not submit14   those from a private window (same limit as Persistence).153. **Never `no-store`, never password pages.** When the caller reports `Cache-Control: no-store` or a password16   field, the page is refused. No setting overrides this.174. **Per-site exclusions.** Host patterns: `example.org` (host and subdomains), `*.example.org` (subdomains only),18   `=example.org` (that host only). Adding an exclusion also deletes what was indexed for it.195. **Default exclusions of sensitive pages**, by URL heuristics (`MemoryPolicy.sensitiveCategory`):2021   | Category | Signals |22   |---|---|23   | authentication | subdomain label `login`, `signin`, `auth`, `sso`, `id`, `idp`, `identity`, `account(s)`, `secure`, `oauth`, `passport`; path word `login`, `signin`/`sign-in`, `signup`, `logout`, `auth…`, `oauth`, `sso`, `saml`, `openid`, `password`, `passcode`, `2fa`, `mfa`, `otp`, `verify`, `recover…`, `challenge`, `captcha` |24   | account | path word `account(s)`, `myaccount`, `billing`, `subscription(s)` |25   | payment | path word `checkout`, `payment(s)`, `pay`, `wallet`, `invoice(s)`, `card(s)` |26   | banking | host containing `bank`, `banque`, `banco`, `sparkasse`, `creditunion`, `caisse`, `desjardins`, `paypal`; path word `banking`, `ebanking`, `onlinebanking`, `netbanking` |27   | health | host containing `health`, `sante`, `clinic`, `clinique`, `hospital`, `hopital`, `medical`, `medic`, `patient`, `pharma`, `doctor`, `mychart`, `therapy` |28   | webmail | known webmail hosts (Gmail, Outlook, Yahoo, Proton, Fastmail, Zoho, HEY, AOL, Tuta, iCloud Mail) or a subdomain label `mail`, `webmail`, `email`, `outlook`, `inbox`, `owa` |29   | credentialsInURL | user/password in the URL; query key `token`, `access_token`, `id_token`, `code`, `session`, `sid`, `key`, `api_key`, `password`, `secret`, `auth`, `signature`, `sig`, `otp`, `state`, `ticket`, `jwt`; fragment with `token=` or `code=` |30   | localNetwork | `localhost`, single-label hosts, `.local`, `.internal`, `.lan`, `.home.arpa`, any IP literal |3132   These are heuristics: they err on the side of excluding (`foodbank.example` is treated as a bank) and they miss33   sensitive sites whose URL gives no hint. The user can exempt a host (`setAllowed`) or turn the heuristics off34   (`setUsesDefaultExclusions(false)`); neither overrides rules 2–4.356. Only `http`/`https` pages are indexed.367. **The index is excluded from capsules and sync** by construction: it lives in tables Persistence does not know,37   `UserDataBundle` and the capsule exporter enumerate Persistence stores only, and the sync engine refuses every38   `memory.*` setting key. A test checks that indexed text does not appear in the JSON export.3940## Storage4142Tables created idempotently by the module through `database.sqlite` (Persistence's schema is untouched); version in43the setting `memory.schema_version` (currently 1).4445| Table | Content |46|---|---|47| `memory_documents` | one row per indexed item: kind (`page`, `note`, `archive`, `snapshot`), item id, profile, space, URL, host, title, language, content hash, item date, indexing date, accounted size |48| `memory_chunks` | chunks of a document: ordinal, embedding model id, dimension, `embedding` BLOB (Float32, little-endian, L2-normalised) or NULL |49| `memory_fts` | FTS5 (`unicode61 remove_diacritics 2`) over chunk text and title; rowid = chunk id |5051The chunk text is stored once, in the FTS5 table. The database is not encrypted by the application (see52PERSISTENCE.md, "Encryption at rest"): the index has the same protection as history.5354## Pipeline55561. The caller extracts the text and passes a `MemoryInput` (helpers: `.page`, `.note`, `.snapshot`, `.archive`).572. Policy check (above).583. **Chunking** (`MemoryChunker`): paragraphs → sentences (`NLTokenizer`) → chunks of about 900 characters that never59   cut a sentence, prefer to end at a paragraph, and start with the last sentence(s) of the previous chunk (up to 15060   characters of overlap). Over-long sentences are cut at spaces (1 400 characters maximum). At most 300 chunks per61   document; beyond that the document is truncated and the report says so.624. **Language** detection (`NLLanguageRecognizer`).635. **Embeddings**: `MemoryEmbedder.model(for: language)` is asked at run time. With a model, each chunk gets a64   vector; without one the chunks are stored without vectors and the report's `embeddingModel` is `nil`.656. One transaction replaces the item's previous rows. Indexing the same content again returns `.unchanged`; the66   content hash includes the model identifier, so text indexed without vectors is embedded when a model appears.677. The storage cap is enforced.6869### Embedders7071| Type | What it uses | Default |72|---|---|---|73| `NLSentenceMemoryEmbedder` | `NLEmbedding.sentenceEmbedding(for:)` — static sentence embeddings shipped with the OS | **yes** |74| `NLContextualMemoryEmbedder` | `NLContextualEmbedding`, mean-pooled token vectors; only when the assets are already on the device (it never downloads by itself; `requestAssets(for:)` is explicit) | no |75| `PreferredMemoryEmbedder.appleDefault` | sentence embeddings first, contextual for languages without them | no |76| `NoMemoryEmbedder` | nothing: full-text only | no |7778Observed on the development Mac (macOS 27, Apple Silicon): sentence embeddings available for `en` (512 dimensions),79`fr`, `de`, `es`, `it`, `pt` (640 dimensions); not for `nl`, `ja`, `zh-Hans`, `ru`, `ar`. Contextual assets for `en`80and `fr` were present. Availability is checked per language at run time and differs between OS versions and devices.8182Measured similarities (a few probe sentences, English):8384| Model | Related text | Unrelated text |85|---|---|---|86| Sentence embedding | 0.19 – 0.46 | −0.02 – 0.11 |87| Contextual, mean-pooled | 0.82 – 0.87 | 0.62 – 0.76 |8889Hence the default floor of 0.15 for sentence embeddings, a floor of 0.8 for contextual vectors, and sentence90embeddings as the default. Both floors come from a handful of sentences, not from an evaluation corpus.9192## Search9394`MemoryIndex.search(query, filter:, limit:)`:9596- **Full text**: the query is split into words by `FTSQuery.tokens` (letters and digits only) and each word is97  quoted, so no user input reaches the FTS5 query language (tested with operators, quotes, NUL, 100 000-character98  input). Words are OR-ed and ranked by BM25 (title weighted ×2).99- **Vectors**: for each embedding model present in the index (at most four languages, largest first) the query is100  embedded with that same model and compared by cosine similarity with an **exact scan**: all vectors of a model101  sit in one contiguous Float32 matrix and the scan is one `vDSP_mmul`. Vectors of different models are never102  compared.103- **Fusion**: reciprocal rank fusion, `score = Σ 1 / (60 + rank)` over the two lists. One hit per item (its best104  chunk).105- **Filters** (applied to both rankers): kinds, profile, space, host (with subdomains), date range.106- **Snippets**: about 240 characters around the first matching word, with UTF-16 highlight ranges (case and107  diacritics ignored).108- The response states whether meaning-based search took part: `.used(models:)`, `.noEmbeddingsInIndex` or109  `.queryNotEmbeddable`. `isFullTextOnly` is true for the last two. A hit carries `fullTextRank`, `semanticRank` and110  `similarity`, so the UI can show why it matched. **When there is no model for a language, nothing semantic is111  computed or implied for it.**112113### Measured cost of the exact scan114115`swift test`, development Mac (Apple Silicon), 512-dimension vectors read back from SQLite, top-100:116117| Chunks | Matrix in RAM | Scan (release) | Scan (debug) | Load from SQLite (release) |118|---|---|---|---|---|119| 10 000 | 19 MiB | 0.24 ms | 1.4 ms | 10 ms |120| 50 000 | 97 MiB | 1.7 ms | 12.7 ms | 72 ms |121122At these sizes an approximate index would save nothing a user could notice, so none is implemented. The costs that123do grow are memory (2 KiB per chunk at 512 dimensions, held while the cache is warm — `releaseVectorCache()` drops124it) and disk. The default storage cap of 256 MiB bounds the index to roughly 100 000 chunks. Nothing was measured125on an iPhone or iPad.126127## Lifecycle128129- Delete: `delete(kind:itemID:)`, `delete(url:)`, `delete(host:includingSubdomains:)`, `delete(in: DateInterval)`130  (half-open, on the item date), `delete(space:)`, `delete(profile:)`, `deleteEverything()`. Each removes the131  document rows, the chunks with their vectors and the FTS entries in one transaction, and drops the in-memory132  vectors; tests assert that no row, vector or FTS entry is left. `deleteEverything()` additionally merges the FTS5133  segments.134- Size: `statistics()` (documents, chunks, embedded chunks, accounted bytes = UTF-8 text + titles + vector bytes;135  SQLite/FTS overhead not included, per-kind and per-model counts).136- Cap: `setStorageCap(bytes:)` / setting `memory.storage_cap_bytes`. Over the cap, the least recently **indexed**137  documents are deleted first. An item larger than the whole cap is refused (`.tooLarge`).138- Re-index: `index(_:)` again for changed content; `rebuildEmbeddings()` recomputes every vector with the current139  embedder (new model, new OS revision, model gone) without re-chunking.140- Opt-out: `setEnabled(false, purge:)` — the caller chooses whether turning the memory off also deletes it.141142## Integration notes for the app143144- `NavigatorDatabase.lifecycle.deleteEverything()` and `deleteProfile` do not know this module's tables: call145  `MemoryIndex.deleteEverything()` / `delete(profile:)` alongside. History deletions (by range, by host) should146  call the matching `delete` here.147- When a note, archive or snapshot is deleted, call `delete(kind:itemID:)`.148- The web runtime must supply `cacheControlNoStore` and `hasPasswordField`; this module cannot observe them.149150## Not verified / limits151152- No part of the app calls the module yet: extraction, the `no-store` and password-field facts, and deletion hooks153  are the caller's work and are untested end to end.154- Search quality is not evaluated on a corpus. The similarity floors and the fusion constant are defaults, not155  tuned values. Sentence embeddings of a 900-character chunk are a coarse summary of it.156- The contextual embedder was only checked to produce vectors of the right dimension on this Mac; its retrieval157  quality with mean pooling looked poor on the probes above.158- The sensitive-page heuristics are English/French-centric keyword lists; they are a safety net, not a classifier.159- Deleted text can remain in SQLite's WAL until the next checkpoint (see PERSISTENCE.md); FTS5 `secure-delete` is160  requested when the system SQLite supports it and silently skipped otherwise.161- CJK text is not word-segmented by `unicode61` (same limit as history search).162- Nothing was run on iOS; the target only compiles for it.163
Files main
Menu

Theme