SPB Git

Repository Public License

MEMORY.md 11.5 KB

# Memory (opt-in local index)

Module MemoryEngine (Packages/NavigatorKit/Sources/MemoryEngine): a local index of what the user read or wrote, searchable by words and — where the device has a model for the language — by meaning. Everything runs on the device. Imports: NavigatorCore, Persistence, Foundation, CryptoKit, NaturalLanguage, Accelerate.

# Privacy rules (enforced in code, covered by tests)

  1. Off by default. The setting memory.enabled is false until the user turns the memory on. While off, index returns .skipped(.disabled) without creating a table, and search returns no hit.

  2. Never ghost. An input is refused when the caller flags it private (MemoryPageFacts.isPrivate), when its profile or space is declared in database.ghosts, or when its profile is simply not stored (a ghost profile never is). Limit: a note or other item with neither profile nor space carries no owner — the caller must not submit those from a private window (same limit as Persistence).

  3. Never no-store, never password pages. When the caller reports Cache-Control: no-store or a password field, the page is refused. No setting overrides this.

  4. Per-site exclusions. Host patterns: example.org (host and subdomains), *.example.org (subdomains only), =example.org (that host only). Adding an exclusion also deletes what was indexed for it.

  5. Default exclusions of sensitive pages, by URL heuristics (MemoryPolicy.sensitiveCategory):

    Category Signals
    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
    account path word account(s), myaccount, billing, subscription(s)
    payment path word checkout, payment(s), pay, wallet, invoice(s), card(s)
    banking host containing bank, banque, banco, sparkasse, creditunion, caisse, desjardins, paypal; path word banking, ebanking, onlinebanking, netbanking
    health host containing health, sante, clinic, clinique, hospital, hopital, medical, medic, patient, pharma, doctor, mychart, therapy
    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
    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=
    localNetwork localhost, single-label hosts, .local, .internal, .lan, .home.arpa, any IP literal

    These are heuristics: they err on the side of excluding (foodbank.example is treated as a bank) and they miss sensitive sites whose URL gives no hint. The user can exempt a host (setAllowed) or turn the heuristics off (setUsesDefaultExclusions(false)); neither overrides rules 2–4.

  6. Only http/https pages are indexed.

  7. The index is excluded from capsules and sync by construction: it lives in tables Persistence does not know, UserDataBundle and the capsule exporter enumerate Persistence stores only, and the sync engine refuses every memory.* setting key. A test checks that indexed text does not appear in the JSON export.

# Storage

Tables created idempotently by the module through database.sqlite (Persistence's schema is untouched); version in the setting memory.schema_version (currently 1).

Table Content
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
memory_chunks chunks of a document: ordinal, embedding model id, dimension, embedding BLOB (Float32, little-endian, L2-normalised) or NULL
memory_fts FTS5 (unicode61 remove_diacritics 2) over chunk text and title; rowid = chunk id

The chunk text is stored once, in the FTS5 table. The database is not encrypted by the application (see PERSISTENCE.md, "Encryption at rest"): the index has the same protection as history.

# Pipeline

  1. The caller extracts the text and passes a MemoryInput (helpers: .page, .note, .snapshot, .archive).
  2. Policy check (above).
  3. Chunking (MemoryChunker): paragraphs → sentences (NLTokenizer) → chunks of about 900 characters that never cut a sentence, prefer to end at a paragraph, and start with the last sentence(s) of the previous chunk (up to 150 characters of overlap). Over-long sentences are cut at spaces (1 400 characters maximum). At most 300 chunks per document; beyond that the document is truncated and the report says so.
  4. Language detection (NLLanguageRecognizer).
  5. Embeddings: MemoryEmbedder.model(for: language) is asked at run time. With a model, each chunk gets a vector; without one the chunks are stored without vectors and the report's embeddingModel is nil.
  6. One transaction replaces the item's previous rows. Indexing the same content again returns .unchanged; the content hash includes the model identifier, so text indexed without vectors is embedded when a model appears.
  7. The storage cap is enforced.

# Embedders

Type What it uses Default
NLSentenceMemoryEmbedder NLEmbedding.sentenceEmbedding(for:) — static sentence embeddings shipped with the OS yes
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
PreferredMemoryEmbedder.appleDefault sentence embeddings first, contextual for languages without them no
NoMemoryEmbedder nothing: full-text only no

Observed on the development Mac (macOS 27, Apple Silicon): sentence embeddings available for en (512 dimensions), fr, de, es, it, pt (640 dimensions); not for nl, ja, zh-Hans, ru, ar. Contextual assets for en and fr were present. Availability is checked per language at run time and differs between OS versions and devices.

Measured similarities (a few probe sentences, English):

Model Related text Unrelated text
Sentence embedding 0.19 – 0.46 −0.02 – 0.11
Contextual, mean-pooled 0.82 – 0.87 0.62 – 0.76

Hence the default floor of 0.15 for sentence embeddings, a floor of 0.8 for contextual vectors, and sentence embeddings as the default. Both floors come from a handful of sentences, not from an evaluation corpus.

MemoryIndex.search(query, filter:, limit:):

  • Full text: the query is split into words by FTSQuery.tokens (letters and digits only) and each word is quoted, so no user input reaches the FTS5 query language (tested with operators, quotes, NUL, 100 000-character input). Words are OR-ed and ranked by BM25 (title weighted ×2).
  • Vectors: for each embedding model present in the index (at most four languages, largest first) the query is embedded with that same model and compared by cosine similarity with an exact scan: all vectors of a model sit in one contiguous Float32 matrix and the scan is one vDSP_mmul. Vectors of different models are never compared.
  • Fusion: reciprocal rank fusion, score = Σ 1 / (60 + rank) over the two lists. One hit per item (its best chunk).
  • Filters (applied to both rankers): kinds, profile, space, host (with subdomains), date range.
  • Snippets: about 240 characters around the first matching word, with UTF-16 highlight ranges (case and diacritics ignored).
  • The response states whether meaning-based search took part: .used(models:), .noEmbeddingsInIndex or .queryNotEmbeddable. isFullTextOnly is true for the last two. A hit carries fullTextRank, semanticRank and similarity, so the UI can show why it matched. When there is no model for a language, nothing semantic is computed or implied for it.

# Measured cost of the exact scan

swift test, development Mac (Apple Silicon), 512-dimension vectors read back from SQLite, top-100:

Chunks Matrix in RAM Scan (release) Scan (debug) Load from SQLite (release)
10 000 19 MiB 0.24 ms 1.4 ms 10 ms
50 000 97 MiB 1.7 ms 12.7 ms 72 ms

At these sizes an approximate index would save nothing a user could notice, so none is implemented. The costs that do grow are memory (2 KiB per chunk at 512 dimensions, held while the cache is warm — releaseVectorCache() drops it) and disk. The default storage cap of 256 MiB bounds the index to roughly 100 000 chunks. Nothing was measured on an iPhone or iPad.

# Lifecycle

  • Delete: delete(kind:itemID:), delete(url:), delete(host:includingSubdomains:), delete(in: DateInterval) (half-open, on the item date), delete(space:), delete(profile:), deleteEverything(). Each removes the document rows, the chunks with their vectors and the FTS entries in one transaction, and drops the in-memory vectors; tests assert that no row, vector or FTS entry is left. deleteEverything() additionally merges the FTS5 segments.
  • Size: statistics() (documents, chunks, embedded chunks, accounted bytes = UTF-8 text + titles + vector bytes; SQLite/FTS overhead not included, per-kind and per-model counts).
  • Cap: setStorageCap(bytes:) / setting memory.storage_cap_bytes. Over the cap, the least recently indexed documents are deleted first. An item larger than the whole cap is refused (.tooLarge).
  • Re-index: index(_:) again for changed content; rebuildEmbeddings() recomputes every vector with the current embedder (new model, new OS revision, model gone) without re-chunking.
  • Opt-out: setEnabled(false, purge:) — the caller chooses whether turning the memory off also deletes it.

# Integration notes for the app

  • NavigatorDatabase.lifecycle.deleteEverything() and deleteProfile do not know this module's tables: call MemoryIndex.deleteEverything() / delete(profile:) alongside. History deletions (by range, by host) should call the matching delete here.
  • When a note, archive or snapshot is deleted, call delete(kind:itemID:).
  • The web runtime must supply cacheControlNoStore and hasPasswordField; this module cannot observe them.

# Not verified / limits

  • No part of the app calls the module yet: extraction, the no-store and password-field facts, and deletion hooks are the caller's work and are untested end to end.
  • Search quality is not evaluated on a corpus. The similarity floors and the fusion constant are defaults, not tuned values. Sentence embeddings of a 900-character chunk are a coarse summary of it.
  • The contextual embedder was only checked to produce vectors of the right dimension on this Mac; its retrieval quality with mean pooling looked poor on the probes above.
  • The sensitive-page heuristics are English/French-centric keyword lists; they are a safety net, not a classifier.
  • Deleted text can remain in SQLite's WAL until the next checkpoint (see PERSISTENCE.md); FTS5 secure-delete is requested when the system SQLite supports it and silently skipped otherwise.
  • CJK text is not word-segmented by unicode61 (same limit as history search).
  • Nothing was run on iOS; the target only compiles for it.
Files main
Menu

Theme