AI, fully local on your computer.
TypeScript aiai-toolskiwixllama-cpplocal-ailocal-llmofflineoffline-aioffline-firstprivacy-firstragwikipediazim
import { createRequire } from 'node:module'
import { randomUUID } from 'node:crypto'
import { closeSync, fstatSync, openSync, readSync, statSync } from 'node:fs'
import { resolve } from 'node:path'
import { ocrMetaFromJson, parseOcrMeta } from './ingestion/ocr-meta'
// SQLite storage via Node's built-in driver (no native compilation).
// Requires the bundled Node >= 22.12; Electron is pinned ^43.7.7 (Node 24.x) so the packaged
// main process has node:sqlite (Electron 33 bundles Node 20 and lacks it).
// Measured on Electron 43.7.7 (DEP-5, 2026-10-01): Node 24.21.0, SQLite 3.53.4, with the
// FTS5 trio (bm25/snippet/highlight) giving the same results as 43.4.0 (3.53.1). Note the
// SQLite version is NOT a function of the Node version — E39 bundled 3.51.2 while host
// Node 24.13 bundles 3.50.4 — so it must be read off the real binary after every bump.
// Encrypted-at-rest mode wraps this same file/schema.
//
// node:sqlite is experimental and not listed in module.builtinModules, which
// makes bundlers (Vite/esbuild) try to resolve a non-existent "sqlite" package.
// Loading it through createRequire keeps the specifier opaque to bundlers so it
// resolves natively at runtime in both Electron's main process and vitest.
const nodeRequire = createRequire(process.execPath)
const { DatabaseSync } = nodeRequire('node:sqlite') as typeof import('node:sqlite')
export type Db = InstanceType<typeof DatabaseSync>
/** A compiled, reusable statement — `node:sqlite`'s `StatementSync`. */
export type Stmt = ReturnType<Db['prepare']>
// DB-5 — hot-path prepared-statement cache (perf audit 2026-06-18, Wave P5).
//
// node:sqlite re-parses AND re-plans the SQL text on every `db.prepare()`. The hottest read/
// write paths run that parse+plan per chat turn (chat.ts listMessages/appendMessage/
// getConversation/listConversations, collections.ts resolveScope ~2×/turn, the listDocuments
// grouped counters), re-compiling the SAME static SQL each call. This caches one compiled
// `StatementSync` per (Db, sql-text), keyed by the literal SQL string, so the compile happens
// once per connection. A `StatementSync` is freely re-runnable with new bind params and `.all()`
// fully materializes, so reuse is safe across calls. The WeakMap on `Db` lets the statements GC
// with their connection (no leak across open/close of encrypted workspaces).
//
// HARD CONSTRAINT — call this ONLY with a CONSTANT SQL string. A statement whose text varies per
// call (a dynamic `IN (?, ?, …)` arity, or any interpolated fragment) MUST stay on `db.prepare()`:
// caching those would leak an unbounded number of cache entries AND bind the wrong arity. The
// cache is keyed by exact text, so a one-off dynamic string would never even be reused.
const statementCaches = new WeakMap<Db, Map<string, Stmt>>()
export function prepareCached(db: Db, sql: string): Stmt {
let perDb = statementCaches.get(db)
if (!perDb) {
perDb = new Map<string, Stmt>()
statementCaches.set(db, perDb)
}
let stmt = perDb.get(sql)
if (!stmt) {
stmt = db.prepare(sql)
perDb.set(sql, stmt)
}
return stmt
}
// Schema mirrors spec §8. `IF NOT EXISTS` makes migration idempotent.
const SCHEMA = `
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value_json TEXT NOT NULL,
updated_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS conversations (
id TEXT PRIMARY KEY,
title TEXT NOT NULL,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
model_id TEXT,
mode TEXT NOT NULL DEFAULT 'chat'
);
CREATE TABLE IF NOT EXISTS messages (
id TEXT PRIMARY KEY,
conversation_id TEXT NOT NULL,
role TEXT NOT NULL,
content TEXT NOT NULL,
created_at TEXT NOT NULL,
token_count INTEGER,
citations_json TEXT,
FOREIGN KEY (conversation_id) REFERENCES conversations(id)
);
CREATE INDEX IF NOT EXISTS idx_messages_conversation ON messages(conversation_id);
CREATE TABLE IF NOT EXISTS documents (
id TEXT PRIMARY KEY,
title TEXT NOT NULL,
original_path TEXT,
stored_path TEXT,
mime_type TEXT,
size_bytes INTEGER,
sha256 TEXT,
status TEXT NOT NULL,
error_message TEXT,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS chunks (
id TEXT PRIMARY KEY,
document_id TEXT NOT NULL,
chunk_index INTEGER NOT NULL,
text TEXT NOT NULL,
source_label TEXT NOT NULL,
page_number INTEGER,
section_label TEXT,
token_count INTEGER,
created_at TEXT NOT NULL,
FOREIGN KEY (document_id) REFERENCES documents(id)
);
CREATE INDEX IF NOT EXISTS idx_chunks_document ON chunks(document_id);
CREATE TABLE IF NOT EXISTS embeddings (
chunk_id TEXT PRIMARY KEY,
embedding_model_id TEXT NOT NULL,
vector_blob BLOB NOT NULL,
dimensions INTEGER NOT NULL,
created_at TEXT NOT NULL,
FOREIGN KEY (chunk_id) REFERENCES chunks(id)
);
CREATE TABLE IF NOT EXISTS runtime_events (
id TEXT PRIMARY KEY,
event_type TEXT NOT NULL,
message TEXT NOT NULL,
metadata_json TEXT,
created_at TEXT NOT NULL
);
-- Local-API access key (local-api wave P2). Single row BY CONSTRAINT. Deliberately NOT a
-- settings row: getSettings spreads every stored row to the renderer on three IPC
-- surfaces, so the secret lives in its own main-process-only table
-- (services/local-api/token.ts is the sole reader/writer). Inside the workspace DB, so
-- it is encrypted at rest on an encrypted workspace and unreadable before unlock (D7).
CREATE TABLE IF NOT EXISTS local_api_token (
id INTEGER PRIMARY KEY CHECK (id = 1),
token TEXT NOT NULL,
updated_at TEXT NOT NULL
);
-- Document organization (architecture.md "Document organization — design record" §3). A collection is
-- the unifying primitive: Projects are collections; Library/Temporary are seeded
-- built-ins; Archive is a lifecycle; Generated is a role/view. Membership never
-- duplicates documents/chunks/embeddings.
CREATE TABLE IF NOT EXISTS collections (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
type TEXT NOT NULL, -- 'library' | 'project' | 'temporary' | 'archive' | 'smart'
description TEXT,
builtin INTEGER NOT NULL DEFAULT 0, -- 1 for the seeded Library/Temporary (undeletable)
color TEXT, -- optional UI accent; null = neutral
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
archived_at TEXT, -- project-level archive (null = active)
retention_policy_json TEXT -- reserved for later explicit retention (null in v1)
);
CREATE INDEX IF NOT EXISTS idx_collections_type ON collections(type);
-- Many-to-many document↔collection membership. ON DELETE CASCADE on BOTH FKs is
-- load-bearing for version-skew safety (plan C4): foreign_keys is ON and deleteDocument
-- deletes the documents row directly, so without CASCADE a delete would hit an FK
-- violation and dangling rows; CASCADE makes the orphan membership rows disappear.
CREATE TABLE IF NOT EXISTS document_collections (
document_id TEXT NOT NULL,
collection_id TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'source', -- 'source' | 'reference' | 'attachment' ('generated' RESERVED, unused in v1)
added_at TEXT NOT NULL,
PRIMARY KEY (document_id, collection_id),
FOREIGN KEY (document_id) REFERENCES documents(id) ON DELETE CASCADE,
FOREIGN KEY (collection_id) REFERENCES collections(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_doccoll_collection ON document_collections(collection_id);
CREATE INDEX IF NOT EXISTS idx_doccoll_document ON document_collections(document_id);
-- Temporary chat attachments are bound to their conversation HERE (plan C3), never via
-- scope_json. CASCADE removes only the LINK on conversation delete, never the document.
CREATE TABLE IF NOT EXISTS conversation_documents (
conversation_id TEXT NOT NULL,
document_id TEXT NOT NULL,
added_at TEXT NOT NULL,
PRIMARY KEY (conversation_id, document_id),
FOREIGN KEY (conversation_id) REFERENCES conversations(id) ON DELETE CASCADE,
FOREIGN KEY (document_id) REFERENCES documents(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_convdoc_conversation ON conversation_documents(conversation_id);
CREATE INDEX IF NOT EXISTS idx_convdoc_document ON conversation_documents(document_id);
-- Whole-document analysis (docs/rag-design.md §14.2 — analysis design record). A persistent
-- hierarchical summary tree (RAPTOR-lite) per document: level-1 nodes summarize groups of
-- chunks, level-2+ summarize lower nodes, up to one root. Built at ingest time so a
-- whole-document summary is a cheap read. Node summaries are CONTENT — never logged/audited.
CREATE TABLE IF NOT EXISTS tree_nodes (
id TEXT PRIMARY KEY,
document_id TEXT NOT NULL, -- source document (per-doc tree)
scope_key TEXT, -- reserved for a collection-level tree (NULL in per-doc v1)
level INTEGER NOT NULL, -- 1 = first summary level (children are chunks); 2+ summarize nodes
ordinal INTEGER NOT NULL, -- order within (document_id, level)
parent_id TEXT, -- NULL for the root
is_root INTEGER NOT NULL DEFAULT 0,
summary_text TEXT NOT NULL,
embedding_blob BLOB, -- raw LE Float32; NULL at build time, filled lazily on first symmetric compare (L6, rag-design §14.6)
dimensions INTEGER,
embedding_model_id TEXT, -- the embedder that produced embedding_blob (node search scopes by this)
content_hash TEXT NOT NULL, -- sha256 over ORDERED child texts — the summary_cache key (NOT node identity)
model_id TEXT, -- chat model that produced summary_text
created_at TEXT NOT NULL,
FOREIGN KEY (document_id) REFERENCES documents(id) ON DELETE CASCADE,
FOREIGN KEY (parent_id) REFERENCES tree_nodes(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_tree_nodes_doc ON tree_nodes(document_id, level, ordinal);
-- A node's ordered children: chunks (level-1 nodes) or lower nodes (level >= 2). child_id is
-- polymorphic (chunks.id when child_is_chunk=1, else tree_nodes.id), so it carries NO FK to
-- chunks — deleting chunks does NOT cascade here; re-index tears the tree down explicitly
-- (ingestion processDocument). Edges DO cascade when their parent node is deleted.
CREATE TABLE IF NOT EXISTS tree_edges (
parent_id TEXT NOT NULL,
child_id TEXT NOT NULL,
child_is_chunk INTEGER NOT NULL,
ordinal INTEGER NOT NULL,
PRIMARY KEY (parent_id, child_id),
FOREIGN KEY (parent_id) REFERENCES tree_nodes(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_tree_edges_parent ON tree_edges(parent_id);
-- Reverse lookup "which node(s) contain chunk/node X" (chunk->node provenance).
CREATE INDEX IF NOT EXISTS idx_tree_edges_child ON tree_edges(child_id, child_is_chunk);
-- Content cache (plan C3): maps the exact summarize-input text to its computed summary so a
-- rebuild — or a different document with identical boilerplate — skips the model call. This
-- is SEPARATE from node identity: a tree always gets one fresh tree_nodes row per structural
-- position, so repeated content can never collapse two positions into one node. Keyed by
-- (content_hash, model_id) so a chat-model change doesn't reuse an older model's summary. The
-- node vector (embedding_blob) is NULL at build time, embedded lazily on first use (L6,
-- rag-design §14.6). Carries no document_id; survives node/tree deletion; never pruned by FK.
-- Growth is bounded by a row-count cap (backend-audit-2026-06-27 DATA-3/MAINT-3): each tree
-- build opportunistically evicts the oldest rows past SUMMARY_CACHE_MAX_ROWS via
-- evictSummaryCache (analysis/summary-cache.ts). It is a cache, so eviction only costs a
-- future re-summarize, never data loss.
CREATE TABLE IF NOT EXISTS summary_cache (
content_hash TEXT NOT NULL,
model_id TEXT NOT NULL, -- chat model that produced summary_text
summary_text TEXT NOT NULL,
embedding_blob BLOB, -- node vector for this summary (NULL until first symmetric compare — L6)
embedding_model_id TEXT,
dimensions INTEGER,
created_at TEXT NOT NULL,
PRIMARY KEY (content_hash, model_id)
);
-- Structured extraction records (whole-document-analysis plan §3.3, Phase 3). One row per
-- item surfaced by the per-chunk extract pass over the fixed v1 type set, plus exactly one
-- bookkeeping "__scan__" marker row per scanned chunk (normalized_value 'ok' | 'unparsed')
-- that records the scan outcome and is the per-chunk resume/cache key. Query-time aggregation
-- GROUPs by normalized_value (scoped via buildScopeFilter) so "list every X" is 0 model calls.
-- value_text/normalized_value are CONTENT — never logged/audited.
-- [H1 free win] chunk_id has ON DELETE CASCADE, so re-index (which deletes+recreates chunks)
-- drops a document's extraction rows automatically — extraction self-invalidates on re-index
-- (under PRAGMA foreign_keys = ON, set in openDatabase).
CREATE TABLE IF NOT EXISTS extraction_records (
id TEXT PRIMARY KEY,
document_id TEXT NOT NULL,
chunk_id TEXT NOT NULL, -- provenance (which chunk this came from)
record_type TEXT NOT NULL, -- 'generic'|'date'|'amount'|'party'|'obligation' | '__scan__' marker
value_text TEXT NOT NULL, -- the surfaced item, verbatim-ish ('' for a marker)
normalized_value TEXT NOT NULL, -- lowercased/trimmed dedup key ('ok'|'unparsed' for a marker)
attributes_json TEXT, -- optional structured fields per type (NULL in v1)
model_id TEXT, -- chat model that produced the extraction
content_hash TEXT NOT NULL, -- sha256(chunk text + type-set version) — per-chunk cache key
created_at TEXT NOT NULL,
FOREIGN KEY (document_id) REFERENCES documents(id) ON DELETE CASCADE,
FOREIGN KEY (chunk_id) REFERENCES chunks(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_extract_doc_type ON extraction_records(document_id, record_type, normalized_value);
CREATE INDEX IF NOT EXISTS idx_extract_chunk ON extraction_records(chunk_id);
-- Result tables (result-tables plan §4, Phase 2): ONE generic tabular artifact attached to an
-- assistant message — the structured table behind an answer (e.g. the bank format path's
-- rows+categories), re-serializable on demand by the message-level "Export CSV" affordance.
-- Kept OUT of the messages row so a large table never rides every listMessages load (messages
-- carry only a derived hasResultTable flag). columns_json/rows_json are CONTENT — never
-- logged/audited; source is a content-free discriminator ('bank-statement'). The message FK
-- CASCADEs, so the regenerate delete and the conversation delete (which removes messages first,
-- in one transaction) both drop the table automatically under PRAGMA foreign_keys = ON.
-- Rider: the regenerate delete still cascades, but the two legs that put the OLD answer back (a
-- non-abort generation failure, and a Stop before the first token) now capture these rows before
-- the delete and replay them with the message -- so only a SUCCESSFUL regenerate actually drops
-- the table, which is correct: that answer was genuinely replaced. See DeletedMessage in
-- services/chat.ts. Note message_id carries only an INDEX, not a UNIQUE constraint, so the
-- "ONE tabular artifact per message" wording above is an intended invariant, not an enforced one;
-- the capture/replay handles N rows in (created_at, rowid) order accordingly.
-- (No backticks in this comment: it lives inside the SCHEMA template literal.)
CREATE TABLE IF NOT EXISTS result_tables (
id TEXT PRIMARY KEY,
message_id TEXT NOT NULL,
conversation_id TEXT NOT NULL,
columns_json TEXT NOT NULL, -- JSON TableColumn[] (key/label/kind)
rows_json TEXT NOT NULL, -- JSON row objects (content)
row_count INTEGER NOT NULL,
source TEXT, -- content-free origin discriminator
created_at TEXT NOT NULL,
FOREIGN KEY (message_id) REFERENCES messages(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_result_tables_message ON result_tables(message_id);
-- Skills registry (architecture.md "Skills — design record" §3/§10, revised §0 — plaintext plain-folder model). A
-- pure DERIVED INDEX + state cache over the on-disk skill folders (app-skills/ + user-skills/):
-- disk is the source of truth (DS1), so a DB rebuild simply re-reads the folders and re-derives
-- every row (no orphan, no recovery path). NOTE: there is deliberately NO foreign key FROM the
-- core tables (conversations/messages) INTO skills (audit C3 / §9.4) — a real FK would block
-- deletion and an older app must ignore the columns; references are cleared by an app-level sweep
-- (S4), never a cascade.
--
-- install_id is the DETERMINISTIC natural key "<source>:<id>" (S3 decision), NOT a random uuid:
-- user-skill folders are named by id so two same-id user skills can't coexist on disk, and a
-- disk-derived key is STABLE across a DB rebuild — so conversations.active_skill_id /
-- messages.skill_id keep resolving after a rebuild (a re-minted uuid would orphan them). Same-id
-- app vs user skills get distinct keys ("app:x" vs "user:x"), so DS12's collision handling holds.
CREATE TABLE IF NOT EXISTS skills (
install_id TEXT PRIMARY KEY, -- deterministic "<source>:<id>" (disk-derivable; stable across rebuilds)
id TEXT NOT NULL, -- declared kebab skill id (indexed, NON-unique across sources)
title TEXT NOT NULL,
version TEXT NOT NULL,
kind TEXT NOT NULL, -- 'instruction' | 'tool'
source TEXT NOT NULL, -- 'app' | 'user' (which folder it was discovered in)
path TEXT NOT NULL, -- on-disk folder BASENAME, relative to the source dir (portable, machine-independent)
enabled INTEGER NOT NULL, -- 0/1; app installs enabled, user drop-ins DISABLED (DS19)
warning_ack INTEGER NOT NULL, -- 0/1; untrusted-skill warning acknowledged (DS7; app=1, user drop-in=0)
trusted_level TEXT NOT NULL, -- 'app' | 'user' (APP-ASSIGNED, never self-declared)
manifest_json TEXT NOT NULL, -- cached parsed manifest (re-derivable cache; carries triggers + compatibility, §22-C2)
unavailable_at TEXT, -- NULL = folder present; ISO timestamp = folder vanished (mark-unavailable; never blind-deleted)
installed_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_skills_id ON skills(id); -- duplicate-id lookups across sources (the DS12 warning)
-- + disabled_reason TEXT (added by ensureColumn in applyPragmasAndMigrations, #846): why enabled = 0 —
-- 'user' | 'min_app_version' | 'duplicate' | 'unconfirmed', NULL = none recorded. Read only while enabled = 0.
-- Skill tool-run history (architecture.md "Skills — design record" §10, S11a). One row PER
-- app-orchestrated tool run (DS4), bracketed started → done|failed|cancelled. IDS/REFS ONLY —
-- never document/chat content: document_ids_json is ids, result_ref is a bank_statements.id or an
-- invoices.id, and
-- error is a friendly/technical reason. Excluded from every export (skills-plan §9.5). No FK INTO
-- skills (same audit-C3 reasoning as conversations/messages — references cleared by app sweep, not
-- a cascade), so a deleted skill never blocks or rewrites its run history.
CREATE TABLE IF NOT EXISTS skill_runs (
id TEXT PRIMARY KEY,
skill_install_id TEXT NOT NULL, -- skills.install_id ("<source>:<id>")
conversation_id TEXT, -- nullable: a doc-action run may not be a chat
document_ids_json TEXT, -- ids only, never content
status TEXT NOT NULL, -- 'started' | 'done' | 'failed' | 'cancelled'
created_at TEXT NOT NULL,
completed_at TEXT,
result_ref TEXT, -- e.g. a bank_statements.id / invoices.id; NEVER inline content
error TEXT -- friendly/technical reason; NEVER document/chat text
);
CREATE INDEX IF NOT EXISTS idx_skill_runs_skill ON skill_runs(skill_install_id);
-- Bank-statement data tables (architecture.md "Skills — design record" §10, S11a). CONTENT-CLASS: the extracted
-- figures are user content, so they live ONLY here in the encrypted workspace DB (a workspace
-- backup carries them — correct), are NEVER logged/audited (audit stays ids/counts), and are NEVER
-- in the skill .skill.zip or conversation export. Distinct from the non-secret skill packages
-- (DS20). S11a creates only what extract_transactions needs; categories/rules/corrections arrive
-- additively with S11c (the tree_nodes-per-feature precedent — no overbuild, skills-plan §13).
-- ON DELETE CASCADE on the document FK is load-bearing on FRESH drives (audit DATA-1): foreign_keys
-- is ON and deleteDocument deletes the documents row directly, so without CASCADE a delete of a
-- document that has an extraction would hit an FK violation. The whole bank chain cascades
-- (statement → transactions → corrections), so a bare DELETE FROM documents cleans up cleanly. On
-- drives created BEFORE this fix the FK has NO cascade (CREATE TABLE IF NOT EXISTS can't alter it),
-- so deleteDocument also does an explicit ordered delete (purgeDocumentDerivatives) — that ordered
-- delete is what keeps EXISTING drives safe; the cascade is defense-in-depth for fresh ones.
CREATE TABLE IF NOT EXISTS bank_statements (
id TEXT PRIMARY KEY,
document_id TEXT NOT NULL, -- the source document (id only)
run_id TEXT, -- the skill_runs.id that produced this extraction
period_start TEXT, -- as printed, nullable
period_end TEXT,
currency TEXT, -- statement currency, nullable
created_at TEXT NOT NULL,
FOREIGN KEY (document_id) REFERENCES documents(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_bank_statements_document ON bank_statements(document_id);
CREATE TABLE IF NOT EXISTS bank_transactions (
id TEXT PRIMARY KEY,
statement_id TEXT NOT NULL, -- references bank_statements.id
run_id TEXT,
row_index INTEGER NOT NULL, -- stable order within the statement
date TEXT NOT NULL, -- content: booking date as printed (ISO)
value_date TEXT, -- content
description TEXT NOT NULL, -- content
amount REAL NOT NULL, -- content: signed
currency TEXT NOT NULL,
balance_after REAL, -- content, nullable
source_page INTEGER, -- provenance (1-based) for quoting
created_at TEXT NOT NULL,
FOREIGN KEY (statement_id) REFERENCES bank_statements(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_bank_transactions_statement ON bank_transactions(statement_id);
-- Categorization + reconciliation + user-correction tables (architecture.md "Skills — design record" §10 full
-- future DDL, created additively at S11c — the tree_nodes-per-feature precedent). All CONTENT-CLASS
-- (a category name / a corrected figure is user content): encrypted workspace DB only, NEVER
-- logged/audited, NEVER exported (skills-plan §9.5). bank_corrections is created now but only
-- written by a future correction UI (out of S11c scope, §8) — the schema is ratified, so it lands
-- additively rather than as a later migration.
CREATE TABLE IF NOT EXISTS bank_categories (
id TEXT PRIMARY KEY,
name TEXT NOT NULL, -- content: the category label (e.g. "Income", "Fees")
builtin INTEGER NOT NULL DEFAULT 0,-- 1 = a built-in deterministic-rule category
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS bank_category_rules (
id TEXT PRIMARY KEY,
category_id TEXT NOT NULL, -- references bank_categories.id
match_kind TEXT NOT NULL, -- 'description-substring' | 'amount-sign'
pattern TEXT NOT NULL, -- the substring, or 'positive'|'negative' for amount-sign
created_at TEXT NOT NULL,
FOREIGN KEY (category_id) REFERENCES bank_categories(id)
);
CREATE INDEX IF NOT EXISTS idx_bank_category_rules_category ON bank_category_rules(category_id);
CREATE TABLE IF NOT EXISTS bank_corrections (
id TEXT PRIMARY KEY,
transaction_id TEXT NOT NULL, -- references bank_transactions.id
field TEXT NOT NULL, -- which column the user corrected
old_value TEXT, -- content
new_value TEXT, -- content
created_at TEXT NOT NULL,
FOREIGN KEY (transaction_id) REFERENCES bank_transactions(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_bank_corrections_transaction ON bank_corrections(transaction_id);
-- Invoice data tables (architecture.md "Skills — design record" §8/§10). The SECOND Tier-2
-- content-class domain, mirroring the bank_* tables exactly: the extracted figures are user content,
-- so they live ONLY here in the encrypted workspace DB (a workspace backup carries them — correct),
-- are NEVER logged/audited (audit stays ids/counts), and are NEVER in the skill .skill.zip or
-- conversation export. skill_runs.result_ref points at an invoices.id; it never inlines content.
CREATE TABLE IF NOT EXISTS invoices (
id TEXT PRIMARY KEY,
document_id TEXT NOT NULL, -- the source document (id only)
run_id TEXT, -- the skill_runs.id that produced this extraction
vendor TEXT, -- content: seller name as printed, nullable
invoice_number TEXT, -- content, nullable
invoice_date TEXT, -- content: ISO, nullable
due_date TEXT, -- content: ISO, nullable
currency TEXT, -- invoice currency, nullable
net_total REAL, -- content, nullable
tax_total REAL, -- content, nullable
tax_rate REAL, -- content: tax rate percent, nullable
gross_total REAL, -- content, nullable
totals_reconciled INTEGER, -- 1 reconciled / 0 not / NULL unchecked (validate_invoice_totals)
created_at TEXT NOT NULL,
-- ON DELETE CASCADE (document → invoices → line items) mirrors the bank chain: load-bearing on
-- fresh drives, with the explicit ordered delete in purgeDocumentDerivatives covering existing
-- ones (audit DATA-1).
FOREIGN KEY (document_id) REFERENCES documents(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_invoices_document ON invoices(document_id);
CREATE TABLE IF NOT EXISTS invoice_line_items (
id TEXT PRIMARY KEY,
invoice_id TEXT NOT NULL, -- references invoices.id
run_id TEXT,
row_index INTEGER NOT NULL, -- stable order within the invoice
description TEXT NOT NULL, -- content
quantity REAL, -- content, nullable
unit_price REAL, -- content, nullable
line_total REAL NOT NULL, -- content
currency TEXT NOT NULL,
created_at TEXT NOT NULL,
FOREIGN KEY (invoice_id) REFERENCES invoices(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_invoice_line_items_invoice ON invoice_line_items(invoice_id);
-- Image-understanding history (docs/architecture.md image-understanding record). Each
-- analyzed image becomes a session: the image bytes are stored under workspace/images/
-- (encrypted-at-rest when the vault is encrypted — same DocumentCipher as documents) and
-- the Q&A turns are appended here. Deleting a session shreds the stored image (in the
-- service) and CASCADE-removes its turns. stored_name is a RELATIVE filename (resolved
-- against imagesDir at call time) so the drive stays portable across OSes.
CREATE TABLE IF NOT EXISTS image_sessions (
id TEXT PRIMARY KEY,
title TEXT NOT NULL, -- original file name
stored_name TEXT NOT NULL, -- relative filename under images/ (never absolute)
mime_type TEXT NOT NULL,
size_bytes INTEGER NOT NULL,
width INTEGER,
height INTEGER,
encrypted INTEGER NOT NULL DEFAULT 0, -- 1 when stored as a .enc sidecar
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS image_turns (
id TEXT PRIMARY KEY,
session_id TEXT NOT NULL,
question TEXT NOT NULL,
answer TEXT NOT NULL,
created_at TEXT NOT NULL,
FOREIGN KEY (session_id) REFERENCES image_sessions(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_image_turns_session ON image_turns(session_id);
-- Evidence Pack / Review Mode (EP-1 plan §5, spec §18.1). One review per assistant message
-- (v1, service-enforced — deliberately NOT a UNIQUE constraint so relaxing later is additive).
-- ALL review text/snapshot columns are CONTENT — never logged/audited (audit stays ids/counts).
-- The tables live in the one workspace DB, so they inherit encrypted-at-rest for free (spec
-- §18.5 satisfied structurally — nothing extra built). status stores ONLY 'draft'|'ready';
-- outdated is DERIVED at read time (spec §18.4 — it must never erase ready). JSON snapshot
-- columns are nullable (plan §5 item 3) and parsed tolerantly (the parseCitations idiom).
-- The message FK CASCADEs (the result_tables template): deleteConversation deletes messages
-- with explicit SQL under PRAGMA foreign_keys = ON, which drops the whole review chain
-- (reviews → items → links, reviews → exports) automatically.
CREATE TABLE IF NOT EXISTS evidence_reviews (
id TEXT PRIMARY KEY,
conversation_id TEXT NOT NULL, -- denormalized for the delete-confirm count (D-2)
message_id TEXT NOT NULL, -- the reviewed assistant message
question_message_id TEXT, -- the question turn, when identifiable
title TEXT NOT NULL, -- content (D-6: conversation title default, renameable)
status TEXT NOT NULL, -- 'draft' | 'ready'
reviewer_label TEXT, -- content (D-3: free-text label only)
general_note TEXT, -- content
answer_snapshot TEXT NOT NULL, -- content: the frozen answer markdown
question_snapshot TEXT NOT NULL, -- content: the frozen question text ('' when none)
source_snapshot_json TEXT, -- JSON EvidenceSourceSnapshot[] (content)
coverage_snapshot_json TEXT, -- JSON CoverageInfo (counts/mode only)
generation_snapshot_json TEXT, -- JSON EvidenceGenerationSnapshot (ids/flags only)
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
completed_at TEXT, -- last marked ready; NULL while draft
freshness_ack_json TEXT, -- EP-1 P4: JSON { acknowledgedAt, fingerprint } — the
-- acknowledged drift state (spec §15.5/§28.6); NULL = never
-- acknowledged. Never touches status/completed_at (§18.4).
FOREIGN KEY (message_id) REFERENCES messages(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_evidence_reviews_message ON evidence_reviews(message_id);
-- AUD-14: conversation_id is denormalized onto the head row purely so two conversation-scoped
-- reads never have to join through messages -- the delete-confirm COUNT (D-2) and the chat
-- transcript's chip-state batch. Both filtered on an UNINDEXED column, so each one scanned
-- every review row in the workspace; this additive index turns them into index SEARCHes.
-- (No backticks in this comment: it lives inside the SCHEMA template literal.)
CREATE INDEX IF NOT EXISTS idx_evidence_reviews_conversation ON evidence_reviews(conversation_id);
CREATE TABLE IF NOT EXISTS evidence_review_items (
id TEXT PRIMARY KEY,
review_id TEXT NOT NULL,
ordinal INTEGER NOT NULL, -- creation/render order within the review
kind TEXT NOT NULL, -- 'block' | 'selection'
block_key TEXT NOT NULL, -- stable segment key against the snapshot (plan §6.1)
block_kind TEXT, -- 'paragraph'|'list_item'|'heading'|'fence'|'table'|'blockquote';
-- NULL = unknown → REQUIRED by the D-7 gate (safe direction)
start_offset INTEGER, -- selections: UTF-16 offsets into the parent block's text_snapshot
end_offset INTEGER,
text_snapshot TEXT NOT NULL, -- content: the unit's frozen text
decision TEXT NOT NULL, -- ReviewDecision ('not_reviewed' default)
reviewer_note TEXT, -- content
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
FOREIGN KEY (review_id) REFERENCES evidence_reviews(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_evidence_review_items_review ON evidence_review_items(review_id);
CREATE TABLE IF NOT EXISTS evidence_review_links (
id TEXT PRIMARY KEY,
review_item_id TEXT NOT NULL,
evidence_key TEXT NOT NULL, -- EvidenceSourceSnapshot.key (one link per item+key)
link_origin TEXT NOT NULL, -- 'answer_marker' | 'reviewer' (honesty split, spec §13.3)
reviewer_relation TEXT, -- 'supports'|'qualifies'|'contradicts'|'context'
created_at TEXT NOT NULL,
FOREIGN KEY (review_item_id) REFERENCES evidence_review_items(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_evidence_review_links_item ON evidence_review_links(review_item_id);
-- Export history (D-8): metadata + content hash ONLY — no file copy, and the destination
-- path is deliberately NOT persisted (spec §18.1; file_name is the bare chosen name).
CREATE TABLE IF NOT EXISTS evidence_exports (
id TEXT PRIMARY KEY,
review_id TEXT NOT NULL,
format TEXT NOT NULL, -- 'html' | 'pdf' (plain TEXT — later formats additive)
schema_version INTEGER NOT NULL,
file_name TEXT NOT NULL, -- content-adjacent (user-chosen name; never audited)
file_sha256 TEXT NOT NULL,
options_json TEXT, -- JSON option flags (D-4); nullable
created_at TEXT NOT NULL,
FOREIGN KEY (review_id) REFERENCES evidence_reviews(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_evidence_exports_review ON evidence_exports(review_id);
-- Knowledge packs (ZIM wave): registered external ZIM archives the chat can retrieve from
-- via the kiwix-serve sidecar. Like skills, a derived index over on-disk files — the id
-- is the archive's own UUID (read by kiwix-manage at registration), so a re-registration
-- of the same archive is an upsert and the id survives a DB rebuild. The FILE is never
-- copied (multi-GB, public, read-only — the deliberate exception to the stored-copy rule,
-- rag-design ZIM record): leaf + recorded_path follow the stored-copy resolution shape
-- (drive-relative zim/<leaf> first, recorded path second; ingestion/stored-copy.ts
-- precedent), and a missing file marks unavailable_at — never a blind delete. Metadata
-- columns are pack-level facts from the archive header (title/description/language/counts):
-- they name what the user reads, so they are CONTENT for audit/export purposes (ids/counts
-- only in runtime_events) but plain rows here inside the encrypted workspace DB.
-- No FK from conversations into this table: a chat's scope stores pack ids in
-- scope_v2_json and a removed pack degrades to "not retrieved from" (the skills C3 rule).
CREATE TABLE IF NOT EXISTS knowledge_packs (
id TEXT PRIMARY KEY, -- ZIM archive UUID (natural key; stable across re-adds/rebuilds)
title TEXT NOT NULL,
description TEXT,
language TEXT, -- archive-declared ISO code ("deu", "eng")
zim_date TEXT, -- archive build date YYYY-MM-DD
article_count INTEGER,
media_count INTEGER,
size_bytes INTEGER,
leaf TEXT NOT NULL, -- file BASENAME (portable resolution: <drive>/zim/<leaf> first)
recorded_path TEXT NOT NULL, -- path as registered (fallback resolution; may be absolute)
enabled INTEGER NOT NULL, -- 0/1 (a disabled pack stays registered but is never queried)
unavailable_at TEXT, -- NULL = file present at last look; ISO stamp = vanished (never blind-deleted)
removed_at TEXT, -- tombstone: user removed the registration. The ROW stays so
-- drive auto-discovery (keyed by leaf) cannot resurrect a
-- deliberately removed pack; an explicit re-add clears it.
searchable TEXT, -- CONFIRMED full-text capability: 'yes' | 'no'; NULL = unknown (never probed,
-- or the cache key below moved). Only a validated /suggest probe writes it.
searchable_key TEXT, -- the fingerprint the verdict was taken under: <size>:<mtimeMs> of the archive
-- plus the kiwix-serve binary's <size>:<mtimeMs>. A different key resets the verdict.
ftindex_hint TEXT, -- the archive's own _ftindex tag ('yes' | 'no'; NULL = no tag) — a HINT only:
-- it never sets searchable and never affects an ask's eligibility.
added_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
`
// Additive column migrations on top of the spec §8 base schema. `CREATE TABLE IF NOT
// EXISTS` never alters an existing table, so columns added after a workspace was created
// must be ALTERed in — guarded by a pragma check to stay idempotent.
// conversations.scope_json — the optional "ask selected documents" scope, a JSON
// array of document ids (NULL = whole corpus).
// documents.summary_json — the persisted one-click summary
// `{ text, modelId, createdAt, truncated }` (NULL = none).
// documents.origin_json — provenance of an app-generated document — a `DocumentOrigin`
// (translation `{ translatedFrom, targetLang }` or compare `{ type: 'compare',
// comparedFrom: [a, b] }`; NULL = normal import).
function ensureColumn(db: Db, table: string, column: string, ddl: string): void {
// The arguments are interpolated into SQL (SQLite cannot parameterize DDL). Every
// caller passes compile-time constants, but assert the shape anyway so a future
// caller cannot turn this into an injection point.
const ident = /^[A-Za-z_][A-Za-z0-9_]*$/
if (!ident.test(table) || !ident.test(column) || !/^[A-Za-z0-9_ ]+$/.test(ddl)) {
throw new Error(`ensureColumn: unsafe identifier/DDL (${table}.${column}: ${ddl})`)
}
const cols = db.prepare(`PRAGMA table_info(${table})`).all() as Array<{ name: string }>
if (!cols.some((c) => c.name === column)) {
db.exec(`ALTER TABLE ${table} ADD COLUMN ${ddl}`)
}
}
/**
* PERF-3 (full-audit-2026-06-29 follow-up, Phase 4) — one-time backfill of the `ocr_meta_json`
* sidecar for rows imported before that column existed. Reads each row's `ocr_json` blob ONCE,
* extracts ONLY the surface metadata (`ocrMetaFromJson` — never page text), and writes the sidecar
* so the hot `listDocuments` path can read the OCR badge without parsing the blob again. After the
* first open every OCR'd row has meta, so subsequent opens re-derive nothing (they read only the
* small sidecars of the OCR'd rows). Touches ONLY the new column — `updated_at` is left alone (a
* transparent migration, not a content edit), and no FK/lifecycle column is read or written, so an
* old on-disk workspace opens cleanly. Batched in one transaction to amortize fsyncs on the
* high-latency USB drive (DB-2).
*
* #576: a sidecar written before `textPageCount` existed counted blank pages as recognized; it is
* re-derived from `ocr_json` the same way (once — the re-derived sidecar carries the field). A
* malformed sidecar is re-derived too. Filtered in JS, not with `json_extract`: a corrupt value
* must never make the open itself fail. (A photo's sidecar has no `ocr_json` behind it, #574, and
* is written whole.)
*/
function backfillOcrMeta(db: Db): void {
const candidates = db
.prepare('SELECT id, ocr_meta_json FROM documents WHERE ocr_json IS NOT NULL')
.all() as Array<{ id: string; ocr_meta_json: string | null }>
const stale = candidates.filter((r) => parseOcrMeta(r.ocr_meta_json)?.textPageCount === undefined)
if (stale.length === 0) return
const read = db.prepare('SELECT ocr_json FROM documents WHERE id = ?')
const update = db.prepare('UPDATE documents SET ocr_meta_json = ? WHERE id = ?')
inOneTransaction(db, () => {
for (const r of stale) {
const row = read.get(r.id) as { ocr_json: string | null } | undefined
const meta = ocrMetaFromJson(row?.ocr_json)
// A blob that yields no valid page leaves meta NULL (the badge was already absent); it is
// re-examined on the next open (negligible — effectively never happens for real OCR output).
if (meta) update.run(JSON.stringify(meta), r.id)
}
})
}
// CODE-4 (full audit 2026-07-11) — the canonical, rowid-targeted FTS sync trigger sets.
//
// The original AD/AU triggers deleted `WHERE chunk_id/message_id = old.id`. FTS5 has NO index
// on UNINDEXED columns, so every per-row trigger firing full-scanned the `%_content` shadow
// table — O(K·N) for a K-row delete over an N-row corpus. Measured on the production schema
// (50k chunks / ~30 MB text, in-memory): 3536 ms to delete one 250-chunk document via the
// triggers vs 29 ms set-based (123×) — synchronous on the Electron main process, fired by
// re-index/delete (ingestion), every regenerate, and conversation delete (chat.ts).
//
// The fix: a nullable `fts_rowid` handle column on `chunks`/`messages` (FTS5's `%_content`
// table has an EXPLICIT integer PK, so FTS rowids are VACUUM-stable — unlike the base tables'
// implicit rowids that ruled out external-content). The AI trigger stamps it via
// `last_insert_rowid()` (which, INSIDE a trigger body, reflects the trigger's own FTS insert —
// probed on node:sqlite/SQLite 3.50); the AD/AU triggers delete `WHERE rowid = old.fts_rowid`,
// an O(log N) lookup (EXPLAIN QUERY PLAN "VIRTUAL TABLE INDEX 0:=", not the bare-scan "0:").
//
// The NULL fallback is a SEPARATE `_legacy` trigger gated by `WHEN old.fts_rowid IS NULL`
// rather than an OR inside one DELETE: a constant conjunct on a virtual-table scan is evaluated
// per row, not short-circuited at plan time, so a single combined predicate would still scan.
// The WHEN split keeps the hot path provably rowid-only while legacy rows (pre-migration, or a
// row written mid-upgrade) keep the exact old predicate — correctness never regresses, even
// under a ROLLED-BACK binary: triggers live in the DB file, so an older app keeps stamping and
// consuming the handle without knowing about it.
//
// Recursion safety: the AI-trigger `UPDATE chunks SET fts_rowid=…` cannot re-fire the AU
// triggers (they are `UPDATE OF text`/`OF content` only), and recursive triggers are off by
// default in SQLite.
const CHUNKS_FTS_TRIGGERS = `
CREATE TRIGGER chunks_fts_ai AFTER INSERT ON chunks BEGIN
INSERT INTO chunks_fts(text, chunk_id) VALUES (new.text, new.id);
UPDATE chunks SET fts_rowid = last_insert_rowid() WHERE id = new.id;
END;
CREATE TRIGGER chunks_fts_ad AFTER DELETE ON chunks WHEN old.fts_rowid IS NOT NULL BEGIN
DELETE FROM chunks_fts WHERE rowid = old.fts_rowid;
END;
CREATE TRIGGER chunks_fts_ad_legacy AFTER DELETE ON chunks WHEN old.fts_rowid IS NULL BEGIN
DELETE FROM chunks_fts WHERE chunk_id = old.id;
END;
CREATE TRIGGER chunks_fts_au AFTER UPDATE OF text ON chunks WHEN old.fts_rowid IS NOT NULL BEGIN
DELETE FROM chunks_fts WHERE rowid = old.fts_rowid;
INSERT INTO chunks_fts(text, chunk_id) VALUES (new.text, new.id);
UPDATE chunks SET fts_rowid = last_insert_rowid() WHERE id = new.id;
END;
CREATE TRIGGER chunks_fts_au_legacy AFTER UPDATE OF text ON chunks WHEN old.fts_rowid IS NULL BEGIN
DELETE FROM chunks_fts WHERE chunk_id = old.id;
INSERT INTO chunks_fts(text, chunk_id) VALUES (new.text, new.id);
UPDATE chunks SET fts_rowid = last_insert_rowid() WHERE id = new.id;
END;
`
// The messages twins carry the compaction `kind` guards (R8/DATA-1) IN the canonical set, so
// an older binary reopening a migrated workspace sees `new.kind` and leaves them alone, and the
// canonical set is the only place an old workspace gets the guards (`ensureFtsRowidSync`).
// Nuances beyond the chunks set:
// - messages_fts_ad_legacy ALSO excludes `old.kind IS 'compaction'`: a compaction row is
// guaranteed absent from the index (the AI guard for new rows; ensureMessagesFtsKindFilter
// pruned any legacy-indexed ones on the same upgrade open), so its handle is permanently
// NULL and without the exclusion every checkpoint-row delete would pay one legacy scan for
// a row that has no FTS entry at all.
// - the AU stamps `CASE WHEN new.kind IS NOT 'compaction' THEN last_insert_rowid() ELSE NULL
// END`: when the kind guard suppresses the re-insert, last_insert_rowid() is a stale value
// from some earlier statement and must not be stored (a plain→compaction transition parks
// the handle at NULL, matching the row's now-unindexed state).
const MESSAGES_FTS_TRIGGERS = `
CREATE TRIGGER messages_fts_ai AFTER INSERT ON messages WHEN new.kind IS NOT 'compaction' BEGIN
INSERT INTO messages_fts(content, message_id) VALUES (new.content, new.id);
UPDATE messages SET fts_rowid = last_insert_rowid() WHERE id = new.id;
END;
CREATE TRIGGER messages_fts_ad AFTER DELETE ON messages WHEN old.fts_rowid IS NOT NULL BEGIN
DELETE FROM messages_fts WHERE rowid = old.fts_rowid;
END;
CREATE TRIGGER messages_fts_ad_legacy AFTER DELETE ON messages
WHEN old.fts_rowid IS NULL AND old.kind IS NOT 'compaction' BEGIN
DELETE FROM messages_fts WHERE message_id = old.id;
END;
CREATE TRIGGER messages_fts_au AFTER UPDATE OF content ON messages WHEN old.fts_rowid IS NOT NULL BEGIN
DELETE FROM messages_fts WHERE rowid = old.fts_rowid;
INSERT INTO messages_fts(content, message_id)
SELECT new.content, new.id WHERE new.kind IS NOT 'compaction';
UPDATE messages SET fts_rowid = CASE WHEN new.kind IS NOT 'compaction' THEN last_insert_rowid() ELSE NULL END
WHERE id = new.id;
END;
CREATE TRIGGER messages_fts_au_legacy AFTER UPDATE OF content ON messages WHEN old.fts_rowid IS NULL BEGIN
DELETE FROM messages_fts WHERE message_id = old.id;
INSERT INTO messages_fts(content, message_id)
SELECT new.content, new.id WHERE new.kind IS NOT 'compaction';
UPDATE messages SET fts_rowid = CASE WHEN new.kind IS NOT 'compaction' THEN last_insert_rowid() ELSE NULL END
WHERE id = new.id;
END;
`
/**
* Run `body` inside ONE transaction: COMMIT when it returns, ROLLBACK when it throws (best-effort —
* the original failure is what propagates). Outside a transaction a multi-statement `db.exec`
* commits statement by statement (a failure part-way leaves the prefix committed), so FTS DDL that
* must land together with its backfill goes through here. Never nest it: a nested BEGIN throws.
*/
function inOneTransaction(db: Db, body: () => void): void {
db.exec('BEGIN')
try {
body()
db.exec('COMMIT')
} catch (err) {
try {
db.exec('ROLLBACK')
} catch {
/* keep the original failure as the thrown error */
}
throw err
}
}
/**
* CODE-4 — populate `fts_rowid` for rows that predate the handle (the one-time backfill half
* of the migration; also used by the fresh-create paths, whose bulk `INSERT … SELECT` into the
* FTS table bypasses the AI trigger). ONE scan of the FTS table builds the id→rowid map (the
* per-row correlated-subquery alternative would be the very O(N²) scan this migration removes),
* then PK-targeted updates run inside the CALLER's transaction: every caller commits its DDL and
* this backfill as one (`inOneTransaction`), so the handles are never lost apart from the
* triggers that stamp and read them (#737). Rows with no FTS entry (compaction messages; a
* genuinely orphaned row) keep NULL and stay on the legacy-trigger path — correct, just slow, and
* never re-scanned per open (the caller's trigger check is the run-once guard). `target` is a
* compile-time union, so the interpolation cannot become an injection point.
*/
function backfillFtsRowids(db: Db, target: 'chunks' | 'messages'): void {
const fts = target === 'chunks' ? 'chunks_fts' : 'messages_fts'
const key = target === 'chunks' ? 'chunk_id' : 'message_id'
const rows = db
.prepare(`SELECT rowid AS r, ${key} AS id FROM ${fts}`)
.all() as unknown as Array<{ r: number; id: string }>
// `AND fts_rowid IS NULL` keeps this idempotent-safe: a handle the triggers already stamped
// (rows written after the trigger rewrite, before this backfill ran) is never clobbered.
const update = db.prepare(`UPDATE ${target} SET fts_rowid = ? WHERE id = ? AND fts_rowid IS NULL`)
for (const row of rows) update.run(row.r, row.id)
}
// #737 — what "current" means for a live FTS sync trigger: it carries every style marker its
// canonical body carries. `fts_rowid` is CODE-4's handle (every canonical trigger stamps, targets
// or gates on it); `new.kind` is the R8/DATA-1 guard that keeps a checkpoint out of the index
// (messages ai/au/au_legacy). Markers, not bytes: a body that differs only in spacing or comments
// still counts, so no other build's text of the same set is rewritten on every open.
const FTS_STYLE_MARKERS = ['fts_rowid', 'new.kind']
/** A canonical set as name → the style markers its trigger carries, parsed from the DDL itself
* (each statement runs from `CREATE TRIGGER <name>` to an `END;` line). */
function canonicalTriggerMarkers(ddl: string): Map<string, string[]> {
const markers = new Map<string, string[]>()
for (const [statement, name] of ddl.matchAll(/^CREATE TRIGGER (\w+)[\s\S]*?^END;$/gm)) {
markers.set(name, FTS_STYLE_MARKERS.filter((m) => statement.includes(m)))
}
// Five per table (ai, ad, au and the two legacy twins). A DDL edit this pattern no longer matches would
// otherwise read every table as current and switch the heal off without a word; fail at load instead.
if (markers.size !== 5) throw new Error(`FTS trigger DDL parsed to ${markers.size} triggers, expected 5`)
return markers
}
const CANONICAL_FTS_TRIGGERS = {
chunks: { ddl: CHUNKS_FTS_TRIGGERS, markers: canonicalTriggerMarkers(CHUNKS_FTS_TRIGGERS) },
messages: { ddl: MESSAGES_FTS_TRIGGERS, markers: canonicalTriggerMarkers(MESSAGES_FTS_TRIGGERS) }
} as const
/**
* CODE-4 (full audit 2026-07-11) — upgrade a pre-fix workspace to the rowid-targeted trigger
* sets (see the CHUNKS_FTS_TRIGGERS comment for the why + measurements), and heal a torn set.
* Idempotent: a table whose live triggers already make up its whole canonical set — every
* trigger the canonical DDL creates exists and carries its style markers (FTS_STYLE_MARKERS) —
* is left alone, for one sqlite_master read per table; any other state rewrites all five and
* backfills the handles, in the same open. Runs AFTER the FTS ensures + the kind-filter prune,
* so (a) the tables/columns exist, (b) a pre-compaction / pre-DATA-1 workspace's unguarded ai/au
* are replaced here by the guarded canonical set, and (c) the compaction-row prune has already
* run, so the backfill can never map a checkpoint row (its FTS entry is gone by now).
*
* Crash-atomicity (CODE-4 review follow-up): the DROPs + CREATEs + backfill run inside ONE
* transaction (trigger DDL is transactional in SQLite), so a process kill mid-upgrade rolls
* back to the intact pre-migration state and the check simply retries on the next open —
* a bare multi-statement `db.exec` auto-commits per statement, which could tear the trigger
* set (e.g. AD dropped but never recreated: deletes silently stop maintaining the index) and
* could commit the CREATEs with the backfill lost (the whole corpus parked on the legacy scan
* path forever). The DDL uses DROP TRIGGER IF EXISTS throughout, so the rewrite is safe from
* ANY trigger state.
*
* What it heals (#737): any set missing a trigger or holding one in an older style — a torn
* upgrade, a torn fresh create from a build before #737 (whose exec committed statement by
* statement, ai first), an AI without the compaction guard beside a current AD. Until #737 the
* check read the AD trigger alone, so every tear that kept AD stayed torn. What it cannot heal:
* index ENTRIES. Rows written while a trigger was missing, and the bulk fill or handle backfill a
* pre-#737 fresh create lost, stay unindexed (or on the legacy scan path): the triggers are made
* whole, but nothing re-reads the base table. Since #737 ensureChunksFts/ensureMessagesFts
* commit as one transaction too, so no build from here on leaves those states behind. No repair
* is built (#779): only a workspace created before either index existed (tags v0.1.0–v0.1.5,
* before any build was handed out) can have lost entries — rag-design.md §11.
*/
function ensureFtsRowidSync(db: Db): void {
const liveTriggers = db.prepare("SELECT name, sql FROM sqlite_master WHERE type='trigger' AND tbl_name = ?")
for (const target of ['chunks', 'messages'] as const) {
const { ddl, markers } = CANONICAL_FTS_TRIGGERS[target]
const live = new Map(
(liveTriggers.all(target) as unknown as Array<{ name: string; sql: string }>).map((r) => [r.name, r.sql])
)
const current = [...markers].every(([name, required]) => {
const sql = live.get(name)
return sql !== undefined && required.every((m) => sql.includes(m))
})
if (current) continue
inOneTransaction(db, () => {
db.exec([...markers.keys()].map((n) => `DROP TRIGGER IF EXISTS ${n};`).join('\n') + ddl)
backfillFtsRowids(db, target)
})
}
}
// The FTS5 keyword index over chunk text, used by hybrid retrieval (rag-design §11).
// SELF-CONTAINED (text + chunk_id UNINDEXED), deliberately NOT an
// external-content table keyed on chunks' implicit rowid — `chunks.id` is a TEXT PK, so
// the table has only an implicit rowid, and VACUUM is documented to renumber those,
// which would silently desync an external-content index. Sync is via triggers so no
// ingest/reindex/delete code path can ever miss it (rowid-targeted since CODE-4 — see
// CHUNKS_FTS_TRIGGERS above); the one-time backfill makes an older workspace searchable
// on first open after upgrade (guarded additive migration). FTS5 availability in BOTH
// runtimes (Electron's bundled Node + system Node) is verified.
function ensureChunksFts(db: Db): void {
const exists = db
.prepare("SELECT name FROM sqlite_master WHERE name = 'chunks_fts'")
.get() as unknown as { name: string } | undefined
if (exists) return
// #737: the table, its triggers, the bulk fill and the handle backfill commit as ONE
// transaction. A bare multi-statement exec commits statement by statement, and the guard above
// never revisits a table that exists, so a failure part-way used to leave its prefix for good:
// triggers over an empty index, or every handle NULL.
inOneTransaction(db, () => {
db.exec(`
CREATE VIRTUAL TABLE chunks_fts USING fts5(text, chunk_id UNINDEXED);
${CHUNKS_FTS_TRIGGERS}
INSERT INTO chunks_fts(text, chunk_id) SELECT text, id FROM chunks;
`)
// The bulk INSERT above writes the FTS table directly (no chunks trigger fires), so a
// pre-FTS workspace's existing chunks still carry a NULL handle — stamp them now (CODE-4).
backfillFtsRowids(db, 'chunks')
})
}
// The FTS5 index over message text, used by conversation search.
// Mirrors `ensureChunksFts` exactly — self-contained (NOT external-content,
// same VACUUM rationale), trigger-synced so no chat code path can miss it (message
// content is never UPDATEd by current code; the update trigger is cheap
// defense-in-depth), and a one-time guarded backfill makes an older workspace
// searchable on first open after upgrade. Messages are persisted with think blocks
// already stripped, so reasoning text can never be indexed. FTS5 +
// snippet()/highlight() availability in BOTH runtimes is verified.
//
// The compaction `kind` guard (R8) lives on BOTH the insert AND the update trigger so a
// checkpoint summary can never enter conversation search through either path (DATA-1, full
// audit 2026-06-28). The update trigger guards its INSERT (not the whole trigger via WHEN) so
// its DELETE still runs unconditionally — a plain row that is converted to a compaction row in
// the same content UPDATE still has its old FTS entry purged.
function ensureMessagesFts(db: Db): void {
const exists = db
.prepare("SELECT name FROM sqlite_master WHERE name = 'messages_fts'")
.get() as unknown as { name: string } | undefined
if (exists) return
// As in ensureChunksFts: one transaction (#737), and the bulk INSERT bypasses the AI trigger —
// stamp the handles (CODE-4).
inOneTransaction(db, () => {
db.exec(`
CREATE VIRTUAL TABLE messages_fts USING fts5(content, message_id UNINDEXED);
${MESSAGES_FTS_TRIGGERS}
INSERT INTO messages_fts(content, message_id) SELECT content, id FROM messages WHERE kind IS NOT 'compaction';
`)
backfillFtsRowids(db, 'messages')
})
}
/**
* R8 (context-compaction-plan §8) — on a workspace whose `messages_fts_ai` predates the compaction
* guard, prune any checkpoint row already in the index (defence in depth: no shipped binary can
* index one, and `searchMessages` has no kind filter of its own — the index is the guard). The
* guarded trigger itself arrives with `ensureFtsRowidSync` in the same open: its check requires
* the `new.kind` guard on `messages_fts_ai`, so whenever this gate opens, that upgrade recreates
* all five message triggers from `MESSAGES_FTS_TRIGGERS` (#737 — before, it rested on the
* canonical set writing `ai` before `ad`, and an unguarded `ai` beside a current `ad` kept the
* guard off for good). Runs after `ensureMessagesFts` so the table + the `kind` column already
* exist.
*/
function ensureMessagesFtsKindFilter(db: Db): void {
const row = db
.prepare("SELECT sql FROM sqlite_master WHERE type='trigger' AND name='messages_fts_ai'")
.get() as unknown as { sql: string } | undefined
if (!row || row.sql.includes('new.kind')) return
db.exec(`DELETE FROM messages_fts WHERE message_id IN (SELECT id FROM messages WHERE kind = 'compaction');`)
}
/**
* Seed the built-in collections and back-fill Library membership (document-organization
* plan §9). Idempotent: built-ins are seeded once (guarded by `type`), and the backfill
* only touches documents that have NO membership yet, so re-opening never double-files.
*
* Backfill rule (plan §9 step 4): every `status='indexed'` document with NO membership and
* `origin_json IS NULL` becomes a Library member. The `status='indexed'` gate (M1) skips a
* doc still importing for a Project/Temporary destination; the `origin_json IS NULL` guard
* (D3) keeps generated translations/comparisons OUT of the default corpus — they get no
* membership at all and are reached only via explicit selection.
*/
function seedCollections(db: Db): void {
const now = new Date().toISOString()
const ensureBuiltin = (type: 'library' | 'temporary', name: string): string => {
const existing = db
.prepare('SELECT id FROM collections WHERE type = ? LIMIT 1')
.get(type) as unknown as { id: string } | undefined
if (existing) return existing.id
const id = randomUUID()
db.prepare(
`INSERT INTO collections (id, name, type, description, builtin, color, created_at, updated_at, archived_at, retention_policy_json)
VALUES (?, ?, ?, NULL, 1, NULL, ?, ?, NULL, NULL)`
).run(id, name, type, now, now)
return id
}
// Canonical English names; the UI localizes built-ins by type (plan §9 step 3).
const libraryId = ensureBuiltin('library', 'Library')
ensureBuiltin('temporary', 'Temporary')
db.prepare(
`INSERT INTO document_collections (document_id, collection_id, role, added_at)
SELECT d.id, ?, 'source', ?
FROM documents d
WHERE d.status = 'indexed'
AND d.origin_json IS NULL
AND NOT EXISTS (SELECT 1 FROM document_collections dc WHERE dc.document_id = d.id)`
).run(libraryId, now)
}
// #581 — the documents-corpus GENERATION: a counter that moves on every write that can change which documents
// a scope resolves to (`documentsInScope`: `status`, `lifecycle`, collection membership) or the title/MIME they
// carry. It replaced a `(COUNT, MAX(rowid))` signature that could not see the commonest such write: `documents`
// and `document_collections` are rowid tables, so deleting the newest row and importing another hands the new
// row the freed rowid and both figures repeat. A trigger catches every write path (the import pipeline, a
// delete and its FK cascade, filing, archive, a collection delete) without each caller having to remember.
// TEMP, so nothing is added to the workspace file: an older build opening the drive sees no new table or
// trigger, and the counter lives in memory (`temp_store = MEMORY`), off the slow drive. The cost is that only
// this connection's writes count — sound because the app holds one connection per session and every writer
// goes through it (a reopen is a new `Db`, so a cache keyed on it starts empty). Installed after
// `temp_store` (changing that PRAGMA drops every temp object) and after the `lifecycle` column exists.
//
// The `documents` triggers count only what can change the answer, so the suggestion memo survives work that
// cannot: a row that is not `indexed` before or after the write is in no scope (an import's queued →
// extracting → embedding steps and its MIME write), and the update trigger lists only the columns the scope
// query reads (a deep-index build re-stamps `updated_at` / `tree_status` all the time). That list must name
// every `documents` column `documentsInScope` or `buildScopeFilter` reads; `skills-suggest.test.ts` writes
// every column in turn and fails when a write that changes the answer leaves the counter where it was.
const CORPUS_GENERATION = `
CREATE TEMP TABLE IF NOT EXISTS corpus_generation (
id INTEGER PRIMARY KEY CHECK (id = 1),
n INTEGER NOT NULL
);
INSERT OR IGNORE INTO temp.corpus_generation (id, n) VALUES (1, 0);
-- A trigger body may not schema-qualify the table it writes; a TEMP trigger resolves the bare name temp-first.
CREATE TEMP TRIGGER IF NOT EXISTS corpus_generation_doc_insert AFTER INSERT ON main.documents
WHEN new.status = 'indexed' BEGIN
UPDATE corpus_generation SET n = n + 1;
END;
CREATE TEMP TRIGGER IF NOT EXISTS corpus_generation_doc_delete AFTER DELETE ON main.documents
WHEN old.status = 'indexed' BEGIN
UPDATE corpus_generation SET n = n + 1;
END;
CREATE TEMP TRIGGER IF NOT EXISTS corpus_generation_doc_update
AFTER UPDATE OF status, title, mime_type, lifecycle ON main.documents
WHEN (old.status = 'indexed' OR new.status = 'indexed')
AND (old.status IS NOT new.status OR old.title IS NOT new.title
OR old.mime_type IS NOT new.mime_type OR old.lifecycle IS NOT new.lifecycle)
BEGIN
UPDATE corpus_generation SET n = n + 1;
END;
CREATE TEMP TRIGGER IF NOT EXISTS corpus_generation_member_insert AFTER INSERT ON main.document_collections BEGIN
UPDATE corpus_generation SET n = n + 1;
END;
CREATE TEMP TRIGGER IF NOT EXISTS corpus_generation_member_delete AFTER DELETE ON main.document_collections BEGIN
UPDATE corpus_generation SET n = n + 1;
END;
CREATE TEMP TRIGGER IF NOT EXISTS corpus_generation_member_update
AFTER UPDATE OF document_id, collection_id ON main.document_collections BEGIN
UPDATE corpus_generation SET n = n + 1;
END;
`
/** The connection's corpus generation (#581, see `CORPUS_GENERATION`): two equal readings mean nothing written
* in between could have changed any scope's document set or the titles/MIME types it carries. */
export function corpusGeneration(db: Db): number {
return (prepareCached(db, 'SELECT n FROM temp.corpus_generation').get() as { n: number }).n
}
/**
* The schema version this build writes and understands (#247, owner decision #225). Stored in
* the database header as `PRAGMA user_version`; read FIRST on every open, before any PRAGMA
* that writes. `0` = every database written before this stamp existed (upgraded in place and
* stamped); a value ABOVE this constant was written by a newer build and is refused with
* `WorkspaceNewerError` — the migrations below are additive, and an older build cannot know
* what a newer schema means, so opening it would degrade silently. Bump it whenever the schema
* changes in a way an older build must not open. Builds ≤ 0.1.59 never read the stamp, so it
* protects only pairs where the older build is newer than this change.
*
* #985 (W-66): `probeDatabaseFile` reads the same stamp from the header, before SQLite parses the schema, so a working
* copy or `.recovery` a newer build left is kept, never judged damaged and discarded. Rule for every later release:
* schema text an older SQLite cannot parse (a newer clause in an index, a trigger, a generated column, a table option)
* ships only with a bump of this constant. An older SQLite fails every schema read of such a file with SQLITE_CORRUPT
* ("malformed database schema"), which the probe would call damage when the stamp did not say "newer".
*/
export const SCHEMA_VERSION = 1
/**
* Thrown by `openDatabase` when the file's `user_version` exceeds `SCHEMA_VERSION`. The
* handle is closed before it propagates and nothing was written. Content-free on purpose
* (like the vault errors): the IPC layer maps it to `workspace_newer` + `main.workspace.newer`.
*/
export class WorkspaceNewerError extends Error {
constructor(
readonly found: number,
readonly supported: number = SCHEMA_VERSION
) {
super(
`The workspace database was written by a newer build (schema ${found}; this build reads up to ${supported})`
)
this.name = 'WorkspaceNewerError'
}
}
/** instanceof PLUS the name — the production bundle can hold a second copy of this module. */
export function isWorkspaceNewerError(err: unknown): err is WorkspaceNewerError {
return err instanceof WorkspaceNewerError || (err instanceof Error && err.name === 'WorkspaceNewerError')
}
/** SQLite's primary result codes for "this is not a database" and "this database is corrupt". */
const SQLITE_CORRUPT = 11
const SQLITE_NOTADB = 26
/**
* Whether SQLite itself judged the file damaged (#844): `node:sqlite` errors carry SQLite's
* extended result code as `errcode`, whose low byte is the primary code. Noise fails the first
* read with NOTADB (#208); a real database with a damaged page passes that read and fails a later
* statement with CORRUPT. Anything else (a full drive, an I/O error, a constraint, a JS error in
* a backfill) is an open that could not finish, not damage.
*/
export function sqliteJudgedDamaged(err: unknown): boolean {
const code = sqlitePrimaryCode(err)
return code === SQLITE_CORRUPT || code === SQLITE_NOTADB
}
/** The primary SQLite result code of a `node:sqlite` error (the low byte of its extended `errcode`), else null. */
function sqlitePrimaryCode(err: unknown): number | null {
const code = (err as { errcode?: unknown } | null)?.errcode
return typeof code === 'number' ? code & 0xff : null
}
/**
* SQLITE_TOOBIG: a value longer than SQLite allows. Damage only inside {@link probeDatabaseFile}, whose reads (the
* schema, one row per table) can meet such a value only where a record's header claims one, which noise does (#876
* review round 3: Fable's fuzz). The open's verdict ({@link sqliteJudgedDamaged}: the unlock's #844 split, the lock's
* WAL retry) keeps it out: a backfill or a statement there can raise it on a healthy database (a value over this
* build's limit, a bug in a step), and calling that damage would condemn the vault.
*/
const SQLITE_TOOBIG = 18
/**
* What {@link probeDatabaseFile} found at a path (#876): a `database` SQLite can read the structure of; `damaged`, a
* file that starts with the SQLite header but whose structure SQLite calls CORRUPT or NOTADB, or whose rows claim a value
* longer than SQLite allows (TOOBIG), or an index root that is no b-tree page, a page size no database has, a schema
* format no SQLite writes; `not-database`, no SQLite header at all (noise, a shred survivor, an
* empty or cut-short file); `gone` (ENOENT); `unknown`, the header read itself failed (a hold, a permission error),
* which no caller may read as "lost"; `unchecked` (review round 2), the header reads but the structure could not be read
* for a reason that is NOT damage (SQLite could not open the file through its URI, an I/O error, out of memory, a table
* it cannot read; or an index-root read that failed after the header read). The probe may only ADD a refusal or a
* discard for proven damage: on `unchecked` every caller judges the file by its header, exactly as before the probe
* existed, and reports the fallback (the `code`) for the log. `newer` (#985): the header's schema stamp
* (`user_version`) is above {@link SCHEMA_VERSION}, so a newer build wrote the file, judged before SQLite reads its
* schema (which may hold text this SQLite cannot parse). No caller discards it: the salvage keeps it, the unlock
* refuses it as `WorkspaceNewerError`, and the lock and the rekey stage read it as a database.
*/
export type DatabaseFileVerdict = 'database' | 'damaged' | 'not-database' | 'gone' | 'unknown' | 'unchecked' | 'newer'
/** {@link probeDatabaseFile}'s answer: the verdict, and for `unchecked` what stopped the structural read (SQLite's result
* code and its fixed description, or a Node error code; content-free); for `newer` the schema stamp it found. */
export type DatabaseFileProbe =
| { verdict: Exclude<DatabaseFileVerdict, 'newer'>; code?: string }
| { verdict: 'newer'; found: number }
/** A failure's content-free code for the log: SQLite's result code and fixed description, else the Node error code. */
function failureCode(err: unknown): string {
const e = err as { errcode?: unknown; errstr?: unknown; code?: unknown; name?: unknown } | null
if (typeof e?.errcode === 'number') return `sqlite ${e.errcode}${typeof e.errstr === 'string' ? `: ${e.errstr}` : ''}`
if (typeof e?.code === 'string') return e.code
return typeof e?.name === 'string' ? e.name : typeof err
}
/** A real SQLite database file starts with this 16-byte header. */
const SQLITE_HEADER = Buffer.from('SQLite format 3\u0000')
/** The database header's size: page 1's b-tree header starts after it. */
const DATABASE_HEADER_BYTES = 100
/**
* SQLite's URI for the file at `path`, opened with `immutable=1` (#876). SQLite then takes no lock and opens no
* `-wal`/`-shm`: it reads the main file alone, which is exactly what the lock encrypts. A plain read-only open of a
* WAL-mode file leaves an empty `-wal` and a 32 KiB `-shm` behind, and the init() salvage reads live sidecars as a
* mid-session crash and shreds the file they belong to (A1 §2.5, trap 1). Built by hand, not with `pathToFileURL`:
* SQLite accepts only an empty (or `localhost`) authority, and `pathToFileURL` puts a Windows UNC path's host there
* (`\\server\share\…` → `file://server/share/…`, and the URL standard drops a `localhost` host altogether), so a drive
* started from a network share would probe `unknown` and refuse every lock. SQLite's own spelling of a UNC path is an
* empty authority and a path that starts with `//`. On Windows the path is also written in the `\\?\` long form
* (`\\?\UNC\server\share\…` for a UNC path): without it SQLite cannot open a path of 260 characters or more, where
* `node:fs` can (a `.recovery` beside a 251-character working file is 260 characters, and a probe answering
* `unknown` there would refuse every unlock; #876 review round 1). So `C:\x` becomes `file:////%3F/C:/x`. Every byte
* but unreserved ASCII, `/` and `:` is percent-encoded (`?`, `#` and `%` must be); SQLite decodes them.
*/
function immutableUri(path: string): string {
let p = resolve(path)
if (process.platform === 'win32') {
if (!p.startsWith('\\\\?\\')) p = p.startsWith('\\\\') ? `\\\\?\\UNC\\${p.slice(2)}` : `\\\\?\\${p}`
p = p.replace(/\\/g, '/') // //?/C:/x, //?/UNC/server/share/x
}
let encoded = ''
for (const byte of Buffer.from(p, 'utf8')) {
const c = String.fromCharCode(byte)
encoded += /[A-Za-z0-9\-._~/:]/.test(c) ? c : `%${byte.toString(16).toUpperCase().padStart(2, '0')}`
}
return `file://${encoded}?immutable=1`
}
/**
* Whether the 12 bytes at the start of an index b-tree's root page are a plausible b-tree page header (#876): the
* page type (interior 0x02, leaf 0x0A), the cell pointer array inside the page and before the cell content area, a
* first freeblock inside that area, at most 60 fragmented bytes, and an interior page's right child inside the file.
* Noise passes all of it with odds far below one in a million per page.
*/
function indexRootLooksValid(header: Buffer, usableSize: number, pageCount: number): boolean {
const type = header[0]
if (type !== 0x02 && type !== 0x0a) return false
const cellPointersEnd = (type === 0x02 ? 12 : 8) + 2 * header.readUInt16BE(3)
const contentStart = header.readUInt16BE(5) || 65_536
const firstFreeblock = header.readUInt16BE(1)
if (header[7] > 60) return false
if (cellPointersEnd > contentStart || contentStart > usableSize) return false
if (firstFreeblock !== 0 && (firstFreeblock < contentStart || firstFreeblock > usableSize - 4)) return false
if (type === 0x02) {
const rightChild = header.readUInt32BE(8)
if (rightChild < 1 || rightChild > pageCount) return false
}
return true
}
/** A WAL file starts with one of these two magic numbers (big-endian; the low bit names the checksum byte order). */
const WAL_MAGIC = [0x377f0682, 0x377f0683]
/** The WAL header's size: a WAL this short or shorter holds no frame. */
const WAL_HEADER_BYTES = 32
/**
* Does the `-wal` beside the database at `dbPath` still hold commits (#876 review round 1)? After the last connection
* closes, SQLite has checkpointed the WAL into the main file and deleted it (a TRUNCATE checkpoint leaves it empty). A
* `-wal` with a valid header and frames that survives that close means the checkpoint did not finish (a full drive:
* commits still land in the WAL's allocated space, the copy back fails where the main file has to grow), so the main
* file alone is stale or torn while the session itself is intact. True only for a valid WAL header with frames after it:
* a `-wal` that is noise (#208's sweep shreds the sidecars too) holds nothing to replay. The size is read first (a stat
* works through an antivirus hold), so a `-wal` of the header or less never counts (an empty one a TRUNCATE checkpoint
* left, whose delete failed); one with frames that cannot be opened or read counts as holding commits (refusing is the
* safe answer there; the lock retries once through SQLite, see {@link checkpointLeftoverWal}).
*/
export function walAwaitsCheckpoint(dbPath: string): boolean {
const walPath = `${dbPath}-wal`
try {
if (statSync(walPath).size <= WAL_HEADER_BYTES) return false
} catch (err) {
return (err as NodeJS.ErrnoException | null)?.code !== 'ENOENT'
}
let fd: number
try {
fd = openSync(walPath, 'r')
} catch {
return true
}
try {
const head = Buffer.alloc(4)
if (readSync(fd, head, 0, head.length, 0) < head.length) return false
return WAL_MAGIC.includes(head.readUInt32BE(0))
} catch {
return true
} finally {
closeSync(fd)
}
}
/** What the lock's one retry of an unfinished checkpoint found ({@link checkpointLeftoverWal}). */
export type WalCheckpointRetry =
| { outcome: 'checkpointed' | 'busy'; log: number; checkpointed: number }
| { outcome: 'damaged' | 'failed'; code: string }
/**
* The lock's one retry when {@link walAwaitsCheckpoint} says the `-wal` still holds commits (#876 review round 2): open
* the database at `dbPath` with a plain connection, so SQLite's own WAL recovery decides what the WAL really holds,
* checkpoint it (TRUNCATE) and close (as the last connection, SQLite deletes the WAL). A WAL SQLite ignores (a foreign
* salt, a bad header checksum, noise after a valid header) or has already copied in (its delete failed) is gone
* afterwards, and the lock goes on. One that still holds commits (a full drive, a second connection reading) stays, and
* the caller re-checks. `damaged`: SQLite calls the database CORRUPT or NOTADB, so the WAL cannot be replayed into it
* and does not protect it. `busy`: a reader kept the checkpoint from finishing. Writes only what a checkpoint writes; no
* migrations, no schema change.
*/
export function checkpointLeftoverWal(dbPath: string): WalCheckpointRetry {
let db: Db | null = null
try {
db = new DatabaseSync(dbPath)
// #911: the start also runs this before any password, on a file anyone with write access could plant: as in the
// probe, no function the file's schema names runs with the trust SQLite gives a schema by default.
db.exec('PRAGMA trusted_schema = OFF;')
const row = db.prepare('PRAGMA wal_checkpoint(TRUNCATE)').get() as { busy: number; log: number; checkpointed: number }
return { outcome: row.busy ? 'busy' : 'checkpointed', log: row.log, checkpointed: row.checkpointed }
} catch (err) {
return { outcome: sqliteJudgedDamaged(err) ? 'damaged' : 'failed', code: failureCode(err) }
} finally {
try {
db?.close()
} catch {
/* the checkpoint's answer is the story; a close that fails leaves the WAL, which the re-check then sees */
}
}
}
/**
* Is the file at `path` a database SQLite can read (#876)? Every place that encrypts a working file over `.enc`, or
* decides one is lost, asks this (the lock's guard and its #855 verdict, the init() salvage, the `.recovery`
* roll-forward, the v1 rekey stage). A check of the 16-byte header is not enough: a file overwritten in place while
* the session's last commits sat in the WAL gets page 1 (the header, the schema root) written back by the lock's own
* checkpoint, and is noise past it. In three steps, cheapest first:
*
* 1. The header, read through `node:fs` FIRST: a 0-byte file is a valid empty database to SQLite itself, and a hold
* or a missing file must answer `unknown`/`gone` before SQLite is involved (the recovery-guard suites fail exactly
* this read).
* 2. An `immutable=1` read-only open (see {@link immutableUri}): the whole schema, then the first row of every table
* with a root page (rowid, WITHOUT ROWID and FTS5 shadow tables alike; `NOT INDEXED` so the table's own b-tree is
* read, not an index that covers it; virtual tables have no root page and are skipped), and the last row of every
* rowid table (`ORDER BY rowid DESC`, a reverse scan: the rightmost path, whose pages the latest writes put near
* the end of the file; a WITHOUT ROWID table has no rowid to order by and is read from its first row only; on a
* table with a column of its own named `rowid` the order is that column's, so SQLite sorts the table for it: right,
* only slow, and no app table has such a column).
* 3. The root page header of every index, read through `node:fs` ({@link indexRootLooksValid}). Not through SQL: an
* index cannot be read by name (`INDEXED BY` throws "no query solution" on a partial index, and the app has one,
* `idx_documents_pending_dest`, so such a probe would refuse every lock; A1 §2.5, trap 2).
*
* Step 1 also reads the schema stamp (#985): a `user_version` above {@link SCHEMA_VERSION} is `newer`, answered before
* SQLite reads anything, because a newer build's schema can hold text this SQLite cannot parse, which fails step 2
* with CORRUPT although the file is intact.
*
* SQLite's CORRUPT, NOTADB or TOOBIG is `damaged` (as are a page size or a schema format number no SQLite writes, in
* step 1); any other SQLite failure, and an index-root read that fails after the header read, is `unchecked` (with the
* code): the probe adds a refusal or a discard only for proven damage, so the callers judge an `unchecked` file by its
* header, as before. A header read that fails is `unknown`. The schema is read with `trusted_schema` OFF. What it
* reads (the schema, each index root, each table's leftmost and, for rowid tables, rightmost path) is a small part of a
* large file. It catches an overwrite that starts at the beginning of the file (#208's shred: the review's fuzz missed
* none of 1,820) or runs to its end (1 of 200 missed), but mostly misses noise confined to a range or a page in between (57–91 % missed in
* that fuzz), as the header check did. Milliseconds on a warm cache (the lock logs it as `vault_lock_done.probeMs`); a few hundred
* random reads on a cold one. Writes nothing and leaves no sidecar. It reads the main file ALONE: when commits still
* sit in the `-wal` (a checkpoint that did not finish) its verdict is about a stale or torn file, so a caller about to
* encrypt or discard asks {@link walAwaitsCheckpoint} first.
*/
export function probeDatabaseFile(path: string): DatabaseFileProbe {
const answer = (verdict: Exclude<DatabaseFileVerdict, 'newer'>): DatabaseFileProbe => ({ verdict })
let pageSize: number
let usableSize: number
try {
const fd = openSync(path, 'r')
try {
const header = Buffer.alloc(DATABASE_HEADER_BYTES)
const got = readSync(fd, header, 0, header.length, 0)
if (got < header.length || !header.subarray(0, SQLITE_HEADER.length).equals(SQLITE_HEADER)) return answer('not-database')
const stored = header.readUInt16BE(16)
pageSize = stored === 1 ? 65_536 : stored
if (pageSize < 512 || pageSize > 65_536 || (pageSize & (pageSize - 1)) !== 0) return answer('damaged')
// The schema format number (offset 44, a big-endian u32 of which SQLite reads only the low byte): no SQLite
// writes one above 4, and SQLite refuses it with a plain SQLITE_ERROR ("unsupported file format"), which step 2
// would report as `unchecked` (#876 review round 3).
if (header[47] > 4) return answer('damaged')
// #985 (W-66): the schema stamp (`PRAGMA user_version`: offset 60, a big-endian signed 32-bit integer, as SQLite
// stores it). Above this build's, a newer build wrote the file: kept by every caller, and judged here, before
// step 2, which reads a schema this SQLite may not parse (SQLITE_CORRUPT, "malformed database schema").
const userVersion = header.readInt32BE(60)
if (userVersion > SCHEMA_VERSION) return { verdict: 'newer', found: userVersion }
usableSize = pageSize - header[20]
} finally {
closeSync(fd)
}
} catch (err) {
return answer((err as NodeJS.ErrnoException | null)?.code === 'ENOENT' ? 'gone' : 'unknown')
}
const indexRoots: number[] = []
let db: Db | null = null
try {
db = new DatabaseSync(immutableUri(path), { readOnly: true })
// The schema read here is whatever the file holds, possibly before any unlock (the init() salvage): no function a
// view, trigger or generated column in it names runs with the trust SQLite gives a schema by default (ON in
// node:sqlite's build). The app's own schema needs no such trust (#876 review round 3).
db.exec('PRAGMA trusted_schema = OFF;')
const objects = db.prepare('SELECT type, name, rootpage FROM sqlite_schema').all() as Array<{
type: string
name: string
rootpage: number | null
}>
const withoutRowid = db.prepare("SELECT name FROM pragma_table_list WHERE schema = 'main' AND wr = 1").all() as Array<{
name: string
}>
const noRowid = new Set(withoutRowid.map((t) => t.name))
for (const o of objects) {
if (typeof o.rootpage !== 'number' || o.rootpage <= 0) continue // views, triggers, virtual tables
if (o.type === 'table') {
const table = `"${o.name.replace(/"/g, '""')}"`
db.prepare(`SELECT * FROM ${table} NOT INDEXED LIMIT 1`).all()
if (!noRowid.has(o.name)) db.prepare(`SELECT * FROM ${table} NOT INDEXED ORDER BY rowid DESC LIMIT 1`).all()
} else if (o.type === 'index') indexRoots.push(o.rootpage)
}
} catch (err) {
return sqliteJudgedDamaged(err) || sqlitePrimaryCode(err) === SQLITE_TOOBIG
? answer('damaged')
: { verdict: 'unchecked', code: failureCode(err) }
} finally {
try {
db?.close()
} catch {
/* the read is the story; a failed close of a read-only, lock-free handle leaves nothing behind */
}
}
try {
const fd = openSync(path, 'r')
try {
const pageCount = Math.floor(fstatSync(fd).size / pageSize)
const header = Buffer.alloc(12)
for (const root of indexRoots) {
if (root > pageCount) return answer('damaged')
const got = readSync(fd, header, 0, header.length, (root - 1) * pageSize)
if (got < header.length || !indexRootLooksValid(header, usableSize, pageCount)) return answer('damaged')
}
} finally {
closeSync(fd)
}
} catch (err) {
if ((err as NodeJS.ErrnoException | null)?.code === 'ENOENT') return answer('gone')
return { verdict: 'unchecked', code: failureCode(err) }
}
return answer('database')
}
/** Open (or create) the database at `path` and run migrations. */
export function openDatabase(path: string): Db {
const db = new DatabaseSync(path)
// #208: everything below the constructor can throw (the very first PRAGMA does, with
// "file is not a database", when the file's bytes are not SQLite — the destroyed-vault
// unlock path). Without the close, the native handle LEAKED open: on Windows that open
// handle then blocks the caller's cleanup unlink (EPERM, no FILE_SHARE_DELETE), so the
// vault code could not even shred the not-a-database file it had just decrypted.
try {
applyPragmasAndMigrations(db)
} catch (err) {
try {
db.close()
} catch {
/* the open itself may be broken past closing — the throw below is the story */
}
throw err
}
return db
}
/** The PRAGMA + additive-migration body of {@link openDatabase}. Throws on a file whose
* bytes are not a SQLite database; the caller owns closing the handle on failure. */
function applyPragmasAndMigrations(db: Db): void {
// #247: the stamp is read before anything writes, so a refused file is byte-identical and
// no sidecar is left behind (a WAL-mode file opens `-wal`/`-shm` transiently for the read;
// the close on the refusal path removes them). On a non-SQLite file this read is what
// throws "file is not a database" — the caller's damaged-vault path is unchanged.
const found = (db.prepare('PRAGMA user_version').get() as { user_version: number }).user_version
if (found > SCHEMA_VERSION) throw new WorkspaceNewerError(found)
db.exec('PRAGMA journal_mode = WAL;')
db.exec('PRAGMA foreign_keys = ON;')
// DB-2 — portable-drive performance PRAGMAs (perf audit 2026-06-18). HilbertRaum runs from a
// high-latency USB drive where every fsync is 5–20 ms, so the durability/throughput trade-offs
// that suit a fixed SSD are wrong here.
// synchronous=NORMAL — WAL-safe: still durable across app crashes, only risks the last txn on
// an OS/power loss, in exchange for far fewer fsyncs (compounds DB-1).
// busy_timeout=5000 — the concurrent import loop vs chat/tree-build waits briefly instead of
// throwing SQLITE_BUSY.
// mmap_size=256 MB — the linear vector scan (RAG-1) reads BLOBs via mapped pages, not syscalls.
// cache_size=-16 MB — negative = KiB of page cache (~16 MB), not page count.
// temp_store=MEMORY — keep transient sorts/temp B-trees off the slow drive.
db.exec('PRAGMA synchronous = NORMAL;')
db.exec('PRAGMA busy_timeout = 5000;')
db.exec('PRAGMA mmap_size = 268435456;')
db.exec('PRAGMA cache_size = -16000;')
db.exec('PRAGMA temp_store = MEMORY;')
db.exec(SCHEMA)
ensureColumn(db, 'conversations', 'scope_json', 'scope_json TEXT')
ensureColumn(db, 'documents', 'summary_json', 'summary_json TEXT')
ensureColumn(db, 'documents', 'origin_json', 'origin_json TEXT')
// Persisted per-page OCR recognition (content — lives only in this DB).
ensureColumn(db, 'documents', 'ocr_json', 'ocr_json TEXT')
// PERF-3 (full-audit-2026-06-29 follow-up, Phase 4): cheap metadata-only OCR sidecar
// (`{ pageCount, textPageCount, lowConfidencePageCount?, languages, engineId, createdAt }` — a
// serialized DocumentOcrInfo, counts/ids only, NEVER page text). `listDocuments` reads the OCR
// badge from this column instead of JSON.parse-ing the multi-MB `ocr_json` blob per row. Additive
// + nullable (NULL = not yet backfilled OR no OCR); populated at OCR-write time, for a photo at
// import (#574, the one sidecar with no `ocr_json` behind it), and by the backfill below.
ensureColumn(db, 'documents', 'ocr_meta_json', 'ocr_meta_json TEXT')
backfillOcrMeta(db)
// #575: a text PDF's scanned pages (`{ pages, pageCount }` — page numbers and a count, never
// text), written at import/re-index; NULL = none, not a PDF, or not parsed since #575.
ensureColumn(db, 'documents', 'scanned_pages_json', 'scanned_pages_json TEXT')
// Document-organization columns (plan §8.2/§8.3). All nullable — the ensureColumn DDL
// grammar allows no DEFAULT/NOT NULL, so NULL is the sentinel, coalesced in code
// (`lifecycle` NULL ⇒ 'permanent', the parseScope precedent).
ensureColumn(db, 'documents', 'lifecycle', 'lifecycle TEXT')
// Issue #188 — the stored copy's leaf name (`<id><ext>[.enc]`), RELATIVE to the workspace's
// `documents/` dir, mirroring `image_sessions.stored_name` and `skills.path`. `stored_path`
// stays (it is what a legacy row carries, and the tooltip/provenance reads it) but is no
// longer authoritative: it is absolute, so it goes stale the moment the drive comes back
// under a different mount point. Nullable — NULL means "not yet healed", and the resolver
// derives the leaf from `stored_path` and writes it back on the next read (D3, lazy).
ensureColumn(db, 'documents', 'stored_name', 'stored_name TEXT')
ensureColumn(db, 'documents', 'source_relative_path', 'source_relative_path TEXT')
ensureColumn(db, 'documents', 'source_folder_label', 'source_folder_label TEXT')
ensureColumn(db, 'documents', 'pending_destination_json', 'pending_destination_json TEXT')
ensureColumn(db, 'documents', 'expires_at', 'expires_at TEXT')
ensureColumn(db, 'conversations', 'collection_id', 'collection_id TEXT')
ensureColumn(db, 'conversations', 'scope_v2_json', 'scope_v2_json TEXT')
// Whole-document analysis (plan §3.2). All nullable (the ensureColumn DDL grammar forbids
// DEFAULT/NOT NULL, so NULL is the sentinel, coalesced in code).
// tree_status — NULL | 'pending' | 'building' | 'ready' | 'stale' | 'failed'
// tree_meta_json — { rootId, levels, leafChunkCount, builtAt, modelId, embeddingModelId }
// fully_chunked — set by processDocument on every successful index (C4); NULL = legacy
// (maybe truncated) ⇒ must re-index before deep-index / 100% coverage.
ensureColumn(db, 'documents', 'tree_status', 'tree_status TEXT')
ensureColumn(db, 'documents', 'tree_meta_json', 'tree_meta_json TEXT')
ensureColumn(db, 'documents', 'fully_chunked', 'fully_chunked TEXT')
// extract_status — NULL | 'pending' | 'extracting' | 'ready' | 'stale' | 'failed' (Phase 3,
// the per-chunk structured-extract pass; mirrors tree_status, NULL-sentinel).
ensureColumn(db, 'documents', 'extract_status', 'extract_status TEXT')
// Skills (skills plan §8.2). Both nullable — NULL = no skill (the scope_v2_json NULL-sentinel
// convention). No FK into `skills` (audit C3): refs are cleared by an app-level sweep on delete
// (S4), so an older app can ignore these columns and skill deletion is never FK-blocked.
// conversations.active_skill_id — the STICKY DEFAULT skill for new turns (DS18).
// messages.skill_id — the skill that shaped THIS turn; powers the per-message glyph (DS16/DS18).
ensureColumn(db, 'conversations', 'active_skill_id', 'active_skill_id TEXT')
ensureColumn(db, 'messages', 'skill_id', 'skill_id TEXT')
// #846 — WHY a skill row is disabled: 'user' (the Settings toggle), 'min_app_version' (the app was too
// old for the skill), 'duplicate' (DS12: a same-id sibling is the active one) or 'unconfirmed' (a DS19
// drop-in), NULL when none is recorded (an enabled row, or one an older build wrote). The reconcile acts on
// 'min_app_version' alone: it switches an app skill back on once this build satisfies it. Additive +
// nullable, no `SCHEMA_VERSION` bump: builds up to v0.1.65 read `skills` with `SELECT *` and write it with
// explicit column lists, so they ignore the column (and may leave it stale; it means nothing while enabled).
ensureColumn(db, 'skills', 'disabled_reason', 'disabled_reason TEXT')
// S13c — auto-fire provenance (skills-s13-plan.md §5/D3). Additive + nullable (NULL/0 = the skill
// was an explicit pick or there was none; 1 = the app AUTO-FIRED it). Stamped on the assistant row
// only when the auto-fire path placed the skill, so the per-turn "answer without it" undo shows ONLY
// on an auto-fired turn. Privacy-safe: a boolean, never content. An older app simply ignores it.
ensureColumn(db, 'messages', 'auto_fired', 'auto_fired INTEGER')
// Full-doc-skills plan Phase 1 — per-message coverage breadth (D48). Additive + nullable: NULL =
// legacy/pre-migration row OR a turn that recorded no coverage; the renderer coalesces NULL to the
// relevance label, so an older app simply ignores the column and the badge is byte-identical. Holds
// a JSON-serialized `CoverageInfo` (mode + sections covered/total); CONTENT-free (only counts/mode).
ensureColumn(db, 'messages', 'coverage_json', 'coverage_json TEXT')
// Context compaction (context-compaction-plan §4.4, R13). Additive + nullable: `kind` NULL = a
// plain 'message' (the NULL-sentinel convention, coalesced in code), 'compaction' marks a summary
// checkpoint row; `covers_through_rowid` is the max messages.rowid that checkpoint subsumes (NULL on
// plain rows). An older app ignores both columns and reads every row as a message — no behaviour change.
ensureColumn(db, 'messages', 'kind', 'kind TEXT')
ensureColumn(db, 'messages', 'covers_through_rowid', 'covers_through_rowid INTEGER')
// Honest-signal flag (D:\ testing report 2026-07-01): 1 when an assistant reply was CUT OFF at the
// token/context ceiling (llama-server `finish_reason: 'length'`), NULL otherwise (complete reply,
// user turn, or user Stop). Additive + nullable — an older app ignores it and reads every reply as
// complete, byte-identical to before. CONTENT-free (a single boolean).
ensureColumn(db, 'messages', 'truncated', 'truncated INTEGER')
// #498 — WHICH ceiling cut the reply short: 'context' (the model ran out of context room) or
// 'cap' (the app's own fixed per-reply token cap), NULL on every complete reply and on every
// pre-#498 row. Additive + nullable; a truncated legacy row with NULL reads back as 'context',
// the flag's historical meaning, so the badge's advice is unchanged for old history. CODE-only
// (a two-value enum), never content.
ensureColumn(db, 'messages', 'truncated_cause', 'truncated_cause TEXT')
// #600 — what ended a turn early: 'model' (the user stopped or switched the chat model mid-answer),
// 'user' (the Stop button) or 'lock' (lock / quit) — both written since #612 — NULL on every complete
// turn and every pre-#600 row. On an assistant row the partial was cut; on a user row the question
// got no answer. Its OWN column, not a `truncated_cause` value: an older app reads an unknown cause
// as "raise the context size", while it ignores this column and shows the text as complete.
// Additive + nullable, no `SCHEMA_VERSION` bump. CODE-only (a three-value enum), never content.
ensureColumn(db, 'messages', 'ended_early', 'ended_early TEXT')
// Issue #80 (wave R80) — the per-answer actionable skill OFFER: JSON-serialized `SkillOffer`
// (installId + title + provenance 'deterministic' | 'classifier'), or NULL (no offer — every
// ordinary answer and every pre-migration row). Additive + nullable, STRUCTURAL only (never the
// question or document text, §22-M1); an older app ignores the column and renders no offer.
ensureColumn(db, 'messages', 'skill_offer_json', 'skill_offer_json TEXT')
// Knowledge packs (#301 P4, findings M6/M7; owner ruling plan §7) — the per-ask PACK OUTCOMES of
// an assistant turn: a JSON array of `KnowledgePackOutcome` (packId + title + status + reason
// code + found/admitted counts), or NULL (a pre-migration row, or an ask whose scope selected no
// pack). Additive + nullable, so no `SCHEMA_VERSION` bump and an older app simply ignores the
// column and renders no notice. CODE-only diagnostics — never a path, a filename or stderr.
ensureColumn(db, 'messages', 'pack_outcomes_json', 'pack_outcomes_json TEXT')
// EP-1 Phase 4 (spec §15.5/§28.6): the acknowledged-drift record — JSON
// { acknowledgedAt, fingerprint } written by acknowledgeEvidenceReviewFreshness; NULL =
// never acknowledged. Additive + nullable so P0–P3 workspaces open unchanged; the ack is
// lifecycle METADATA and deliberately not part of updated_at/status/completed_at (§18.4).
ensureColumn(db, 'evidence_reviews', 'freshness_ack_json', 'freshness_ack_json TEXT')
// Bank-transaction derived annotations (architecture.md "Skills — design record" §10, S11c). All nullable —
// a row has no category/reconciled/confidence until a downstream tool computes one. CONTENT-CLASS
// (a category id / reconcile verdict is derived from user figures): never logged/audited/exported.
// bank_transactions.category_id — the assigned bank_categories.id (categorize_transactions).
// bank_transactions.reconciled — 0/1 balance-reconcile verdict (validate_statement_balances).
// bank_transactions.confidence — extraction/categorization confidence, 0..1 (future use).
ensureColumn(db, 'bank_transactions', 'category_id', 'category_id TEXT')
ensureColumn(db, 'bank_transactions', 'reconciled', 'reconciled INTEGER')
ensureColumn(db, 'bank_transactions', 'confidence', 'confidence REAL')
// Statement-level opening/closing balances (PDF geometry-extraction plan §3.5, D56). Additive +
// nullable: the completeness gate's only true proof is opening + Σamounts == closing, so these are
// captured + stored to gate any presented total. CONTENT-CLASS (printed figures): never
// logged/audited/exported. NULL = a statement that printed no opening/closing balance (gate downgrades).
ensureColumn(db, 'bank_statements', 'opening_balance', 'opening_balance REAL')
ensureColumn(db, 'bank_statements', 'closing_balance', 'closing_balance REAL')
// Whether the categorizer doctask consulted the LLM for this statement (Phase 33). Additive +
// nullable: NULL/0 = deterministic rule pass (or not categorized), 1 = the model was involved, so the
// breakdown is labelled "model-assisted". The authoritative signal — replaces the lossy "any category
// outside the rule set" heuristic, which false-negatives when the model only emits in-rule-set labels
// (Income/Transfer/Fees/Cash). CONTENT-CLASS adjacent (a derived flag): never logged/audited/exported.
ensureColumn(db, 'bank_statements', 'categorized_by_model', 'categorized_by_model INTEGER')
// The deterministic extractor version that produced this statement (A9, Phase 31–33 follow-up).
// Additive + nullable: NULL = extracted before versioning (or by an older parser) → STALE, so the
// analysis read-back + categorize doctask RE-EXTRACT (replacing the stale rows) instead of serving
// figures a since-fixed parser bug mis-signed / lost a payee on. Stamped with `BANK_EXTRACTOR_VERSION`
// on every extraction; bumped whenever the line parser OR the geometry reconstruction changes output.
// CONTENT-CLASS adjacent (a provenance int): never logged/audited/exported.
ensureColumn(db, 'bank_statements', 'extractor_version', 'extractor_version INTEGER')
// Whether the statement's date ORDER rests on evidence or defaulted to day-first on ambiguous dates (R5,
// audit §5.7). Additive + nullable: NULL/'evidence' = the order is trustworthy or moot (no caveat);
// 'default' = day-first was applied to genuinely order-ambiguous dates with nothing in the document to
// justify it, so the deterministic answer appends ONE honest date caveat. A provenance flag (never a
// figure); CONTENT-CLASS adjacent — never logged/audited/exported.
ensureColumn(db, 'bank_statements', 'date_order_inferred', 'date_order_inferred TEXT')
// How many money-bearing lines the extractor REJECTED (could not turn into a transaction row) — U1,
// audit §2.3. Additive + nullable: NULL = extracted before this column (pre-U1) → the answer omits the
// "N lines could not be parsed" gate (the honesty signal is simply absent, not falsely zero); 0 = every
// money-shaped line parsed (the "whole statement" claim stands); > 0 = the deterministic answer replaces
// the "across the whole statement" phrasing with an honest "M lines with figures could not be parsed".
// Stamped on every extraction; a provenance COUNT (never a figure) — CONTENT-CLASS adjacent, never
// logged/audited/exported.
ensureColumn(db, 'bank_statements', 'dropped_row_count', 'dropped_row_count INTEGER')
// The deterministic INVOICE extractor version (F5 — the same reuse/replace/staleness machinery as the
// bank `extractor_version` above, mirrored for the second Tier-2 content class). Additive + nullable:
// NULL = extracted before versioning → STALE, so the invoice analysis read-back RE-EXTRACTS (replacing
// the rows) instead of serving figures a since-fixed parser bug mis-read. Stamped with
// `INVOICE_EXTRACTOR_VERSION` on every extraction; bumped whenever the invoice parser changes output.
// CONTENT-CLASS adjacent (a provenance int): never logged/audited/exported.
ensureColumn(db, 'invoices', 'extractor_version', 'extractor_version INTEGER')
// The invoice date-order provenance flag (R5, audit §5.7 — mirror of `bank_statements.date_order_inferred`
// above). Additive + nullable; drives the same one-line honest date caveat on the invoice answer.
ensureColumn(db, 'invoices', 'date_order_inferred', 'date_order_inferred TEXT')
// How many money-bearing lines the invoice extractor REJECTED (U1, audit §2.3 — mirror of
// `bank_statements.dropped_row_count`). Additive + nullable: NULL = pre-U1 (gate omitted); 0 = every
// money-shaped line parsed ("whole invoice" stands); > 0 = the answer swaps "the whole invoice" for an
// honest "M lines with figures could not be parsed". A provenance COUNT — never logged/audited/exported.
ensureColumn(db, 'invoices', 'dropped_row_count', 'dropped_row_count INTEGER')
// The bill-to party (invoice-hardening-2026-07-04 P3) — read from a labeled line only. Additive +
// nullable: NULL = not stated / extracted before this column (the version bump re-extracts).
// CONTENT (a name): lives only in the content-class invoices table, never logged/audited/exported.
ensureColumn(db, 'invoices', 'recipient', 'recipient TEXT')
// The glyph-soup text-quality verdict (invoice-hardening-2026-07-04 P3): NULL = the text layer looked
// normal; 'suspect' = the extractor read glyph-mangled text (the answer layer retries once via the
// geometry reader); 'suspect-confirmed' = the retry ALSO read soup (final — the handler stops
// retrying and refuses confident figures). A provenance flag — never logged/audited/exported.
ensureColumn(db, 'invoices', 'text_quality', 'text_quality TEXT')
// WHY a knowledge pack is unavailable (#301 P3b, finding M5). Additive + nullable, so
// SCHEMA_VERSION stays put (the P0 posture for additive migrations): NULL = available, or a
// workspace written before this column existed (the next reconcile fills it in);
// 'missing' = no candidate file at either location; 'identity_mismatch' = a file IS there but
// its 80-byte header carries a different archive UUID — a materially different state, because
// old citations still point at the registered archive and the viewer must say so. A reason
// CODE, never a path or a title: it rides `KnowledgePack.unavailableReason` to the panel badge.
ensureColumn(db, 'knowledge_packs', 'unavailable_reason', 'unavailable_reason TEXT')
// Knowledge-pack SEARCHABILITY (#301 P4, finding M7, plan §9.21 (d)1). Three additive,
// nullable columns — SCHEMA_VERSION stays put, and a workspace written before them reads
// every pack as "unknown" until the next reconciliation probes it.
// searchable — 'yes' | 'no', CONFIRMED only by a validated /suggest probe; NULL =
// unknown, which is what a 404, a timeout, a malformed body or a response
// observed across a server change leaves behind. An unknown pack is
// searched like a 'yes'; a confirmed 'no' is skipped by the ask (outcome
// `not-searchable`) but stays readable in the article viewer.
// searchable_key — the fingerprint that verdict was taken under (archive size/mtime plus
// the kiwix-serve binary's size/mtime). The reconcile resets `searchable`
// to NULL whenever the key moves, so a replaced file or a swapped tools
// bundle is re-probed instead of trusting a stale "no".
// ftindex_hint — the archive's own `_ftindex` tag ('yes' | 'no'; NULL = no tag), a HINT
// recorded at registration/discovery that never sets `searchable`.
ensureColumn(db, 'knowledge_packs', 'searchable', 'searchable TEXT')
ensureColumn(db, 'knowledge_packs', 'searchable_key', 'searchable_key TEXT')
ensureColumn(db, 'knowledge_packs', 'ftindex_hint', 'ftindex_hint TEXT')
// Additive performance indexes (perf audit 2026-06-18, Wave P1 — DB-4/DB-6/DB-7). CREATE INDEX
// IF NOT EXISTS is the same additive-migration idiom as the inline SCHEMA indexes; these live
// here (after ensureColumn) because idx_bank_transactions_category indexes a migrated column.
db.exec(
// DB-4/RAG-4: every retrieval + stale-check filters embeddings WHERE embedding_model_id = ?.
'CREATE INDEX IF NOT EXISTS idx_embeddings_model ON embeddings(embedding_model_id);'
)
db.exec(
// DB-6: unscoped "list every date/amount" filters on record_type (and record_type,
// normalized_value) with no leading document_id — the doc-leading idx_extract_doc_type can't
// serve it. The doc-leading index still serves the scoped (per-document) queries.
'CREATE INDEX IF NOT EXISTS idx_extract_type_nv ON extraction_records(record_type, normalized_value);'
)
db.exec(
// DB-7: documents.status is filtered on every list + the re-index honesty check.
'CREATE INDEX IF NOT EXISTS idx_documents_status ON documents(status);'
)
db.exec(
// #571: `resolveScope` (every documents-mode ask) and `listAttachments` read the unfiled
// conversation attachments — the rows whose `pending_destination_json` is still set (importing,
// or failed). Partial, so the read is proportional to those few rows, not the library (the
// CODE-21 intent); here, not in SCHEMA, because the column is migrated in late.
'CREATE INDEX IF NOT EXISTS idx_documents_pending_dest ON documents(id) WHERE pending_destination_json IS NOT NULL;'
)
db.exec(
// DB-7: bank_transactions.category_id (a migrated column) — joined as transaction volume grows.
'CREATE INDEX IF NOT EXISTS idx_bank_transactions_category ON bank_transactions(category_id);'
)
db.exec(
// PERF-3 (full audit 2026-06-28): getLatestCheckpoint runs on EVERY chat + grounded turn,
// filtering `conversation_id AND kind='compaction' ORDER BY rowid DESC LIMIT 1`. The only prior
// key was idx_messages_conversation (conversation_id alone), forcing an O(messages-in-conv)
// partial scan per turn on a high-latency USB drive. This composite turns it into an index
// SEARCH with no SCAN and no temp B-tree: SQLite appends the rowid to every index, so trailing
// `(conversation_id, kind)` already satisfies the `ORDER BY rowid DESC LIMIT 1` — naming rowid
// explicitly is REJECTED by SQLite ("no such column: rowid") since messages has a TEXT PK and
// only an implicit rowid. This index targets getLatestCheckpoint specifically;
// listConversationTurns and getConversationSummaryMarker keep using idx_messages_conversation
// (their `rowid > ?` range + `ORDER BY rowid` can't be served here — the non-equality
// `kind IS NOT 'compaction'` predicate sits before the trailing rowid and blocks the seek), so
// idx_messages_conversation must NOT be treated as redundant.
'CREATE INDEX IF NOT EXISTS idx_messages_conv_kind ON messages(conversation_id, kind);'
)
db.exec(
// PERF-4 (full audit 2026-06-28): summary_cache eviction deletes the oldest rows
// `ORDER BY created_at ASC`, but the table's only key was the PK (content_hash, model_id), so
// each over-cap tree build did a full scan + temp B-tree sort of up to 50k rows. This makes
// eviction an ordered index scan (LIMIT-bounded — the residual partial sort is only the
// content_hash tiebreak within an identical created_at).
'CREATE INDEX IF NOT EXISTS idx_summary_cache_created ON summary_cache(created_at);'
)
db.exec(
// PF-3 (full audit 2026-07-10): the audit-log retention prune orders runtime_events by
// created_at (audit.ts pruneAuditEvents); the table's only prior key was the TEXT PK, so
// every prune full-scanned + temp-B-tree-sorted the table. Same additive ensure-on-open
// idiom as idx_summary_cache_created above, so it applies to existing workspaces too.
'CREATE INDEX IF NOT EXISTS idx_runtime_events_created ON runtime_events(created_at);'
)
// run_id indexes (DB-7) deliberately OMITTED: run_id is only ever INSERTed, never joined or
// filtered anywhere in the codebase, so an index would be pure write-amplification on USB with
// no read benefit. Add one alongside the first query that joins on run_id.
// CODE-4 (full audit 2026-07-11): the FTS rowid handle columns — added BEFORE the FTS
// ensures below, whose triggers read and stamp them. Additive + nullable (NULL = legacy
// row, served by the `_legacy` fallback triggers; see CHUNKS_FTS_TRIGGERS).
ensureColumn(db, 'chunks', 'fts_rowid', 'fts_rowid INTEGER')
ensureColumn(db, 'messages', 'fts_rowid', 'fts_rowid INTEGER')
ensureChunksFts(db)
ensureMessagesFts(db)
ensureMessagesFtsKindFilter(db)
ensureFtsRowidSync(db)
seedCollections(db)
db.exec(CORPUS_GENERATION)
// #247: stamp AFTER the migrations, and only when moving up — a same-version open writes
// nothing here, so a second open is a no-op.
if (found < SCHEMA_VERSION) db.exec(`PRAGMA user_version = ${SCHEMA_VERSION};`)
}