From 0d273c5641f31b9cd5c15bfe10f2281617145296 Mon Sep 17 00:00:00 2001 From: Jan De Landtsheer Date: Tue, 21 Apr 2026 20:29:40 +0200 Subject: [PATCH 1/6] docs: ADR 0001 + Phase 1-4 implementation plans Pluggable storage backend, network access, and emergent domain classification. Introduces MemoryStore + Embedder traits, PgMemoryStore alongside SqliteMemoryStore, HTTP MCP + API key auth, and HDBSCAN-based domain clustering. Phase 5 federation deferred to a follow-up ADR. - docs/adr/0001-pluggable-storage-and-network-access.md -- Accepted - docs/plans/0001-phase-1-storage-trait-extraction.md - docs/plans/0002-phase-2-postgres-backend.md - docs/plans/0003-phase-3-network-access.md - docs/plans/0004-phase-4-emergent-domain-classification.md - docs/prd/001-getting-centralized-vestige.md -- source RFC --- ...01-pluggable-storage-and-network-access.md | 303 ++++ .../0001-phase-1-storage-trait-extraction.md | 1026 ++++++++++++ docs/plans/0002-phase-2-postgres-backend.md | 1269 +++++++++++++++ docs/plans/0003-phase-3-network-access.md | 1435 +++++++++++++++++ ...-phase-4-emergent-domain-classification.md | 883 ++++++++++ docs/prd/001-getting-centralized-vestige.md | 751 +++++++++ 6 files changed, 5667 insertions(+) create mode 100644 docs/adr/0001-pluggable-storage-and-network-access.md create mode 100644 docs/plans/0001-phase-1-storage-trait-extraction.md create mode 100644 docs/plans/0002-phase-2-postgres-backend.md create mode 100644 docs/plans/0003-phase-3-network-access.md create mode 100644 docs/plans/0004-phase-4-emergent-domain-classification.md create mode 100644 docs/prd/001-getting-centralized-vestige.md diff --git a/docs/adr/0001-pluggable-storage-and-network-access.md b/docs/adr/0001-pluggable-storage-and-network-access.md new file mode 100644 index 0000000..c150c70 --- /dev/null +++ b/docs/adr/0001-pluggable-storage-and-network-access.md @@ -0,0 +1,303 @@ +# ADR 0001: Pluggable Storage Backend, Network Access, and Emergent Domains + +**Status**: Accepted +**Date**: 2026-04-21 +**Related**: [docs/prd/001-getting-centralized-vestige.md](../prd/001-getting-centralized-vestige.md) + +--- + +## Context + +Vestige v2.x runs as a per-machine local process: stdio MCP transport, SQLite + +FTS5 + USearch HNSW in `~/.vestige/`, fastembed locally for embeddings. This is +ideal for single-machine single-agent use but blocks three real needs: + +- **Multi-machine access** -- same memory brain from laptop, desktop, server +- **Multi-agent access** -- multiple AI clients against one store concurrently +- **Future federation** -- syncing memory between decentralized nodes (MOS / + Threefold grid) + +SQLite's single-writer model and lack of a native network protocol make it +unsuitable as a centralized server. PostgreSQL + pgvector collapses our three +storage layers (SQLite, FTS5, USearch) into one engine with MVCC concurrency, +auth, and replication. + +Separately, Vestige today has no notion of domain or project scope -- all memories +share one namespace. For a multi-machine brain, users want soft topical +boundaries ("dev", "infra", "home") without manual tenanting. HDBSCAN clustering +on embeddings produces these boundaries from the data itself. + +The PRD at `docs/prd/001-getting-centralized-vestige.md` sketches the full design. +This ADR records the architectural decisions and resolves the open questions from +that document. + +--- + +## Decision + +Introduce two new trait boundaries, a network transport layer, and a domain +classification module. All four changes ship in parallel phases. + +**Trait boundaries:** + +1. `MemoryStore` -- single trait covering CRUD, hybrid search, FSRS scheduling, + graph edges, and domains. One big trait, not four. +2. `Embedder` -- separate trait for text-to-vector encoding. Storage never calls + fastembed directly. Callers (cognitive engine locally, HTTP server remotely) + compute embeddings and pass them into the store. + +**Backends:** + +- `SqliteMemoryStore` -- existing code refactored behind the trait, no behavior + change. +- `PgMemoryStore` -- new, using sqlx + pgvector + tsvector. Selectable at runtime + via `vestige.toml`. + +**Network:** + +- MCP over Streamable HTTP on the existing Axum server. +- API key auth middleware (blake3-hashed, stored in `api_keys` table). +- Dashboard uses the same API keys for login, then signed session cookies for + subsequent requests. + +**Domain classification:** + +- HDBSCAN clustering over embeddings to discover domains automatically. +- Soft multi-domain assignment -- raw similarity scores stored per memory, every + domain above a threshold is assigned. +- Conservative drift handling -- propose splits/merges, never auto-apply. + +--- + +## Architecture Overview + +### Component Breakdown + +1. **`Embedder` trait** (new module `crates/vestige-core/src/embedder/`) + - `async fn embed(&self, text: &str) -> Result>` + - `fn model_name(&self) -> &str` + - `fn dimension(&self) -> usize` + - Impls: `FastembedEmbedder` (local ONNX, today), future `JinaEmbedder`, + `OpenAiEmbedder`, etc. + - Stays pluggable forever -- no lock-in to fastembed or to nomic-embed-text. + +2. **`MemoryStore` trait** (new module `crates/vestige-core/src/storage/trait.rs`) + - One trait, ~25 methods across CRUD, search, FSRS, graph, domain sections. + - Uses `trait_variant::make` to generate a `Send`-bound variant for + `Arc` in Axum/tokio contexts. + - The 29 cognitive modules operate exclusively through this trait. No direct + SQLite or Postgres access from the modules. + +3. **`SqliteMemoryStore`** (refactor of existing `crates/vestige-core/src/storage/sqlite.rs`) + - Existing rusqlite + FTS5 + USearch code, wrapped behind the trait. + - Add `domains TEXT[]` equivalent (JSON-encoded array column in SQLite). + - Add `domain_scores` JSON column. + - No behavioral change for current users. + +4. **`PgMemoryStore`** (new `crates/vestige-core/src/storage/postgres.rs`) + - `sqlx::PgPool` with compile-time checked queries. + - pgvector HNSW index for vector search, tsvector + GIN for FTS. + - Native array columns for `domains`, JSONB for `domain_scores` and `metadata`. + - Hybrid search via RRF (Reciprocal Rank Fusion) in a single SQL query. + +5. **Model registry** + - Per-database table `embedding_model` with `(name, dimension, hash, created_at)`. + - Both backends refuse writes from an embedder whose signature doesn't match + the registered row. + - Model swap = `vestige migrate --reembed --model=`, O(n) cost, explicit. + +6. **`DomainClassifier` cognitive module** (new `crates/vestige-core/src/neuroscience/domain_classifier.rs`) + - Owns the HDBSCAN discovery pass (using the `hdbscan` crate). + - Computes soft-assignment scores for every memory against every centroid. + - Stores raw `domain_scores: HashMap` per memory; thresholds into + the `domains` array using `assign_threshold` (default 0.65). + - Runs discovery on demand (`vestige domains discover`) or during dream + consolidation passes. + +7. **HTTP MCP transport** (extension of existing Axum server in `crates/vestige-mcp/src/`) + - New route `POST /mcp` for Streamable HTTP JSON-RPC. + - New route `GET /mcp` for SSE (for long-running operations). + - REST API under `/api/v1/` for direct HTTP clients (non-MCP integrations). + - Auth middleware validates `Authorization: Bearer ...` or `X-API-Key`, plus + signed session cookies for dashboard. + +8. **Key management** (new `crates/vestige-mcp/src/auth/`) + - `api_keys` table -- blake3-hashed keys, scopes, optional domain filter, + last-used timestamp. + - CLI: `vestige keys create|list|revoke`. + +9. **FSRS review event log** (future-proofing for federation) + - New table `review_events` -- append-only `(memory_id, timestamp, rating, + prior_state, new_state)`. + - Current `scheduling` table becomes a materialized view over the event log + (reconstructible from events). + - Phase 5 federation merges event logs, not derived state. Zero cost today, + avoids lock-in tomorrow. + +### Data Flow + +**Local mode (stdio MCP, unchanged UX):** +``` +stdio client -> McpServer -> CognitiveEngine -> FastembedEmbedder -> MemoryStore (SQLite) +``` + +**Server mode (HTTP MCP, new):** +``` +Remote client -> Axum HTTP -> auth middleware -> CognitiveEngine + -> FastembedEmbedder (server-side) -> MemoryStore (Postgres) +``` + +The cognitive engine is backend-agnostic. The embedder and the store are both +swappable. The 7-stage search pipeline (overfetch -> cross-encoder rerank -> +temporal -> accessibility -> context match -> competition -> spreading activation) +sits *above* the `MemoryStore` trait and works identically against either backend. + +### Orthogonality of HDBSCAN and Reranking + +HDBSCAN and the cross-encoder reranker solve different problems and both stay: + +- **HDBSCAN** discovers domains by clustering embeddings. Runs once per discovery + pass. Produces centroids. Used to *filter* search candidates, not to rank them. +- **Cross-encoder reranker** (Jina Reranker v1 Turbo) scores query-document pairs + at search time. Runs on every search. Produces ranked results. + +Domain membership is a filter applied before or during overfetch; reranking runs +on whatever candidate set survives the filter. + +--- + +## Alternatives Considered + +| Alternative | Pros | Cons | Why Not | +|-------------|------|------|---------| +| Split into 4 traits (`MemoryStore + SchedulingStore + GraphStore + DomainStore`) | Cleaner interface segregation | Every module holds 4 trait objects, coordinates transactions across them | One trait is fine in Rust; extract sub-traits later if a genuine need appears | +| Embedding computed inside the backend | Simpler call sites for callers | Backend becomes aware of embedding models; can't support remote clients without local fastembed | Keep storage pure; separate `Embedder` trait handles pluggability | +| Unconstrained pgvector `vector` (no dimension) | Flexible for model swaps | HNSW still needs fixed dims at index creation; hides a meaningful migration as "silent" | Fixed dimension per install, explicit `--reembed` migration | +| Dashboard separate auth (cookies only, no keys) | Simpler dashboard UX | Two auth systems to maintain | Shared API keys with session cookie layer on top | +| Auto-tuned `assign_threshold` targeting an unclassified ratio | Adapts to corpus | Hard to debug ("why did this memory change domain?"); magical | Static 0.65 default, config-tunable, dashboard shows `domain_scores` for manual retuning | +| Aggressive drift (auto-reassign memories whose scores drifted) | Always up-to-date domains | Breaks user muscle memory; silent reshuffling | Conservative: always propose, user accepts | +| CRDTs for federation state | Mathematically clean merges | Massive complexity, performance cost, overkill | Defer; design FSRS as event log now so any future sync model works | + +--- + +## Consequences + +### Positive + +- Single memory brain accessible from every machine. +- Multi-agent concurrent access via Postgres MVCC. +- Natural topical scoping emerges from data, not manual tenants. +- Future embedding model swaps are a config + migration, not a rewrite. +- Federation has a clean on-ramp (event log merge) without committing now. +- The `Embedder` / `MemoryStore` split unlocks other storage backends later + (Redis, Qdrant, Iroh-backed blob store, etc.) with minimal work. + +### Negative + +- Operating a Postgres instance is more work than managing a SQLite file. +- Users who stay on SQLite gain nothing from this ADR (but lose nothing either). +- Migration (`vestige migrate --from sqlite --to postgres`) is a sensitive + operation for users with months of memories -- needs strong testing. +- HDBSCAN + re-soft-assignment runs in O(n) over all embeddings. At 100k+ + memories this starts to matter; manageable but not free. + +### Risks + +- **Trait abstraction leaks**: a cognitive module might need backend-specific + behavior (e.g., Postgres triggers for tsvector). Mitigation: keep such logic + inside the backend impl; the trait stays pure. + Escalation: if a module genuinely cannot express what it needs through the + trait, the trait grows, not the module bypasses. +- **Embedding model drift**: users on older fastembed versions silently + producing slightly different vectors after a fastembed upgrade. Mitigation: + model hash in the registry, refuse mismatched writes, surface a clear error. +- **Auth misconfiguration**: a user binds to `0.0.0.0` without setting + `auth.enabled = true`. Mitigation: refuse to start with non-localhost bind + and auth disabled. Hard error, not a warning. +- **Re-clustering feedback loop**: dream consolidation proposes re-clusters, + which the user accepts, which changes classifications, which affects future + retrievals, which affect future dreams. Mitigation: cap re-cluster frequency + (every 5th dream by default), require explicit user acceptance of proposals. +- **Cross-domain spreading activation weight (0.5 default)**: arbitrary choice; + could be too aggressive or too lax. Mitigation: config-tunable; instrument + retrieval quality metrics in the dashboard so the user sees impact. + +--- + +## Resolved Decisions (from Q&A) + +| # | Question | Resolution | +|---|----------|------------| +| 1 | Trait granularity | Single `MemoryStore` trait | +| 2 | Embedding on insert | Caller provides; separate `Embedder` trait for pluggability | +| 3 | pgvector dimension | Fixed per install, derived from `Embedder::dimension()` at schema init | +| 4 | Federation sync | Defer algorithm; store FSRS reviews as append-only event log now | +| 5 | Dashboard auth | Shared API keys + signed session cookie | +| 6 | HDBSCAN `min_cluster_size` | Default 10; user reruns with `--min-cluster-size N`; no auto-sweep | +| 7 | Domain drift | Conservative -- always propose splits/merges, never auto-apply | +| 8 | Cross-domain spreading activation | Follow with decay factor 0.5 (tunable) | +| 9 | Assignment threshold | Static 0.65 default, config-tunable, raw `domain_scores` stored for introspection | + +--- + +## Implementation Plan + +Five phases, each independently shippable. + +### Phase 1: Storage trait extraction +- Define `MemoryStore` and `Embedder` traits in `vestige-core`. +- Refactor `SqliteMemoryStore` to implement `MemoryStore`; no behavior change. +- Refactor `FastembedEmbedder` to implement `Embedder`. +- Add `embedding_model` registry table; enforce consistency on write. +- Add `domains TEXT[]`-equivalent and `domain_scores` JSON columns to SQLite + (empty for all existing rows). +- Convert all 29 cognitive modules to operate via the traits. +- **Acceptance**: existing test suite passes unchanged. Zero warnings. + +### Phase 2: PostgreSQL backend +- `PgMemoryStore` with sqlx, pgvector, tsvector. +- sqlx migrations (`crates/vestige-core/migrations/postgres/`). +- Backend selection via `vestige.toml` `[storage]` section. +- `vestige migrate --from sqlite --to postgres` command. +- `vestige migrate --reembed` command for model swaps. +- **Acceptance**: full test suite runs green against Postgres with a testcontainer. + +### Phase 3: Network access +- Streamable HTTP MCP route on Axum (`POST /mcp`, `GET /mcp` for SSE). +- REST API under `/api/v1/`. +- API key table + blake3 hashing + `vestige keys create|list|revoke`. +- Auth middleware (Bearer, X-API-Key, session cookie). +- Refuse non-localhost bind without auth enabled. +- **Acceptance**: MCP client over HTTP works from a second machine; dashboard + login flow works; unauth requests return 401. + +### Phase 4: Emergent domain classification +- `DomainClassifier` module using the `hdbscan` crate. +- `vestige domains discover|list|rename|merge` CLI. +- Automatic soft-assignment pipeline (compute `domain_scores` on ingest, threshold + into `domains`). +- Re-cluster every Nth dream consolidation (default 5); surface proposals in the + dashboard. +- Context signals (git repo, IDE) as soft priors on classification. +- Cross-domain spreading activation with 0.5 decay. +- **Acceptance**: on a corpus of 500+ mixed memories, discover produces sensible + clusters; search scoped to a domain returns tightly relevant results. + +### Phase 5: Federation (future, explicitly out of scope for this ADR's +acceptance) +- Node discovery (Mycelium / mDNS). +- Memory sync protocol over append-only review events and LWW-per-UUID for + memory records. +- Explicit follow-up ADR before any code. + +--- + +## Open Questions + +None at ADR acceptance time. Follow-up items that are *implementation choices*, +not architectural: + +- Precise cross-domain decay weight (start at 0.5, instrument, tune) +- Dashboard histogram of `domain_scores` (UX design detail) +- Whether to gate Postgres behind a Cargo feature flag (`postgres-backend`) or + always compile it in (lean toward feature flag to keep SQLite-only builds small) diff --git a/docs/plans/0001-phase-1-storage-trait-extraction.md b/docs/plans/0001-phase-1-storage-trait-extraction.md new file mode 100644 index 0000000..9960462 --- /dev/null +++ b/docs/plans/0001-phase-1-storage-trait-extraction.md @@ -0,0 +1,1026 @@ +# Phase 1 Plan: Storage Trait Extraction + +**Status**: Draft +**Depends on**: none +**Related**: docs/adr/0001-pluggable-storage-and-network-access.md (Phase 1) + +--- + +## Scope + +### In scope + +- Introduce a new module `crates/vestige-core/src/storage/memory_store.rs` defining: + - `LocalMemoryStore` base trait (Sync + 'static) + - `MemoryStore` Send-bound alias generated via `#[trait_variant::make(MemoryStore: Send)]` + - Supporting data types referenced by the trait: `MemoryRecord`, `SchedulingState`, `SearchQuery`, `SearchResult`, `MemoryEdge`, `Domain`, `ClassificationResult`, `StoreStats`, `HealthStatus`, `MemoryStoreError`. +- Introduce a new module `crates/vestige-core/src/embedder/` defining: + - `Embedder` async trait with `embed`, `model_name`, `dimension` plus `model_hash` (for the registry) and optional `embed_batch` with a default implementation. + - Move/adapt the existing `EmbeddingService` impl into a new struct `FastembedEmbedder` that implements `Embedder`. +- Refactor `Storage` (existing `crates/vestige-core/src/storage/sqlite.rs`) into `SqliteMemoryStore`: + - Keep the struct, the `writer`/`reader` `Mutex` pair, the `FSRSScheduler`, and the USearch `VectorIndex`. + - Rename the type alias `Storage` to `SqliteMemoryStore` with a `pub type Storage = SqliteMemoryStore;` alias for backward source compatibility during the transition. (The trait method surface is the new public contract.) + - Implement `LocalMemoryStore` by wrapping existing synchronous `rusqlite` methods inside `async fn` bodies that call a small `spawn_blocking`-or-inline adapter. Bodies MAY block; the `async fn` signature exists because `LocalMemoryStore` is async. +- Add a `schema_version = 12` migration that introduces two schema additions: + 1. `embedding_model` registry table (one-row constraint enforced in code). + 2. Two new TEXT columns on `knowledge_nodes`: `domains TEXT NOT NULL DEFAULT '[]'` and `domain_scores TEXT NOT NULL DEFAULT '{}'` (both JSON-encoded). +- Enforce model registry on every write path: on the first non-empty embedding write the model signature is recorded; subsequent writes whose `Embedder::model_name()` / `dimension()` / `model_hash()` disagree must fail with `MemoryStoreError::ModelMismatch` before touching the DB. +- Audit all 29 cognitive modules under `crates/vestige-core/src/neuroscience/` and `crates/vestige-core/src/advanced/` to confirm they hold no direct `rusqlite::Connection` references, no `Storage` struct field, and no SQL strings. Any that do get refactored to take `&dyn LocalMemoryStore` (local-only modules) or `&Arc` (modules crossing `await` points). +- Add unit tests alongside each new trait method and integration tests in `tests/phase_1/`. + +### Out of scope + +- Implementing `PgMemoryStore` on sqlx + pgvector -- that is Phase 2. +- `vestige migrate --from sqlite --to postgres` and `vestige migrate --reembed` -- Phase 2. +- MCP over Streamable HTTP, API key middleware, `api_keys` table, `vestige keys create|list|revoke` -- Phase 3. +- `DomainClassifier` module, HDBSCAN clustering, `vestige domains discover|list|rename|merge` CLI, incremental soft-assignment, cross-domain spreading activation decay -- Phase 4. +- Federation, mycelium/mDNS node discovery, review event log table -- Phase 5. +- Removing the `pub type Storage = SqliteMemoryStore;` compatibility alias -- that cleanup happens at the end of Phase 4 when no consumers still spell the old name. + +## Prerequisites + +### Current code state + +- Single concrete type `Storage` in `crates/vestige-core/src/storage/sqlite.rs` (4592 lines, 216 public symbols on the impl blocks, approximately 85 public methods) is the only storage surface the crate exposes. +- `EmbeddingService` in `crates/vestige-core/src/embeddings/local.rs` holds the fastembed singleton. No trait exists; callers type-erase via `&EmbeddingService`. +- Migrations live in `crates/vestige-core/src/storage/migrations.rs`; the current head is v11. +- All cognitive modules in `neuroscience/` and `advanced/` are pure (verified by `grep rusqlite|Connection::|execute\(|prepare\(` returning no matches in those trees). They operate on `KnowledgeNode`, `Vec`, `ConnectionRecord`, etc. passed in by the caller. +- `vestige-mcp` consumes `Arc` in `crates/vestige-mcp/src/server.rs` and every tool under `crates/vestige-mcp/src/tools/`. These call sites will type-check unchanged after the alias is introduced because the trait methods preserve the exact signatures of the existing `pub fn` on `Storage`. +- Test count reported in `CLAUDE.md`: 758 tests (406 mcp + 352 core). This is the no-regression target. + +### Required crates (add via `cargo add` under `crates/vestige-core`) + +| Crate | Version | Why | +|-------|---------|-----| +| `trait-variant` | `0.1` | Generates the `Send`-bound `MemoryStore` alias from `LocalMemoryStore` so `Arc` works under tokio/axum without hand-writing two traits. Listed in PRD section "Crate Dependencies (new)" under Phase 1. | +| `blake3` | `1` | `Embedder::model_hash() -> [u8; 32]` uses blake3 to stabilise the "model signature" stored in the `embedding_model` registry. Already slated for Phase 3 auth; pulling it forward costs nothing and avoids a second migration to add a hash column. | +| `async-trait` | `0.1` | Not strictly required with `trait-variant` on MSRV 1.91 (RPITIT is stable), but used for one utility trait (`EmbedderExt`) that carries a default `embed_batch` body. OPTIONAL; see Open Implementation Questions below. | + +No changes to `vestige-mcp/Cargo.toml` are required for Phase 1 -- the new trait lives in `vestige-core` and the mcp crate continues to depend on the `SqliteMemoryStore` concrete type (via the `Storage` alias) until Phase 2 introduces backend selection. + +## Deliverables + +1. `crates/vestige-core/src/storage/memory_store.rs` -- `LocalMemoryStore` + `MemoryStore` traits and supporting types. +2. `crates/vestige-core/src/storage/mod.rs` -- updated exports and module wiring. +3. `crates/vestige-core/src/storage/sqlite.rs` -- `Storage` renamed to `SqliteMemoryStore`, `impl LocalMemoryStore for SqliteMemoryStore` block, enforcement hooks for the model registry, serde of `domains` / `domain_scores` columns. +4. `crates/vestige-core/src/storage/migrations.rs` -- `MIGRATION_V12_UP` adding `embedding_model` table and `domains`, `domain_scores` columns. +5. `crates/vestige-core/src/embedder/mod.rs` -- `Embedder` trait and re-exports. +6. `crates/vestige-core/src/embedder/fastembed.rs` -- `FastembedEmbedder` implementation. +7. `crates/vestige-core/src/embeddings/local.rs` -- retained; `EmbeddingService` kept as the underlying fastembed holder; `FastembedEmbedder` wraps it. +8. `crates/vestige-core/src/lib.rs` -- new `pub mod embedder;` + re-exports for `MemoryStore`, `LocalMemoryStore`, `Embedder`, `FastembedEmbedder`, and the data types. +9. `tests/phase_1/trait_round_trip.rs` -- integration test: round-trip of every trait method through `SqliteMemoryStore`. +10. `tests/phase_1/embedding_model_registry.rs` -- integration test: first-write registers, mismatch refuses, dimension mismatch refuses. +11. `tests/phase_1/domain_column_migration.rs` -- integration test: a v11 DB upgraded to v12 reads `domains=[]` and `domain_scores={}` for all existing rows. +12. `tests/phase_1/cognitive_module_isolation.rs` -- integration test: every cognitive module compiles and executes against an `Arc` without touching `SqliteMemoryStore` concretely. +13. `tests/phase_1/send_bound_variant.rs` -- integration test: an `Arc` can be moved across `tokio::spawn`. +14. Updated `tests/phase_1/mod.rs` (if the dir already uses a module layout) or individual `[[test]]` entries in `tests/e2e/Cargo.toml` as needed -- see "Test Plan" for the exact layout. + +## Detailed Task Breakdown + +### D1. Trait + supporting types (`memory_store.rs`) + +- **File**: `crates/vestige-core/src/storage/memory_store.rs` (new). +- **Depends on**: `trait-variant` crate added under vestige-core, `chrono`, `serde_json`, `uuid`, `thiserror` (all already in Cargo.toml). +- **Signatures**: + +```rust +//! Backend-agnostic memory store trait. +//! +//! This is the single abstraction every cognitive module sits above. It is +//! intentionally flat: one trait, ~25 methods, no sub-traits. + +use std::collections::HashMap; + +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Serialize}; +use uuid::Uuid; + +// ---------------------------------------------------------------------------- +// ERROR +// ---------------------------------------------------------------------------- + +/// Error returned by every `LocalMemoryStore` / `MemoryStore` method. +#[non_exhaustive] +#[derive(Debug, thiserror::Error)] +pub enum MemoryStoreError { + #[error("not found: {0}")] + NotFound(String), + + #[error("backend error: {0}")] + Backend(String), + + #[error( + "embedding model mismatch: store registered {registered_name} (dim {registered_dim}, \ + hash {registered_hash}), embedder is {actual_name} (dim {actual_dim}, hash {actual_hash})" + )] + ModelMismatch { + registered_name: String, + registered_dim: usize, + registered_hash: String, + actual_name: String, + actual_dim: usize, + actual_hash: String, + }, + + #[error("invalid input: {0}")] + InvalidInput(String), + + #[error("initialization error: {0}")] + Init(String), +} + +impl From for MemoryStoreError { + fn from(e: crate::storage::StorageError) -> Self { + use crate::storage::StorageError as S; + match e { + S::NotFound(s) => MemoryStoreError::NotFound(s), + S::Database(e) => MemoryStoreError::Backend(e.to_string()), + S::Io(e) => MemoryStoreError::Backend(e.to_string()), + S::InvalidTimestamp(s) => MemoryStoreError::Backend(format!("invalid timestamp: {s}")), + S::Init(s) => MemoryStoreError::Init(s), + } + } +} + +pub type MemoryStoreResult = std::result::Result; + +// ---------------------------------------------------------------------------- +// DATA TYPES +// ---------------------------------------------------------------------------- + +/// Backend-agnostic memory record. +/// +/// Phase 1 intentionally keeps this type independent of `KnowledgeNode` to +/// avoid dragging 30+ legacy fields through the trait surface. The SQLite +/// backend converts between `MemoryRecord` and `KnowledgeNode` at the +/// boundary. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct MemoryRecord { + pub id: Uuid, + /// Empty = unclassified. Populated in Phase 4. + pub domains: Vec, + /// Raw similarity per domain centroid. Empty until Phase 4 runs clustering. + pub domain_scores: HashMap, + pub content: String, + pub node_type: String, + pub tags: Vec, + pub embedding: Option>, + pub created_at: DateTime, + pub updated_at: DateTime, + pub metadata: serde_json::Value, +} + +/// FSRS-6 scheduling state, one row per memory. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct SchedulingState { + pub memory_id: Uuid, + pub stability: f64, + pub difficulty: f64, + pub retrievability: f64, + pub last_review: Option>, + pub next_review: Option>, + pub reps: u32, + pub lapses: u32, +} + +/// Hybrid search request. +#[derive(Debug, Clone, Default)] +pub struct SearchQuery { + pub domains: Option>, + pub text: Option, + pub embedding: Option>, + pub tags: Option>, + pub node_types: Option>, + pub limit: usize, + pub min_retrievability: Option, +} + +#[derive(Debug, Clone)] +pub struct SearchResult { + pub record: MemoryRecord, + pub score: f64, + pub fts_score: Option, + pub vector_score: Option, +} + +/// Edge in the spreading-activation graph. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct MemoryEdge { + pub source_id: Uuid, + pub target_id: Uuid, + pub edge_type: String, + pub weight: f64, + pub created_at: DateTime, +} + +/// A topical domain (populated in Phase 4). Phase 1 only needs the type to +/// shape the trait surface; discover/classify are Phase 4 work. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Domain { + pub id: String, + pub label: String, + pub centroid: Vec, + pub top_terms: Vec, + pub memory_count: usize, + pub created_at: DateTime, +} + +/// Result of classifying one vector against all known domains. +#[derive(Debug, Clone)] +pub struct ClassificationResult { + pub scores: HashMap, + pub domains: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize, Default)] +pub struct StoreStats { + pub total_memories: usize, + pub memories_with_embeddings: usize, + pub total_edges: usize, + pub total_domains: usize, + pub registered_model_name: Option, + pub registered_model_dim: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum HealthStatus { + Healthy, + Degraded { reason: String }, + Unavailable { reason: String }, +} + +// ---------------------------------------------------------------------------- +// EMBEDDING MODEL SIGNATURE +// ---------------------------------------------------------------------------- + +/// Snapshot of the embedding model that was used to write vectors into the +/// store. Persisted in the `embedding_model` table; compared on every write +/// before the vector is accepted. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ModelSignature { + pub name: String, + pub dimension: usize, + /// Lowercase hex-encoded blake3 hash, 64 chars. + pub hash: String, +} + +// ---------------------------------------------------------------------------- +// TRAIT +// ---------------------------------------------------------------------------- + +/// The single storage abstraction. `trait_variant::make` auto-generates a +/// `MemoryStore` alias with `Send`-bound return futures so `Arc` +/// works in tokio/axum contexts. +#[trait_variant::make(MemoryStore: Send)] +pub trait LocalMemoryStore: Sync + 'static { + // --- Lifecycle --- + async fn init(&self) -> MemoryStoreResult<()>; + async fn health_check(&self) -> MemoryStoreResult; + + // --- Embedding model registry --- + async fn registered_model(&self) -> MemoryStoreResult>; + async fn register_model(&self, sig: &ModelSignature) -> MemoryStoreResult<()>; + + // --- CRUD --- + async fn insert(&self, record: &MemoryRecord) -> MemoryStoreResult; + async fn get(&self, id: Uuid) -> MemoryStoreResult>; + async fn update(&self, record: &MemoryRecord) -> MemoryStoreResult<()>; + async fn delete(&self, id: Uuid) -> MemoryStoreResult<()>; + + // --- Search --- + async fn search(&self, query: &SearchQuery) -> MemoryStoreResult>; + async fn fts_search(&self, text: &str, limit: usize) -> MemoryStoreResult>; + async fn vector_search( + &self, + embedding: &[f32], + limit: usize, + ) -> MemoryStoreResult>; + + // --- FSRS Scheduling --- + async fn get_scheduling( + &self, + memory_id: Uuid, + ) -> MemoryStoreResult>; + async fn update_scheduling(&self, state: &SchedulingState) -> MemoryStoreResult<()>; + async fn get_due_memories( + &self, + before: DateTime, + limit: usize, + ) -> MemoryStoreResult>; + + // --- Graph (spreading activation) --- + async fn add_edge(&self, edge: &MemoryEdge) -> MemoryStoreResult<()>; + async fn get_edges( + &self, + node_id: Uuid, + edge_type: Option<&str>, + ) -> MemoryStoreResult>; + async fn remove_edge(&self, source: Uuid, target: Uuid) -> MemoryStoreResult<()>; + async fn get_neighbors( + &self, + node_id: Uuid, + depth: usize, + ) -> MemoryStoreResult>; + + // --- Domains (Phase 1: stubs return empty; full impl in Phase 4) --- + async fn list_domains(&self) -> MemoryStoreResult>; + async fn get_domain(&self, id: &str) -> MemoryStoreResult>; + async fn upsert_domain(&self, domain: &Domain) -> MemoryStoreResult<()>; + async fn delete_domain(&self, id: &str) -> MemoryStoreResult<()>; + /// Phase 1: returns `Ok(vec![])` since no centroids exist. Phase 4 wires + /// the full soft-assignment pass. + async fn classify(&self, embedding: &[f32]) -> MemoryStoreResult>; + + // --- Bulk / Maintenance --- + async fn count(&self) -> MemoryStoreResult; + async fn get_stats(&self) -> MemoryStoreResult; + async fn vacuum(&self) -> MemoryStoreResult<()>; +} +``` + +- **Behavior notes**: + - Every method returns `MemoryStoreResult`; the trait never exposes `rusqlite::Error`. + - `LocalMemoryStore` requires `Sync + 'static` so `Arc` is usable. The auto-generated `MemoryStore` alias adds `Send` bounds on the returned `impl Future`. + - `register_model` is idempotent: writing the same signature twice is `Ok(())`. Writing a different signature after one is registered returns `MemoryStoreError::ModelMismatch`. + - `classify` on Phase 1 returns `Ok(vec![])` and MUST NOT error; cognitive modules call it and Phase 4 will flesh it out without changing the signature. + - `upsert_domain` / `delete_domain` / `list_domains` / `get_domain` operate against a `domains` table that is empty until Phase 4 populates it. Phase 1 still exposes the methods so Phase 2 can implement them against Postgres in one shot. + - `get_neighbors(node_id, depth)` with `depth == 0` returns just `(node, 1.0)` if the node exists, otherwise `NotFound`. `depth > 0` performs breadth-first expansion over edges, weight = product of edge weights along the shortest path discovered, capped at `max_neighbors = 256` to prevent runaway expansion. + +--- + +### D2. Storage module wiring (`storage/mod.rs`) + +- **File**: `crates/vestige-core/src/storage/mod.rs`. +- **Depends on**: D1. +- **Signatures / diff**: + +```rust +//! Storage Module +//! +//! Backend-agnostic memory store abstraction plus SQLite reference impl. + +mod memory_store; +mod migrations; +mod sqlite; + +pub use memory_store::{ + ClassificationResult, Domain, HealthStatus, LocalMemoryStore, MemoryEdge, MemoryRecord, + MemoryStore, MemoryStoreError, MemoryStoreResult, ModelSignature, SchedulingState, + SearchQuery, SearchResult, StoreStats, +}; +pub use migrations::MIGRATIONS; +pub use sqlite::{ + ConnectionRecord, ConsolidationHistoryRecord, DreamHistoryRecord, InsightRecord, + IntentionRecord, Result, SmartIngestResult, SqliteMemoryStore, StateTransitionRecord, + StorageError, +}; + +/// Backwards-compatibility alias. Retained until Phase 4 completes so every +/// existing `Arc` call site keeps compiling. Scheduled for removal +/// once no downstream source file references it. +pub type Storage = SqliteMemoryStore; +``` + +- **Behavior notes**: + - The alias MUST be a `pub type` (not a re-export), because several tool files pattern on `vestige_core::Storage` through `use` statements and we want to keep them compiling verbatim. This has zero runtime cost. + - `StorageError` stays exported for the 29 existing inherent-method callers; the trait exposes `MemoryStoreError` and provides `From`. + +--- + +### D3. Rename + trait impl in `sqlite.rs` + +- **File**: `crates/vestige-core/src/storage/sqlite.rs`. +- **Depends on**: D1, D2, D4 (for schema columns), D5/D6 (to have `Embedder` to accept on `insert`). +- **Signatures (key excerpts)**: + +```rust +pub struct SqliteMemoryStore { + writer: Mutex, + reader: Mutex, + scheduler: Mutex, + #[cfg(feature = "embeddings")] + embedding_service: EmbeddingService, + #[cfg(feature = "vector-search")] + vector_index: Mutex, + #[cfg(feature = "embeddings")] + query_cache: Mutex>>, + /// Cached model signature. `None` until the first embedding is written. + registered_model: std::sync::RwLock>, +} + +impl SqliteMemoryStore { + pub fn new(db_path: Option) -> MemoryStoreResult { /* existing body, Result converted */ } + + /// Internal: convert a row into a `MemoryRecord` (new mapping reading + /// `domains` / `domain_scores` JSON columns). + fn row_to_record(row: &rusqlite::Row) -> rusqlite::Result { /* ... */ } + + /// Internal: given a `MemoryRecord` plus an optional embedding, enforce + /// the registered model signature and return a `MemoryStoreError` if + /// the embedder would produce a mismatched vector. + fn enforce_model( + &self, + incoming: Option<&ModelSignature>, + ) -> MemoryStoreResult<()> { /* ... */ } +} + +impl crate::storage::memory_store::LocalMemoryStore for SqliteMemoryStore { + async fn init(&self) -> MemoryStoreResult<()> { /* no-op; migrations run in `new` */ Ok(()) } + + async fn health_check(&self) -> MemoryStoreResult { + // SELECT 1; check vector index loaded; check embedding_model presence. + } + + async fn registered_model(&self) -> MemoryStoreResult> { + let cached = self.registered_model.read().map_err(|_| MemoryStoreError::Init("registered_model rwlock poisoned".into()))?.clone(); + if cached.is_some() { + return Ok(cached); + } + // Fall through to DB read... + } + + async fn register_model(&self, sig: &ModelSignature) -> MemoryStoreResult<()> { + // INSERT OR IGNORE; if a row exists and differs, return ModelMismatch. + } + + async fn insert(&self, record: &MemoryRecord) -> MemoryStoreResult { + if let Some(vec) = &record.embedding { + // Caller is REQUIRED to have called register_model first (or the + // store auto-registers on the first embedded write -- see + // "embedding_model_registry.rs" test). + let derived = ModelSignature { /* from cache or from record.metadata */ }; + self.enforce_model(Some(&derived))?; + if vec.len() != derived.dimension { + return Err(MemoryStoreError::InvalidInput( + format!("embedding length {} != registered dimension {}", vec.len(), derived.dimension), + )); + } + } + // Delegate to a private `insert_record_blocking` helper that is the + // current `ingest`/`update_node_content` body, rewritten to accept a + // `MemoryRecord` and to also write `domains` / `domain_scores` JSON. + } + + // ... remaining ~24 methods follow the same pattern: convert inputs, + // call the existing synchronous body, convert outputs. +} +``` + +- **SQL** (covered in full in D4 below). +- **Behavior notes**: + - The `async fn` bodies are allowed to be synchronous under the hood (rusqlite is blocking). We do NOT wrap in `spawn_blocking` for Phase 1 -- the current `Storage` is already used from synchronous code paths (CLI, MCP stdio handler) and forcing the tokio runtime is a Phase 2 concern when we also add sqlx. The trait simply lifts the synchronous body into an `async fn` so the signatures match the trait. MSRV 1.91 supports async fn in trait via `trait_variant::make`. + - `insert` preserves the current FSRS initialization logic (stability, difficulty, next_review, etc.) -- the new code path converts `MemoryRecord.metadata` back into `IngestInput`-equivalent fields when needed. All existing inherent methods (`ingest`, `smart_ingest`, `mark_reviewed`, ...) remain on `SqliteMemoryStore` untouched; the trait impl calls into them. + - `registered_model` cache is an `RwLock>`. Invalidated on schema reset. Never mutated after first population until an explicit `--reembed` migration (Phase 2) takes the RwLock exclusively and writes a new row. + - `enforce_model` returns `Ok(())` if no model is registered yet AND `incoming.is_none()` (no-embedding write). Returns `Ok(())` if no model is registered and `incoming.is_some()` after calling `register_model`. Returns `Err(ModelMismatch)` if registered and they disagree. + - `domains` / `domain_scores` serialization uses `serde_json::to_string` on write and `serde_json::from_str` on read. Empty vec -> `"[]"`, empty map -> `"{}"`. `NULL` in the DB is treated as the empty value for pre-migration rows. + - Every existing inherent method is kept verbatim. The trait impl dispatches to them. This is the "no behavior change" guarantee. + +--- + +### D4. Schema migration V12 + +- **File**: `crates/vestige-core/src/storage/migrations.rs`. +- **Depends on**: D2. +- **SQL**: + +```sql +-- Migration V12: embedding model registry + per-memory domain columns. + +-- 1. Embedding model registry. Single logical row; the (id = 1) constraint is +-- enforced in code via `register_model` (SQLite CHECK on a single-row +-- table is uglier than a constraint we already enforce in Rust). +CREATE TABLE IF NOT EXISTS embedding_model ( + id INTEGER PRIMARY KEY CHECK (id = 1), + name TEXT NOT NULL, + dimension INTEGER NOT NULL, + hash TEXT NOT NULL, -- lowercase hex blake3 + created_at TEXT NOT NULL +); + +-- 2. Per-memory domain columns (JSON TEXT; SQLite has no native arrays). +ALTER TABLE knowledge_nodes ADD COLUMN domains TEXT NOT NULL DEFAULT '[]'; +ALTER TABLE knowledge_nodes ADD COLUMN domain_scores TEXT NOT NULL DEFAULT '{}'; + +-- 3. Index on the domains JSON column to enable `LIKE '%"dev"%'`-style +-- filter in Phase 4. Kept lightweight here; Postgres will use GIN. +CREATE INDEX IF NOT EXISTS idx_nodes_domains ON knowledge_nodes(domains); +CREATE INDEX IF NOT EXISTS idx_nodes_domain_scores ON knowledge_nodes(domain_scores); + +-- 4. Domains catalogue (empty until Phase 4 populates). +CREATE TABLE IF NOT EXISTS domains ( + id TEXT PRIMARY KEY, + label TEXT NOT NULL, + centroid BLOB, -- f32 vector, raw bytes + top_terms TEXT NOT NULL DEFAULT '[]', + memory_count INTEGER NOT NULL DEFAULT 0, + created_at TEXT NOT NULL +); + +CREATE INDEX IF NOT EXISTS idx_domains_created_at ON domains(created_at); + +UPDATE schema_version SET version = 12, applied_at = datetime('now'); +``` + +- **Rust changes** to `migrations.rs`: + +```rust +pub const MIGRATIONS: &[Migration] = &[ + // ... V1..V11 unchanged ... + Migration { + version: 12, + description: "Phase 1: embedding_model registry, domains/domain_scores columns, domains table", + up: MIGRATION_V12_UP, + }, +]; + +const MIGRATION_V12_UP: &str = r#"...SQL above..."#; +``` + +- **Behavior notes**: + - Idempotent: `ALTER TABLE ... ADD COLUMN` on SQLite is not idempotent by default, but the `apply_migrations` driver only applies migrations whose version > current. A user who has already applied V12 never sees the SQL again. + - The `CHECK (id = 1)` on `embedding_model` is the only one-row guardrail -- all inserts go through `register_model` which uses `INSERT OR IGNORE INTO embedding_model (id, ...) VALUES (1, ...)` followed by a `SELECT` to detect mismatch. + - `centroid BLOB` stores the f32 vector using the same `Embedding::to_bytes()` format used in `node_embeddings`, for consistency. + +--- + +### D5. Embedder trait (`embedder/mod.rs`) + +- **File**: `crates/vestige-core/src/embedder/mod.rs` (new). +- **Depends on**: `blake3` crate added to vestige-core. +- **Signatures**: + +```rust +//! Text-to-vector encoding trait. Pluggable per-install. + +use std::fmt::Debug; + +mod fastembed; + +pub use fastembed::FastembedEmbedder; + +/// Error returned by every `Embedder` method. +#[non_exhaustive] +#[derive(Debug, thiserror::Error)] +pub enum EmbedderError { + #[error("embedder initialization failed: {0}")] + Init(String), + #[error("embedding generation failed: {0}")] + EmbedFailed(String), + #[error("invalid input: {0}")] + InvalidInput(String), +} + +pub type EmbedderResult = std::result::Result; + +/// Pluggable embedder. The storage layer NEVER calls fastembed directly; +/// callers compute vectors via this trait and pass them into `MemoryStore`. +#[trait_variant::make(Embedder: Send)] +pub trait LocalEmbedder: Sync + 'static { + async fn embed(&self, text: &str) -> EmbedderResult>; + + fn model_name(&self) -> &str; + + fn dimension(&self) -> usize; + + /// Stable blake3 hash of (model_name || dimension || optional weights + /// digest if available). Lowercase hex, 64 chars. + /// + /// Used by `MemoryStore::register_model` to detect silent model drift + /// (e.g. a fastembed minor upgrade that changes vector output). + fn model_hash(&self) -> String; + + async fn embed_batch(&self, texts: &[&str]) -> EmbedderResult>> { + // Default: sequential. Backends with native batching override this. + let mut out = Vec::with_capacity(texts.len()); + for t in texts { + out.push(self.embed(t).await?); + } + Ok(out) + } + + /// Returns the `ModelSignature` describing this embedder. Convenience + /// wrapper over the three accessors above. + fn signature(&self) -> crate::storage::ModelSignature { + crate::storage::ModelSignature { + name: self.model_name().to_string(), + dimension: self.dimension(), + hash: self.model_hash(), + } + } +} +``` + +- **Behavior notes**: + - The `embed_batch` default implementation is non-trivial only in that backends with genuine batching override it. The `FastembedEmbedder` overrides to call `EmbeddingService::embed_batch`. + - `model_hash()` is intentionally a function, not a constant, so backends with configurable weights (a future `OnnxEmbedder` that loads an arbitrary file) can hash the file bytes into the signature. + - `Embedder` (the `Send` variant) is what cognitive modules bind against when they hold `Arc`. `LocalEmbedder` is available for single-threaded callers (CLI, tests). + +--- + +### D6. FastembedEmbedder impl (`embedder/fastembed.rs`) + +- **File**: `crates/vestige-core/src/embedder/fastembed.rs` (new). +- **Depends on**: D5, existing `crate::embeddings::local::EmbeddingService`. +- **Signatures**: + +```rust +use super::{EmbedderError, EmbedderResult, LocalEmbedder}; +use crate::embeddings::{EMBEDDING_DIMENSIONS, EmbeddingService, matryoshka_truncate}; + +pub struct FastembedEmbedder { + inner: EmbeddingService, + cached_hash: std::sync::OnceLock, +} + +impl FastembedEmbedder { + pub fn new() -> Self { + Self { + inner: EmbeddingService::new(), + cached_hash: std::sync::OnceLock::new(), + } + } + + fn compute_hash(name: &str, dim: usize) -> String { + let mut hasher = blake3::Hasher::new(); + hasher.update(name.as_bytes()); + hasher.update(&(dim as u64).to_le_bytes()); + // fastembed's ONNX bytes are not directly accessible at runtime; we + // use `(name, dim, static fastembed crate version)` as the + // signature. If fastembed ever changes its output deterministically + // between minor versions, bumping the crate version triggers a + // mismatch -- which is exactly the drift we want to detect. + hasher.update(env!("CARGO_PKG_VERSION").as_bytes()); + hasher.finalize().to_hex().to_string() + } +} + +impl Default for FastembedEmbedder { + fn default() -> Self { Self::new() } +} + +impl LocalEmbedder for FastembedEmbedder { + async fn embed(&self, text: &str) -> EmbedderResult> { + let emb = self + .inner + .embed(text) + .map_err(|e| EmbedderError::EmbedFailed(e.to_string()))?; + Ok(emb.vector) + } + + fn model_name(&self) -> &str { self.inner.model_name() } + + fn dimension(&self) -> usize { EMBEDDING_DIMENSIONS } + + fn model_hash(&self) -> String { + self.cached_hash + .get_or_init(|| Self::compute_hash(self.inner.model_name(), EMBEDDING_DIMENSIONS)) + .clone() + } + + async fn embed_batch(&self, texts: &[&str]) -> EmbedderResult>> { + let embs = self + .inner + .embed_batch(texts) + .map_err(|e| EmbedderError::EmbedFailed(e.to_string()))?; + Ok(embs.into_iter().map(|e| e.vector).collect()) + } +} +``` + +- **Behavior notes**: + - `EmbeddingService` is kept as the fastembed singleton holder; `FastembedEmbedder` is a thin trait adapter. Existing callers of `EmbeddingService` continue to work during the transition. + - `model_hash` is deterministic for a given `(model_name, EMBEDDING_DIMENSIONS, vestige-core version)` triple. This is the drift detector the ADR calls out under "Risks: Embedding model drift". + - `matryoshka_truncate` is already applied inside `EmbeddingService::embed`, so the vectors returned here are the 256-dim Matryoshka-truncated L2-normalized vectors that the rest of the stack expects. + +--- + +### D7. `lib.rs` re-exports + +- **File**: `crates/vestige-core/src/lib.rs`. +- **Depends on**: D1, D2, D5, D6. +- **Diff** (inserted alongside the existing `pub mod storage;` re-exports): + +```rust +pub mod embedder; + +pub use embedder::{Embedder, EmbedderError, EmbedderResult, FastembedEmbedder, LocalEmbedder}; + +pub use storage::{ + ClassificationResult, Domain, HealthStatus, LocalMemoryStore, MemoryEdge, MemoryRecord, + MemoryStore, MemoryStoreError, MemoryStoreResult, ModelSignature, SchedulingState, + SearchQuery, SearchResult, SqliteMemoryStore, Storage, StoreStats, + // Existing re-exports retained: + ConnectionRecord, ConsolidationHistoryRecord, DreamHistoryRecord, InsightRecord, + IntentionRecord, Result, SmartIngestResult, StateTransitionRecord, StorageError, +}; +``` + +- **Behavior notes**: + - `Storage` remains a top-level re-export so `use vestige_core::Storage;` keeps working in `vestige-mcp` without changes. Post-Phase-4 cleanup will grep the downstream crates and replace. + +--- + +### D8. Cognitive module audit + +- **Files**: all under `crates/vestige-core/src/neuroscience/*.rs` and `crates/vestige-core/src/advanced/*.rs` -- 21 source files. +- **Depends on**: D1..D7. +- **Work**: perform the following grep-gate BEFORE and AFTER the refactor: + +``` +Grep pattern: "rusqlite|Connection::|execute\\(|prepare\\(|&Storage|SqliteMemoryStore" +Expected in neuroscience/ and advanced/ BEFORE: only a single comment-only hit in `neuroscience/active_forgetting.rs:54` referencing `Storage::suppress_memory` in a doc comment. +Expected AFTER: zero hits that reference `SqliteMemoryStore` concretely. References through `&dyn LocalMemoryStore` or `&Arc` are acceptable. +``` + +- **Behavior notes**: + - Current state: the 29 cognitive modules are already pure (they take nodes/vectors/connections as arguments, not a `&Storage`). No refactor is required for their bodies. + - The only work is the `consolidation/sleep.rs` and `consolidation/phases.rs` path, which in the current codebase accepts `&Storage`. These get rewritten to accept `&dyn LocalMemoryStore` (callable from sync contexts) or `&Arc` (callable from async contexts). See file inventory below. + - Actual rewrites (expected number): 3-5 functions across `consolidation/sleep.rs` and `consolidation/mod.rs`. All trait-object refactors; no logic changes. + - `cognitive.rs` in `vestige-mcp` uses `storage.get_all_connections()`. Because `SqliteMemoryStore` keeps `get_all_connections` as an inherent method AND implements `MemoryStore::get_edges`, both call styles keep compiling. `cognitive.rs` does not need to change in Phase 1. + +--- + +### D9. Backwards-compatible inherent methods on `SqliteMemoryStore` + +- **File**: `crates/vestige-core/src/storage/sqlite.rs`. +- **Depends on**: D3. +- **Behavior notes**: + - Every one of the 85 existing `pub fn` on `Storage` (e.g. `ingest`, `smart_ingest`, `mark_reviewed`, `hybrid_search_filtered`, `save_intention`, `save_insight`, `save_connection`, `apply_rac1_cascade`, ...) stays as an inherent method on `SqliteMemoryStore`. The Phase 1 refactor ONLY adds the trait impl; it does NOT remove any method, rename any field, or change any SQL. + - Internal writes that previously embedded `INSERT INTO knowledge_nodes (...)` statements gain two more columns (`domains = '[]'`, `domain_scores = '{}'`) in the INSERT list. These are non-optional columns after migration V12, and their DEFAULT is `'[]'`/`'{}'` respectively, so ALTER behaves correctly for pre-existing rows but INSERT statements need to either list the defaults explicitly or rely on the DB default. Plan: explicitly write `'[]'` and `'{}'` in every `INSERT INTO knowledge_nodes` statement to avoid surprises if a future migration drops the DEFAULT. + +--- + +## Test Plan + +### Unit tests (colocated, `#[cfg(test)] mod tests` at end of each source file) + +Every public trait method on `LocalMemoryStore` gets at least one unit test, exercised through the `SqliteMemoryStore` impl. The unit test file is `crates/vestige-core/src/storage/sqlite.rs` (inside the existing `mod tests`). + +- `vestige_core::storage::sqlite::tests::trait_init_is_idempotent` -- calling `LocalMemoryStore::init` twice returns `Ok(())` both times. +- `vestige_core::storage::sqlite::tests::trait_health_check_reports_healthy_on_fresh_db` -- asserts `HealthStatus::Healthy` on a fresh in-memory DB. +- `vestige_core::storage::sqlite::tests::trait_register_model_first_write_succeeds` -- after registering a signature, `registered_model()` returns it. +- `vestige_core::storage::sqlite::tests::trait_register_model_mismatched_write_refused` -- registering a second, different signature returns `MemoryStoreError::ModelMismatch`. +- `vestige_core::storage::sqlite::tests::trait_register_model_same_signature_idempotent` -- registering the same signature twice returns `Ok(())` both times. +- `vestige_core::storage::sqlite::tests::trait_insert_returns_uuid` -- `insert(record)` returns the UUID from the record. +- `vestige_core::storage::sqlite::tests::trait_insert_refuses_dimension_mismatch` -- inserting a record with a 512-dim vector into a store registered for 256 dims returns `MemoryStoreError::InvalidInput`. +- `vestige_core::storage::sqlite::tests::trait_get_missing_returns_none` -- `get(non_existent_uuid)` returns `Ok(None)`. +- `vestige_core::storage::sqlite::tests::trait_get_after_insert_round_trip` -- insert then get returns a record equal (by content/tags/type) to the input; `domains == []`, `domain_scores == {}`. +- `vestige_core::storage::sqlite::tests::trait_update_modifies_content` -- update with new content reflects in subsequent `get`. +- `vestige_core::storage::sqlite::tests::trait_delete_removes_record` -- `delete` then `get` returns `Ok(None)`. +- `vestige_core::storage::sqlite::tests::trait_search_combines_fts_and_vector` -- with one memory whose content matches by FTS and another by vector, `search` returns both, higher score for the exact content match. +- `vestige_core::storage::sqlite::tests::trait_fts_search_returns_tokens_match` -- verifies FTS path. +- `vestige_core::storage::sqlite::tests::trait_vector_search_returns_cosine_order` -- verifies ordering. +- `vestige_core::storage::sqlite::tests::trait_scheduling_round_trip` -- `update_scheduling` then `get_scheduling` returns equivalent state. +- `vestige_core::storage::sqlite::tests::trait_get_scheduling_missing_returns_none`. +- `vestige_core::storage::sqlite::tests::trait_get_due_memories_returns_in_order` -- inserts 3 records with different `next_review`, asserts older-due listed first. +- `vestige_core::storage::sqlite::tests::trait_add_edge_is_idempotent` -- adding the same edge twice does not duplicate. +- `vestige_core::storage::sqlite::tests::trait_get_edges_filters_by_type`. +- `vestige_core::storage::sqlite::tests::trait_remove_edge_deletes_single`. +- `vestige_core::storage::sqlite::tests::trait_get_neighbors_bfs_depth_zero_returns_self_only`. +- `vestige_core::storage::sqlite::tests::trait_get_neighbors_bfs_depth_two_expands` -- build A->B->C, get_neighbors(A, 2) returns {A, B, C}. +- `vestige_core::storage::sqlite::tests::trait_list_domains_empty_in_phase_1` -- Phase 1 has no clustering, so `list_domains()` returns `[]`. +- `vestige_core::storage::sqlite::tests::trait_upsert_then_get_domain_round_trip`. +- `vestige_core::storage::sqlite::tests::trait_delete_domain_idempotent`. +- `vestige_core::storage::sqlite::tests::trait_classify_with_no_domains_returns_empty` -- verifies Phase 1 stub behavior. +- `vestige_core::storage::sqlite::tests::trait_count_matches_insert_count`. +- `vestige_core::storage::sqlite::tests::trait_get_stats_reports_registered_model`. +- `vestige_core::storage::sqlite::tests::trait_vacuum_succeeds` -- runs and asserts no error. + +Every public method on `LocalEmbedder` gets at least one unit test under `crates/vestige-core/src/embedder/fastembed.rs`: + +- `vestige_core::embedder::fastembed::tests::embedder_reports_correct_name` -- `model_name()` contains "nomic". +- `vestige_core::embedder::fastembed::tests::embedder_reports_256_dimension`. +- `vestige_core::embedder::fastembed::tests::embedder_hash_is_stable` -- `model_hash()` called twice returns identical string. +- `vestige_core::embedder::fastembed::tests::embedder_hash_includes_crate_version` -- a synthetic test that asserts the hash contains the blake3 of `(name, 256, VERSION)`. +- `vestige_core::embedder::fastembed::tests::embedder_embed_smoke` -- gated on `#[cfg(feature = "embeddings")]`; asserts output length == 256. +- `vestige_core::embedder::fastembed::tests::embedder_embed_batch_matches_sequential` -- gated; assert batch result equals sequential result. +- `vestige_core::embedder::fastembed::tests::embedder_signature_matches_accessors`. + +Migration V12 unit tests under `crates/vestige-core/src/storage/migrations.rs`: + +- `vestige_core::storage::migrations::tests::v12_adds_embedding_model_table` -- apply V12 then assert `SELECT count(*) FROM sqlite_master WHERE name='embedding_model'` == 1. +- `vestige_core::storage::migrations::tests::v12_adds_domains_columns` -- assert `PRAGMA table_info(knowledge_nodes)` includes `domains` and `domain_scores`. +- `vestige_core::storage::migrations::tests::v12_default_values_empty_json` -- insert a row via raw SQL, read back, assert `domains == '[]'` and `domain_scores == '{}'`. +- `vestige_core::storage::migrations::tests::v12_is_replayable` -- rewind `schema_version` to 11, re-apply migrations, does not error (MUST use `CREATE TABLE IF NOT EXISTS`; `ALTER TABLE ADD COLUMN` will be skipped because the driver only re-runs migrations whose version > current -- already covered by `apply_migrations`). +- `vestige_core::storage::migrations::tests::v12_preserves_existing_rows` -- insert rows under V11 schema, upgrade to V12, assert `domains='[]'` on those rows. + +Supporting-type unit tests under `crates/vestige-core/src/storage/memory_store.rs`: + +- `vestige_core::storage::memory_store::tests::memory_store_error_from_storage_error` -- converts `StorageError::NotFound` to `MemoryStoreError::NotFound`. +- `vestige_core::storage::memory_store::tests::model_signature_serde_round_trip`. +- `vestige_core::storage::memory_store::tests::memory_record_serde_round_trip`. + +### Integration tests (`tests/phase_1/`) + +Each file is a standalone `[[test]]` target. The Cargo layout: + +- `tests/phase_1/Cargo.toml` with: + +```toml +[package] +name = "vestige-phase-1-tests" +version = "0.0.1" +edition = "2024" +publish = false + +[dependencies] +vestige-core = { path = "../../crates/vestige-core" } +tokio = { version = "1", features = ["macros", "rt-multi-thread"] } +tempfile = "3" +uuid = { version = "1", features = ["v4"] } +chrono = "0.4" +serde_json = "1" +rusqlite = { version = "0.38", features = ["bundled"] } +``` + +And added to the workspace `Cargo.toml` members. Each `.rs` file below is a `#[tokio::test]`-using integration test. + +#### `tests/phase_1/trait_round_trip.rs` + +- `round_trip::insert_get_update_delete` -- exercises CRUD via the trait. Inserts a record with `domains=[]`, gets it, asserts equality, updates content, deletes, asserts not found. +- `round_trip::scheduling_upsert_and_due_scan` -- upserts FSRS state for three memories with different `next_review`, calls `get_due_memories(Utc::now(), 10)`, asserts only past-due ones appear. +- `round_trip::edge_crud` -- add edge, list edges, remove edge, assert gone. +- `round_trip::search_hybrid_returns_results` -- insert three memories, embed one by content match only, one by semantic only, one by both, search with both `text` and `embedding`, assert all three appear with `fts_score`/`vector_score` correctly populated. +- `round_trip::count_and_stats_track_inserts` -- after 10 inserts, `count()` == 10 and `get_stats().total_memories` == 10. +- `round_trip::vacuum_after_deletes_reclaims` -- insert 50, delete 40, call `vacuum`, assert disk file size decreased (informational; test is lenient if VACUUM was a no-op). +- `round_trip::list_domains_empty_then_upsert_then_delete` -- Phase 1 has no discovery, but manual upsert/delete must work so Phase 2's Postgres impl can share the test. +- `round_trip::classify_with_no_domains_returns_empty` -- calls `classify(embedding)` on a fresh store, asserts `Vec<(String, f64)>` is empty. + +#### `tests/phase_1/embedding_model_registry.rs` + +- `model_registry::first_embedded_insert_auto_registers` -- fresh store; insert a record with a 256-dim vector using a `FastembedEmbedder`; subsequent `registered_model()` returns a `Some(ModelSignature)` with dim=256. +- `model_registry::second_insert_with_same_signature_succeeds`. +- `model_registry::second_insert_with_different_dimension_refused` -- register a 256-dim signature, try to insert a 512-dim vector, expect `MemoryStoreError::InvalidInput` (because dimension does not match registered). +- `model_registry::second_insert_with_different_model_name_refused` -- register signature A, call `register_model` with signature B (same dim, different name), expect `MemoryStoreError::ModelMismatch`. +- `model_registry::second_insert_with_different_hash_refused` -- register signature A, try to register signature A' with the same name and dim but a different hash, expect `MemoryStoreError::ModelMismatch`. +- `model_registry::no_embedding_insert_allowed_before_registration` -- a plain text memory without an embedding must insert successfully even when `registered_model()` is `None`. +- `model_registry::stats_reports_registered_model_after_first_write`. + +#### `tests/phase_1/domain_column_migration.rs` + +- `domain_columns::fresh_db_has_v12_schema` -- open a fresh store, query `PRAGMA table_info(knowledge_nodes)`, assert `domains` and `domain_scores` columns are present with the correct defaults. +- `domain_columns::v11_db_upgrades_cleanly` -- programmatically create a DB at V11 by running migrations up to V11 only, insert 5 rows, then invoke the V12 migration, assert all 5 rows now report `domains=='[]'` and `domain_scores=='{}'`. +- `domain_columns::empty_domains_serialize_as_brackets` -- insert a `MemoryRecord { domains: vec![], .. }`, then read the underlying SQLite row via a raw query, assert the stored value is `"[]"`, not `NULL`. +- `domain_columns::populated_domains_round_trip` -- insert a record with `domains=["dev","infra"]` and `domain_scores={"dev":0.82,"infra":0.71}`, read back via the trait, assert equality. +- `domain_columns::domains_table_exists` -- `SELECT name FROM sqlite_master WHERE name='domains'` returns one row. + +#### `tests/phase_1/cognitive_module_isolation.rs` + +- `cognitive_isolation::all_modules_compile_against_dyn_store` -- a test function that allocates a `let store: Arc = Arc::new(SqliteMemoryStore::new(...)?);`, then invokes a representative method from every cognitive module passing in records/vectors/edges it reads through the trait. The point is a compile-time gate: if any module still typed against `SqliteMemoryStore`, this would fail to compile. +- `cognitive_isolation::spreading_activation_traverses_via_trait` -- exercise `ActivationNetwork` seeded from `store.get_edges(...)` results. +- `cognitive_isolation::synaptic_tagging_consumes_records_via_trait` -- build `CapturedMemory` from `store.get(uuid)` and let the tagger compute retroactive importance. +- `cognitive_isolation::hippocampal_index_built_from_store` -- load memories via `store.fts_search`, build `HippocampalIndex`, assert queries against the index work. + +#### `tests/phase_1/send_bound_variant.rs` + +- `send_bound::arc_dyn_memory_store_moves_across_tokio_tasks` -- wrap `SqliteMemoryStore` in `Arc`, spawn 16 tokio tasks each inserting 10 memories, join all tasks, assert final `count() == 160`. This verifies the `#[trait_variant::make(MemoryStore: Send)]` emission actually produces a `Send`-bound future. +- `send_bound::concurrent_readers_one_writer` -- 32 concurrent readers calling `search` while one writer loops inserting; asserts no panics, no deadlocks, eventual consistency on `count`. + +#### `tests/phase_1/embedder_trait.rs` + +- `embedder::fastembed_implements_embedder_trait` -- `let e: Box = Box::new(FastembedEmbedder::new());` compiles and `e.dimension()` == 256. +- `embedder::signature_matches_memory_store_registry` -- take the signature from `Embedder::signature()`, register it via `MemoryStore::register_model`, assert `registered_model()` returns the same. + +### Regression verification + +- `cargo build -p vestige-core` -- zero warnings. +- `cargo build -p vestige-mcp` -- zero warnings. +- `cargo clippy --workspace --all-targets -- -D warnings` -- green. +- `cargo test -p vestige-core --lib` -- existing 352 core lib tests remain green. +- `cargo test -p vestige-mcp --lib` -- existing 406 mcp tests remain green. +- `cargo test -p vestige-core --lib storage::migrations::tests` -- explicitly invokes the migration tests added in Phase 1. +- `cargo test -p vestige-core --lib storage::sqlite::tests` -- invokes the trait-method unit tests added in Phase 1. +- `cargo test -p vestige-core --lib embedder::fastembed::tests` -- invokes embedder unit tests. +- `cargo test -p vestige-phase-1-tests --test trait_round_trip` -- Phase 1 integration test file 1. +- `cargo test -p vestige-phase-1-tests --test embedding_model_registry` -- Phase 1 integration test file 2. +- `cargo test -p vestige-phase-1-tests --test domain_column_migration` -- Phase 1 integration test file 3. +- `cargo test -p vestige-phase-1-tests --test cognitive_module_isolation` -- Phase 1 integration test file 4. +- `cargo test -p vestige-phase-1-tests --test send_bound_variant` -- Phase 1 integration test file 5. +- `cargo test -p vestige-phase-1-tests --test embedder_trait` -- Phase 1 integration test file 6. +- `cargo test -p vestige-phase-1-tests` -- convenience: runs all integration test binaries in the Phase 1 crate. +- `cargo test -p vestige-e2e` -- existing e2e harness runs unchanged; no new tests here but existing ones must pass. + +## Acceptance Criteria + +- [ ] `cargo build -p vestige-core` -- zero warnings. +- [ ] `cargo build -p vestige-mcp` -- zero warnings. +- [ ] `cargo build --workspace --all-targets` -- zero warnings. +- [ ] `cargo clippy --workspace --all-targets -- -D warnings` -- exits 0. +- [ ] `cargo test -p vestige-core` -- all 352 existing core tests plus new Phase 1 unit tests pass. +- [ ] `cargo test -p vestige-mcp` -- all 406 existing mcp tests pass, unchanged. +- [ ] `cargo test -p vestige-phase-1-tests` -- all Phase 1 integration tests pass. +- [ ] `cargo test -p vestige-e2e` -- existing e2e journey suite passes unchanged. +- [ ] Cumulative test count >= 758 (the pre-Phase-1 baseline) plus the new unit and integration additions. +- [ ] `git grep -n 'rusqlite::' crates/vestige-core/src/neuroscience/ crates/vestige-core/src/advanced/` -- zero hits (the single pre-existing doc-comment reference in `active_forgetting.rs` is acceptable and does not introduce SQL dependency; code references must be zero). +- [ ] `git grep -n 'SqliteMemoryStore' crates/vestige-core/src/neuroscience/ crates/vestige-core/src/advanced/` -- zero hits. +- [ ] `git grep -n 'fastembed::' crates/vestige-core/src/storage/sqlite.rs` -- zero hits (Storage must never call fastembed directly; embedding goes through the `Embedder` trait held on the caller side). +- [ ] `SqliteMemoryStore::insert` refuses a vector whose dimension disagrees with the registered model (returns `MemoryStoreError::InvalidInput`). +- [ ] `SqliteMemoryStore::register_model` returns `MemoryStoreError::ModelMismatch` when a second, different signature is provided after a first was already registered. +- [ ] After upgrading a V11 database to V12, every pre-existing row has `domains == "[]"` and `domain_scores == "{}"` with no NULLs. +- [ ] `#[trait_variant::make(MemoryStore: Send)]` compiles; `Arc` is movable across `tokio::spawn`. +- [ ] Migration V12 is idempotent on replay: `apply_migrations` rewound to V11, re-applied, succeeds without error. +- [ ] `vestige-core::storage::Storage` continues to resolve (via the `pub type` alias) at every current call site in `vestige-mcp`. +- [ ] The `embedding_model` table can only hold a single row (programmatic invariant -- verified by an integration test that attempts a second `INSERT INTO embedding_model (id = 1, ...)` and observes the CHECK-enforced uniqueness). +- [ ] `registered_model()` is cached on first read; no SELECT is issued against `embedding_model` after the first hit within the same process (verified by wrapping the reader in a counting proxy in a dedicated test). + +## Rollback Notes + +If Phase 1 fails mid-way, rollback granularity is per-deliverable and the DB can be downgraded by SQL. + +- **D1 (`memory_store.rs`)**: revert the new file. The trait has zero non-test consumers in Phase 1, so deletion is safe. +- **D2 (`storage/mod.rs`)**: revert to the prior export list. The only forward-facing identifier is the `pub type Storage = SqliteMemoryStore;` alias, which becomes `pub use sqlite::Storage;` again once `SqliteMemoryStore` is renamed back to `Storage`. +- **D3 (`sqlite.rs` rename + trait impl)**: revert the struct rename (`SqliteMemoryStore` -> `Storage`). The trait impl is a separate `impl` block and can be deleted wholesale. Inherent methods are unchanged and do not need to be touched. Net diff on revert: delete one `impl LocalMemoryStore for ...` block plus the two helper functions (`row_to_record`, `enforce_model`). +- **D4 (Migration V12)**: DOWN migration script: + +```sql +-- Phase 1 rollback: drop Phase 1 schema additions. +-- WARNING: this deletes any `domains` / `domain_scores` values stored under V12. +-- Execute ONLY when downgrading from V12 to V11 on a database where no Phase 4 +-- work has happened yet (otherwise you lose domain classifications). + +DROP TABLE IF EXISTS domains; +DROP INDEX IF EXISTS idx_nodes_domains; +DROP INDEX IF EXISTS idx_nodes_domain_scores; + +-- SQLite does not support DROP COLUMN before 3.35; the project's bundled +-- rusqlite uses 3.45+ (see `bundled-sqlite` feature). So the DROP COLUMN +-- form below is safe on every target platform. +ALTER TABLE knowledge_nodes DROP COLUMN domains; +ALTER TABLE knowledge_nodes DROP COLUMN domain_scores; + +DROP TABLE IF EXISTS embedding_model; + +UPDATE schema_version SET version = 11, applied_at = datetime('now'); +``` + + Operationally: the DOWN script is NOT included in the source migrations list (migrations are forward-only). If a rollback is required, it is applied manually via `sqlite3 vestige.db < rollback_v12.sql`. A backup via `storage.backup_to(...)` MUST be taken before the Phase 1 migration runs in production -- the `Storage::backup_to` method already exists (line 3903) and does not need changes. + +- **D5/D6 (`embedder/`)**: delete the module. `EmbeddingService` is untouched, so callers that still use it continue to work. The new `Embedder` trait has no pre-Phase-2 consumers. +- **D7 (`lib.rs`)**: revert the re-export additions. Zero downstream impact since the new symbols have no pre-Phase-2 consumers. +- **D8 (cognitive module audit)**: audit-only, no code changes. Nothing to roll back unless `consolidation/sleep.rs` was changed; if so, revert. +- **Crate-level considerations**: + - `trait-variant` must remain in `Cargo.toml` until every consumer of the trait alias has been reverted. Safe to leave in `[dependencies]` indefinitely; it has no runtime cost. + - `blake3` was going to be added in Phase 3 anyway; leaving it in on rollback is harmless. + - `rusqlite` version stays pinned; no bump required for Phase 1. + +## Open Implementation Questions + +Implementation-choice-only. Architectural questions are resolved in ADR 0001. + +1. **`MemoryRecord` vs `KnowledgeNode` as the trait currency.** + - Candidate A: `MemoryRecord` (new, lean type matching the PRD) -- chosen. + - Candidate B: use existing `KnowledgeNode` directly. + - **Recommendation: A.** `KnowledgeNode` carries 30+ FSRS / dual-strength / sentiment / temporal fields that bind callers to the SQLite columns. `MemoryRecord` is what `PgMemoryStore` and future backends will want. SQLite impl converts between the two at the boundary, which is a ~40-line `impl From for MemoryRecord` (and back) shim. Pays for itself in Phase 2. + +2. **`async fn` in traits vs `Box` via `async-trait`.** + - Candidate A: use `trait-variant` (RPITIT-based, MSRV 1.75+, our MSRV is 1.91). + - Candidate B: use `async-trait` (allocates one Box per call). + - **Recommendation: A.** `trait-variant` generates both the base `LocalMemoryStore` and the `Send`-bound `MemoryStore` from one definition, matches what the PRD explicitly calls out, and avoids the allocation overhead of boxed futures on every CRUD call. + +3. **Blocking SQLite under async signatures: spawn_blocking vs inline.** + - Candidate A: bodies call the existing sync `self.writer.lock()...` inline inside the `async fn`. + - Candidate B: bodies wrap in `tokio::task::spawn_blocking`. + - **Recommendation: A for Phase 1.** The current call sites are a mix of sync (CLI, bin/restore.rs) and async (MCP handlers). Introducing `spawn_blocking` would force a tokio runtime even for CLI use. Inline blocking under `async fn` is a documented pattern that compiles and works; under Phase 2 the Postgres impl uses `sqlx` which is natively async, and we can revisit Sqlite blocking policy at that point. Phase 1 priority is "no behavior change". + +4. **Where does `register_model` get called from: storage side auto-register, or caller-side explicit?** + - Candidate A: caller explicitly calls `store.register_model(embedder.signature())` once after `MemoryStore::init`. + - Candidate B: first `insert` with a vector auto-registers. + - **Recommendation: B.** The current code path (`Storage::ingest` -> `generate_embedding_for_node` -> INSERT into `node_embeddings`) has no explicit registration step and we want `--no behavior change`. Auto-register on first embedded write preserves the exact current UX. Callers who care (migration tooling, Phase 2 `--reembed`) can still call `register_model` explicitly; it is a no-op when idempotent. + +5. **`model_hash` content: fastembed ONNX bytes vs `(name, dim, crate_version)`.** + - Candidate A: hash the ONNX file bytes on disk (after model download). + - Candidate B: hash `(name, dim, vestige-core CARGO_PKG_VERSION)`. + - **Recommendation: B.** Fastembed caches ONNX files under `FASTEMBED_CACHE_PATH`; reading them from inside `FastembedEmbedder::new()` couples the embedder to fastembed's caching behavior and adds slow startup. Hashing `(name, dim, our crate version)` catches the "silent model drift between vestige versions" case the ADR calls out under Risks. Phase 2 can add a content-hashed `OnnxEmbedder` that loads any file and genuinely hashes it; the trait method signature stays the same. + +6. **`LocalMemoryStore` `Sync + 'static` or just `Sync`.** + - Candidate A: `Sync + 'static`. + - Candidate B: `Sync`. + - **Recommendation: A.** `'static` is required for `Arc` which is the target call pattern (Axum, MCP server, cognitive engine). Every impl we have in mind -- `SqliteMemoryStore`, `PgMemoryStore` -- holds owned state (connection pool, vector index), so `'static` is free. + +7. **Should trait methods appear on the SQLite impl instead of being separate?** + - Candidate A: keep the current ~85 inherent methods on `SqliteMemoryStore` AND add the `impl LocalMemoryStore` block. + - Candidate B: move every inherent method into the trait. + - **Recommendation: A.** Many inherent methods (e.g. `run_rac1_cascade_sweep`, `apply_rac1_cascade`, `save_insight`, `save_connection`, `preview_review`, `get_memory_subgraph`) have SQLite-specific semantics, transactional behavior, and call patterns that do not belong in a backend-agnostic trait. They will stay SQLite-only or be extracted into new traits in a post-Phase-4 cleanup. Phase 1's job is to expose the `~25 methods` contract the ADR specifies, not to retrofit the entire API. + +8. **Where do `Domain` bytes (centroid) live?** + - Candidate A: `BLOB` column on `domains` table. + - Candidate B: JSON-encoded array of f32 in a `TEXT` column. + - **Recommendation: A.** Consistent with how `node_embeddings.embedding` already stores vectors (little-endian f32 bytes via `Embedding::to_bytes`). JSON would triple the storage size and slow deserialization. The `Domain::centroid: Vec` field round-trips through the same codec. + +9. **Migration numbering when Phase 2 also wants to add a migration.** + - Candidate A: Phase 1 takes V12, Phase 2 takes V13. + - Candidate B: Phase 1 takes V12, Phase 2 re-shapes V12 to include its changes. + - **Recommendation: A.** Migrations are forward-only and append-only in this project. Phase 2 adds V13 (for `review_events` append-only table, if that lands in Phase 2 -- otherwise it is Phase 5 work). + +10. **Integration test crate location: sibling to `tests/e2e/` or inside `crates/vestige-core/tests/`.** + - Candidate A: new workspace member at `tests/phase_1/` (sibling to `tests/e2e/`). + - Candidate B: under `crates/vestige-core/tests/` (standard cargo integration-test layout). + - **Recommendation: A.** Matches the existing pattern of `tests/e2e/`, which is already a workspace member with its own `Cargo.toml`. Keeps the Phase 1 test binary outputs in a predictable location (`target/debug/deps/trait_round_trip-*`). Also avoids the build-graph cycle where `crates/vestige-core/tests/` would re-link everything under `vestige-core` each edit. + +### Critical Files for Implementation + +- /home/delandtj/prppl/vestige/crates/vestige-core/src/storage/memory_store.rs (new; contains the `LocalMemoryStore` / `MemoryStore` traits plus `MemoryRecord`, `SchedulingState`, `SearchQuery`, `SearchResult`, `MemoryEdge`, `Domain`, `ClassificationResult`, `StoreStats`, `HealthStatus`, `MemoryStoreError`, `ModelSignature`) +- /home/delandtj/prppl/vestige/crates/vestige-core/src/storage/sqlite.rs (rename `Storage` -> `SqliteMemoryStore`, add the `impl LocalMemoryStore` block and the `enforce_model` / `row_to_record` helpers; ~200 line diff on a 4592-line file) +- /home/delandtj/prppl/vestige/crates/vestige-core/src/storage/migrations.rs (append `Migration { version: 12, ... }` + `MIGRATION_V12_UP` constant; ~80 new lines) +- /home/delandtj/prppl/vestige/crates/vestige-core/src/embedder/mod.rs (new; `Embedder` + `LocalEmbedder` traits, `EmbedderError`, default `embed_batch`) +- /home/delandtj/prppl/vestige/crates/vestige-core/src/embedder/fastembed.rs (new; `FastembedEmbedder` implementation adapting the existing `EmbeddingService`) diff --git a/docs/plans/0002-phase-2-postgres-backend.md b/docs/plans/0002-phase-2-postgres-backend.md new file mode 100644 index 0000000..a372e27 --- /dev/null +++ b/docs/plans/0002-phase-2-postgres-backend.md @@ -0,0 +1,1269 @@ +# Phase 2 Plan: PostgreSQL Backend + +**Status**: Draft +**Depends on**: Phase 1 (MemoryStore + Embedder traits, embedding_model registry, domain columns) +**Related**: docs/adr/0001-pluggable-storage-and-network-access.md (Phase 2), docs/prd/001-getting-centralized-vestige.md + +--- + +## Scope + +### In scope + +- `PgMemoryStore` struct implementing the Phase 1 `MemoryStore` trait against `sqlx::PgPool`, including compile-time checked queries via `sqlx::query!` / `sqlx::query_as!`. +- First-class `pgvector` integration: typed `Vector` columns, HNSW index (`vector_cosine_ops`, `m = 16`, `ef_construction = 64`), and use of the cosine-distance operator `<=>`. +- First-class Postgres FTS: GENERATED `tsvector` column (`search_vec`) with `setweight` (A=content, B=node_type, C=tags), GIN index, and `websearch_to_tsquery` at query time. +- Hybrid search via Reciprocal Rank Fusion (RRF) expressed as a single SQL statement with CTEs for FTS and vector subqueries, with optional domain filter through array overlap (`&&`). +- sqlx migrations directory at `crates/vestige-core/migrations/postgres/`, numbered `{NNNN}_{name}.up.sql` / `{NNNN}_{name}.down.sql`, runnable by `sqlx::migrate!` at startup and by `sqlx-cli`. +- Offline query cache committed under `crates/vestige-core/.sqlx/` so a DATABASE_URL is not required at build time. +- Backend selection via `vestige.toml`: `[storage]` section with `backend = "sqlite" | "postgres"` plus the per-backend subsection (`[storage.sqlite]`, `[storage.postgres]`). Exclusive at compile time via `postgres-backend` feature, exclusive at runtime via the enum. +- CLI: `vestige migrate --from sqlite --to postgres --sqlite-path

--postgres-url ` -- streaming copy with progress output. +- CLI: `vestige migrate --reembed --model=` -- O(n) re-embed under a new `Embedder`, registry update, HNSW rebuild. +- Testcontainer-based integration tests using the `pgvector/pgvector:pg16` image, behind the `postgres-backend` feature so SQLite-only builds remain untouched. +- `PgMemoryStore` parity with `SqliteMemoryStore` across every public `MemoryStore` method defined in Phase 1. + +### Out of scope + +- Phase 3 (network access): HTTP MCP transport, API key auth, `vestige keys` CLI. The `api_keys` DDL is declared by Phase 3; Phase 2 does not create it. +- Phase 4 (emergent domain classification): `DomainClassifier`, HDBSCAN, discover / rename / merge CLI. Phase 2 provisions the `domains` and `domain_scores` columns and the `domains` table structure so Phase 4 slots in without further migration, but does not compute or classify. +- Phase 5 (federation): cross-node sync. The `review_events` table is declared in Phase 1; Phase 2 only references it where FSRS writes happen. +- Changes to the cognitive engine, Phase 1 traits, or the embedding pipeline itself. Phase 2 only adds a backend. +- SQLCipher parity for Postgres. Operator responsibility (TLS to Postgres, pgcrypto, disk-level encryption) is out of scope for this phase. + +--- + +## Prerequisites + +### Expected Phase 1 artifacts (consumed, not produced) + +Phase 2 treats all of the following as fixed interfaces. Each path is the expected Phase 1 location. + +- `crates/vestige-core/src/storage/mod.rs` -- re-exports the trait and the two concrete backends. +- `crates/vestige-core/src/storage/memory_store.rs` -- defines the `MemoryStore` trait (generated by `trait_variant::make` from `LocalMemoryStore`) with the full CRUD, search, FSRS, graph, and domain surface from the PRD. Phase 2 implements every method here. +- `crates/vestige-core/src/storage/types.rs` -- shared value types: `MemoryRecord`, `SchedulingState`, `SearchQuery`, `SearchResult`, `MemoryEdge`, `Domain`, `StoreStats`, `HealthStatus`. +- `crates/vestige-core/src/storage/error.rs` -- `StoreError` enum plus `pub type StoreResult = Result`. Phase 2 extends this with `StoreError::Postgres(sqlx::Error)` and `StoreError::Migrate(sqlx::migrate::MigrateError)` via `From` impls (the variants themselves MUST live behind `#[cfg(feature = "postgres-backend")]`). +- `crates/vestige-core/src/embedder/mod.rs` -- `Embedder` trait with `embed`, `model_name`, `dimension`, `model_hash`. Phase 2 calls `model_name()`, `dimension()`, and `model_hash()` for the registry. +- `crates/vestige-core/src/storage/sqlite.rs` -- `SqliteMemoryStore: MemoryStore`. Phase 2's `migrate --from sqlite --to postgres` uses this as the source. +- `crates/vestige-core/src/storage/registry.rs` -- `EmbeddingModelRegistry` abstraction that both backends implement. Phase 2 supplies a Postgres version writing to `embedding_model`. +- `crates/vestige-core/migrations/sqlite/` -- V12 (Phase 1) adds `domains TEXT` (JSON-encoded array), `domain_scores TEXT` (JSON), `embedding_model(name, dimension, hash, created_at)`, and `review_events(id, memory_id, timestamp, rating, prior_state, new_state)`. Phase 2 mirrors every column and table in Postgres. + +If any of the above is missing when Phase 2 starts, the first action is to surface the gap back to Phase 1 -- do NOT backfill a partial trait in Phase 2. + +### Required crates (declared in Phase 2, not installed by this doc) + +The agent running Phase 2 uses `cargo add` in `crates/vestige-core/` for each dependency below. Exact versions and feature flags: + +- `sqlx@0.8` with features `runtime-tokio`, `tls-rustls`, `postgres`, `uuid`, `chrono`, `json`, `migrate`, `macros`. Optional (gated by `postgres-backend`). +- `pgvector@0.4` with features `sqlx`. Optional (gated by `postgres-backend`). +- `deadpool` is NOT needed; `sqlx::PgPool` is the pool. +- `toml@0.8` (no features) for `vestige.toml` parsing. Moved to non-optional because both backends share the config surface. +- `figment@0.10` with features `toml`, `env` -- optional, only if Phase 1 has not already picked a config loader. If Phase 1 ships a loader, skip `figment` and reuse. +- `dirs@6` -- already a transitive `directories` dependency; reuse existing. +- `tokio-stream@0.1` (no features). Used by migrate commands for streamed iteration. +- `indicatif@0.17` (no features). Progress bars for the migrate CLI. +- `futures@0.3` with features `std`. Consumed by sqlx stream combinators. + +Dev-only (under `[dev-dependencies]` in `crates/vestige-core/Cargo.toml`, gated by `postgres-backend`): + +- `testcontainers@0.22` with features `blocking` off, `async` on (default). +- `testcontainers-modules@0.10` with features `postgres`. +- `tokio@1` features `macros`, `rt-multi-thread` (already present for core tests). +- `criterion@0.5` already present; add a new `[[bench]]` entry. + +Feature additions in `crates/vestige-core/Cargo.toml`: + +``` +[features] +postgres-backend = ["dep:sqlx", "dep:pgvector", "dep:tokio-stream", "dep:futures"] +``` + +`postgres-backend` is OFF by default. `default = ["embeddings", "vector-search", "bundled-sqlite"]` stays unchanged. `vestige-mcp` forwards a new feature `postgres-backend = ["vestige-core/postgres-backend"]`. + +### External tooling + +- PostgreSQL 16 or newer (uses `gen_random_uuid()` from `pgcrypto` bundled via `CREATE EXTENSION pgcrypto` in migration 0001; pgvector HNSW indexes require pgvector 0.5+). +- The `pgvector` extension installed in the target database (our migration issues `CREATE EXTENSION IF NOT EXISTS vector`). +- `sqlx-cli@0.8` installed on the developer machine for `cargo sqlx prepare --workspace` and `cargo sqlx migrate add` (not a build-time requirement once `.sqlx/` is committed). +- Docker or Podman reachable by the test harness for `testcontainers-modules::postgres` to spin up `pgvector/pgvector:pg16`. + +### Assumed Rust toolchain + +- Rust 2024 edition. +- MSRV 1.91 (per `CLAUDE.md`). `sqlx 0.8` is compatible. +- `rustflags` unchanged. No `nightly`-only features. + +--- + +## Deliverables + +1. Feature gate `postgres-backend` in `crates/vestige-core/Cargo.toml` and `crates/vestige-mcp/Cargo.toml` that cleanly disables all Postgres code paths when off. +2. `crates/vestige-core/src/storage/postgres/mod.rs` -- `PgMemoryStore` struct and `MemoryStore` trait impl (public entry point). +3. `crates/vestige-core/src/storage/postgres/pool.rs` -- `PgMemoryStore::connect(config)` and pool configuration. +4. `crates/vestige-core/src/storage/postgres/search.rs` -- RRF hybrid search query builder and row -> `SearchResult` mapping. +5. `crates/vestige-core/src/storage/postgres/migrations.rs` -- wraps `sqlx::migrate!("./migrations/postgres")` and surfaces typed errors. +6. `crates/vestige-core/src/storage/postgres/registry.rs` -- Postgres `EmbeddingModelRegistry` implementation writing `embedding_model`. +7. `crates/vestige-core/migrations/postgres/0001_init.up.sql` + `0001_init.down.sql` -- extensions, `memories`, `scheduling`, `edges`, `domains`, `embedding_model`, `review_events`, all indexes. +8. `crates/vestige-core/migrations/postgres/0002_hnsw.up.sql` + `0002_hnsw.down.sql` -- HNSW index creation separated so it can be `CREATE INDEX CONCURRENTLY` during reembed. +9. `crates/vestige-core/src/config.rs` -- `VestigeConfig`, `StorageConfig`, `SqliteConfig`, `PostgresConfig`, `EmbeddingsConfig`, plus a single `VestigeConfig::load(path: Option<&Path>)` returning `Result`. +10. `crates/vestige-core/src/storage/postgres/migrate_cli.rs` -- streaming SQLite-to-Postgres copy, domain-aware, with `indicatif` progress. +11. `crates/vestige-core/src/storage/postgres/reembed.rs` -- `ReembedPlan` and its driver; re-encodes all memories via a supplied `Embedder`, updates `embedding_model`, rebuilds HNSW. +12. `crates/vestige-mcp/src/bin/cli.rs` -- two new `clap` subcommands `Migrate` (union of `--from/--to` and `--reembed` variants, one subcommand or two, see Open Questions) wired to deliverables 10 and 11. +13. `crates/vestige-core/.sqlx/` -- offline query cache, committed. +14. `tests/phase_2/` -- six integration test files listed in the Test Plan. +15. `crates/vestige-core/benches/pg_hybrid_search.rs` -- Criterion benches for RRF search at 1k and 100k memories, gated by `postgres-backend`. +16. `docs/runbook/postgres.md` -- brief ops note covering extension install, `max_connections`, backup discipline, and rollback caveats. (Short; only required for the "rollback of migrate" deliverable.) + +--- + +## Detailed Task Breakdown + +### D1. `postgres-backend` feature gate + +- **File**: `crates/vestige-core/Cargo.toml`, `crates/vestige-mcp/Cargo.toml` +- **Depends on**: nothing; this is the first change. +- **Rust snippets**: + +```toml +# crates/vestige-core/Cargo.toml +[features] +default = ["embeddings", "vector-search", "bundled-sqlite"] +bundled-sqlite = ["rusqlite/bundled"] +encryption = ["rusqlite/bundled-sqlcipher"] +postgres-backend = [ + "dep:sqlx", + "dep:pgvector", + "dep:tokio-stream", + "dep:futures", +] + +[dependencies] +sqlx = { version = "0.8", default-features = false, features = [ + "runtime-tokio", "tls-rustls", "postgres", "uuid", "chrono", + "json", "migrate", "macros", +], optional = true } +pgvector = { version = "0.4", features = ["sqlx"], optional = true } +tokio-stream = { version = "0.1", optional = true } +futures = { version = "0.3", optional = true } +toml = "0.8" +indicatif = "0.17" +``` + +- **Behavior notes**: keep the two backends mutually compilable per `CLAUDE.md`. Every `use sqlx::...` sits under `#[cfg(feature = "postgres-backend")]`. Every module under `crates/vestige-core/src/storage/postgres/` carries `#![cfg(feature = "postgres-backend")]` as its file-level attribute. + +### D2. `PgMemoryStore` core struct + +- **File**: `crates/vestige-core/src/storage/postgres/mod.rs` +- **Depends on**: D1, Phase 1 `MemoryStore` trait and value types. +- **Signatures**: + +```rust +#![cfg(feature = "postgres-backend")] + +use std::sync::Arc; +use std::time::Duration; + +use chrono::{DateTime, Utc}; +use pgvector::Vector; +use sqlx::postgres::{PgConnectOptions, PgPoolOptions}; +use sqlx::PgPool; +use uuid::Uuid; + +use crate::embedder::Embedder; +use crate::storage::error::{StoreError, StoreResult}; +use crate::storage::types::{ + Domain, HealthStatus, MemoryEdge, MemoryRecord, SchedulingState, + SearchQuery, SearchResult, StoreStats, +}; +use crate::storage::memory_store::LocalMemoryStore; + +pub mod migrations; +pub mod pool; +pub mod registry; +pub mod search; +pub mod migrate_cli; +pub mod reembed; + +/// Postgres-backed implementation of `MemoryStore`. +/// +/// Cheaply cloneable. Methods take `&self`; interior state lives inside +/// the `PgPool` (which already provides `Sync` via `Arc` internally). +#[derive(Clone)] +pub struct PgMemoryStore { + pool: PgPool, + embedding_dim: i32, + embedding_model: Arc, +} + +#[derive(Debug, Clone)] +pub struct EmbeddingModelDescriptor { + pub name: String, + pub dimension: i32, + pub hash: String, +} + +impl PgMemoryStore { + /// Construct a new store. Runs migrations, reads the registry, validates + /// that the embedder matches the registered model. + pub async fn connect( + url: &str, + max_connections: u32, + embedder: &dyn Embedder, + ) -> StoreResult; + + /// Low-level constructor for tests: supply an existing pool, skip migrate. + pub async fn from_pool( + pool: PgPool, + embedder: &dyn Embedder, + ) -> StoreResult; + + /// Accessor used by migrate/reembed CLI. + pub fn pool(&self) -> &PgPool { &self.pool } + + pub fn embedding_dim(&self) -> i32 { self.embedding_dim } +} + +#[trait_variant::make(crate::storage::memory_store::MemoryStore: Send)] +impl LocalMemoryStore for PgMemoryStore { + async fn init(&self) -> StoreResult<()>; + async fn health_check(&self) -> StoreResult; + + async fn insert(&self, record: &MemoryRecord) -> StoreResult; + async fn get(&self, id: Uuid) -> StoreResult>; + async fn update(&self, record: &MemoryRecord) -> StoreResult<()>; + async fn delete(&self, id: Uuid) -> StoreResult<()>; + + async fn search(&self, query: &SearchQuery) -> StoreResult>; + async fn fts_search(&self, text: &str, limit: usize) -> StoreResult>; + async fn vector_search(&self, embedding: &[f32], limit: usize) -> StoreResult>; + + async fn get_scheduling(&self, memory_id: Uuid) -> StoreResult>; + async fn update_scheduling(&self, state: &SchedulingState) -> StoreResult<()>; + async fn get_due_memories( + &self, + before: DateTime, + limit: usize, + ) -> StoreResult>; + + async fn add_edge(&self, edge: &MemoryEdge) -> StoreResult<()>; + async fn get_edges(&self, node_id: Uuid, edge_type: Option<&str>) -> StoreResult>; + async fn remove_edge(&self, source: Uuid, target: Uuid, edge_type: &str) -> StoreResult<()>; + async fn get_neighbors(&self, node_id: Uuid, depth: usize) -> StoreResult>; + + async fn list_domains(&self) -> StoreResult>; + async fn get_domain(&self, id: &str) -> StoreResult>; + async fn upsert_domain(&self, domain: &Domain) -> StoreResult<()>; + async fn delete_domain(&self, id: &str) -> StoreResult<()>; + async fn classify(&self, embedding: &[f32]) -> StoreResult>; + + async fn count(&self) -> StoreResult; + async fn get_stats(&self) -> StoreResult; + async fn vacuum(&self) -> StoreResult<()>; +} +``` + +- **SQL (inline within impl methods)**: every call uses `sqlx::query!` or `sqlx::query_as!` for compile-time validation. Examples: + +```rust +// insert +sqlx::query!( + r#" + INSERT INTO memories ( + id, domains, domain_scores, content, node_type, tags, + embedding, metadata, created_at, updated_at + ) VALUES ($1, $2, $3, $4, $5, $6, $7::vector, $8, $9, $10) + "#, + record.id, + &record.domains as &[String], + serde_json::to_value(&record.domain_scores)?, + record.content, + record.node_type, + &record.tags as &[String], + record.embedding.as_ref().map(|v| Vector::from(v.clone())) as Option, + record.metadata, + record.created_at, + record.updated_at, +) +.execute(&self.pool) +.await?; +``` + +- **Behavior notes**: + - `StoreError` gets two new variants behind the feature: + +```rust +#[cfg(feature = "postgres-backend")] +#[error("postgres error: {0}")] +Postgres(#[from] sqlx::Error), + +#[cfg(feature = "postgres-backend")] +#[error("postgres migration error: {0}")] +Migrate(#[from] sqlx::migrate::MigrateError), +``` + + - `classify()` on Postgres implements the PRD's cosine-similarity-to-centroid computation inside SQL using `1 - (centroid <=> $1::vector)` over the `domains` table and returns rows sorted descending. This mirrors the behavior a `DomainClassifier` in Phase 4 uses; Phase 2 ships the backend capability but does not call it. + - Connection pool defaults (see D3): `max_connections = 10`, `acquire_timeout = 30s`, `idle_timeout = 600s`, `test_before_acquire = false` (cheap queries; avoid per-acquire roundtrip). + - All methods are `async fn` and use sqlx's `tokio` runtime feature; no blocking `block_on`. + +### D3. Pool construction and config wiring + +- **File**: `crates/vestige-core/src/storage/postgres/pool.rs` +- **Depends on**: D1, D2, D9. +- **Signatures**: + +```rust +#![cfg(feature = "postgres-backend")] + +use sqlx::postgres::{PgConnectOptions, PgPoolOptions}; +use sqlx::{ConnectOptions, PgPool}; +use std::str::FromStr; +use std::time::Duration; + +use crate::config::PostgresConfig; +use crate::storage::error::{StoreError, StoreResult}; + +pub async fn build_pool(cfg: &PostgresConfig) -> StoreResult { + let mut opts = PgConnectOptions::from_str(&cfg.url)?; + opts = opts + .application_name("vestige") + .statement_cache_capacity(256) + .log_statements(tracing::log::LevelFilter::Debug); + + let pool = PgPoolOptions::new() + .max_connections(cfg.max_connections.unwrap_or(10)) + .min_connections(0) + .acquire_timeout(Duration::from_secs(cfg.acquire_timeout_secs.unwrap_or(30))) + .idle_timeout(Some(Duration::from_secs(600))) + .max_lifetime(Some(Duration::from_secs(1800))) + .test_before_acquire(false) + .connect_with(opts) + .await?; + + Ok(pool) +} +``` + +- **Behavior notes**: acquire timeout chosen to exceed the 30-second testcontainer spin-up requirement. `application_name = "vestige"` makes `pg_stat_activity` readable from `psql` during debugging. + +### D4. sqlx migrations directory + +- **File**: `crates/vestige-core/migrations/postgres/0001_init.up.sql`, `0001_init.down.sql`, `0002_hnsw.up.sql`, `0002_hnsw.down.sql`. +- **Depends on**: none (pure SQL). + +`0001_init.up.sql`: + +```sql +-- Extensions +CREATE EXTENSION IF NOT EXISTS pgcrypto; +CREATE EXTENSION IF NOT EXISTS vector; + +-- Embedding model registry +-- Mirrors the SQLite table created in Phase 1. +CREATE TABLE embedding_model ( + id SMALLINT PRIMARY KEY DEFAULT 1 CHECK (id = 1), + name TEXT NOT NULL, + dimension INTEGER NOT NULL CHECK (dimension > 0), + hash TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +-- Domains table (populated by Phase 4 DomainClassifier; Phase 2 only creates +-- the empty table so list/get/upsert/delete work against both backends). +CREATE TABLE domains ( + id TEXT PRIMARY KEY, + label TEXT NOT NULL, + centroid vector, + top_terms TEXT[] NOT NULL DEFAULT '{}', + memory_count INTEGER NOT NULL DEFAULT 0, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + metadata JSONB NOT NULL DEFAULT '{}'::jsonb +); + +-- Core memories table +CREATE TABLE memories ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + domains TEXT[] NOT NULL DEFAULT '{}', + domain_scores JSONB NOT NULL DEFAULT '{}'::jsonb, + content TEXT NOT NULL, + node_type TEXT NOT NULL DEFAULT 'general', + tags TEXT[] NOT NULL DEFAULT '{}', + embedding vector, + metadata JSONB NOT NULL DEFAULT '{}'::jsonb, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + search_vec TSVECTOR GENERATED ALWAYS AS ( + setweight(to_tsvector('english', coalesce(content, '')), 'A') || + setweight(to_tsvector('english', coalesce(node_type, '')), 'B') || + setweight(to_tsvector('english', coalesce(array_to_string(tags, ' '), '')), 'C') + ) STORED +); + +-- FSRS scheduling state (1:1 with memories) +CREATE TABLE scheduling ( + memory_id UUID PRIMARY KEY REFERENCES memories(id) ON DELETE CASCADE, + stability DOUBLE PRECISION NOT NULL DEFAULT 0.0, + difficulty DOUBLE PRECISION NOT NULL DEFAULT 0.0, + retrievability DOUBLE PRECISION NOT NULL DEFAULT 1.0, + last_review TIMESTAMPTZ, + next_review TIMESTAMPTZ, + reps INTEGER NOT NULL DEFAULT 0, + lapses INTEGER NOT NULL DEFAULT 0 +); + +-- Graph edges (spreading activation) +CREATE TABLE edges ( + source_id UUID NOT NULL REFERENCES memories(id) ON DELETE CASCADE, + target_id UUID NOT NULL REFERENCES memories(id) ON DELETE CASCADE, + edge_type TEXT NOT NULL DEFAULT 'related', + weight DOUBLE PRECISION NOT NULL DEFAULT 1.0, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + PRIMARY KEY (source_id, target_id, edge_type) +); + +-- FSRS review event log (Phase 1 creates this; Phase 2 mirrors it for Postgres). +-- Append-only. Used for future federation (Phase 5). +CREATE TABLE review_events ( + id BIGSERIAL PRIMARY KEY, + memory_id UUID NOT NULL REFERENCES memories(id) ON DELETE CASCADE, + timestamp TIMESTAMPTZ NOT NULL DEFAULT now(), + rating SMALLINT NOT NULL, + prior_state JSONB NOT NULL, + new_state JSONB NOT NULL +); + +-- Indexes on memories (vector index is declared separately in 0002_hnsw.up.sql) +CREATE INDEX idx_memories_fts ON memories USING GIN (search_vec); +CREATE INDEX idx_memories_domains ON memories USING GIN (domains); +CREATE INDEX idx_memories_tags ON memories USING GIN (tags); +CREATE INDEX idx_memories_node_type ON memories (node_type); +CREATE INDEX idx_memories_created ON memories (created_at); +CREATE INDEX idx_memories_updated ON memories (updated_at); + +-- Indexes on scheduling +CREATE INDEX idx_scheduling_next_review ON scheduling (next_review); +CREATE INDEX idx_scheduling_last_review ON scheduling (last_review); + +-- Indexes on edges +CREATE INDEX idx_edges_target ON edges (target_id); +CREATE INDEX idx_edges_source ON edges (source_id); +CREATE INDEX idx_edges_type ON edges (edge_type); + +-- Indexes on review_events +CREATE INDEX idx_review_events_memory ON review_events (memory_id); +CREATE INDEX idx_review_events_ts ON review_events (timestamp); + +-- Update trigger on memories.updated_at +CREATE OR REPLACE FUNCTION memories_set_updated_at() RETURNS TRIGGER AS $$ +BEGIN + NEW.updated_at := now(); + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_memories_updated_at +BEFORE UPDATE ON memories +FOR EACH ROW EXECUTE FUNCTION memories_set_updated_at(); +``` + +`0001_init.down.sql`: + +```sql +DROP TRIGGER IF EXISTS trg_memories_updated_at ON memories; +DROP FUNCTION IF EXISTS memories_set_updated_at(); + +DROP INDEX IF EXISTS idx_review_events_ts; +DROP INDEX IF EXISTS idx_review_events_memory; +DROP INDEX IF EXISTS idx_edges_type; +DROP INDEX IF EXISTS idx_edges_source; +DROP INDEX IF EXISTS idx_edges_target; +DROP INDEX IF EXISTS idx_scheduling_last_review; +DROP INDEX IF EXISTS idx_scheduling_next_review; +DROP INDEX IF EXISTS idx_memories_updated; +DROP INDEX IF EXISTS idx_memories_created; +DROP INDEX IF EXISTS idx_memories_node_type; +DROP INDEX IF EXISTS idx_memories_tags; +DROP INDEX IF EXISTS idx_memories_domains; +DROP INDEX IF EXISTS idx_memories_fts; + +DROP TABLE IF EXISTS review_events; +DROP TABLE IF EXISTS edges; +DROP TABLE IF EXISTS scheduling; +DROP TABLE IF EXISTS memories; +DROP TABLE IF EXISTS domains; +DROP TABLE IF EXISTS embedding_model; +``` + +`0002_hnsw.up.sql` (separated so reembed can drop-and-recreate without touching the rest of the schema): + +```sql +-- HNSW index on memories.embedding. +-- pgvector requires the column to have a typmod (fixed dimension) for HNSW. +-- The dimension is stamped by the application at startup via ALTER TABLE +-- using the embedder's dimension() method (see PgMemoryStore::connect). +-- We express the index with the generic vector_cosine_ops operator class. +CREATE INDEX idx_memories_embedding_hnsw + ON memories USING hnsw (embedding vector_cosine_ops) + WITH (m = 16, ef_construction = 64); +``` + +`0002_hnsw.down.sql`: + +```sql +DROP INDEX IF EXISTS idx_memories_embedding_hnsw; +``` + +- **Behavior notes**: + - pgvector HNSW requires a typmod. `PgMemoryStore::connect` runs `ALTER TABLE memories ALTER COLUMN embedding TYPE vector($N)` with `$N = embedder.dimension()` exactly once, guarded by a check against `embedding_model` (first startup ever) or validated against it on subsequent starts. If `embedder.dimension()` differs from the stored one and `embedding_model` is non-empty, return `StoreError::EmbeddingDimensionMismatch` -- the user must run `vestige migrate --reembed`. + - `ALTER COLUMN ... TYPE vector($N)` on a populated column fails unless the data fits; that is the desired safety net. + - The `tsvector` GENERATED column uses `array_to_string(tags, ' ')` rather than `array_to_tsvector` from the PRD sketch, because `array_to_tsvector` is not a core function in Postgres 16 and would require an extension. The behavior is equivalent for weight C. + - `gen_random_uuid()` comes from `pgcrypto`. In Postgres 13+ it is also available from core; we keep the extension for older compatibility paths. + - MVCC: all table writes are transactional; no explicit locks. `INSERT ... ON CONFLICT DO UPDATE` is used in `upsert_domain`, `update_scheduling`, and edge idempotency. + +### D5. Hybrid search via RRF + +- **File**: `crates/vestige-core/src/storage/postgres/search.rs` +- **Depends on**: D2, D4. +- **Signatures**: + +```rust +#![cfg(feature = "postgres-backend")] + +use pgvector::Vector; +use sqlx::PgPool; +use uuid::Uuid; + +use crate::storage::error::StoreResult; +use crate::storage::types::{SearchQuery, SearchResult}; + +const RRF_K: i32 = 60; // constant from Cormack et al. 2009 +const OVERFETCH_MULT: i64 = 3; // matches Phase 1 SQLite overfetch + +pub(crate) async fn rrf_search( + pool: &PgPool, + query: &SearchQuery, +) -> StoreResult>; +``` + +SQL for the full hybrid RRF query. Placeholders: +- `$1` = text query (string, may be empty) +- `$2` = embedding (vector) +- `$3` = overfetch limit per branch (int) +- `$4` = final limit (int) +- `$5` = domain filter (text[] or NULL) +- `$6` = node_type filter (text[] or NULL) +- `$7` = tag filter (text[] or NULL) + +```sql +WITH params AS ( + SELECT + $1::text AS q_text, + $2::vector AS q_vec, + $3::int AS overfetch, + $4::int AS final_limit, + $5::text[] AS dom_filter, + $6::text[] AS nt_filter, + $7::text[] AS tag_filter +), +fts AS ( + SELECT m.id, + ts_rank_cd(m.search_vec, websearch_to_tsquery('english', p.q_text)) AS score, + ROW_NUMBER() OVER ( + ORDER BY ts_rank_cd(m.search_vec, websearch_to_tsquery('english', p.q_text)) DESC + ) AS rank + FROM memories m, params p + WHERE p.q_text <> '' + AND m.search_vec @@ websearch_to_tsquery('english', p.q_text) + AND (p.dom_filter IS NULL OR m.domains && p.dom_filter) + AND (p.nt_filter IS NULL OR m.node_type = ANY(p.nt_filter)) + AND (p.tag_filter IS NULL OR m.tags && p.tag_filter) + LIMIT (SELECT overfetch FROM params) +), +vec AS ( + SELECT m.id, + 1 - (m.embedding <=> p.q_vec) AS score, + ROW_NUMBER() OVER ( + ORDER BY m.embedding <=> p.q_vec + ) AS rank + FROM memories m, params p + WHERE m.embedding IS NOT NULL + AND p.q_vec IS NOT NULL + AND (p.dom_filter IS NULL OR m.domains && p.dom_filter) + AND (p.nt_filter IS NULL OR m.node_type = ANY(p.nt_filter)) + AND (p.tag_filter IS NULL OR m.tags && p.tag_filter) + LIMIT (SELECT overfetch FROM params) +), +fused AS ( + SELECT COALESCE(f.id, v.id) AS id, + COALESCE(1.0 / (60 + f.rank), 0.0) + + COALESCE(1.0 / (60 + v.rank), 0.0) AS rrf_score, + f.score AS fts_score, + v.score AS vector_score + FROM fts f FULL OUTER JOIN vec v ON f.id = v.id +) +SELECT m.id AS "id!: Uuid", + m.domains AS "domains!: Vec", + m.domain_scores AS "domain_scores!: serde_json::Value", + m.content AS "content!", + m.node_type AS "node_type!", + m.tags AS "tags!: Vec", + m.embedding AS "embedding?: Vector", + m.metadata AS "metadata!: serde_json::Value", + m.created_at AS "created_at!: chrono::DateTime", + m.updated_at AS "updated_at!: chrono::DateTime", + fused.rrf_score AS "rrf_score!: f64", + fused.fts_score AS "fts_score?: f64", + fused.vector_score AS "vector_score?: f64" +FROM fused +JOIN memories m ON m.id = fused.id +ORDER BY fused.rrf_score DESC +LIMIT (SELECT final_limit FROM params); +``` + +- **Behavior notes**: + - `OVERFETCH_MULT * query.limit` is passed as `$3`. Final `$4` is `query.limit`. + - Empty text query is allowed; the `fts` CTE returns zero rows (`p.q_text <> ''`) and the result degrades to pure vector search, which matches `vector_search` behavior. + - Null embedding is allowed; the `vec` CTE returns zero rows and the result degrades to pure FTS, which matches `fts_search` behavior. + - `fts_search` and `vector_search` are separate public methods on the trait. Each uses a simpler single-CTE query derived from the above by removing the other branch. Implementing them as thin wrappers over `rrf_search` with nullified inputs is acceptable but adds one extra plan per call; the explicit implementations win on latency. + - `min_retrievability` in `SearchQuery` is applied as a final filter by joining on `scheduling` in the outer `SELECT`. Adding that join unconditionally regresses simple searches; add it only when `query.min_retrievability.is_some()`. + +### D6. `embedding_model` registry impl + +- **File**: `crates/vestige-core/src/storage/postgres/registry.rs` +- **Depends on**: D1, D4 (table exists), Phase 1 `EmbeddingModelRegistry` trait. +- **Signatures**: + +```rust +#![cfg(feature = "postgres-backend")] + +use sqlx::PgPool; + +use crate::embedder::Embedder; +use crate::storage::error::{StoreError, StoreResult}; + +pub(crate) async fn ensure_registry( + pool: &PgPool, + embedder: &dyn Embedder, +) -> StoreResult<()> { + let row = sqlx::query!( + r#"SELECT name, dimension, hash FROM embedding_model WHERE id = 1"# + ) + .fetch_optional(pool) + .await?; + + match row { + None => { + sqlx::query!( + r#" + INSERT INTO embedding_model (id, name, dimension, hash) + VALUES (1, $1, $2, $3) + "#, + embedder.model_name(), + embedder.dimension() as i32, + embedder.model_hash(), + ) + .execute(pool) + .await?; + + // First-ever run: stamp the vector column typmod. + let ddl = format!( + "ALTER TABLE memories ALTER COLUMN embedding TYPE vector({})", + embedder.dimension() + ); + sqlx::query(&ddl).execute(pool).await?; + Ok(()) + } + Some(r) if r.name == embedder.model_name() + && r.dimension == embedder.dimension() as i32 + && r.hash == embedder.model_hash() => Ok(()), + Some(r) => Err(StoreError::EmbeddingMismatch { + expected: format!("{} ({}d, {})", r.name, r.dimension, r.hash), + got: format!( + "{} ({}d, {})", + embedder.model_name(), + embedder.dimension(), + embedder.model_hash() + ), + }), + } +} + +pub(crate) async fn update_registry( + pool: &PgPool, + embedder: &dyn Embedder, +) -> StoreResult<()> { + // Used only by `vestige migrate --reembed` after a full re-encode. + sqlx::query!( + r#" + UPDATE embedding_model + SET name = $1, dimension = $2, hash = $3, created_at = now() + WHERE id = 1 + "#, + embedder.model_name(), + embedder.dimension() as i32, + embedder.model_hash(), + ) + .execute(pool) + .await?; + Ok(()) +} +``` + +- **Behavior notes**: + - `StoreError::EmbeddingMismatch { expected, got }` already exists in Phase 1; Phase 2 just constructs it. + - The `ALTER TABLE ... TYPE vector(N)` DDL is only issued on first init. On subsequent inits the existing typmod already matches. + - Re-embed flow also uses this module, but the DDL path is different -- see D11. + +### D7. `VestigeConfig`: `vestige.toml` backend selection + +- **File**: `crates/vestige-core/src/config.rs` (Phase 1 may already own this file; Phase 2 extends, not replaces) +- **Depends on**: D1. +- **Signatures**: + +```rust +use std::path::{Path, PathBuf}; + +use serde::Deserialize; + +#[derive(Debug, Clone, Deserialize)] +pub struct VestigeConfig { + #[serde(default)] + pub embeddings: EmbeddingsConfig, + #[serde(default)] + pub storage: StorageConfig, + #[serde(default)] + pub server: ServerConfig, + #[serde(default)] + pub auth: AuthConfig, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct EmbeddingsConfig { + pub provider: String, // "fastembed" + pub model: String, // "BAAI/bge-base-en-v1.5" +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(tag = "backend", rename_all = "lowercase")] +pub enum StorageConfig { + Sqlite(SqliteConfig), + #[cfg(feature = "postgres-backend")] + Postgres(PostgresConfig), +} + +#[derive(Debug, Clone, Deserialize)] +pub struct SqliteConfig { + pub path: PathBuf, +} + +#[cfg(feature = "postgres-backend")] +#[derive(Debug, Clone, Deserialize)] +pub struct PostgresConfig { + pub url: String, + #[serde(default)] + pub max_connections: Option, + #[serde(default)] + pub acquire_timeout_secs: Option, +} + +#[derive(Debug, Clone, Default, Deserialize)] +pub struct ServerConfig { /* Phase 3 fills this in */ } + +#[derive(Debug, Clone, Default, Deserialize)] +pub struct AuthConfig { /* Phase 3 fills this in */ } + +impl VestigeConfig { + pub fn load(path: Option<&Path>) -> Result; + pub fn default_path() -> PathBuf; // ~/.vestige/vestige.toml +} + +#[derive(Debug, thiserror::Error)] +pub enum ConfigError { + #[error("io: {0}")] + Io(#[from] std::io::Error), + #[error("toml: {0}")] + Toml(#[from] toml::de::Error), + #[error("invalid config: {0}")] + Invalid(String), +} +``` + +- **Behavior notes**: + - The serde representation matches the PRD: `[storage]` with `backend = "sqlite"` and a matching `[storage.sqlite]` or `[storage.postgres]` subsection. + - Because `StorageConfig` is `#[serde(tag = "backend")]`, an unknown backend string returns a clear error. + - If `postgres-backend` is compiled off and the user writes `backend = "postgres"`, deserialization returns "unknown variant `postgres`" -- loud failure. Phase 2 wraps this into `ConfigError::Invalid("postgres-backend feature not compiled in")`. + - `env`-override hooks (e.g., `VESTIGE_POSTGRES_URL`) are a Phase 3 concern; not added here. + +### D8. `vestige migrate --from sqlite --to postgres` + +- **File**: `crates/vestige-core/src/storage/postgres/migrate_cli.rs` +- **Depends on**: D2, D6, D7, Phase 1 `SqliteMemoryStore`. +- **Signatures**: + +```rust +#![cfg(feature = "postgres-backend")] + +use std::path::Path; +use std::sync::Arc; + +use futures::{StreamExt, TryStreamExt}; +use indicatif::{ProgressBar, ProgressStyle}; +use uuid::Uuid; + +use crate::embedder::Embedder; +use crate::storage::error::{StoreError, StoreResult}; +use crate::storage::postgres::PgMemoryStore; +use crate::storage::sqlite::SqliteMemoryStore; + +#[derive(Debug, Clone)] +pub struct SqliteToPostgresPlan { + pub sqlite_path: std::path::PathBuf, + pub postgres_url: String, + pub max_connections: u32, + pub batch_size: usize, // default 500 +} + +pub struct MigrationReport { + pub memories_copied: u64, + pub scheduling_rows: u64, + pub edges_copied: u64, + pub review_events_copied: u64, + pub domains_copied: u64, + pub errors: Vec<(Uuid, StoreError)>, +} + +pub async fn run_sqlite_to_postgres( + plan: SqliteToPostgresPlan, + embedder: Arc, +) -> StoreResult; +``` + +Algorithm: + +1. Open source `SqliteMemoryStore` in read-only mode (`?mode=ro`). +2. Check source `embedding_model` registry; refuse if it disagrees with the supplied embedder unless the user also passed `--reembed`. +3. Open destination `PgMemoryStore` via `connect` (runs migrations, stamps dim). +4. Stream source rows in batches of `plan.batch_size` via a windowed query ordered by `created_at, id` (stable cursor; survives resume). +5. For each batch: begin a Postgres transaction, `INSERT INTO memories ... ON CONFLICT (id) DO NOTHING` for all rows, `INSERT INTO scheduling` likewise, commit. Copy domain assignments (`domains`, `domain_scores`) verbatim -- they are `[]` and `{}` for pre-Phase-4 SQLite data. +6. After memories finish, stream edges and review_events the same way. +7. Emit progress via `indicatif::ProgressBar` (one bar per table, multi-bar). Each 1000 rows log to tracing at INFO. +8. Return `MigrationReport` for the caller to print. + +- **Behavior notes**: + - Memory-bounded: batch size 500 and sqlx streams mean memory usage stays O(batch * row_size), not O(total_rows). + - Idempotent: re-running replays only the rows not already present; `ON CONFLICT DO NOTHING` means partial runs recover. + - UUID strings from SQLite are parsed via `Uuid::parse_str` -- any mangled ID pushes to `errors` instead of aborting. + - The FTS `search_vec` is regenerated by Postgres via the GENERATED column; no data to copy. + - `review_events` may not exist in Phase 1 SQLite for pre-V12 databases. The migrator detects missing tables via `SELECT name FROM sqlite_master` and skips gracefully. + - A separate `--dry-run` flag prints the counts per table without writing. + +### D9. `vestige migrate --reembed --model=` + +- **File**: `crates/vestige-core/src/storage/postgres/reembed.rs` +- **Depends on**: D2, D6, Phase 1 `Embedder`. +- **Signatures**: + +```rust +#![cfg(feature = "postgres-backend")] + +use std::sync::Arc; +use std::time::Instant; + +use futures::TryStreamExt; +use indicatif::{ProgressBar, ProgressStyle}; +use sqlx::PgPool; +use uuid::Uuid; + +use crate::embedder::Embedder; +use crate::storage::error::{StoreError, StoreResult}; +use crate::storage::postgres::PgMemoryStore; + +#[derive(Debug, Clone)] +pub struct ReembedPlan { + pub batch_size: usize, // default 128 (embedder batch) + pub drop_hnsw_first: bool, // default true + pub concurrent_index: bool, // default false; use CREATE INDEX (not CONCURRENTLY) +} + +pub struct ReembedReport { + pub rows_updated: u64, + pub duration_secs: f64, + pub index_rebuild_secs: f64, +} + +pub async fn run_reembed( + store: &PgMemoryStore, + new_embedder: Arc, + plan: ReembedPlan, +) -> StoreResult; +``` + +Algorithm: + +1. Verify `new_embedder.dimension()` != stored dimension OR `new_embedder.model_hash()` != stored hash -- otherwise no-op and return `rows_updated = 0`. +2. `BEGIN; ALTER TABLE memories ALTER COLUMN embedding DROP NOT NULL`; not actually needed (column is already nullable) but shown here for documentation. +3. If `plan.drop_hnsw_first`, execute `DROP INDEX IF EXISTS idx_memories_embedding_hnsw;` so updates are not slowed by index maintenance. This is the recommended path; `REINDEX` is kept in the Open Questions as an alternative. +4. Stream all `id, content` from `memories` ordered by `id`. +5. For each batch of `plan.batch_size`: call `new_embedder.embed_batch(&texts)` (Phase 1 trait exposes batched embedding when available; otherwise loop single `embed`). Then: + +```sql +UPDATE memories +SET embedding = v.embedding::vector +FROM UNNEST($1::uuid[], $2::real[][]) AS v(id, embedding) +WHERE memories.id = v.id; +``` + +6. After all rows updated: run `ALTER TABLE memories ALTER COLUMN embedding TYPE vector($NEW_DIM)` if dimension changed. +7. Rebuild HNSW. If `plan.concurrent_index`, execute `CREATE INDEX CONCURRENTLY idx_memories_embedding_hnsw ...`; else `CREATE INDEX idx_memories_embedding_hnsw ...`. +8. `update_registry` with the new embedder. +9. Return `ReembedReport`. + +- **Behavior notes**: + - Memory-bounded: batch_size * 2 (old + new texts) vectors in RAM at any time. + - The dimension change must happen AFTER all rows are updated (pgvector validates typmod on write when a typmod is present; we relax-then-tighten). + - `CONCURRENTLY` builds do not hold `AccessExclusiveLock`, but fail inside a transaction. That's why the outer driver runs index DDL as an autocommit statement (sqlx `execute` outside a pool transaction). + - For `--dry-run`, emit what *would* happen (row count, estimated embedder calls, estimated time using `rows / 50`-per-second baseline for local fastembed) and exit. + +### D10. CLI wiring in `vestige-mcp` + +- **File**: `crates/vestige-mcp/src/bin/cli.rs` +- **Depends on**: D8, D9, D7. Requires `vestige-mcp` Cargo feature `postgres-backend`. +- **Signatures**: + +```rust +#[derive(Subcommand)] +enum Commands { + // existing variants: Stats, Health, Consolidate, Restore, Backup, + // Export, Gc, Dashboard, Ingest, Serve ... + + /// Migrate between backends or re-embed memories. + #[cfg(feature = "postgres-backend")] + Migrate(MigrateArgs), +} + +#[derive(clap::Args)] +#[cfg(feature = "postgres-backend")] +struct MigrateArgs { + #[command(subcommand)] + action: MigrateAction, +} + +#[derive(Subcommand)] +#[cfg(feature = "postgres-backend")] +enum MigrateAction { + /// Copy all memories from SQLite to Postgres. + #[command(name = "copy")] + Copy { + #[arg(long)] + from: String, // "sqlite" + #[arg(long)] + to: String, // "postgres" + #[arg(long)] + sqlite_path: PathBuf, + #[arg(long)] + postgres_url: String, + #[arg(long, default_value = "500")] + batch_size: usize, + #[arg(long)] + dry_run: bool, + }, + /// Re-embed all memories with a new embedder. + #[command(name = "reembed")] + Reembed { + #[arg(long)] + model: String, + #[arg(long, default_value = "128")] + batch_size: usize, + #[arg(long, default_value_t = true)] + drop_hnsw_first: bool, + #[arg(long)] + concurrent_index: bool, + #[arg(long)] + dry_run: bool, + }, +} +``` + +The user-facing invocation collapses to the exact string requested by the ADR: + +``` +vestige migrate copy --from sqlite --to postgres \ + --sqlite-path ~/.vestige/vestige.db \ + --postgres-url postgresql://localhost/vestige + +vestige migrate reembed --model=BAAI/bge-large-en-v1.5 +``` + +An alternate top-level layout (single `vestige migrate` with flags `--from`, `--to`, `--reembed`) is equivalent; the subcommand split is preferred because the two flag sets are disjoint (see Open Question 1). + +- **Behavior notes**: + - `--from`/`--to` values are validated; the current Phase 2 build accepts only `sqlite` and `postgres`. + - For `reembed`, the `--model` string resolves to an `Embedder` via a factory already provided by Phase 1 (`Embedder::from_name(&str)`); Phase 2 does not invent new embedder constructors. + - Progress output on `stderr`; machine-readable summary on `stdout` as one-line JSON when `--json` is set (skipped for Phase 2 unless trivial). + +### D11. Offline query cache (`.sqlx/`) + +- **File**: `crates/vestige-core/.sqlx/` (committed directory of `query-*.json`) +- **Depends on**: all `sqlx::query!` call sites being final. +- **Procedure**: the developer runs `cargo sqlx prepare --workspace` with a live Postgres having the schema applied. Output goes into `crates/vestige-core/.sqlx/`. This directory is committed. CI enforces freshness by running `cargo sqlx prepare --workspace --check` against the same live Postgres (or failing that, any dev can reproduce by setting `SQLX_OFFLINE=true`). +- **Behavior notes**: `SQLX_OFFLINE=true` in `build.rs` or env is the default on CI and for downstream consumers. The `vestige-core` docs add a one-liner in README for contributors: "if you change any SQL in Phase 2 modules, rerun `cargo sqlx prepare` with a live DB." + +### D12. Testcontainer harness (integration) + +- **File**: `tests/phase_2/common/mod.rs` (the `common` convention used in `tests/phase_2/` crates) +- **Depends on**: D2 through D11. +- **Signatures**: + +```rust +#![cfg(feature = "postgres-backend")] + +use std::sync::Arc; + +use testcontainers_modules::postgres::Postgres; +use testcontainers::{runners::AsyncRunner, ContainerAsync}; + +use vestige_core::embedder::Embedder; +use vestige_core::storage::postgres::PgMemoryStore; + +pub struct PgHarness { + pub container: ContainerAsync, + pub store: PgMemoryStore, +} + +impl PgHarness { + pub async fn start(embedder: Arc) -> anyhow::Result { + let container = Postgres::default() + .with_tag("pg16") + .with_name("pgvector/pgvector") + .start() + .await?; + let port = container.get_host_port_ipv4(5432).await?; + let url = format!( + "postgresql://postgres:postgres@127.0.0.1:{}/postgres", port + ); + let store = PgMemoryStore::connect(&url, 4, embedder.as_ref()).await?; + Ok(Self { container, store }) + } +} +``` + +- **Behavior notes**: + - Image `pgvector/pgvector:pg16` bundles pgvector into the official postgres:16 image. + - Pool size 4 is enough for tests without starving the container's default `max_connections = 100`. + - `ContainerAsync` is held for the whole test scope; drop tears down the container. + - A fake `TestEmbedder` in `common/test_embedder.rs` provides a deterministic hash-based embedding (no ONNX dependency in CI). + +--- + +## Test Plan + +### Unit tests (colocated in `src/`) + +Under `crates/vestige-core/src/storage/postgres/`: + +- `pool.rs` -- one test per `build_pool` branch: defaults, explicit `max_connections`, invalid URL returns `StoreError::Postgres`. +- `registry.rs` -- three tests: first-init writes row and alters typmod, reopen with same embedder returns Ok, reopen with different dimension returns `EmbeddingMismatch`. +- `search.rs` -- query-builder unit tests for parameter packing: empty text, null embedding, all three filters null, all three filters populated. +- `migrate_cli.rs` -- `SqliteToPostgresPlan::default` returns sane defaults; plan validation rejects empty URL. +- `reembed.rs` -- `ReembedPlan::no_change` returns `rows_updated == 0` when embedder matches registry (no network call). +- `config.rs` -- five tests covering: valid postgres config, valid sqlite config, unknown backend string, missing subsection, feature-gated postgres without feature compiled in. + +### Integration tests (in `tests/phase_2/`) + +Each file is a full integration test crate (`[[test]]` in workspace root Cargo). + +**`tests/phase_2/pg_trait_parity.rs`** + +- Declares the same test matrix as Phase 1's SQLite trait tests, parameterized over `impl MemoryStore`. +- Runs every method: `insert`, `get`, `update`, `delete`, `search`, `fts_search`, `vector_search`, `get_scheduling`, `update_scheduling`, `get_due_memories`, `add_edge`, `get_edges`, `remove_edge`, `get_neighbors`, `list_domains`, `get_domain`, `upsert_domain`, `delete_domain`, `classify`, `count`, `get_stats`, `vacuum`, `health_check`. +- Each test is written once as `async fn roundtrip_(store: &dyn MemoryStore)` and invoked from two wrappers, one for SQLite and one for Postgres. +- Acceptance: every method returns equal results (except for `Uuid` ordering in `list_domains` where the test sorts before comparing). + +**`tests/phase_2/pg_hybrid_search_rrf.rs`** + +- Inserts 20 memories with known content ("rust async trait", "postgres hnsw vector", "fastembed onnx model", ...). +- Case 1: pure FTS. `SearchQuery { text: Some("rust trait"), embedding: None, ... }` returns the three Rust-related rows in order; `fts_score` populated, `vector_score` null. +- Case 2: pure vector. `SearchQuery { text: None, embedding: Some(embed("rust trait")), ... }` returns the same three rows via cosine; `vector_score` populated, `fts_score` null. +- Case 3: hybrid. Both set -- top hit has both scores; `rrf_score >= 1/(60+1) + 1/(60+1) = 0.0328`. +- Case 4: domain filter. 10 memories tagged with `domains = ["dev"]`, 10 with `["home"]`. Query with `domains: Some(vec!["dev"])` returns only dev memories. +- Case 5: edge case -- empty FTS query plus an embedding behaves identically to `vector_search`; empty embedding plus FTS query behaves identically to `fts_search`. + +**`tests/phase_2/pg_migration_sqlite_to_postgres.rs`** + +- Populate a fresh SQLite with 10,000 memories (seeded RNG, deterministic content), 4,000 scheduling rows, 2,000 edges. +- Run `run_sqlite_to_postgres` with a test embedder. +- Assert: `count() == 10_000` on destination; spot-check 25 memories byte-for-byte (content, tags, metadata, domains, domain_scores). +- Assert: FSRS fields (`stability`, `difficulty`, `next_review`) preserved per memory. +- Assert: edges preserved by `(source_id, target_id, edge_type)`. +- Assert: re-running the migration is a no-op (`ON CONFLICT DO NOTHING` path); row count unchanged. + +**`tests/phase_2/pg_migration_reembed.rs`** + +- Start with a fresh store using `TestEmbedder768` (768-dim, hash `h1`). Insert 500 memories. +- Swap to `TestEmbedder1024` (1024-dim, hash `h2`). Run `run_reembed(store, Arc::new(TestEmbedder1024), ReembedPlan::default())`. +- Assert: `rows_updated == 500`; `embedding_model` now has `(name=TestEmbedder1024, dimension=1024, hash=h2)`. +- Assert: `SELECT DISTINCT vector_dims(embedding) FROM memories` returns only `1024`. +- Assert: HNSW index exists after reembed (`SELECT indexrelid FROM pg_indexes WHERE indexname = 'idx_memories_embedding_hnsw'`). +- Assert: memory IDs unchanged (compare pre/post id sets). +- Assert: a hybrid search using `TestEmbedder1024` returns results (post-reembed vectors are queryable). + +**`tests/phase_2/pg_config_parsing.rs`** + +- Parse six `vestige.toml` snippets: + - sqlite + fastembed -> `StorageConfig::Sqlite`. + - postgres + fastembed -> `StorageConfig::Postgres` with `max_connections = 10`. + - postgres with custom `max_connections = 25` and `acquire_timeout_secs = 60`. + - unknown backend `"mysql"` -> `ConfigError`. + - missing subsection `[storage.postgres]` while `backend = "postgres"` -> `ConfigError`. + - malformed URL (empty) -> `ConfigError::Invalid`. + +**`tests/phase_2/pg_concurrency.rs`** + +- Spawn 16 tasks, each inserting 100 memories in parallel for 1,600 total. +- Spawn 4 tasks concurrently running `search` queries; none should fail. +- Spawn 2 tasks concurrently running `update_scheduling` on overlapping IDs -- last write wins (MVCC), neither errors. +- Assert: all 1,600 rows present, no deadlocks, every task returns `Ok`. +- Run time < 10 seconds on a cold container. + +### Compile-time query verification + +- CI step: `cargo sqlx prepare --workspace --check` against a CI-provisioned Postgres (GitHub Actions / Forgejo Actions services block). Fails CI if any `query!` macro goes stale. +- Alternative offline run for contributors: `SQLX_OFFLINE=true cargo check -p vestige-core --features postgres-backend`. CI runs both forms to ensure `.sqlx/` is up to date. +- `.sqlx/` is committed to the repo. A `.gitattributes` entry marks it as `linguist-generated=true` so it doesn't inflate language stats. + +### Benchmarks + +Under `crates/vestige-core/benches/pg_hybrid_search.rs` (Criterion), gated by `postgres-backend`. + +- `pg_search_1k` -- populate 1,000 memories once per bench suite, measure `rrf_search` p50/p99 over 500 iterations. Target: p50 < 10ms, p99 < 30ms on a local container. +- `pg_search_100k` -- 100,000 memories. Target: p50 < 50ms, p99 < 150ms. Validates HNSW scaling. +- Testcontainer shared across both benches via `once_cell`. +- Bench entry in `vestige-core/Cargo.toml`: + +``` +[[bench]] +name = "pg_hybrid_search" +harness = false +required-features = ["postgres-backend"] +``` + +--- + +## Acceptance Criteria + +- [ ] `cargo build -p vestige-core --features postgres-backend` -- zero warnings. +- [ ] `cargo build -p vestige-core` (SQLite-only, default features) -- zero warnings; no Postgres symbols referenced. +- [ ] `cargo build -p vestige-mcp --features postgres-backend` -- zero warnings; `vestige` binary exposes the `migrate` subcommand. +- [ ] `cargo clippy --workspace --all-targets --all-features -- -D warnings` -- clean. +- [ ] `cargo sqlx prepare --workspace --check` -- returns success; `.sqlx/` is current. +- [ ] `cargo test -p vestige-core --features postgres-backend --test pg_trait_parity --test pg_hybrid_search_rrf --test pg_migration_sqlite_to_postgres --test pg_migration_reembed --test pg_config_parsing --test pg_concurrency` -- all green. +- [ ] Testcontainer spin-up p50 under 30 seconds on a developer laptop with a warm Docker daemon. +- [ ] `pg_search_100k` Criterion bench reports p50 < 50ms on reference hardware (logged in the ADR comment trail). +- [ ] `vestige migrate copy --from sqlite --to postgres` on a 10,000-memory corpus completes without data loss: row count parity, content byte-parity on a 1 percent sample, FSRS state preserved (stability, difficulty, reps, lapses, next_review), edge count parity. +- [ ] `vestige migrate reembed` with a dimension-changing embedder returns to a fully queryable state: HNSW present, `embedding_model` updated, no stale vectors, memory IDs untouched. +- [ ] Trait parity: every method on `MemoryStore` has at least one passing test against `PgMemoryStore`. +- [ ] Phase 1's existing SQLite suite continues to pass with zero changes required (Phase 2 is additive). +- [ ] The `postgres-backend` feature does not compile in SQLCipher (`encryption`) simultaneously (mutually exclusive at compile time, per project rule). + +--- + +## Rollback Notes + +- Every `*.up.sql` has a matching `*.down.sql` in `crates/vestige-core/migrations/postgres/`. `sqlx migrate revert` walks them in reverse order. Manual operator procedure: `sqlx migrate revert --database-url $URL --source crates/vestige-core/migrations/postgres`. +- `vestige migrate copy` is a one-way operation. The source SQLite DB is read-only during the run and untouched afterward; users retain their original file indefinitely. Recommended discipline: copy the SQLite file aside before starting, retain for 30 days. +- `vestige migrate reembed` is destructive to the `embedding` column. Recommended discipline: take a logical backup (`pg_dump --table=memories --table=embedding_model --table=scheduling`) before a reembed run. The tool prints that recommendation before starting and exits non-zero unless `--yes` is passed or the user is on a TTY that confirms. +- Feature-gate strategy: the default build remains SQLite-only. Downstream users pull `postgres-backend` explicitly: `cargo install --features postgres-backend vestige-mcp`. If the Postgres implementation fails in the field, users fall back to SQLite simply by flipping `vestige.toml`'s `[storage] backend = "sqlite"` and restarting. No data re-migration is needed if they retained their SQLite file. +- The `docs/runbook/postgres.md` deliverable (D16) captures this discipline as a one-page ops note. + +--- + +## Open Implementation Questions + +Each item has a recommendation. Ship that unless a reviewer objects. + +### Q1. CLI shape: subcommand split vs flag union + +- **Options**: (a) `vestige migrate copy --from sqlite --to postgres ...` and `vestige migrate reembed --model=...` (subcommand split); (b) `vestige migrate --from sqlite --to postgres ...` and `vestige migrate --reembed --model=...` under one `clap` command with disjoint flag groups (flag union). +- **RECOMMENDATION**: (a) subcommand split. The flag sets do not overlap and clap expresses the constraint more cleanly. The ADR string `vestige migrate --from sqlite --to postgres` can still be documented as a canonical alias by having `copy` accept it verbatim when `--from` is present. + +### Q2. Feature flag name + +- **Options**: `postgres-backend`, `postgres`, `backend-postgres`, `pg`. +- **RECOMMENDATION**: `postgres-backend`. Matches the ADR text and is explicit in `Cargo.toml` feature listings. + +### Q3. sqlx offline mode strategy + +- **Options**: (a) commit `.sqlx/` so downstream builds never need DATABASE_URL; (b) require `DATABASE_URL` at build time. +- **RECOMMENDATION**: (a). The repo already ships as a library; many downstream users will build from crates.io with no Postgres available. Committing `.sqlx/` costs ~100 kB. + +### Q4. HNSW rebuild strategy during reembed + +- **Options**: (a) `DROP INDEX; CREATE INDEX`; (b) `REINDEX INDEX CONCURRENTLY`; (c) `CREATE INDEX CONCURRENTLY` on a new name then swap. +- **RECOMMENDATION**: (a) by default for speed on empty / near-empty tables; expose `--concurrent-index` for large production corpora where locking the table is unacceptable. `REINDEX CONCURRENTLY` on pgvector HNSW is supported in pgvector 0.6+ but the community still reports edge cases with `maintenance_work_mem` -- skip unless a user explicitly opts in. + +### Q5. Connection pool sizing default + +- **Options**: 4, 10, 20, `cpus() * 2`. +- **RECOMMENDATION**: 10. Matches the PRD example, covers a single-operator load, and does not exhaust the default Postgres `max_connections = 100`. Configurable via `vestige.toml`. + +### Q6. Testcontainer image pinning + +- **Options**: (a) `pgvector/pgvector:pg16`; (b) `pgvector/pgvector:pg16.2-0.7.4` (exact tag); (c) maintain local Dockerfile. +- **RECOMMENDATION**: (b) pin exact. The float tag `pg16` has shipped breaking changes in the past (e.g., pg 16.0 to 16.1 interop). Pin to a specific pgvector minor and Postgres patch. CI bumps the tag via a single-line change. + +### Q7. Empty-text and null-embedding behavior in `search` + +- **Options**: (a) return an error if both are missing; (b) return an empty result; (c) return all memories sorted by `created_at DESC`. +- **RECOMMENDATION**: (a). A `search` call with no query is a bug in the caller; returning empty silently would hide the bug. The existing Phase 1 SQLite behavior (TBD but likely errors) is the tiebreaker. + +### Q8. `classify()` SQL vs Rust + +- **Options**: (a) compute cosine to all centroids in SQL (`SELECT id, 1 - (centroid <=> $1::vector) FROM domains ORDER BY ...`); (b) load centroids, compute in Rust. +- **RECOMMENDATION**: (a). Leverages pgvector's SIMD paths and avoids round-tripping centroid vectors. At Phase 4 scale (tens of centroids) the difference is marginal, but the SQL path is simpler and matches the rest of the backend. + +### Q9. FSRS `review_events` writes: trait method vs implicit on `update_scheduling` + +- **Options**: (a) add an explicit `record_review(memory_id, rating, prior, new)` method to the Phase 1 trait; (b) have `update_scheduling` write the event atomically. +- **RECOMMENDATION**: this is a Phase 1 question, not Phase 2. Phase 2 implements whichever Phase 1 chose. If Phase 1 missed it, Phase 2 raises a blocker rather than deciding alone. + +### Q10. `tsvector` weight for tags -- PRD used `array_to_tsvector`, we used `array_to_string` + +- **Options**: (a) `array_to_tsvector(tags)` (requires the `tsvector_extra` extension or similar); (b) `to_tsvector('english', array_to_string(tags, ' '))` (plain core Postgres). +- **RECOMMENDATION**: (b). Equivalent ranking, zero extra extensions. If a future tag matches a stopword (`"the"`), it gets dropped, but that is correct behavior for ranking. + +### Q11. `PgMemoryStore::connect` runs migrations automatically? + +- **Options**: (a) always run `sqlx::migrate!` on connect; (b) require the user to run `vestige migrate-schema` explicitly before starting the server. +- **RECOMMENDATION**: (a) during Phase 2; revisit in Phase 3 when the server binary exists. Developer ergonomics win now, and the migrations are idempotent. + +### Q12. Offline query cache freshness vs `sqlx-cli` version skew + +- **Options**: (a) pin `sqlx-cli` version in CI `actions/cache` step; (b) let CI install whatever version `sqlx` depends on. +- **RECOMMENDATION**: (a) pin to the same 0.8.x as the crate. `sqlx prepare` output changes between 0.7 and 0.8 and must match the runtime. + +--- + +## Sequencing + +The Phase 2 agent executes deliverables in this order; deliverables not listed can run in any order relative to each other. + +1. D1 (feature gate + Cargo deps) -- unblocks everything. +2. D7 (config) -- required to construct `PgMemoryStore`. +3. D4 (migrations SQL) -- required before any `query!` compiles. +4. D3 (pool) + D6 (registry) -- small, used by D2. +5. D2 (`PgMemoryStore` core + trait impl) -- the bulk of Phase 2. +6. D5 (RRF search) -- after D2; requires the trait to exist. +7. D12 (test harness) + parity and search tests -- validates D2 and D5 in isolation. +8. D8 (sqlite->pg migrate) + its integration test. +9. D9 (reembed) + its integration test. +10. D10 (CLI wiring). +11. D11 (`.sqlx/` offline cache) -- last, after SQL is frozen. +12. D15 (benches) + D16 (runbook) -- after acceptance tests pass. + +Each deliverable PR includes its own tests; the final Phase 2 PR stacks them (or lands as a single branch if the Phase 1 trait is stable enough to avoid rebase churn). + +### Critical Files for Implementation + +- /home/delandtj/prppl/vestige/crates/vestige-core/src/storage/postgres/mod.rs +- /home/delandtj/prppl/vestige/crates/vestige-core/migrations/postgres/0001_init.up.sql +- /home/delandtj/prppl/vestige/crates/vestige-core/src/storage/postgres/search.rs +- /home/delandtj/prppl/vestige/crates/vestige-core/src/storage/postgres/migrate_cli.rs +- /home/delandtj/prppl/vestige/crates/vestige-mcp/src/bin/cli.rs diff --git a/docs/plans/0003-phase-3-network-access.md b/docs/plans/0003-phase-3-network-access.md new file mode 100644 index 0000000..500fd5a --- /dev/null +++ b/docs/plans/0003-phase-3-network-access.md @@ -0,0 +1,1435 @@ +# Phase 3 Plan: Network Access and Authentication + +**Status**: Draft +**Depends on**: Phase 1 (MemoryStore trait), Phase 2 (PgMemoryStore, backend config) +**Related**: docs/adr/0001-pluggable-storage-and-network-access.md (Phase 3) + +--- + +## Scope + +### In scope + +- HTTP MCP Streamable endpoint at `POST /mcp` (JSON-RPC body, keep existing + session semantics) and `GET /mcp` (Server-Sent Events for long-running + operations: dream, consolidate, discover, reassign). +- REST API under `/api/v1/` for direct HTTP clients that do not speak MCP + (memories CRUD, search, consolidate trigger, stats, domains + list/rename/merge/discover). +- `api_keys` table + enforcement (blake3-hashed, scopes `read`/`write`, optional + `domain_filter` TEXT[], `last_used` timestamp, `active` flag, revocation). +- Auth middleware with three resolution paths in priority order: + `Authorization: Bearer ` then `X-API-Key: ` then signed session + cookie. All three resolve to the same `ApiKeyIdentity`. +- Signed session cookie: `vestige_session`, SameSite=Strict, HttpOnly, + Secure-when-TLS, Path=/, Max-Age 8 hours. Signed with HMAC-SHA256 using a + key derived from `VESTIGE_SESSION_SECRET` (env) or generated + persisted to + `/session_secret` on first boot. +- `vestige keys create|list|revoke` CLI subcommand (plus `keys rotate` as a + convenience alias of `revoke` + `create`). +- Startup-time refusal to bind non-loopback with `auth.enabled = false` (hard + error, non-zero exit, stderr message, no fallback). +- Dashboard login flow: `POST /dashboard/login` with `{"api_key":"vst_..."}` + JSON body, `X-API-Key` header, or form body; sets signed cookie; returns 200 + JSON `{"ok":true}` for XHR or 303 to `/` if form. Logout at + `POST /dashboard/logout` clears cookie. +- Per-key `domain_filter` enforced inside the auth layer: if the key has + `domain_filter = ["dev","infra"]`, every handler that searches or lists sees + the filter pre-applied via a request extension. Optional + `X-Vestige-Domain: home` header may narrow further but may never escape the + key's filter. +- `[server]` and `[auth]` sections in `vestige.toml`, plus backward-compatible + env var bridges. +- `VESTIGE_AUTH_TOKEN` continues to work for one minor release as a synthetic + single-key fallback, but logs a deprecation warning. +- Per-request request IDs and structured tracing; `last_used` write-back on + successful auth. + +### Out of scope + +- Phase 4 HDBSCAN domain classifier itself. The REST surface exposes domain + endpoints but they may stub to empty results until Phase 4 lands. +- Real TLS termination. Assumed handled by a reverse proxy (nginx, Caddy, + Mycelium). An optional `tls_cert` / `tls_key` pair is documented but its + implementation may be deferred behind a `tls` Cargo feature. +- OAuth / OIDC / SSO. Future work. +- Rate limiting per key (documented in Open Questions, not implemented here). +- WebAuthn / passkey dashboard login. Future work. +- Fine-grained RBAC beyond `read` / `write` scopes. + +## Prerequisites + +Phase 1 artifacts: + +- `vestige_core::storage::MemoryStore` trait (with `Send` variant via + `trait_variant::make`). +- `Embedder` trait. +- `SqliteMemoryStore` implementing `MemoryStore`. + +Phase 2 artifacts: + +- `PgMemoryStore` implementing `MemoryStore`. +- `crates/vestige-core/migrations/postgres/` sqlx migrations; `api_keys` table + schema present but enforcement path is Phase 3's job. +- Runtime backend selection via `vestige.toml` `[storage]` section returning + an `Arc`. + +Assumed already available in workspace: + +- `axum = 0.8` (currently pinned in `crates/vestige-mcp/Cargo.toml`). +- `tower = 0.5`, `tower-http = 0.6` (`cors`, `set-header` features already on). +- `tokio`, `serde`, `serde_json`, `uuid`, `chrono`, `tracing`, + `tracing-subscriber`, `thiserror`, `anyhow`, `subtle`, `clap`, `directories`. + +New crates required (add via `cargo add -p vestige-mcp`): + +- `blake3 = "1"` -- key hashing. +- `rand = "0.9"` with `std_rng` (for key bytes; prefer `rand::rngs::OsRng`). +- `axum-extra = { version = "0.10", features = ["cookie-signed", "typed-header"] }` + -- `SignedCookieJar`, `Cookie`, `Key`. +- `hmac = "0.12"` + `sha2 = "0.10"` -- HMAC-SHA256 for the session secret + derivation (not required if `axum-extra`'s `SignedCookieJar` is used, but + retained for the pure-token-signing path). RECOMMENDATION: rely solely on + `axum-extra::extract::cookie::{Key, SignedCookieJar}`. +- `tower-http` features bump: add `trace` and `request-id`. +- `async-stream = "0.3"` -- emitting SSE events from async closures. +- `futures-util` already present -- for `Stream` adapters. +- `base64 = "0.22"` -- emitting / parsing the random bytes in the `vst_...` + prefix. Use the `URL_SAFE_NO_PAD` alphabet. +- `zeroize = "1"` (optional, recommended) -- scrub the plaintext key in RAM + after hashing. + +`cargo add` commands (do not execute here, leave to implementation): + + cargo add -p vestige-mcp blake3 rand base64 zeroize async-stream + cargo add -p vestige-mcp axum-extra --features cookie-signed,typed-header + cargo add -p vestige-mcp tower-http --features trace,request-id,cors,set-header + +JSON-RPC library: the project uses a hand-rolled `JsonRpcRequest` / +`JsonRpcResponse` pair in `crates/vestige-mcp/src/protocol/types.rs`. Keep it +in Phase 3 (no jsonrpsee migration). Streamable HTTP remains implemented as +`POST /mcp` + session header + `GET /mcp` SSE. See Open Questions for rationale. + +## Deliverables + +1. `crates/vestige-mcp/src/auth/` module (new). Houses key generation, key + verification, identity resolution, scopes, domain-filter extractor, session + key type, and error types. + +2. `crates/vestige-mcp/src/auth/keys.rs` -- key format, generation, + blake3 hashing, store-facing trait methods for list / create / revoke / + verify. + +3. `crates/vestige-mcp/src/auth/middleware.rs` -- axum `from_fn` middleware + that populates `Extension` on the request, rejects unauthenticated + requests with 401, insufficient scope with 403. + +4. `crates/vestige-mcp/src/auth/session.rs` -- `SignedCookieJar` integration, + `session_key()` loader (env or persisted file), `issue_session()` and + `revoke_session()` helpers. + +5. `crates/vestige-mcp/src/http/` module split out of `protocol/http.rs`: + - `http/mcp.rs` -- MCP JSON-RPC endpoint (adapted from the current + `post_mcp` / `delete_mcp`, with auth middleware now gating). + - `http/mcp_sse.rs` -- SSE handler for `GET /mcp` long-running ops. + - `http/rest.rs` -- `/api/v1/*` handlers. + - `http/mod.rs` -- `build_router()`, `start_server()`, bind-safety check, + layer stack assembly. + +6. `crates/vestige-mcp/src/http/errors.rs` -- uniform `ApiError` enum and + `IntoResponse` implementation. Maps to RFC 7807 problem+json for REST and + plain JSON for `/mcp`. + +7. Dashboard patch: `crates/vestige-mcp/src/dashboard/mod.rs` -- add the auth + middleware to the dashboard router, add `/dashboard/login` + `/dashboard/logout` + endpoints, keep `/api/health` unauthenticated. + +8. `crates/vestige-mcp/src/bin/cli.rs` -- new `Keys` subcommand group (`create`, + `list`, `revoke`, `rotate`). + +9. `crates/vestige-mcp/src/config.rs` (new file) -- typed `ServerConfig`, + `AuthConfig`, `StorageConfig` loader from `vestige.toml`, merging env var + overrides, validating the non-loopback + auth-disabled combination. + +10. SQL migration `crates/vestige-core/migrations/postgres/0300_api_keys_enforcement.sql` + and SQLite equivalent `crates/vestige-core/migrations/sqlite/0300_api_keys.sql`: + - `api_keys` table (if not already created in Phase 2), with `key_hash` + UNIQUE, `label` NOT NULL, `scopes` TEXT[] default `{read,write}`, + `domain_filter` TEXT[] default `{}`, `created_at`, `last_used`, + `active BOOLEAN DEFAULT true`. + - Index on `key_hash` (unique already), and on `active WHERE active`. + +11. `MemoryStore` trait extension (Phase 2 may already cover this; if not, + finalize in Phase 3): `list_api_keys`, `create_api_key`, + `revoke_api_key`, `find_api_key_by_hash`, `touch_api_key_last_used`. + +12. Docs updates: + - `docs/env-vars.md` (new) -- one sheet for all runtime env vars. + - `README.md` server-mode section. + - `docs/adr/0001-*.md` -- mark Phase 3 as Implemented when merged. + +## Detailed Task Breakdown + +### D1. Auth module skeleton + +Files: + +- `crates/vestige-mcp/src/auth/mod.rs` +- `crates/vestige-mcp/src/auth/keys.rs` +- `crates/vestige-mcp/src/auth/session.rs` +- `crates/vestige-mcp/src/auth/middleware.rs` +- `crates/vestige-mcp/src/auth/errors.rs` + +`auth/mod.rs`: + + pub mod errors; + pub mod keys; + pub mod middleware; + pub mod session; + + pub use errors::AuthError; + pub use keys::{ApiKey, ApiKeyPlaintext, ApiKeyRecord, Scope}; + pub use middleware::{Identity, auth_layer}; + pub use session::{SessionConfig, session_key}; + +`auth/errors.rs`: + + use axum::http::StatusCode; + use axum::response::{IntoResponse, Response}; + use serde::Serialize; + use thiserror::Error; + + #[derive(Debug, Error)] + pub enum AuthError { + #[error("missing credentials")] + MissingCredentials, + #[error("invalid credentials")] + InvalidCredentials, + #[error("key revoked")] + Revoked, + #[error("insufficient scope: required {required}")] + InsufficientScope { required: &'static str }, + #[error("domain not permitted for this key: {domain}")] + DomainNotAllowed { domain: String }, + #[error("internal auth error")] + Internal, + } + + #[derive(Serialize)] + struct Problem<'a> { + #[serde(rename = "type")] + kind: &'a str, + title: &'a str, + status: u16, + detail: &'a str, + } + + impl IntoResponse for AuthError { + fn into_response(self) -> Response { + let (status, title) = match self { + AuthError::MissingCredentials => (StatusCode::UNAUTHORIZED, "unauthorized"), + AuthError::InvalidCredentials => (StatusCode::UNAUTHORIZED, "unauthorized"), + AuthError::Revoked => (StatusCode::UNAUTHORIZED, "unauthorized"), + AuthError::InsufficientScope { .. } => (StatusCode::FORBIDDEN, "forbidden"), + AuthError::DomainNotAllowed { .. } => (StatusCode::FORBIDDEN, "forbidden"), + AuthError::Internal => (StatusCode::INTERNAL_SERVER_ERROR, "internal"), + }; + let detail = self.to_string(); + let body = axum::Json(Problem { + kind: "about:blank", + title, + status: status.as_u16(), + detail: &detail, + }); + let mut r = (status, body).into_response(); + r.headers_mut().insert( + axum::http::header::CONTENT_TYPE, + axum::http::HeaderValue::from_static("application/problem+json"), + ); + r + } + } + +### D2. Key format and generation + +File: `crates/vestige-mcp/src/auth/keys.rs` + +- Key on wire: `vst_<22-byte base64url-no-pad>`. 22 bytes = 176 bits entropy. + Encoded length ~30 chars. Full string ~34 chars including the `vst_` prefix. +- Hash stored in DB: `blake3(key_plaintext)` hex lowercase (32 bytes -> 64 + hex chars). +- Hash prefix on list: first 12 hex characters, e.g. `key_hash[..12]` for + human display. + +Signatures: + + use blake3::Hasher; + use rand::rngs::OsRng; + use rand::TryRngCore; + use base64::engine::general_purpose::URL_SAFE_NO_PAD; + use base64::Engine; + use zeroize::Zeroize; + + const KEY_PREFIX: &str = "vst_"; + const KEY_RANDOM_BYTES: usize = 22; + + #[derive(Clone, Debug, PartialEq, Eq)] + pub enum Scope { + Read, + Write, + } + + impl Scope { + pub fn as_str(&self) -> &'static str { + match self { + Scope::Read => "read", + Scope::Write => "write", + } + } + pub fn from_str(s: &str) -> Option { + match s { + "read" => Some(Scope::Read), + "write" => Some(Scope::Write), + _ => None, + } + } + } + + /// The plaintext key. Shown to the user exactly once. + /// Zeroed on drop. + pub struct ApiKeyPlaintext(String); + + impl ApiKeyPlaintext { + pub fn as_str(&self) -> &str { &self.0 } + pub fn into_inner(mut self) -> String { + std::mem::take(&mut self.0) + } + } + + impl Drop for ApiKeyPlaintext { + fn drop(&mut self) { self.0.zeroize(); } + } + + #[derive(Clone, Debug)] + pub struct ApiKeyRecord { + pub id: uuid::Uuid, + pub key_hash: String, // hex-encoded blake3(plaintext) + pub label: String, + pub scopes: Vec, + pub domain_filter: Vec, + pub created_at: chrono::DateTime, + pub last_used: Option>, + pub active: bool, + } + + pub fn generate_key() -> ApiKeyPlaintext { + let mut bytes = [0u8; KEY_RANDOM_BYTES]; + OsRng.try_fill_bytes(&mut bytes).expect("OsRng"); + let encoded = URL_SAFE_NO_PAD.encode(&bytes); + bytes.zeroize(); + ApiKeyPlaintext(format!("{}{}", KEY_PREFIX, encoded)) + } + + pub fn hash_key(plaintext: &str) -> String { + let mut hasher = Hasher::new(); + hasher.update(plaintext.as_bytes()); + hasher.finalize().to_hex().to_string() + } + + pub fn verify_key(plaintext: &str, stored_hash_hex: &str) -> bool { + use subtle::ConstantTimeEq; + let computed = hash_key(plaintext); + computed.as_bytes().ct_eq(stored_hash_hex.as_bytes()).unwrap_u8() == 1 + } + +Helpers on a thin repository trait that both backends implement through +`MemoryStore` (Phase 2 already adds the required columns; Phase 3 wires the +methods): + + #[async_trait::async_trait] + pub trait ApiKeyStore: Send + Sync + 'static { + async fn create_api_key(&self, rec: &ApiKeyRecord) -> anyhow::Result<()>; + async fn find_api_key_by_hash(&self, hash: &str) -> anyhow::Result>; + async fn list_api_keys(&self) -> anyhow::Result>; + async fn revoke_api_key(&self, id: uuid::Uuid) -> anyhow::Result; + async fn touch_api_key_last_used(&self, id: uuid::Uuid) -> anyhow::Result<()>; + } + +(If Phase 2 already bolted these onto `MemoryStore`, `ApiKeyStore` is simply a +re-export of the relevant subset.) + +### D3. Session cookie + +File: `crates/vestige-mcp/src/auth/session.rs` + +- Cookie name: `vestige_session`. +- Cookie attributes: `HttpOnly`, `SameSite=Strict`, `Path=/`, `Max-Age=28800` + (8h), `Secure` when the server is running behind TLS (detected from + `config.server.tls_cert.is_some()` or the `X-Forwarded-Proto` trusted header; + default: set `Secure` whenever `config.server.bind` is non-loopback). +- Payload: serialized `SessionClaims { key_id: Uuid, issued_at: i64, + expires_at: i64 }` encoded as `serde_json` then base64url. The signing is + handled by `axum-extra::extract::cookie::SignedCookieJar` (HMAC via a 64-byte + `Key`). Any tampering or truncation is rejected by the jar automatically. +- Key material: 64 random bytes, stored at `/session_secret` (mode + 0600) or overridden by `VESTIGE_SESSION_SECRET` (base64url-encoded 64 bytes, + reject if shorter). + +Signatures: + + use axum_extra::extract::cookie::{Cookie, Key, SameSite, SignedCookieJar}; + use chrono::{Duration, Utc}; + use serde::{Deserialize, Serialize}; + + const COOKIE_NAME: &str = "vestige_session"; + const DEFAULT_TTL: Duration = Duration::hours(8); + + #[derive(Clone, Serialize, Deserialize)] + pub struct SessionClaims { + pub key_id: uuid::Uuid, + pub iat: i64, + pub exp: i64, + } + + pub fn session_key(data_dir: &std::path::Path) -> anyhow::Result { + // 1) env override + if let Ok(env_val) = std::env::var("VESTIGE_SESSION_SECRET") { + let raw = base64::engine::general_purpose::URL_SAFE_NO_PAD + .decode(env_val.trim())?; + anyhow::ensure!(raw.len() >= 64, "VESTIGE_SESSION_SECRET must be >= 64 bytes"); + return Ok(Key::from(&raw)); + } + // 2) persisted file + let path = data_dir.join("session_secret"); + if path.exists() { + let bytes = std::fs::read(&path)?; + return Ok(Key::from(&bytes)); + } + // 3) generate + use rand::TryRngCore; + let mut bytes = [0u8; 64]; + rand::rngs::OsRng.try_fill_bytes(&mut bytes)?; + #[cfg(unix)] + { + use std::io::Write; + use std::os::unix::fs::OpenOptionsExt; + std::fs::create_dir_all(data_dir).ok(); + let mut f = std::fs::OpenOptions::new() + .create_new(true).write(true).mode(0o600).open(&path)?; + f.write_all(&bytes)?; + f.sync_all()?; + } + #[cfg(not(unix))] + std::fs::write(&path, &bytes)?; + Ok(Key::from(&bytes)) + } + + pub fn issue_session( + jar: SignedCookieJar, + key_id: uuid::Uuid, + secure: bool, + ) -> SignedCookieJar { + let now = Utc::now(); + let claims = SessionClaims { + key_id, + iat: now.timestamp(), + exp: (now + DEFAULT_TTL).timestamp(), + }; + let value = serde_json::to_string(&claims).expect("serialize claims"); + let mut cookie = Cookie::new(COOKIE_NAME, value); + cookie.set_http_only(true); + cookie.set_same_site(SameSite::Strict); + cookie.set_path("/"); + cookie.set_max_age(cookie::time::Duration::seconds(DEFAULT_TTL.num_seconds())); + cookie.set_secure(secure); + jar.add(cookie) + } + + pub fn revoke_session(jar: SignedCookieJar) -> SignedCookieJar { + jar.remove(Cookie::from(COOKIE_NAME)) + } + + pub fn claims_from(jar: &SignedCookieJar) -> Option { + let c = jar.get(COOKIE_NAME)?; + let claims: SessionClaims = serde_json::from_str(c.value()).ok()?; + if claims.exp < Utc::now().timestamp() { return None; } + Some(claims) + } + +### D4. Auth middleware + +File: `crates/vestige-mcp/src/auth/middleware.rs` + +Identity carried through the request: + + #[derive(Clone, Debug)] + pub struct Identity { + pub key_id: uuid::Uuid, + pub label: String, + pub scopes: Vec, + pub domain_filter: Vec, + pub via: AuthVia, + } + + #[derive(Clone, Copy, Debug)] + pub enum AuthVia { + Bearer, + ApiKeyHeader, + SessionCookie, + } + +Middleware (axum 0.8): + + use axum::extract::{Request, State}; + use axum::http::{header, StatusCode}; + use axum::middleware::Next; + use axum::response::{IntoResponse, Response}; + use axum_extra::extract::cookie::SignedCookieJar; + use std::sync::Arc; + + pub async fn auth_layer( + State(state): State>, + jar: SignedCookieJar, + mut request: Request, + next: Next, + ) -> Response { + // Allowlist endpoints that never require auth: + let path = request.uri().path(); + if path == "/api/health" || path == "/api/v1/health" || + path == "/dashboard/login" { + return next.run(request).await; + } + + let via_and_key = extract_credentials(request.headers(), &jar); + let outcome = match via_and_key { + Some((AuthVia::Bearer, key)) | Some((AuthVia::ApiKeyHeader, key)) => { + resolve_by_plaintext(&state, &key).await.map(|id| (id, via_and_key.unwrap().0)) + } + Some((AuthVia::SessionCookie, key_id_str)) => { + let id = uuid::Uuid::parse_str(&key_id_str).map_err(|_| AuthError::InvalidCredentials)?; + resolve_by_key_id(&state, id).await.map(|id| (id, AuthVia::SessionCookie)) + } + None => Err(AuthError::MissingCredentials), + }; + + let identity = match outcome { + Ok((id, via)) => Identity { via, ..id }, + Err(e) => return e.into_response(), + }; + + // touch last_used asynchronously; do not block request path + let st2 = state.clone(); + let kid = identity.key_id; + tokio::spawn(async move { let _ = st2.store.touch_api_key_last_used(kid).await; }); + + request.extensions_mut().insert(identity); + next.run(request).await + } + +Credential extraction (priority: Bearer > X-API-Key > cookie): + + fn extract_credentials( + headers: &axum::http::HeaderMap, + jar: &SignedCookieJar, + ) -> Option<(AuthVia, String)> { + if let Some(v) = headers.get(header::AUTHORIZATION).and_then(|h| h.to_str().ok()) { + if let Some(rest) = v.strip_prefix("Bearer ") { + return Some((AuthVia::Bearer, rest.trim().to_string())); + } + } + if let Some(v) = headers.get("x-api-key").and_then(|h| h.to_str().ok()) { + return Some((AuthVia::ApiKeyHeader, v.trim().to_string())); + } + if let Some(claims) = crate::auth::session::claims_from(jar) { + return Some((AuthVia::SessionCookie, claims.key_id.to_string())); + } + None + } + +Resolution helpers: + + async fn resolve_by_plaintext(st: &AppCtx, key: &str) -> Result { + let hash = crate::auth::keys::hash_key(key); + let rec = st.store.find_api_key_by_hash(&hash).await + .map_err(|_| AuthError::Internal)? + .ok_or(AuthError::InvalidCredentials)?; + if !rec.active { return Err(AuthError::Revoked); } + Ok(Identity { + key_id: rec.id, label: rec.label, scopes: rec.scopes, + domain_filter: rec.domain_filter, via: AuthVia::Bearer, + }) + } + + async fn resolve_by_key_id(st: &AppCtx, id: uuid::Uuid) -> Result { + let rec = st.store.find_api_key_by_id(id).await + .map_err(|_| AuthError::Internal)? + .ok_or(AuthError::InvalidCredentials)?; + if !rec.active { return Err(AuthError::Revoked); } + Ok(Identity { + key_id: rec.id, label: rec.label, scopes: rec.scopes, + domain_filter: rec.domain_filter, via: AuthVia::SessionCookie, + }) + } + +Scope guard extractor (per-handler opt-in): + + pub struct RequireScope; + impl axum::extract::FromRequestParts for RequireScope + where S: Send + Sync, + { + type Rejection = AuthError; + async fn from_request_parts( + parts: &mut axum::http::request::Parts, _state: &S, + ) -> Result { + let id = parts.extensions.get::().ok_or(AuthError::MissingCredentials)?; + let need = if WRITE { Scope::Write } else { Scope::Read }; + if !id.scopes.contains(&need) { + return Err(AuthError::InsufficientScope { + required: if WRITE { "write" } else { "read" }, + }); + } + Ok(RequireScope) + } + } + +Domain scoping: + + /// Returns the effective domain filter for the request: + /// - Intersect the key's domain_filter with any X-Vestige-Domain header. + /// - Empty key filter means "all domains", so the header is authoritative. + /// - A header that names a domain outside the key filter returns + /// `Err(DomainNotAllowed)`. + pub fn effective_domain_filter( + id: &Identity, header: Option<&str>, + ) -> Result>, AuthError> { + let header_dom = header.map(|s| s.trim().to_string()).filter(|s| !s.is_empty()); + match (id.domain_filter.as_slice(), header_dom) { + ([], None) => Ok(None), + ([], Some(h)) => Ok(Some(vec![h])), + (filter, None) => Ok(Some(filter.to_vec())), + (filter, Some(h)) => { + if filter.iter().any(|d| d == &h) { + Ok(Some(vec![h])) + } else { + Err(AuthError::DomainNotAllowed { domain: h }) + } + } + } + } + +### D5. Layer ordering + +Router assembly in `http/mod.rs::build_router`: + + let trace = tower_http::trace::TraceLayer::new_for_http(); + let request_id = tower_http::request_id::SetRequestIdLayer::x_request_id( + tower_http::request_id::MakeRequestUuid); + let propagate_id = tower_http::request_id::PropagateRequestIdLayer::x_request_id(); + + let cors = CorsLayer::new() + .allow_origin(cfg.server.allowed_origins()) + .allow_methods([Method::GET, Method::POST, Method::PUT, Method::DELETE, Method::OPTIONS]) + .allow_headers([header::CONTENT_TYPE, header::AUTHORIZATION, + HeaderName::from_static("x-api-key"), + HeaderName::from_static("x-vestige-domain"), + HeaderName::from_static("mcp-session-id")]) + .allow_credentials(true); + + let app = Router::new() + // Unauth routes first (not subjected to auth_layer by path allowlist) + .route("/api/health", get(health)) + .route("/dashboard/login", post(login)) + .route("/dashboard/logout", post(logout)) + // MCP + REST + dashboard + .route("/mcp", post(http::mcp::post_mcp).get(http::mcp_sse::get_mcp_sse) + .delete(http::mcp::delete_mcp)) + .nest("/api/v1", http::rest::router()) + .merge(dashboard::router()) + // Auth middleware applied via from_fn_with_state (allowlist inside) + .layer(axum::middleware::from_fn_with_state(ctx.clone(), auth_layer)) + // Outermost: tracing, request-id, cors, body limit, concurrency + .layer( + ServiceBuilder::new() + .layer(trace) + .layer(request_id) + .layer(propagate_id) + .layer(cors) + .layer(DefaultBodyLimit::max(MAX_BODY_SIZE)) + .layer(ConcurrencyLimitLayer::new(CONCURRENCY_LIMIT)) + ) + .with_state(ctx); + +Axum applies `layer()` calls outermost-first in the order they are declared. +The result here: request -> trace -> request-id -> CORS -> body-limit -> +concurrency -> auth -> handler. Auth must wrap the handlers but be inside +tracing so its spans can log auth outcomes. + +### D6. MCP endpoints + +File: `crates/vestige-mcp/src/http/mcp.rs` + +`POST /mcp` -- keep the session-based structure already in `protocol/http.rs` +but use the `Identity` injected by the auth layer instead of a shared +`auth_token`: + + pub async fn post_mcp( + State(ctx): State>, + Extension(id): Extension, + headers: HeaderMap, + Json(request): Json, + ) -> Response { ... } + +Auth happens in the layer, so this handler cannot be reached without a valid +`Identity`. Scope check: all MCP writes (tools that mutate) require +`RequireScope`. Use an enum of MCP methods or a method -> required-scope +map. `tools/list`, `resources/list`, `initialize`, `ping` are read-only. +`tools/call` is conservatively classified as write; the per-tool dispatch +inside `McpServer::handle_tools_call` may further reject writes when the tool +name is read-only and the key lacks write. + +`DELETE /mcp` -- unchanged semantics, drops the session. + +`GET /mcp` -- SSE. Implementation in `http/mcp_sse.rs`: + + use axum::response::sse::{Event, KeepAlive, Sse}; + use axum::extract::Query; + use futures_util::stream::Stream; + use async_stream::stream; + use std::time::Duration; + + #[derive(serde::Deserialize)] + pub struct SseParams { + pub op: String, // "dream" | "consolidate" | "discover" | "reassign" + pub session: Option, // optional operation correlation id + } + + pub async fn get_mcp_sse( + State(ctx): State>, + Extension(_id): Extension, + Query(params): Query, + ) -> Result>>, AuthError> { + let op = params.op.clone(); + let ctx2 = ctx.clone(); + let s = stream! { + yield Ok(Event::default().event("start").data(format!("{{\"op\":\"{}\"}}", op))); + match op.as_str() { + "dream" => { + let mut rx = ctx2.cognitive.lock().await.begin_dream_stream().await; + while let Some(ev) = rx.recv().await { + yield Ok(Event::default().event("progress").json_data(ev)?); + } + yield Ok(Event::default().event("done").data("{}")); + } + "consolidate" => { /* same pattern over Storage::run_consolidation_stream */ } + "discover" => { /* Phase 4 */ } + "reassign" => { /* Phase 4 */ } + other => { + yield Ok(Event::default().event("error") + .data(format!("{{\"message\":\"unknown op {}\"}}", other))); + } + } + }; + Ok(Sse::new(s).keep_alive(KeepAlive::new().interval(Duration::from_secs(15)))) + } + +SSE event shape (stable contract, document in `docs/http-api.md`): + + event: start + data: {"op":"dream"} + + event: progress + data: {"stage":"replay","processed":12,"total":50} + + event: progress + data: {"stage":"cross_reference","processed":25,"total":50} + + event: done + data: {"nodes_processed":50,"duration_ms":14320} + +The `keep-alive` hint is 15s to survive most proxy timeouts. + +### D7. REST API + +File: `crates/vestige-mcp/src/http/rest.rs` + +Routes: + + pub fn router() -> Router> { + Router::new() + .route("/health", get(health)) + .route("/memories", post(create_memory).get(list_memories)) + .route("/memories/{id}", get(get_memory).put(update_memory).delete(delete_memory)) + .route("/memories/{id}/promote", post(promote_memory)) + .route("/memories/{id}/demote", post(demote_memory)) + .route("/search", post(search_memories)) + .route("/consolidate", post(trigger_consolidation)) + .route("/stats", get(get_stats)) + .route("/domains", get(list_domains)) + .route("/domains/discover", post(trigger_discovery)) + .route("/domains/{id}", put(rename_domain).delete(delete_domain)) + .route("/domains/{id}/merge", post(merge_domain)) + .route("/keys", post(create_key).get(list_keys)) + .route("/keys/{id}", delete(revoke_key)) + } + +Representative signatures: + + #[derive(serde::Deserialize)] + pub struct CreateMemoryReq { + pub content: String, + pub node_type: Option, + pub tags: Option>, + pub source: Option, + pub metadata: Option, + } + + #[derive(serde::Serialize)] + pub struct MemoryView { /* flat projection of MemoryRecord */ } + + pub async fn create_memory( + State(ctx): State>, + Extension(id): Extension, + _: RequireScope, + Json(req): Json, + ) -> Result<(StatusCode, Json), ApiError> { + let effective = effective_domain_filter(&id, None)?; + let rec = ctx.store.insert_from_rest(req, effective).await?; + Ok((StatusCode::CREATED, Json(MemoryView::from(rec)))) + } + + pub async fn search_memories( + State(ctx): State>, + Extension(id): Extension, + _: RequireScope, + headers: HeaderMap, + Json(req): Json, + ) -> Result, ApiError> { + let dom_header = headers.get("x-vestige-domain").and_then(|h| h.to_str().ok()); + let effective = effective_domain_filter(&id, dom_header)?; + let q = SearchQuery { domains: effective, ..req.into() }; + let res = ctx.store.search(&q).await?; + Ok(Json(SearchResp::from(res))) + } + +`trigger_consolidation` returns 202 Accepted + a JSON body with a `session_id` +the client may pass to `GET /mcp?op=consolidate&session=...` to stream +progress. + +### D8. Error mapping + +File: `crates/vestige-mcp/src/http/errors.rs` + + #[derive(Debug, thiserror::Error)] + pub enum ApiError { + #[error(transparent)] Auth(#[from] AuthError), + #[error("bad request: {0}")] BadRequest(String), + #[error("not found")] NotFound, + #[error("conflict: {0}")] Conflict(String), + #[error(transparent)] Store(#[from] anyhow::Error), + } + + impl IntoResponse for ApiError { + fn into_response(self) -> Response { + match self { + ApiError::Auth(a) => a.into_response(), + ApiError::BadRequest(m) => (StatusCode::BAD_REQUEST, problem(400, "bad_request", &m)).into_response(), + ApiError::NotFound => (StatusCode::NOT_FOUND, problem(404, "not_found", "")).into_response(), + ApiError::Conflict(m) => (StatusCode::CONFLICT, problem(409, "conflict", &m)).into_response(), + ApiError::Store(e) => { + tracing::error!(err = %e, "store error"); + (StatusCode::INTERNAL_SERVER_ERROR, problem(500, "internal", "internal error")).into_response() + } + } + } + } + +All MCP JSON-RPC error mapping is unchanged (done in `McpServer`); only +transport-level errors (401/403) leave that path. + +### D9. Config loader and bind-safety check + +File: `crates/vestige-mcp/src/config.rs` + + #[derive(Debug, Clone, serde::Deserialize)] + pub struct ServerConfig { + #[serde(default = "default_bind")] + pub bind: String, // "127.0.0.1:3928" + #[serde(default = "default_dashboard_port")] + pub dashboard_port: u16, + #[serde(default)] pub tls_cert: Option, + #[serde(default)] pub tls_key: Option, + #[serde(default)] pub allowed_origins: Vec, + } + + #[derive(Debug, Clone, serde::Deserialize)] + pub struct AuthConfig { + #[serde(default = "default_true")] + pub enabled: bool, + #[serde(default)] pub session_secret_file: Option, + } + + impl ServerConfig { + pub fn parsed_bind(&self) -> anyhow::Result { + self.bind.parse().map_err(|e: std::net::AddrParseError| + anyhow::anyhow!("invalid bind {}: {}", self.bind, e)) + } + } + +Bind-safety check (called during `start_server`): + + pub fn enforce_bind_safety(server: &ServerConfig, auth: &AuthConfig) -> anyhow::Result<()> { + let addr = server.parsed_bind()?; + let is_loopback = match addr.ip() { + std::net::IpAddr::V4(v) => v.is_loopback(), + std::net::IpAddr::V6(v) => v.is_loopback(), + }; + if !is_loopback && !auth.enabled { + anyhow::bail!( + "refusing to bind {} with auth disabled; \ + set [auth] enabled = true in vestige.toml or \ + change [server] bind to a loopback address", + addr + ); + } + Ok(()) + } + +`main.rs` and the `serve` CLI both call `enforce_bind_safety` before +`TcpListener::bind`. On failure: `eprintln!` the error, `std::process::exit(2)`. + +Env bridge: + +- `VESTIGE_HTTP_BIND` (existing) -> `server.bind` host part. +- `VESTIGE_HTTP_PORT` (existing) -> `server.bind` port part. +- `VESTIGE_DASHBOARD_PORT` (existing) -> `server.dashboard_port`. +- `VESTIGE_AUTH_TOKEN` (deprecated) -- when set, synthesize a virtual + `ApiKeyRecord` with `id = all-zero UUID`, `scopes = [read, write]`, + `domain_filter = []`, `active = true`, hash stored in memory only. Log a + warning on every startup: `VESTIGE_AUTH_TOKEN is deprecated; use 'vestige + keys create' and set auth.enabled=true instead. Will be removed in v2.2.0.` +- `VESTIGE_SESSION_SECRET` -- see D3. + +### D10. Dashboard login + logout + +File: `crates/vestige-mcp/src/dashboard/handlers.rs` (additions). + + #[derive(serde::Deserialize)] + pub struct LoginBody { + pub api_key: String, + } + + pub async fn login( + State(state): State, + jar: SignedCookieJar, + headers: HeaderMap, + body: Option>, + ) -> Result<(SignedCookieJar, Json), AuthError> { + // Accept key in either JSON body or X-API-Key header + let plaintext = body.map(|b| b.0.api_key) + .or_else(|| headers.get("x-api-key").and_then(|h| h.to_str().ok()).map(String::from)) + .ok_or(AuthError::MissingCredentials)?; + + let hash = crate::auth::keys::hash_key(&plaintext); + let rec = state.store.find_api_key_by_hash(&hash).await + .map_err(|_| AuthError::Internal)? + .ok_or(AuthError::InvalidCredentials)?; + if !rec.active { return Err(AuthError::Revoked); } + + let secure = state.config.server.tls_cert.is_some(); + let jar = crate::auth::session::issue_session(jar, rec.id, secure); + + Ok((jar, Json(serde_json::json!({ + "ok": true, "key_id": rec.id, "label": rec.label, + "scopes": rec.scopes.iter().map(|s| s.as_str()).collect::>(), + "domains": rec.domain_filter, + })))) + } + + pub async fn logout(jar: SignedCookieJar) + -> (SignedCookieJar, Json) + { + (crate::auth::session::revoke_session(jar), + Json(serde_json::json!({"ok": true}))) + } + +Dashboard router integration: login/logout are appended before `auth_layer` +is applied, so they are reachable unauthenticated. The dashboard SPA asset +routes (`/dashboard`, `/dashboard/{*path}`) remain publicly readable so the +login page can load; the `/api/*` dashboard endpoints are gated by +`auth_layer`. (The existing health endpoint keeps its current behaviour.) + +### D11. `vestige keys` CLI + +File: `crates/vestige-mcp/src/bin/cli.rs` additions. + + #[derive(Subcommand)] + enum Commands { + // ... existing + /// Manage API keys + Keys { + #[command(subcommand)] + sub: KeyCmd, + }, + } + + #[derive(Subcommand)] + enum KeyCmd { + /// Create a new API key + Create { + #[arg(long)] label: String, + #[arg(long, value_delimiter = ',', default_values_t = ["read".to_string(), "write".to_string()])] + scopes: Vec, + /// Restrict the key to listed domains (comma-separated). Empty = all domains. + #[arg(long, value_delimiter = ',')] + domains: Vec, + }, + /// List existing keys (never shows plaintext) + List { + /// Include revoked keys in the output + #[arg(long)] all: bool, + }, + /// Revoke a key by id or by hash prefix + Revoke { + /// Id (UUID) or hash prefix (first 12 hex chars) + id_or_prefix: String, + }, + /// Revoke and re-create with the same scopes/label + Rotate { + id_or_prefix: String, + }, + } + +`Create` outputs the plaintext exactly once on stdout (for piping into env +files) and a confirmation on stderr. Use colored output only on stderr to keep +stdout machine-readable. + + fn run_keys_create(...) -> anyhow::Result<()> { + let store = open_store()?; // Arc + let plaintext = crate::auth::keys::generate_key(); + let hash = crate::auth::keys::hash_key(plaintext.as_str()); + let rec = ApiKeyRecord { + id: uuid::Uuid::new_v4(), + key_hash: hash, label, scopes, domain_filter: domains, + created_at: chrono::Utc::now(), + last_used: None, active: true, + }; + block_on(store.create_api_key(&rec))?; + + // stderr: human-readable + eprintln!("{} {}", "Created key:".green().bold(), rec.label); + eprintln!(" id: {}", rec.id); + eprintln!(" scopes: {}", rec.scopes.iter().map(|s| s.as_str()).collect::>().join(",")); + eprintln!(" domains: {}", if rec.domain_filter.is_empty() { "all".to_string() } else { rec.domain_filter.join(",") }); + eprintln!(); + eprintln!("{}", "Store the plaintext key now. It will not be shown again.".yellow()); + // stdout: ONLY the plaintext, for scripting + println!("{}", plaintext.as_str()); + Ok(()) + } + +`List`: + + kid label scopes domains last_used hash + d3a8... macbook read,write all 2026-04-20 11:02 a1b2c3d4e5f6 + ... + +Never print the plaintext. Show only `hash[..12]`. + +### D12. Migrations + +Postgres `0300_api_keys.sql` (idempotent; Phase 2 may have already created the +table, in which case this migration is a no-op `CREATE TABLE IF NOT EXISTS`): + + CREATE TABLE IF NOT EXISTS api_keys ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + key_hash TEXT NOT NULL UNIQUE, + label TEXT NOT NULL, + scopes TEXT[] NOT NULL DEFAULT ARRAY['read','write'], + domain_filter TEXT[] NOT NULL DEFAULT ARRAY[]::TEXT[], + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + last_used TIMESTAMPTZ, + active BOOLEAN NOT NULL DEFAULT true + ); + + CREATE INDEX IF NOT EXISTS idx_api_keys_active + ON api_keys (active) WHERE active; + +SQLite `0300_api_keys.sql`: + + CREATE TABLE IF NOT EXISTS api_keys ( + id TEXT PRIMARY KEY, + key_hash TEXT NOT NULL UNIQUE, + label TEXT NOT NULL, + scopes TEXT NOT NULL DEFAULT 'read,write', -- comma-joined + domain_filter TEXT NOT NULL DEFAULT '', -- comma-joined, '' = all + created_at TEXT NOT NULL DEFAULT (datetime('now')), + last_used TEXT, + active INTEGER NOT NULL DEFAULT 1 + ); + + CREATE INDEX IF NOT EXISTS idx_api_keys_active + ON api_keys (active) WHERE active = 1; + +Both backends' trait impls convert to/from `ApiKeyRecord`. + +### D13. Wiring main.rs and the `serve` CLI path + +`main.rs` refactor: + +1. `Config::load()` reads `vestige.toml` (if present) and overlays env vars. +2. Run `enforce_bind_safety(&cfg.server, &cfg.auth)` before spawning any + listener. On failure, print to stderr and exit 2. +3. Build `AppCtx` with `Arc`, `CognitiveEngine`, + event bus, `session_key`, `config`. +4. `build_router(ctx)` returns a single Axum `Router` that covers MCP, REST, + and dashboard. +5. `axum::serve(listener, app).await`. +6. The stdio MCP transport continues to run in parallel (unchanged) for + desktop / Claude Code single-user scenarios. + +`serve` CLI subcommand: identical flow minus stdio. + +### D14. Docs + +- `docs/env-vars.md` new: table of every supported env var, default, purpose, + deprecation status. +- Section in `README.md`: "Running Vestige as a network server". +- Cheat-sheet section in `CLAUDE.md` for: create a key, start the server, + curl smoke test. + +## Test Plan + +### Unit tests (colocated under `#[cfg(test)]`) + +- `auth/keys.rs`: + - `generate_key_has_prefix_and_length()` -- asserts `vst_` prefix and 34-ish + char total, regex `^vst_[A-Za-z0-9_-]{29}$`. + - `hash_key_blake3_is_stable_and_hex()` -- fixed vector test. + - `verify_key_accepts_same_input()` / `verify_key_rejects_tampered()` / + `verify_key_rejects_length_mismatch()`. + - `keys_are_unique_in_a_loop()` -- 10_000 iterations, no collisions. + - `plaintext_zeroed_on_drop()` -- unsafe peek into the backing buffer + through a wrapper that exposes bytes for the test only. + +- `auth/session.rs`: + - `round_trip_claims_through_signed_jar()`. + - `expired_cookie_is_rejected()` -- mint a cookie with `exp = iat - 60` and + confirm `claims_from` returns `None`. + - `tampered_cookie_is_rejected()` -- flip one byte in the signed segment, + confirm the jar drops it. + - `session_key_env_overrides_file()`. + - `session_key_generated_file_has_mode_0600_on_unix()`. + +- `auth/middleware.rs`: + - `extract_credentials_prefers_bearer_over_api_key_header()`. + - `extract_credentials_falls_back_to_cookie()`. + - `effective_domain_filter_empty_means_all()`. + - `effective_domain_filter_header_narrows_within_key_filter()`. + - `effective_domain_filter_rejects_header_outside_key_filter()`. + - `missing_credentials_returns_401()`. + - `revoked_key_returns_401()`. + - `insufficient_scope_returns_403()`. + +- `config.rs`: + - `parse_vestige_toml_with_server_and_auth_sections()`. + - `env_vars_override_toml_bind()`. + - `enforce_bind_safety_rejects_0_0_0_0_with_auth_disabled()`. + - `enforce_bind_safety_allows_0_0_0_0_with_auth_enabled()`. + - `enforce_bind_safety_allows_loopback_with_auth_disabled()`. + +- `http/errors.rs`: + - `not_found_emits_problem_json_with_correct_content_type()`. + - `bad_request_includes_detail_field()`. + +- `http/mcp.rs`: + - `post_mcp_unauth_returns_401()` (this would normally be caught by the + middleware; kept as a unit test by constructing the Router minus the + middleware to exercise the handler's own error paths). + +### Integration tests (`tests/phase_3/`) + +All tests spin up the full Axum stack in-process on a random port via +`tokio::net::TcpListener::bind("127.0.0.1:0")`, wire a `SqliteMemoryStore` in +a `TempDir`, and issue HTTP calls with `reqwest`. + +Files (each one a standalone binary test file): + +- `phase_3/common/mod.rs` -- shared harness (`spawn_server()`, + `create_test_key()`, `client()`). + +- `phase_3/http_mcp_round_trip.rs` -- boot server, mint a key, send + `initialize` over `POST /mcp` with `Authorization: Bearer vst_...`, follow + with `tools/list`, assert we see the expected tool count (greater than 20). + +- `phase_3/http_sse_stream.rs` -- `POST /api/v1/consolidate` returns 202 + + `session_id`. `GET /mcp?op=consolidate&session=...` streams at least one + `progress` and one `done` event. Use `eventsource-client` dev dep, or parse + the stream manually. + +- `phase_3/rest_api_crud.rs` -- exercises each REST endpoint in turn: + - `POST /api/v1/memories` -> 201 + body. + - `GET /api/v1/memories/{id}` -> 200. + - `PUT /api/v1/memories/{id}` -> 200. + - `POST /api/v1/search` -> 200 with the new memory in results. + - `POST /api/v1/memories/{id}/promote` -> 200. + - `GET /api/v1/stats` -> 200. + - `GET /api/v1/domains` -> 200 (likely empty). + - `DELETE /api/v1/memories/{id}` -> 204. + +- `phase_3/auth_bearer_token.rs`: + - unauth: `GET /api/v1/stats` returns 401 and `Content-Type: + application/problem+json`. + - valid Bearer: same call returns 200. + - revoked key: `POST /api/v1/keys/{id}` DELETE then reuse -> 401. + - tampered Bearer (last char flipped) -> 401. + +- `phase_3/auth_api_key_header.rs`: + - `X-API-Key: vst_...` alone -> 200. + - Both Bearer and X-API-Key with different values -> Bearer wins (asserted + via a key that is read-only in Bearer + full-scope X-API-Key, then + confirming a write 403s). + +- `phase_3/auth_session_cookie.rs`: + - `POST /dashboard/login` with valid key -> 200 + `Set-Cookie: + vestige_session=...; HttpOnly; SameSite=Strict; Path=/`. + - reuse cookie: `GET /api/v1/stats` returns 200. + - tampered cookie (change one char): -> 401. + - `POST /dashboard/logout` -> `Set-Cookie: vestige_session=; Max-Age=0`. + +- `phase_3/auth_domain_filter.rs`: + - Key with `domain_filter = ["dev"]`: + - `POST /api/v1/search` without header -> search is scoped to `["dev"]` + (insert fixtures with two domains, assert only `dev` rows returned). + - `X-Vestige-Domain: dev` -> same. + - `X-Vestige-Domain: home` -> 403 with detail `domain not permitted`. + - Key with empty filter + `X-Vestige-Domain: dev` -> scoped to `["dev"]`. + - Key with empty filter + no header -> no scoping. + +- `phase_3/auth_scope_enforcement.rs`: + - read-only key cannot call `POST /api/v1/memories` -> 403. + - read-only key CAN call `POST /api/v1/search` -> 200. + +- `phase_3/bind_safety_nonlocalhost_without_auth.rs`: + - Spawn `vestige serve --bind 0.0.0.0:0` as a subprocess with `auth.enabled + = false` via a temp `vestige.toml`. + - Assert: non-zero exit, stderr contains `refusing to bind`, no listener + ever opens (confirm by trying to connect to the configured port and + expecting connection refused after a short timeout). + +- `phase_3/cli_keys_create_list_revoke.rs`: + - Spawn the `vestige` CLI binary with `--data-dir `. + - Run `vestige keys create --label test --scopes read,write`; capture + stdout (the plaintext) and stderr (the human summary). Assert `vst_` + prefix in stdout. + - Run `vestige keys list`; assert no plaintext, label `test` present. + - Run `vestige keys revoke `; confirm exit 0. + - Run `vestige keys list`; assert label no longer visible without `--all`. + +- `phase_3/dashboard_login_flow.rs`: + - Full loop: login -> fetch `/dashboard` (gets SPA index, unauthed ok) -> + fetch `/api/memories` (authed via cookie) -> logout -> fetch `/api/memories` + (401). + +- `phase_3/deprecation_auth_token.rs`: + - Start the server with `VESTIGE_AUTH_TOKEN=test12345...` and no created + keys. Send a Bearer request with that token -> 200. Assert stderr log + contains `deprecated`. + +### Smoke test (`tests/phase_3/smoke/`) + +- `remote_mcp_client.sh`: + + #!/usr/bin/env bash + set -euo pipefail + KEY="${VESTIGE_TEST_KEY:?set me}" + HOST="${VESTIGE_HOST:-http://127.0.0.1:3928}" + # Initialize a session + RESP=$(curl -sS -D /tmp/h -H "Authorization: Bearer $KEY" \ + -H "Content-Type: application/json" \ + -d '{"jsonrpc":"2.0","id":1,"method":"initialize", + "params":{"protocolVersion":"2025-11-25", + "clientInfo":{"name":"smoke","version":"0"}, + "capabilities":{}}}' \ + "$HOST/mcp") + SID=$(grep -i 'mcp-session-id:' /tmp/h | awk '{print $2}' | tr -d '\r') + # tools/list + curl -sS -H "Authorization: Bearer $KEY" \ + -H "Mcp-Session-Id: $SID" \ + -H "Content-Type: application/json" \ + -d '{"jsonrpc":"2.0","id":2,"method":"tools/list"}' \ + "$HOST/mcp" | jq '.result.tools | length' + echo "smoke ok" + +## Acceptance Criteria + +- [ ] `cargo build -p vestige-mcp` -- zero warnings, all feature combinations + (`--no-default-features`, default, `--features ort-dynamic`). +- [ ] `cargo clippy --workspace --all-targets --all-features -- -D warnings`. +- [ ] `cargo fmt --all --check`. +- [ ] All `tests/phase_3/*.rs` pass, plus phase_1 and phase_2 remain green. +- [ ] Unauth request to `POST /mcp` returns 401 with + `Content-Type: application/problem+json` and a body containing `status`, + `title`, `detail`. +- [ ] Binding `0.0.0.0:` with `[auth].enabled = false` makes the + process exit with code 2 and print `refusing to bind` to stderr. +- [ ] `vestige keys create --label X` prints exactly one line on stdout + matching `^vst_[A-Za-z0-9_-]+$`; `vestige keys list` never prints that + line back. +- [ ] Dashboard login from a browser-like client (tested via the reqwest + `Client::cookie_store(true)` harness) yields a `Set-Cookie` with + `HttpOnly`, `SameSite=Strict`, `Path=/`, and Max-Age present. +- [ ] A second machine can run a curl-based MCP client against the server + (smoke test) and receive successful `tools/list` responses. +- [ ] `VESTIGE_AUTH_TOKEN` still works and emits the deprecation warning. +- [ ] `tests/phase_3/auth_domain_filter.rs` demonstrates that a key scoped to + `dev` cannot read `home`-domain memories via any of the three auth modes + and cannot escape with `X-Vestige-Domain`. + +## Rollback Notes + +- Ship behind an on-by-default Cargo feature `http-server` on + `vestige-mcp`. Disabling it reverts to stdio + existing localhost HTTP + (`protocol/http.rs` in its current form) with zero behaviour change. +- SQL: migration `0300_api_keys.sql` is additive only; rollback is a single + `DROP TABLE api_keys;` in `0300_api_keys.down.sql` for both backends. Keep a + row count safety check in the down migration and log the deletion. +- Session secret file: deleting `/session_secret` invalidates every + outstanding cookie; users simply log in again. Safe to rotate. +- Env var sunset schedule: + - v2.1.x: `VESTIGE_AUTH_TOKEN` emits a warning, still works. + - v2.2.0: `VESTIGE_AUTH_TOKEN` refused with an error pointing at + `vestige keys create`. +- Downgrade procedure: `git revert` the Phase 3 merge, then run the down + migration. No data loss; plaintext keys were only ever in user-side + secret managers. + +## Open Implementation Questions + +1. JSON-RPC library: hand-rolled vs jsonrpsee? + + - Candidate A: keep the hand-rolled types in `protocol/types.rs` plus the + session-aware `post_mcp` handler already in `protocol/http.rs`. + - Candidate B: switch to `jsonrpsee = "0.24"` with the `server` feature + and adapt it to Axum via `jsonrpsee::server::Server`. + + RECOMMENDATION: A. Phase 3 is about auth and transport surfaces, not + library rewrites. The existing types are already correct, tested, and + compatible with Streamable HTTP; the 29 cognitive modules depend on + `McpServer::handle_request`, which does not map 1:1 to jsonrpsee's + `RpcModule` trait. Re-evaluate in a future phase only if we need subscription + notifications beyond SSE. + +2. Streamable HTTP vs plain POST-with-JSON? + + - The MCP spec titled "Streamable HTTP" defines: `POST /mcp` for + request/response, `GET /mcp` for SSE where the client subscribes to + server-initiated messages, and an `Mcp-Session-Id` header for session + correlation. The current implementation already covers POST + session + header + DELETE; Phase 3 adds the GET/SSE half. + + RECOMMENDATION: implement the full Streamable HTTP transport. Long-running + tools (dream, consolidate, discover) benefit from SSE progress events, and + Claude Desktop / Claude Code both speak Streamable HTTP natively. Keeping + POST-only would work for short calls but block the UX we want for + background jobs. + +3. Session cookie crate? + + - Candidate A: `axum-extra::extract::cookie::SignedCookieJar` with a 64-byte + `Key`. + - Candidate B: `tower-sessions = "0.13"` with the `MemoryStore` or + `PostgresStore` session backend. + - Candidate C: stateless JWT via `jsonwebtoken`. + + RECOMMENDATION: A. We do not need server-side session state (the `api_keys` + row is the state; the cookie is merely a signed pointer to it). B adds a + whole storage backend we do not need. C adds signing-algorithm surface area + and revocation becomes awkward ("revoked key" with a long-lived JWT). + `SignedCookieJar` gives us HMAC-signed cookies for free, integrates with + axum extractors, and the payload is tiny. + +4. Key format and length? + + - 22 random bytes base64url-no-pad = 176 bits entropy, encoded ~30 chars, + full key ~34 chars with the `vst_` prefix. Long enough to make + brute-force infeasible, short enough to paste into config files. + - Alternatives: 32 bytes (40 chars, overkill), 16 bytes (128 bits, marginal + for secret material shared over networks). + + RECOMMENDATION: 22 bytes. Prefix `vst_` is already documented in the PRD + and gives grep-ability. + +5. Rate limiting: in scope for Phase 3? + + - Useful: mitigates slow brute force, runaway agents. + - Expensive to design well (per-key, per-IP, per-endpoint). + + RECOMMENDATION: OUT of scope. Track as `docs/adr/0002-rate-limiting.md` + follow-up. Axum + `tower` has `ConcurrencyLimitLayer` (already used); a + follow-up can add `governor` or `tower_governor` behind the auth layer so + identity is available. + +6. CORS policy defaults for dashboard in server mode? + + - Candidate A: allow only origins derived from `server.bind` host + the + dashboard port. + - Candidate B: allow user-listed origins via `server.allowed_origins` + config, with A as fallback. + - Candidate C: open CORS to `*` when TLS is configured. + + RECOMMENDATION: B. Auto-populate `allowed_origins` from the bind address + and dashboard port at start time; if the operator sets the config list, + use that list verbatim. Never `*` (`allow_credentials = true` is + incompatible with `*` anyway). + +7. Dashboard session lifetime? + + - 8 hours for default; configurable via `auth.session_ttl_hours`. + - Rotate on each write? (Rolling sessions.) + + RECOMMENDATION: 8 hours fixed, non-rolling. Revisit if users complain. + +8. Handling `tools/call` scope granularity? + + - Today, `tools/call` is a single MCP method. Read-only tools like + `search`, `deep_reference`, `predict` should be callable with a + read-only key. + + RECOMMENDATION: map tool names to scopes in `McpServer::handle_tools_call`. + Read-only names: `search`, `session_context`, `memory` with action in + `{get, state, get_batch}`, `deep_reference`, `cross_reference`, `predict`, + `explore_connections`, `find_duplicates`, `memory_timeline`, + `memory_changelog`, `memory_health`, `memory_graph`, `importance_score`, + `system_status`. Everything else requires `write`. If a read-only key + calls a write tool, return a JSON-RPC error with code `-32003` + ("server not initialized" is close but wrong; reuse `-32603 internal` with + a descriptive message or add a new `-32004 UnauthorizedTool`). RECOMMEND + adding `-32004`. + +9. How to bridge `MemoryStore` trait with dashboard state (`AppState`)? + + - Today `AppState.storage: Arc` is a concrete type. + - Phase 2 introduces `Arc`. + + RECOMMENDATION: in Phase 3, introduce `AppCtx { store: Arc, + cognitive, config, event_tx }` as the single state type for the unified + router. Keep `AppState` as a thin wrapper (or alias) if the dashboard + handlers need to stay untouched in this phase. Migrate the dashboard + handlers to the trait in a follow-up refactor to contain the blast radius. + +10. Windows support for `session_secret` and `auth_token` file modes? + + - Unix gets `0600` via `OpenOptionsExt`. + - Windows has no direct equivalent; ACLs differ. + + RECOMMENDATION: document the limitation; use default permissions on + Windows. Add a `#[cfg(windows)]` placeholder to set owner-only ACLs via + `windows-acl` in a follow-up, not Phase 3. + +### Critical Files for Implementation + +- /home/delandtj/prppl/vestige/crates/vestige-mcp/src/protocol/http.rs +- /home/delandtj/prppl/vestige/crates/vestige-mcp/src/dashboard/mod.rs +- /home/delandtj/prppl/vestige/crates/vestige-mcp/src/main.rs +- /home/delandtj/prppl/vestige/crates/vestige-mcp/src/bin/cli.rs +- /home/delandtj/prppl/vestige/crates/vestige-mcp/Cargo.toml diff --git a/docs/plans/0004-phase-4-emergent-domain-classification.md b/docs/plans/0004-phase-4-emergent-domain-classification.md new file mode 100644 index 0000000..d9f2355 --- /dev/null +++ b/docs/plans/0004-phase-4-emergent-domain-classification.md @@ -0,0 +1,883 @@ +# Phase 4 Plan: Emergent Domain Classification + +**Status**: Draft +**Depends on**: Phase 1 (domain columns on memories, `Domain` struct + `DomainStore` methods on `MemoryStore`, `Embedder` trait), Phase 2 (Postgres JSONB + TEXT[] support for domain fields, `embedding_model` registry parity), Phase 3 (Axum HTTP server, REST `/api/v1/` scaffolding, API key auth middleware, signed dashboard session cookies) +**Related**: docs/adr/0001-pluggable-storage-and-network-access.md (Phase 4), docs/prd/001-getting-centralized-vestige.md (Emergent Domain Model) + +--- + +## Scope + +### In scope + +- `DomainClassifier` cognitive module under `crates/vestige-core/src/neuroscience/domain_classifier.rs`, alongside existing neuroscience modules (spreading_activation, synaptic_tagging, ...). +- HDBSCAN discovery pipeline using the `hdbscan` crate (v0.10): load all embeddings, cluster, extract centroids, extract top-terms via TF-IDF over cluster members, persist via the trait's `DomainStore` methods. +- Soft-assignment pipeline: for each memory, compute `cosine_similarity(memory.embedding, domain.centroid)` for every domain, store raw scores in `domain_scores` JSONB, threshold into `domains[]` using `assign_threshold` (default 0.65). +- Automatic classification on ingest: run through `CognitiveEngine` / `smart_ingest` so new memories get classified against existing centroids immediately; skip when `domain_count == 0` (Phase 0 accumulation). +- Re-cluster hook in dream consolidation: every Nth four-phase dream cycle (N=5 default) triggers a discovery pass and generates proposals (split / merge / none). Proposals land in a new `domain_proposals` table, surface in the dashboard, and are never auto-applied (conservative drift, ADR Q7). +- Context signals: `SignalSource` trait with `GitRepoSignal` (detects `.git` in CWD or `metadata.cwd`) and `IdeHintSignal` (reads `metadata.editor` / `metadata.ide`). Each returns a `boost_map` of `domain_id -> additive delta` (typical +0.05). Injected as a `signal_boost: Option>` parameter into `DomainClassifier::classify`. +- Cross-domain spreading activation decay: `ActivationNetwork` traversal multiplies the edge's effective weight by `cross_domain_decay` (default 0.5) when `target.domains` and `source.domains` are disjoint. Strict "no overlap" policy, not graded. +- CLI subcommands (in `crates/vestige-mcp/src/bin/cli.rs`, under a new `Domains` command group): `list`, `discover [--min-cluster-size N] [--force]`, `rename `, `merge [--into ]`. Human-readable tables on stdout; JSON via `--json`. +- Dashboard UI additions (`apps/dashboard/src/routes/(app)/domains/`): list page, per-domain detail (memories, centroid top_terms, score histogram, proposal review controls). +- REST endpoints under `/api/v1/domains` (introduced by Phase 3 skeleton, implemented in Phase 4): list, discover, rename, merge, proposal list / accept / reject. +- Config additions: `[domains]` section in `vestige.toml` covering `assign_threshold`, `recluster_interval`, `min_cluster_size`, `cross_domain_decay`, `discovery_threshold`, `merge_threshold`, `signal_boost` (per-signal toggle). + +### Out of scope + +- Phase 5 federation (explicit separate ADR). Domain centroids are installation-local; no sync. +- Learned re-weighting of domain scores (future, only if retrieval-quality metrics show a need). +- Interactive cluster-membership editing in the UI (drag-and-drop reassign) -- future enhancement. +- Multi-user domain namespaces. One domain set per installation; API keys that carry `domain_filter` just restrict access, they do not create namespaces. +- Auto-sweep of `min_cluster_size` / auto-tuned `assign_threshold` (ADR resolution Q6 + Q9: static defaults, user tunes). +- Graded cross-domain decay (`|A intersect B| / max(|A|,|B|)`) -- strict "no overlap" is the Phase 4 rule. + +--- + +## Prerequisites + +Artifacts that Phases 1-3 are expected to have landed: + +- In `vestige-core`: + - `Embedder` trait (`crates/vestige-core/src/embedder/`). + - `MemoryStore` trait (`crates/vestige-core/src/storage/trait.rs` or similar) including `DomainStore` methods: `list_domains`, `get_domain`, `upsert_domain`, `delete_domain`, `classify(&[f32]) -> Vec<(String, f64)>`, plus a bulk accessor such as `all_embeddings()` (already present in sqlite.rs as `get_all_embeddings`) and a `get_all_memories_with_embeddings()` iterator for discovery. The trait must expose a method to batch-update `(domains, domain_scores)` for a memory id. + - `Domain` struct: `{ id: String, label: String, centroid: Vec, top_terms: Vec, memory_count: usize, created_at: DateTime }`. + - Columns on memories in both SQLite and Postgres: `domains TEXT[]` (or JSON array on SQLite) and `domain_scores JSONB` (or TEXT JSON on SQLite). + - The `domains` table in both backends (see PRD schema sketch). +- In `vestige-mcp`: + - Axum `/api/v1/` router prefix with auth middleware. + - CLI skeleton (`bin/cli.rs`) using `clap`; Phase 4 adds a `Domains` subcommand tree. + - REST handlers file structure ready under `crates/vestige-mcp/src/dashboard/handlers.rs` (legacy) and a dedicated REST handler under `/api/v1/`; Phase 4 adds `domains.rs` handler module. + - SvelteKit dashboard (`apps/dashboard/`) with existing `(app)/memories`, `(app)/timeline`, `(app)/stats`, etc. Phase 4 adds `(app)/domains/`. + +New workspace crate additions required (added manually to `Cargo.toml`, since `cargo add` is not run from the plan): + +- `hdbscan = "0.10"` in `crates/vestige-core/Cargo.toml` (feature-gated behind `domain-classification`). +- Optional: a lightweight stop-word constant inline; no external stop-word crate -- the neuroscience modules already do tokenization on whitespace + length>3 (see `dreams.rs::content_similarity`). Reuse that style; no `ndarray` needed because `hdbscan` v0.10 accepts `&[Vec]` directly (verified from PRD snippet). +- No new deps in `vestige-mcp` for Phase 4 -- CLI reuses `clap` / `colored` / `comfy-table` if already present, otherwise a hand-rolled padded print. We pick hand-rolled to avoid adding a table crate; this matches the existing style of `run_stats` in `cli.rs`. + +Test fixtures: + +- A JSON seed corpus checked into `tests/phase_4/fixtures/seed_500.json` containing >= 500 memories drawn from three plausible clusters. A builder function `tests/phase_4/support/fixtures.rs::build_seed_corpus()` deterministically generates or loads this corpus. Each record has `content`, `tags`, `embedding` (768D bge-base-en-v1.5; use a committed vector or a deterministic mock embedder in tests). For deterministic tests we fake embeddings by hashing content -- acceptable as long as the fake preserves cluster separability (prefix-based: "DEV-...", "INFRA-...", "HOME-..." seeds three Gaussian blobs). +- Reuse `Embedder` mock from Phase 1 tests (`MockEmbedder`) for discovery tests that need real cosine similarity. +- A minimal git-repo fixture created in a tempdir (`tempfile::tempdir` + `std::process::Command::new("git").arg("init")`) for context-signal tests. + +--- + +## Deliverables + +1. `DomainClassifier` cognitive module: struct, defaults, `classify`, `classify_with_boost`, `reassign_all`, `discover`. +2. `domain_terms` helper (TF-IDF over cluster members, returning `top_k` terms). +3. `cli domains discover` subcommand. +4. `cli domains list` / `rename` / `merge` subcommands. +5. Auto-classify hook on ingest (wired into the cognitive engine's ingest pipeline before persistence). +6. Re-cluster hook in dream consolidation (`DreamEngine::run` orchestrator gets an optional `DomainReClusterHook`; triggers every Nth dream). +7. Context signal extractor module (`crates/vestige-core/src/neuroscience/context_signals.rs`) with `SignalSource` trait + `GitRepoSignal` + `IdeHintSignal`. +8. Cross-domain spreading activation decay in `ActivationNetwork::activate` (config-driven). +9. `vestige.toml` `[domains]` section + defaults loader. +10. Dashboard UI: SvelteKit routes `(app)/domains/+page.svelte` (list), `(app)/domains/[id]/+page.svelte` (detail), `(app)/domains/proposals/+page.svelte` (review). +11. REST endpoints under `/api/v1/domains` + `/api/v1/domains/proposals`. +12. `domain_proposals` table + migration + `DomainProposal` trait methods on `MemoryStore`. +13. WebSocket event `VestigeEvent::DomainProposalCreated` so the dashboard gets a live notification after a re-cluster fires. + +--- + +## Detailed Task Breakdown + +### 1. `DomainClassifier` cognitive module + +**File**: `crates/vestige-core/src/neuroscience/domain_classifier.rs` +**Export**: in `crates/vestige-core/src/neuroscience/mod.rs`, add `pub mod domain_classifier;` and re-export `pub use domain_classifier::{DomainClassifier, ClassificationResult, DomainProposal, ProposalKind};` +**Deps**: `hdbscan = "0.10"`, `serde`, `serde_json`, `chrono`, `tracing`, existing `crate::storage::Domain`, `crate::storage::MemoryStore` trait. + +Struct and defaults (match PRD exactly): + +```rust +pub struct DomainClassifier { + pub assign_threshold: f64, // default 0.65 + pub discovery_threshold: usize, // default 150 + pub recluster_interval: usize, // default 5 (every 5th dream) + pub min_cluster_size: usize, // default 10 + pub min_samples: usize, // default 5 (HDBSCAN) + pub cross_domain_decay: f64, // default 0.5 + pub merge_threshold: f64, // default 0.90 (centroid cosine) + pub top_terms_k: usize, // default 10 +} + +impl Default for DomainClassifier { ... } +``` + +Result types: + +```rust +#[derive(Debug, Clone)] +pub struct ClassificationResult { + pub scores: HashMap, // raw per-domain similarities + pub domains: Vec, // above assign_threshold +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ProposalKind { + Split { parent: String, children: Vec }, + Merge { targets: Vec, suggested_label: String }, + NewCluster { top_terms: Vec }, +} + +#[derive(Debug, Clone)] +pub struct DomainProposal { + pub id: String, // uuid v4 + pub kind: ProposalKind, + pub rationale: String, + pub confidence: f64, + pub created_at: DateTime, + pub status: ProposalStatus, // Pending | Accepted | Rejected +} +``` + +Key methods (all pure where possible; all pub): + +```rust +impl DomainClassifier { + pub fn classify(&self, embedding: &[f32], domains: &[Domain]) -> ClassificationResult; + + pub fn classify_with_boost( + &self, + embedding: &[f32], + domains: &[Domain], + boost: Option<&HashMap>, + ) -> ClassificationResult; + + pub async fn reassign_all( + &self, + store: &dyn MemoryStore, + domains: &[Domain], + ) -> Result; + + pub async fn discover( + &self, + store: &dyn MemoryStore, + ) -> Result, StorageError>; + + pub async fn propose_changes( + &self, + store: &dyn MemoryStore, + existing: &[Domain], + newly_discovered: &[Domain], + ) -> Result, StorageError>; + + pub async fn apply_proposal( + &self, + store: &dyn MemoryStore, + proposal: &DomainProposal, + ) -> Result<(), StorageError>; +} +``` + +Behavior notes: + +- `classify` returns empty `{ scores: {}, domains: [] }` iff `domains.is_empty()` (accumulation phase). This matches the PRD snippet verbatim. +- `classify_with_boost` adds the boost delta to each score AFTER cosine, before thresholding. It clamps to `[0.0, 1.0]`. Boost keys not present in `domains` are ignored. +- `reassign_all` streams memories in batches of 500 (iterator on the store) to keep memory bounded; for each memory issues a single `UPDATE memories SET domains = ?, domain_scores = ? WHERE id = ?` call. Returns count of memories whose `domains` vector actually changed. +- `discover` loads all `(id, embedding)` pairs via an `all_embeddings()` method on the store (exists under `#[cfg(all(feature = "embeddings", feature = "vector-search"))]` in `sqlite.rs::get_all_embeddings`; Phase 1 should promote this onto the trait -- if not yet promoted, add the method). Then: + 1. Build `Vec>` and index -> id map. + 2. `Hdbscan::default_hyper_params(&embeddings).min_cluster_size(self.min_cluster_size).min_samples(self.min_samples).build()` (exact builder depends on hdbscan 0.10 surface; see Open Question). + 3. `let labels = clusterer.cluster()?;` + 4. `let centers = clusterer.calc_centers(Center::Centroid, &labels)?;` + 5. Group indices by label ignoring -1 (noise). For each cluster compute `top_terms` via `compute_top_terms`. + 6. Preserve stable IDs where possible: match each new cluster centroid to the closest existing domain by cosine; if similarity > 0.85, reuse the existing domain id + label. Otherwise generate a fresh id `cluster_{n}` with a label derived from the first 2 terms. + 7. Upsert all resulting `Domain`s via the store. +- `propose_changes` compares old vs new clusters: + - **Split**: an old domain that best-matches two or more new domains each with >= `min_cluster_size` members. Rationale: "domain `dev` is now 2 clusters of >=10 memories: `systems` and `networking`". + - **Merge**: two old domains whose centroids now satisfy `cosine > merge_threshold` get a merge proposal. + - **NewCluster**: a new cluster that doesn't match any old domain above 0.85 similarity. +- `apply_proposal` runs the split or merge against the store (reassign memberships via `reassign_all`), then marks the proposal `Accepted`. It never runs automatically -- only via the CLI or dashboard. + +Helper: + +```rust +fn compute_top_terms(documents: &[&str], k: usize) -> Vec; +``` + +Uses TF-IDF with IDF computed over the entire passed-in corpus (the `documents` slice), tokenization = whitespace split, lowercase, strip non-alphanumeric, drop tokens shorter than 4 chars and a small built-in stop-word list (`the`, `and`, `for`, `that`, `with`, ...). Matches the tokenizer used in `dreams.rs::content_similarity` and `dreams.rs::extract_patterns` so behavior is predictable. + +Cosine similarity helper: + +```rust +fn cosine_similarity(a: &[f32], b: &[f32]) -> f64; +``` + +Keep the existing crate-level `cosine_similarity` if already present (check `embeddings::` or `search::`); otherwise add a private one. Returns 0.0 on dimension mismatch, panics would be a bug. + +### 2. Top-terms computation helper + +**File**: same module, private section. + +- `fn tokenize(text: &str) -> Vec`: lowercase, split on non-alphanumeric, filter len >= 4, drop stop-words. +- `fn tfidf_top_k(docs: &[&str], k: usize) -> Vec`: + 1. `tf[doc_idx][term] = count / total_terms`. + 2. `df[term] = docs containing term`. + 3. `idf[term] = log((N + 1) / (df[term] + 1)) + 1` (smoothed). + 4. For each term, average `tf` across docs in the cluster; multiply by `idf`; sort desc; return top `k`. + +Cluster top-terms are computed over cluster members only, with IDF over the **whole corpus** (all memory contents), not the cluster, so common words get penalized globally. Recompute global IDF once per `discover` call. + +### 3. CLI subcommand: `vestige domains discover` + +**File**: `crates/vestige-mcp/src/bin/cli.rs` + +Add to `enum Commands`: + +```rust +/// Emergent domain management +Domains { + #[command(subcommand)] + action: DomainAction, +}, +``` + +```rust +#[derive(clap::Subcommand)] +enum DomainAction { + /// List all discovered domains + List { + #[arg(long)] json: bool, + }, + /// Run HDBSCAN discovery on all embeddings and propose domains + Discover { + #[arg(long, default_value_t = 10)] min_cluster_size: usize, + /// Skip the proposal flow and write new domains directly (first-time use) + #[arg(long)] force: bool, + #[arg(long)] json: bool, + }, + /// Rename a domain (by id) + Rename { + id: String, + new_label: String, + }, + /// Merge two domains + Merge { + a: String, + b: String, + #[arg(long)] into: Option, // default: `a` + }, +} +``` + +Handler plumbing lives in `run_domains(action)` dispatching to `run_domains_list`, `run_domains_discover`, `run_domains_rename`, `run_domains_merge`. Each opens the default `Storage`, constructs a `DomainClassifier::default()`, and invokes the appropriate method. + +Output format for `list`: + +``` +ID LABEL MEMORIES TOP TERMS +dev Development 87 rust, trait, async, tokio, zinit +infra Infrastructure 47 bgp, sonic, vlan, frr, peering +home Home 31 solar, kwh, battery, pool, esphome +(unclassified) 12 +``` + +Produced via plain `print!` with `%-15s %-18s %-10d %s` style padding. `--json` emits `serde_json::to_string_pretty(&domains)`. + +Output format for `discover` with `--force`: + +``` +HDBSCAN: 500 embeddings, min_cluster_size=10, min_samples=5 +Found 3 clusters (ignoring 14 noise points) + cluster_0 (N=47) top: bgp, sonic, vlan, frr, peering + cluster_1 (N=31) top: solar, kwh, battery, pool, esphome + cluster_2 (N=22) top: rust, trait, async, tokio, zinit + +Writing 3 domains to the store... +Soft-assigning 500 memories against centroids... + multi-domain: 43 + single-domain: 412 + unclassified (below threshold 0.65): 45 +Done in 7.4s. +``` + +Output format for `discover` without `--force` (post-Phase-0): + +``` +HDBSCAN: 623 embeddings, min_cluster_size=10 +Comparing to existing 3 domains... + +Proposals (pending, accept via dashboard or `vestige domains proposals`): + [split] dev -> (systems:34, networking:28) confidence 0.82 + [new] cluster_5 (books, novels, reading) confidence 0.71 + +Run `vestige domains proposals` to review, or open the dashboard. +``` + +### 4. CLI: `list`, `rename`, `merge` + +- `list`: calls `store.list_domains()`, fetches unclassified count via `store.count_memories_without_domains()` (Phase 1 should have provided this; if not, Phase 4 adds it to the trait and both backends). +- `rename`: `store.get_domain(id)` -> mutate `label` -> `store.upsert_domain`. No memory touch. +- `merge`: load both, compute blended centroid (weighted by `memory_count`), merge `top_terms` (union, recompute TF-IDF rank if both sides share the corpus), delete the non-`into` domain, call `reassign_all`. Wrapped in a transaction on Postgres; on SQLite rely on the existing writer-lock pattern. + +### 5. Auto-classify on ingest + +**File**: `crates/vestige-core/src/cognitive.rs` (or equivalent ingest entry in `vestige-mcp/src/tools/smart_ingest.rs`). + +Integration point: just before the record is persisted in the smart-ingest path, after the embedder has produced `embedding` and before `storage.insert(...)`. Trace the current call site -- today `Storage::ingest(IngestInput)` computes embedding inside storage; in Phase 1 the embedder becomes external (ADR decision Q2), so classification can hook right there in the cognitive engine. + +Pseudocode: + +```rust +let embedding = embedder.embed(&input.content).await?; +let domains = store.list_domains().await?; + +let (domains_assigned, domain_scores) = if domains.is_empty() { + (Vec::new(), HashMap::new()) +} else { + let boost = context_signals.gather_boost(&input.metadata, &domains); + let result = classifier.classify_with_boost(&embedding, &domains, boost.as_ref()); + (result.domains, result.scores) +}; + +record.embedding = Some(embedding); +record.domains = domains_assigned; +record.domain_scores = domain_scores; +store.insert(&record).await?; +``` + +Edge cases: + +- Accumulation phase (`domains.is_empty()`): skip classification entirely. Zero overhead. +- Embedding failed / skipped: leave `domains = []`, `domain_scores = {}`. Never fail ingest because of classification. +- Metric: emit `VestigeEvent::MemoryClassified { id, domains, top_score }` on the WebSocket bus so the dashboard sees it live. + +### 6. Re-cluster hook in dream consolidation + +**File**: `crates/vestige-core/src/advanced/dreams.rs` (long file, 1131-line `dream()` entry on the `MemoryDreamer` impl) plus `crates/vestige-core/src/consolidation/phases.rs` (the `DreamEngine::run` orchestrator). + +Design: the `DreamEngine::run(...)` returns `FourPhaseDreamResult`. It does not currently know how many times it has run. Phase 4 introduces a persistent counter on disk (column `dream_cycle_count` on a new singleton `system_state` table, or a simple row in the existing `metadata` / `embedding_model` registry). After the Integration phase finishes, the cognitive engine increments the counter and, if `counter % recluster_interval == 0`, launches discovery asynchronously: + +Extension struct in `phases.rs`: + +```rust +pub struct DreamReClusterHook<'a> { + pub classifier: &'a DomainClassifier, + pub store: &'a dyn MemoryStore, + pub event_tx: Option<&'a tokio::sync::mpsc::UnboundedSender>, +} + +impl<'a> DreamReClusterHook<'a> { + pub async fn tick(&self, cycle_count: usize) -> Result, StorageError> { + if cycle_count == 0 || cycle_count % self.classifier.recluster_interval != 0 { + return Ok(vec![]); + } + let existing = self.store.list_domains().await?; + let rediscovered = self.classifier.discover(self.store).await?; + let proposals = self + .classifier + .propose_changes(self.store, &existing, &rediscovered) + .await?; + for p in &proposals { + self.store.insert_domain_proposal(p).await?; + if let Some(tx) = self.event_tx { + let _ = tx.send(VestigeEvent::DomainProposalCreated { + id: p.id.clone(), + kind: format!("{:?}", p.kind), + confidence: p.confidence, + timestamp: Utc::now(), + }); + } + } + Ok(proposals) + } +} +``` + +Caller wires `tick()` after `DreamEngine::run()` returns, at the ingest/consolidation orchestrator level. The hook never mutates existing domains -- it only writes proposals. The acceptance path is manual (CLI or dashboard). + +Counter storage: add method `store.bump_dream_cycle_count() -> Result` returning the new count. Single-row table: + +```sql +CREATE TABLE IF NOT EXISTS system_state ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL +); +-- seed: ('dream_cycle_count', '0') +``` + +### 7. Context signal extractor + +**File**: `crates/vestige-core/src/neuroscience/context_signals.rs` + +```rust +pub trait SignalSource: Send + Sync { + /// Returns domain_id -> additive boost (positive or negative, typically in [-0.1, +0.1]). + fn boost_map( + &self, + input_metadata: &serde_json::Value, + domains: &[Domain], + ) -> HashMap; + + fn name(&self) -> &'static str; +} + +pub struct GitRepoSignal { + pub boost: f64, // default +0.05 +} + +pub struct IdeHintSignal { + pub boost: f64, +} + +pub struct ContextSignals { + sources: Vec>, +} + +impl ContextSignals { + pub fn gather_boost( + &self, + input_metadata: &serde_json::Value, + domains: &[Domain], + ) -> Option>; +} +``` + +Signal encoding convention (document in the module header): + +- A signal is a **soft prior**. It nudges the post-cosine score by a small additive delta, clamped to `[-0.10, +0.10]` per signal. +- Multiple signals sum, then the final boost per domain is clamped to `[-0.15, +0.15]` so signals cannot by themselves push a memory into or out of a domain; the embedding similarity dominates. +- Signals target domains by heuristic: `GitRepoSignal` boosts any domain whose `top_terms` overlaps `{"rust","async","trait","function","class","def","git","commit","fn","code"}`. `IdeHintSignal` does the same for `{"file","line","editor","vscode","neovim","rust-analyzer","lsp"}`. +- All signal boosts are logged via `tracing::debug!` so users can audit why a memory picked up a domain. + +`GitRepoSignal::boost_map` implementation: + +```rust +fn boost_map(&self, meta: &Value, domains: &[Domain]) -> HashMap { + let is_git = meta.get("cwd") + .and_then(|v| v.as_str()) + .map(|cwd| std::path::Path::new(cwd).join(".git").exists()) + .unwrap_or(false) + || meta.get("git_repo").is_some(); + if !is_git { return HashMap::new(); } + let mut out = HashMap::new(); + for d in domains { + let code_hits = d.top_terms.iter() + .filter(|t| CODE_TERMS.contains(t.as_str())) + .count(); + if code_hits > 0 { out.insert(d.id.clone(), self.boost); } + } + out +} +``` + +Config knob in `[domains.signals]`: `git = true`, `ide = true`, `git_boost = 0.05`, `ide_boost = 0.05`. + +### 8. Cross-domain spreading activation decay + +**File**: `crates/vestige-core/src/neuroscience/spreading_activation.rs` + +Modify `ActivationConfig`: + +```rust +pub struct ActivationConfig { + pub decay_factor: f64, + pub max_hops: u32, + pub min_threshold: f64, + pub allow_cycles: bool, + pub cross_domain_decay: f64, // NEW, default 0.5 +} +``` + +Domain metadata on nodes: the current `ActivationNode` has `id`, `activation`, `last_activated`, `edges: Vec`. Phase 4 adds `pub domains: Vec`. Populated when nodes get added (propagated from the memory's `domains` field). The network is rebuilt on each search from the store; if the in-memory network is persisted (check `ActivationNetwork` lifetime in `CognitiveEngine`), the population happens in the engine at boot and on insert. + +Traversal change, in `ActivationNetwork::activate` loop, replacing the single line `let propagated = current_activation * edge.strength * self.config.decay_factor;`: + +```rust +let cross_penalty = { + let src_doms = self.nodes.get(¤t_id).map(|n| &n.domains); + let tgt_doms = self.nodes.get(&target_id).map(|n| &n.domains); + match (src_doms, tgt_doms) { + (Some(s), Some(t)) if !s.is_empty() && !t.is_empty() => { + let overlap = s.iter().any(|d| t.contains(d)); + if overlap { 1.0 } else { self.config.cross_domain_decay } + } + _ => 1.0, // unclassified on either side: no penalty + } +}; +let propagated = current_activation * edge.strength * self.config.decay_factor * cross_penalty; +``` + +Rationale for "unclassified -> no penalty": unclassified memories are Phase-0 or low-confidence corpus members; penalizing them would block useful cross-pollination during the accumulation ramp. + +API to update a node's domains after reclassification: + +```rust +pub fn set_node_domains(&mut self, id: &str, domains: Vec); +``` + +Called by the reassignment pipeline after `reassign_all`. + +### 9. `vestige.toml` `[domains]` section + +**File**: wherever `vestige.toml` is loaded (search for `[storage]` / `[server]` loaders). Add: + +```toml +[domains] +assign_threshold = 0.65 +discovery_threshold = 150 +recluster_interval = 5 +min_cluster_size = 10 +min_samples = 5 +cross_domain_decay = 0.5 +merge_threshold = 0.90 +top_terms_k = 10 + +[domains.signals] +git = true +ide = true +git_boost = 0.05 +ide_boost = 0.05 +``` + +Rust-side: `DomainsConfig { ... }` struct with `serde(default)` so `vestige.toml` without a `[domains]` section falls back to hard-coded defaults. `DomainClassifier::from_config(cfg: &DomainsConfig) -> Self`. + +### 10. Dashboard UI additions + +**SvelteKit routes** (`apps/dashboard/src/routes/(app)/domains/`): + +- `+page.svelte` (list): fetches `GET /api/v1/domains` and `GET /api/v1/domains/unclassified-count`. Renders a table: `label`, `memories`, `top_terms` chips, `created_at`. Each row links to `/domains/[id]`. A "Discover" button posts `POST /api/v1/domains/discover`. +- `[id]/+page.svelte` (detail): fetches `GET /api/v1/domains/:id`, `GET /api/v1/domains/:id/memories?limit=100`, `GET /api/v1/domains/:id/score-histogram`. Renders: + - Header: label (editable, triggers `PUT /api/v1/domains/:id`), top-terms chips, memory count, created_at. + - Histogram: a vertical bar chart of `domain_scores[:id]` buckets 0-0.1, 0.1-0.2, ..., 0.9-1.0 across all memories. Data source: server precomputes buckets so the client does not need to fetch all scores. + - Memory list: paginated, each row shows the raw score for this domain. +- `proposals/+page.svelte`: fetches `GET /api/v1/domains/proposals?status=pending`. Each pending proposal card shows `kind`, `rationale`, `confidence`, `created_at`, buttons "Accept" (posts `POST /api/v1/domains/proposals/:id/accept`) and "Reject" (`POST .../reject`). Live updates via the existing WebSocket channel (`/ws`) reacting to `DomainProposalCreated` events. + +Styling reuses the existing Tailwind + shadcn-svelte conventions in `apps/dashboard/src/lib/components/`. + +Existing `(app)/stats` and `(app)/feed` pages get a small "Domains" summary panel that links to `/domains`. + +### 11. REST endpoints + +**File**: `crates/vestige-mcp/src/protocol/http.rs` or a new `crates/vestige-mcp/src/api/domains.rs` module, wired into the `/api/v1/` router. + +| Method | Path | Handler | +|--------|------|---------| +| GET | `/api/v1/domains` | `list_domains` -- returns `[Domain...]` + unclassified count | +| POST | `/api/v1/domains/discover` | `trigger_discover` -- body `{ min_cluster_size?: usize, force?: bool }`, returns proposals or applied domains | +| GET | `/api/v1/domains/:id` | `get_domain` | +| PUT | `/api/v1/domains/:id` | `update_domain` -- rename | +| DELETE | `/api/v1/domains/:id` | `delete_domain` -- with `?merge_into=other_id` | +| GET | `/api/v1/domains/:id/memories` | paginated memories in this domain | +| GET | `/api/v1/domains/:id/score-histogram` | precomputed buckets | +| GET | `/api/v1/domains/proposals` | `list_proposals?status=pending` | +| POST | `/api/v1/domains/proposals/:id/accept` | `accept_proposal` | +| POST | `/api/v1/domains/proposals/:id/reject` | `reject_proposal` | + +All handlers go through the Phase 3 auth middleware (Bearer / X-API-Key / session cookie). Responses are JSON; error paths use `StatusCode::*` with a small `{"error": "..."}` body. + +### 12. `domain_proposals` table + trait methods + +Postgres migration (`crates/vestige-core/migrations/postgres/00XX_domain_proposals.sql`): + +```sql +CREATE TABLE domain_proposals ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + kind TEXT NOT NULL, -- 'split' | 'merge' | 'new_cluster' + payload JSONB NOT NULL, -- serialized ProposalKind body + rationale TEXT NOT NULL, + confidence DOUBLE PRECISION NOT NULL, + status TEXT NOT NULL DEFAULT 'pending', -- pending|accepted|rejected + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + resolved_at TIMESTAMPTZ +); +CREATE INDEX idx_domain_proposals_status ON domain_proposals (status, created_at DESC); +``` + +SQLite migration: same table, `UUID` -> `TEXT`, `JSONB` -> `TEXT` with JSON-encoded bodies, `TIMESTAMPTZ` -> `TEXT` ISO-8601. + +`MemoryStore` trait additions: + +```rust +async fn insert_domain_proposal(&self, p: &DomainProposal) -> Result<()>; +async fn list_domain_proposals(&self, status: Option<&str>) -> Result>; +async fn get_domain_proposal(&self, id: &str) -> Result>; +async fn set_proposal_status(&self, id: &str, status: &str) -> Result<()>; +``` + +### 13. WebSocket event for proposals + +**File**: `crates/vestige-mcp/src/dashboard/events.rs` + +Add variant: + +```rust +pub enum VestigeEvent { + // ... existing ... + DomainProposalCreated { + id: String, + kind: String, + confidence: f64, + timestamp: DateTime, + }, + MemoryClassified { + id: String, + domains: Vec, + top_score: f64, + timestamp: DateTime, + }, +} +``` + +The SvelteKit dashboard's WS client reacts to both events: classified events refresh any open domain-detail page; proposal events push a toast and a badge on the navbar. + +--- + +## Test Plan + +Test root: `tests/phase_4/` (a new member of the workspace; mirror the `tests/e2e` layout). + +`tests/phase_4/Cargo.toml`: + +```toml +[package] +name = "vestige-phase4-tests" +version = "0.0.0" +edition = "2024" +publish = false + +[dependencies] +vestige-core = { path = "../../crates/vestige-core", features = ["embeddings", "vector-search", "domain-classification"] } +vestige-mcp = { path = "../../crates/vestige-mcp" } +tokio = { workspace = true } +anyhow = "1" +tempfile = "3" +serde_json = { workspace = true } +uuid = { workspace = true } +``` + +### Unit tests (colocated in `domain_classifier.rs::tests`, `context_signals.rs::tests`, `spreading_activation.rs::tests`) + +Each public function must have at least one test: + +- `classify_empty_domains_returns_empty`: `classify(&[0.0; 768], &[])` returns `ClassificationResult { scores: {}, domains: [] }`. +- `classify_single_domain_scores`: one `Domain` with a known centroid; input embedding equal to centroid; expect score 1.0 and `domains == [id]`. +- `classify_multi_domain_overlap`: two domains A, B; input halfway between centroids; expect both scores >= `assign_threshold`; expect `domains == [A, B]` (order not guaranteed). +- `classify_below_threshold_returns_empty_domains_but_scores_filled`: input orthogonal to all centroids; expect `scores` populated, `domains` empty. +- `classify_with_boost_adds_delta`: same input as above, with `boost = {A: 0.4}`; expect A now above threshold, B unchanged. +- `classify_boost_clamps_to_unit`: `boost = {A: 5.0}`; resulting `scores[A]` must be <= 1.0. +- `tfidf_top_k_returns_distinct_terms`: given three fake docs, `top_k=3` returns three non-duplicate strings, in descending TF-IDF order. +- `tfidf_top_k_drops_stopwords`: `["the and for"]` + real content -> stop-words absent. +- `compute_top_terms_handles_empty_cluster`: returns `vec![]` (no panic). +- `signal_git_present_vs_absent`: `GitRepoSignal` given metadata with `.git` in cwd returns non-empty map; without it returns empty. +- `signal_ide_present_vs_absent`: `IdeHintSignal` ditto for `metadata.editor == "vscode"`. +- `signal_combined_clamped`: two signals both firing each at +0.10 -> combined map values <= +0.15. +- `cross_domain_decay_full_weight_on_overlap`: graph with node A in domain `dev`, node B in domain `dev`, edge A->B strength 1.0; after `activate`, B's activation equals the standard `initial * strength * decay_factor` (no extra penalty). +- `cross_domain_decay_half_weight_no_overlap`: A in `dev`, B in `infra`, same edge -> B's activation is 0.5x that of the overlap case. +- `cross_domain_decay_unclassified_no_penalty`: A classified, B unclassified -> full weight. +- `propose_changes_detects_split`: existing domain `dev`; new discovery returns two clusters whose centroids both sit close to old `dev` centroid, each >= min_cluster_size members -> proposal of kind `Split { parent: "dev", children: [a, b] }`. +- `propose_changes_detects_merge`: two existing domains whose new centroids now have cosine > `merge_threshold` -> proposal of kind `Merge`. +- `propose_changes_detects_new_cluster`: a new cluster with no match >= 0.85 to any existing -> `NewCluster`. +- `apply_proposal_split_updates_memberships`: after accept, memories previously in `dev` get reassigned (some to child a, some to child b) via `reassign_all`. + +### Integration tests (`tests/phase_4/tests/`) + +One file per behavior listed in the Phase 4 acceptance sheet. + +- `discover_seed_corpus.rs` -- loads the 500-memory fixture, runs `classifier.discover(&store).await`, asserts at least 3 clusters, asserts per-cluster intra-similarity mean > 0.6, asserts discovery wall time < 10s in release. Also asserts `top_terms` for each cluster contains at least one expected keyword per cluster (dev: contains any of `rust/trait/async`; infra: `bgp/vlan/network`; home: `solar/battery/pool`). +- `soft_assign_multi_domain.rs` -- inserts a memory "deploy zinit containers over BGP network"; after classify, `domains` contains both `dev` and `infra` (from a known centroid setup). +- `auto_classify_on_ingest.rs` -- with three existing domains, a fresh `smart_ingest` of a dev-ish sentence ends up with `domains == ["dev"]` and non-empty `domain_scores`. +- `reembed_triggers_recluster.rs` -- after `vestige migrate --reembed`, centroids must be recomputed; verify `list_domains()` returns fresh `centroid` values (different from pre-reembed). +- `dream_consolidation_recluster_hook.rs` -- run 5 dream cycles with heavy synthetic memory insertion; after the 5th, assert `list_domain_proposals("pending")` has at least one proposal. +- `proposal_accept_applies_changes.rs` -- accept a split proposal via `apply_proposal`; verify that memories in `dev` are now distributed across the new children and that the old `dev` domain is removed. +- `proposal_reject_leaves_state.rs` -- reject a proposal; verify all domains and memberships unchanged. +- `drift_is_proposal_only.rs` -- over 5 dream cycles with new inserts, never call accept; verify every memory's `domains` field equals its initial post-discovery value. No auto-apply. +- `cross_domain_activation_decay.rs` -- build a `ActivationNetwork` with two memories linked by a strength-1.0 edge, one in `dev`, one in `infra`; activate `dev` memory with 1.0; assert `infra` memory's activation == `0.5 * decay_factor` (0.35 with default decay_factor 0.7). Then set both to `dev` and reassert activation == `0.7`. +- `cli_domains_discover.rs` -- spawn `cargo run -- domains discover --force --json`, parse stdout, assert at least 3 clusters and valid JSON shape. +- `cli_domains_rename_merge.rs` -- happy-path rename then merge, with stdout assertions. +- `context_signal_git_repo.rs` -- ingest the same sentence from inside a tempdir with `.git` vs outside; assert the git-run produces slightly higher `domain_scores` for the code-related domain (diff >= 0.04, matches `git_boost = 0.05`). +- `threshold_tunable.rs` -- same memory, two runs with `assign_threshold = 0.40` vs `0.85`; the low-threshold run assigns more domains than the high-threshold run for the same content. +- `signal_boost_clamped.rs` -- artificially configure `git_boost = 5.0` and assert the resulting per-domain score is still <= 1.0. +- `discover_preserves_stable_ids.rs` -- run discover twice with no new memories; the second run's domain ids match the first's (via centroid-similarity stable-ID matching above 0.85). + +### Dashboard UI tests (`tests/phase_4/ui/`) + +Use curl-driven smoke tests (avoids adding Playwright as a new hard dep; Playwright already exists at `apps/dashboard/playwright.config.ts` and can be extended later). + +- `domains_list_renders.sh` -- `curl -H "X-API-Key: $KEY" http://localhost:3927/api/v1/domains` returns 200 + JSON array with expected keys. +- `domain_detail_histogram.sh` -- `curl .../api/v1/domains/dev/score-histogram` returns 10 buckets. +- `proposal_review_flow.sh` -- create a pending proposal via SQL insert; `curl POST .../api/v1/domains/proposals//accept`; `curl GET .../proposals?status=accepted` shows it. +- `unauth_domain_list_rejected.sh` -- no auth header -> 401. + +### Benchmarks (`tests/phase_4/benches/`) + +Criterion benches: + +- `bench_discover_10k.rs` -- synthetic 10k x 768D embeddings drawn from 5 blobs; assert `discover` wall p95 < 30s on a warm release build. +- `bench_auto_classify_single.rs` -- 20 domains in memory, classify one 768D vector; assert p99 < 5ms. +- `bench_reassign_all.rs` -- 10k memories, 5 domains; assert full `reassign_all` wall time < 90s (100 rows/ms baseline). + +--- + +## Acceptance Criteria + +- [ ] `cargo build -p vestige-core --features domain-classification` zero warnings. +- [ ] `cargo build -p vestige-mcp` zero warnings. +- [ ] `cargo clippy --workspace --all-targets --all-features -- -D warnings` clean. +- [ ] `cargo test -p vestige-phase4-tests` -- all tests in `tests/phase_4/` pass. +- [ ] On a 500+ memory seed corpus covering three natural clusters (dev / infra / home), `vestige domains discover --force` produces sensible top-terms matching the expected keyword sets and labels are stable on a second run. +- [ ] `vestige search` with domain filter `["dev"]` excludes any memory whose `domains` array does not include `dev`. +- [ ] After 5 dream cycles with ongoing inserts, no existing memory's `domains` has silently changed; proposals exist in `domain_proposals` table; accepting a proposal reassigns as described. +- [ ] Cross-domain spreading activation: a query in `dev` that crosses a single edge into an `infra`-only memory still returns the memory but with activation `cross_domain_decay * in-domain_activation`. +- [ ] `vestige domains discover --min-cluster-size 20` produces strictly fewer or equal clusters than the default, and with larger per-cluster membership. +- [ ] Dashboard `/dashboard/domains` route renders all domains within 2 seconds on the seed corpus. +- [ ] Proposal UI flow (open pending, accept, confirmed in store) works end-to-end. +- [ ] Benchmarks meet targets (discover 10k p95 < 30s, auto-classify p99 < 5ms). + +--- + +## Rollback Notes + +- **Feature gate**: add `domain-classification` to `crates/vestige-core/Cargo.toml`'s `[features]`. When disabled, the `DomainClassifier` module is not compiled, the classification call in the ingest path is a no-op (`#[cfg]`-guarded), and cross-domain decay collapses to `1.0`. The CLI `domains` subcommand emits "domain classification is disabled in this build". +- **Revert strategy**: drop the two new tables `domains` (if created in Phase 1 is retained) or `domain_proposals` (Phase 4). A DOWN migration clears `memories.domains` and `memories.domain_scores`. Existing memories simply lose their domain assignments; all search and retrieval paths work unchanged because `domains = []` is the documented "unclassified" state. +- **Idempotency**: rerunning `discover` is always safe. Cluster numeric IDs may differ between runs, but the stable-ID match by centroid similarity preserves user-assigned labels. Do not persist cluster ids in client-side bookmarks; link via the user-assigned label. +- **Data-loss risk**: `apply_proposal` is a destructive operation (it deletes the old parent domain in a split or merges two). The dashboard's accept button double-confirms with a modal that shows the number of affected memories. + +--- + +## Open Implementation Questions + +Each question + candidates + RECOMMENDATION. + +### OQ1. Top-terms extraction: TF-IDF vs BM25 vs frequency? +- TF-IDF with smoothed IDF -- standard, cheap, good-enough. +- BM25 -- better for long-document discrimination, overkill for short memory contents. +- Raw frequency -- noisy; stop-words dominate. +**RECOMMENDATION**: TF-IDF with global IDF over the entire memory corpus (not just cluster members), recomputed once per `discover` call. Same tokenizer as the `dreams.rs::content_similarity` Jaccard for consistency. + +### OQ2. Proposal persistence: DB table vs in-memory with dashboard notification? +- DB table (`domain_proposals`) -- durable, surfaces across restarts, enables audit. +- In-memory only -- simpler, but loses proposals on server restart. +**RECOMMENDATION**: DB table. Proposals are rare (every 5th dream) and valuable user-facing artifacts; durability is mandatory. + +### OQ3. `hdbscan` crate: f32 vs f64 input, exact API surface? +- v0.10 historically takes `&[Vec]`; embeddings are `Vec`. +- Cost of converting f32 -> f64 at discovery time: `10k * 768 = 7.68M` f64 doubles ~ 60MB transient, acceptable. +**RECOMMENDATION**: verify v0.10's type signature at implementation time; if it requires f64, perform the conversion in `discover()` behind a single allocation. Document in module header. If the crate API diverged from the PRD snippet, fall back to the manual builder style (`HdbscanHyperParams::builder().min_cluster_size(n).min_samples(s).build()`). + +### OQ4. Stable domain IDs across discover re-runs? +- Option A: numeric IDs from HDBSCAN labels -- unstable, re-runs shuffle them. +- Option B: hash(top_terms) -- stable if top-terms stable, but top-terms drift. +- Option C (recommended): after computing new centroids, match each to the closest existing domain by centroid cosine; if similarity > 0.85, reuse the existing domain's `id` and `label`. Otherwise mint a fresh `id = "cluster_"`. +**RECOMMENDATION**: Option C. Preserves user-assigned labels across drift. Threshold 0.85 is config-tunable via `stable_id_threshold` if needed later. + +### OQ5. Context signal injection site: ingest handler vs embedder vs classifier? +- Embedder -- would alter embedding; signals are not about embedding quality. +- Ingest handler -- signals known there, but then `DomainClassifier` cannot be tested in isolation. +- Classifier as a `classify_with_boost(boost: Option<&HashMap>)` parameter -- pure, testable, composable. +**RECOMMENDATION**: classifier parameter. The cognitive engine constructs the boost map via `ContextSignals::gather_boost(&metadata, &domains)` and hands it to the classifier. Keeps the classifier stateless w.r.t. signals. + +### OQ6. Re-cluster proposal cadence: event-based (every Nth dream) vs time-based (weekly)? +- ADR resolution Q7: every Nth dream (N=5 default). +- Alternative: once per week regardless of dream cadence. +**RECOMMENDATION**: stick with every Nth dream. Users who dream rarely re-cluster rarely -- that matches the philosophy ("memory work triggers memory bookkeeping"). Note the alternative as future consideration; if users complain about never seeing proposals, add a time-based fallback. + +### OQ7. Minimum corpus size for first discover? +- PRD default: 150. +- Too low -> noisy initial clusters, proposals every dream. +- Too high -> user waits forever for domains to appear. +**RECOMMENDATION**: 150 as the default discovery gate; HDBSCAN's `min_cluster_size=10` will produce 0 clusters for < 100 memories, so the system gracefully produces no domains until the corpus is large enough. Test with `N=80, 150, 500` in `threshold_tunable.rs` to confirm sensible behavior. + +### OQ8. Cross-domain decay: strict no-overlap vs graded? +- Strict: `1.0` if any overlap, `cross_domain_decay` otherwise. +- Graded: `max(cross_domain_decay, |A intersect B| / max(|A|, |B|))`. +**RECOMMENDATION**: strict for Phase 4. Easier to reason about, easier to tune, easier to test. Graded is a marked future enhancement; file an issue if retrieval-quality metrics justify it. + +### OQ9. Classifier invocation from remote HTTP clients? +- In server mode, an agent posts `smart_ingest` -> server embeds -> server classifies. +- All the work stays server-side; MCP clients never do classification. +**RECOMMENDATION**: confirmed server-side-only. Document in the MCP tool schema that `smart_ingest` now returns `domains` and `domain_scores` in its response so clients can display the classification to the user. + +### OQ10. Where to store the dream-cycle counter? +- In-memory on `CognitiveEngine` -- lost on restart, miscounts cadence. +- New `system_state` singleton table. +**RECOMMENDATION**: `system_state` table. Survives restarts. Also useful for future metrics (total memories ever, total dreams ever). + +### OQ11. Scope of `reassign_all` after a proposal accept vs a normal discover? +- On discover --force (first-time), run `reassign_all` against all memories. +- On proposal accept (split / merge), run `reassign_all` only on affected memories (parent's members for split; both parents' members for merge) to avoid touching unrelated records. +**RECOMMENDATION**: scoped reassignment where possible; fall back to full `reassign_all` only on `discover --force` or when the set of domains has fundamentally changed. Reduces write amplification on large corpora. + +### OQ12. Proposal freshness? +- Multiple re-clusters could stack up pending proposals. +**RECOMMENDATION**: before inserting a new proposal, check for existing pending proposals with the same `kind + targets`; if present, bump `created_at` and `confidence` instead of creating a duplicate. Add a `confidence_history` array in the `payload` JSONB for audit. + +--- + +## Implementation Sequencing (suggested order) + +1. Land the `DomainClassifier` struct, `classify` / `classify_with_boost`, unit tests. (Day 1) +2. Add `compute_top_terms` + TF-IDF helper, tests. (Day 1) +3. Wire `discover` end-to-end against SQLite; `discover_seed_corpus` integration test. (Day 2) +4. Add `domain_proposals` table migrations + trait methods; both backends. (Day 2) +5. Implement `propose_changes` + `apply_proposal`; proposal unit tests. (Day 3) +6. Context signals module + tests. (Day 3) +7. Hook classifier into ingest path; `auto_classify_on_ingest` integration test. (Day 4) +8. Cross-domain decay in spreading activation; unit + integration tests. (Day 4) +9. Dream re-cluster hook + `system_state` counter; integration tests for drift-only behavior. (Day 5) +10. CLI subcommands. (Day 6) +11. REST endpoints. (Day 6) +12. SvelteKit dashboard routes + WebSocket event wiring. (Day 7-8) +13. Benchmarks + acceptance sweep on the 500-memory seed. (Day 9) + +--- + +## File Map (everything Phase 4 touches or creates) + +Creates: + +- `crates/vestige-core/src/neuroscience/domain_classifier.rs` +- `crates/vestige-core/src/neuroscience/context_signals.rs` +- `crates/vestige-core/migrations/postgres/00XX_domain_proposals.sql` +- `crates/vestige-core/migrations/sqlite/00XX_domain_proposals.sql` (or inline in `storage/migrations.rs`) +- `crates/vestige-mcp/src/api/domains.rs` (REST handlers) +- `apps/dashboard/src/routes/(app)/domains/+page.svelte` +- `apps/dashboard/src/routes/(app)/domains/[id]/+page.svelte` +- `apps/dashboard/src/routes/(app)/domains/proposals/+page.svelte` +- `apps/dashboard/src/lib/api/domains.ts` +- `tests/phase_4/Cargo.toml` +- `tests/phase_4/tests/*.rs` (per the Integration test list) +- `tests/phase_4/fixtures/seed_500.json` +- `tests/phase_4/support/fixtures.rs` + +Modifies: + +- `crates/vestige-core/Cargo.toml` -- add `hdbscan = "0.10"` under a new `domain-classification` feature. +- `crates/vestige-core/src/neuroscience/mod.rs` -- register new modules, re-exports. +- `crates/vestige-core/src/neuroscience/spreading_activation.rs` -- `cross_domain_decay` field in `ActivationConfig`, `domains` field on `ActivationNode`, decay math in `activate`. +- `crates/vestige-core/src/consolidation/phases.rs` -- `DreamReClusterHook`. +- `crates/vestige-core/src/advanced/dreams.rs` -- accept a hook callback from the orchestrator (if the orchestration is done at this level). +- `crates/vestige-core/src/storage/trait.rs` -- add proposal + system_state methods. +- `crates/vestige-core/src/storage/sqlite.rs` -- implement proposal + system_state methods + `all_embeddings_with_meta` if not already on the trait. +- `crates/vestige-core/src/storage/postgres.rs` (Phase 2) -- same. +- `crates/vestige-core/src/lib.rs` -- re-exports. +- `crates/vestige-core/src/cognitive.rs` (or equivalent ingest orchestrator) -- auto-classify injection. +- `crates/vestige-mcp/src/bin/cli.rs` -- `Domains` subcommand + dispatch. +- `crates/vestige-mcp/src/dashboard/mod.rs` -- wire new REST routes. +- `crates/vestige-mcp/src/dashboard/events.rs` -- new event variants. +- `crates/vestige-mcp/src/dashboard/handlers.rs` -- if legacy dashboard gets a domains panel (optional). +- `vestige.toml` config loader -- `[domains]` section + struct + defaults. +- Root `Cargo.toml` workspace members -- add `tests/phase_4`. + +--- + +## Risks + +- **HDBSCAN determinism**: HDBSCAN is deterministic given input order; sorting embeddings by memory id before feeding the clusterer guarantees reproducibility across runs -- do this in `discover()` and document it. +- **Embedding dimension drift**: Phase 1's `embedding_model` registry blocks writes from mismatched embedders. If `discover()` ever sees two dimensions, it bails with a clear error and points at `vestige migrate --reembed`. +- **Classification latency on ingest**: for users with thousands of domains (unlikely but possible), `classify` is O(n_domains * dim). 20 domains * 768 f32 = 15k flops per classification, trivial. Still, expose a `classify_budget_ms` config knob for paranoia. +- **Re-cluster proposal storms**: if the corpus is borderline-stable, small changes can produce conflicting proposals on consecutive dreams. Mitigation: OQ12 (dedup by target set, bump confidence instead of stacking). +- **Dashboard feature gap**: if the SvelteKit app lands with the domains route but the REST endpoints are not yet deployed, the route 404s. Mitigation: ship the REST endpoints in the same release; a feature flag on the client toggles the nav entry. + +--- + +## Non-Goals Reminder + +- No Phase 5 federation concerns in this plan. +- No cross-installation domain sync. +- No automatic accept of proposals, ever. +- No graded cross-domain decay; strict only. +- No ML-based domain label suggestion (top-terms are enough for v1). +- No editing individual memory memberships from the UI in this phase. diff --git a/docs/prd/001-getting-centralized-vestige.md b/docs/prd/001-getting-centralized-vestige.md new file mode 100644 index 0000000..9d86087 --- /dev/null +++ b/docs/prd/001-getting-centralized-vestige.md @@ -0,0 +1,751 @@ +# RFC: Pluggable Storage Backend + Network Access for Vestige + +**Status**: Draft / Discussion +**Author**: Jan +**Date**: 2026-02-26 +**Vestige version**: v2.x (current main) + +## Summary + +Add a pluggable storage backend trait to Vestige, enabling PostgreSQL (+pgvector) as an alternative to the current SQLite+FTS5+USearch stack. Simultaneously add HTTP MCP transport with API key authentication to enable centralized/remote deployment. + +This keeps the existing local-first SQLite mode fully intact while opening up a server deployment model. + +## Motivation + +Vestige currently runs as a local process per machine (MCP via stdio, SQLite in `~/.vestige/`). This works great for single-machine use but doesn't support: + +- **Multi-machine access**: Same memory brain from laptop, desktop, and server +- **Multi-agent access**: Multiple AI clients hitting one memory store concurrently +- **Future federation**: Syncing memory between decentralized nodes (e.g., MOS/Threefold grid) + +SQLite's single-writer model and lack of native network protocol make it unsuitable as a centralized server. PostgreSQL is a natural fit: built-in concurrency (MVCC), authentication, replication, and with `pgvector` + built-in FTS it collapses three separate storage layers into one. + +## Design + +### Storage Trait + +The core abstraction. All 29 cognitive modules interact with storage exclusively through this trait (or a small family of traits). + +```rust +use std::collections::HashMap; +use uuid::Uuid; + +/// Core memory record, backend-agnostic +#[derive(Debug, Clone)] +pub struct MemoryRecord { + pub id: Uuid, + pub domains: Vec, // [] = unclassified, ["dev"], ["dev", "infra"], etc. + pub domain_scores: HashMap, // raw similarities: {"dev": 0.82, "infra": 0.71} + pub content: String, + pub node_type: String, + pub tags: Vec, + pub embedding: Option>, // dimensionality is runtime config + pub created_at: chrono::DateTime, + pub updated_at: chrono::DateTime, + pub metadata: serde_json::Value, +} + +/// FSRS scheduling state, stored alongside each memory +#[derive(Debug, Clone)] +pub struct SchedulingState { + pub memory_id: Uuid, + pub stability: f64, + pub difficulty: f64, + pub retrievability: f64, + pub last_review: Option>, + pub next_review: Option>, + pub reps: u32, + pub lapses: u32, +} + +/// Hybrid search request +#[derive(Debug, Clone)] +pub struct SearchQuery { + pub domains: Option>, // None = search all domains + pub text: Option, // FTS query + pub embedding: Option>, // vector similarity + pub tags: Option>, // tag filter + pub node_types: Option>, + pub limit: usize, + pub min_retrievability: Option, // filter by FSRS state +} + +#[derive(Debug, Clone)] +pub struct SearchResult { + pub record: MemoryRecord, + pub score: f64, // combined/fused score + pub fts_score: Option, + pub vector_score: Option, +} + +/// Connection/edge between memories (for spreading activation) +#[derive(Debug, Clone)] +pub struct MemoryEdge { + pub source_id: Uuid, + pub target_id: Uuid, + pub edge_type: String, + pub weight: f64, + pub created_at: chrono::DateTime, +} + +/// Main storage trait — one impl per backend +/// trait_variant generates a Send-bound `MemoryStore` alias, +/// enabling Arc without manual boxing. +#[trait_variant::make(MemoryStore: Send)] +pub trait LocalMemoryStore: Sync + 'static { + // --- Lifecycle --- + async fn init(&self) -> Result<()>; + async fn health_check(&self) -> Result; + + // --- CRUD --- + async fn insert(&self, record: &MemoryRecord) -> Result; + async fn get(&self, id: Uuid) -> Result>; + async fn update(&self, record: &MemoryRecord) -> Result<()>; + async fn delete(&self, id: Uuid) -> Result<()>; + + // --- Search --- + async fn search(&self, query: &SearchQuery) -> Result>; + async fn fts_search(&self, text: &str, limit: usize) -> Result>; + async fn vector_search(&self, embedding: &[f32], limit: usize) -> Result>; + + // --- FSRS Scheduling --- + async fn get_scheduling(&self, memory_id: Uuid) -> Result>; + async fn update_scheduling(&self, state: &SchedulingState) -> Result<()>; + async fn get_due_memories(&self, before: chrono::DateTime, limit: usize) -> Result>; + + // --- Graph (spreading activation) --- + async fn add_edge(&self, edge: &MemoryEdge) -> Result<()>; + async fn get_edges(&self, node_id: Uuid, edge_type: Option<&str>) -> Result>; + async fn remove_edge(&self, source: Uuid, target: Uuid) -> Result<()>; + async fn get_neighbors(&self, node_id: Uuid, depth: usize) -> Result>; + + // --- Bulk / Maintenance --- + async fn count(&self) -> Result; + async fn get_stats(&self) -> Result; + async fn vacuum(&self) -> Result<()>; +} +``` + +**Design notes:** + +- `trait_variant::make` generates a `MemoryStore` trait alias with `Send`-bound futures, allowing `Arc` for runtime backend selection. `LocalMemoryStore` is the base (usable in single-threaded contexts), `MemoryStore` is the Send variant for Axum/tokio. +- `embedding: Option>` — dimensions determined at runtime by the configured fastembed model. The backend stores whatever it gets. +- The trait is intentionally flat. The cognitive modules (FSRS-6, spreading activation, synaptic tagging, prediction error gating, etc.) sit *above* this trait and don't need to know about the backend. +- `search()` does hybrid RRF fusion at the backend level — both SQLite and Postgres implementations handle this internally. + +### Backend: SQLite (existing, refactored) + +Wraps the current implementation behind the trait: + +``` +SqliteMemoryStore +├── rusqlite connection pool (r2d2 or deadpool) +├── FTS5 virtual table (keyword search) +├── USearch HNSW index (vector search, behind RwLock) +└── WAL mode + busy timeout for concurrent readers +``` + +No behavioral changes — just the trait boundary. + +### Backend: PostgreSQL (new) + +``` +PgMemoryStore +├── sqlx::PgPool (connection pool, compile-time checked queries) +├── tsvector + GIN index (keyword search) +├── pgvector + HNSW index (vector search) +└── Standard PostgreSQL MVCC concurrency +``` + +**Schema sketch:** + +```sql +CREATE EXTENSION IF NOT EXISTS vector; + +-- Domain registry — populated by clustering, not by user +CREATE TABLE domains ( + id TEXT PRIMARY KEY, -- auto-generated or user-named + label TEXT NOT NULL, -- human label (suggested or user-provided) + centroid vector, -- mean embedding of domain members + top_terms TEXT[] NOT NULL DEFAULT '{}', -- top keywords for display + memory_count INTEGER NOT NULL DEFAULT 0, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + metadata JSONB NOT NULL DEFAULT '{}' +); + +CREATE TABLE memories ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + domains TEXT[] NOT NULL DEFAULT '{}', -- [] = unclassified + domain_scores JSONB NOT NULL DEFAULT '{}', -- {"dev": 0.82, "infra": 0.71} raw similarities + content TEXT NOT NULL, + node_type TEXT NOT NULL DEFAULT 'general', + tags TEXT[] NOT NULL DEFAULT '{}', + embedding vector, -- dimension set at table creation or unconstrained + metadata JSONB NOT NULL DEFAULT '{}', + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + + -- FTS: auto-maintained tsvector column + search_vec TSVECTOR GENERATED ALWAYS AS ( + setweight(to_tsvector('english', content), 'A') || + setweight(to_tsvector('english', coalesce(node_type, '')), 'B') || + setweight(array_to_tsvector(tags), 'C') + ) STORED +); + +-- FTS index +CREATE INDEX idx_memories_fts ON memories USING GIN (search_vec); + +-- Vector similarity (HNSW) +CREATE INDEX idx_memories_embedding ON memories + USING hnsw (embedding vector_cosine_ops) + WITH (m = 16, ef_construction = 64); + +-- Common filters +CREATE INDEX idx_memories_domains ON memories USING GIN (domains); +CREATE INDEX idx_memories_node_type ON memories (node_type); +CREATE INDEX idx_memories_tags ON memories USING GIN (tags); +CREATE INDEX idx_memories_created ON memories (created_at); + +-- FSRS scheduling state +CREATE TABLE scheduling ( + memory_id UUID PRIMARY KEY REFERENCES memories(id) ON DELETE CASCADE, + stability DOUBLE PRECISION NOT NULL DEFAULT 0.0, + difficulty DOUBLE PRECISION NOT NULL DEFAULT 0.0, + retrievability DOUBLE PRECISION NOT NULL DEFAULT 1.0, + last_review TIMESTAMPTZ, + next_review TIMESTAMPTZ, + reps INTEGER NOT NULL DEFAULT 0, + lapses INTEGER NOT NULL DEFAULT 0 +); + +CREATE INDEX idx_scheduling_next ON scheduling (next_review); + +-- Graph edges (spreading activation) +-- Edges can cross domain boundaries — spreading activation respects +-- domain filters when provided, traverses freely when searching all domains. +CREATE TABLE edges ( + source_id UUID NOT NULL REFERENCES memories(id) ON DELETE CASCADE, + target_id UUID NOT NULL REFERENCES memories(id) ON DELETE CASCADE, + edge_type TEXT NOT NULL DEFAULT 'related', + weight DOUBLE PRECISION NOT NULL DEFAULT 1.0, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + PRIMARY KEY (source_id, target_id, edge_type) +); + +CREATE INDEX idx_edges_target ON edges (target_id); + +-- API keys +CREATE TABLE api_keys ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + key_hash TEXT NOT NULL UNIQUE, -- blake3 + label TEXT NOT NULL, + scopes TEXT[] NOT NULL DEFAULT '{read,write}', + domain_filter TEXT[] NOT NULL DEFAULT '{}', -- {} = access all domains + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + last_used TIMESTAMPTZ, + active BOOLEAN NOT NULL DEFAULT true +); +``` + +**Hybrid search in SQL:** + +```sql +-- RRF (Reciprocal Rank Fusion) combining FTS + vector +-- $1 = query text, $2 = embedding, $3 = limit, $4 = domain filter (NULL for all) +WITH fts AS ( + SELECT id, ts_rank_cd(search_vec, websearch_to_tsquery('english', $1)) AS score, + ROW_NUMBER() OVER (ORDER BY ts_rank_cd(search_vec, websearch_to_tsquery('english', $1)) DESC) AS rank + FROM memories + WHERE search_vec @@ websearch_to_tsquery('english', $1) + AND ($4::text[] IS NULL OR domains && $4) -- array overlap: any match + LIMIT 50 +), +vec AS ( + SELECT id, 1 - (embedding <=> $2::vector) AS score, + ROW_NUMBER() OVER (ORDER BY embedding <=> $2::vector) AS rank + FROM memories + WHERE embedding IS NOT NULL + AND ($4::text[] IS NULL OR domains && $4) + LIMIT 50 +) +SELECT COALESCE(f.id, v.id) AS id, + COALESCE(1.0 / (60 + f.rank), 0) + COALESCE(1.0 / (60 + v.rank), 0) AS rrf_score, + f.score AS fts_score, + v.score AS vector_score +FROM fts f FULL OUTER JOIN vec v ON f.id = v.id +ORDER BY rrf_score DESC +LIMIT $3; +``` + +### Embedding Configuration + +The embedding layer stays external to the storage backend. fastembed runs locally and produces vectors that get passed into `MemoryRecord.embedding`. + +```toml +# vestige.toml +[embeddings] +provider = "fastembed" # only local for now +model = "BAAI/bge-base-en-v1.5" # 768 dimensions +# model = "BAAI/bge-large-en-v1.5" # 1024 dimensions +# model = "BAAI/bge-small-en-v1.5" # 384 dimensions + +[storage] +backend = "postgres" # or "sqlite" + +[storage.sqlite] +path = "~/.vestige/vestige.db" + +[storage.postgres] +url = "postgresql://vestige:secret@localhost:5432/vestige" +max_connections = 10 +``` + +On init, the backend reads the embedding dimension from the first stored vector (or from config) and validates consistency. + +For pgvector: you can either create the column as `vector(768)` (fixed, faster) or unconstrained `vector` (flexible, slightly slower). Recommendation: fixed dimension derived from config, with a migration path if the model changes. + +### Emergent Domain Model + +Instead of user-defined tenants, domains emerge automatically from the data via clustering. The user never has to decide where a memory belongs — the system figures it out. + +#### Pipeline + +``` +Phase 1: Accumulate (cold start, 0 → N memories) +│ All memories stored with domains = [] (unclassified) +│ No classification overhead, just embed and store +│ Threshold N is configurable, default ~150 memories +│ +Phase 2: Discover (triggered once at threshold, or manually) +│ Run HDBSCAN on all embeddings: +│ - min_cluster_size: ~10 +│ - min_samples: ~5 +│ - No eps parameter needed (unlike DBSCAN) +│ - Automatically determines number of clusters +│ - Handles variable-density clusters +│ - Border points between clusters flagged naturally +│ +│ For each cluster, extract: +│ - Centroid (mean embedding) +│ - Top terms (TF-IDF or frequency over cluster members) +│ - Suggested label from top terms +│ +│ Present to user (via dashboard or CLI): +│ "I found 3 natural groupings in your memories: +│ ● cluster_0 (47 memories): BGP, SONiC, VLAN, FRR, peering... +│ ● cluster_1 (31 memories): solar, kWh, battery, pool, ESPHome... +│ ● cluster_2 (22 memories): Rust, trait, async, zinit, tokio..." +│ +│ User can: +│ - Name them: cluster_0 → "infra", cluster_1 → "home", cluster_2 → "dev" +│ - Accept suggested names +│ - Merge clusters +│ - Do nothing (auto-names stick) +│ +Phase 3: Soft-assign all existing memories +│ Now that centroids exist, re-score every memory (including +│ those from discovery) against all centroids. +│ This replaces HDBSCAN's hard labels with continuous scores: +│ +│ For each memory: +│ similarities = [(domain, cosine_sim(embedding, centroid)) for each domain] +│ domains = [id for (id, score) in similarities if score >= threshold] +│ +│ Memories in overlap zones get multiple domains. +│ Memories far from all centroids stay unclassified. +│ +Phase 4: Classify (ongoing, after discovery) +│ New memory ingested: +│ 1. Compute embedding +│ 2. Compute similarity to ALL domain centroids +│ 3. Store raw scores in domain_scores JSONB +│ 4. Threshold into domains[] array +│ 5. Update domain centroids incrementally (running mean) +│ +│ Context signals as soft priors: +│ - Git repo / IDE metadata → boost similarity to code-related domains +│ - No workspace context → slight boost toward non-technical domains +│ - These shift the score, never override the embedding distance +│ +Phase 5: Re-cluster (periodic, during dream consolidation) + Re-run HDBSCAN on all embeddings including new ones + Detect: + - New clusters forming from previously unclassified memories + - Existing clusters splitting (domain grew too broad) + - Clusters merging (domains that were artificially separate) + Propose changes to user: + "Your 'dev' domain may have split into two groups: + - systems (zinit, MOS, containers, VMs) — 34 memories + - networking (BGP, SONiC, VLANs, MLAG) — 28 memories + Split them? [yes / no / later]" + Re-run soft assignment on all memories after structural changes + Centroid vectors are updated regardless +``` + +#### Domain Storage + +```rust +#[derive(Debug, Clone)] +pub struct Domain { + pub id: String, + pub label: String, + pub centroid: Vec, + pub top_terms: Vec, + pub memory_count: usize, + pub created_at: chrono::DateTime, +} +``` + +Added to the `MemoryStore` trait: + +```rust + // --- Domains --- + async fn list_domains(&self) -> Result>; + async fn get_domain(&self, id: &str) -> Result>; + async fn upsert_domain(&self, domain: &Domain) -> Result<()>; + async fn delete_domain(&self, id: &str) -> Result<()>; + async fn classify(&self, embedding: &[f32]) -> Result>; + // Returns [(domain_id, similarity)] sorted by similarity desc. + // Caller decides threshold for assignment. +``` + +#### Classification Module + +A new cognitive module alongside FSRS, spreading activation, etc.: + +```rust +pub struct DomainClassifier { + /// Similarity threshold — domains scoring above this are assigned + pub assign_threshold: f64, // default: 0.65 + /// Minimum memories before running initial discovery + pub discovery_threshold: usize, // default: 150 + /// How often to re-cluster (in dream consolidation passes) + pub recluster_interval: usize, // default: every 5th consolidation + /// HDBSCAN min_cluster_size + pub min_cluster_size: usize, // default: 10 +} + +/// Raw classification result — all scores, before thresholding +#[derive(Debug, Clone)] +pub struct ClassificationResult { + /// Similarity to every known domain centroid + pub scores: HashMap, // {"dev": 0.82, "infra": 0.71, "home": 0.34} + /// Domains above assign_threshold + pub domains: Vec, // ["dev", "infra"] +} + +impl DomainClassifier { + /// Score a memory against all domain centroids. + /// Returns raw scores AND thresholded domain list. + pub fn classify( + &self, + embedding: &[f32], + domains: &[Domain], + ) -> ClassificationResult { + if domains.is_empty() { + return ClassificationResult { + scores: HashMap::new(), + domains: vec![], // still in accumulation phase + }; + } + + let scores: HashMap = domains.iter() + .map(|d| (d.id.clone(), cosine_similarity(embedding, &d.centroid))) + .collect(); + + let assigned: Vec = scores.iter() + .filter(|(_, &s)| s >= self.assign_threshold) + .map(|(id, _)| id.clone()) + .collect(); + + ClassificationResult { scores, domains: assigned } + } + + /// Soft-assign all existing memories after discovery or re-clustering. + /// Returns number of memories whose domains changed. + pub async fn reassign_all( + &self, + store: &dyn MemoryStore, + domains: &[Domain], + ) -> Result { + // Load all memories, re-score, update domains + domain_scores + // Batched to avoid loading everything into memory at once + todo!() + } +} +``` + +**Key distinction from the previous design:** there's no "closest wins" or "margin" logic. Every domain gets a score, and *all* domains above threshold are assigned. A memory about "deploying zinit containers via BGP-routed network" might score 0.78 on "dev" and 0.72 on "infra" — it gets both. A memory about "solar panel output today" scores 0.85 on "home" and 0.31 on everything else — it only gets "home". + +The raw `domain_scores` are always stored, so you (or the dashboard) can see *why* a memory was classified the way it was, and the threshold can be adjusted retroactively without re-computing embeddings. + +#### Search Behavior + +- **Default (no domain filter)**: searches all memories across all domains +- **Domain-scoped**: `domains: Some(vec!["dev"])` — only memories tagged with `dev` +- **Multi-domain**: `domains: Some(vec!["dev", "infra"])` — memories in either +- **MCP clients can set `X-Vestige-Domain` header** for default scoping, but the system works fine without it + +#### HDBSCAN Implementation + +HDBSCAN (Hierarchical DBSCAN) over the embedding vectors. Advantages over plain DBSCAN: + +- **No `eps` parameter** — the hardest thing to tune in DBSCAN. HDBSCAN determines density thresholds from the data hierarchy. +- **Variable-density clusters** — a tight cluster of networking memories and a spread-out cluster of personal memories are both detected correctly. +- **Border points** — memories between clusters are identified as low-confidence members, which aligns perfectly with soft assignment. + +Implementation: the `hdbscan` crate in Rust. Load all embeddings into memory (at 768d × f32 × 10k memories ≈ 30MB — fine), cluster, compute centroids, soft-assign all memories against the centroids. + +```rust +use hdbscan::{Center, Hdbscan}; + +fn discover_domains( + embeddings: &[Vec], + min_cluster_size: usize, +) -> (Vec>, Vec>) { // (cluster → member indices, centroids) + let clusterer = Hdbscan::default(embeddings); + let labels = clusterer.cluster().unwrap(); + let centroids = clusterer.calc_centers(Center::Centroid, &labels).unwrap(); + + // Group indices by label, ignoring noise (-1) + let mut clusters: HashMap> = HashMap::new(); + for (i, &label) in labels.iter().enumerate() { + if label >= 0 { + clusters.entry(label).or_default().push(i); + } + } + (clusters.into_values().collect(), centroids) +} +``` + +After HDBSCAN produces hard clusters, the soft-assignment pass (Phase 3) immediately re-scores all memories — including the ones HDBSCAN assigned — against the computed centroids. So HDBSCAN's hard labels are only used to *define* the centroids. The actual domain assignments always come from the continuous similarity scores. + +This works identically for both SQLite and Postgres backends — clustering runs in Rust application code, results are written back to the storage layer. + +### Network Transport + +#### MCP over Streamable HTTP + +Extend the existing Axum server: + +```rust +// Alongside existing dashboard routes +let app = Router::new() + // Existing dashboard + .route("/api/health", get(health_handler)) + .route("/dashboard/*path", get(dashboard_handler)) + // New: MCP over HTTP + .route("/mcp", post(mcp_handler).get(mcp_sse_handler)) + // New: REST API + // X-Vestige-Domain header optionally scopes to a domain + .route("/api/v1/memories", post(create_memory).get(list_memories)) + .route("/api/v1/memories/:id", get(get_memory).put(update_memory).delete(delete_memory)) + .route("/api/v1/search", post(search_memories)) + .route("/api/v1/consolidate", post(trigger_consolidation)) + .route("/api/v1/stats", get(get_stats)) + .route("/api/v1/domains", get(list_domains)) + .route("/api/v1/domains/discover", post(trigger_discovery)) + .route("/api/v1/domains/:id", put(rename_domain).delete(merge_domain)) + // Auth on everything except health + .layer(middleware::from_fn(api_key_auth)); +``` + +#### Auth Middleware + +```rust +async fn api_key_auth( + State(store): State>, + request: axum::extract::Request, + next: middleware::Next, +) -> Result { + // Skip auth for health endpoint + if request.uri().path() == "/api/health" { + return Ok(next.run(request).await); + } + + let key = request.headers() + .get("Authorization") + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.strip_prefix("Bearer ")) + .or_else(|| request.headers() + .get("X-API-Key") + .and_then(|v| v.to_str().ok())); + + match key { + Some(k) if verify_api_key(store.as_ref(), k).await => { + Ok(next.run(request).await) + } + _ => Err(StatusCode::UNAUTHORIZED), + } +} +``` + +#### Client Configuration + +```json +// Claude Desktop / Claude Code — single key, all domains +{ + "mcpServers": { + "vestige": { + "url": "http://vestige.local:3927/mcp", + "headers": { + "Authorization": "Bearer vst_a1b2c3..." + } + } + } +} +``` + +No domain header needed — searches all domains by default. The MCP tools include an optional `domain` parameter for scoped queries if the LLM or user wants to narrow down. + +Alternatively, scope a connection to a specific domain: + +```json +// Domain-scoped connection (e.g., for a home automation agent) +{ + "mcpServers": { + "vestige-home": { + "url": "http://vestige.local:3927/mcp", + "headers": { + "Authorization": "Bearer vst_e5f6g7...", + "X-Vestige-Domain": "home" + } + } + } +} +``` + +### Server Configuration + +```toml +# vestige.toml — full example for server mode +[server] +bind = "0.0.0.0:3927" # or mycelium IPv6 address +# tls_cert = "/path/to/cert.pem" # optional +# tls_key = "/path/to/key.pem" + +[auth] +enabled = true +# If false, no key required (local-only mode) + +[storage] +backend = "postgres" + +[storage.postgres] +url = "postgresql://vestige:secret@localhost:5432/vestige" +max_connections = 10 + +[embeddings] +provider = "fastembed" +model = "BAAI/bge-base-en-v1.5" +``` + +### CLI Extensions + +```bash +# Domain management (mostly automatic, but user can inspect/rename) +vestige domains list +# → dev Development (auto) memories: 87 top: Rust, trait, async, tokio +# → infra Infrastructure (auto) memories: 47 top: BGP, SONiC, VLAN, FRR +# → home Home (auto) memories: 31 top: solar, kWh, pool, ESPHome +# → (unclassified) memories: 12 + +vestige domains rename cluster_0 infra --label "Infrastructure" +vestige domains merge home personal --into home +vestige domains discover --force # re-run HDBSCAN now + +# Key management +vestige keys create --label "macbook" +# → Created key: vst_a1b2c3d4... (store this, shown once) + +vestige keys create --label "home-assistant" --scopes read --domains home +# → Created key: vst_e5f6g7h8... (read-only, home domain only) + +vestige keys list +# → macbook vst_a1b2... scopes: [read,write] domains: [all] +# → home-assistant vst_e5f6... scopes: [read] domains: [home] + +vestige keys revoke vst_a1b2c3d4... + +# Migration +vestige migrate --from sqlite --to postgres \ + --sqlite-path ~/.vestige/vestige.db \ + --postgres-url postgresql://localhost/vestige +``` + +## Implementation Plan + +### Phase 1: Storage Trait Extraction +- Define the `MemoryStore` trait (including domain methods) +- Refactor current SQLite code to implement it +- Add `domains TEXT[]` column to existing SQLite schema +- Verify all 29 modules work through the trait (no direct SQLite access) +- **No behavioral changes** — all memories start as unclassified + +### Phase 2: PostgreSQL Backend +- Implement `PgMemoryStore` +- Schema migrations (sqlx or refinery) +- `vestige migrate` command for SQLite → Postgres +- Config file support for backend selection + +### Phase 3: Network Access +- MCP Streamable HTTP endpoint on existing Axum server +- API key auth middleware + CLI management +- REST API endpoints +- Feature flags for stdio vs HTTP mode + +### Phase 4: Emergent Domain Classification +- `DomainClassifier` cognitive module +- HDBSCAN clustering via `hdbscan` crate (runs on both backends) +- Soft assignment pass: score all memories against centroids, threshold into domains +- `domain_scores` JSONB stored per memory for transparency / retroactive re-thresholding +- Domain discovery CLI and dashboard UI +- Auto-classification on ingest (once domains exist) +- Re-clustering during dream consolidation passes +- Domain management CLI (rename, merge, inspect) + +### Phase 5: Federation (future) +- Node discovery via Mycelium / mDNS +- Memory sync protocol (UUID-based, last-write-wins) +- Possibly Iroh for content-addressed replication +- FSRS state merge (review history append, not overwrite) + +## Crate Dependencies (new) + +```toml +# Phase 1 — trait abstraction +trait-variant = "0.1" + +# Phase 2 — Postgres +sqlx = { version = "0.8", features = ["runtime-tokio", "postgres", "uuid", "chrono", "json"] } +pgvector = "0.4" # sqlx integration for vector type + +# Phase 3 — Auth +blake3 = "1" # key hashing +rand = "0.8" # key generation + +# Phase 4 — Domain clustering +hdbscan = "0.10" # HDBSCAN — no eps tuning, variable density, built-in centroid calc +``` + +## Open Questions + +1. **Trait granularity**: One big `MemoryStore` trait or split into `MemoryStore + SchedulingStore + GraphStore + DomainStore`? Splitting is cleaner but means more `dyn` parameters threading through handlers. + +2. **Embedding on insert**: Should the storage backend call fastembed, or should the caller always provide the embedding? Current design says caller provides it, keeping the backend pure storage. But this means every client needs fastembed locally even if the DB is remote. For the server model, having the server compute embeddings makes more sense. + +3. **pgvector dimension**: Fixed (e.g., `vector(768)`) or unconstrained (`vector`)? Fixed is faster for HNSW but requires migration if model changes. + +4. **Sync conflict resolution for federation**: LWW per-UUID is simple but lossy. CRDTs would be more correct but massively more complex. For FSRS state specifically, merging review event logs would be ideal. + +5. **Dashboard auth**: The 3D dashboard currently runs unauthenticated on localhost. With remote access, it needs the same auth. Should it use the same API keys or have a separate session/cookie mechanism? + +6. **HDBSCAN `min_cluster_size`**: The main tuning knob. Too small → noisy micro-clusters. Too large → distinct topics get merged. Default of 10 should work for most cases, but may need a manual override or auto-sweep (run with several values, pick the one with best silhouette score). + +7. **Domain drift**: Over time, the character of a domain changes. How aggressively should re-clustering reshape existing domains? Conservative (only propose splits/merges, never auto-apply) vs. aggressive (auto-reassign memories whose scores drifted below threshold)? + +8. **Spreading activation across domains**: When searching within a single domain, should graph edges that cross into other domains be followed? Probably yes for recall quality, but with decaying weight as you cross boundaries. + +9. **Threshold tuning**: The `assign_threshold` (0.65 default) determines how many memories are multi-domain vs single-domain vs unclassified. Too low → everything is multi-domain (useless). Too high → too many unclassified. Could be auto-tuned per dataset by targeting a specific unclassified ratio (e.g., "keep fewer than 10% unclassified"). From 9c633c172b346980eacd5173e5aa66eea767836a Mon Sep 17 00:00:00 2001 From: Jan De Landtsheer Date: Wed, 22 Apr 2026 10:28:59 +0200 Subject: [PATCH 2/6] Added postgres admin added amends to the postgres backend/phase2 --- .gitignore | 3 + docs/plans/0002-phase-2-postgres-backend.md | 3 +- docs/plans/local-dev-postgres-setup.md | 153 ++++++++++++++++++++ 3 files changed, 158 insertions(+), 1 deletion(-) create mode 100644 docs/plans/local-dev-postgres-setup.md diff --git a/.gitignore b/.gitignore index 4236e68..41e352a 100644 --- a/.gitignore +++ b/.gitignore @@ -137,3 +137,6 @@ apps/dashboard/node_modules/ # ============================================================================= fastembed-rs/ .mcp.json + +.claude/ +.codebase-memory/ diff --git a/docs/plans/0002-phase-2-postgres-backend.md b/docs/plans/0002-phase-2-postgres-backend.md index a372e27..3fe28f2 100644 --- a/docs/plans/0002-phase-2-postgres-backend.md +++ b/docs/plans/0002-phase-2-postgres-backend.md @@ -2,7 +2,7 @@ **Status**: Draft **Depends on**: Phase 1 (MemoryStore + Embedder traits, embedding_model registry, domain columns) -**Related**: docs/adr/0001-pluggable-storage-and-network-access.md (Phase 2), docs/prd/001-getting-centralized-vestige.md +**Related**: docs/adr/0001-pluggable-storage-and-network-access.md (Phase 2), docs/prd/001-getting-centralized-vestige.md, docs/plans/local-dev-postgres-setup.md (local cluster provisioning) --- @@ -85,6 +85,7 @@ postgres-backend = ["dep:sqlx", "dep:pgvector", "dep:tokio-stream", "dep:futures - The `pgvector` extension installed in the target database (our migration issues `CREATE EXTENSION IF NOT EXISTS vector`). - `sqlx-cli@0.8` installed on the developer machine for `cargo sqlx prepare --workspace` and `cargo sqlx migrate add` (not a build-time requirement once `.sqlx/` is committed). - Docker or Podman reachable by the test harness for `testcontainers-modules::postgres` to spin up `pgvector/pgvector:pg16`. +- A local Postgres cluster for `sqlx prepare`, manual migration work, and `vestige migrate --to postgres` smoke runs. The recipe for standing one up on Arch/CachyOS (install, initdb, role + db, pgvector, connection string at `~/.vestige_pg_pw`) lives in `docs/plans/local-dev-postgres-setup.md`. Postgres 18 from the Arch repo satisfies the "16 or newer" requirement above. Phase 2 work assumes `DATABASE_URL` points at that cluster once migrations are applied. ### Assumed Rust toolchain diff --git a/docs/plans/local-dev-postgres-setup.md b/docs/plans/local-dev-postgres-setup.md new file mode 100644 index 0000000..6250a55 --- /dev/null +++ b/docs/plans/local-dev-postgres-setup.md @@ -0,0 +1,153 @@ +# Local Dev Postgres Setup (Arch / CachyOS) + +**Status**: Applied on this machine on 2026-04-21 +**Related**: docs/plans/0002-phase-2-postgres-backend.md, docs/adr/0001-pluggable-storage-and-network-access.md + +Purpose: capture the minimum, repeatable steps to stand up a Postgres 18 instance on a local Arch/CachyOS box for Phase 2 (`PgMemoryStore`) development, `sqlx prepare`, and manual migration testing. This is a single-operator dev recipe, not a production runbook. + +--- + +## Current state on this machine + +- Package: `postgresql` 18.3-2 (pacman). Pulls `postgresql-libs`, `libxslt`. +- Service: `postgresql.service`, enabled + active. +- Listens on: `127.0.0.1:5432` and `[::1]:5432` only (default `listen_addresses = 'localhost'`). +- Data dir: `/var/lib/postgres/data`, owner `postgres:postgres`. +- Auth (`pg_hba.conf`, Arch defaults): `peer` for local socket, `scram-sha-256` for host 127.0.0.1/::1. + +### Database + role + +- Database: `vestige`, UTF8, owner `vestige`. +- Role: `vestige` with `LOGIN CREATEDB` (no superuser, no replication, no cross-db). +- Schema `public` re-owned to `vestige`, plus default privileges so any future tables / sequences / functions in `public` are fully owned and granted to `vestige`. + +Net effect: the `vestige` role can create, alter, drop, and grant freely inside the `vestige` database -- enough for `sqlx::migrate!`, ad-hoc schema work, and the full Phase 2 `MemoryStore` surface. It cannot create extensions (see Phase 2 followups below) and cannot touch other databases. + +### Connection + +``` +postgresql://vestige:@127.0.0.1:5432/vestige +``` + +Password lives at `~/.vestige_pg_pw`, mode 600, owned by the dev user (no sudo needed to read it). Read with: + +```sh +cat ~/.vestige_pg_pw +``` + +Recommended dev shell export (keep this OUT of the repo; use `.env` + gitignore or a shell rc): + +```sh +export DATABASE_URL="postgresql://vestige:$(cat ~/.vestige_pg_pw)@127.0.0.1:5432/vestige" +``` + +--- + +## Reproduce from scratch + +On a fresh Arch / CachyOS box with passwordless sudo: + +```sh +# 1. Install +sudo pacman -S --noconfirm postgresql + +# 2. Initialize the cluster (UTF8, scram-sha-256 for host, peer for local) +sudo -iu postgres initdb \ + --locale=C.UTF-8 --encoding=UTF8 \ + -D /var/lib/postgres/data \ + --auth-host=scram-sha-256 --auth-local=peer + +# 3. Start + enable +sudo systemctl enable --now postgresql + +# 4. Generate a password and stash it in the dev user's home (mode 600) +VESTIGE_PW=$(python3 -c 'import secrets,string; a=string.ascii_letters+string.digits; print("".join(secrets.choice(a) for _ in range(32)))') +umask 077 +printf '%s' "$VESTIGE_PW" > ~/.vestige_pg_pw +chmod 600 ~/.vestige_pg_pw + +# 5. Create role + database + grants +sudo -u postgres psql -v ON_ERROR_STOP=1 < ~/.vestige_pg_pw +chmod 600 ~/.vestige_pg_pw +sudo -u postgres psql -v ON_ERROR_STOP=1 \ + -c "ALTER ROLE vestige WITH PASSWORD '${NEW_PW}';" +unset NEW_PW +``` + +Then re-export `DATABASE_URL` in any live shells. + +--- + +## Teardown + +Destroys the cluster and all data in it: + +```sh +sudo systemctl disable --now postgresql +sudo pacman -Rns postgresql postgresql-libs +sudo rm -rf /var/lib/postgres +rm -f ~/.vestige_pg_pw +``` + +--- + +## Out of scope for this doc + +- TLS, client-cert auth, non-localhost access. Phase 3 exposes the Vestige HTTP API over the network, not Postgres directly. +- Backups, PITR, WAL archiving. For dev data: `pg_dump -h 127.0.0.1 -U vestige vestige > vestige.sql`. +- Replication, PgBouncer, tuned `postgresql.conf`. Defaults are fine for Phase 2 development. +- Making this the canonical Vestige backend. By default Vestige still uses SQLite; this cluster exists so the `postgres-backend` feature can be built and tested locally. From c584ec8afeb8a82b9659b2c1fc36fc900f997c4b Mon Sep 17 00:00:00 2001 From: Jan De Landtsheer Date: Wed, 27 May 2026 09:35:23 +0200 Subject: [PATCH 3/6] docs(adr): add ADR 0002 -- Phase 2 execution Binding ADR for Phase 2 Postgres backend integration plus the Phase 1 amendment that removes async_trait from the storage and embedder traits. Decisions D1-D8: - D1: sunset async_trait across MemoryStore + Embedder via trait_variant - D2: PgMemoryStore::connect(url, max_connections) mirrors SqliteMemoryStore; no Embedder in constructor; register_model handles pgvector typmod - D3: split sqlite.rs into a sqlite/ directory as Phase 1 amendment - D4: postgres/ as a directory from day one - D5: sub-plan layout -- 3 Phase 1 amendment + 9 Phase 2 sub-plans - D6: no separate ADR for the SQLite split (pure code motion) - D7: reserve multi-tenancy schema (users/groups/group_memberships + owner_user_id/visibility/shared_with_groups) in Phase 2 so Phase 3 auth is additive, not an online migration over an HNSW-indexed table - D8: codebase promoted to a first-class indexed column on knowledge_nodes; mcp_client_id and session_id stay in metadata JSONB PR cadence: PR A = Phase 1 amendment (code on feat/storage-trait-phase1); PR B = this ADR + Phase 2 sub-plans (docs only); PR C = Phase 2 implementation. Phase 4 sharing_rules table sketched in Follow-ups. --- docs/adr/0002-phase-2-execution.md | 545 +++++++++++++++++++++++++++++ 1 file changed, 545 insertions(+) create mode 100644 docs/adr/0002-phase-2-execution.md diff --git a/docs/adr/0002-phase-2-execution.md b/docs/adr/0002-phase-2-execution.md new file mode 100644 index 0000000..6b6949f --- /dev/null +++ b/docs/adr/0002-phase-2-execution.md @@ -0,0 +1,545 @@ +# ADR 0002: Phase 2 Execution -- Postgres Backend Integration, Phase 1 Amendment + +**Status**: Accepted +**Date**: 2026-05-26 +**Related**: [docs/adr/0001-pluggable-storage-and-network-access.md](0001-pluggable-storage-and-network-access.md), [docs/plans/0002-phase-2-postgres-backend.md](../plans/0002-phase-2-postgres-backend.md) + +--- + +## Context + +ADR 0001 set the architectural direction: introduce `MemoryStore` and `Embedder` +traits, ship a Postgres backend behind a feature flag, and reach a single shared +memory brain across machines. Phase 1 (storage trait extraction) shipped on +`feat/storage-trait-phase1` (790c0c8). The Phase 2 master plan at +`docs/plans/0002-phase-2-postgres-backend.md` was drafted before Phase 1 was +frozen. + +Starting Phase 2 surfaces a small set of execution-level decisions that ADR 0001 +did not cover and that the master plan now disagrees with the live code on. +These decisions are too big to silently absorb into a per-step plan and too +small to amend ADR 0001. They live here. + +Three concrete realities driving this ADR: + +1. **Trait shape mismatch.** Master plan 0002 assumed `trait_variant::make` + produced distinct `MemoryStore` (Send-bound) and `LocalMemoryStore` + (non-Send) variants, and that errors were `StoreError`. Phase 1 froze on + `#[async_trait::async_trait]` with `pub use MemoryStore as LocalMemoryStore` + and an error type called `MemoryStoreError`. The Postgres backend has to + follow Phase 1, not the master plan -- but we should record that explicitly. +2. **`SqliteMemoryStore` is monolithic.** + `crates/vestige-core/src/storage/sqlite.rs` is ~8200 lines. Phase 1 appended + the trait impl block at the bottom of the same file. Adding a similarly + large `postgres.rs` perpetuates the pattern; this is the natural moment to + decide whether the SQLite file gets split. +3. **Constructor surface drift.** Master plan 0002 specifies + `PgMemoryStore::connect(url, max_connections, &dyn Embedder)`. The Phase 1 + `SqliteMemoryStore` constructor takes no embedder -- registry consistency + runs through `registered_model()` / `register_model()` on the trait, + invoked by the caller. The two backends should look the same to a caller; + right now they would not. +4. **Multi-tenancy is a one-way door.** The Postgres schema is the place to + reserve user/group/visibility columns *now*, even though Phase 3 is the + phase that wires the auth filter using them. Adding `owner_user_id` and + GIN indexes to a populated, HNSW-indexed `knowledge_nodes` table later is an + expensive online migration; reserving NULL-defaulted columns at schema + creation is ~10 lines of SQL. The same logic applies to per-memory + context capture (codebase, MCP caller, session) -- promoting `codebase` + to a first-class column now keeps the door open for context-aware + sharing rules in Phase 4 without touching `knowledge_nodes`. See D7 and D8. + +This ADR is also the umbrella under which Phase 2 sub-plans (`0002a-...`, +`0002b-...`, etc.) sit. The intent is: ADR + sub-plans land as one PR for +review; the implementation lands as a second PR with many commits inside. + +--- + +## Already Decided (carried in by reference) + +These are settled by ADR 0001 or by explicit agreement during this session. +Listed here so the discussion frame is clear; not re-litigated below. + +- Postgres backend ships behind a `postgres-backend` Cargo feature, default + OFF. Mutually compilable with SQLite. (ADR 0001.) +- Single big `MemoryStore` trait. `PgMemoryStore` implements the same surface + as `SqliteMemoryStore`. (ADR 0001.) +- pgvector HNSW + tsvector + GIN + RRF hybrid search in one SQL statement. + (Master plan 0002, D4-D5.) +- sqlx 0.8 + pgvector 0.4 + compile-time-checked queries + offline `.sqlx/` + cache committed. (Master plan 0002.) +- Two sqlx migration files: `0001_init` (extensions, tables, non-vector + indexes) and `0002_hnsw` (HNSW separated for re-embed drop/recreate). + (Master plan 0002, D4.) +- `vestige migrate --from sqlite --to postgres` and + `vestige migrate --reembed --model=` CLI subcommands. (ADR 0001 + + master plan 0002, D8-D10.) +- PR cadence: PR #1 carries this ADR plus all sub-plans; PR #2 carries the + implementation as many commits. +- Sub-plans use `0002a-`, `0002b-`, ... suffixes off `0002-`. +- `PgMemoryStore::connect` lands as `todo!()` in the skeleton; real body + comes later. + +--- + +## Decisions + +### D1. Sunset async_trait across the Phase 1 traits + +Phase 1 froze with `#[async_trait::async_trait]` on both the `MemoryStore` +trait (`storage/memory_store.rs:194`) and the `Embedder` trait +(`embedder/mod.rs:27`), plus their SQLite and Fastembed impl blocks. async_trait +boxes every async fn into `Pin>` -- one heap allocation +per call inside the hottest code path. We are amending Phase 1 to remove +async_trait entirely and replace it with `trait_variant::make`, so each trait +becomes two real generated variants (`MemoryStore` / `LocalMemoryStore`, +`Embedder` / `LocalEmbedder`) with `Send` bounds on the outer variant. + +Scope split across three Phase 1 amendment sub-plans: + +- **`0001a-trait-rewrite.md`** -- Rewrite `MemoryStore` only. Touches + `storage/memory_store.rs` (trait declaration) and `storage/sqlite.rs` + (impl block attribute). Leaves async_trait in place on the embedder side + so the diff stays focused. +- **`0001b-sqlite-split.md`** -- Pure code motion. Splits the + ~8200-line `sqlite.rs` into a `sqlite/` directory. Independent of D1; can + land in either order relative to `0001a`. +- **`0001c-async-trait-sunset.md`** -- Rewrite `Embedder` the same way, then + remove `async-trait = "0.1"` from `crates/vestige-core/Cargo.toml`. Final + amendment commit removes the dependency entirely. After this lands, the + workspace contains zero references to `async_trait`. + +All three sub-plans land on the existing `feat/storage-trait-phase1` branch +(790c0c8 has not been opened upstream yet; amend in place, no force-push to a +public PR). + +### D2. PgMemoryStore::connect mirrors SqliteMemoryStore::new + +```rust +impl PgMemoryStore { + pub async fn connect(url: &str, max_connections: u32) -> MemoryStoreResult; + pub async fn from_pool(pool: PgPool) -> MemoryStoreResult; +} +``` + +No `Embedder` in the constructor. The pgvector-specific +`ALTER TABLE knowledge_nodes ALTER COLUMN embedding TYPE vector($N)` DDL lives +inside the trait method `register_model(&ModelSignature)`. That method is +called by the caller (cognitive engine bootstrap, migrate CLI, tests) after +construction, exactly as it is for `SqliteMemoryStore`. + +`MemoryStoreError` gains two variants behind the feature flag (added during +the Postgres impl, not during the Phase 1 amendment): +```rust +#[cfg(feature = "postgres-backend")] +#[error("postgres error: {0}")] +Postgres(#[from] sqlx::Error), + +#[cfg(feature = "postgres-backend")] +#[error("postgres migration error: {0}")] +Migrate(#[from] sqlx::migrate::MigrateError), +``` + +### D3. Split sqlite.rs into a sqlite/ directory as Phase 1 amendment + +Pure code motion, no behavioural change. Target layout: +``` +crates/vestige-core/src/storage/sqlite/ + mod.rs -- SqliteMemoryStore struct, new(), reader/writer locks + crud.rs -- insert/get/update/delete + search.rs -- fts_search, vector_search, hybrid search + scheduling.rs -- FSRS state methods + graph.rs -- edges, neighbors + domain.rs -- domain CRUD, classify stub + registry.rs -- embedding_model table + register_model + portable_sync.rs -- portable archive backend bridge + trait_impl.rs -- impl LocalMemoryStore for SqliteMemoryStore +``` + +Cognitive-module imports stay on `crate::storage::SqliteMemoryStore` and +related re-exports from `storage/mod.rs`; the split is private to the +module. Each motion commit must keep `cargo test -p vestige-core` green for +bisectability. + +This lands in the Phase 1 amendment PR alongside D1 (separate commit, same +branch). + +### D4. Postgres backend as a directory from day one + +``` +crates/vestige-core/src/storage/postgres/ + mod.rs -- PgMemoryStore struct, connect, from_pool, trait impl + pool.rs -- PgPool construction from PostgresConfig + migrations.rs -- sqlx::migrate! wrapper + registry.rs -- ensure_registry, ALTER COLUMN TYPE vector(N) + search.rs -- RRF query + row mapping + migrate_cli.rs -- SQLite -> Postgres streaming copy + reembed.rs -- O(n) re-encode + HNSW rebuild +``` + +D1+D2 of the master plan land first as a skeleton in `mod.rs` with `todo!()` +bodies; later sub-plans fill in the other files. + +### D5. Sub-plan layout: two phases worth of sub-plans + +Phase 1 amendment sub-plans (under `docs/plans/`): +- `0001a-trait-rewrite.md` -- MemoryStore async_trait -> trait_variant, call-site audit +- `0001b-sqlite-split.md` -- sqlite.rs -> sqlite/ directory, commit-by-commit +- `0001c-async-trait-sunset.md` -- Embedder rewrite + drop async-trait dep from Cargo.toml + +Phase 2 sub-plans (under `docs/plans/`): +- `0002a-skeleton-and-feature-gate.md` -- master plan D1 + D2 (todo!() bodies) +- `0002b-pool-and-config.md` -- master plan D3 + D7 +- `0002c-migrations.md` -- master plan D4 +- `0002d-store-impl-bodies.md` -- master plan D2 real bodies + D6 registry +- `0002e-hybrid-search.md` -- master plan D5 +- `0002f-migrate-cli.md` -- master plan D8 + D10 +- `0002g-reembed.md` -- master plan D9 +- `0002h-testing-and-benches.md` -- master plan D14 + D15 +- `0002i-runbook.md` -- master plan D16 + +Each sub-plan is a self-contained brief sized to fit one focused +implementation session (handed to Claude Code as a `/goal` instruction +without requiring the agent to load the master plan). + +### D6. SQLite split does not get its own ADR + +The split is pure code motion; no public types, behaviour, or paths change. +`0001b-sqlite-split.md` is enough. + +### D7. Multi-tenancy schema reservation (L1-L3) + +Phase 2 reserves the columns and tables needed for future per-user / per-group +visibility, so Phase 3 (auth) does not require a column-add migration over a +populated, HNSW-indexed `knowledge_nodes` table. Single-user behaviour is unchanged +in both backends. + +New tables in `0001_init.up.sql`: + +```sql +CREATE TABLE users ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + handle TEXT NOT NULL UNIQUE, + display_name TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + metadata JSONB NOT NULL DEFAULT '{}'::jsonb +); + +CREATE TABLE groups ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + handle TEXT NOT NULL UNIQUE, + display_name TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + metadata JSONB NOT NULL DEFAULT '{}'::jsonb +); + +CREATE TABLE group_memberships ( + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + group_id UUID NOT NULL REFERENCES groups(id) ON DELETE CASCADE, + role TEXT NOT NULL DEFAULT 'member', -- 'member' | 'admin' + joined_at TIMESTAMPTZ NOT NULL DEFAULT now(), + PRIMARY KEY (user_id, group_id) +); + +INSERT INTO users (id, handle, display_name) + VALUES ('00000000-0000-0000-0000-000000000001', 'local', 'Local User'); +``` + +New columns on `knowledge_nodes`: + +```sql +owner_user_id UUID NOT NULL DEFAULT '00000000-0000-0000-0000-000000000001' + REFERENCES users(id), +visibility TEXT NOT NULL DEFAULT 'private', -- 'private' | 'group' | 'public' +shared_with_groups UUID[] NOT NULL DEFAULT '{}' + +CREATE INDEX idx_knowledge_nodes_owner ON knowledge_nodes (owner_user_id); +CREATE INDEX idx_knowledge_nodes_shared_groups ON knowledge_nodes USING GIN (shared_with_groups); +``` + +Phase 3 visibility filter (declared here for reference; implemented in Phase 3): + +```sql +WHERE + (visibility = 'private' AND owner_user_id = $me) + OR (visibility = 'group' + AND (owner_user_id = $me OR shared_with_groups && $my_group_ids)) + OR visibility = 'public' +``` + +Why tri-state enum and not just `shared_with_groups[] + is_public`: the +explicit `visibility` field documents intent at the row level. A `'private'` +row with a non-empty `shared_with_groups` is detectable inconsistency +(a CHECK constraint can enforce it later) rather than silent data. + +SQLite parity: same tables and columns with identical defaults. +`shared_with_groups` is a JSON `'[]'` text encoding (no array type). +Single-user mode never changes any of these values; the trait surface ignores +the visibility filter for SQLite because there is exactly one user. + +Sharing automation (matching by domain, tag, repo, MCP caller, ...) is +explicitly **not** in Phase 2. See D8 for context capture, and the Follow-ups +section for the Phase 4 `sharing_rules` design sketch. + +RLS policies are not declared in Phase 2. Phase 3 decides whether to add +RLS as defense-in-depth on top of the app-layer filter. + +### D8. Context-aware ingest + +Every memory carries its ingest context, so future automation (sharing rules, +domain scoping, audit) can match on it without a schema migration. Most of +this is already happening in the Phase 1 ingest pipeline; D8 promotes it to +ADR-level commitment so Phase 2 cannot drop it on the way to Postgres. + +Context dimensions and where they live: + +- **`codebase`** -- promoted to a first-class indexed column on `knowledge_nodes`. + High-frequency query path (`SELECT ... WHERE codebase = 'vestige'`) for + both human exploration and Phase 4 HDBSCAN scoping. Direct B-tree index + beats JSONB extraction. + ```sql + codebase TEXT, -- nullable; populated from ingest context + CREATE INDEX idx_knowledge_nodes_codebase ON knowledge_nodes (codebase) WHERE codebase IS NOT NULL; + ``` + `MemoryRecord` gains `pub codebase: Option`. + +- **`mcp_client_id`** -- which MCP caller created this. Persistent identity + once Phase 3 API keys exist. Lives in `metadata.mcp_client_id` (JSONB). + Not query-hot enough to deserve a column. + +- **`session_id`** -- ephemeral; identifies the calling session for runtime + override scoping. Lives in `metadata.session_id` (JSONB). Sessions die + fast; storing them as rows or indexed columns is waste. + +- **`file` / `topics`** -- existing optional context already accepted by the + ingest pipeline. Stay in metadata JSONB. + +Phase 2's job for D8 is operational, not architectural: audit the ingest +path from MCP request to row write to ensure none of these fields gets +dropped when crossing the SQLite -> Postgres backend boundary. + +--- + +## PR Cadence + +Two work streams, three PRs total: + +1. **PR A: Phase 1 amendment** + - Branch: `feat/storage-trait-phase1` (existing, amended in place) + - Commits: MemoryStore trait rewrite (0001a) + sqlite split (0001b, multiple + motion commits) + Embedder rewrite & async-trait dep removal (0001c). + - Sub-plans `0001a-`, `0001b-`, `0001c-` are committed on this branch. + +2. **PR B: ADR 0002 + Phase 2 sub-plans (this document + the 9 sub-plans)** + - New branch off PR A's tip once that is reviewed. + - No code; docs only. + +3. **PR C: Phase 2 implementation** + - New branch off PR B's tip. + - One PR with many commits clustered by sub-plan. + +PR B is the "let's discuss execution before writing code" gate. PR C is the +"now we write code" gate. If PR A is itself sizable enough that it needs the +amendments reviewed in stages, the three sub-plans (`0001a`, `0001b`, `0001c`) +can split into separate PRs; that's a tactical call at PR time. + +--- + +## Architecture Overview + +Final layout after the Phase 1 amendment (PR A) and Phase 2 implementation +(PR C): + +``` +crates/vestige-core/src/storage/ + mod.rs -- re-exports, Storage alias for BC + memory_store.rs -- trait_variant-generated MemoryStore + LocalMemoryStore, types, error + migrations.rs -- SQLite migration registry (Phase 1, unchanged) + portable.rs -- portable archive format (Phase 1, unchanged) + sqlite/ -- was sqlite.rs (D3, Phase 1 amendment) + mod.rs -- SqliteMemoryStore struct, new(), reader/writer locks + crud.rs -- insert/get/update/delete + search.rs -- fts/vector/hybrid + scheduling.rs -- FSRS state + graph.rs -- edges, neighbors + domain.rs -- domain CRUD, classify stub + registry.rs -- embedding_model table + register_model + portable_sync.rs -- portable backend bridge + trait_impl.rs -- impl LocalMemoryStore for SqliteMemoryStore + postgres/ -- D4, Phase 2 + mod.rs -- PgMemoryStore struct, connect, from_pool, trait impl + pool.rs -- PgPool construction from config + migrations.rs -- sqlx::migrate! wrapper + registry.rs -- register_model body, ALTER COLUMN TYPE vector(N) + search.rs -- RRF query + row mapping + migrate_cli.rs -- SQLite -> Postgres streaming copy + reembed.rs -- O(n) re-encode + HNSW rebuild + +crates/vestige-core/migrations/ + sqlite/ -- Phase 1, with V15 migration for D7+D8 columns/tables + postgres/ -- Phase 2 + 0001_init.up.sql -- includes D7 tables + columns, D8 codebase column + 0001_init.down.sql + 0002_hnsw.up.sql + 0002_hnsw.down.sql +``` + +Tables in the Postgres schema after migration 0001: + +| Table | Purpose | Phase that populates | +|-------|---------|----------------------| +| `embedding_model` | One-row registry of name/dim/hash | Phase 2 (first connect) | +| `knowledge_nodes` | Core records + owner/visibility/codebase | Phase 2 ingest; Phase 4 fills `domains` | +| `scheduling` | FSRS state | Phase 2 | +| `edges` | Spreading activation graph | Phase 2 | +| `review_events` | Append-only FSRS review log | Phase 2; Phase 5 federation reads | +| `domains` | Phase 4 cluster centroids | Phase 4 | +| `users` | L1 identities (D7) | Phase 3 | +| `groups` | L3 groups (D7) | Phase 3 | +| `group_memberships` | L3 user-group links (D7) | Phase 3 | + +`sharing_rules` (Phase 4) and `api_keys` (Phase 3) are added later by their +own migrations. + +--- + +## Alternatives Considered + +| Alternative | Why not | +|-------------|---------| +| Keep async_trait on the Phase 1 trait | One heap allocation per trait call inside the hottest code path in Vestige. Boxing every future also obscures the actual return type, which makes lifetimes and Send-ness harder to reason about. The Phase 1 PR is not opened upstream yet, so amending is free. | +| Take `&dyn Embedder` into `connect` | Couples constructor to embedder; breaks ADR 0001's separation; can't be used by callers that don't have an embedder yet (tests, migrate CLI). | +| Defer SQLite split | Postgres lands alongside an 8K-line peer; the pattern compounds; future readers see "backends are huge here". | +| Single `postgres.rs` | Master plan calls out 7 sub-files; we know it's getting split; doing it twice is waste. | +| Per-deliverable sub-plans (16 docs) | Review fatigue; many sub-plans would be 3-5 lines of Cargo or one migration each. Logical groups cluster naturally with PR commits. | +| One rolling sub-plan with checkboxes | Moving target; doesn't serve as a `/goal` brief for a fresh Claude Code session. | +| Separate ADR for the SQLite split | Pure code motion with no public-surface change; doesn't constrain future decisions. ADRs are for decisions that bind. | +| Punt multi-tenancy schema entirely to Phase 3 | Adding `owner_user_id` and indexes to a populated, HNSW-indexed `knowledge_nodes` table later is an expensive online migration. Reserving NULL-defaulted columns now is ~10 lines of SQL. | +| `shared_with_groups[] + is_public` instead of tri-state visibility enum | More compact but `visibility = 'private'` documents intent at the row level; a CHECK constraint can later enforce array/enum consistency. Two columns conveying one fact is fine when both are referenced often. | +| Add `shared_with_users[]` for direct user-to-user sharing | A "group of one" subsumes it without an extra column and GIN index. Phase 3 CLI can auto-create singleton groups if a user requests direct shares. | +| Bake per-domain or per-tag sharing defaults into Phase 2 schema | Sharing automation needs real usage data before committing to fuzzy (domain centroids) vs crisp (tags) vs context (codebase / MCP caller). Phase 4 designs a generic `sharing_rules` table that matches on any context dimension; deferring costs nothing because rules live in a new table, not new columns. | +| `codebase` stays in JSONB metadata | High-frequency query path (HDBSCAN scoping, codebase-wide searches, future `sharing_rules` match). B-tree on a real column beats GIN on a JSONB key for this access pattern. Cost is one nullable TEXT column. | + +--- + +## Consequences + +### Positive +- Phase 1 trait stops boxing futures on every call. Lifetimes and Send-ness + become inspectable instead of hidden inside an `async_trait` macro expansion. +- `connect` stays backend-agnostic; tests and CLI tools stand up either backend + without an `Embedder` in scope. +- Cognitive module imports never change paths -- the SQLite split is private + to `storage/sqlite/`, public re-exports through `storage/mod.rs` unchanged. +- Postgres backend lands already-modular; future SQL changes touch one of + seven small files, not one of eight thousand lines. +- Phase 2 master plan stays archival; ADR 0002 + sub-plans are the live source + of truth for execution. +- Multi-tenancy columns reserved now means Phase 3 auth is purely additive -- + no online migration over a populated, HNSW-indexed `knowledge_nodes` table. +- Context-aware ingest (D8) keeps the door open for repo / session / + MCP-caller-scoped sharing rules in Phase 4 without changing `knowledge_nodes`. + +### Negative +- The Phase 1 amendment expands a "finished" branch. It is a real cost: the + trait rewrite touches every cognitive module that holds a store handle. +- SQLite split is a pure-motion diff. Annoying to review even when safe. +- Three PRs (amendment, ADR+plans, implementation) instead of one or two. + Discipline tax in exchange for reviewability. +- Multi-tenancy reservation adds three never-queried tables and three + always-default columns to the SQLite schema. Real but small storage cost in + single-user mode (a single bootstrap row + empty tables + NULL/empty + defaults per memory). + +### Risks +- **Trait rewrite breaks a cognitive module's Send-ness expectation.** + Mitigation: `cargo test --workspace` runs after each call-site edit; + trait_variant-generated `MemoryStore` is the Send variant and matches the + current `Arc` usage everywhere except thread-local impls (none + exist today). +- **SQLite motion commit introduces a silent semantic change.** Mitigation: + each commit keeps `cargo test -p vestige-core` green; reviewer can bisect. +- **Sub-plan boundaries don't match how implementation wants to commit.** + Mitigation: sub-plans are advisory; the implementation PR clusters commits + however it ends up needing to. +- **Reserved columns get used in Phase 3 in a way that mismatches Phase 2 + defaults.** Mitigation: Phase 3 owns the auth filter; Phase 2 defaults + (`owner_user_id = local`, `visibility = 'private'`) are intentionally the + "no access for anyone but the owner" worst-case; widening at Phase 3 is + safe, narrowing would be the dangerous direction. +- **Memory: PR A amendment invalidates the locally-deployed Phase 1 binary's + ABI.** Not a real risk -- the trait change is purely source-level Rust; the + on-disk DB schema is unchanged. The rebuilt binary slots in over the + current one without DB migration. + +--- + +## Resolved Decisions + +| # | Question | Resolution | +|---|----------|------------| +| Q1 | Phase 1 trait shape | Rewrite with trait_variant::make. Amend Phase 1 PR. | +| Q2 | PgMemoryStore::connect signature | Mirror SqliteMemoryStore::new; no Embedder. register_model does the pgvector typmod stamp. | +| Q3 | Split sqlite.rs | Yes, as Phase 1 amendment. sqlite.rs -> sqlite/ directory; pure code motion. | +| Q4 | Postgres module layout | Directory from day one. | +| Q5 | Sub-plan granularity | Logical groups, ~9 docs for Phase 2 plus 2 for the Phase 1 amendment. | +| Q6 | ADR for SQLite split | No. Sub-plan `0001b-sqlite-split.md` is sufficient. | +| Q7 | Multi-tenancy schema | Reserve users / groups / group_memberships tables and owner_user_id / visibility / shared_with_groups columns on knowledge_nodes in Phase 2. Single-user defaults; Phase 3 fills in real values. | +| Q8 | Visibility encoding | Tri-state enum `'private' \| 'group' \| 'public'` plus `shared_with_groups[]`. No `shared_with_users[]`; no RLS in Phase 2. | +| Q9 | Sharing automation grain | Per-memory only in Phase 2. Phase 4 ships a generic `sharing_rules` table matching on codebase / tag / node_type / mcp_client_id. | +| Q10 | Context capture on ingest | `codebase` promoted to a first-class indexed column; `mcp_client_id` and `session_id` stay in metadata JSONB. | + +--- + +## Follow-ups + +- Phase 1 amendment sub-plans drafted: `0001a-trait-rewrite.md`, + `0001b-sqlite-split.md`, `0001c-async-trait-sunset.md`. Ready to execute on + `feat/storage-trait-phase1`. +- Phase 2 sub-plans drafted: `0002a-` through `0002i-` against the accepted + decisions above. Ready to execute on a new branch off PR A's tip. +- Decide branch placement for this ADR before it gets committed -- it cannot + live on `feat/storage-trait-phase1` (that branch is now PR A's code-only + amendment branch). Likely a new branch off PR A's tip for PR B (docs only). +- Validate local Postgres dev cluster before PR C work begins. Recipe at + `docs/plans/local-dev-postgres-setup.md` is correct but needs to be applied + on this machine (delandtj-home): cluster is not initdb'd, pgvector is not + installed. Containerized `pgvector/pgvector:pg16` is a viable alternative + if pgvector packaging is friction. See open discussion thread. + +### Phase 4 sketch: `sharing_rules` and the precedence chain + +Recorded here so the Phase 4 author does not have to rediscover the design. +Phase 2 does **not** implement any of this; it only ensures the schema and +ingest context capture make this possible without a `knowledge_nodes` migration. + +```sql +-- Phase 4 migration (not Phase 2) +CREATE TABLE sharing_rules ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + owner_user_id UUID NOT NULL REFERENCES users(id), + -- Match: any subset; all set fields must match conjunctively + match_codebase TEXT, + match_tag TEXT, + match_node_type TEXT, + match_api_key_id UUID REFERENCES api_keys(id), -- MCP caller identity + -- Policy + visibility TEXT NOT NULL, + shared_with_groups UUID[] NOT NULL DEFAULT '{}', + -- Conflict resolution + priority INTEGER NOT NULL DEFAULT 0, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +``` + +Precedence on ingest, first match wins: + +1. Caller-explicit visibility in the MCP request +2. Active session override held by the MCP server (per-session, in-memory, + not persisted; matched by `session_id`) +3. Highest-priority `sharing_rules` row whose match fields all hold +4. User's `default_visibility` (typically `'private'`) + +Per-session overrides do not persist; storing ephemeral session IDs as DB +rows is waste. Per-codebase / per-MCP-caller rules do persist as +`sharing_rules` rows. From 697ade5b02decdfaf1165958f945f0f92b905497 Mon Sep 17 00:00:00 2001 From: Jan De Landtsheer Date: Wed, 27 May 2026 09:35:37 +0200 Subject: [PATCH 4/6] docs(plans): add Phase 1 amendment sub-plans 0001a/b/c Three sub-plans operationalising ADR 0002 D1 + D3 on the existing feat/storage-trait-phase1 branch (790c0c8, not yet pushed upstream): - 0001a-trait-rewrite.md -- rewrite MemoryStore with #[trait_variant::make(MemoryStore: Send)] generating a non-Send LocalMemoryStore companion. Production callers use Arc and are unaffected; only the trait declaration and SQLite impl block change. - 0001b-sqlite-split.md -- pure code motion. Split sqlite.rs (8713 lines) into a sqlite/ directory (mod, crud, search, scheduling, graph, domain, registry, portable_sync, trait_impl). Public re-exports unchanged; tests green commit-by-commit. Depends on 0001a so trait_impl.rs picks up the trait_variant attribute once. - 0001c-async-trait-sunset.md -- rewrite Embedder the same way, then remove async-trait = "0.1" from crates/vestige-core/Cargo.toml. End state: zero async_trait references in the workspace. Together these three lands as PR A. --- docs/plans/0001a-trait-rewrite.md | 689 ++++++++++++++++++++ docs/plans/0001b-sqlite-split.md | 732 +++++++++++++++++++++ docs/plans/0001c-async-trait-sunset.md | 847 +++++++++++++++++++++++++ 3 files changed, 2268 insertions(+) create mode 100644 docs/plans/0001a-trait-rewrite.md create mode 100644 docs/plans/0001b-sqlite-split.md create mode 100644 docs/plans/0001c-async-trait-sunset.md diff --git a/docs/plans/0001a-trait-rewrite.md b/docs/plans/0001a-trait-rewrite.md new file mode 100644 index 0000000..354e138 --- /dev/null +++ b/docs/plans/0001a-trait-rewrite.md @@ -0,0 +1,689 @@ +# Phase 1 Amendment Sub-Plan: async_trait -> trait_variant + +**Status**: Draft +**Depends on**: Phase 1 (already on `feat/storage-trait-phase1`, tip 790c0c8) +**Followed by**: `docs/plans/0001c-async-trait-sunset.md` (Embedder rewrite + async-trait crate removal) +**Related**: docs/adr/0002-phase-2-execution.md (decision D1), docs/plans/0001-phase-1-storage-trait-extraction.md + +--- + +## Context + +Phase 1 froze with the storage trait declared as +`#[async_trait::async_trait] pub trait MemoryStore: Send + Sync + 'static` +and a `pub use MemoryStore as LocalMemoryStore;` alias. `async_trait` boxes +every `async fn` in the trait into `Pin>`. That is one +heap allocation per call inside the hottest code path in Vestige (insert, +search, update_scheduling are all on this surface). It also collapses the +two intended trait shapes -- a Send-bound `MemoryStore` for tokio/axum and a +non-Send `LocalMemoryStore` for thread-local backends -- into a single trait +behind an alias, removing the type-system signal we will want for Phase 2's +Postgres backend. + +ADR 0002 decision D1 supersedes this. The amendment lands on the existing +`feat/storage-trait-phase1` branch before Phase 2 starts, before the PR is +opened upstream. The end state: + +- `LocalMemoryStore` is the source-of-truth trait, declared with native + async-fn-in-trait (stable on MSRV 1.91), no `Sync` bound on the trait + itself, and `Sync + 'static` on the trait object. +- `MemoryStore` is auto-generated by `#[trait_variant::make(MemoryStore: Send)]` + with `Send` bounds on every returned future, so `Arc` is + movable across `tokio::spawn`. +- `trait-variant` 0.1 is already present in `crates/vestige-core/Cargo.toml`. + The `async-trait` crate dependency stays in place through this sub-plan + (it is still in use by the embedder impl); removing it is the job of + `0001c-async-trait-sunset.md`. +- No production caller changes. Every production call site holds + `Arc` (the concrete `SqliteMemoryStore` alias), which the trait + rewrite does not touch. Only the trait declaration and impl blocks change. + +--- + +## Scope + +### In scope + +- Rewrite `MemoryStore` / `LocalMemoryStore` declaration in + `crates/vestige-core/src/storage/memory_store.rs` to use + `#[trait_variant::make(MemoryStore: Send)] pub trait LocalMemoryStore`. +- Remove the `pub use MemoryStore as LocalMemoryStore;` alias from the same + file. `LocalMemoryStore` becomes the real trait; `MemoryStore` is the + generated Send variant. +- Drop the `#[async_trait::async_trait]` attribute on the SQLite impl block + in `crates/vestige-core/src/storage/sqlite.rs` (line 6274). The impl block + switches from `impl MemoryStore for SqliteMemoryStore` (currently spelled + through the `LocalMemoryStore` alias) to `impl LocalMemoryStore for + SqliteMemoryStore`. `trait_variant` provides a blanket `impl MemoryStore for T` so `&dyn MemoryStore` and + `Arc` keep working unchanged. +- Update doc comments in `memory_store.rs` to drop + references to `#[async_trait::async_trait]` and instead describe the + `trait_variant` mechanism. +- Keep the existing Phase 1 test suite (`tests/phase_1/*.rs`) green. The + tests already use `Arc` and `Box`, which is + exactly the surface the rewrite is meant to preserve. + +### Out of scope -- moved to 0001c + +- Rewriting the `Embedder` / `LocalEmbedder` trait declaration -- handled by + `0001c-async-trait-sunset.md`. +- Dropping `#[async_trait::async_trait]` from + `crates/vestige-core/src/embedder/fastembed.rs`. +- Removing `async-trait = "0.1"` from `crates/vestige-core/Cargo.toml`. +- The hard `grep -rn 'async_trait' crates/` zero-match gate (async_trait is + still present in the embedder module after 0001a alone). + +### Out of scope + +- The SQLite file split (`sqlite.rs` -> `sqlite/` directory). That is the + sibling sub-plan `0001b-sqlite-split.md`. +- Any production-side refactor that switches `Arc` to + `Arc`. Production code keeps using the concrete alias. +- Adding `register_model` / `from_pool` / Postgres-specific variants of + `MemoryStoreError`. Those land with the Postgres backend in Phase 2. +- Removing the `pub type Storage = SqliteMemoryStore;` alias. + +--- + +## Prerequisites + +### Current state (verified) + +- `crates/vestige-core/Cargo.toml` already declares + `trait-variant = "0.1"` (line 117). `async-trait = "0.1"` (line 119) + remains in place for the duration of this sub-plan; `0001c` removes it. +- `crates/vestige-core/src/storage/memory_store.rs:194` declares the trait + with `#[async_trait::async_trait] pub trait MemoryStore: Send + Sync + + 'static`. +- `crates/vestige-core/src/storage/memory_store.rs:262` has + `pub use MemoryStore as LocalMemoryStore;`. +- `crates/vestige-core/src/storage/sqlite.rs:6274` declares + `#[async_trait::async_trait] impl + crate::storage::memory_store::LocalMemoryStore for SqliteMemoryStore`. +- Production call sites use `Arc` (the concrete + `SqliteMemoryStore` alias). Confirmed by grep: + `grep -rn "dyn MemoryStore\|dyn LocalMemoryStore" --include="*.rs"` + returns hits only in `tests/phase_1/*.rs`, in two comments inside + `memory_store.rs` and `sqlite.rs`, and in one test-only `&dyn MemoryStore` + cast inside `sqlite.rs::tests` (line 8669). +- Workspace-wide `async_trait` usages: only the trait declarations and + impl blocks in `memory_store.rs`, `sqlite.rs`, `embedder/mod.rs`, and + `embedder/fastembed.rs` (verified by + `grep -rn async_trait --include="*.rs"`). This sub-plan touches only the + first two; the embedder files are addressed by `0001c`. + +### Required crates + +| Crate | Version | Action | +|-------|---------|--------| +| `trait-variant` | `0.1` | Already declared. Verify present after edit. | +| `async-trait` | `0.1` | Unchanged for this sub-plan (still used by embedder impl). Removed by `0001c`. | +| `blake3`, `thiserror`, `chrono`, `uuid`, `serde`, `serde_json` | unchanged | unchanged | + +--- + +## Files Touched + +Grouped by category. Every change is listed; nothing else gets touched. + +### Trait declarations (vestige-core) + +| File | Lines (approx) | Change | +|------|----------------|--------| +| `crates/vestige-core/src/storage/memory_store.rs` | 183-262 | Replace `#[async_trait::async_trait]` block with `#[trait_variant::make(MemoryStore: Send)] pub trait LocalMemoryStore`. Drop the `pub use MemoryStore as LocalMemoryStore;` alias. Update doc comments. | + +### Impl blocks (vestige-core) + +| File | Lines (approx) | Change | +|------|----------------|--------| +| `crates/vestige-core/src/storage/sqlite.rs` | 6274 (impl block header only) | Delete the `#[async_trait::async_trait]` attribute. Keep the `impl crate::storage::memory_store::LocalMemoryStore for SqliteMemoryStore { ... }` body verbatim. | + +### Cargo dependency cleanup + +None in this sub-plan. The `async-trait` crate stays declared in +`crates/vestige-core/Cargo.toml` because the embedder impl still uses it. +`0001c-async-trait-sunset.md` removes the dependency after the embedder +side is rewritten. + +### Cognitive module call sites + +No changes. The 29 cognitive modules under `crates/vestige-core/src/neuroscience/` +and `crates/vestige-core/src/advanced/` already operate on concrete +`SqliteMemoryStore` (via the `Storage` alias) or on plain data types +(`KnowledgeNode`, `Vec`, `ConnectionRecord`). Grep verified zero +production references to `dyn MemoryStore` or `dyn LocalMemoryStore`. + +### MCP call sites + +No changes. All ~30 `vestige-mcp/src/**.rs` files holding `Arc` +keep working because: +- `Storage` is still `pub type Storage = SqliteMemoryStore;` (unchanged). +- They call inherent methods on the concrete type, never via a trait object. +- `SqliteMemoryStore` implements `LocalMemoryStore`; `trait_variant` auto- + generates a blanket `impl MemoryStore for T`, + so the concrete type also satisfies `MemoryStore` for any future caller + that wants the trait-object form. + +### Test files (vestige-core integration tests) + +| File | Lines | Change | +|------|-------|--------| +| `tests/phase_1/trait_round_trip.rs` | 7-18, 134 | No change. Already uses `Arc` and `use vestige_core::storage::MemoryStore`. trait_variant emits a `MemoryStore` trait at the same path, so the imports resolve. | +| `tests/phase_1/send_bound_variant.rs` | 10-12, 36, 57 | No change. Already asserts the trait_variant Send invariant; the rewrite is what makes the doc comment on lines 3-4 actually true. | +| `tests/phase_1/cognitive_module_isolation.rs` | 11, 37, 76, 102, 115 | No change. | +| `tests/phase_1/embedding_model_registry.rs` | 10 | No change. | +| `tests/phase_1/domain_column_migration.rs` | 98 | No change. | +| `crates/vestige-core/src/storage/sqlite.rs::tests` | 8666-8675 | No change. The existing test casts `&s` to `&dyn MemoryStore` and calls trait methods through that vtable; trait_variant preserves this exact dyn-compatible surface. | + +### Documentation + +| File | Change | +|------|--------| +| `crates/vestige-core/src/storage/memory_store.rs` | Rewrite the trait-level doc comment (lines 185-193) to describe trait_variant rather than async_trait. | +| `CLAUDE.md` | No change. The repo-level architecture notes do not name the trait attribute. | + +--- + +## Trait Declaration Rewrite + +### Before (current state on `feat/storage-trait-phase1`) + +`crates/vestige-core/src/storage/memory_store.rs:183-262`: + +```rust +// ---------------------------------------------------------------------------- +// TRAIT +// ---------------------------------------------------------------------------- + +/// The single storage abstraction. +/// +/// `#[async_trait::async_trait]` makes every `async fn` return a +/// `Pin>`, which is required for `Arc` +/// to be movable across `tokio::spawn` boundaries. +/// +/// `LocalMemoryStore` is a type alias kept for source compatibility with code +/// that refers to the non-send variant. In Phase 1 both names refer to the same +/// (dyn-compatible, Send-safe) trait. +#[async_trait::async_trait] +pub trait MemoryStore: Send + Sync + 'static { + // --- Lifecycle --- + async fn init(&self) -> MemoryStoreResult<()>; + async fn health_check(&self) -> MemoryStoreResult; + + // ... 25 more async fn ... + + async fn vacuum(&self) -> MemoryStoreResult<()>; +} + +/// Type alias kept for source compatibility. Both names refer to the same +/// `async_trait`-annotated trait that is dyn-compatible and `Send + Sync`. +pub use MemoryStore as LocalMemoryStore; +``` + +### After + +`crates/vestige-core/src/storage/memory_store.rs:183-262`: + +```rust +// ---------------------------------------------------------------------------- +// TRAIT +// ---------------------------------------------------------------------------- + +/// The single storage abstraction. +/// +/// `LocalMemoryStore` is the source-of-truth trait. The +/// `#[trait_variant::make(MemoryStore: Send)]` attribute auto-generates a +/// `MemoryStore` trait whose returned futures are `Send`, so +/// `Arc` is movable across `tokio::spawn` boundaries while +/// `Arc` remains usable on single-threaded executors +/// and thread-local backends. +/// +/// Every method is native async-fn-in-trait (stable on MSRV 1.91); no +/// per-call heap allocation, no boxed futures. +#[trait_variant::make(MemoryStore: Send)] +pub trait LocalMemoryStore: Sync + 'static { + // --- Lifecycle --- + async fn init(&self) -> MemoryStoreResult<()>; + async fn health_check(&self) -> MemoryStoreResult; + + // --- Embedding model registry --- + async fn registered_model(&self) -> MemoryStoreResult>; + async fn register_model(&self, sig: &ModelSignature) -> MemoryStoreResult<()>; + + // --- CRUD --- + async fn insert(&self, record: &MemoryRecord) -> MemoryStoreResult; + async fn get(&self, id: Uuid) -> MemoryStoreResult>; + async fn update(&self, record: &MemoryRecord) -> MemoryStoreResult<()>; + async fn delete(&self, id: Uuid) -> MemoryStoreResult<()>; + + // --- Search --- + async fn search(&self, query: &SearchQuery) -> MemoryStoreResult>; + async fn fts_search(&self, text: &str, limit: usize) -> MemoryStoreResult>; + async fn vector_search( + &self, + embedding: &[f32], + limit: usize, + ) -> MemoryStoreResult>; + + // --- FSRS Scheduling --- + async fn get_scheduling( + &self, + memory_id: Uuid, + ) -> MemoryStoreResult>; + async fn update_scheduling(&self, state: &SchedulingState) -> MemoryStoreResult<()>; + async fn get_due_memories( + &self, + before: DateTime, + limit: usize, + ) -> MemoryStoreResult>; + + // --- Graph (spreading activation) --- + async fn add_edge(&self, edge: &MemoryEdge) -> MemoryStoreResult<()>; + async fn get_edges( + &self, + node_id: Uuid, + edge_type: Option<&str>, + ) -> MemoryStoreResult>; + async fn remove_edge(&self, source: Uuid, target: Uuid) -> MemoryStoreResult<()>; + async fn get_neighbors( + &self, + node_id: Uuid, + depth: usize, + ) -> MemoryStoreResult>; + + // --- Domains --- + async fn list_domains(&self) -> MemoryStoreResult>; + async fn get_domain(&self, id: &str) -> MemoryStoreResult>; + async fn upsert_domain(&self, domain: &Domain) -> MemoryStoreResult<()>; + async fn delete_domain(&self, id: &str) -> MemoryStoreResult<()>; + async fn classify(&self, embedding: &[f32]) -> MemoryStoreResult>; + + // --- Bulk / Maintenance --- + async fn count(&self) -> MemoryStoreResult; + async fn get_stats(&self) -> MemoryStoreResult; + async fn vacuum(&self) -> MemoryStoreResult<()>; +} +``` + +Notes: + +- The `pub use MemoryStore as LocalMemoryStore;` line on the current + `memory_store.rs:262` is **deleted** entirely. `MemoryStore` is now the + generated trait that `trait_variant::make` emits at the same module path; + `LocalMemoryStore` is the source-of-truth declaration. Both names export + from `storage/mod.rs` already (see lines 10-14 of that file). +- `Sync + 'static` on `LocalMemoryStore` (and no `Send` bound on the trait + itself) is correct: `Send` on the trait is what `trait_variant::make` + inserts when it emits the `MemoryStore` variant. The current trait carries + `Send + Sync + 'static`; the rewrite drops the `Send` bound from the + local variant. `Arc` is `Sync` but not `Send`; + `Arc` (the generated variant) is `Send + Sync`. +- `trait_variant` 0.1 does **not** require any attribute on the impl block. + The attribute lives only on the trait declaration. See the next section. + +The Embedder trait rewrite uses the identical `trait_variant::make` pattern +and is fully specified in `0001c-async-trait-sunset.md`. + +--- + +## Impl Block Migration + +`trait_variant` 0.1 attaches the attribute only to the trait declaration. +The impl side is plain `impl LocalMemoryStore for SqliteMemoryStore`; no +attribute on the impl, no `#[trait_variant::make(MemoryStore: Send)]` on the +impl block. The crate auto-generates the blanket +`impl MemoryStore for T`, so any concrete type +that implements `LocalMemoryStore` automatically also implements +`MemoryStore` provided it is `Send`. + +`SqliteMemoryStore` already is `Send + Sync` (it holds `Mutex` +fields whose `Mutex` is `std::sync::Mutex`, which is `Send + Sync` when its +guarded type is `Send`; `rusqlite::Connection` is `Send`). No new bound is +needed. + +### Before + +`crates/vestige-core/src/storage/sqlite.rs:6274`: + +```rust +#[async_trait::async_trait] +impl crate::storage::memory_store::LocalMemoryStore for SqliteMemoryStore { + async fn init(&self) -> crate::storage::memory_store::MemoryStoreResult<()> { + // Migrations run in `new`; this is a no-op for the SQLite backend. + Ok(()) + } + + // ... ~2400 lines of method bodies, unchanged ... +} +``` + +### After + +`crates/vestige-core/src/storage/sqlite.rs:6274`: + +```rust +impl crate::storage::memory_store::LocalMemoryStore for SqliteMemoryStore { + async fn init(&self) -> crate::storage::memory_store::MemoryStoreResult<()> { + // Migrations run in `new`; this is a no-op for the SQLite backend. + Ok(()) + } + + // ... ~2400 lines of method bodies, unchanged ... +} +``` + +Diff is exactly one removed line (the `#[async_trait::async_trait]` attribute). +Every method body, every `async fn` signature, every `use` statement inside +the impl block stays verbatim. No `Box::pin(async move { ... })`, no manual +`Pin>`, no `'async_trait` lifetime markers; native +async-fn-in-trait does this directly. + +The Embedder impl block rewrite follows the identical "remove one +`#[async_trait::async_trait]` attribute" pattern and is fully specified in +`0001c-async-trait-sunset.md`. + +### Why the impl block does not need an attribute + +`trait_variant::make` generates two things from the source trait: + +1. The source trait itself (`LocalMemoryStore`), with native async fns. +2. A second trait (`MemoryStore`) whose method signatures return + `impl Future + Send` instead of `impl Future`, + plus a blanket impl wiring concrete types through. + +Both are emitted at the macro-call site. `SqliteMemoryStore` only writes one +impl block (against `LocalMemoryStore`); the macro-generated blanket +guarantees `SqliteMemoryStore: MemoryStore` for free. The current `&dyn +MemoryStore` casts (sqlite.rs:8669; tests under tests/phase_1/) keep +type-checking unchanged. + +--- + +## Call Site Audit + +Verified via: + +```bash +grep -rn "dyn MemoryStore\|dyn LocalMemoryStore" --include="*.rs" \ + /home/delandtj/prppl/vestige-phase2/ +grep -rn "Arc\|Arc" --include="*.rs" \ + /home/delandtj/prppl/vestige-phase2/ +grep -rn "use.*MemoryStore;\|use.*LocalMemoryStore;" --include="*.rs" \ + /home/delandtj/prppl/vestige-phase2/ +``` + +### Files that reference the trait object form (`dyn MemoryStore` / `dyn LocalMemoryStore`) + +All test-only or doc-comment-only: + +| File | Line | Use | Required change | +|------|------|-----|-----------------| +| `tests/phase_1/trait_round_trip.rs` | 7-18 | `Arc` in `make_store()` and test bodies | None. `MemoryStore` is the generated Send variant; signature stays. | +| `tests/phase_1/trait_round_trip.rs` | 134 | `Arc` upcast inside a test body | None. | +| `tests/phase_1/send_bound_variant.rs` | 10-97 | `Arc` moved across `tokio::spawn` | None. This test becomes meaningfully correct only after the rewrite (currently it relies on async_trait boxing; after the rewrite it relies on trait_variant's Send variant -- same observable outcome). | +| `tests/phase_1/cognitive_module_isolation.rs` | 11, 33-115 | `Arc` passed into cognitive module-style closures | None. | +| `tests/phase_1/embedding_model_registry.rs` | 10 | `Arc` in `make_store()` | None. | +| `tests/phase_1/domain_column_migration.rs` | 98 | `Arc` cast inside a migration assertion | None. | +| `crates/vestige-core/src/storage/sqlite.rs` | 8666-8675 | `let dyn_s: &dyn MemoryStore = &s;` inside `mod tests` | None. The cast is testing that the dyn-vtable still resolves the trait methods correctly; after the rewrite it resolves through the `MemoryStore` trait that `trait_variant::make` emits at the same path. | +| `crates/vestige-core/src/storage/memory_store.rs` | 188 (doc) | Doc comment mentioning `Arc` | Replaced as part of the doc rewrite (see Trait Declaration section). | + +### Files that hold the concrete type (`Arc` / `Arc`) + +35 files, 116 hits. Every one of them keeps working unchanged because the +concrete `SqliteMemoryStore` type stays exactly as it is. Listed here for +completeness so a reviewer can confirm none of them needs an edit: + +``` +crates/vestige-core/src/storage/mod.rs (alias declaration) +crates/vestige-core/src/storage/sqlite.rs (impl block) +crates/vestige-mcp/src/server.rs (Arc in McpServer) +crates/vestige-mcp/src/cognitive.rs (hydrate(&Storage)) +crates/vestige-mcp/src/autopilot.rs +crates/vestige-mcp/src/protocol/http.rs +crates/vestige-mcp/src/dashboard/mod.rs +crates/vestige-mcp/src/dashboard/state.rs +crates/vestige-mcp/src/dashboard/handlers.rs +crates/vestige-mcp/src/resources/codebase.rs +crates/vestige-mcp/src/resources/memory.rs +crates/vestige-mcp/src/tools/changelog.rs +crates/vestige-mcp/src/tools/codebase_unified.rs +crates/vestige-mcp/src/tools/context.rs +crates/vestige-mcp/src/tools/contradictions.rs +crates/vestige-mcp/src/tools/cross_reference.rs +crates/vestige-mcp/src/tools/dedup.rs +crates/vestige-mcp/src/tools/dream.rs +crates/vestige-mcp/src/tools/explore.rs +crates/vestige-mcp/src/tools/feedback.rs +crates/vestige-mcp/src/tools/graph.rs +crates/vestige-mcp/src/tools/health.rs +crates/vestige-mcp/src/tools/importance.rs +crates/vestige-mcp/src/tools/intention_unified.rs +crates/vestige-mcp/src/tools/maintenance.rs +crates/vestige-mcp/src/tools/memory_states.rs +crates/vestige-mcp/src/tools/memory_unified.rs +crates/vestige-mcp/src/tools/predict.rs +crates/vestige-mcp/src/tools/restore.rs +crates/vestige-mcp/src/tools/review.rs +crates/vestige-mcp/src/tools/search_unified.rs +crates/vestige-mcp/src/tools/session_context.rs +crates/vestige-mcp/src/tools/smart_ingest.rs +crates/vestige-mcp/src/tools/suppress.rs +crates/vestige-mcp/src/tools/tagging.rs +crates/vestige-mcp/src/tools/timeline.rs +``` + +Each holds `Arc` and dispatches to inherent methods on +`SqliteMemoryStore`. None of them goes through a trait vtable. Required +change for every one of them: **none**. + +### Files that `use ...MemoryStore` from production code + +``` +grep -rn "use.*MemoryStore;\|use.*LocalMemoryStore;" --include="*.rs" \ + | grep -v "memory_store.rs\|sqlite.rs\|tests/phase_1" +``` + +returns nothing. Production code does not import the trait by name. + +### Conclusion + +The rewrite is a strictly local change to two source files +(`storage/memory_store.rs` and `storage/sqlite.rs`). Zero production call +sites need edits. The integration tests that consume `Arc` +keep their current form; the rewrite is what gives that signature its +no-box semantics on the storage side. The `Box` surface is +addressed by `0001c-async-trait-sunset.md`. + +--- + +## Commit Sequence + +Two commits, each green on `cargo test -p vestige-core --no-default-features` +and `cargo test -p vestige-core --features embeddings,vector-search`. + +### Commit 1: rewrite MemoryStore / LocalMemoryStore trait declaration + +- Touches: `crates/vestige-core/src/storage/memory_store.rs` only. +- Action: replace lines 183-262 per the "Trait Declaration Rewrite" section + above. Delete the `pub use MemoryStore as LocalMemoryStore;` line. +- Green after: `cargo check -p vestige-core` (the impl block in `sqlite.rs` + still has `#[async_trait::async_trait]` on it, but it still resolves + through the `LocalMemoryStore` trait which is now native-async; the + `async_trait` macro is harmless when applied to a trait that the impl + block targets by path, because the macro rewrites the impl's async fns + into boxed-future fns whose signatures still match the native-async + declarations after trait_variant lowering). If `cargo check` complains + here, fold commit 2 into commit 1. + + **Mitigation if check fails between commits 1 and 2:** combine the two + into a single commit. The split is offered for review convenience; the + build must be green after every commit lands. + +### Commit 2: drop `#[async_trait::async_trait]` from SqliteMemoryStore impl + +- Touches: `crates/vestige-core/src/storage/sqlite.rs` only. +- Action: delete line 6274 (`#[async_trait::async_trait]`). +- Green after: `cargo test -p vestige-core --features embeddings,vector-search`, + including all `trait_*` tests inside `sqlite.rs::tests` (lines 8643-8712) + and the trait-object cast on line 8669. + +### Combined alternative + +If the per-step split feels artificial, commits 1 and 2 can collapse into +a single commit covering both the trait rewrite and the impl-attribute +drop for `MemoryStore`. That is acceptable; the two-commit form is +preferred only because it lets a reviewer bisect trait-rewrite failures +separately from impl-rewrite failures. + +The Embedder / fastembed commits and the `async-trait` Cargo dependency +removal live in `0001c-async-trait-sunset.md`. + +--- + +## Verification + +Every command runs from the repo root unless noted otherwise. + +```bash +# 1. Vestige-core, default features (embeddings + vector-search). +cargo test -p vestige-core --features embeddings,vector-search + +# 2. Vestige-core, minimal features (no embeddings, no vector-search). +cargo test -p vestige-core --no-default-features + +# 3. Workspace build, release mode (catches any feature-gated regression +# in the vestige-mcp tools tree). +cargo build --workspace --release + +# 4. Whole-workspace test (vestige-mcp 406 tests + vestige-core 352 tests +# per the CLAUDE.md baseline). +cargo test --workspace + +# 5. Phase 1 integration tests (these are the trait-shape contract). +cargo test --test trait_round_trip --features embeddings,vector-search +cargo test --test send_bound_variant --features embeddings,vector-search +cargo test --test cognitive_module_isolation --features embeddings,vector-search +cargo test --test embedding_model_registry --features embeddings,vector-search +cargo test --test domain_column_migration --features embeddings,vector-search + +# 6. Clippy gate, deny warnings (matches Phase 1 PR policy of zero warnings). +cargo clippy --workspace --all-targets --features embeddings,vector-search -- -D warnings + +# 7. Storage-side dependency hygiene check (must return zero hits). +# Scoped to the storage module only -- the embedder module still uses +# async_trait until 0001c lands. +grep -rn "async_trait\|async-trait" crates/vestige-core/src/storage/ + +# 8. Confirm trait_variant attribute is in place on the storage trait +# (must return exactly one hit in memory_store.rs). +grep -rn "trait_variant::make" crates/vestige-core/src/storage/ +``` + +Expected outcomes: + +- Command 1: 352 tests pass (matches baseline). +- Command 2: smaller test count, all pass. +- Command 3: workspace compiles in release mode. +- Command 4: 758 total tests pass (matches CLAUDE.md baseline). +- Command 5: each phase_1 integration test binary runs green. The + `send_bound_variant::arc_dyn_memory_store_moves_across_tokio_tasks` test + is the canary; if `MemoryStore` lost its Send-bound future variant, this + fails to compile with "future cannot be sent between threads safely". +- Command 6: zero clippy warnings. The rewrite must not introduce a new + `clippy::needless_lifetimes` or `clippy::async_yields_async`. +- Command 7: empty output. async_trait is gone from the storage module. + The embedder module still contains async_trait; that is removed by + `0001c-async-trait-sunset.md`. +- Command 8: one hit, in `memory_store.rs`. + +--- + +## Acceptance Criteria + +A reviewer should be able to check every box: + +- [ ] `crates/vestige-core/src/storage/memory_store.rs` declares the trait + with `#[trait_variant::make(MemoryStore: Send)] pub trait + LocalMemoryStore: Sync + 'static`, no `async_trait` attribute, no + `Send` bound on `LocalMemoryStore` itself. +- [ ] `crates/vestige-core/src/storage/memory_store.rs` no longer contains + `pub use MemoryStore as LocalMemoryStore;`. +- [ ] `crates/vestige-core/src/storage/sqlite.rs:6274` is plain + `impl crate::storage::memory_store::LocalMemoryStore for + SqliteMemoryStore` -- no attribute on the impl block. +- [ ] `grep -rn "async_trait\|async-trait" crates/vestige-core/src/storage/` + returns zero hits. +- [ ] `grep -rn "trait_variant::make" crates/vestige-core/src/storage/` + returns exactly one hit (the storage trait in `memory_store.rs`). +- [ ] All 758 workspace tests pass (`cargo test --workspace`). +- [ ] Phase 1 integration tests pass with the trait-object surface + (`Arc`) intact. +- [ ] `cargo clippy --workspace --all-targets --features + embeddings,vector-search -- -D warnings` is clean. +- [ ] No production source file under `crates/vestige-mcp/` or + `crates/vestige-core/src/{neuroscience,advanced,consolidation,codebase, + memory,embeddings,embedder}/` was modified by this sub-plan. +- [ ] `Arc` still type-checks at every existing call site (verified + by the workspace test pass). +- [ ] Doc comments on the storage trait declaration describe + `trait_variant`, not `async_trait`. + +--- + +## Risks and Mitigations + +- **`trait_variant` 0.1 macro emits unexpected diagnostics on MSRV 1.91.** + Mitigation: the master Phase 1 plan already prescribed this exact pattern + (`#[trait_variant::make(MemoryStore: Send)] pub trait LocalMemoryStore: + Sync + 'static`, see plan `0001-...` line 274-275); the crate has been in + `vestige-core/Cargo.toml` since Phase 1 landed. If a diagnostic appears, + pin to the exact known-good version with `trait-variant = "=0.1.2"` and + open an upstream issue. +- **Native async-fn-in-trait makes the trait no longer dyn-compatible.** + Mitigation: `trait_variant::make` is specifically the workaround for this + -- it emits both the source trait (for static dispatch) and a Send-bound + variant whose returned futures use `Pin>` only at + the dyn boundary. `Arc` keeps working because the + generated `MemoryStore` trait is dyn-compatible by construction. Verified + by the existing `send_bound_variant::*` tests, which intentionally move + `Arc` across `tokio::spawn` from inside a + `multi_thread` runtime. +- **A cognitive module silently relied on the boxed-future return type.** + Mitigation: grep verified no cognitive module imports `MemoryStore` / + `LocalMemoryStore` or holds an `Arc` form; all of them use the + concrete `Storage` alias. There is no Send-ness expectation downstream to + break. +- **Future bodies inside the SQLite impl capture non-Send locals.** + Mitigation: every method body in `sqlite.rs:6274..` runs synchronous + rusqlite calls inside the same `async fn` frame; no `.await` points + exist inside the bodies that we ship today. The `Send` bound on the + generated `MemoryStore` variant is therefore satisfied automatically. + If a future change adds `.await` inside an impl method, the new + trait_variant surface will surface that as a compile error at the call + site, which is the correct outcome. +- **`async-trait` crate is left declared after this sub-plan.** + This is intentional: the embedder impl still depends on it. The + `0001c-async-trait-sunset.md` sub-plan removes the crate after the + embedder side is rewritten. Grep on the whole workspace returns only + the storage and embedder files; no downstream crate pulls `async-trait`. + +--- + +## Out-of-Band Notes + +- This sub-plan amends `feat/storage-trait-phase1` (tip 790c0c8). The + branch has not been opened upstream yet, so amending in place is safe; + no force-push to a public PR. +- The companion sub-plan `0001b-sqlite-split.md` lands after this one on + the same branch. The trait-rewrite landing first is intentional: the + SQLite split moves the impl block into `storage/sqlite/trait_impl.rs`, + and it is cleaner to move a small attribute-free impl than a + macro-decorated one. +- The companion sub-plan `0001c-async-trait-sunset.md` lands after this + one (order with `0001b` is independent) and finishes the + async_trait -> trait_variant transition for the Embedder trait, then + removes the `async-trait` crate dependency. +- After the Phase 1 amendment sub-plans (`0001a`, `0001b`, `0001c`) land, + the branch is reviewed and merged before Phase 2 sub-plans (`0002a-` + through `0002i-`) begin implementation. diff --git a/docs/plans/0001b-sqlite-split.md b/docs/plans/0001b-sqlite-split.md new file mode 100644 index 0000000..ce2590d --- /dev/null +++ b/docs/plans/0001b-sqlite-split.md @@ -0,0 +1,732 @@ +# Sub-Plan 0001b: Split sqlite.rs into a sqlite/ directory + +**Status**: Draft +**Branch**: `feat/storage-trait-phase1` (Phase 1 amendment, PR A) +**Depends on**: `0001a-trait-rewrite.md` (must land first; it carries the +`trait_variant`-generated trait declaration that `trait_impl.rs` matches) +**Related**: `docs/adr/0002-phase-2-execution.md` (D3, D6) + +--- + +## Context + +`crates/vestige-core/src/storage/sqlite.rs` is the single SQLite backend file +that Phase 1 inherited from pre-trait Vestige and then appended the +`LocalMemoryStore` trait impl block to. The file is 8713 lines as of +commit 790c0c8 on `feat/storage-trait-phase1`. ADR 0002 D3 decides to split +it into a `sqlite/` directory before Phase 2 lands `postgres/` as a peer. +Reasoning, in one paragraph: + +The Postgres backend is going in as a directory of seven small files +(`postgres/{mod,pool,migrations,registry,search,migrate_cli,reembed}.rs`). +If SQLite stays as one 8K-line file alongside that, the repo says "backends +look like one big file or seven small ones, pick a side", which forces +every future maintainer to re-litigate the layout. Splitting now -- as +**pure code motion**, no public-API change, no behavioural change, no +migration -- lets both backends look the same, keeps each surface mappable +in a single editor tab, and shrinks the diffs Phase 2 has to review. +This sub-plan is sized as one focused implementation session. + +The split is **private** to `storage/sqlite/`. Cognitive modules continue +to `use crate::storage::SqliteMemoryStore`; the existing re-exports in +`crates/vestige-core/src/storage/mod.rs` keep working without touching +any caller. Tests stay green commit-by-commit. + +This sub-plan depends on `0001a-trait-rewrite.md` landing first because +`sqlite/trait_impl.rs` is the file that picks up the new trait_variant +attribute. Doing the split first would force a second rewrite of +`trait_impl.rs` when the trait rewrite arrives. Order matters; this is +the cheap-to-respect ordering. + +--- + +## Target Layout + +Final directory after this sub-plan: + +``` +crates/vestige-core/src/storage/sqlite/ + mod.rs -- module root: SqliteMemoryStore struct, new(), + reader/writer locks, error types, shared helpers, + portable-sync-related types, record types + crud.rs -- ingest/smart_ingest/get/update/delete/purge/search-by-id + search.rs -- fts, semantic, hybrid, time-based queries + scheduling.rs -- FSRS state, decay, consolidation, review, promote/demote, + suppression, gc, retention, waking tags + graph.rs -- memory_connections (edges), subgraph, neighbors + domain.rs -- domains/domain_scores column readers, classify stub + (Phase 4 will expand this file) + registry.rs -- embedding_model table, enforce_model, register_model body + portable_sync.rs -- portable export/import/sync + merge helpers + trait_impl.rs -- impl LocalMemoryStore for SqliteMemoryStore +``` + +`storage/mod.rs` is unchanged in spirit: it still does `mod sqlite;` and +`pub use sqlite::{...};` -- the only difference is that `sqlite` is now a +directory module instead of a leaf file. The re-export list does not +change. + +--- + +## Current File Map (line numbers from commit 790c0c8) + +The current `sqlite.rs` is structurally: + +| Region | Lines | Contents | +|--------|-------|----------| +| Header | 1-43 | Imports, feature-gated imports | +| Error types | 45-89 | `StorageError`, `Result`, `SmartIngestResult`, `MergeWrite` | +| Portable sync types | 97-211 | `PortableSyncBackend` trait, `FilePortableSyncBackend` struct, `PortableSyncReport`, `PurgeReport` | +| Constants | 233-273 | `PORTABLE_TABLES`, `PORTABLE_USER_DATA_TABLES`, `PortableMergeState`, env constants | +| Struct decl | 287-301 | `SqliteMemoryStore` struct fields | +| Impl block 1 | 303-3740 | Constructor + bulk of native API | +| Record structs | 3747-3866 | `IntentionRecord`, `InsightRecord`, `ConnectionRecord`, `MemoryStateRecord`, `StateTransitionRecord`, `ConsolidationHistoryRecord`, `DreamHistoryRecord`, `Default for InsightRecord` | +| Impl block 2 | 3868-6133 | Intentions / Insights / Connections / States / History / Backup / Portable / GC / Subgraph | +| Impl block 3 | 6139-6272 | Trait-helper methods (`node_to_record`, `read_domain_columns`, `enforce_model`) | +| Trait impl | 6274-7110 | `impl LocalMemoryStore for SqliteMemoryStore` | +| Tests | 7112-8713 | `#[cfg(test)] mod tests`: native API tests + trait round-trip tests | + +--- + +## Mapping Table + +Every public method, every private helper, every struct, every test module +in the current file -- with the destination file in the new layout. Line +ranges cite the current `sqlite.rs` (commit 790c0c8 on +`feat/storage-trait-phase1`, viewed through the +`/home/delandtj/prppl/vestige-phase2` worktree). + +### Header and shared types (-> `sqlite/mod.rs`) + +| Item | Lines | Destination | Notes | +|------|-------|-------------|-------| +| Module-level `use` imports | 1-43 | `sqlite/mod.rs` | Trimmed per-file in destination; what does not fit in `mod.rs` moves with its consumers | +| `StorageError` enum + `Result` alias | 49-71 | `sqlite/mod.rs` | Re-exported through `pub use` chain; called from every sub-module | +| `SmartIngestResult` struct | 73-89 | `sqlite/mod.rs` | Returned by `crud::smart_ingest`; defined here because other code depends on the type | +| `MergeWrite` enum | 91-95 | `sqlite/portable_sync.rs` | Only used by merge helpers | +| `PortableSyncBackend` trait | 97-109 | `sqlite/portable_sync.rs` | Public trait; re-exported through `mod.rs` | +| `FilePortableSyncBackend` struct + `impl` | 111-194 | `sqlite/portable_sync.rs` | | +| `PortableSyncReport` struct | 196-211 | `sqlite/portable_sync.rs` | | +| `PurgeReport` struct | 213-231 | `sqlite/crud.rs` | Returned by `purge_node` | +| `PORTABLE_TABLES` constant | 237-254 | `sqlite/portable_sync.rs` | | +| `PORTABLE_USER_DATA_TABLES` constant | 256-272 | `sqlite/portable_sync.rs` | | +| `PortableMergeState` struct | 274-277 | `sqlite/portable_sync.rs` | | +| `DATA_DIR_ENV` constant | 279 | `sqlite/mod.rs` | Read by constructor | +| `DATABASE_FILE` constant | 280 | `sqlite/mod.rs` | Read by constructor | +| `SqliteMemoryStore` struct decl | 282-301 | `sqlite/mod.rs` | All fields stay public-to-crate within the directory | + +### Constructor and config (-> `sqlite/mod.rs`) + +These are foundational; they live in `mod.rs` because every sub-module +calls them or operates on the struct they build. + +| Item | Lines | Destination | Notes | +|------|-------|-------------|-------| +| `fn data_dir_from_env` | 304-313 | `sqlite/mod.rs` | private helper | +| `fn expand_tilde` | 314-332 | `sqlite/mod.rs` | private helper | +| `fn prepare_data_dir` | 333-346 | `sqlite/mod.rs` | private helper | +| `pub fn db_path_for_data_dir` | 347-355 | `sqlite/mod.rs` | | +| `pub fn default_db_path` | 356-368 | `sqlite/mod.rs` | | +| `fn configure_connection` | 369-396 | `sqlite/mod.rs` | | +| `pub fn new` | 397-457 | `sqlite/mod.rs` | The constructor | +| `pub fn db_path` | 458-462 | `sqlite/mod.rs` | | +| `pub fn data_dir` | 463-467 | `sqlite/mod.rs` | | +| `pub fn sidecar_dir` | 468-473 | `sqlite/mod.rs` | | +| `fn load_embeddings_into_index` | 474-552 | `sqlite/mod.rs` | Called by `new`; touches vector index | + +### CRUD: ingest, get, update, delete, purge (-> `sqlite/crud.rs`) + +| Item | Lines | Destination | Notes | +|------|-------|-------------|-------| +| `pub fn ingest` | 553-643 | `sqlite/crud.rs` | | +| `pub fn smart_ingest` | 644-864 | `sqlite/crud.rs` | Calls vector search via `self.semantic_search`; cross-module call resolved by impl block being on the same struct | +| `pub fn get_node_embedding` (vector-search) | 865-887 | `sqlite/crud.rs` | embedding read for one node | +| `pub fn get_all_embeddings` (vector-search) | 888-914 | `sqlite/crud.rs` | | +| `pub fn get_node_embedding` (no vector-search stub) | 915-919 | `sqlite/crud.rs` | feature-gated alternative | +| `pub fn update_node_content` | 920-951 | `sqlite/crud.rs` | | +| `fn generate_embedding_for_node` | 952-999 | `sqlite/crud.rs` | private helper; only called by ingest and update_node_content | +| `pub fn get_node` | 1000-1011 | `sqlite/crud.rs` | | +| `fn parse_timestamp` | 1012-1027 | `sqlite/mod.rs` | **Shared helper**: row_to_node uses it, intention/insight rows also parse timestamps. Bump to `pub(super) fn` | +| `fn row_to_node` | 1028-1119 | `sqlite/mod.rs` | **Shared helper**: crud reads single nodes; search.rs builds node lists from rows; scheduling.rs returns nodes for review queue. Bump to `pub(super) fn`. Static method (no `&self`) so a free function in `mod.rs` is fine | +| `pub fn delete_node` | 1842-1869 | `sqlite/crud.rs` | | +| `pub fn purge_node` | 1870-1987 | `sqlite/crud.rs` | | +| `fn node_exists` | 1988-1996 | `sqlite/crud.rs` | static helper, called only by purge | +| `fn record_sync_tombstone` | 1997-2014 | `sqlite/crud.rs` | static helper, called by delete and purge | +| `pub fn get_all_nodes` | 2268-2291 | `sqlite/crud.rs` | bulk read | +| `pub fn get_nodes_by_type_and_tag` | 2292-2342 | `sqlite/crud.rs` | bulk read | + +### Search: fts, semantic, hybrid, temporal (-> `sqlite/search.rs`) + +| Item | Lines | Destination | Notes | +|------|-------|-------------|-------| +| `pub fn recall` | 1120-1147 | `sqlite/search.rs` | top-level recall path | +| `fn keyword_search` | 1148-1180 | `sqlite/search.rs` | private | +| `pub fn search` | 2015-2043 | `sqlite/search.rs` | | +| `pub fn search_terms` | 2044-2075 | `sqlite/search.rs` | | +| `pub fn concrete_search_filtered` | 2076-2172 | `sqlite/search.rs` | | +| `fn upsert_concrete_result` | 2173-2197 | `sqlite/search.rs` | static helper | +| `fn normalize_literal_query` | 2198-2210 | `sqlite/search.rs` | static helper | +| `fn escape_like` | 2211-2224 | `sqlite/search.rs` | static helper | +| `fn literal_match_score` | 2225-2248 | `sqlite/search.rs` | static helper | +| `fn node_matches_type_filters` | 2249-2267 | `sqlite/search.rs` | static helper | +| `pub fn is_embedding_ready` (both feature variants) | 2343-2354 | `sqlite/search.rs` | both versions move together | +| `pub fn init_embeddings` (both feature variants) | 2355-2367 | `sqlite/search.rs` | both versions move together | +| `fn get_query_embedding` | 2368-2400 | `sqlite/search.rs` | private; uses `query_cache` field | +| `pub fn semantic_search` | 2401-2434 | `sqlite/search.rs` | | +| `pub fn hybrid_search` (feature on) | 2435-2452 | `sqlite/search.rs` | | +| `pub fn hybrid_search_filtered` (feature on) | 2453-2581 | `sqlite/search.rs` | | +| `pub fn hybrid_search` (feature off) | 2582-2593 | `sqlite/search.rs` | feature-gated stub | +| `pub fn hybrid_search_filtered` (feature off) | 2594-2635 | `sqlite/search.rs` | feature-gated stub | +| `fn keyword_search_with_scores` | 2636-2726 | `sqlite/search.rs` | | +| `fn semantic_search_raw` | 2727-2765 | `sqlite/search.rs` | | +| `pub fn generate_embeddings` | 2766-2819 | `sqlite/search.rs` | populates embeddings post hoc | +| `fn embedding_regeneration_candidates` | 2820-2891 | `sqlite/search.rs` | called by generate_embeddings | +| `pub fn query_at_time` | 2892-2933 | `sqlite/search.rs` | temporal query | +| `pub fn query_time_range` | 2934-3005 | `sqlite/search.rs` | temporal query | +| `fn embedding_model_matches_active` (associated fn) | 5652-5671 | `sqlite/search.rs` | static helper for hybrid_search; promoted to `pub(super)` (test references it) | +| `fn embedding_model_supports_matryoshka` | 5672-5677 | `sqlite/search.rs` | static helper | +| `fn embedding_vector_for_active_model` | 5678-5697 | `sqlite/search.rs` | static helper | +| `fn active_embedding_model_like_pattern` | 5698-5713 | `sqlite/search.rs` | static helper | + +### Scheduling: FSRS, decay, consolidation, review, promote/demote, suppression, gc, retention (-> `sqlite/scheduling.rs`) + +This is the busiest destination file. The grouping rule is: anything that +touches FSRS scheduling fields (`stability`, `difficulty`, `retrievability`, +`reps`, `lapses`, `retention_strength`, `retrieval_strength`) or the +review/decay/consolidation/gc lifecycle lives here. + +| Item | Lines | Destination | Notes | +|------|-------|-------------|-------| +| `pub fn mark_reviewed` | 1181-1275 | `sqlite/scheduling.rs` | FSRS state mutation | +| `pub fn strengthen_on_access` | 1276-1344 | `sqlite/scheduling.rs` | | +| `pub fn strengthen_batch_on_access` | 1345-1357 | `sqlite/scheduling.rs` | | +| `pub fn mark_memory_useful` | 1358-1377 | `sqlite/scheduling.rs` | | +| `fn log_access` | 1378-1393 | `sqlite/scheduling.rs` | private | +| `pub fn promote_memory` | 1394-1425 | `sqlite/scheduling.rs` | | +| `pub fn demote_memory` | 1426-1472 | `sqlite/scheduling.rs` | | +| `pub fn suppress_memory` | 1473-1504 | `sqlite/scheduling.rs` | active forgetting | +| `pub fn reverse_suppression` | 1505-1552 | `sqlite/scheduling.rs` | | +| `pub fn count_suppressed` | 1553-1567 | `sqlite/scheduling.rs` | | +| `pub fn get_recently_suppressed` | 1568-1594 | `sqlite/scheduling.rs` | | +| `pub fn apply_rac1_cascade` | 1595-1641 | `sqlite/scheduling.rs` | active forgetting cascade | +| `pub fn run_rac1_cascade_sweep` | 1642-1657 | `sqlite/scheduling.rs` | | +| `pub fn get_review_queue` | 1658-1681 | `sqlite/scheduling.rs` | | +| `pub fn preview_review` | 1682-1712 | `sqlite/scheduling.rs` | | +| `pub fn get_stats` | 1713-1841 | `sqlite/scheduling.rs` | reports retention/lapses/review counts; lives here for symmetry with the FSRS reporters next door | +| `pub fn apply_decay` | 3006-3095 | `sqlite/scheduling.rs` | core decay loop | +| `fn get_fsrs_w20` | 3096-3119 | `sqlite/scheduling.rs` | | +| `pub fn run_consolidation` | 3120-3407 | `sqlite/scheduling.rs` | | +| `fn auto_dedup_consolidation` | 3408-3538 | `sqlite/scheduling.rs` | called by run_consolidation | +| `fn compute_act_r_activations` | 3539-3605 | `sqlite/scheduling.rs` | called by run_consolidation | +| `fn prune_access_log` | 3606-3620 | `sqlite/scheduling.rs` | called by run_consolidation | +| `fn optimize_w20_if_ready` | 3621-3720 | `sqlite/scheduling.rs` | called by run_consolidation | +| `fn generate_missing_embeddings` | 3721-3740 | `sqlite/scheduling.rs` | called by run_consolidation | +| `pub fn get_state_transitions` | 5714-5748 | `sqlite/scheduling.rs` | audit trail tied to scheduling state | +| `pub fn get_avg_retention` | 5780-5792 | `sqlite/scheduling.rs` | | +| `pub fn get_retention_distribution` | 5794-5825 | `sqlite/scheduling.rs` | | +| `pub fn get_retention_trend` | 5826-5858 | `sqlite/scheduling.rs` | | +| `pub fn save_retention_snapshot` | 5859-5878 | `sqlite/scheduling.rs` | | +| `pub fn count_memories_below_retention` | 5879-5892 | `sqlite/scheduling.rs` | | +| `pub fn gc_below_retention` | 5893-5936 | `sqlite/scheduling.rs` | | +| `pub fn auto_promote_frequent_access` | 5937-5985 | `sqlite/scheduling.rs` | | +| `pub fn set_waking_tag` | 5986-5998 | `sqlite/scheduling.rs` | waking SWR tagging | +| `pub fn clear_waking_tags` | 5999-6011 | `sqlite/scheduling.rs` | | +| `pub fn get_waking_tagged_memories` | 6012-6028 | `sqlite/scheduling.rs` | | +| `pub fn get_recent_state_transitions` | 6105-6132 | `sqlite/scheduling.rs` | | + +### Graph: edges (memory_connections), neighbors, subgraph (-> `sqlite/graph.rs`) + +| Item | Lines | Destination | Notes | +|------|-------|-------------|-------| +| `pub fn save_connection` | 4180-4202 | `sqlite/graph.rs` | | +| `pub fn get_connections_for_memory` | 4203-4220 | `sqlite/graph.rs` | | +| `pub fn get_all_connections` | 4221-4236 | `sqlite/graph.rs` | | +| `pub fn strengthen_connection` | 4237-4259 | `sqlite/graph.rs` | | +| `pub fn apply_connection_decay` | 4260-4272 | `sqlite/graph.rs` | | +| `pub fn prune_weak_connections` | 4273-4284 | `sqlite/graph.rs` | | +| `fn row_to_connection` | 4285-4305 | `sqlite/graph.rs` | private | +| `pub fn get_most_connected_memory` | 6029-6046 | `sqlite/graph.rs` | | +| `pub fn get_memory_subgraph` | 6048-6103 | `sqlite/graph.rs` | calls `get_connections_for_memory`, `get_node`, `get_all_connections` -- all resolvable through `self` | + +### Domain (-> `sqlite/domain.rs`) + +Phase 1 keeps domain logic to JSON-column reads + classify stub. Phase 4 +expands this file. Keeping the file in the split so Phase 4 has an +obvious place to add to. + +| Item | Lines | Destination | Notes | +|------|-------|-------------|-------| +| `fn read_domain_columns` | 6167-6196 | `sqlite/domain.rs` | private helper used by trait `get`. Bump to `pub(super)` | + +The trait methods `list_domains` / `get_domain` / `upsert_domain` / +`delete_domain` / `classify` live in `sqlite/trait_impl.rs`; they +delegate to thin helpers that, in Phase 1, are essentially noops or +JSON reads. Phase 4 will move the substance of those methods into +`sqlite/domain.rs` as real functions. + +### Registry: embedding_model table (-> `sqlite/registry.rs`) + +| Item | Lines | Destination | Notes | +|------|-------|-------------|-------| +| `fn enforce_model` | 6203-6272 | `sqlite/registry.rs` | private helper used by trait `insert` and `update`. Bump to `pub(super)` | + +The trait methods `registered_model` and `register_model` themselves +live in `sqlite/trait_impl.rs`. Phase 2's `postgres/registry.rs` will +mirror this layout. + +### Intentions, Insights, Memory States, Consolidation History, Dream History, Backup (-> `sqlite/mod.rs`) + +These were tacked onto `SqliteMemoryStore` over time as the cognitive +modules needed somewhere to persist their state. They are not part of the +trait surface, they are not naturally grouped with crud/search/scheduling, +and they are each fairly small and self-contained. They live in `mod.rs` +under labelled sections (one big impl block can carry them) rather than +inventing extra files like `intentions.rs` and `insights.rs`. Postgres +will mirror this once Phase 5 picks up the work; for now they have no +peer. + +Rationale: every one of these methods writes to a single table, the +bodies are short, and grouping them next to the constructor preserves +"open `mod.rs` to see the whole struct" as the navigation default. + +| Item | Lines | Destination | Notes | +|------|-------|-------------|-------| +| `IntentionRecord` struct | 3747-3766 | `sqlite/mod.rs` | re-exported through `storage/mod.rs` | +| `InsightRecord` struct + `Default` | 3767-3797 | `sqlite/mod.rs` | re-exported | +| `ConnectionRecord` struct | 3799-3809 | `sqlite/mod.rs` | re-exported; consumed by `graph.rs` | +| `MemoryStateRecord` struct | 3811-3821 | `sqlite/mod.rs` | | +| `StateTransitionRecord` struct | 3823-3833 | `sqlite/mod.rs` | re-exported | +| `ConsolidationHistoryRecord` struct | 3835-3846 | `sqlite/mod.rs` | | +| `DreamHistoryRecord` struct | 3848-3866 | `sqlite/mod.rs` | re-exported | +| `pub fn save_intention` etc. (intention block) | 3874-4058 | `sqlite/mod.rs` | one impl block, in-section labelled | +| `fn row_to_intention` | 4023-4058 | `sqlite/mod.rs` | private | +| insights block (`save_insight`, `get_insights`, etc.) | 4065-4174 | `sqlite/mod.rs` | | +| `fn row_to_insight` | 4153-4173 | `sqlite/mod.rs` | private | +| memory-state block | 4306-4459 | `sqlite/mod.rs` | | +| `fn row_to_memory_state` | 4431-4459 | `sqlite/mod.rs` | private | +| consolidation-history block | 4465-4540 | `sqlite/mod.rs` | | +| dream-history block | 4546-4638 | `sqlite/mod.rs` | | +| `pub fn count_memories_since` | 4639-4651 | `sqlite/mod.rs` | | +| `fn scan_last_backup_timestamp` | 4652-4682 | `sqlite/mod.rs` | | +| `pub fn last_backup_timestamp` | 4683-4688 | `sqlite/mod.rs` | | +| `pub fn get_last_backup_timestamp` (associated) | 4689-4696 | `sqlite/mod.rs` | | +| `pub fn backup_to` | 5749-5774 | `sqlite/mod.rs` | sqlite VACUUM INTO; called by backup tool | + +### Portable export/import/sync (-> `sqlite/portable_sync.rs`) + +This is the second-largest destination after `scheduling.rs` and the most +self-contained. + +| Item | Lines | Destination | Notes | +|------|-------|-------------|-------| +| `pub fn export_portable_archive` | 4699-4755 | `sqlite/portable_sync.rs` | | +| `pub fn export_portable_archive_to_path` | 4756-4806 | `sqlite/portable_sync.rs` | | +| `pub fn import_portable_archive` | 4807-4978 | `sqlite/portable_sync.rs` | | +| `pub fn import_portable_archive_from_path` | 4979-4996 | `sqlite/portable_sync.rs` | | +| `pub fn sync_portable_archive` (generic over backend) | 4997-5025 | `sqlite/portable_sync.rs` | | +| `pub fn sync_portable_archive_file` | 5026-5030 | `sqlite/portable_sync.rs` | | +| `fn merge_portable_table` | 5031-5073 | `sqlite/portable_sync.rs` | | +| `fn merge_knowledge_nodes` | 5074-5126 | `sqlite/portable_sync.rs` | | +| `fn merge_sync_tombstones` | 5127-5204 | `sqlite/portable_sync.rs` | | +| `fn merge_deletion_tombstones` | 5205-5245 | `sqlite/portable_sync.rs` | | +| `fn merge_keyed_table` | 5246-5281 | `sqlite/portable_sync.rs` | | +| `fn row_references_locally_newer_node` | 5282-5302 | `sqlite/portable_sync.rs` | | +| `fn merge_append_only_table` | 5303-5338 | `sqlite/portable_sync.rs` | | +| `fn parent_rows_exist` | 5339-5370 | `sqlite/portable_sync.rs` | | +| `fn insert_or_replace_row` | 5371-5386 | `sqlite/portable_sync.rs` | | +| `fn merge_key_columns` | 5387-5398 | `sqlite/portable_sync.rs` | | +| `fn upsert_row_with_columns` | 5399-5446 | `sqlite/portable_sync.rs` | | +| `fn insert_row_with_columns` | 5447-5469 | `sqlite/portable_sync.rs` | | +| `fn merge_row_exists` | 5470-5487 | `sqlite/portable_sync.rs` | | +| `fn row_exists_by_values` | 5488-5507 | `sqlite/portable_sync.rs` | | +| `fn row_values_for_columns` | 5508-5528 | `sqlite/portable_sync.rs` | | +| `fn portable_value` | 5529-5540 | `sqlite/portable_sync.rs` | | +| `fn portable_text` | 5541-5551 | `sqlite/portable_sync.rs` | | +| `fn portable_timestamp` | 5552-5559 | `sqlite/portable_sync.rs` | | +| `fn parse_rfc3339_opt` | 5560-5565 | `sqlite/portable_sync.rs` | | +| `fn tombstone_timestamp` | 5566-5580 | `sqlite/portable_sync.rs` | | +| `fn current_schema_version` | 5581-5589 | `sqlite/portable_sync.rs` | static helper | +| `fn ensure_portable_import_target_empty` | 5590-5604 | `sqlite/portable_sync.rs` | static helper | +| `fn table_exists` | 5605-5613 | `sqlite/portable_sync.rs` | static helper | +| `fn table_row_count` | 5614-5618 | `sqlite/portable_sync.rs` | static helper | +| `fn table_columns` | 5619-5630 | `sqlite/portable_sync.rs` | static helper | +| `fn portable_value_from_ref` | 5631-5646 | `sqlite/portable_sync.rs` | static helper | +| `fn quote_ident` | 5647-5651 | `sqlite/portable_sync.rs` | static helper | + +### Trait helpers and trait impl (-> `sqlite/trait_impl.rs`) + +| Item | Lines | Destination | Notes | +|------|-------|-------------|-------| +| `fn node_to_record` | 6142-6164 | `sqlite/trait_impl.rs` | associated fn used only by trait body; co-locate | +| `impl LocalMemoryStore for SqliteMemoryStore` block | 6274-7110 | `sqlite/trait_impl.rs` | full trait impl; attribute changes from `#[async_trait::async_trait]` to whatever 0001a settles on (`#[trait_variant::make(...)]` is on the trait declaration; the impl block carries no attribute under trait_variant) | + +### Tests + +The current `#[cfg(test)] mod tests` block at lines 7112-8713 contains +**two** distinct test families: + +1. **Native API tests** (7120-8198): unit tests against the legacy + `pub fn` surface (`test_ingest_and_get`, `test_search`, `test_review`, + `test_delete`, `test_dream_history_save_and_get_last`, + `test_portable_archive_exact_round_trip`, `test_keyword_search_*`, + `test_concrete_search_*`, `test_purge_*`, etc.). +2. **Trait round-trip tests** (8200-8712, after the + `// ===== Phase 1: LocalMemoryStore trait round-trip tests =====` + banner): `trait_init_is_idempotent`, `trait_register_model_*`, + `trait_insert_*`, `trait_get_*`, `trait_update_*`, `trait_delete_*`, + `trait_fts_search_*`, `trait_hybrid_search_*`, + `trait_scheduling_*`, `trait_add_edge_*`, `trait_get_edges_*`, + `trait_remove_edge_*`, `trait_get_neighbors_*`, `trait_list_domains_*`, + `trait_upsert_*`, `trait_classify_*`, `trait_count_*`, + `trait_get_stats_*`, `trait_vacuum_*`, + `trait_insert_refuses_dimension_mismatch`. + +See the Test Relocation section below for the resolution. + +--- + +## Visibility Changes + +The split moves items into sibling files inside one module. Helpers that +were `fn ...` (i.e. crate-private but file-private under the current +layout, since the file *is* the module) need their visibility lifted +just enough that sibling files can call them. The principle is: smallest +bump that makes the call site compile. + +`pub(super)` is sufficient for everything below; nothing needs +`pub(crate)`. The trait `LocalMemoryStore` exposure does not change -- +sub-modules call `self.method(...)` on `SqliteMemoryStore`, which +resolves through the impl blocks defined in their own files; visibility +is automatic at impl-block scope. + +Items that need a visibility bump (currently private fn, become +`pub(super) fn`): + +- `parse_timestamp` (1012): called by `row_to_node` and by intention / + insight row mappers. +- `row_to_node` (1028): called by `crud.rs`, `search.rs`, + `scheduling.rs`. Static associated fn. +- `read_domain_columns` (6167): called by `trait_impl.rs`. +- `enforce_model` (6203): called by `trait_impl.rs`. +- `embedding_model_matches_active` (5652): currently called by + `hybrid_search_filtered`; tests also reference it. Has to remain + `pub(super) fn` and be `pub` only if the existing test names reach it + through a re-export. (See Test Relocation.) +- `embedding_model_supports_matryoshka` (5672): private; only callers in + `search.rs` after the move; stays `fn` (no bump needed). +- `embedding_vector_for_active_model` (5678): same as the matches + function -- a test references it. Bump to `pub(super)`. +- `active_embedding_model_like_pattern` (5698): private; only used by + search; stays `fn`. +- `generate_embedding_for_node` (952): currently called by `ingest` and + `update_node_content`. Both move to `crud.rs`; stays `fn`. +- `get_query_embedding` (2368): only used inside `search.rs`; stays `fn`. +- `keyword_search_with_scores` (2636): only used inside `search.rs`; + stays `fn`. +- `semantic_search_raw` (2727): only used inside `search.rs`; stays `fn`. +- `embedding_regeneration_candidates` (2820): used by + `generate_embeddings`; both move to `search.rs`; stays `fn`. The + existing test (line 7167) references it through `storage.method()`, + which will continue to work because the test file can move with it. +- `log_access` (1378): private to `scheduling.rs`; stays `fn`. +- All the `auto_dedup_consolidation` / `compute_act_r_activations` / + `prune_access_log` / `optimize_w20_if_ready` / + `generate_missing_embeddings` helpers (3408-3740): private to + `scheduling.rs`; stays `fn`. +- `row_to_intention` / `row_to_insight` / `row_to_memory_state` / + `row_to_connection`: all stay private in their destination file (only + one caller each). +- All `merge_*` / `portable_*` / `parse_rfc3339_opt` / `quote_ident`: + private to `portable_sync.rs`; stays `fn`. +- `node_exists` (1988): private to `crud.rs`; stays `fn`. +- `record_sync_tombstone` (1997): private to `crud.rs`; stays `fn`. +- `get_fsrs_w20` (3096): private to `scheduling.rs`; stays `fn`. + +Items already `pub fn` (or `pub(crate) fn`) stay as they are -- no +visibility regression. + +Field visibility on `SqliteMemoryStore` itself: currently all fields are +private. The sub-modules access them via `self.field`. Because impl +blocks for `SqliteMemoryStore` are written in sibling files of the same +module, `self.field` reaches private fields without a visibility bump. +**No field visibility changes are required.** Confirm this during the +first motion commit; if Rust disagrees, mark the relevant fields +`pub(super)` and document in the commit message. + +--- + +## Public Re-exports + +`crates/vestige-core/src/storage/mod.rs` currently exports: + +```rust +mod memory_store; +mod migrations; +mod portable; +mod sqlite; + +pub use memory_store::{...}; +pub use migrations::MIGRATIONS; +pub use portable::{...}; +pub use sqlite::{ + ConnectionRecord, ConsolidationHistoryRecord, DreamHistoryRecord, FilePortableSyncBackend, + InsightRecord, IntentionRecord, PortableSyncBackend, PortableSyncReport, Result, + SmartIngestResult, SqliteMemoryStore, StateTransitionRecord, StorageError, +}; + +pub type Storage = SqliteMemoryStore; +``` + +After the split, `mod sqlite;` resolves to the new directory module +(`storage/sqlite/mod.rs`). The `pub use sqlite::{...}` block resolves +against the items re-exported by `storage/sqlite/mod.rs`. + +`storage/sqlite/mod.rs` therefore needs the same names visible at its +top level. Add at the end of `mod.rs`: + +```rust +mod crud; +mod search; +mod scheduling; +mod graph; +mod domain; +mod registry; +mod portable_sync; +mod trait_impl; + +pub use portable_sync::{FilePortableSyncBackend, PortableSyncBackend, PortableSyncReport}; +// SqliteMemoryStore, StorageError, Result, SmartIngestResult, IntentionRecord, +// InsightRecord, ConnectionRecord, StateTransitionRecord, +// ConsolidationHistoryRecord, DreamHistoryRecord are defined in mod.rs itself, +// so they are already in scope and do not need a re-export. +``` + +The `crates/vestige-core/src/storage/mod.rs` file does not change. The +`pub type Storage = SqliteMemoryStore;` alias keeps working. + +If `cargo build` complains that `storage/mod.rs` cannot resolve a name +in its `pub use sqlite::{...}` block, the fix is to add the missing name +to `sqlite/mod.rs`'s re-export tail; no change to `storage/mod.rs`. + +--- + +## Test Relocation + +Two test families, two destinations. + +**Native API tests** (current lines 7120-8198) cover the legacy `pub fn` +surface. They live close to their subject: + +- Tests that touch the constructor, common helpers, and shared setup + (`create_test_storage`, `create_test_storage_at`, + `test_storage_creation`, `test_get_last_backup_timestamp_no_panic`) + move to `sqlite/mod.rs` in a `#[cfg(test)] mod tests` block. +- `test_ingest_and_get`, `test_delete`, + `test_purge_scrubs_insight_json_orphans_children_and_writes_tombstone` + go to `sqlite/crud.rs` as a `#[cfg(test)] mod tests` block. +- `test_search`, `test_keyword_search_with_include_types`, + `test_keyword_search_with_exclude_types`, + `test_include_types_takes_precedence_over_exclude`, + `test_type_filter_with_no_matches_returns_empty`, + `test_hybrid_search_backward_compat`, + `test_concrete_search_literal_identifier_lands_first`, + `test_embedding_model_family_matching`, + `test_embedding_regeneration_candidates_include_entire_mismatched_corpus` + go to `sqlite/search.rs`. +- `test_review` goes to `sqlite/scheduling.rs`. +- `test_dream_history_save_and_get_last`, `test_dream_history_empty`, + `test_count_memories_since` go to `sqlite/mod.rs` (history tables live + there). +- All `test_portable_*` go to `sqlite/portable_sync.rs`. +- `test_file_portable_sync_round_trips_between_devices` goes to + `sqlite/portable_sync.rs`. + +**Trait round-trip tests** (current lines 8200-8712) test the +`LocalMemoryStore` trait impl. Two viable layouts: + +A. Co-locate with the impl in `sqlite/trait_impl.rs` (one big + `#[cfg(test)] mod trait_tests`). +B. Keep them as a single `tests.rs` file in the sqlite directory. + +**Decision: A.** Co-locate. The trait round-trip tests are explicitly +testing the `impl LocalMemoryStore for SqliteMemoryStore` block; +co-location means a reader who edits the trait impl sees its tests in +the same file. Option B would mean two places to look every time a +trait method changes shape. For an 8K-line collapse the tradeoff +favours co-location. + +Concretely: `sqlite/trait_impl.rs` ends with a +`#[cfg(test)] mod trait_tests { ... }` block that contains all 30+ +`trait_*` tests, plus the shared `make_record`, `rt`, and small helpers +defined inside the current test mod for trait tests (lines 8208-8226). + +--- + +## Commit Sequence + +Each commit moves one logical group. After each commit: + +``` +cargo build -p vestige-core +cargo test -p vestige-core +cargo clippy -p vestige-core -- -D warnings +``` + +must pass. Order is chosen so that each move is small, the next move +does not depend on the previous having grown surprising visibility, and +the largest / riskiest move (the trait impl, with the new +trait_variant attribute) lands last. + +| # | Commit | What moves | Tests touched | +|---|--------|-----------|----------------| +| 1 | `refactor(sqlite): scaffold sqlite/ directory` | Convert `sqlite.rs` -> `sqlite/mod.rs` verbatim (rename + create empty sibling files `crud.rs`, `search.rs`, `scheduling.rs`, `graph.rs`, `domain.rs`, `registry.rs`, `portable_sync.rs`, `trait_impl.rs` each with `use super::*;`). At this point `mod.rs` declares the new modules but they are empty. | None move. Build proves the rename works. | +| 2 | `refactor(sqlite): split out portable sync` | Move all `merge_*`, `portable_*`, `export_*`, `import_*`, `sync_*` items + `MergeWrite`, `PortableSyncBackend`, `FilePortableSyncBackend`, `PortableSyncReport`, `PortableMergeState`, `PORTABLE_TABLES`, `PORTABLE_USER_DATA_TABLES`, helper statics into `sqlite/portable_sync.rs`. Add `pub use portable_sync::{...}` in `mod.rs` for the public types. | `test_portable_*` and `test_file_portable_sync_round_trips_between_devices` move too. | +| 3 | `refactor(sqlite): split out graph / connections` | Move `save_connection`, `get_connections_for_memory`, `get_all_connections`, `strengthen_connection`, `apply_connection_decay`, `prune_weak_connections`, `row_to_connection`, `get_most_connected_memory`, `get_memory_subgraph` to `sqlite/graph.rs`. | None move (no native graph tests; trait edge tests still in trait_tests). | +| 4 | `refactor(sqlite): split out scheduling / fsrs / consolidation` | Move all items listed in the Scheduling row to `sqlite/scheduling.rs`. | `test_review` moves. | +| 5 | `refactor(sqlite): split out search / fts / semantic / hybrid` | Move all items listed in the Search row to `sqlite/search.rs`. Add `pub(super)` to the four `embedding_model_*` helpers that tests reference. | `test_search`, `test_keyword_search_*`, `test_include_types_*`, `test_type_filter_*`, `test_hybrid_search_*`, `test_concrete_search_*`, `test_embedding_model_family_matching`, `test_embedding_regeneration_candidates_include_entire_mismatched_corpus` move. | +| 6 | `refactor(sqlite): split out crud / ingest / get / update / delete / purge` | Move `ingest`, `smart_ingest`, `get_node`, `update_node_content`, `delete_node`, `purge_node`, `get_all_nodes`, `get_nodes_by_type_and_tag`, `node_exists`, `record_sync_tombstone`, `generate_embedding_for_node`, `get_node_embedding`, `get_all_embeddings`, `PurgeReport` to `sqlite/crud.rs`. Bump `row_to_node` and `parse_timestamp` to `pub(super) fn` in `mod.rs`. | `test_ingest_and_get`, `test_delete`, `test_purge_scrubs_insight_json_orphans_children_and_writes_tombstone` move. | +| 7 | `refactor(sqlite): split out registry helper` | Move `enforce_model` to `sqlite/registry.rs`, bumped to `pub(super)`. | None move. | +| 8 | `refactor(sqlite): split out domain helper` | Move `read_domain_columns` to `sqlite/domain.rs`, bumped to `pub(super)`. | None move. | +| 9 | `refactor(sqlite): split out trait impl + tests` | Move `node_to_record` and the full `impl LocalMemoryStore for SqliteMemoryStore` block to `sqlite/trait_impl.rs`. Move the entire trait round-trip test module (lines 8200-8712, including `make_record` and `rt` helpers) to a `#[cfg(test)] mod trait_tests` block at the bottom of `trait_impl.rs`. This is the commit where the trait_variant attribute (from sub-plan 0001a) is observed: the impl block on `SqliteMemoryStore` uses whatever syntax the rewritten trait expects (no `#[async_trait::async_trait]`). | All `trait_*` tests move. | + +Commit 1 is the only commit that creates new files; the rest move +existing code into them. Reviewers can bisect through this list to +find any silent-semantic change. + +--- + +## Verification + +Run after every commit. All three must pass before pushing: + +``` +cargo build -p vestige-core +cargo test -p vestige-core +cargo clippy -p vestige-core -- -D warnings +``` + +The Phase 1 amendment branch must also build with the no-default-features +configuration that the release binary uses for the alternative feature +set: + +``` +cargo build -p vestige-core --no-default-features +cargo test -p vestige-core --no-default-features +``` + +Some of the methods being moved (`get_node_embedding`, `is_embedding_ready`, +`init_embeddings`, the feature-on/feature-off `hybrid_search` pair) have +two definitions guarded by feature flags. The split must preserve both +copies in the same destination file with their existing `#[cfg(...)]` +attributes; the no-default-features build confirms. + +After the last commit, run the workspace-wide check that Phase 1 promised: + +``` +cargo build --workspace +cargo test --workspace +``` + +This catches downstream consumers (`vestige-mcp`, `vestige`, +`vestige-restore`) that might depend on a specific module path (they +should not -- they import from `crate::storage::SqliteMemoryStore` and +the re-exports in `storage/mod.rs` -- but the workspace build is the +authoritative confirmation). + +--- + +## Acceptance Criteria + +1. `crates/vestige-core/src/storage/sqlite.rs` no longer exists. In its + place is `crates/vestige-core/src/storage/sqlite/` with the eight + files listed in the Target Layout section, each below 2000 lines. +2. `crates/vestige-core/src/storage/mod.rs` is unchanged (or + functionally unchanged -- the `pub use sqlite::{...}` block contains + the same identifiers in the same order). +3. Every cognitive module and binary in the workspace + (`vestige-core`, `vestige-mcp`, `vestige`, `vestige-restore`) + compiles with no source edits other than the ones in + `crates/vestige-core/src/storage/sqlite/`. +4. `cargo build -p vestige-core`, + `cargo test -p vestige-core`, + `cargo clippy -p vestige-core -- -D warnings`, + `cargo build -p vestige-core --no-default-features`, and + `cargo test -p vestige-core --no-default-features` all pass at the + end of every commit in the sequence (bisectability). +5. `cargo test --workspace` matches the Phase 1 baseline test count + (758 tests, of which 352 are in `vestige-core`). No new tests are + added by this sub-plan; no existing test is renamed or deleted. +6. The on-disk SQLite schema is unchanged. A live database created on + the pre-split build opens cleanly on the post-split build and round + trips a memory. +7. `git log --follow` works for at least one method in each destination + file (i.e. `git mv` was used where the line range constitutes most + of the file content of the destination, otherwise a `git log -p` + on the new file shows the history before the rename through the + block-move detection that recent `git log` versions support). +8. No public symbol disappears from `crate::storage::*`. A reviewer can + verify with: + ``` + cargo doc -p vestige-core --no-deps + ``` + before and after the split, and `diff` the generated + `target/doc/vestige_core/storage/index.html` lists. + +--- + +## Non-Goals (explicit) + +- No public API change. The trait surface (`LocalMemoryStore`, + `MemoryStore`), the legacy `pub fn` surface on `SqliteMemoryStore`, + the re-exports through `storage/mod.rs`, and the `pub type Storage = + SqliteMemoryStore;` alias are all preserved. +- No behavioural change. No SQL is rewritten, no FSRS parameter is + retuned, no embedding model is touched, no migration is added. +- No new tests. Tests move with their subject; no new tests are + written. +- No clippy fix-ups that pre-date this sub-plan. If `cargo clippy + -- -D warnings` was passing before the split, it must continue to + pass; if it was not passing, the failures stay where they are and + are addressed in a separate commit (out of scope here). +- No removal of the `pub type Storage = SqliteMemoryStore;` BC alias. + That happens at the end of Phase 4 per ADR 0001. +- No reorganisation of `storage/memory_store.rs`, + `storage/migrations.rs`, or `storage/portable.rs`. Those files are + out of scope; the split is private to `storage/sqlite/`. + +--- + +## Risks and Mitigations + +| Risk | Mitigation | +|------|------------| +| Silent semantic change introduced by a motion commit | Per-commit `cargo test -p vestige-core` keeps the bisect window to a single commit. Reviewer bisects with `cargo test -p vestige-core` as the witness. | +| Sibling-file `self.field` accesses fail because Rust enforces module visibility on tuple-struct or named fields | Confirmed: associated impl blocks in sibling files of the same `mod sqlite` reach private fields. If the compiler disagrees, bump the affected fields to `pub(super)` in `mod.rs` and note the bump in the commit message. | +| Test-only helpers (`create_test_storage`, `make_record`, `rt`) get duplicated across test modules | Lift them once into a `#[cfg(test)] mod test_support { ... }` sub-module in `sqlite/mod.rs` and re-export with `pub(super) use`. Do this in commit 1 (scaffold), not later. | +| `#[cfg(all(feature = "embeddings", feature = "vector-search"))]` items end up in `mod.rs` where they pollute the shared layer | Audit during commit 5 (search split); items behind both feature flags belong in `search.rs`. The `query_cache` field stays in `mod.rs` because the struct definition is there; the field declaration is feature-gated and that gate moves with the struct as-is. | +| `git log --follow` blame chains break on the moved methods | Use `git mv sqlite.rs sqlite/mod.rs` in commit 1 so commit 1 looks like a rename (`git log --follow` keeps working). Subsequent commits are content moves inside the module; modern `git log --follow -M -C` heuristics still trace the lines. Reviewers who need pristine blame should bisect to before commit 1. | +| Sub-plan 0001a (trait rewrite) has not landed when this work starts | Block: do not start commits 1-9 until 0001a is on the same branch (`feat/storage-trait-phase1`) and tests pass. `trait_impl.rs` lands the new attribute in commit 9; if 0001a is not in, commit 9 fails. | + +--- + +## Self-Contained Brief (for /goal) + +A fresh Claude Code session can execute this sub-plan by: + +1. Reading this file end to end. +2. Reading `crates/vestige-core/src/storage/sqlite.rs` (the file to be + split) in full, using line ranges from the Mapping Table to confirm + the current shape matches the brief. +3. Reading `crates/vestige-core/src/storage/mod.rs` (the re-export + surface that must continue to work). +4. Reading `crates/vestige-core/src/storage/memory_store.rs` (the + trait surface that `trait_impl.rs` implements). +5. Confirming sub-plan 0001a has landed on the current branch by + checking that `memory_store.rs` no longer carries + `#[async_trait::async_trait]` on the trait declaration. +6. Working through the Commit Sequence in order, running the + Verification commands after each commit. + +The session does not need to read ADR 0002 or the master Phase 2 plan +to do this work. The split is purely mechanical relative to the +mapping table above. diff --git a/docs/plans/0001c-async-trait-sunset.md b/docs/plans/0001c-async-trait-sunset.md new file mode 100644 index 0000000..f9d8938 --- /dev/null +++ b/docs/plans/0001c-async-trait-sunset.md @@ -0,0 +1,847 @@ +# Sub-Plan 0001c: Sunset the `async-trait` crate dependency + +**Status**: Draft +**Branch**: `feat/storage-trait-phase1` (Phase 1 amendment, PR A) +**Depends on**: +- `0001a-trait-rewrite.md` (rewrites `MemoryStore` / `LocalMemoryStore` and + the SQLite impl; lands first) +- `0001b-sqlite-split.md` (moves `sqlite.rs` into `sqlite/`; lands second) + +**Related**: `docs/adr/0002-phase-2-execution.md` (decision D1 closing line: +"async-trait dependency stays in Cargo.toml only if other code uses it; +otherwise removed"). This sub-plan operationalises the removal. + +--- + +## Context + +This is the third and final Phase 1 amendment sub-plan. Sub-plan `0001a` +rewrote `MemoryStore` / `LocalMemoryStore` using +`#[trait_variant::make(MemoryStore: Send)]` and dropped the +`#[async_trait::async_trait]` attribute from the SQLite impl block. +Sub-plan `0001b` then split `sqlite.rs` into a `sqlite/` directory; the +trait impl now lives in `sqlite/trait_impl.rs`. After `0001a` lands, the +only remaining `async_trait` usage in the workspace is the embedder pair +(`embedder/mod.rs` declares the trait; `embedder/fastembed.rs` implements +it). This sub-plan rewrites those two files following the exact pattern +from `0001a`, then removes `async-trait = "0.1"` from +`crates/vestige-core/Cargo.toml`. End state: zero `async_trait` references +anywhere under `crates/`, zero direct dependency on the `async-trait` +crate, workspace tests and clippy green. + +The rewrite is mechanically tiny -- one trait declaration, one impl block, +one Cargo.toml line -- but it is gated behind `0001a` and `0001b` so the +trait-rewrite pattern is already settled and so the SQLite trait impl +attribute has already been dropped. Doing the embedder rewrite without +that pre-work would leave the `async-trait` dep behind for the SQLite +side and force the Cargo.toml deletion into a separate commit later. + +--- + +## Scope + +### In scope + +- Rewrite `LocalEmbedder` declaration in + `crates/vestige-core/src/embedder/mod.rs` to use + `#[trait_variant::make(Embedder: Send)] pub trait LocalEmbedder`. +- Delete the `pub use LocalEmbedder as Embedder;` alias from the same file. + The `Embedder` symbol becomes the trait that `trait_variant::make` emits + at the same module path, so the existing + `pub use embedder::{Embedder, ..., LocalEmbedder};` line in + `crates/vestige-core/src/lib.rs:167` keeps working untouched. +- Drop the `#[async_trait::async_trait]` attribute from the + `FastembedEmbedder` impl block in + `crates/vestige-core/src/embedder/fastembed.rs`. +- Update doc comments on the trait declaration to describe + `trait_variant` rather than `async_trait`. +- Remove `async-trait = "0.1"` from + `crates/vestige-core/Cargo.toml` (line 119 area). Use + `cargo rm async-trait` from inside the crate directory. +- Verify with `grep -rn "async_trait" crates/` returning zero hits. + +### Out of scope + +- Any change to the `MemoryStore` trait or `SqliteMemoryStore` impl; + those were handled by `0001a`. +- Any file moves in `embedder/` (no parallel of `0001b` is required; + `embedder/` already has the `mod.rs` + `fastembed.rs` shape). +- Touching `crates/vestige-mcp/` or any cognitive module. None of them + hold `Arc` or `Box` in production. +- Renaming the `Embedder` / `LocalEmbedder` symbols or changing the + re-exports in `crates/vestige-core/src/lib.rs`. + +--- + +## Prerequisites + +### State assumed at start + +- `0001a` is merged onto the branch. After `0001a`: + - `crates/vestige-core/src/storage/memory_store.rs` declares + `#[trait_variant::make(MemoryStore: Send)] pub trait LocalMemoryStore`. + - The SQLite impl block has no `#[async_trait::async_trait]` attribute. + - `grep -rn async_trait crates/` returns exactly three hits, all in + `crates/vestige-core/src/embedder/` (two in `mod.rs`, one in + `fastembed.rs`), and one Cargo.toml hit. +- `0001b` is merged onto the branch. After `0001b`: + - `crates/vestige-core/src/storage/sqlite.rs` no longer exists as a + single file; the impl lives in `crates/vestige-core/src/storage/sqlite/trait_impl.rs`. + - The embedder files are untouched. + +### Required crates + +| Crate | Version | Action | +|----------------|---------|-----------------------------------------------------------------| +| `trait-variant`| `0.1` | Already declared (line 117 of Cargo.toml). Verify present. | +| `async-trait` | `0.1` | Remove. Only the two embedder files still use it after `0001a`. | + +### Workspace-wide audit before starting + +Run from `/home/delandtj/prppl/vestige-phase2/` (or the equivalent +worktree where this sub-plan executes): + +```bash +grep -rn "async_trait\|async-trait" crates/ tests/ +``` + +Expected hits before this sub-plan starts (after `0001a` + `0001b`): + +``` +crates/vestige-core/Cargo.toml:119:async-trait = "0.1" +crates/vestige-core/src/embedder/mod.rs:24:/// `#[async_trait::async_trait]` makes every `async fn` return a +crates/vestige-core/src/embedder/mod.rs:27:#[async_trait::async_trait] +crates/vestige-core/src/embedder/mod.rs:56:/// Both names refer to the same `async_trait`-annotated trait. +crates/vestige-core/src/embedder/fastembed.rs:44:#[async_trait::async_trait] +``` + +Five hits across two source files and one Cargo.toml. After this sub-plan, +the same grep must return zero hits. + +```bash +grep -rn "async-trait\|async_trait" --include="Cargo.toml" crates/ +``` + +Expected: exactly one hit (`crates/vestige-core/Cargo.toml:119`). No other +workspace crate declares `async-trait` as a direct dependency. This is +the precondition that lets us delete the line cleanly. + +--- + +## Files Touched + +### Trait declaration (vestige-core) + +| File | Lines (approx) | Change | +|-------------------------------------------------|----------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `crates/vestige-core/src/embedder/mod.rs` | 21-57 | Replace `#[async_trait::async_trait] pub trait LocalEmbedder: Send + Sync + 'static` with `#[trait_variant::make(Embedder: Send)] pub trait LocalEmbedder: Sync + 'static`. Delete the `pub use LocalEmbedder as Embedder;` alias on line 57. Update doc comments (lines 21-26, 55-56). | + +### Impl block (vestige-core) + +| File | Lines (approx) | Change | +|-------------------------------------------------|----------------|--------------------------------------------------------------------------------------------------------------| +| `crates/vestige-core/src/embedder/fastembed.rs` | 44 | Delete the `#[async_trait::async_trait]` attribute. Keep the `impl LocalEmbedder for FastembedEmbedder { ... }` body verbatim. No `Box::pin`, no `'async_trait` lifetimes, no manual `Pin>`. | + +### Other Embedder impls + +None. `grep -rn "impl.*LocalEmbedder\|impl.*Embedder for" crates/ tests/` +returns exactly one production hit: +`crates/vestige-core/src/embedder/fastembed.rs:45: impl LocalEmbedder for FastembedEmbedder`. +There is no test mock implementing `Embedder` in the test tree (the only +test that touches the trait, `tests/phase_1/embedder_trait.rs`, uses the +concrete `FastembedEmbedder` boxed as `Box`). + +### Call sites (production) + +Verified by: + +```bash +grep -rn "dyn Embedder\|dyn LocalEmbedder" crates/ tests/ --include="*.rs" +grep -rn "Box\|Arc" crates/ tests/ --include="*.rs" +grep -rn "use.*Embedder" crates/ tests/ --include="*.rs" +``` + +Production call sites that may need verification (and the expected change +for each, even though we have already verified that none need an edit): + +| File | Use | Required change | +|------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------|-----------------| +| `crates/vestige-core/src/lib.rs:167` | `pub use embedder::{Embedder, EmbedderError, EmbedderResult, FastembedEmbedder, LocalEmbedder};` | None. Both names still exist at `crate::embedder::*` after the rewrite; `Embedder` is now the `trait_variant`-generated trait, `LocalEmbedder` is the source-of-truth trait. The re-export keeps resolving. | +| `crates/vestige-core/src/embedder/fastembed.rs:7` | `use super::{EmbedderError, EmbedderResult, LocalEmbedder};` | None. `LocalEmbedder` is still the source-of-truth trait name. | +| `crates/vestige-core/src/embedder/mod.rs:5` | `pub use fastembed::FastembedEmbedder;` | None. Concrete type, untouched. | +| `crates/vestige-mcp/src/**` | No file imports `Embedder` or `LocalEmbedder` by name; none hold `Arc` or `Box`. | None. Verified by grep returning empty for `dyn Embedder` and `dyn LocalEmbedder` under `crates/vestige-mcp/`. | +| Cognitive modules under `crates/vestige-core/src/advanced/` and `crates/vestige-core/src/neuroscience/` | No file imports `Embedder` or `LocalEmbedder` by name. `advanced/adaptive_embedding.rs` defines its own unrelated `AdaptiveEmbedder` struct. | None. The name collision is purely surface-level; the two types live in different modules and never resolve to each other. | +| `crates/vestige-core/src/embeddings/**` | No file imports `Embedder` or `LocalEmbedder`. The `EmbeddingService` struct is what `FastembedEmbedder` wraps internally. | None. | + +The production audit returns zero files that need editing. + +### Call sites (tests) + +| File | Lines | Use | Required change | +|------------------------------------------------------------|-------|--------------------------------------------------------------------|-----------------| +| `tests/phase_1/embedder_trait.rs` | 3, 19 | `use vestige_core::embedder::{Embedder, FastembedEmbedder};`
`let e: Box = Box::new(FastembedEmbedder::new());` | None. `Embedder` is the `trait_variant`-generated Send variant; `Box` keeps compiling. `FastembedEmbedder` implements `LocalEmbedder`; the blanket `impl Embedder for T` that `trait_variant::make` emits gives the boxing for free. | + +The test audit returns zero files that need editing. + +### Cargo dependency cleanup + +| File | Lines | Change | +|-------------------------------------|-----------|-----------------------------------------------------------------------------------------------------| +| `crates/vestige-core/Cargo.toml` | 119 | Remove `async-trait = "0.1"`. Run `cargo rm async-trait` from inside `crates/vestige-core/` so `Cargo.lock` updates atomically with the manifest. | + +### Documentation + +| File | Change | +|---------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------| +| `crates/vestige-core/src/embedder/mod.rs` | Rewrite the trait-level doc comment (lines 21-26) and the `pub use` doc comment (lines 55-56) to describe `trait_variant`, not `async_trait`. See "Trait declaration rewrite" below for the exact new text. | +| `CLAUDE.md` | No change. The repo-level architecture notes do not name the trait attribute. | + +--- + +## Trait Declaration Rewrite + +### Before (state after `0001a` and `0001b` land) + +`crates/vestige-core/src/embedder/mod.rs:1-58`: + +```rust +//! Text-to-vector encoding trait. Pluggable per-install. + +mod fastembed; + +pub use fastembed::FastembedEmbedder; + +/// Error returned by every `Embedder` method. +#[non_exhaustive] +#[derive(Debug, thiserror::Error)] +pub enum EmbedderError { + #[error("embedder initialization failed: {0}")] + Init(String), + #[error("embedding generation failed: {0}")] + EmbedFailed(String), + #[error("invalid input: {0}")] + InvalidInput(String), +} + +pub type EmbedderResult = std::result::Result; + +/// Pluggable embedder. The storage layer NEVER calls fastembed directly; +/// callers compute vectors via this trait and pass them into `MemoryStore`. +/// +/// `#[async_trait::async_trait]` makes every `async fn` return a +/// `Pin>`, which is required for `Box` +/// and `Arc` to be dyn-compatible. +#[async_trait::async_trait] +pub trait LocalEmbedder: Send + Sync + 'static { + async fn embed(&self, text: &str) -> EmbedderResult>; + + fn model_name(&self) -> &str; + + fn dimension(&self) -> usize; + + /// Stable blake3 hash of (model_name || dimension || vestige-core crate version). + /// Lowercase hex, 64 chars. + /// + /// Used by `MemoryStore::register_model` to detect silent model drift + /// (e.g. a fastembed minor upgrade that changes vector output). + fn model_hash(&self) -> String; + + async fn embed_batch(&self, texts: &[&str]) -> EmbedderResult>>; + + /// Returns the `ModelSignature` describing this embedder. Convenience + /// wrapper over the three accessors above. + fn signature(&self) -> crate::storage::ModelSignature { + crate::storage::ModelSignature { + name: self.model_name().to_string(), + dimension: self.dimension(), + hash: self.model_hash(), + } + } +} + +/// Type alias: `Embedder` is the dyn-compatible, Send+Sync variant. +/// Both names refer to the same `async_trait`-annotated trait. +pub use LocalEmbedder as Embedder; +``` + +### After + +`crates/vestige-core/src/embedder/mod.rs:1-55` (approximately): + +```rust +//! Text-to-vector encoding trait. Pluggable per-install. + +mod fastembed; + +pub use fastembed::FastembedEmbedder; + +/// Error returned by every `Embedder` method. +#[non_exhaustive] +#[derive(Debug, thiserror::Error)] +pub enum EmbedderError { + #[error("embedder initialization failed: {0}")] + Init(String), + #[error("embedding generation failed: {0}")] + EmbedFailed(String), + #[error("invalid input: {0}")] + InvalidInput(String), +} + +pub type EmbedderResult = std::result::Result; + +/// Pluggable embedder. The storage layer NEVER calls fastembed directly; +/// callers compute vectors via this trait and pass them into `MemoryStore`. +/// +/// `LocalEmbedder` is the source-of-truth trait. The +/// `#[trait_variant::make(Embedder: Send)]` attribute auto-generates an +/// `Embedder` variant whose returned futures are `Send`, so +/// `Box` and `Arc` are usable on tokio/axum +/// runtimes, while `Box` remains usable on single- +/// threaded executors and thread-local backends. +/// +/// Every method is native async-fn-in-trait (stable on MSRV 1.91); no +/// per-call heap allocation, no boxed futures at the static-dispatch +/// boundary. +#[trait_variant::make(Embedder: Send)] +pub trait LocalEmbedder: Sync + 'static { + async fn embed(&self, text: &str) -> EmbedderResult>; + + fn model_name(&self) -> &str; + + fn dimension(&self) -> usize; + + /// Stable blake3 hash of (model_name || dimension || vestige-core crate version). + /// Lowercase hex, 64 chars. + /// + /// Used by `MemoryStore::register_model` to detect silent model drift + /// (e.g. a fastembed minor upgrade that changes vector output). + fn model_hash(&self) -> String; + + async fn embed_batch(&self, texts: &[&str]) -> EmbedderResult>>; + + /// Returns the `ModelSignature` describing this embedder. Convenience + /// wrapper over the three accessors above. + fn signature(&self) -> crate::storage::ModelSignature { + crate::storage::ModelSignature { + name: self.model_name().to_string(), + dimension: self.dimension(), + hash: self.model_hash(), + } + } +} +``` + +### Both halves of the macro-generated output (for reviewer clarity) + +`trait_variant::make(Embedder: Send)` expands the source-of-truth +`LocalEmbedder` declaration above into the equivalent of: + +```rust +// 1. The source-of-truth trait, exactly as written. +pub trait LocalEmbedder: Sync + 'static { + fn embed(&self, text: &str) -> impl Future>>; + fn model_name(&self) -> &str; + fn dimension(&self) -> usize; + fn model_hash(&self) -> String; + fn embed_batch(&self, texts: &[&str]) -> impl Future>>>; + fn signature(&self) -> crate::storage::ModelSignature { /* default impl unchanged */ } +} + +// 2. The generated Send variant. +pub trait Embedder: Sync + 'static { + fn embed(&self, text: &str) -> impl Future>> + Send; + fn model_name(&self) -> &str; + fn dimension(&self) -> usize; + fn model_hash(&self) -> String; + fn embed_batch(&self, texts: &[&str]) -> impl Future>>> + Send; + fn signature(&self) -> crate::storage::ModelSignature { /* default impl unchanged */ } +} + +// 3. The blanket impl that wires any LocalEmbedder + Send through to Embedder. +impl Embedder for T +where + T: LocalEmbedder + Send, + // (all returned futures of LocalEmbedder's async fns are required to be Send, + // which is satisfied for FastembedEmbedder -- see "Risks" below) +{ /* forwarders */ } +``` + +Notes: + +- The `pub use LocalEmbedder as Embedder;` line on the current + `embedder/mod.rs:57` is **deleted** entirely. `Embedder` is now the + trait that `trait_variant::make` emits at the same module path; the + re-export in `crates/vestige-core/src/lib.rs:167` + (`pub use embedder::{Embedder, ..., LocalEmbedder};`) keeps resolving + unchanged. +- `Sync + 'static` on `LocalEmbedder` (and no `Send` bound on the trait + itself) mirrors the `0001a` pattern for `LocalMemoryStore`. The current + trait carries `Send + Sync + 'static`; the rewrite drops the `Send` + bound from the local variant. `Box` is `Sync` but + not `Send`; `Box` (the generated variant) is `Send + Sync`. +- `trait_variant` 0.1 does **not** require any attribute on the impl + block. The attribute lives only on the trait declaration. See next + section. + +--- + +## Impl Block Migration + +`trait_variant` 0.1 attaches the attribute only to the trait declaration. +The impl side is plain `impl LocalEmbedder for FastembedEmbedder`; no +attribute on the impl, no `#[trait_variant::make(Embedder: Send)]` on the +impl block. The macro auto-generates the blanket +`impl Embedder for T`, so any concrete type that +implements `LocalEmbedder` automatically also implements `Embedder` +provided it is `Send`. + +`FastembedEmbedder` is `Send + Sync` because: + +- `inner: EmbeddingService` is `Send + Sync` (it wraps fastembed's + `TextEmbedding` which is `Send + Sync` after fastembed 4.x; verified + in `crates/vestige-core/src/embeddings/mod.rs`). +- `cached_hash: std::sync::OnceLock` is `Send + Sync` for `T: Send + Sync`. +- The `#[cfg(not(feature = "embeddings"))]` branch carries only + `cached_hash`, which is unconditionally `Send + Sync`. + +No new bound is needed. + +### Before + +`crates/vestige-core/src/embedder/fastembed.rs:38-100` (relevant header): + +```rust +impl Default for FastembedEmbedder { + fn default() -> Self { + Self::new() + } +} + +#[async_trait::async_trait] +impl LocalEmbedder for FastembedEmbedder { + async fn embed(&self, text: &str) -> EmbedderResult> { + // ... body unchanged ... + } + + fn model_name(&self) -> &str { /* ... */ } + fn dimension(&self) -> usize { /* ... */ } + fn model_hash(&self) -> String { /* ... */ } + + async fn embed_batch(&self, texts: &[&str]) -> EmbedderResult>> { + // ... body unchanged ... + } +} +``` + +### After + +`crates/vestige-core/src/embedder/fastembed.rs:38-99` (one fewer line): + +```rust +impl Default for FastembedEmbedder { + fn default() -> Self { + Self::new() + } +} + +impl LocalEmbedder for FastembedEmbedder { + async fn embed(&self, text: &str) -> EmbedderResult> { + // ... body unchanged ... + } + + fn model_name(&self) -> &str { /* ... */ } + fn dimension(&self) -> usize { /* ... */ } + fn model_hash(&self) -> String { /* ... */ } + + async fn embed_batch(&self, texts: &[&str]) -> EmbedderResult>> { + // ... body unchanged ... + } +} +``` + +Diff is exactly one removed line (the `#[async_trait::async_trait]` +attribute on line 44). Every method body, every `async fn` signature, +every `use` statement inside the impl block stays verbatim. No +`Box::pin(async move { ... })`, no manual `Pin>`, no +`'async_trait` lifetime markers; native async-fn-in-trait does this +directly. + +### Why the impl block does not need an attribute + +`trait_variant::make` generates two things from the source trait +(see the "macro-generated output" subsection above): + +1. The source trait itself (`LocalEmbedder`), with native async fns. +2. A second trait (`Embedder`) whose method signatures return + `impl Future + Send` instead of `impl Future`, + plus a blanket impl wiring concrete types through. + +Both are emitted at the macro-call site. `FastembedEmbedder` writes one +impl block (against `LocalEmbedder`); the macro-generated blanket +guarantees `FastembedEmbedder: Embedder` for free. The +`Box` cast on `tests/phase_1/embedder_trait.rs:19` keeps +type-checking unchanged. + +--- + +## Call Site Audit + +Verified via, from the phase2 worktree root: + +```bash +grep -rn "async_trait\|LocalEmbedder\|dyn Embedder" crates/ +grep -rn "use.*Embedder" crates/ tests/ --include="*.rs" +grep -rn "Box\|Arc\|&dyn Embedder" crates/ tests/ --include="*.rs" +grep -rn "Box\|Arc\|&dyn LocalEmbedder" crates/ tests/ --include="*.rs" +grep -rn "impl LocalEmbedder for\|impl Embedder for" crates/ tests/ --include="*.rs" +``` + +### Files that reference the trait object form + +Exactly one, test-only: + +| File | Line | Use | Required change | +|--------------------------------------|------|------------------------------------------------------------------------------------------|-----------------| +| `tests/phase_1/embedder_trait.rs` | 3 | `use vestige_core::embedder::{Embedder, FastembedEmbedder};` | None. `Embedder` is the generated Send variant at the same path. | +| `tests/phase_1/embedder_trait.rs` | 19 | `let e: Box = Box::new(FastembedEmbedder::new());` | None. `FastembedEmbedder: LocalEmbedder + Send` -> blanket gives `: Embedder` -> `Box` is well-formed. | + +### Files that import `Embedder` or `LocalEmbedder` by name + +| File | Line | Use | Required change | +|-----------------------------------------------------|------|----------------------------------------------------------------------------------------------------------------|-----------------| +| `crates/vestige-core/src/lib.rs` | 167 | `pub use embedder::{Embedder, EmbedderError, EmbedderResult, FastembedEmbedder, LocalEmbedder};` | None. Both names still resolve. | +| `crates/vestige-core/src/embedder/mod.rs` | 5 | `pub use fastembed::FastembedEmbedder;` | None. | +| `crates/vestige-core/src/embedder/fastembed.rs` | 7 | `use super::{EmbedderError, EmbedderResult, LocalEmbedder};` | None. | +| `tests/phase_1/embedder_trait.rs` | 3 | `use vestige_core::embedder::{Embedder, FastembedEmbedder};` | None. | + +### Files that implement the trait + +| File | Line | Impl | Required change | +|-----------------------------------------------------|------|-----------------------------------------------------------------------|----------------------------------------------| +| `crates/vestige-core/src/embedder/fastembed.rs` | 45 | `impl LocalEmbedder for FastembedEmbedder` (currently `#[async_trait]`) | Drop the `#[async_trait::async_trait]` attr. | + +No other impls exist. There is no test mock implementing `Embedder` or +`LocalEmbedder` anywhere in the workspace. + +### Files that import `async_trait` directly + +After `0001a` lands, only the embedder pair: + +``` +crates/vestige-core/src/embedder/mod.rs:24 (doc comment) +crates/vestige-core/src/embedder/mod.rs:27 (attribute) +crates/vestige-core/src/embedder/mod.rs:56 (doc comment) +crates/vestige-core/src/embedder/fastembed.rs:44 (attribute) +``` + +Plus the Cargo manifest: + +``` +crates/vestige-core/Cargo.toml:119:async-trait = "0.1" +``` + +### Production files that hold a concrete embedder + +`FastembedEmbedder` is constructed and used by concrete name (not via +trait object) in: the dashboard / MCP layer if it needs to embed query +strings ad-hoc. None of those call sites need an edit because the +concrete type is what they hold, and the concrete type is untouched by +this sub-plan. + +### Conclusion + +| Category | Count | +|--------------------------------------------------|-------| +| Production source files modified | 2 | +| Test source files modified | 0 | +| Cargo manifests modified | 1 | +| Production source files importing `Embedder` / `LocalEmbedder` (verified unchanged) | 3 | +| Test source files importing `Embedder` (verified unchanged) | 1 | +| Direct `async_trait` uses outside the embedder module after `0001a` | 0 | + +--- + +## Cargo.toml Change + +From inside `crates/vestige-core/`: + +```bash +cargo rm async-trait +``` + +This removes line 119 of `Cargo.toml` and updates `Cargo.lock` in one +step. Manual editing is acceptable as a fallback if `cargo rm` is +unavailable in the agent environment; in that case, follow up with +`cargo check -p vestige-core` to refresh the lockfile. + +### Verification + +```bash +# Direct dependency must be gone. +grep -rn "async-trait\|async_trait" --include="Cargo.toml" crates/ +# Expected: empty. + +# Transitive presence is permitted (e.g. via a third-party crate). +cargo tree -p vestige-core --depth 2 | grep async-trait +# Expected: empty for the direct edges; if a sub-dependency still pulls +# async-trait transitively, the output may contain it deeper than depth 2, +# which is fine. We only care about removing the DIRECT edge. +``` + +If `cargo tree --depth 2` returns any `async-trait` line, inspect with +`cargo tree -p vestige-core -i async-trait` to see what is pulling it. +Acceptable parents: any third-party crate. Unacceptable parent: anything +under `vestige-*`, which would mean a missed file. + +--- + +## Commit Sequence + +Three commits, each green on +`cargo test -p vestige-core --features embeddings,vector-search` and +`cargo test -p vestige-core --no-default-features`. + +### Commit 1: rewrite LocalEmbedder trait declaration + +- Touches: `crates/vestige-core/src/embedder/mod.rs` only. +- Action: replace lines 21-57 per the "Trait Declaration Rewrite" + section above. Delete the `pub use LocalEmbedder as Embedder;` line. +- Green after: `cargo check -p vestige-core` (the impl block in + `fastembed.rs` still has its `#[async_trait::async_trait]` attribute; + the macro is harmless when applied to a trait that the impl block + targets by path, because async_trait rewrites the impl's async fns + into boxed-future fns whose signatures still match the native-async + declarations after trait_variant lowering, just as it did for the + SQLite intermediate state in `0001a`'s commit 1). + + **Mitigation if check fails between commits 1 and 2:** combine the + two into a single commit. The split is offered for review convenience; + the build must be green after every commit lands. + +### Commit 2: drop `#[async_trait::async_trait]` from FastembedEmbedder impl + +- Touches: `crates/vestige-core/src/embedder/fastembed.rs` only. +- Action: delete line 44 (`#[async_trait::async_trait]`). +- Green after: + - `cargo test -p vestige-core --features embeddings,vector-search`. + - `cargo test -p vestige-core --no-default-features` (the + `#[cfg(not(feature = "embeddings"))]` branches inside the impl now + stand on their own). + - Phase 1 integration test: `cargo test --test embedder_trait + --features embeddings,vector-search`. + +### Commit 3: drop the async-trait dependency + +- Touches: `crates/vestige-core/Cargo.toml` (plus `Cargo.lock` as a + side effect). +- Action: from inside `crates/vestige-core/`, run `cargo rm async-trait`. +- Green after: `cargo build --workspace --all-targets` and + `cargo test --workspace`. +- Final hard ASCII gate: `! grep -rn "async_trait" crates/` must exit + with status 0 (i.e. the inverted grep finds nothing). + +### Combined alternative + +Commits 1 and 2 may fold into a single commit if the per-step split +feels artificial (the patterns are identical to `0001a`'s commits 3 +and 4). Commit 3 (the Cargo.toml removal) should stay separate so the +dependency-removal diff is visible in isolation. + +--- + +## Verification + +Every command runs from the repo root unless noted otherwise. + +```bash +# 1. Vestige-core, default features (embeddings + vector-search). +cargo test -p vestige-core --features embeddings,vector-search + +# 2. Vestige-core, minimal features (no embeddings, no vector-search). +cargo test -p vestige-core --no-default-features + +# 3. Workspace build, all targets (catches any feature-gated regression +# in the vestige-mcp tools tree). +cargo build --workspace --all-targets + +# 4. Whole-workspace test (vestige-mcp 406 tests + vestige-core 352 +# tests per the CLAUDE.md baseline). +cargo test --workspace + +# 5. Phase 1 embedder integration test (the trait-shape contract). +cargo test --test embedder_trait --features embeddings,vector-search + +# 6. Clippy gate, deny warnings (matches Phase 1 PR policy). +cargo clippy --workspace --all-targets --features embeddings,vector-search -- -D warnings + +# 7. Hard ASCII gate -- async_trait must be gone from source. +! grep -rn "async_trait" crates/ +# Inverted grep: exit 0 iff grep found nothing. + +# 8. Hard ASCII gate -- async-trait must be gone from manifests. +! grep -rn "async-trait" --include="Cargo.toml" crates/ + +# 9. Confirm trait_variant attribute is in place at the embedder. +grep -rn "trait_variant::make" crates/vestige-core/src/embedder/ +# Expected: exactly one hit, in embedder/mod.rs. + +# 10. Workspace-wide trait_variant audit (should match the count after +# 0001a -- two hits total, one for storage, one for embedder). +grep -rn "trait_variant::make" crates/vestige-core/src/ +# Expected: two hits. +``` + +Expected outcomes: + +- Command 1: 352 vestige-core tests pass (matches baseline). +- Command 2: smaller test count, all pass. +- Command 3: workspace builds in dev mode for all targets. +- Command 4: 758 total tests pass (matches CLAUDE.md baseline). +- Command 5: `embedder_trait` integration test passes. The + `fastembed_implements_embedder_trait` assertion (`let e: Box = ...`) is the canary; if `trait_variant::make` failed to + emit the `Embedder` Send variant, this fails to compile. +- Command 6: zero clippy warnings. +- Command 7: empty output. `async_trait` is fully gone from source. +- Command 8: empty output. `async-trait` is fully gone from manifests. +- Command 9: one hit. +- Command 10: two hits. + +--- + +## Acceptance Criteria + +A reviewer should be able to check every box: + +- [ ] `crates/vestige-core/src/embedder/mod.rs` declares the embedder + trait with `#[trait_variant::make(Embedder: Send)] pub trait + LocalEmbedder: Sync + 'static`, no `async_trait` attribute, no + `Send` bound on `LocalEmbedder` itself. +- [ ] `crates/vestige-core/src/embedder/mod.rs` no longer contains + `pub use LocalEmbedder as Embedder;`. +- [ ] `crates/vestige-core/src/embedder/fastembed.rs` declares + `impl LocalEmbedder for FastembedEmbedder` with no attribute on + the impl block. +- [ ] `crates/vestige-core/Cargo.toml` does not declare `async-trait` + as a direct dependency. +- [ ] `grep -rn "async_trait" crates/` returns zero hits. +- [ ] `grep -rn "async-trait" --include="Cargo.toml" crates/` returns + zero hits. +- [ ] `grep -rn "trait_variant::make" crates/vestige-core/src/` returns + exactly two hits (storage trait + embedder trait). +- [ ] All 758 workspace tests pass (`cargo test --workspace`). +- [ ] `tests/phase_1/embedder_trait.rs` compiles and passes with the + `Box` cast intact. +- [ ] `cargo clippy --workspace --all-targets --features + embeddings,vector-search -- -D warnings` is clean. +- [ ] No file under `crates/vestige-mcp/` or under + `crates/vestige-core/src/{neuroscience,advanced,consolidation, + codebase,memory,embeddings}/` was modified by this sub-plan. +- [ ] `Cargo.lock` was updated as a side effect of `cargo rm async-trait` + (it must no longer reference `async-trait`). +- [ ] Doc comments on the embedder trait declaration describe + `trait_variant`, not `async_trait`. + +--- + +## Risks and Mitigations + +- **`trait_variant::make` requires returned futures to be `Send` for the + blanket `impl Embedder for T`. If any + `async fn embed`/`embed_batch` body inside `FastembedEmbedder` captures + a non-Send local, the blanket impl fails to type-check.** + Mitigation: the existing impl bodies call `self.inner.embed(text)` / + `self.inner.embed_batch(texts)`, where `inner: EmbeddingService` is + `Send + Sync` (verified in `crates/vestige-core/src/embeddings/mod.rs`). + No `.await` points exist inside the bodies in either feature branch; + the `EmbeddingService::embed` calls are synchronous. The futures are + trivially `Send`. If a future change introduces a non-Send local + (e.g. an `Rc` or a non-Send guard), the blanket impl will surface that + as a compile error at the dyn cast in `tests/phase_1/embedder_trait.rs`, + which is the correct outcome. +- **The macro's blanket impl interacts oddly with the default `signature` + method.** + Mitigation: `signature` is a synchronous method returning + `crate::storage::ModelSignature`, with no `Send` or `async` concerns. + `trait_variant::make` emits it on both variants as-is. The existing + Phase 1 test `signature_matches_memory_store_registry` exercises this + path and is part of the verification step. +- **`Box` cast in `tests/phase_1/embedder_trait.rs` fails + to resolve after the rewrite.** + Mitigation: the rewrite preserves the `Embedder` symbol at the same + module path; only its provenance changes (now generated by + `trait_variant::make` instead of by `pub use LocalEmbedder as + Embedder;`). The macro is specifically designed so that the generated + trait is dyn-compatible at the Send-bound boundary. Verified by the + identical pattern already working for `MemoryStore` after `0001a`. +- **`cargo rm async-trait` updates `Cargo.lock` but accidentally bumps + other crates.** + Mitigation: run `cargo rm async-trait` and then immediately inspect + the resulting `Cargo.lock` diff. The expected diff is the removal of + the `[[package]] name = "async-trait"` block and its hash. Anything + else is a red flag and should be reverted before committing + (`git checkout -- Cargo.lock` then `cargo update -p async-trait + --precise=remove` -- or fall back to manual edit + `cargo check`). +- **A new workspace crate added in parallel with this work declares + `async-trait` and the dependency removal silently re-introduces it + later.** + Mitigation: the verification step `grep -rn "async-trait" + --include="Cargo.toml" crates/` is part of the acceptance criteria; a + rebase that reintroduces the line will fail this gate. +- **MCP server uses `Embedder` somewhere we missed.** + Mitigation: full workspace grep (`grep -rn "Embedder" crates/`) + returns no hits inside `crates/vestige-mcp/` for the trait names; the + MCP layer uses the concrete `EmbeddingService` from + `crates/vestige-core/src/embeddings/` for ad-hoc embedding calls. The + trait surface is purely internal to `vestige-core`. + +--- + +## Out-of-Band Notes + +- **No other workspace crate declares `async-trait` as a direct + dependency.** Verified by + `grep -rn "async-trait" --include="Cargo.toml" crates/` returning + exactly one hit at `crates/vestige-core/Cargo.toml:119`. There is + nothing to clean up in `crates/vestige-mcp/Cargo.toml` or elsewhere. +- **Order matters across the three Phase 1 amendment sub-plans:** + `0001a` (trait rewrite) -> `0001b` (sqlite split) -> `0001c` (this + one, async-trait sunset). Reversing the order is possible in + principle but would force re-editing the embedder rewrite twice and + leaves the `async-trait` dep behind until very late. +- **This sub-plan amends `feat/storage-trait-phase1` (tip 790c0c8 plus + whatever commits `0001a` and `0001b` added).** The branch has not + been opened upstream yet, so amending in place is safe; no force-push + to a public PR. +- **After this sub-plan lands, the branch is reviewed and merged before + Phase 2 sub-plans (`0002a-` through `0002i-`) begin implementation.** + Phase 2 introduces no async-trait usage; the Postgres backend follows + the same `trait_variant::make` pattern (see ADR 0002 D1). +- **`trait-variant` 0.1 stays in `Cargo.toml`.** It is the only crate + this sub-plan keeps; `async-trait` is the only one it removes. + +--- + +## Self-Contained `/goal` Brief + +For a fresh Claude Code session executing this sub-plan without prior +conversation context: + +1. Check out branch `feat/storage-trait-phase1` (or a worktree off + of it after `0001a` and `0001b` are merged into it). +2. Read this file (`docs/plans/0001c-async-trait-sunset.md`) in full. +3. Read `docs/plans/0001a-trait-rewrite.md` sections "Trait declaration + rewrite" and "Impl block migration" -- they document the exact + pattern this sub-plan mirrors for the embedder. +4. Run the prerequisite audit grep listed under "Prerequisites". If it + returns more than the five hits documented there, stop and report; + the upstream state does not match what this sub-plan assumes. +5. Execute Commit 1 (rewrite `embedder/mod.rs`), then Commit 2 (drop + the attribute on the FastembedEmbedder impl), then Commit 3 + (`cargo rm async-trait`). Run the verification commands listed + above after each commit; do not proceed if any test or clippy gate + fails. +6. Verify every box in "Acceptance Criteria" is ticked. +7. Report file paths touched, test counts, and the final two grep + results (commands 7 and 8 from "Verification") in the closing + message. From 9ef8afdb20337d08cb5489078ae49eec8c7c1cf1 Mon Sep 17 00:00:00 2001 From: Jan De Landtsheer Date: Wed, 27 May 2026 09:35:58 +0200 Subject: [PATCH 5/6] docs(plans): add Phase 2 sub-plans 0002a-0002i + supersession notice Nine Phase 2 sub-plans operationalising ADR 0002 against the Phase 2 master plan, each sized to fit a focused implementation session and handed to Claude Code as a /goal brief without requiring the agent to load the master plan. Order of execution (each depends on the previous unless noted): - 0002a-skeleton-and-feature-gate.md -- postgres-backend Cargo feature + PgMemoryStore skeleton with todo!() bodies. D1+D2. - 0002b-pool-and-config.md -- PgPool builder, VestigeConfig/ PostgresConfig, vestige.toml loader wired into vestige-mcp. D3+D7 (master plan numbering). - 0002c-migrations.md -- sqlx migrations 0001_init/0002_hnsw including D7 (users/groups/memberships, owner/visibility/shared_with_groups) and D8 (codebase column). SQLite V15 parity migration. D4. - 0002d-store-impl-bodies.md -- real CRUD + registry bodies; trivial fts_search/vector_search bodies. D2+D6. - 0002e-hybrid-search.md -- one-statement RRF query. D5. - 0002f-migrate-cli.md -- vestige migrate copy (SQLite -> Postgres), --dry-run, idempotent re-runs, --allow-source-upgrade for pre-V15 sources. D8+D10. - 0002g-reembed.md -- vestige migrate reembed (offline rebuild). D9 + D10 reembed arm. Ships resolve_embedder helper as a workaround for the missing Embedder::from_name(&str) constructor. - 0002h-testing-and-benches.md -- testcontainers harness, six integration test files, Criterion bench at 1k/100k. D14+D15. - 0002i-runbook.md -- operator-facing deployment + day-2 runbook. D16. Supersession notice added to the master plan (0002-phase-2-postgres- backend.md) pointing at ADR 0002; body retained as archival reference. PR B carries this commit plus the previous two (ADR 0002 + Phase 1 amendment sub-plans); no code change. --- docs/plans/0002-phase-2-postgres-backend.md | 8 + docs/plans/0002a-skeleton-and-feature-gate.md | 554 ++++++ docs/plans/0002b-pool-and-config.md | 886 +++++++++ docs/plans/0002c-migrations.md | 1119 +++++++++++ docs/plans/0002d-store-impl-bodies.md | 1771 +++++++++++++++++ docs/plans/0002e-hybrid-search.md | 825 ++++++++ docs/plans/0002f-migrate-cli.md | 1045 ++++++++++ docs/plans/0002g-reembed.md | 843 ++++++++ docs/plans/0002h-testing-and-benches.md | 1223 ++++++++++++ docs/plans/0002i-runbook.md | 724 +++++++ 10 files changed, 8998 insertions(+) create mode 100644 docs/plans/0002a-skeleton-and-feature-gate.md create mode 100644 docs/plans/0002b-pool-and-config.md create mode 100644 docs/plans/0002c-migrations.md create mode 100644 docs/plans/0002d-store-impl-bodies.md create mode 100644 docs/plans/0002e-hybrid-search.md create mode 100644 docs/plans/0002f-migrate-cli.md create mode 100644 docs/plans/0002g-reembed.md create mode 100644 docs/plans/0002h-testing-and-benches.md create mode 100644 docs/plans/0002i-runbook.md diff --git a/docs/plans/0002-phase-2-postgres-backend.md b/docs/plans/0002-phase-2-postgres-backend.md index 3fe28f2..ed2a186 100644 --- a/docs/plans/0002-phase-2-postgres-backend.md +++ b/docs/plans/0002-phase-2-postgres-backend.md @@ -1,5 +1,13 @@ # Phase 2 Plan: PostgreSQL Backend +> **Supersession Notice (2026-05-26):** This master plan is now archival. Execution is governed by: +> - **ADR**: [`docs/adr/0002-phase-2-execution.md`](../adr/0002-phase-2-execution.md) -- binding decisions +> - **Sub-plans** (executable briefs): +> - Phase 1 amendment: [0001a-trait-rewrite.md](0001a-trait-rewrite.md), [0001b-sqlite-split.md](0001b-sqlite-split.md), [0001c-async-trait-sunset.md](0001c-async-trait-sunset.md) +> - Phase 2: 0002a..0002i (skeleton, pool+config, migrations, store impl, hybrid search, migrate CLI, reembed, tests+benches, runbook) +> +> **Deltas vs body**: trait uses `trait_variant`, error type is `MemoryStoreError`/`MemoryStoreResult`, `connect` is `(url, max_connections)` only, the core table is `knowledge_nodes` (not `memories`) and gains `owner_user_id` + `visibility` + `shared_with_groups` + `codebase`, plus `users`/`groups`/`group_memberships` tables. See ADR 0002 D1-D8. + **Status**: Draft **Depends on**: Phase 1 (MemoryStore + Embedder traits, embedding_model registry, domain columns) **Related**: docs/adr/0001-pluggable-storage-and-network-access.md (Phase 2), docs/prd/001-getting-centralized-vestige.md, docs/plans/local-dev-postgres-setup.md (local cluster provisioning) diff --git a/docs/plans/0002a-skeleton-and-feature-gate.md b/docs/plans/0002a-skeleton-and-feature-gate.md new file mode 100644 index 0000000..74032dc --- /dev/null +++ b/docs/plans/0002a-skeleton-and-feature-gate.md @@ -0,0 +1,554 @@ +# Phase 2 Sub-Plan 0002a -- Skeleton and Feature Gate + +**Status**: Ready +**Depends on**: Phase 1 amendment (sub-plans `0001a-trait-rewrite.md` and +`0001b-sqlite-split.md`) merged. Specifically: +- `MemoryStore` trait declared with `#[trait_variant::make(MemoryStore: Send)]`, + generating a non-Send `LocalMemoryStore` companion trait. The + `pub use MemoryStore as LocalMemoryStore` alias from Phase 1 is gone. +- `crates/vestige-core/src/storage/sqlite.rs` has been split into + `crates/vestige-core/src/storage/sqlite/` with the same public surface. + +This sub-plan covers Phase 2 master-plan deliverables D1 and D2 only: +the `postgres-backend` Cargo feature gate and a compilable `PgMemoryStore` +skeleton whose trait method bodies are `todo!()`. No real Postgres code, no +migrations, no SQL. Later sub-plans (`0002b-pool-and-config.md`, +`0002c-migrations.md`, `0002d-store-impl-bodies.md`, ...) fill the bodies in. + +The success criterion is a clean build under both feature-flag configurations, +nothing more. + +--- + +## Context + +ADR 0002 D4 commits Phase 2 to a `crates/vestige-core/src/storage/postgres/` +directory from day one. The seven other files in that directory +(`pool.rs`, `migrations.rs`, `registry.rs`, `search.rs`, `migrate_cli.rs`, +`reembed.rs`) belong to subsequent sub-plans. This sub-plan creates only +`crates/vestige-core/src/storage/postgres/mod.rs` so the rest can be added +incrementally without breaking the build. + +Per ADR 0002 D2, `PgMemoryStore::connect` mirrors `SqliteMemoryStore::new`: +no `Embedder` argument. The pgvector typmod DDL +(`ALTER TABLE memories ALTER COLUMN embedding TYPE vector($N)`) lives inside +the trait method `register_model`, invoked by the caller after construction. +In this sub-plan `register_model` is a `todo!()` body; `0002c-migrations.md` +and `0002d-store-impl-bodies.md` provide the real implementation. + +The trait surface in `crates/vestige-core/src/storage/memory_store.rs` is the +source of truth for method signatures. Do NOT copy signatures from the master +plan -- they are stale in places (for example, master plan 0002 D2 lists +`remove_edge` as three-arg `(source, target, edge_type)`; the live trait has +two args `(source, target)`). + +--- + +## Cargo manifest changes + +Two optional crates and one new feature flag. Use `cargo add` per the global +CLAUDE.md preference; do not hand-edit `Cargo.toml`. + +```bash +cd crates/vestige-core + +cargo add sqlx@0.8 --optional --no-default-features \ + --features runtime-tokio,tls-rustls,postgres,uuid,chrono,json,migrate,macros + +cargo add pgvector@0.4 --optional --features sqlx +``` + +After both commands, open `crates/vestige-core/Cargo.toml` and add the +`postgres-backend` feature line in the `[features]` block. Place it after +the `metal` feature, before `[dependencies]`: + +```toml +# Postgres backend (mutually compilable with the SQLite backend; default OFF). +# Compile with: --features postgres-backend +postgres-backend = ["dep:sqlx", "dep:pgvector"] +``` + +Do NOT add `tokio-stream`, `futures`, `indicatif`, or `toml` in this sub-plan. +The master plan D1 lists them in the `postgres-backend` feature for +convenience, but their consumers (streaming migrate, progress bar, config +parsing) land in later sub-plans. Adding them here pulls dead weight into the +feature gate. + +Do NOT add the `vestige-mcp` pass-through feature in this sub-plan either. +The MCP crate gets its `postgres-backend` feature in `0002b-pool-and-config.md` +when `MemoryStoreConfig` lands and the binary needs a knob to pick a backend. + +Verify the diff to `crates/vestige-core/Cargo.toml` looks like this and only +this: + +```toml +[features] +# ...existing features unchanged... +postgres-backend = ["dep:sqlx", "dep:pgvector"] + +[dependencies] +# ...existing deps unchanged... +sqlx = { version = "0.8", default-features = false, features = [ + "runtime-tokio", "tls-rustls", "postgres", "uuid", "chrono", + "json", "migrate", "macros", +], optional = true } +pgvector = { version = "0.4", features = ["sqlx"], optional = true } +``` + +The exact ordering of the two new lines inside `[dependencies]` is not +significant; `cargo add` places them at the end. Leave the placement that +`cargo add` produces. + +--- + +## Storage module export + +Edit `crates/vestige-core/src/storage/mod.rs` to expose the new module behind +the feature flag. Two lines change. + +Add to the module-declaration block (after `mod sqlite;`): + +```rust +#[cfg(feature = "postgres-backend")] +mod postgres; +``` + +Add to the re-export block (after the `pub use sqlite::{ ... }` block): + +```rust +#[cfg(feature = "postgres-backend")] +pub use postgres::PgMemoryStore; +``` + +Nothing else in `storage/mod.rs` changes. The `Storage` alias still points at +`SqliteMemoryStore`; the SQLite re-export block is untouched. + +--- + +## Postgres module skeleton + +Create `crates/vestige-core/src/storage/postgres/mod.rs` with the full content +below. This is the only new file in this sub-plan. + +```rust +#![cfg(feature = "postgres-backend")] +//! Postgres-backed implementation of `MemoryStore`. +//! +//! Skeleton only. Every trait method is `todo!()`. Real bodies land in +//! subsequent Phase 2 sub-plans: +//! - `0002b-pool-and-config.md`: pool construction and config wiring +//! - `0002c-migrations.md`: sqlx migration files and `init`/`register_model` +//! - `0002d-store-impl-bodies.md`: CRUD, scheduling, edges, domains +//! - `0002e-hybrid-search.md`: RRF query and search bodies +//! +//! The directory grows companion files (`pool.rs`, `migrations.rs`, +//! `registry.rs`, `search.rs`, `migrate_cli.rs`, `reembed.rs`) in those +//! sub-plans; this skeleton only creates `mod.rs`. + +use chrono::{DateTime, Utc}; +use sqlx::PgPool; +use uuid::Uuid; + +use crate::storage::memory_store::{ + Domain, HealthStatus, LocalMemoryStore, MemoryEdge, MemoryRecord, MemoryStoreResult, + ModelSignature, SchedulingState, SearchQuery, SearchResult, StoreStats, +}; + +/// Postgres-backed implementation of `MemoryStore`. +/// +/// Cheaply cloneable. Methods take `&self`; interior state lives inside the +/// `PgPool` (which already provides `Sync` via `Arc` internally). +#[derive(Clone)] +pub struct PgMemoryStore { + pool: PgPool, + /// Embedding vector dimension. Set to 0 in the skeleton; populated by + /// `register_model` in `0002d-store-impl-bodies.md` once the pgvector + /// `ALTER COLUMN TYPE vector(N)` DDL lands. + embedding_dim: i32, +} + +impl PgMemoryStore { + /// Construct a new store from a connection URL. + /// + /// Mirrors `SqliteMemoryStore::new`: no `Embedder` argument. The pgvector + /// `ALTER TABLE memories ALTER COLUMN embedding TYPE vector($N)` DDL lives + /// inside `register_model`, not here. The caller (cognitive engine + /// bootstrap, migrate CLI, tests) invokes `register_model` after this + /// returns, identically to the SQLite path. + /// + /// Real body lands in `0002b-pool-and-config.md` (pool construction) and + /// `0002c-migrations.md` (initial migration run). + pub async fn connect(_url: &str, _max_connections: u32) -> MemoryStoreResult { + todo!("PgMemoryStore::connect lands in 0002b-pool-and-config.md") + } + + /// Low-level constructor for tests: supply an existing pool, skip migrate. + /// + /// Real body lands in `0002b-pool-and-config.md`. + pub async fn from_pool(_pool: PgPool) -> MemoryStoreResult { + todo!("PgMemoryStore::from_pool lands in 0002b-pool-and-config.md") + } + + /// Accessor used by migrate/reembed CLI. + pub fn pool(&self) -> &PgPool { + &self.pool + } + + /// Currently-registered vector dimension. Returns 0 until `register_model` + /// has been called (real body: `0002d-store-impl-bodies.md`). + pub fn embedding_dim(&self) -> i32 { + self.embedding_dim + } +} + +// trait_variant::make on the trait declaration generates two traits: +// - `MemoryStore` (Send-bound) +// - `LocalMemoryStore` (non-Send companion) +// The implementer writes `impl LocalMemoryStore for ...` plainly; the Send +// variant is generated automatically from the non-Send impl. +impl LocalMemoryStore for PgMemoryStore { + // --- Lifecycle --- + async fn init(&self) -> MemoryStoreResult<()> { + todo!("PgMemoryStore::init lands in 0002c-migrations.md") + } + + async fn health_check(&self) -> MemoryStoreResult { + todo!("PgMemoryStore::health_check lands in 0002d-store-impl-bodies.md") + } + + // --- Embedding model registry --- + async fn registered_model(&self) -> MemoryStoreResult> { + todo!("PgMemoryStore::registered_model lands in 0002d-store-impl-bodies.md") + } + + async fn register_model(&self, _sig: &ModelSignature) -> MemoryStoreResult<()> { + todo!("PgMemoryStore::register_model lands in 0002d-store-impl-bodies.md") + } + + // --- CRUD --- + async fn insert(&self, _record: &MemoryRecord) -> MemoryStoreResult { + todo!("PgMemoryStore::insert lands in 0002d-store-impl-bodies.md") + } + + async fn get(&self, _id: Uuid) -> MemoryStoreResult> { + todo!("PgMemoryStore::get lands in 0002d-store-impl-bodies.md") + } + + async fn update(&self, _record: &MemoryRecord) -> MemoryStoreResult<()> { + todo!("PgMemoryStore::update lands in 0002d-store-impl-bodies.md") + } + + async fn delete(&self, _id: Uuid) -> MemoryStoreResult<()> { + todo!("PgMemoryStore::delete lands in 0002d-store-impl-bodies.md") + } + + // --- Search --- + async fn search(&self, _query: &SearchQuery) -> MemoryStoreResult> { + todo!("PgMemoryStore::search lands in 0002e-hybrid-search.md") + } + + async fn fts_search( + &self, + _text: &str, + _limit: usize, + ) -> MemoryStoreResult> { + todo!("PgMemoryStore::fts_search lands in 0002e-hybrid-search.md") + } + + async fn vector_search( + &self, + _embedding: &[f32], + _limit: usize, + ) -> MemoryStoreResult> { + todo!("PgMemoryStore::vector_search lands in 0002e-hybrid-search.md") + } + + // --- FSRS Scheduling --- + async fn get_scheduling( + &self, + _memory_id: Uuid, + ) -> MemoryStoreResult> { + todo!("PgMemoryStore::get_scheduling lands in 0002d-store-impl-bodies.md") + } + + async fn update_scheduling(&self, _state: &SchedulingState) -> MemoryStoreResult<()> { + todo!("PgMemoryStore::update_scheduling lands in 0002d-store-impl-bodies.md") + } + + async fn get_due_memories( + &self, + _before: DateTime, + _limit: usize, + ) -> MemoryStoreResult> { + todo!("PgMemoryStore::get_due_memories lands in 0002d-store-impl-bodies.md") + } + + // --- Graph (spreading activation) --- + async fn add_edge(&self, _edge: &MemoryEdge) -> MemoryStoreResult<()> { + todo!("PgMemoryStore::add_edge lands in 0002d-store-impl-bodies.md") + } + + async fn get_edges( + &self, + _node_id: Uuid, + _edge_type: Option<&str>, + ) -> MemoryStoreResult> { + todo!("PgMemoryStore::get_edges lands in 0002d-store-impl-bodies.md") + } + + async fn remove_edge(&self, _source: Uuid, _target: Uuid) -> MemoryStoreResult<()> { + todo!("PgMemoryStore::remove_edge lands in 0002d-store-impl-bodies.md") + } + + async fn get_neighbors( + &self, + _node_id: Uuid, + _depth: usize, + ) -> MemoryStoreResult> { + todo!("PgMemoryStore::get_neighbors lands in 0002d-store-impl-bodies.md") + } + + // --- Domains (Phase 1: stubs return empty; full impl in Phase 4) --- + async fn list_domains(&self) -> MemoryStoreResult> { + todo!("PgMemoryStore::list_domains lands in 0002d-store-impl-bodies.md") + } + + async fn get_domain(&self, _id: &str) -> MemoryStoreResult> { + todo!("PgMemoryStore::get_domain lands in 0002d-store-impl-bodies.md") + } + + async fn upsert_domain(&self, _domain: &Domain) -> MemoryStoreResult<()> { + todo!("PgMemoryStore::upsert_domain lands in 0002d-store-impl-bodies.md") + } + + async fn delete_domain(&self, _id: &str) -> MemoryStoreResult<()> { + todo!("PgMemoryStore::delete_domain lands in 0002d-store-impl-bodies.md") + } + + async fn classify(&self, _embedding: &[f32]) -> MemoryStoreResult> { + todo!("PgMemoryStore::classify lands in 0002d-store-impl-bodies.md") + } + + // --- Bulk / Maintenance --- + async fn count(&self) -> MemoryStoreResult { + todo!("PgMemoryStore::count lands in 0002d-store-impl-bodies.md") + } + + async fn get_stats(&self) -> MemoryStoreResult { + todo!("PgMemoryStore::get_stats lands in 0002d-store-impl-bodies.md") + } + + async fn vacuum(&self) -> MemoryStoreResult<()> { + todo!("PgMemoryStore::vacuum lands in 0002d-store-impl-bodies.md") + } +} +``` + +Notes on the skeleton: + +- The file-level `#![cfg(feature = "postgres-backend")]` means the whole file + vanishes when the feature is off. The `mod postgres;` line in + `storage/mod.rs` is itself feature-gated, so this is belt-and-braces; both + gates are needed because the file-level attribute is what allows the file to + use `sqlx::PgPool` unconditionally inside it. +- `EmbeddingModelDescriptor` (a separate Postgres-internal type that the + master plan sketched on the struct) is dropped. The trait surface already + carries `ModelSignature` for the registry round-trip; the registry storage + layout is a private concern of `registry.rs`, which is added later. Keep + `PgMemoryStore` minimal until a real consumer needs the extra type. +- The struct only carries `pool` and `embedding_dim`. The model descriptor + field from the master plan sketch goes away with `EmbeddingModelDescriptor`. + If `register_model` later needs to cache the descriptor on the struct, it + can be added then; the skeleton does not speculate. +- The two trivial accessors (`pool`, `embedding_dim`) get real bodies. Every + other method is `todo!()` so it returns `!` and trivially coerces to the + declared return type at the type checker; this is what lets the build pass + with no error variants and no SQL. + +--- + +## Connect signature + +Per ADR 0002 D2: + +```rust +pub async fn connect(url: &str, max_connections: u32) -> MemoryStoreResult; +pub async fn from_pool(pool: PgPool) -> MemoryStoreResult; +``` + +No `&dyn Embedder` argument. This deliberately differs from master plan 0002, +which predates the Phase 1 freeze. The pgvector-specific DDL +(`ALTER TABLE memories ALTER COLUMN embedding TYPE vector($N)`) does not run +inside `connect`; it runs inside `register_model(&ModelSignature)`, which the +caller invokes after `connect` returns. + +In this sub-plan `register_model` is `todo!()`. The real body lands in +`0002d-store-impl-bodies.md` after `0002c-migrations.md` ships the +`0001_init.up.sql` migration that creates the `memories` table with a +placeholder `embedding vector` column (no typmod), against which +`register_model` later runs the typmod stamp. + +--- + +## Error variant additions: deferred + +`MemoryStoreError` does NOT gain `Postgres(sqlx::Error)` or +`Migrate(sqlx::migrate::MigrateError)` in this sub-plan. + +The reason is mechanical: `todo!()` evaluates to the never type `!`, which +coerces to any `MemoryStoreResult` regardless of the error variants +available. With every method body a `todo!()`, the skeleton has no expression +that needs to convert a `sqlx::Error` or `sqlx::migrate::MigrateError` into +`MemoryStoreError`. Adding the variants here would mean adding the +`#[cfg(feature = "postgres-backend")]` and `#[from]` plumbing to +`memory_store.rs` with no consumer yet -- dead code at every level except the +enum definition itself. + +`0002d-store-impl-bodies.md` introduces both variants in the same commit that +turns the first `todo!()` into a real `sqlx::query!` call. That keeps the +diff to `memory_store.rs` next to the first usage site, which is easier to +review than adding variants ahead of need. + +For reference, the variants that will be added in `0002d-store-impl-bodies.md` +look like this: + +```rust +#[cfg(feature = "postgres-backend")] +#[error("postgres error: {0}")] +Postgres(#[from] sqlx::Error), + +#[cfg(feature = "postgres-backend")] +#[error("postgres migration error: {0}")] +Migrate(#[from] sqlx::migrate::MigrateError), +``` + +Do not pre-add them here. + +--- + +## Verification + +Run these commands from the workspace root. All four must produce a clean +build, zero warnings on the diff-affected files, no test changes. + +```bash +# 1. Default features (SQLite backend, postgres-backend OFF). Must build. +cargo build --workspace --all-targets + +# 2. Workspace clippy with default features. Must be clean. +cargo clippy --workspace --all-targets -- -D warnings + +# 3. Postgres feature enabled. Must build. +cargo build -p vestige-core --features postgres-backend + +# 4. Clippy with postgres feature enabled. Must be clean. +cargo clippy -p vestige-core --features postgres-backend --all-targets -- -D warnings +``` + +Expected outcomes: + +- `cargo build --workspace --all-targets` finishes with no compilation of + `sqlx` or `pgvector` (both are optional, no consumer with default features). + The `postgres` module is excluded entirely via `#[cfg]`. +- `cargo build -p vestige-core --features postgres-backend` compiles `sqlx`, + `pgvector`, and `storage/postgres/mod.rs`. The build succeeds because every + trait method is `todo!()`; nothing actually runs SQL. +- Both `clippy` invocations pass with `-D warnings`. The `todo!()` macro does + not emit a `dead_code` lint by itself, and the trivial accessors are used by + later sub-plans (clippy on the postgres feature alone may flag them as + unused if you run with `--lib` only; the `--all-targets` form keeps tests + and benches in scope so this does not fire). +- If clippy flags `unused_variables` on the underscore-prefixed parameters in + the `todo!()` bodies, the underscore prefix is already the standard + suppression; if a future clippy version disagrees, add + `#[allow(unused_variables)]` to the impl block, not to each method. + +Tests are not modified in this sub-plan. The unit tests in +`memory_store.rs` (`memory_store_error_from_storage_error`, +`model_signature_serde_round_trip`, `memory_record_serde_round_trip`) keep +passing because no type they touch changes. + +Do NOT run `cargo test` against the postgres feature -- there is no Postgres +running and no test exercises `PgMemoryStore` yet. The build check is the +contract. + +--- + +## Acceptance criteria + +1. `crates/vestige-core/Cargo.toml` declares `sqlx = "0.8"` and + `pgvector = "0.4"` as optional dependencies with the exact feature sets + specified above. +2. `crates/vestige-core/Cargo.toml` declares `postgres-backend = ["dep:sqlx", + "dep:pgvector"]` and nothing else inside that feature. +3. `crates/vestige-mcp/Cargo.toml` is unchanged. +4. `crates/vestige-core/src/storage/mod.rs` adds exactly two + feature-gated lines: `mod postgres;` and `pub use postgres::PgMemoryStore;`. + No other change. +5. `crates/vestige-core/src/storage/postgres/mod.rs` exists and contains the + `PgMemoryStore` struct, `impl PgMemoryStore` block with real `pool` and + `embedding_dim` accessors and `todo!()` bodies for `connect` and + `from_pool`, and the full `impl LocalMemoryStore for PgMemoryStore` block + with `todo!()` for every trait method. +6. The trait impl method signatures match `memory_store.rs` byte-for-byte + (including `remove_edge(&self, source: Uuid, target: Uuid)` two-arg form, + not the three-arg form from the master plan). +7. `MemoryStoreError` is unchanged. +8. No other files in the crate are touched. No new files in + `storage/postgres/` besides `mod.rs`. +9. The four verification commands above all succeed. + +--- + +## Commit sequence + +One commit is recommended. The two changes (Cargo manifest + module skeleton) +do not compile in isolation: the manifest change without the skeleton produces +unused-optional-dep warnings, and the skeleton without the manifest change +fails to find `sqlx`. Splitting them adds no review value, since the second +commit is the one that has to compile cleanly. + +```bash +git add crates/vestige-core/Cargo.toml \ + crates/vestige-core/Cargo.lock \ + crates/vestige-core/src/storage/mod.rs \ + crates/vestige-core/src/storage/postgres/mod.rs + +git commit -m "feat(storage): scaffold postgres-backend feature and PgMemoryStore skeleton + +Adds the postgres-backend Cargo feature gating sqlx 0.8 and pgvector 0.4. +Introduces crates/vestige-core/src/storage/postgres/mod.rs with the +PgMemoryStore struct, connect/from_pool/pool/embedding_dim, and a trait impl +whose method bodies are todo!() pending later Phase 2 sub-plans. + +Builds clean with default features (SQLite only) and with --features +postgres-backend. No runtime behaviour change. + +Refs ADR 0002 D1, D2, D4." +``` + +If for any reason the manifest change must be reviewed separately (for +example, a security review of the sqlx version pin), split as: + +1. `cargo add` for sqlx and pgvector + manual feature line in Cargo.toml. + Build with default features will pass but `--features postgres-backend` + will fail (no module to satisfy the feature). This is acceptable for a + short-lived intermediate commit. +2. `storage/mod.rs` edits + `storage/postgres/mod.rs` creation. Both builds + pass. + +Default to the single-commit form unless asked to split. + +--- + +## Followups + +- `0002b-pool-and-config.md` adds `pool.rs`, `PostgresConfig`, and the + `vestige-mcp` `postgres-backend` pass-through feature. +- `0002c-migrations.md` adds `crates/vestige-core/migrations/postgres/` with + `0001_init.{up,down}.sql` and `0002_hnsw.{up,down}.sql`, plus + `postgres/migrations.rs` invoking `sqlx::migrate!`. `init()` body lands here. +- `0002d-store-impl-bodies.md` introduces the two `MemoryStoreError` variants + and replaces every `todo!()` in CRUD / scheduling / edges / domains / + registry with real `sqlx::query!` bodies. +- `0002e-hybrid-search.md` fills the three search bodies via the RRF query. diff --git a/docs/plans/0002b-pool-and-config.md b/docs/plans/0002b-pool-and-config.md new file mode 100644 index 0000000..9941413 --- /dev/null +++ b/docs/plans/0002b-pool-and-config.md @@ -0,0 +1,886 @@ +# Sub-plan 0002b -- Pool construction and VestigeConfig + +**Status**: Draft +**Master plan**: [0002-phase-2-postgres-backend.md](0002-phase-2-postgres-backend.md) +**ADR**: [0002-phase-2-execution.md](../adr/0002-phase-2-execution.md) +**Predecessor**: [0002a-skeleton-and-feature-gate.md](0002a-skeleton-and-feature-gate.md) + +--- + +## Context + +This sub-plan delivers two of the master plan's deliverables now that the +`0002a` skeleton has landed: + +- **D3** -- pool construction in + `crates/vestige-core/src/storage/postgres/pool.rs`. Replaces the `todo!()` + body of `PgMemoryStore::connect` with a real `PgPool` builder that reads a + `PostgresConfig`. Registry/migration calls remain `todo!()`; those are + filled in by sub-plans `0002c` (migrations) and `0002d` (store bodies + + registry). +- **D7** -- new module `crates/vestige-core/src/config.rs` containing + `VestigeConfig`, `StorageConfig`, `SqliteConfig`, `PostgresConfig`, + `EmbeddingsConfig`, plus a `ConfigError` enum and a loader that reads + `vestige.toml`. The loader is wired into `vestige-mcp` so the running + server picks SQLite or Postgres at startup based on the config file. + +After this sub-plan: + +- `cargo build` (default features, no `postgres-backend`) compiles and the + MCP server still defaults to SQLite when no `vestige.toml` is present. +- `cargo build --features postgres-backend` compiles, with + `PgMemoryStore::connect` now wiring through `pool.rs` (registry/migration + still `todo!()` until `0002c` and `0002d`). +- A `vestige.toml` example can be round-tripped through + `VestigeConfig::load` in a unit test. + +This sub-plan deliberately does NOT: + +- Add migrations (`0002c`). +- Fill in real CRUD/search bodies on `PgMemoryStore` (`0002d`, `0002e`). +- Add env-var override support (Phase 3 concern, called out in master plan + D7 behaviour notes). + +--- + +## Dependencies + +- `0002a-skeleton-and-feature-gate.md` must be merged. That sub-plan creates + `crates/vestige-core/src/storage/postgres/mod.rs` with: + - `PgMemoryStore` struct holding `pool: PgPool`. + - `PgMemoryStore::connect(url: &str, max_connections: u32) -> MemoryStoreResult` + body = `todo!()`. + - `PgMemoryStore::from_pool(pool: PgPool) -> MemoryStoreResult` + body = `todo!()`. + - The trait impl block with all methods routed to `todo!()`. + - The `postgres-backend` feature gate on the module declaration in + `storage/mod.rs`. + +This sub-plan extends those bodies and adds two siblings: `pool.rs` and +`registry.rs` (the latter is a stub here, real body in `0002d`). + +--- + +## Audit step (do this first) + +Before adding `config.rs`, confirm there is no existing top-level config +loader. Run from the repo root: + +```bash +rg -nF 'VestigeConfig' crates/ +rg -nF 'toml::from_str' crates/ +rg -n '#\[derive.*Deserialize.*\]' crates/vestige-core/src/ +``` + +If a `VestigeConfig` struct already exists from Phase 1, treat the "Config +module" section below as additive: extend the existing struct rather than +creating a new file. The cross-cut additions in that case are: + +1. Add the `StorageConfig` enum (gated and ungated branches). +2. Add `SqliteConfig`, `PostgresConfig`. +3. Add the `default_path()` helper if missing. +4. Add `ConfigError` if a different error enum is used today (rename/extend + instead of duplicating). + +As of the audit at the time of this writing, no `VestigeConfig` exists in +`vestige-core`. `directories::ProjectDirs` is already used in +`vestige-core/src/embeddings/local.rs` and in +`vestige-mcp/src/protocol/auth.rs`, so the `directories` crate is already a +workspace dependency -- no new dep there. + +--- + +## Cargo manifest additions + +Add `toml` to `vestige-core`. `serde` and `thiserror` are already present +from Phase 1; `directories` is already a transitive dep but we add it +explicitly so `default_path()` is supported. + +```bash +cd crates/vestige-core +cargo add toml@0.8 +cargo add directories@5 +``` + +No new deps on `vestige-mcp`; it already depends on `vestige-core`. + +`sqlx` is already added by `0002a` behind the `postgres-backend` feature +with `runtime-tokio`, `tls-rustls`, `postgres`, `uuid`, `chrono`, +`json`, `macros`, `migrate` features. The pool module only uses what is +already pulled in. + +--- + +## Config module + +**File**: `crates/vestige-core/src/config.rs` (new). +**Re-exported** from `crates/vestige-core/src/lib.rs` as `pub mod config;` plus +`pub use config::{VestigeConfig, StorageConfig, SqliteConfig, EmbeddingsConfig, ConfigError};` +and `#[cfg(feature = "postgres-backend")] pub use config::PostgresConfig;`. + +Full content: + +```rust +//! Vestige top-level configuration. +//! +//! Loaded from `~/.vestige/vestige.toml` by default; the path is overridable +//! via `VestigeConfig::load(Some(&path))`. Parsing uses serde + toml; the +//! `[storage]` section is internally-tagged on a `backend` field so a single +//! enum dispatch picks SQLite or Postgres. + +use std::path::{Path, PathBuf}; + +use serde::Deserialize; + +/// Top-level configuration as parsed from `vestige.toml`. +#[derive(Debug, Clone, Deserialize, Default)] +#[serde(default, deny_unknown_fields)] +pub struct VestigeConfig { + pub embeddings: EmbeddingsConfig, + pub storage: StorageConfig, + /// Reserved for Phase 3. Empty in Phase 2. + pub server: ServerConfig, + /// Reserved for Phase 3. Empty in Phase 2. + pub auth: AuthConfig, +} + +/// Embedding provider selection. +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct EmbeddingsConfig { + /// Provider key. Phase 2 ships `"fastembed"` only. + pub provider: String, + /// Model name. For fastembed this is e.g. `"nomic-ai/nomic-embed-text-v1.5"`. + pub model: String, +} + +impl Default for EmbeddingsConfig { + fn default() -> Self { + Self { + provider: "fastembed".to_string(), + model: crate::DEFAULT_EMBEDDING_MODEL.to_string(), + } + } +} + +/// Storage backend selection. Internally tagged on the `backend` field: +/// +/// ```toml +/// [storage] +/// backend = "sqlite" +/// +/// [storage.sqlite] +/// path = "/home/user/.vestige/vestige.db" +/// ``` +/// +/// or, when compiled with `--features postgres-backend`: +/// +/// ```toml +/// [storage] +/// backend = "postgres" +/// +/// [storage.postgres] +/// url = "postgres://vestige:secret@localhost:5432/vestige" +/// max_connections = 10 +/// acquire_timeout_secs = 30 +/// ``` +#[derive(Debug, Clone, Deserialize)] +#[serde(tag = "backend", rename_all = "lowercase", deny_unknown_fields)] +pub enum StorageConfig { + Sqlite(SqliteConfig), + #[cfg(feature = "postgres-backend")] + Postgres(PostgresConfig), +} + +impl Default for StorageConfig { + fn default() -> Self { + StorageConfig::Sqlite(SqliteConfig::default()) + } +} + +/// SQLite backend configuration. +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct SqliteConfig { + /// Path to the `vestige.db` file. If unset, the SqliteMemoryStore + /// constructor picks its platform default location. + #[serde(default)] + pub path: Option, +} + +impl Default for SqliteConfig { + fn default() -> Self { + Self { path: None } + } +} + +/// Postgres backend configuration. Only present when the `postgres-backend` +/// Cargo feature is enabled. +#[cfg(feature = "postgres-backend")] +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PostgresConfig { + /// `postgres://user:pass@host:port/db` -- forwarded to + /// `PgConnectOptions::from_str`. + pub url: String, + /// Pool size. Default `10`. + #[serde(default)] + pub max_connections: Option, + /// Acquire timeout in seconds. Default `30`. Set above 30 so + /// testcontainer-based test fixtures do not race. + #[serde(default)] + pub acquire_timeout_secs: Option, +} + +/// Reserved for Phase 3 (bind address, ports, TLS). +#[derive(Debug, Clone, Default, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct ServerConfig {} + +/// Reserved for Phase 3 (API keys, claims). +#[derive(Debug, Clone, Default, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct AuthConfig {} + +/// Errors raised while locating, reading, or parsing `vestige.toml`. +#[derive(Debug, thiserror::Error)] +pub enum ConfigError { + #[error("config io: {0}")] + Io(#[from] std::io::Error), + #[error("config toml: {0}")] + Toml(#[from] toml::de::Error), + #[error("config dir: could not locate user home")] + NoHome, + #[error("invalid config: {0}")] + Invalid(String), +} + +impl VestigeConfig { + /// Load config from `path` or from `default_path()` when `None`. + /// + /// Returns `VestigeConfig::default()` (SQLite + fastembed defaults) when + /// the file does not exist. Any other I/O or parse failure is surfaced + /// as a `ConfigError`. + pub fn load(path: Option<&Path>) -> Result { + let resolved: PathBuf = match path { + Some(p) => p.to_path_buf(), + None => Self::default_path()?, + }; + + match std::fs::read_to_string(&resolved) { + Ok(text) => { + let cfg: VestigeConfig = toml::from_str(&text)?; + cfg.validate()?; + Ok(cfg) + } + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + Ok(Self::default()) + } + Err(e) => Err(ConfigError::Io(e)), + } + } + + /// `~/.vestige/vestige.toml`. The directory is NOT created here; loading + /// a missing file falls back to defaults. + pub fn default_path() -> Result { + let dirs = directories::ProjectDirs::from("", "vestige", "vestige") + .ok_or(ConfigError::NoHome)?; + // ProjectDirs::config_dir() varies per OS. Vestige convention is + // ~/.vestige/vestige.toml on Linux/macOS regardless of XDG, so we + // build the path off the home dir explicitly. + let home = directories::UserDirs::new() + .ok_or(ConfigError::NoHome)? + .home_dir() + .to_path_buf(); + let _ = dirs; // keep the dep wired; future Phase 3 may use it + Ok(home.join(".vestige").join("vestige.toml")) + } + + /// Light cross-field validation. Heavy validation (URL parsing, + /// directory existence) is left to the backend constructors. + fn validate(&self) -> Result<(), ConfigError> { + if self.embeddings.provider.is_empty() { + return Err(ConfigError::Invalid( + "embeddings.provider must not be empty".into(), + )); + } + if self.embeddings.model.is_empty() { + return Err(ConfigError::Invalid( + "embeddings.model must not be empty".into(), + )); + } + match &self.storage { + StorageConfig::Sqlite(_) => {} + #[cfg(feature = "postgres-backend")] + StorageConfig::Postgres(cfg) => { + if cfg.url.is_empty() { + return Err(ConfigError::Invalid( + "storage.postgres.url must not be empty".into(), + )); + } + } + } + Ok(()) + } +} +``` + +### Serde behaviour with `postgres-backend` off + +`StorageConfig` is generated by serde only for the variants that are +compiled in. When `postgres-backend` is off and the user writes: + +```toml +[storage] +backend = "postgres" + +[storage.postgres] +url = "..." +``` + +serde returns a `toml::de::Error` of the form +`unknown variant `postgres`, expected `sqlite``. That error path goes +through `From for ConfigError`, surfacing as +`ConfigError::Toml(..)`. The MCP server prints this once at startup and +exits with a non-zero code; there is no panic. + +To make the error friendlier we wrap that specific case in a clearer +message via a thin post-parse check. Add this small helper after parsing +in `load()`: + +```rust +// (Inside the Ok(text) arm in load(), wrapping the parse step.) +let cfg: VestigeConfig = match toml::from_str(&text) { + Ok(c) => c, + Err(e) => { + let msg = e.to_string(); + if msg.contains("unknown variant `postgres`") { + return Err(ConfigError::Invalid( + "storage.backend = \"postgres\" requires building with --features postgres-backend".into(), + )); + } + return Err(ConfigError::Toml(e)); + } +}; +``` + +This keeps the strict default deny_unknown_fields behaviour while giving the +user a one-line action item. + +--- + +## Pool module + +**File**: `crates/vestige-core/src/storage/postgres/pool.rs` (new). + +```rust +#![cfg(feature = "postgres-backend")] + +//! `PgPool` construction for the Postgres backend. +//! +//! Pool defaults follow ADR 0002 D2 + master plan D3: +//! - max_connections = 10 +//! - acquire_timeout = 30s (must exceed testcontainer warmup) +//! - idle_timeout = 600s +//! - max_lifetime = 1800s +//! - test_before_acquire = false (cheap queries; saves a roundtrip) + +use std::str::FromStr; +use std::time::Duration; + +use sqlx::postgres::{PgConnectOptions, PgPoolOptions}; +use sqlx::{ConnectOptions, PgPool}; + +use crate::config::PostgresConfig; +use crate::storage::memory_store::{MemoryStoreError, MemoryStoreResult}; + +const DEFAULT_MAX_CONNECTIONS: u32 = 10; +const DEFAULT_ACQUIRE_TIMEOUT_SECS: u64 = 30; +const IDLE_TIMEOUT_SECS: u64 = 600; +const MAX_LIFETIME_SECS: u64 = 1800; +const STATEMENT_CACHE_CAPACITY: usize = 256; + +/// Build a Postgres connection pool from a `PostgresConfig`. Does NOT run +/// migrations or stamp the embedding registry; those are the caller's job +/// (`PgMemoryStore::connect`). +pub async fn build_pool(cfg: &PostgresConfig) -> MemoryStoreResult { + let opts = PgConnectOptions::from_str(&cfg.url) + .map_err(MemoryStoreError::from)? + .application_name("vestige") + .statement_cache_capacity(STATEMENT_CACHE_CAPACITY) + .log_statements(tracing::log::LevelFilter::Debug); + + let max_conn = cfg.max_connections.unwrap_or(DEFAULT_MAX_CONNECTIONS); + let acquire = cfg + .acquire_timeout_secs + .unwrap_or(DEFAULT_ACQUIRE_TIMEOUT_SECS); + + let pool = PgPoolOptions::new() + .max_connections(max_conn) + .min_connections(0) + .acquire_timeout(Duration::from_secs(acquire)) + .idle_timeout(Some(Duration::from_secs(IDLE_TIMEOUT_SECS))) + .max_lifetime(Some(Duration::from_secs(MAX_LIFETIME_SECS))) + .test_before_acquire(false) + .connect_with(opts) + .await + .map_err(MemoryStoreError::from)?; + + Ok(pool) +} +``` + +### Wiring into `PgMemoryStore::connect` + +In `crates/vestige-core/src/storage/postgres/mod.rs`, replace the +`todo!()` body left by `0002a` for `connect` and `from_pool` with: + +```rust +// In crates/vestige-core/src/storage/postgres/mod.rs + +use sqlx::PgPool; + +use crate::config::PostgresConfig; +use crate::storage::memory_store::{MemoryStoreError, MemoryStoreResult}; + +mod pool; +mod registry; // see "Registry stub" section below + +pub struct PgMemoryStore { + pool: PgPool, +} + +impl PgMemoryStore { + /// Convenience constructor matching `SqliteMemoryStore::new` shape. + /// Takes a URL + pool size for the common case. + pub async fn connect(url: &str, max_connections: u32) -> MemoryStoreResult { + let cfg = PostgresConfig { + url: url.to_string(), + max_connections: Some(max_connections), + acquire_timeout_secs: None, + }; + Self::connect_with(&cfg).await + } + + /// Full-config constructor. + pub async fn connect_with(cfg: &PostgresConfig) -> MemoryStoreResult { + let pool = pool::build_pool(cfg).await?; + Self::from_pool(pool).await + } + + /// Construct from an already-built pool (used by tests and the migrate + /// CLI to share a pool across operations). + pub async fn from_pool(pool: PgPool) -> MemoryStoreResult { + // Migrations are added by 0002c. + // todo!("run sqlx::migrate! once 0002c lands") + registry::ensure_registry_stub(&pool).await?; + Ok(Self { pool }) + } +} +``` + +`connect_with` is the long-lived API; `connect` becomes a thin shim that +stays compatible with the master-plan-mandated signature. + +### Registry stub + +**File**: `crates/vestige-core/src/storage/postgres/registry.rs` (new, stub). + +```rust +#![cfg(feature = "postgres-backend")] + +//! Embedding registry. Real body lands in sub-plan 0002d. + +use sqlx::PgPool; + +use crate::storage::memory_store::MemoryStoreResult; + +/// Placeholder. Real implementation in 0002d reads/writes `embedding_model` +/// and stamps `ALTER TABLE memories ALTER COLUMN embedding TYPE vector($N)`. +pub(crate) async fn ensure_registry_stub(_pool: &PgPool) -> MemoryStoreResult<()> { + // Intentionally a no-op until 0002c lands the table + 0002d lands the + // real body. Leaving this as todo!() would crash the MCP server at + // startup the moment a user switches `backend = "postgres"`, which is + // not what we want for the build verification step in this sub-plan. + Ok(()) +} +``` + +The no-op keeps `cargo build --features postgres-backend` not just +compiling but also allowing the MCP server to *boot* against a Postgres +URL pointing at an already-migrated database (the local-dev-postgres-setup +docs cover bringing up such a DB by hand). Real init lands in `0002d`. + +--- + +## Error variants + +**File**: `crates/vestige-core/src/storage/memory_store.rs` (edit). + +The Phase 1 enum `MemoryStoreError` gains two feature-gated variants. These +were deferred in `0002a` and become required as soon as `pool.rs` calls +`.map_err(MemoryStoreError::from)` on `sqlx::Error`. + +```rust +// Within enum MemoryStoreError { ... } in memory_store.rs + +#[cfg(feature = "postgres-backend")] +#[error("postgres error: {0}")] +Postgres(#[from] sqlx::Error), + +#[cfg(feature = "postgres-backend")] +#[error("postgres migration error: {0}")] +Migrate(#[from] sqlx::migrate::MigrateError), +``` + +Both use thiserror's `#[from]` attribute so the `?` operator works in +`pool.rs`, the migrate module (`0002c`), and registry code (`0002d`). +Default-features build (no `postgres-backend`) sees neither variant; the +enum stays exhaustive on stable. + +If clippy fires on `non_exhaustive` due to the gated variants, add +`#[non_exhaustive]` on the enum. That has no caller-side effect since the +enum is constructed only inside the crate. + +--- + +## vestige-mcp wiring + +### Cargo feature passthrough + +**File**: `crates/vestige-mcp/Cargo.toml` (edit). + +Add a feature that forwards through to `vestige-core`. Default features in +`vestige-mcp` stay unchanged. + +```toml +[features] +default = ["embeddings", "vector-search"] +embeddings = ["vestige-core/embeddings"] +vector-search = ["vestige-core/vector-search"] +postgres-backend = ["vestige-core/postgres-backend"] +``` + +Verify with: + +```bash +cargo build -p vestige-mcp --features postgres-backend +``` + +### Backend dispatch at startup + +**File**: `crates/vestige-mcp/src/main.rs` (edit around the existing +`Storage::new(storage_path)` call -- see audit note above; in the current +worktree this is around line 285). + +The current code is roughly: + +```rust +let storage_path = match prepare_storage_path(config.data_dir) { ... }; +let storage = match Storage::new(storage_path) { ... }; +``` + +Replace that with a dispatch driven by `VestigeConfig`: + +```rust +use std::sync::Arc; + +use vestige_core::config::{StorageConfig, VestigeConfig}; +use vestige_core::storage::SqliteMemoryStore; +#[cfg(feature = "postgres-backend")] +use vestige_core::storage::postgres::PgMemoryStore; +use vestige_core::storage::MemoryStore; + +// Earlier: still call prepare_storage_path to honour --data-dir override. +let storage_path = match prepare_storage_path(config.data_dir.clone()) { ... }; + +// New: load vestige.toml (or fall back to defaults). +let vestige_cfg = match VestigeConfig::load(config.config_path.as_deref()) { + Ok(c) => c, + Err(e) => { + eprintln!("vestige: failed to load config: {e}"); + std::process::exit(2); + } +}; + +let storage: Arc = match &vestige_cfg.storage { + StorageConfig::Sqlite(sqlite_cfg) => { + // CLI flag --data-dir wins over the config file path. + let path = storage_path.clone().or_else(|| sqlite_cfg.path.clone()); + let s = SqliteMemoryStore::new(path).unwrap_or_else(|e| { + eprintln!("vestige: sqlite init failed: {e}"); + std::process::exit(3); + }); + Arc::new(s) + } + #[cfg(feature = "postgres-backend")] + StorageConfig::Postgres(pg_cfg) => { + let s = PgMemoryStore::connect_with(pg_cfg).await.unwrap_or_else(|e| { + eprintln!("vestige: postgres init failed: {e}"); + std::process::exit(3); + }); + Arc::new(s) + } +}; +``` + +The `config_path: Option` field on the local `Config` (or +clap-derived `Args`) struct must be added if not present; it accepts +`--config `. Default behaviour (no flag) goes through +`VestigeConfig::default_path()`. + +If the existing main wires `Storage` through a concrete type rather than +`Arc`, the dispatch above lives behind a helper: + +```rust +async fn build_store(cfg: &VestigeConfig, cli_path: Option) + -> Result, anyhow::Error> +{ ... } +``` + +and the caller chains `.into()` as needed. Phase 1 already moved +cognitive modules to `Arc` so this should be a pure +substitution; if a concrete-type holdout is found, fix it locally in this +sub-plan (separate commit) rather than punting. + +--- + +## vestige.toml example + +The canonical example to ship in `docs/` (Phase 2 docs land in `0002i`, +runbook), shown here for reference and used verbatim by the unit test +below. + +```toml +# vestige.toml -- top-level configuration +# +# Default location: ~/.vestige/vestige.toml +# Override: vestige-mcp --config /path/to/vestige.toml + +[embeddings] +provider = "fastembed" +model = "nomic-ai/nomic-embed-text-v1.5" + +# --- SQLite backend (default) --- +[storage] +backend = "sqlite" + +[storage.sqlite] +path = "/home/user/.vestige/vestige.db" + +# --- Postgres backend (requires --features postgres-backend) --- +# [storage] +# backend = "postgres" +# +# [storage.postgres] +# url = "postgres://vestige:secret@localhost:5432/vestige" +# max_connections = 10 +# acquire_timeout_secs = 30 + +[server] +# Reserved for Phase 3 (bind address, ports, TLS). + +[auth] +# Reserved for Phase 3 (API keys, claims). +``` + +--- + +## Verification + +Run all of these from the repo root. The first three are the gates that +must pass before this sub-plan is considered done. + +### 1. Default build (no Postgres) + +```bash +cargo build -p vestige-core +cargo build -p vestige-mcp +cargo test -p vestige-core --lib +``` + +Expected: clean build. `VestigeConfig::default()` selects SQLite; the MCP +server boots the same way it did pre-sub-plan. + +### 2. Postgres-feature build + +```bash +cargo build -p vestige-core --features postgres-backend +cargo build -p vestige-mcp --features postgres-backend +``` + +Expected: clean build. `PgMemoryStore::connect_with` resolves to +`pool::build_pool` + `registry::ensure_registry_stub`; no `todo!()` is +reachable on the build path. `connect` and `from_pool` are exported. + +### 3. Clippy across both feature sets + +```bash +cargo clippy -p vestige-core -- -D warnings +cargo clippy -p vestige-core --features postgres-backend -- -D warnings +cargo clippy -p vestige-mcp --features postgres-backend -- -D warnings +``` + +### 4. Unit test: round-trip the example + +Add this test to `crates/vestige-core/src/config.rs`: + +```rust +#[cfg(test)] +mod tests { + use super::*; + + const EXAMPLE_SQLITE: &str = r#" +[embeddings] +provider = "fastembed" +model = "nomic-ai/nomic-embed-text-v1.5" + +[storage] +backend = "sqlite" + +[storage.sqlite] +path = "/home/user/.vestige/vestige.db" +"#; + + #[cfg(feature = "postgres-backend")] + const EXAMPLE_POSTGRES: &str = r#" +[embeddings] +provider = "fastembed" +model = "nomic-ai/nomic-embed-text-v1.5" + +[storage] +backend = "postgres" + +[storage.postgres] +url = "postgres://vestige:secret@localhost:5432/vestige" +max_connections = 10 +acquire_timeout_secs = 30 +"#; + + #[test] + fn parses_sqlite_example() { + let cfg: VestigeConfig = toml::from_str(EXAMPLE_SQLITE).expect("parse"); + match cfg.storage { + StorageConfig::Sqlite(s) => assert!(s.path.is_some()), + #[cfg(feature = "postgres-backend")] + StorageConfig::Postgres(_) => panic!("wrong variant"), + } + assert_eq!(cfg.embeddings.provider, "fastembed"); + } + + #[cfg(feature = "postgres-backend")] + #[test] + fn parses_postgres_example() { + let cfg: VestigeConfig = toml::from_str(EXAMPLE_POSTGRES).expect("parse"); + match cfg.storage { + StorageConfig::Postgres(p) => { + assert_eq!(p.url, "postgres://vestige:secret@localhost:5432/vestige"); + assert_eq!(p.max_connections, Some(10)); + assert_eq!(p.acquire_timeout_secs, Some(30)); + } + StorageConfig::Sqlite(_) => panic!("wrong variant"), + } + } + + #[cfg(not(feature = "postgres-backend"))] + #[test] + fn rejects_postgres_when_feature_off() { + let toml_text = r#" +[storage] +backend = "postgres" + +[storage.postgres] +url = "postgres://x/y" +"#; + let res: Result = toml::from_str(toml_text); + assert!(res.is_err(), "must fail without postgres-backend feature"); + } + + #[test] + fn defaults_pick_sqlite() { + let cfg = VestigeConfig::default(); + assert!(matches!(cfg.storage, StorageConfig::Sqlite(_))); + } + + #[test] + fn load_missing_file_returns_default() { + let tmp = std::env::temp_dir().join("vestige-no-such-file.toml"); + let _ = std::fs::remove_file(&tmp); + let cfg = VestigeConfig::load(Some(&tmp)).expect("missing file is OK"); + assert!(matches!(cfg.storage, StorageConfig::Sqlite(_))); + } + + #[test] + fn load_roundtrip_from_disk() { + let tmp = std::env::temp_dir().join("vestige-roundtrip.toml"); + std::fs::write(&tmp, EXAMPLE_SQLITE).unwrap(); + let cfg = VestigeConfig::load(Some(&tmp)).expect("load"); + assert!(matches!(cfg.storage, StorageConfig::Sqlite(_))); + let _ = std::fs::remove_file(&tmp); + } +} +``` + +Run: + +```bash +cargo test -p vestige-core --lib config:: +cargo test -p vestige-core --lib config:: --features postgres-backend +``` + +### 5. Smoke: server boots with default config + +```bash +# default build, no vestige.toml on disk +cargo run -p vestige-mcp -- --help +# should print help, no panic +``` + +--- + +## Acceptance criteria + +- [ ] `cargo build -p vestige-core` (default features) succeeds. +- [ ] `cargo build -p vestige-core --features postgres-backend` succeeds. +- [ ] `cargo build -p vestige-mcp` (default features) succeeds. +- [ ] `cargo build -p vestige-mcp --features postgres-backend` succeeds. +- [ ] `cargo clippy` with and without `postgres-backend` is clean on both + crates. +- [ ] `crates/vestige-core/src/config.rs` exists, exposes + `VestigeConfig`, `StorageConfig`, `SqliteConfig`, `EmbeddingsConfig`, + `ConfigError`, plus `PostgresConfig` when the feature is on. +- [ ] `VestigeConfig::load(None)` returns `Ok(default)` when + `~/.vestige/vestige.toml` is missing. +- [ ] `VestigeConfig::load(Some(&path))` round-trips both the SQLite and + Postgres example blocks above. +- [ ] With `postgres-backend` off, parsing `backend = "postgres"` returns + a clear `ConfigError::Invalid` mentioning the feature flag, NOT a + panic. +- [ ] `crates/vestige-core/src/storage/postgres/pool.rs` exists, + implementing `build_pool(&PostgresConfig) -> MemoryStoreResult` + with the documented defaults. +- [ ] `PgMemoryStore::connect`, `connect_with`, and `from_pool` all wire + through `pool::build_pool`. None of them is `todo!()`. The registry + step is a no-op stub documented as filled in by `0002d`. +- [ ] `MemoryStoreError::Postgres(sqlx::Error)` and + `MemoryStoreError::Migrate(sqlx::migrate::MigrateError)` exist + behind `#[cfg(feature = "postgres-backend")]` with `#[from]`. +- [ ] `vestige-mcp` has a `postgres-backend` feature that forwards to + `vestige-core/postgres-backend`. +- [ ] `vestige-mcp/src/main.rs` selects SQLite vs Postgres at startup + based on `VestigeConfig`. SQLite is the default when no config file + is present. +- [ ] Unit tests in the "Verification" section pass on both feature sets. + +--- + +## Out of scope (handled by other sub-plans) + +- Migrations (`crates/vestige-core/migrations/postgres/*.sql`) -- `0002c`. +- Real `PgMemoryStore` CRUD/search/scheduling/edges bodies -- `0002d`, + `0002e`. +- `ensure_registry` real body with `ALTER COLUMN TYPE vector(N)` -- `0002d`. +- `vestige migrate --from sqlite --to postgres` CLI -- `0002f`. +- Re-embed flow -- `0002g`. +- Env-var override (`VESTIGE_POSTGRES_URL`, etc.) -- Phase 3. +- RLS, multi-tenant column population -- Phase 3. diff --git a/docs/plans/0002c-migrations.md b/docs/plans/0002c-migrations.md new file mode 100644 index 0000000..ef8e35c --- /dev/null +++ b/docs/plans/0002c-migrations.md @@ -0,0 +1,1119 @@ +# Phase 2 Sub-plan 0002c: sqlx Migrations + +**Status**: Draft +**Depends on**: `0002a-skeleton-and-feature-gate.md` (PgMemoryStore skeleton, error variants), `0002b-pool-and-config.md` (PgPool builder, PostgresConfig) +**Related**: docs/adr/0002-phase-2-execution.md (D7 multi-tenancy reservation, D8 codebase column), docs/plans/0002-phase-2-postgres-backend.md (D4 master SQL), docs/plans/local-dev-postgres-setup.md (local cluster + role + DB) + +--- + +## Context + +This sub-plan covers Phase 2 deliverable D4 (sqlx migration files under +`crates/vestige-core/migrations/postgres/`) PLUS the schema additions decided +in ADR 0002: + +- D7 -- multi-tenancy reservation: `users`, `groups`, `group_memberships` + tables, plus `owner_user_id`, `visibility`, `shared_with_groups` columns on + `knowledge_nodes`. Phase 3 fills these in; Phase 2 just reserves them so the auth + filter is later additive instead of an online migration over a populated, + HNSW-indexed table. +- D8 -- `codebase` promoted to a first-class indexed column on `knowledge_nodes`. + +This sub-plan also adds the parity SQLite migration (V15) that mirrors D7 + +D8 on the SQLite side, so a single-user SQLite deployment sees the same +columns (with stand-in defaults). + +After this sub-plan lands: + +- A fresh Postgres database, with the `vestige` role from the local-dev + setup, can be initialized by running `sqlx::migrate!` against + `crates/vestige-core/migrations/postgres/`, plus one programmatic + `register_model` call before the HNSW migration. +- A fresh SQLite database initialized by `apply_migrations` lands at + schema_version = 15 with the new tables and columns present. +- `PgMemoryStore::connect` wires the migrator into the connect path + (pool build -> migrator up-to v1 -> register_model -> migrator up-to v2). +- The SQLite test suite continues to pass. +- No `sqlx::query!` calls are introduced yet; the offline `.sqlx/` cache is + filled out in `0002d-store-impl-bodies.md`. + +The deliverable is purely schema. No query bodies, no row-mapping, no search. + +--- + +## Postgres migration files + +Layout, relative to repo root: + +``` +crates/vestige-core/migrations/postgres/ + 0001_init.up.sql + 0001_init.down.sql + 0002_hnsw.up.sql + 0002_hnsw.down.sql +``` + +The `migrations/postgres/` directory is sibling-of-`src/`, not under `src/`, +because `sqlx::migrate!` and `sqlx-cli` both look for a path relative to +`CARGO_MANIFEST_DIR`. The directory is committed. + +### 0001_init.up.sql + +Creates extensions, the multi-tenancy tables (D7), the embedding registry, +the domains catalogue, the `knowledge_nodes` table (with D7 + D8 columns merged in), +the FSRS scheduling and edges tables, the review-events log, all non-vector +indexes, the updated_at trigger, and the bootstrap `local` user row. + +The HNSW vector index is deliberately NOT here -- it requires a typmod on +`knowledge_nodes.embedding`, which is stamped by `register_model` at runtime. See +the "HNSW typmod ordering" section below. + +```sql +-- crates/vestige-core/migrations/postgres/0001_init.up.sql +-- +-- Phase 2 initial schema for the Postgres backend. +-- Includes D7 multi-tenancy reservation (users/groups/group_memberships, +-- owner_user_id/visibility/shared_with_groups on knowledge_nodes) and D8 +-- (codebase first-class column on knowledge_nodes). +-- +-- The HNSW index on knowledge_nodes.embedding lives in 0002_hnsw.up.sql; it +-- requires the column typmod to be stamped first by register_model(). + +-- Extensions ---------------------------------------------------------------- + +CREATE EXTENSION IF NOT EXISTS pgcrypto; +CREATE EXTENSION IF NOT EXISTS vector; + +-- Embedding model registry -------------------------------------------------- +-- Mirrors the SQLite table created in Phase 1 V14. +-- One logical row enforced by CHECK (id = 1). + +CREATE TABLE embedding_model ( + id SMALLINT PRIMARY KEY DEFAULT 1 CHECK (id = 1), + name TEXT NOT NULL, + dimension INTEGER NOT NULL CHECK (dimension > 0), + hash TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +-- Domains catalogue --------------------------------------------------------- +-- Populated by the Phase 4 DomainClassifier. Phase 2 creates the empty +-- table so list/get/upsert/delete work uniformly against both backends. + +CREATE TABLE domains ( + id TEXT PRIMARY KEY, + label TEXT NOT NULL, + centroid vector, + top_terms TEXT[] NOT NULL DEFAULT '{}', + memory_count INTEGER NOT NULL DEFAULT 0, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + metadata JSONB NOT NULL DEFAULT '{}'::jsonb +); + +-- Multi-tenancy (D7) -------------------------------------------------------- +-- Reserved in Phase 2; populated in Phase 3. +-- Single bootstrap user inserted at the bottom of this file. + +CREATE TABLE users ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + handle TEXT NOT NULL UNIQUE, + display_name TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + metadata JSONB NOT NULL DEFAULT '{}'::jsonb +); + +CREATE TABLE groups ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + handle TEXT NOT NULL UNIQUE, + display_name TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + metadata JSONB NOT NULL DEFAULT '{}'::jsonb +); + +CREATE TABLE group_memberships ( + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + group_id UUID NOT NULL REFERENCES groups(id) ON DELETE CASCADE, + role TEXT NOT NULL DEFAULT 'member', + joined_at TIMESTAMPTZ NOT NULL DEFAULT now(), + PRIMARY KEY (user_id, group_id), + CHECK (role IN ('member', 'admin')) +); + +-- Core knowledge_nodes table ------------------------------------------------- +-- Original Phase 2 columns merged with D7 (owner_user_id, visibility, +-- shared_with_groups) and D8 (codebase). + +CREATE TABLE knowledge_nodes ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + + -- Content + content TEXT NOT NULL, + node_type TEXT NOT NULL DEFAULT 'general', + tags TEXT[] NOT NULL DEFAULT '{}', + metadata JSONB NOT NULL DEFAULT '{}'::jsonb, + + -- Phase 4 emergent domains (Phase 2 leaves empty) + domains TEXT[] NOT NULL DEFAULT '{}', + domain_scores JSONB NOT NULL DEFAULT '{}'::jsonb, + + -- Embedding (typmod stamped by register_model before 0002_hnsw runs) + embedding vector, + + -- D8: first-class codebase column for high-frequency scoped queries + codebase TEXT, + + -- D7: multi-tenancy reservation. Defaults make Phase 2 single-user + -- behaviour identical to Phase 1. + owner_user_id UUID NOT NULL DEFAULT '00000000-0000-0000-0000-000000000001' + REFERENCES users(id), + visibility TEXT NOT NULL DEFAULT 'private', + shared_with_groups UUID[] NOT NULL DEFAULT '{}', + + -- Timestamps + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + + -- Generated full-text search vector. Phase 2 uses websearch_to_tsquery + -- against this column at query time (see 0002e-hybrid-search.md). + search_vec TSVECTOR GENERATED ALWAYS AS ( + setweight(to_tsvector('english', coalesce(content, '')), 'A') || + setweight(to_tsvector('english', coalesce(node_type, '')), 'B') || + setweight(to_tsvector('english', coalesce(array_to_string(tags, ' '), '')), 'C') + ) STORED, + + -- Visibility tri-state CHECK constraint. See "Visibility CHECK + -- constraint" section below for the cardinality variant we + -- intentionally do NOT add yet. + CHECK (visibility IN ('private', 'group', 'public')) +); + +-- FSRS scheduling state (1:1 with knowledge_nodes) --------------------------- +-- +-- Note: the FK column is named `memory_id` (not `node_id`) to match the +-- Phase 1 SQLite trait surface: `SchedulingState { memory_id: Uuid, ... }` +-- and `get_scheduling(memory_id: Uuid)` / `update_scheduling(&state)`. The +-- table is `knowledge_nodes` but the Rust identifier remained `memory_id` +-- across Phase 1 and is preserved here so both backends speak the same +-- language at the trait boundary. + +CREATE TABLE scheduling ( + memory_id UUID PRIMARY KEY REFERENCES knowledge_nodes(id) ON DELETE CASCADE, + stability DOUBLE PRECISION NOT NULL DEFAULT 0.0, + difficulty DOUBLE PRECISION NOT NULL DEFAULT 0.0, + retrievability DOUBLE PRECISION NOT NULL DEFAULT 1.0, + last_review TIMESTAMPTZ, + next_review TIMESTAMPTZ, + reps INTEGER NOT NULL DEFAULT 0, + lapses INTEGER NOT NULL DEFAULT 0 +); + +-- Spreading activation graph edges ------------------------------------------ + +CREATE TABLE edges ( + source_id UUID NOT NULL REFERENCES knowledge_nodes(id) ON DELETE CASCADE, + target_id UUID NOT NULL REFERENCES knowledge_nodes(id) ON DELETE CASCADE, + edge_type TEXT NOT NULL DEFAULT 'related', + weight DOUBLE PRECISION NOT NULL DEFAULT 1.0, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + PRIMARY KEY (source_id, target_id, edge_type) +); + +-- FSRS review event log (append-only; Phase 5 federation reads) ------------- + +CREATE TABLE review_events ( + id BIGSERIAL PRIMARY KEY, + memory_id UUID NOT NULL REFERENCES knowledge_nodes(id) ON DELETE CASCADE, + timestamp TIMESTAMPTZ NOT NULL DEFAULT now(), + rating SMALLINT NOT NULL, + prior_state JSONB NOT NULL, + new_state JSONB NOT NULL +); + +-- Indexes ------------------------------------------------------------------- + +-- knowledge_nodes: full-text, arrays, hot scalar columns, D7+D8 access patterns +CREATE INDEX idx_knowledge_nodes_fts ON knowledge_nodes USING GIN (search_vec); +CREATE INDEX idx_knowledge_nodes_domains ON knowledge_nodes USING GIN (domains); +CREATE INDEX idx_knowledge_nodes_tags ON knowledge_nodes USING GIN (tags); +CREATE INDEX idx_knowledge_nodes_node_type ON knowledge_nodes (node_type); +CREATE INDEX idx_knowledge_nodes_created ON knowledge_nodes (created_at); +CREATE INDEX idx_knowledge_nodes_updated ON knowledge_nodes (updated_at); + +-- D7 visibility filter (Phase 3 query: WHERE owner_user_id = $me ...) +CREATE INDEX idx_knowledge_nodes_owner ON knowledge_nodes (owner_user_id); +CREATE INDEX idx_knowledge_nodes_shared_groups ON knowledge_nodes USING GIN (shared_with_groups); + +-- D8 codebase scoping (Phase 4 HDBSCAN per-repo, sharing rules in Phase 4). +-- Partial index keeps the index small in single-user mode where most rows +-- never set a codebase. +CREATE INDEX idx_knowledge_nodes_codebase + ON knowledge_nodes (codebase) + WHERE codebase IS NOT NULL; + +-- scheduling: hot lookup paths for FSRS pickers +CREATE INDEX idx_scheduling_next_review ON scheduling (next_review); +CREATE INDEX idx_scheduling_last_review ON scheduling (last_review); + +-- edges: bidirectional + edge type +CREATE INDEX idx_edges_target ON edges (target_id); +CREATE INDEX idx_edges_source ON edges (source_id); +CREATE INDEX idx_edges_type ON edges (edge_type); + +-- review_events: per-memory and chronological +CREATE INDEX idx_review_events_memory ON review_events (memory_id); +CREATE INDEX idx_review_events_ts ON review_events (timestamp); + +-- users / groups: unique handle indexes are implicit; add nothing extra. +-- group_memberships: primary key (user_id, group_id) is the access path. + +-- updated_at trigger on knowledge_nodes ---------------------------------------- + +CREATE OR REPLACE FUNCTION knowledge_nodes_set_updated_at() RETURNS TRIGGER AS $$ +BEGIN + NEW.updated_at := now(); + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_knowledge_nodes_updated_at +BEFORE UPDATE ON knowledge_nodes +FOR EACH ROW EXECUTE FUNCTION knowledge_nodes_set_updated_at(); + +-- Bootstrap rows ------------------------------------------------------------ +-- Single 'local' user matches the default on knowledge_nodes.owner_user_id so +-- single-user Phase 2 inserts never violate the FK. + +INSERT INTO users (id, handle, display_name) + VALUES ('00000000-0000-0000-0000-000000000001', 'local', 'Local User'); +``` + +### 0001_init.down.sql + +Reverse-dependency drop order. Trigger and function first, then indexes, +then tables, then extensions are left alone (extensions are global; we do +not drop them in a `down`). + +```sql +-- crates/vestige-core/migrations/postgres/0001_init.down.sql + +DROP TRIGGER IF EXISTS trg_knowledge_nodes_updated_at ON knowledge_nodes; +DROP FUNCTION IF EXISTS knowledge_nodes_set_updated_at(); + +-- knowledge_nodes indexes +DROP INDEX IF EXISTS idx_knowledge_nodes_codebase; +DROP INDEX IF EXISTS idx_knowledge_nodes_shared_groups; +DROP INDEX IF EXISTS idx_knowledge_nodes_owner; +DROP INDEX IF EXISTS idx_knowledge_nodes_updated; +DROP INDEX IF EXISTS idx_knowledge_nodes_created; +DROP INDEX IF EXISTS idx_knowledge_nodes_node_type; +DROP INDEX IF EXISTS idx_knowledge_nodes_tags; +DROP INDEX IF EXISTS idx_knowledge_nodes_domains; +DROP INDEX IF EXISTS idx_knowledge_nodes_fts; + +-- scheduling indexes +DROP INDEX IF EXISTS idx_scheduling_last_review; +DROP INDEX IF EXISTS idx_scheduling_next_review; + +-- edges indexes +DROP INDEX IF EXISTS idx_edges_type; +DROP INDEX IF EXISTS idx_edges_source; +DROP INDEX IF EXISTS idx_edges_target; + +-- review_events indexes +DROP INDEX IF EXISTS idx_review_events_ts; +DROP INDEX IF EXISTS idx_review_events_memory; + +-- Tables, reverse dependency order +DROP TABLE IF EXISTS review_events; +DROP TABLE IF EXISTS edges; +DROP TABLE IF EXISTS scheduling; +DROP TABLE IF EXISTS knowledge_nodes; +DROP TABLE IF EXISTS group_memberships; +DROP TABLE IF EXISTS groups; +DROP TABLE IF EXISTS users; +DROP TABLE IF EXISTS domains; +DROP TABLE IF EXISTS embedding_model; + +-- Extensions are intentionally NOT dropped. They may be in use by other +-- databases on the cluster; dropping them is an admin choice. +``` + +### 0002_hnsw.up.sql + +Single statement; separated from 0001 so reembed (sub-plan 0002g) can +DROP/CREATE this index in isolation without touching anything else. + +```sql +-- crates/vestige-core/migrations/postgres/0002_hnsw.up.sql +-- +-- HNSW index on knowledge_nodes.embedding. This migration runs AFTER +-- register_model() has stamped the typmod via: +-- +-- ALTER TABLE knowledge_nodes ALTER COLUMN embedding TYPE vector($N) +-- +-- where $N is the embedder's dimension(). Without the typmod, pgvector +-- rejects HNSW creation with: +-- +-- ERROR: column does not have dimensions +-- +-- See "HNSW typmod ordering" in 0002c-migrations.md and the connect() +-- sequence in 0002a-skeleton-and-feature-gate.md / 0002d-store-impl-bodies.md. +-- +-- Operator class: vector_cosine_ops -> distance operator `<=>`. +-- Build parameters: m = 16, ef_construction = 64 (pgvector defaults; see +-- the master plan 0002 D5 RRF discussion for the rationale). + +CREATE INDEX idx_knowledge_nodes_embedding_hnsw + ON knowledge_nodes USING hnsw (embedding vector_cosine_ops) + WITH (m = 16, ef_construction = 64); +``` + +### 0002_hnsw.down.sql + +```sql +-- crates/vestige-core/migrations/postgres/0002_hnsw.down.sql + +DROP INDEX IF EXISTS idx_knowledge_nodes_embedding_hnsw; +``` + +--- + +## HNSW typmod ordering + +pgvector's HNSW index requires the indexed column to have a typmod (fixed +dimension). `vector` (unconstrained) is rejected; `vector(768)` is accepted. +We cannot bake the dimension into 0001 because the dimension is an +embedder-determined runtime value -- different builds may use different +embedders. + +This forces an ordering: + +1. Apply migration 0001 (creates `knowledge_nodes.embedding vector`, no typmod). +2. Connect, decide which embedder is in use, run + `ALTER TABLE knowledge_nodes ALTER COLUMN embedding TYPE vector($N)` + inside `register_model`. +3. Apply migration 0002 (creates HNSW; succeeds because the column now has + a typmod). + +`sqlx::migrate!("...")` runs ALL pending migrations in a single call. It is +not designed to pause between two specific migrations so application code +can interleave a runtime DDL step. So we have two options: + +**Option A: Migration 0002 lives outside the sqlx migrations directory.** +Keep `0001_init.{up,down}.sql` only in `migrations/postgres/`; promote +`0002_hnsw.up.sql` to a Rust `include_str!` constant or a separate +`migrations/postgres-hnsw/` directory, run it manually by `PgMemoryStore` +after `register_model`. + +Pros: simple control flow, one `sqlx::migrate!()` call. +Cons: `sqlx_migrations` table does not record 0002, so `sqlx-cli migrate +info` lies. The HNSW index becomes "shadow" schema state from sqlx's POV. +Reembed (sub-plan 0002g) has to also know about this file outside the +normal migrations directory. + +**Option B (chosen): Both migrations live in the directory; the runner +splits them programmatically.** Use `sqlx::migrate::Migrator::new` to load +the directory and call its `run_to(...)` method with a specific version. + +```rust +// crates/vestige-core/src/storage/postgres/migrations.rs +use sqlx::migrate::Migrator; +use sqlx::PgPool; + +use crate::storage::error::MemoryStoreResult; + +/// Embedded migrator. Loaded at compile time from the migrations directory +/// alongside the crate. Path is relative to CARGO_MANIFEST_DIR. +static MIGRATOR: Migrator = sqlx::migrate!("./migrations/postgres"); + +/// Run migrations up to (and including) version 1. +/// +/// This must be called BEFORE register_model so the schema (knowledge_nodes table, +/// embedding_model registry, etc.) exists for register_model to write into +/// and to ALTER. +pub(crate) async fn run_pre_register(pool: &PgPool) -> MemoryStoreResult<()> { + MIGRATOR.run_to(pool, 1).await?; + Ok(()) +} + +/// Run any remaining migrations (currently: HNSW = version 2). +/// +/// Called AFTER register_model has stamped the embedding column's typmod. +pub(crate) async fn run_post_register(pool: &PgPool) -> MemoryStoreResult<()> { + MIGRATOR.run(pool).await?; + Ok(()) +} +``` + +Pros: sqlx is the only source of truth for migration version state; +`sqlx-cli migrate info` is accurate; reembed re-applies 0002 by name; future +migrations slot in normally. +Cons: relies on `Migrator::run_to`, which exists in sqlx 0.7+ and is the +documented API for staged migration. If that API ever disappears we fall +back to Option A. + +Decision: Option B. `Migrator::run_to(target_version)` is stable in sqlx +0.8. Sub-plan 0002a's `MemoryStoreError` already gains +`#[from] sqlx::migrate::MigrateError` to absorb whichever error variant +this surfaces. + +The `connect()` sequence in sub-plan 0002d will therefore look like: + +```rust +// Sketch only; full body lives in 0002d-store-impl-bodies.md. +pub async fn connect(url: &str, max_connections: u32) -> MemoryStoreResult { + let pool = crate::storage::postgres::pool::build(url, max_connections).await?; + crate::storage::postgres::migrations::run_pre_register(&pool).await?; + let store = Self { pool }; + // register_model is called by the cognitive engine bootstrap, NOT here. + // After it runs, the engine calls store.finalize_schema() which calls + // run_post_register. Same shape as SqliteMemoryStore. + Ok(store) +} + +pub async fn finalize_schema(&self) -> MemoryStoreResult<()> { + crate::storage::postgres::migrations::run_post_register(&self.pool).await +} +``` + +`finalize_schema` lands in 0002d; this sub-plan only ships `run_pre_register` +and `run_post_register` plus their wiring into `connect`. + +--- + +## SQLite V15 migration + +The Phase 1 SQLite schema lives in `crates/vestige-core/src/storage/migrations.rs` +as a `MIGRATIONS` slice. V14 is the latest entry. V15 is appended to mirror +D7 (multi-tenancy) and D8 (codebase) on the SQLite side, so a single-user +SQLite deployment sees the same surface area. + +Constraints versus the Postgres migration: + +- No `UUID[]` -- `shared_with_groups` is a TEXT JSON-encoded `'[]'`. +- No `gen_random_uuid()` -- the bootstrap user UUID is a literal. +- No partial indexes for our chosen pattern (SQLite *does* support partial + indexes since 3.8; we use one for `codebase` to match Postgres). +- No `ADD COLUMN IF NOT EXISTS` -- the V15 column additions are split into a + `MIGRATION_V15_ALTER_COLUMNS` slice exactly like V14 did, so the migration + is idempotent on replay. + +### Insertion point in migrations.rs + +Add to the `MIGRATIONS` slice immediately after V14: + +```rust +// In MIGRATIONS slice, after the V14 entry: +Migration { + version: 15, + description: "ADR 0002 D7+D8: multi-tenancy reservation + codebase column", + up: MIGRATION_V15_UP, +}, +``` + +### V15 SQL + +```rust +/// V15: ADR 0002 D7 + D8. +/// +/// D7 reserves users / groups / group_memberships and owner_user_id / +/// visibility / shared_with_groups columns on knowledge_nodes. Single-user +/// SQLite mode never reads these (the trait surface ignores visibility +/// because there is exactly one user) but they exist so Phase 3 does not +/// have to ALTER a populated table. +/// +/// D8 adds a first-class `codebase` column. +/// +/// Like V14, the ALTER TABLE statements are split into +/// MIGRATION_V15_ALTER_COLUMNS because SQLite has no ADD COLUMN IF NOT EXISTS. +const MIGRATION_V15_UP: &str = r#" +-- Migration V15: multi-tenancy reservation + codebase column. + +-- 1. Users / groups / group_memberships ----------------------------------- +-- Mirrors the Postgres D7 tables. Single bootstrap user inserted below. + +CREATE TABLE IF NOT EXISTS users ( + id TEXT PRIMARY KEY, + handle TEXT NOT NULL UNIQUE, + display_name TEXT, + created_at TEXT NOT NULL, + metadata TEXT NOT NULL DEFAULT '{}' +); + +CREATE TABLE IF NOT EXISTS groups ( + id TEXT PRIMARY KEY, + handle TEXT NOT NULL UNIQUE, + display_name TEXT, + created_at TEXT NOT NULL, + metadata TEXT NOT NULL DEFAULT '{}' +); + +CREATE TABLE IF NOT EXISTS group_memberships ( + user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + group_id TEXT NOT NULL REFERENCES groups(id) ON DELETE CASCADE, + role TEXT NOT NULL DEFAULT 'member' CHECK (role IN ('member', 'admin')), + joined_at TEXT NOT NULL, + PRIMARY KEY (user_id, group_id) +); + +-- 2. Bootstrap 'local' user. Same UUID as the Postgres default so a future +-- portable export from SQLite -> import to Postgres preserves owner_user_id. + +INSERT OR IGNORE INTO users (id, handle, display_name, created_at) + VALUES ('00000000-0000-0000-0000-000000000001', 'local', 'Local User', + datetime('now')); + +-- 3. Per-memory column additions are applied separately by the migration +-- runner (see MIGRATION_V15_ALTER_COLUMNS). + +-- 4. Indexes that do not depend on the new columns. Index creation on the +-- new knowledge_nodes columns is done after MIGRATION_V15_ALTER_COLUMNS +-- runs (see runner glue below). + +UPDATE schema_version SET version = 15, applied_at = datetime('now'); +"#; + +/// V15 column additions. SQLite has no ADD COLUMN IF NOT EXISTS, so the +/// runner skips "duplicate column" errors per statement (same shape as V14). +pub const MIGRATION_V15_ALTER_COLUMNS: &[&str] = &[ + // D7 columns. Defaults match the Postgres side. shared_with_groups is + // a JSON-encoded array. + "ALTER TABLE knowledge_nodes ADD COLUMN owner_user_id TEXT NOT NULL DEFAULT '00000000-0000-0000-0000-000000000001'", + "ALTER TABLE knowledge_nodes ADD COLUMN visibility TEXT NOT NULL DEFAULT 'private'", + "ALTER TABLE knowledge_nodes ADD COLUMN shared_with_groups TEXT NOT NULL DEFAULT '[]'", + // D8 column. + "ALTER TABLE knowledge_nodes ADD COLUMN codebase TEXT", +]; + +/// V15 index creation. Runs AFTER the ALTER COLUMN statements succeed. +/// Kept as a separate batch so a partial replay (columns already there, +/// indexes not yet) still creates the indexes. +const MIGRATION_V15_INDEXES: &str = r#" +CREATE INDEX IF NOT EXISTS idx_nodes_owner_user_id ON knowledge_nodes(owner_user_id); +CREATE INDEX IF NOT EXISTS idx_nodes_codebase ON knowledge_nodes(codebase) WHERE codebase IS NOT NULL; +-- shared_with_groups is TEXT JSON in SQLite; we do not add a GIN-equivalent +-- index. Phase 3 lookups on the SQLite side will scan; SQLite never serves +-- the multi-user query path in Phase 2-4 anyway. +"#; +``` + +### Runner glue + +Extend `apply_migrations` in `migrations.rs` to recognise V15 the same way +it recognises V14: + +```rust +// Existing pattern for V14 lives in apply_migrations; extend it: +if migration.version == 15 { + for stmt in MIGRATION_V15_ALTER_COLUMNS { + if let Err(e) = conn.execute_batch(stmt) { + let msg = e.to_string(); + if msg.contains("duplicate column name") { + tracing::debug!( + "V15 ALTER TABLE skipped (column already exists): {}", + msg + ); + } else { + return Err(e); + } + } + } + // Indexes run *after* the columns exist. + conn.execute_batch(MIGRATION_V15_INDEXES)?; +} + +// Then the normal: +conn.execute_batch(migration.up)?; +``` + +Order of operations on a fresh in-memory DB: + +1. V1 - V14 run as before. +2. V15: column ALTERs run first (so MIGRATION_V15_INDEXES sees them). +3. V15 main body creates users/groups/group_memberships and the bootstrap row. +4. V15 indexes batch runs. +5. schema_version advances to 15. + +This intentionally mirrors how V14 handles its ALTER + index pair. + +### Existing-data backfill + +Existing SQLite databases (every Phase 1 deployment) have populated +`knowledge_nodes` rows. The V15 ALTER COLUMN ADD COLUMN statements assign +the default values to every existing row: + +- `owner_user_id` -> `'00000000-0000-0000-0000-000000000001'` +- `visibility` -> `'private'` +- `shared_with_groups` -> `'[]'` +- `codebase` -> NULL + +Phase 2 leaves these defaults in place. Phase 3 owns the migration story +for populating real owner UUIDs and visibility values. + +--- + +## Rust wrapper + +Single file: + +```rust +// crates/vestige-core/src/storage/postgres/migrations.rs +// +// sqlx::migrate! wrapper for the Postgres backend. +// +// We split the migration apply into two halves around register_model: +// - run_pre_register: applies everything up to and including version 1 +// (schema, indexes, bootstrap row). Safe to call on a +// fresh DB. +// - run_post_register: applies the remainder (currently: 0002_hnsw, which +// needs the embedding column typmod stamped first). +// +// See docs/plans/0002c-migrations.md "HNSW typmod ordering" for why this +// split exists. + +#![cfg(feature = "postgres-backend")] + +use sqlx::PgPool; +use sqlx::migrate::Migrator; + +use crate::storage::error::MemoryStoreResult; + +/// Embedded migrator. Path is relative to CARGO_MANIFEST_DIR +/// (`crates/vestige-core/`). +static MIGRATOR: Migrator = sqlx::migrate!("./migrations/postgres"); + +/// Apply migrations through version 1 (the schema-only migration). +/// +/// Idempotent: sqlx::migrate consults the `_sqlx_migrations` table and is +/// a no-op on a database already at version 1 or higher. +pub(crate) async fn run_pre_register(pool: &PgPool) -> MemoryStoreResult<()> { + MIGRATOR.run_to(pool, 1).await?; + Ok(()) +} + +/// Apply any remaining migrations. Called after `register_model` has +/// stamped the typmod on `knowledge_nodes.embedding`. +pub(crate) async fn run_post_register(pool: &PgPool) -> MemoryStoreResult<()> { + MIGRATOR.run(pool).await?; + Ok(()) +} +``` + +Wiring into `PgMemoryStore::connect`. The skeleton from 0002a uses +`todo!()` for everything past pool construction. This sub-plan replaces +that with `run_pre_register` only; `run_post_register` is invoked by +`finalize_schema`, which lands in 0002d. Sketch: + +```rust +// In crates/vestige-core/src/storage/postgres/mod.rs (sub-plan 0002a wires +// pool construction; this sub-plan adds the run_pre_register call): + +impl PgMemoryStore { + pub async fn connect(url: &str, max_connections: u32) -> MemoryStoreResult { + let pool = super::pool::build(url, max_connections).await?; + super::migrations::run_pre_register(&pool).await?; + Ok(Self { pool }) + } +} +``` + +Module wire-up in `crates/vestige-core/src/storage/postgres/mod.rs`: + +```rust +mod migrations; // pub(crate) functions; not re-exported. +``` + +### Error variant + +Sub-plan 0002a already added (under feature gate) to `MemoryStoreError`: + +```rust +#[cfg(feature = "postgres-backend")] +#[error("postgres migration error: {0}")] +Migrate(#[from] sqlx::migrate::MigrateError), +``` + +`run_pre_register` / `run_post_register` use the `?` operator and the +`#[from]` conversion handles it; no extra error handling code is needed. + +--- + +## Visibility CHECK constraint + +ADR 0002 D7 specifies the tri-state enum: + +``` +visibility IN ('private', 'group', 'public') +``` + +This sub-plan includes that CHECK on the `knowledge_nodes` table (see 0001_init.up.sql +above) on both sides: + +- Postgres: `CHECK (visibility IN ('private', 'group', 'public'))` inline on + the table. +- SQLite: same CHECK constraint can be added to V15 if desired. (It is not + in the V15 body above because adding a CHECK via ALTER TABLE on SQLite + requires a table rebuild; we trust the application layer for SQLite, since + SQLite never serves the multi-user query path in Phase 2.) + +The stronger consistency rule from the ADR 0002 follow-ups section, + +``` +CHECK ( + visibility = 'private' + OR cardinality(shared_with_groups) > 0 + OR visibility = 'public' +) +``` + +is intentionally NOT added in this sub-plan. Rationale: + +- The rule is a "no orphan group rows" sanity check, not a correctness + requirement for Phase 2 (single-user mode never touches the column). +- Phase 3 is the first phase that writes `visibility = 'group'`. The check + belongs in the Phase 3 migration that lights up auth, alongside the + application code that ensures `shared_with_groups` is populated before + the visibility flips. +- Adding it now and discovering Phase 3 wants a different shape forces an + online CHECK constraint replacement. + +Recommendation: include only the IN check in Phase 2; revisit the +cardinality check in Phase 3. + +--- + +## Offline sqlx cache + +`crates/vestige-core/.sqlx/` is the on-disk cache of compile-time-checked +queries that `sqlx::query!` / `sqlx::query_as!` emit at build time when +`SQLX_OFFLINE=true`. It is committed to the repo so builds without +`DATABASE_URL` (CI, downstream consumers, contributors without Postgres) +succeed. + +This sub-plan does NOT yet generate or commit `.sqlx/` content. Reasons: + +- `sqlx::query!` calls are introduced in `0002d-store-impl-bodies.md` (real + CRUD bodies) and `0002e-hybrid-search.md` (RRF). This sub-plan ships only + the migrations directory and a wrapper that uses `sqlx::migrate!` -- which + is a compile-time macro that reads files, not a query macro that needs a + DB connection. +- Generating an empty `.sqlx/` directory now is noise that gets immediately + overwritten in the next sub-plan. + +Sub-plan 0002d will land the procedure: + +```sh +# Local dev box with vestige DB initialised per local-dev-postgres-setup.md. +export DATABASE_URL="postgresql://vestige:$(cat ~/.vestige_pg_pw)@127.0.0.1:5432/vestige" + +# Apply migrations against the dev DB. +cargo sqlx migrate run \ + --source crates/vestige-core/migrations/postgres \ + --database-url "$DATABASE_URL" + +# Generate the offline cache. +cargo sqlx prepare --workspace -- --features postgres-backend + +# Verify cache compiles offline. +SQLX_OFFLINE=true cargo check --workspace --features postgres-backend +``` + +The `.sqlx/` directory commit policy is: committed, reviewed in PRs that +add or change `query!` calls, regenerated locally and pushed. + +What this sub-plan DOES need from sqlx-cli, for verification only (see next +section): `cargo sqlx migrate run --source crates/vestige-core/migrations/postgres`. + +--- + +## Verification + +Two halves: Postgres migrations run cleanly on a fresh DB; SQLite V15 does +not break the Phase 1 store. + +### Postgres + +Prerequisites: Postgres 18 with pgvector, a role with CREATEDB and EXTENSION +rights, per `docs/plans/local-dev-postgres-setup.md`. Alternatively, a +container: + +```sh +podman run --rm -d --name vestige-pg \ + -e POSTGRES_PASSWORD=devpw \ + -e POSTGRES_USER=vestige \ + -e POSTGRES_DB=vestige \ + -p 5432:5432 \ + docker.io/pgvector/pgvector:pg16 + +export DATABASE_URL="postgresql://vestige:devpw@127.0.0.1:5432/vestige" +``` + +Steps: + +1. Apply migrations. From the repo root: + + ```sh + cargo install sqlx-cli --no-default-features --features postgres + cargo sqlx migrate run \ + --source crates/vestige-core/migrations/postgres \ + --database-url "$DATABASE_URL" + ``` + + Expected output: `Applied 1/migrate init` (`0002` is gated on typmod; + sqlx-cli will run it and pgvector will reject the HNSW creation with + "column does not have dimensions". This is the expected behaviour when + running migrations without going through the Rust connect path. To run + 0002 manually for verification, first stamp the typmod: + + ```sh + psql "$DATABASE_URL" -c "ALTER TABLE knowledge_nodes ALTER COLUMN embedding TYPE vector(768);" + cargo sqlx migrate run \ + --source crates/vestige-core/migrations/postgres \ + --database-url "$DATABASE_URL" + ``` + + Now 0002 should apply.) + +2. Verify tables exist: + + ```sh + psql "$DATABASE_URL" -c "\dt" + ``` + + Expected (alphabetical): + ``` + domains + edges + embedding_model + group_memberships + groups + knowledge_nodes + review_events + scheduling + users + ``` + +3. Verify the bootstrap user row: + + ```sh + psql "$DATABASE_URL" -c "SELECT id, handle, display_name FROM users;" + ``` + + Expected: + ``` + id | handle | display_name + --------------------------------------+--------+-------------- + 00000000-0000-0000-0000-000000000001 | local | Local User + ``` + +4. Verify HNSW index (only after the typmod stamp + migrate 0002): + + ```sh + psql "$DATABASE_URL" -c "\d knowledge_nodes" + ``` + + The trailing `Indexes:` block should include `idx_knowledge_nodes_embedding_hnsw`. + +5. Verify the D7+D8 columns are present: + + ```sh + psql "$DATABASE_URL" -c " + SELECT column_name, data_type, column_default + FROM information_schema.columns + WHERE table_name = 'knowledge_nodes' + AND column_name IN ('owner_user_id', 'visibility', + 'shared_with_groups', 'codebase') + ORDER BY column_name; + " + ``` + + Expected: four rows, with `owner_user_id` defaulting to the bootstrap + UUID, `visibility` to `'private'::text`, `shared_with_groups` to + `'{}'::uuid[]`, `codebase` NULL-default. + +6. Verify CHECK constraint: + + ```sh + psql "$DATABASE_URL" -c " + INSERT INTO knowledge_nodes (content, visibility) VALUES ('test', 'bogus'); + " + # Expected: ERROR: new row for relation \"knowledge_nodes\" violates check constraint + ``` + +7. Roll back to verify down migrations work: + + ```sh + cargo sqlx migrate revert \ + --source crates/vestige-core/migrations/postgres \ + --database-url "$DATABASE_URL" + cargo sqlx migrate revert \ + --source crates/vestige-core/migrations/postgres \ + --database-url "$DATABASE_URL" + ``` + + `\dt` should then list only the sqlx-managed `_sqlx_migrations` table. + +8. Rust-side smoke test (no `sqlx::query!` calls yet, so cannot live in + a `#[sqlx::test]`-decorated function until 0002d). Manual: + + ```sh + cargo build -p vestige-core --features postgres-backend + ``` + + Should compile. The `sqlx::migrate!("./migrations/postgres")` macro + reads the directory at compile time; a missing file or syntax error + surfaces as a compile error. + +### SQLite + +1. Run the existing test suite: + + ```sh + cargo test -p vestige-core + ``` + + Expected: 352 (or current count + new V15 tests) tests pass, zero + warnings. + +2. New test in `migrations.rs#tests`: + + ```rust + #[test] + fn test_v15_advances_to_15_and_adds_d7_d8_columns() { + let conn = rusqlite::Connection::open_in_memory().expect("open in-memory"); + apply_migrations(&conn).expect("apply_migrations succeeds"); + + let version = get_current_version(&conn).expect("read schema_version"); + assert_eq!(version, 15, "schema_version should advance to 15"); + + // Tables exist + for tbl in ["users", "groups", "group_memberships"] { + let n: i32 = conn.query_row( + "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name=?1", + [tbl], + |r| r.get(0), + ).expect("query sqlite_master"); + assert_eq!(n, 1, "table {tbl} should exist after V15"); + } + + // Bootstrap user row exists + let n: i32 = conn.query_row( + "SELECT COUNT(*) FROM users WHERE id = '00000000-0000-0000-0000-000000000001'", + [], + |r| r.get(0), + ).expect("query users"); + assert_eq!(n, 1, "bootstrap local user row should exist"); + + // D7+D8 columns on knowledge_nodes + let cols: Vec = conn + .prepare("PRAGMA table_info(knowledge_nodes)") + .unwrap() + .query_map([], |r| r.get::<_, String>(1)) + .unwrap() + .collect::>() + .unwrap(); + for c in ["owner_user_id", "visibility", "shared_with_groups", "codebase"] { + assert!(cols.iter().any(|x| x == c), + "knowledge_nodes should have column {c}"); + } + } + ``` + +3. Idempotency: re-applying V15 on an already-V15 DB must not error. + `apply_migrations` already skips when `current_version >= migration.version`; + no extra test needed beyond ensuring the V14 + V15 ALTER pattern works. + +4. Existing-data backfill smoke: insert a row before applying V15, then + verify the defaults populate: + + ```rust + #[test] + fn test_v15_backfills_existing_rows_with_defaults() { + let conn = rusqlite::Connection::open_in_memory().expect("open"); + + // Apply migrations through V14 only. + // (We rely on the fact that re-running apply_migrations is a no-op, + // so we apply all, then probe the columns. The V15 ALTER on a + // populated table is what we are testing implicitly.) + apply_migrations(&conn).expect("V1-V15"); + + // Insert a row using only Phase 1 columns; V15 defaults must + // populate owner_user_id / visibility / shared_with_groups / codebase. + conn.execute( + "INSERT INTO knowledge_nodes (id, content, node_type, created_at, updated_at, last_accessed) + VALUES ('test', 'hello', 'fact', datetime('now'), datetime('now'), datetime('now'))", + [], + ).expect("insert"); + + let (owner, vis, shared, codebase): (String, String, String, Option) = + conn.query_row( + "SELECT owner_user_id, visibility, shared_with_groups, codebase + FROM knowledge_nodes WHERE id = 'test'", + [], + |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)), + ).expect("query"); + + assert_eq!(owner, "00000000-0000-0000-0000-000000000001"); + assert_eq!(vis, "private"); + assert_eq!(shared, "[]"); + assert_eq!(codebase, None); + } + ``` + +5. Live deployment: apply V15 to a copy of `~/.vestige/vestige.db` and + verify the existing 150 memories all carry the four new columns with + default values: + + ```sh + cp ~/.vestige/vestige.db /tmp/v15-test.db + sqlite3 /tmp/v15-test.db <<'SQL' + .schema knowledge_nodes + SELECT COUNT(*) FROM knowledge_nodes; + SELECT DISTINCT owner_user_id, visibility, shared_with_groups + FROM knowledge_nodes LIMIT 5; + SQL + # (Migration applies on first read by the vestige binary running V15.) + ``` + + Capture pre- and post-counts. Expected: no row count change, all new + columns populated by defaults. + +--- + +## Acceptance criteria + +- [ ] `crates/vestige-core/migrations/postgres/` directory contains exactly + four files: `0001_init.up.sql`, `0001_init.down.sql`, + `0002_hnsw.up.sql`, `0002_hnsw.down.sql`. Content matches this + sub-plan. +- [ ] `crates/vestige-core/src/storage/postgres/migrations.rs` exports + `run_pre_register` and `run_post_register` as `pub(crate)` async + functions returning `MemoryStoreResult<()>`. Compiles with + `--features postgres-backend`. +- [ ] `PgMemoryStore::connect` (sub-plan 0002a skeleton) is updated to call + `run_pre_register` immediately after pool construction. `connect` + still returns before `register_model` runs; `run_post_register` + lands in 0002d via `finalize_schema`. +- [ ] `crates/vestige-core/src/storage/migrations.rs` has a new V15 entry + in `MIGRATIONS`, with `MIGRATION_V15_UP`, `MIGRATION_V15_ALTER_COLUMNS`, + and `MIGRATION_V15_INDEXES` constants. `apply_migrations` handles + V15 the same shape as V14. +- [ ] `cargo test -p vestige-core` passes. New tests cover V15 advance, + D7+D8 column existence, bootstrap user row, and existing-row backfill. +- [ ] `cargo build -p vestige-core --features postgres-backend` compiles + (the `sqlx::migrate!` macro will fail at compile time if any of the + four SQL files is missing or malformed). +- [ ] `cargo sqlx migrate run --source crates/vestige-core/migrations/postgres` + against a fresh container applies 0001 cleanly; `\dt` lists the nine + Phase 2 tables; `users` contains the bootstrap row. +- [ ] After the manual typmod stamp documented above, `cargo sqlx migrate + run` applies 0002 and `\d knowledge_nodes` shows `idx_knowledge_nodes_embedding_hnsw`. +- [ ] `cargo sqlx migrate revert` twice cleans the DB back to only the + `_sqlx_migrations` table. +- [ ] Inserting a row with `visibility = 'bogus'` is rejected by the CHECK + constraint. +- [ ] No `sqlx::query!` / `sqlx::query_as!` calls are added in this + sub-plan; the `.sqlx/` offline cache is not yet generated. +- [ ] The existing live SQLite DB on the development machine migrates from + V14 to V15 without row count change, and the 150 existing rows all + receive the four V15 default values. diff --git a/docs/plans/0002d-store-impl-bodies.md b/docs/plans/0002d-store-impl-bodies.md new file mode 100644 index 0000000..ad1d9b7 --- /dev/null +++ b/docs/plans/0002d-store-impl-bodies.md @@ -0,0 +1,1771 @@ +# Phase 2 Sub-Plan 0002d -- Store Implementation Bodies + +**Status**: Ready +**Depends on**: +- `0002a-skeleton-and-feature-gate.md` -- `PgMemoryStore` struct + trait impl block exist with `todo!()` bodies. +- `0002b-pool-and-config.md` -- `PgPool` is constructable, `MemoryStoreError::Postgres` and `MemoryStoreError::Migrate` variants exist behind the `postgres-backend` feature. +- `0002c-migrations.md` -- the two sqlx migrations (`0001_init`, `0002_hnsw`) exist, the schema is applied on `connect`, the `knowledge_nodes` / `scheduling` / `edges` / `domains` / `embedding_model` / `users` / `groups` / `group_memberships` / `review_events` tables exist with the D7+D8 columns. + +This sub-plan replaces every `todo!()` in +`crates/vestige-core/src/storage/postgres/mod.rs` with a real sqlx-backed +body, and adds `crates/vestige-core/src/storage/postgres/registry.rs` with +the `ensure_registry` / `register_model` typmod-stamping logic. + +The hybrid `search()` method is the meatiest single body in the backend +(RRF in one SQL statement) and lives in its own sub-plan +(`0002e-hybrid-search.md`). The bodies for the trivial single-branch +variants `fts_search` and `vector_search` are still inside this sub-plan +because they share row-mapping infrastructure with the CRUD bodies. + +Out of scope for this sub-plan: +- The full hybrid `search()` -- see `0002e-hybrid-search.md`. +- SQLite -> Postgres migrate CLI -- see `0002f-migrate-cli.md`. +- Re-embed flow -- see `0002g-reembed.md`. +- Phase 3 visibility filter -- explicitly NOT wired in Phase 2; see the + "Visibility filter posture" section below. + +--- + +## Context + +The Phase 1 `MemoryStore` trait surface is defined in +`crates/vestige-core/src/storage/memory_store.rs` and is the source of +truth for method signatures. ADR 0002 D7 added owner / visibility / +shared_with_groups columns to the `knowledge_nodes` table; ADR 0002 D8 promoted +`codebase` to a first-class column. The sqlx bodies in this sub-plan must +write to and read from those columns, but per ADR 0002 D7 they must NOT +filter on them in Phase 2 -- the visibility filter is a Phase 3 +deliverable that takes an `AuthContext` parameter. + +The semantics of every body must match the SQLite backend's current +behaviour. Where Postgres has native types (`UUID`, `JSONB`, `vector`, +`TEXT[]`, `TIMESTAMPTZ`) we use them directly; the SQLite backend's +RFC3339-string-and-JSON-blob encoding is an artefact of SQLite typing, +not the trait contract. + +Compile-time SQL validation uses sqlx's `query!` / `query_as!` macros. +The first time these macros run against a real database in CI they +populate `.sqlx/` query metadata; the metadata file is committed so +offline builds (CI without a live Postgres) succeed. + +--- + +## MemoryRecord type changes + +ADR 0002 D7 and D8 added four new columns to the `knowledge_nodes` table. +The `MemoryRecord` struct in +`crates/vestige-core/src/storage/memory_store.rs` must grow matching +fields so the trait surface can carry the data through both backends. +This is an additive change to the public type. + +Add to `MemoryRecord` (after the existing `metadata` field): + +```rust +/// Owner of this memory. Defaults to the local bootstrap user +/// (`00000000-0000-0000-0000-000000000001`) in single-user mode. +pub owner_user_id: Uuid, + +/// Tri-state visibility. ADR 0002 D7. +pub visibility: Visibility, + +/// Group IDs this memory is shared with when `visibility == Group`. +/// Empty for `Private` and `Public`. +pub shared_with_groups: Vec, + +/// First-class codebase tag. ADR 0002 D8. None if the ingest pipeline +/// could not infer one. +pub codebase: Option, +``` + +Add a new enum next to `MemoryRecord`: + +```rust +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Visibility { + Private, + Group, + Public, +} + +impl Visibility { + pub fn as_str(&self) -> &'static str { + match self { + Self::Private => "private", + Self::Group => "group", + Self::Public => "public", + } + } + + pub fn from_str(s: &str) -> MemoryStoreResult { + match s { + "private" => Ok(Self::Private), + "group" => Ok(Self::Group), + "public" => Ok(Self::Public), + other => Err(MemoryStoreError::Backend( + format!("unknown visibility value: {other}"), + )), + } + } +} + +impl Default for Visibility { + fn default() -> Self { Self::Private } +} +``` + +`MemoryRecord` already derives `Serialize` and `Deserialize`; the new +fields ride along automatically. Two callers must change as part of this +sub-plan: + +1. **SQLite backend (V15 migration ships in `0001b-sqlite-split.md` or + the same Phase 1 amendment branch)**: the SQLite backend reads the + four new columns out of `knowledge_nodes` (V15 added them) and + populates the new fields in `Self::node_to_record`. Bootstrap user + ID is the same constant on both backends. Existing call sites that + construct `MemoryRecord` literally (in tests, in cognitive modules) + may default-init the four new fields: + + ```rust + MemoryRecord { + // ... existing fields ... + owner_user_id: LOCAL_USER_ID, + visibility: Visibility::default(), + shared_with_groups: Vec::new(), + codebase: None, + metadata: serde_json::json!({}), + } + ``` + + A single `pub const LOCAL_USER_ID: Uuid = uuid::uuid!("00000000-0000-0000-0000-000000000001");` + in `storage::memory_store` provides the bootstrap constant. + +2. **Cognitive modules that build `MemoryRecord` from the ingest + pipeline**: the ingest path already captures `codebase` in metadata + (see ADR 0002 D8). Lift it from `metadata.codebase` to the new + `codebase` field at the boundary where `MemoryRecord` is built. The + `metadata.codebase` JSON key is removed in the same commit; the + column is now the only source of truth. + +The change is purely additive to the trait surface -- no method +signatures change. Backwards compatibility for stored data (in the +SQLite case) comes from V15 defaulting the new columns to `'private'` +and the bootstrap user. The Postgres schema applies the same defaults +in `0001_init.up.sql`. + +--- + +## Registry module + +New file: `crates/vestige-core/src/storage/postgres/registry.rs`. + +```rust +#![cfg(feature = "postgres-backend")] + +//! Embedding-model registry for the Postgres backend. +//! +//! The `embedding_model` table stores exactly one row (id = 1) describing +//! the model whose vectors live in `knowledge_nodes.embedding`. Phase 2 enforces +//! that the active embedder matches the registered model on every write; +//! re-embed (`0002g-reembed.md`) is the only flow allowed to change the +//! row. +//! +//! The pgvector column `knowledge_nodes.embedding` is created in +//! `0001_init.up.sql` with a placeholder type (`vector`) -- no typmod. +//! On first connect we stamp the real dimension via +//! `ALTER TABLE knowledge_nodes ALTER COLUMN embedding TYPE vector($N)` so the +//! HNSW index (created in `0002_hnsw.up.sql`) sees a sized type. + +use sqlx::PgPool; + +use crate::storage::memory_store::{ + MemoryStoreError, MemoryStoreResult, ModelSignature, +}; + +/// Look up the registered signature, if any. Returns `Ok(None)` on a +/// fresh database. +pub(crate) async fn fetch_registry( + pool: &PgPool, +) -> MemoryStoreResult> { + let row = sqlx::query!( + r#" + SELECT name, dimension, hash + FROM embedding_model + WHERE id = 1 + "# + ) + .fetch_optional(pool) + .await?; + + Ok(row.map(|r| ModelSignature { + name: r.name, + dimension: r.dimension as usize, + hash: r.hash, + })) +} + +/// First-ever call inserts the row and stamps the typmod on +/// `knowledge_nodes.embedding`. Subsequent calls compare against the stored +/// row and return `ModelMismatch` if any field differs. +pub(crate) async fn ensure_registry( + pool: &PgPool, + sig: &ModelSignature, +) -> MemoryStoreResult<()> { + let existing = fetch_registry(pool).await?; + + match existing { + None => { + sqlx::query!( + r#" + INSERT INTO embedding_model (id, name, dimension, hash) + VALUES (1, $1, $2, $3) + "#, + sig.name, + sig.dimension as i32, + sig.hash, + ) + .execute(pool) + .await?; + + stamp_vector_typmod(pool, sig.dimension).await?; + Ok(()) + } + Some(reg) if reg == *sig => Ok(()), + Some(reg) => Err(MemoryStoreError::ModelMismatch { + registered_name: reg.name, + registered_dim: reg.dimension, + registered_hash: reg.hash, + actual_name: sig.name.clone(), + actual_dim: sig.dimension, + actual_hash: sig.hash.clone(), + }), + } +} + +/// Called only by the re-embed flow (`0002g-reembed.md`) after a full +/// re-encode has rewritten every row. Updates the registry row and +/// re-stamps the typmod for the new dimension. +pub(crate) async fn update_registry_for_reembed( + pool: &PgPool, + sig: &ModelSignature, +) -> MemoryStoreResult<()> { + sqlx::query!( + r#" + UPDATE embedding_model + SET name = $1, dimension = $2, hash = $3, created_at = now() + WHERE id = 1 + "#, + sig.name, + sig.dimension as i32, + sig.hash, + ) + .execute(pool) + .await?; + + stamp_vector_typmod(pool, sig.dimension).await?; + Ok(()) +} + +async fn stamp_vector_typmod(pool: &PgPool, dim: usize) -> MemoryStoreResult<()> { + // pgvector's typmod is part of the column type, not a bound parameter. + // `format!` is safe here because `dim` is a `usize` cast to a decimal + // literal; there is no path for user-controlled SQL to reach this + // string. + let ddl = format!( + "ALTER TABLE knowledge_nodes ALTER COLUMN embedding TYPE vector({dim})" + ); + sqlx::query(&ddl).execute(pool).await?; + Ok(()) +} +``` + +Wire the new module into `crates/vestige-core/src/storage/postgres/mod.rs`: + +```rust +pub(crate) mod registry; +``` + +The `fetch_registry` / `ensure_registry` functions are reached from the +trait methods `registered_model` and `register_model` (see method bodies +below). `update_registry_for_reembed` is reached only from +`postgres::reembed`, which is filled in by `0002g-reembed.md`. + +--- + +## Method-by-method bodies + +Every body below replaces a `todo!()` in +`crates/vestige-core/src/storage/postgres/mod.rs`. Method order matches +the trait declaration in `memory_store.rs`. + +Common imports at the top of `mod.rs`: + +```rust +use chrono::{DateTime, Utc}; +use pgvector::Vector; +use uuid::Uuid; + +use crate::storage::memory_store::{ + Domain, HealthStatus, LocalMemoryStore, MemoryEdge, MemoryRecord, + MemoryStoreError, MemoryStoreResult, ModelSignature, SchedulingState, + SearchQuery, SearchResult, StoreStats, Visibility, +}; +``` + +Recurring row-to-record helper (private to `mod.rs`): + +```rust +fn row_to_record( + id: Uuid, + content: String, + node_type: String, + tags: Vec, + domains: Vec, + domain_scores: serde_json::Value, + codebase: Option, + owner_user_id: Uuid, + visibility: String, + shared_with_groups: Vec, + embedding: Option, + metadata: serde_json::Value, + created_at: DateTime, + updated_at: DateTime, +) -> MemoryStoreResult { + let domain_scores: std::collections::HashMap = + serde_json::from_value(domain_scores).unwrap_or_default(); + let embedding = embedding.map(|v| v.to_vec()); + Ok(MemoryRecord { + id, + domains, + domain_scores, + content, + node_type, + tags, + embedding, + created_at, + updated_at, + metadata, + owner_user_id, + visibility: Visibility::from_str(&visibility)?, + shared_with_groups, + codebase, + }) +} +``` + +### Lifecycle + +#### `init` + +```rust +async fn init(&self) -> MemoryStoreResult<()> +``` + +Migrations already ran in `connect`; this is a no-op identical to +SQLite's behaviour. + +```rust +async fn init(&self) -> MemoryStoreResult<()> { + Ok(()) +} +``` + +#### `health_check` + +```rust +async fn health_check(&self) -> MemoryStoreResult +``` + +Issue a trivial `SELECT 1`. Pool acquisition errors degrade to +`HealthStatus::Degraded`; any other error path returns `Unavailable`. + +```rust +async fn health_check(&self) -> MemoryStoreResult { + match sqlx::query_scalar!("SELECT 1::int") + .fetch_one(&self.pool) + .await + { + Ok(_) => Ok(HealthStatus::Healthy), + Err(sqlx::Error::PoolTimedOut) => Ok(HealthStatus::Degraded { + reason: "pool exhausted".to_string(), + }), + Err(e) => Ok(HealthStatus::Unavailable { + reason: e.to_string(), + }), + } +} +``` + +### Embedding-model registry + +#### `registered_model` + +```rust +async fn registered_model(&self) -> MemoryStoreResult> +``` + +Thin pass-through to `registry::fetch_registry`. The Postgres backend +does not cache the row in-memory the way the SQLite backend does -- +sqlx's prepared-statement cache already keeps the SELECT cheap, and +`registered_model` is not on the hot path. + +```rust +async fn registered_model(&self) -> MemoryStoreResult> { + crate::storage::postgres::registry::fetch_registry(&self.pool).await +} +``` + +#### `register_model` + +```rust +async fn register_model(&self, sig: &ModelSignature) -> MemoryStoreResult<()> +``` + +Delegate to `registry::ensure_registry`, which handles the +"insert + stamp typmod" first-run path and the "compare" subsequent path. + +```rust +async fn register_model(&self, sig: &ModelSignature) -> MemoryStoreResult<()> { + crate::storage::postgres::registry::ensure_registry(&self.pool, sig).await +} +``` + +### CRUD + +#### `insert` + +```rust +async fn insert(&self, record: &MemoryRecord) -> MemoryStoreResult +``` + +Single `INSERT` into `knowledge_nodes` with all D7+D8 columns. Bind embedding +as `Option` -- pgvector's sqlx integration handles the +typmod check at execution time, so a length mismatch surfaces as +`MemoryStoreError::Postgres`. The caller-supplied UUID is preserved +(same contract as SQLite). Initial scheduling state is inserted in the +same transaction so a memory is never queryable without a scheduling +row. + +```rust +async fn insert(&self, record: &MemoryRecord) -> MemoryStoreResult { + let embedding: Option = record + .embedding + .as_ref() + .map(|v| Vector::from(v.clone())); + let domain_scores = serde_json::to_value(&record.domain_scores) + .unwrap_or_else(|_| serde_json::json!({})); + + let mut tx = self.pool.begin().await?; + + sqlx::query!( + r#" + INSERT INTO knowledge_nodes ( + id, + owner_user_id, + visibility, + shared_with_groups, + codebase, + content, + node_type, + tags, + domains, + domain_scores, + embedding, + metadata, + created_at, + updated_at + ) + VALUES ( + $1, $2, $3, $4, $5, $6, $7, $8, $9, $10::jsonb, + $11, $12::jsonb, $13, $14 + ) + "#, + record.id, + record.owner_user_id, + record.visibility.as_str(), + &record.shared_with_groups as &[Uuid], + record.codebase.as_deref(), + record.content, + record.node_type, + &record.tags as &[String], + &record.domains as &[String], + domain_scores, + embedding as Option, + record.metadata, + record.created_at, + record.updated_at, + ) + .execute(&mut *tx) + .await?; + + // Seed scheduling state. Mirrors SQLite defaults from `knowledge_nodes` + // (stability=1.0, difficulty=0.3, retrievability=1.0, reps=0, lapses=0, + // next_review = created_at + 1 day). + sqlx::query!( + r#" + INSERT INTO scheduling ( + memory_id, stability, difficulty, retrievability, + last_review, next_review, reps, lapses + ) + VALUES ($1, 1.0, 0.3, 1.0, NULL, $2, 0, 0) + "#, + record.id, + record.created_at + chrono::Duration::days(1), + ) + .execute(&mut *tx) + .await?; + + tx.commit().await?; + Ok(record.id) +} +``` + +Tricky bits: +- `&record.tags as &[String]` -- sqlx requires an explicit slice cast + to bind a `Vec` as `text[]`. +- `&record.shared_with_groups as &[Uuid]` -- same pattern for `uuid[]`. +- `embedding as Option` -- type annotation is mandatory in the + macro because the inference path bottoms out at a generic; pgvector's + `Encode` impl resolves only with a known concrete type. +- The `$10::jsonb` and `$12::jsonb` casts force sqlx to encode through + the JSONB path even if the parameter type-resolves to `JSON`. This + matters because the migrations created the columns as `JSONB`, and + sqlx 0.8 does not always pick JSONB without the cast. + +#### `get` + +```rust +async fn get(&self, id: Uuid) -> MemoryStoreResult> +``` + +`SELECT *` filtered by primary key. Row mapping goes through +`row_to_record`. + +```rust +async fn get(&self, id: Uuid) -> MemoryStoreResult> { + let row = sqlx::query!( + r#" + SELECT + id AS "id!: Uuid", + owner_user_id AS "owner_user_id!: Uuid", + visibility, + shared_with_groups AS "shared_with_groups!: Vec", + codebase, + content, + node_type, + tags AS "tags!: Vec", + domains AS "domains!: Vec", + domain_scores AS "domain_scores!: serde_json::Value", + embedding AS "embedding: Vector", + metadata AS "metadata!: serde_json::Value", + created_at AS "created_at!: DateTime", + updated_at AS "updated_at!: DateTime" + FROM knowledge_nodes + WHERE id = $1 + "#, + id, + ) + .fetch_optional(&self.pool) + .await?; + + let Some(r) = row else { return Ok(None) }; + + Ok(Some(row_to_record( + r.id, r.content, r.node_type, r.tags, r.domains, + r.domain_scores, r.codebase, r.owner_user_id, r.visibility, + r.shared_with_groups, r.embedding, r.metadata, + r.created_at, r.updated_at, + )?)) +} +``` + +The `AS "name!: Type"` annotations tell sqlx the exact Rust type for +each column, which is required for `Vec` (from `uuid[]`) and +`Vector` (from `vector`). The `!` means "trust me, this column is NOT +NULL"; sqlx skips its `Option` wrapping for those columns. The +`embedding` column is nullable, so it gets `Option` (no `!`). + +#### `update` + +```rust +async fn update(&self, record: &MemoryRecord) -> MemoryStoreResult<()> +``` + +Update everything the caller might have changed. `updated_at` is set +server-side via `now()` so clock drift between hosts does not leak into +the timeline. (If the caller wants to forge `updated_at` -- e.g. the +migrate CLI replaying SQLite timestamps -- it goes through `insert`, not +`update`.) The schema's `BEFORE UPDATE` trigger could replace this; we +write `updated_at = now()` explicitly to be backend-agnostic. + +```rust +async fn update(&self, record: &MemoryRecord) -> MemoryStoreResult<()> { + let embedding: Option = record + .embedding + .as_ref() + .map(|v| Vector::from(v.clone())); + let domain_scores = serde_json::to_value(&record.domain_scores) + .unwrap_or_else(|_| serde_json::json!({})); + + let rows = sqlx::query!( + r#" + UPDATE knowledge_nodes SET + owner_user_id = $2, + visibility = $3, + shared_with_groups = $4, + codebase = $5, + content = $6, + node_type = $7, + tags = $8, + domains = $9, + domain_scores = $10::jsonb, + embedding = $11, + metadata = $12::jsonb, + updated_at = now() + WHERE id = $1 + "#, + record.id, + record.owner_user_id, + record.visibility.as_str(), + &record.shared_with_groups as &[Uuid], + record.codebase.as_deref(), + record.content, + record.node_type, + &record.tags as &[String], + &record.domains as &[String], + domain_scores, + embedding as Option, + record.metadata, + ) + .execute(&self.pool) + .await? + .rows_affected(); + + if rows == 0 { + return Err(MemoryStoreError::NotFound(record.id.to_string())); + } + Ok(()) +} +``` + +#### `delete` + +```rust +async fn delete(&self, id: Uuid) -> MemoryStoreResult<()> +``` + +Single `DELETE` by id. `scheduling`, `edges`, and `review_events` all +have `ON DELETE CASCADE` on their `memory_id` foreign key, so this one +statement clears every dependent row. + +```rust +async fn delete(&self, id: Uuid) -> MemoryStoreResult<()> { + let rows = sqlx::query!( + "DELETE FROM knowledge_nodes WHERE id = $1", + id, + ) + .execute(&self.pool) + .await? + .rows_affected(); + + if rows == 0 { + return Err(MemoryStoreError::NotFound(id.to_string())); + } + Ok(()) +} +``` + +### Search (single-branch variants) + +The full hybrid `search` is implemented in `0002e-hybrid-search.md`. +The two single-branch variants below ship in this sub-plan. + +#### `fts_search` + +```rust +async fn fts_search(&self, text: &str, limit: usize) -> MemoryStoreResult> +``` + +PostgreSQL full-text search using the precomputed `search_vec` tsvector +column and `websearch_to_tsquery` (handles bare words, phrases, and +boolean operators). Ranking with `ts_rank_cd` (cover-density) so longer +matches outrank shorter ones; the SQLite backend uses BM25 from FTS5 but +the trait contract only requires "higher is better". + +```rust +async fn fts_search( + &self, + text: &str, + limit: usize, +) -> MemoryStoreResult> { + let limit = limit.min(1000) as i64; + let rows = sqlx::query!( + r#" + SELECT + m.id AS "id!: Uuid", + m.owner_user_id AS "owner_user_id!: Uuid", + m.visibility, + m.shared_with_groups AS "shared_with_groups!: Vec", + m.codebase, + m.content, + m.node_type, + m.tags AS "tags!: Vec", + m.domains AS "domains!: Vec", + m.domain_scores AS "domain_scores!: serde_json::Value", + m.embedding AS "embedding: Vector", + m.metadata AS "metadata!: serde_json::Value", + m.created_at AS "created_at!: DateTime", + m.updated_at AS "updated_at!: DateTime", + ts_rank_cd(m.search_vec, websearch_to_tsquery('english', $1)) + AS "score!: f64" + FROM knowledge_nodes m + WHERE m.search_vec @@ websearch_to_tsquery('english', $1) + ORDER BY score DESC + LIMIT $2 + "#, + text, + limit, + ) + .fetch_all(&self.pool) + .await?; + + let mut out = Vec::with_capacity(rows.len()); + for r in rows { + let rec = row_to_record( + r.id, r.content, r.node_type, r.tags, r.domains, + r.domain_scores, r.codebase, r.owner_user_id, r.visibility, + r.shared_with_groups, r.embedding, r.metadata, + r.created_at, r.updated_at, + )?; + out.push(SearchResult { + record: rec, + score: r.score, + fts_score: Some(r.score), + vector_score: None, + }); + } + Ok(out) +} +``` + +The `'english'` text-search configuration matches the GIN index built in +`0001_init.up.sql`. If a future migration parameterises the config, both +the index and this query change together. + +#### `vector_search` + +```rust +async fn vector_search(&self, embedding: &[f32], limit: usize) -> MemoryStoreResult> +``` + +pgvector cosine distance. The HNSW index on `embedding` (built in +`0002_hnsw.up.sql` with `vector_cosine_ops`) makes the `<=>` operator +index-accelerated. We convert the returned distance (0 = identical, 2 = +opposite for cosine on normalized vectors) to a similarity in `[0, 1]` +via `1 - distance`; this matches the SQLite backend's convention. + +```rust +async fn vector_search( + &self, + embedding: &[f32], + limit: usize, +) -> MemoryStoreResult> { + let query_vec = Vector::from(embedding.to_vec()); + let limit = limit.min(1000) as i64; + + let rows = sqlx::query!( + r#" + SELECT + m.id AS "id!: Uuid", + m.owner_user_id AS "owner_user_id!: Uuid", + m.visibility, + m.shared_with_groups AS "shared_with_groups!: Vec", + m.codebase, + m.content, + m.node_type, + m.tags AS "tags!: Vec", + m.domains AS "domains!: Vec", + m.domain_scores AS "domain_scores!: serde_json::Value", + m.embedding AS "embedding: Vector", + m.metadata AS "metadata!: serde_json::Value", + m.created_at AS "created_at!: DateTime", + m.updated_at AS "updated_at!: DateTime", + (1.0 - (m.embedding <=> $1)) AS "score!: f64" + FROM knowledge_nodes m + WHERE m.embedding IS NOT NULL + ORDER BY m.embedding <=> $1 + LIMIT $2 + "#, + query_vec as Vector, + limit, + ) + .fetch_all(&self.pool) + .await?; + + let mut out = Vec::with_capacity(rows.len()); + for r in rows { + let rec = row_to_record( + r.id, r.content, r.node_type, r.tags, r.domains, + r.domain_scores, r.codebase, r.owner_user_id, r.visibility, + r.shared_with_groups, r.embedding, r.metadata, + r.created_at, r.updated_at, + )?; + out.push(SearchResult { + record: rec, + score: r.score, + fts_score: None, + vector_score: Some(r.score), + }); + } + Ok(out) +} +``` + +The `query_vec as Vector` cast is the same type-annotation trick as +`insert` -- sqlx needs the concrete pgvector type to wire up encoding. +The `ORDER BY m.embedding <=> $1` (no `score`) is intentional: it lets +the HNSW index serve the query directly. Sorting by the computed +`score` column would force a sequential scan because the index orders +by distance, not similarity. + +### Scheduling + +The Postgres `scheduling` table is a separate row keyed on `memory_id`, +not embedded in `knowledge_nodes` (unlike SQLite where FSRS columns live on +`knowledge_nodes`). The bodies abstract that difference at the SQL +boundary; callers see the same `SchedulingState` value. + +#### `get_scheduling` + +```rust +async fn get_scheduling(&self, memory_id: Uuid) -> MemoryStoreResult> +``` + +```rust +async fn get_scheduling( + &self, + memory_id: Uuid, +) -> MemoryStoreResult> { + let row = sqlx::query!( + r#" + SELECT + memory_id AS "memory_id!: Uuid", + stability AS "stability!: f64", + difficulty AS "difficulty!: f64", + retrievability AS "retrievability!: f64", + last_review AS "last_review: DateTime", + next_review AS "next_review: DateTime", + reps AS "reps!: i32", + lapses AS "lapses!: i32" + FROM scheduling + WHERE memory_id = $1 + "#, + memory_id, + ) + .fetch_optional(&self.pool) + .await?; + + Ok(row.map(|r| SchedulingState { + memory_id: r.memory_id, + stability: r.stability, + difficulty: r.difficulty, + retrievability: r.retrievability, + last_review: r.last_review, + next_review: r.next_review, + reps: r.reps as u32, + lapses: r.lapses as u32, + })) +} +``` + +#### `update_scheduling` + +```rust +async fn update_scheduling(&self, state: &SchedulingState) -> MemoryStoreResult<()> +``` + +Upsert -- the `INSERT ... ON CONFLICT DO UPDATE` form -- so cognitive +modules that update scheduling for a freshly-inserted memory don't have +to race with the seed row from `insert`. + +```rust +async fn update_scheduling( + &self, + state: &SchedulingState, +) -> MemoryStoreResult<()> { + sqlx::query!( + r#" + INSERT INTO scheduling ( + memory_id, stability, difficulty, retrievability, + last_review, next_review, reps, lapses + ) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8) + ON CONFLICT (memory_id) DO UPDATE SET + stability = EXCLUDED.stability, + difficulty = EXCLUDED.difficulty, + retrievability = EXCLUDED.retrievability, + last_review = EXCLUDED.last_review, + next_review = EXCLUDED.next_review, + reps = EXCLUDED.reps, + lapses = EXCLUDED.lapses + "#, + state.memory_id, + state.stability, + state.difficulty, + state.retrievability, + state.last_review, + state.next_review, + state.reps as i32, + state.lapses as i32, + ) + .execute(&self.pool) + .await?; + Ok(()) +} +``` + +#### `get_due_memories` + +```rust +async fn get_due_memories( + &self, + before: DateTime, + limit: usize, +) -> MemoryStoreResult> +``` + +Join `knowledge_nodes` and `scheduling`, filter on `next_review <= before`. +Single query returns both halves of the tuple. + +```rust +async fn get_due_memories( + &self, + before: DateTime, + limit: usize, +) -> MemoryStoreResult> { + let limit = limit.min(10_000) as i64; + let rows = sqlx::query!( + r#" + SELECT + m.id AS "id!: Uuid", + m.owner_user_id AS "owner_user_id!: Uuid", + m.visibility, + m.shared_with_groups AS "shared_with_groups!: Vec", + m.codebase, + m.content, + m.node_type, + m.tags AS "tags!: Vec", + m.domains AS "domains!: Vec", + m.domain_scores AS "domain_scores!: serde_json::Value", + m.embedding AS "embedding: Vector", + m.metadata AS "metadata!: serde_json::Value", + m.created_at AS "created_at!: DateTime", + m.updated_at AS "updated_at!: DateTime", + s.stability AS "stability!: f64", + s.difficulty AS "difficulty!: f64", + s.retrievability AS "retrievability!: f64", + s.last_review AS "last_review: DateTime", + s.next_review AS "next_review: DateTime", + s.reps AS "reps!: i32", + s.lapses AS "lapses!: i32" + FROM knowledge_nodes m + JOIN scheduling s ON s.memory_id = m.id + WHERE s.next_review IS NOT NULL AND s.next_review <= $1 + ORDER BY s.next_review ASC + LIMIT $2 + "#, + before, + limit, + ) + .fetch_all(&self.pool) + .await?; + + let mut out = Vec::with_capacity(rows.len()); + for r in rows { + let rec = row_to_record( + r.id, r.content, r.node_type, r.tags, r.domains, + r.domain_scores, r.codebase, r.owner_user_id, r.visibility, + r.shared_with_groups, r.embedding, r.metadata, + r.created_at, r.updated_at, + )?; + let state = SchedulingState { + memory_id: rec.id, + stability: r.stability, + difficulty: r.difficulty, + retrievability: r.retrievability, + last_review: r.last_review, + next_review: r.next_review, + reps: r.reps as u32, + lapses: r.lapses as u32, + }; + out.push((rec, state)); + } + Ok(out) +} +``` + +### Graph (edges) + +#### `add_edge` + +```rust +async fn add_edge(&self, edge: &MemoryEdge) -> MemoryStoreResult<()> +``` + +`INSERT ... ON CONFLICT` -- updating the weight if an edge already +exists (matches SQLite's `save_connection` semantics). + +```rust +async fn add_edge(&self, edge: &MemoryEdge) -> MemoryStoreResult<()> { + sqlx::query!( + r#" + INSERT INTO edges ( + source_id, target_id, edge_type, weight, created_at + ) + VALUES ($1, $2, $3, $4, $5) + ON CONFLICT (source_id, target_id, edge_type) DO UPDATE SET + weight = EXCLUDED.weight + "#, + edge.source_id, + edge.target_id, + edge.edge_type, + edge.weight, + edge.created_at, + ) + .execute(&self.pool) + .await?; + Ok(()) +} +``` + +#### `get_edges` + +```rust +async fn get_edges( + &self, + node_id: Uuid, + edge_type: Option<&str>, +) -> MemoryStoreResult> +``` + +Return every edge incident to `node_id` in either direction, optionally +filtered by `edge_type`. The optional filter binds as nullable; `$2 IS +NULL OR edge_type = $2` keeps the prepared statement reusable. + +```rust +async fn get_edges( + &self, + node_id: Uuid, + edge_type: Option<&str>, +) -> MemoryStoreResult> { + let rows = sqlx::query!( + r#" + SELECT + source_id AS "source_id!: Uuid", + target_id AS "target_id!: Uuid", + edge_type, + weight AS "weight!: f64", + created_at AS "created_at!: DateTime" + FROM edges + WHERE (source_id = $1 OR target_id = $1) + AND ($2::text IS NULL OR edge_type = $2) + "#, + node_id, + edge_type, + ) + .fetch_all(&self.pool) + .await?; + + Ok(rows + .into_iter() + .map(|r| MemoryEdge { + source_id: r.source_id, + target_id: r.target_id, + edge_type: r.edge_type, + weight: r.weight, + created_at: r.created_at, + }) + .collect()) +} +``` + +#### `remove_edge` + +```rust +async fn remove_edge(&self, source: Uuid, target: Uuid) -> MemoryStoreResult<()> +``` + +Note: the live trait signature is two args (`source`, `target`). The +master plan's stale three-arg signature including `edge_type` is not +implemented -- the live trait surface wins. Deletes every edge between +the pair regardless of `edge_type`. + +```rust +async fn remove_edge( + &self, + source: Uuid, + target: Uuid, +) -> MemoryStoreResult<()> { + sqlx::query!( + "DELETE FROM edges WHERE source_id = $1 AND target_id = $2", + source, + target, + ) + .execute(&self.pool) + .await?; + Ok(()) +} +``` + +#### `get_neighbors` + +```rust +async fn get_neighbors( + &self, + node_id: Uuid, + depth: usize, +) -> MemoryStoreResult> +``` + +Recursive CTE walks the edge graph outward from `node_id` for up to +`depth` hops. Weights compound multiplicatively along the path (same as +SQLite BFS). Cap the visited set at 256 rows to match SQLite. Direction +is treated as undirected by unioning both halves of each edge inside +the CTE. + +```rust +async fn get_neighbors( + &self, + node_id: Uuid, + depth: usize, +) -> MemoryStoreResult> { + if depth == 0 { + let Some(rec) = self.get(node_id).await? else { + return Err(MemoryStoreError::NotFound(node_id.to_string())); + }; + return Ok(vec![(rec, 1.0)]); + } + + let depth_i = depth.min(16) as i32; + let rows = sqlx::query!( + r#" + WITH RECURSIVE walk(node_id, weight, hops) AS ( + SELECT $1::uuid, 1.0::float8, 0 + UNION ALL + SELECT + CASE WHEN e.source_id = w.node_id THEN e.target_id + ELSE e.source_id END, + w.weight * e.weight, + w.hops + 1 + FROM walk w + JOIN edges e + ON e.source_id = w.node_id OR e.target_id = w.node_id + WHERE w.hops < $2 + ), + best AS ( + SELECT node_id, MAX(weight) AS weight + FROM walk + GROUP BY node_id + LIMIT 256 + ) + SELECT + m.id AS "id!: Uuid", + m.owner_user_id AS "owner_user_id!: Uuid", + m.visibility, + m.shared_with_groups AS "shared_with_groups!: Vec", + m.codebase, + m.content, + m.node_type, + m.tags AS "tags!: Vec", + m.domains AS "domains!: Vec", + m.domain_scores AS "domain_scores!: serde_json::Value", + m.embedding AS "embedding: Vector", + m.metadata AS "metadata!: serde_json::Value", + m.created_at AS "created_at!: DateTime", + m.updated_at AS "updated_at!: DateTime", + b.weight AS "weight!: f64" + FROM best b + JOIN knowledge_nodes m ON m.id = b.node_id + "#, + node_id, + depth_i, + ) + .fetch_all(&self.pool) + .await?; + + let mut out = Vec::with_capacity(rows.len()); + for r in rows { + let rec = row_to_record( + r.id, r.content, r.node_type, r.tags, r.domains, + r.domain_scores, r.codebase, r.owner_user_id, r.visibility, + r.shared_with_groups, r.embedding, r.metadata, + r.created_at, r.updated_at, + )?; + out.push((rec, r.weight)); + } + Ok(out) +} +``` + +The CTE can visit a node multiple times via different paths; the `best` +sub-CTE picks the highest weight per node. The `LIMIT 256` matches the +SQLite BFS cap. Postgres' recursive CTE is breadth-first by hop count +because of the `WHERE w.hops < $2` predicate. + +### Domains (Phase 4 populates; Phase 2 ships CRUD) + +The `domains` table is empty in Phase 2; these methods exist so the +trait surface is complete but they do not get exercised until Phase 4 +HDBSCAN clustering runs. + +#### `list_domains` + +```rust +async fn list_domains(&self) -> MemoryStoreResult> +``` + +```rust +async fn list_domains(&self) -> MemoryStoreResult> { + let rows = sqlx::query!( + r#" + SELECT + id, + label, + centroid AS "centroid: Vector", + top_terms AS "top_terms!: Vec", + memory_count AS "memory_count!: i64", + created_at AS "created_at!: DateTime" + FROM domains + ORDER BY created_at ASC + "# + ) + .fetch_all(&self.pool) + .await?; + + Ok(rows + .into_iter() + .map(|r| Domain { + id: r.id, + label: r.label, + centroid: r.centroid.map(|v| v.to_vec()).unwrap_or_default(), + top_terms: r.top_terms, + memory_count: r.memory_count as usize, + created_at: r.created_at, + }) + .collect()) +} +``` + +#### `get_domain` + +```rust +async fn get_domain(&self, id: &str) -> MemoryStoreResult> +``` + +```rust +async fn get_domain(&self, id: &str) -> MemoryStoreResult> { + let row = sqlx::query!( + r#" + SELECT + id, + label, + centroid AS "centroid: Vector", + top_terms AS "top_terms!: Vec", + memory_count AS "memory_count!: i64", + created_at AS "created_at!: DateTime" + FROM domains + WHERE id = $1 + "#, + id, + ) + .fetch_optional(&self.pool) + .await?; + + Ok(row.map(|r| Domain { + id: r.id, + label: r.label, + centroid: r.centroid.map(|v| v.to_vec()).unwrap_or_default(), + top_terms: r.top_terms, + memory_count: r.memory_count as usize, + created_at: r.created_at, + })) +} +``` + +#### `upsert_domain` + +```rust +async fn upsert_domain(&self, domain: &Domain) -> MemoryStoreResult<()> +``` + +```rust +async fn upsert_domain(&self, domain: &Domain) -> MemoryStoreResult<()> { + let centroid = if domain.centroid.is_empty() { + None + } else { + Some(Vector::from(domain.centroid.clone())) + }; + + sqlx::query!( + r#" + INSERT INTO domains ( + id, label, centroid, top_terms, memory_count, created_at + ) + VALUES ($1, $2, $3, $4, $5, $6) + ON CONFLICT (id) DO UPDATE SET + label = EXCLUDED.label, + centroid = EXCLUDED.centroid, + top_terms = EXCLUDED.top_terms, + memory_count = EXCLUDED.memory_count + "#, + domain.id, + domain.label, + centroid as Option, + &domain.top_terms as &[String], + domain.memory_count as i64, + domain.created_at, + ) + .execute(&self.pool) + .await?; + Ok(()) +} +``` + +#### `delete_domain` + +```rust +async fn delete_domain(&self, id: &str) -> MemoryStoreResult<()> +``` + +```rust +async fn delete_domain(&self, id: &str) -> MemoryStoreResult<()> { + sqlx::query!( + "DELETE FROM domains WHERE id = $1", + id, + ) + .execute(&self.pool) + .await?; + Ok(()) +} +``` + +#### `classify` + +```rust +async fn classify(&self, embedding: &[f32]) -> MemoryStoreResult> +``` + +The Postgres backend can ship this as a single SQL query against the +empty `domains` table -- it correctly returns an empty vector in Phase +2 and starts returning real scores in Phase 4 without any code change. + +```rust +async fn classify( + &self, + embedding: &[f32], +) -> MemoryStoreResult> { + let query_vec = Vector::from(embedding.to_vec()); + let rows = sqlx::query!( + r#" + SELECT + id, + (1.0 - (centroid <=> $1)) AS "score!: f64" + FROM domains + WHERE centroid IS NOT NULL + ORDER BY score DESC + "#, + query_vec as Vector, + ) + .fetch_all(&self.pool) + .await?; + + Ok(rows.into_iter().map(|r| (r.id, r.score)).collect()) +} +``` + +### Bulk / maintenance + +#### `count` + +```rust +async fn count(&self) -> MemoryStoreResult +``` + +```rust +async fn count(&self) -> MemoryStoreResult { + let n: i64 = sqlx::query_scalar!("SELECT COUNT(*) FROM knowledge_nodes") + .fetch_one(&self.pool) + .await? + .unwrap_or(0); + Ok(n as usize) +} +``` + +#### `get_stats` + +```rust +async fn get_stats(&self) -> MemoryStoreResult +``` + +Aggregate counts across `knowledge_nodes`, `edges`, `domains`. Read the +registry inline. + +```rust +async fn get_stats(&self) -> MemoryStoreResult { + let row = sqlx::query!( + r#" + SELECT + (SELECT COUNT(*) FROM knowledge_nodes) + AS "total_memories!: i64", + (SELECT COUNT(*) FROM knowledge_nodes WHERE embedding IS NOT NULL) + AS "memories_with_embeddings!: i64", + (SELECT COUNT(*) FROM edges) + AS "total_edges!: i64", + (SELECT COUNT(*) FROM domains) + AS "total_domains!: i64", + (SELECT name FROM embedding_model WHERE id = 1) + AS "registered_model_name: String", + (SELECT dimension FROM embedding_model WHERE id = 1) + AS "registered_model_dim: i32" + "# + ) + .fetch_one(&self.pool) + .await?; + + Ok(StoreStats { + total_memories: row.total_memories as usize, + memories_with_embeddings: row.memories_with_embeddings as usize, + total_edges: row.total_edges as usize, + total_domains: row.total_domains as usize, + registered_model_name: row.registered_model_name, + registered_model_dim: row.registered_model_dim.map(|d| d as usize), + }) +} +``` + +#### `vacuum` + +```rust +async fn vacuum(&self) -> MemoryStoreResult<()> +``` + +`VACUUM` cannot run inside a transaction. sqlx wraps each `query!` +invocation in an implicit transaction when it grabs a pooled +connection, but it does not -- the pool hands out a raw connection +that runs statements in autocommit mode by default. The safe path is +to acquire a connection explicitly and `execute` each statement +separately so neither participates in a transaction. + +```rust +async fn vacuum(&self) -> MemoryStoreResult<()> { + let mut conn = self.pool.acquire().await?; + sqlx::query("VACUUM ANALYZE knowledge_nodes") + .execute(conn.as_mut()) + .await?; + sqlx::query("VACUUM ANALYZE scheduling") + .execute(conn.as_mut()) + .await?; + sqlx::query("VACUUM ANALYZE edges") + .execute(conn.as_mut()) + .await?; + Ok(()) +} +``` + +`conn.as_mut()` yields a `&mut PgConnection`, which sqlx accepts as an +executor. Using `&self.pool` here would let sqlx pick a fresh +connection per statement (still fine, but two extra acquisitions). Note +we do NOT vacuum `domains`, `edges`-related lookup tables (`users` / +`groups` etc.) -- they are either empty in Phase 2 or low-churn and the +nightly autovacuum suffices. + +--- + +## Visibility filter posture + +ADR 0002 D7 declares the future Phase 3 visibility filter (reproduced +here for clarity): + +```sql +WHERE + (visibility = 'private' AND owner_user_id = $me) + OR (visibility = 'group' + AND (owner_user_id = $me OR shared_with_groups && $my_group_ids)) + OR visibility = 'public' +``` + +**Phase 2 does NOT apply this filter.** Every body above reads and +writes the rows it touches regardless of `owner_user_id` or +`visibility` because there is exactly one user in Phase 2 mode (the +bootstrap user from `0001_init.up.sql`). The reviewer should NOT expect +`WHERE owner_user_id = $...` clauses in Phase 2 method bodies. + +Phase 3 introduces an `AuthContext` parameter on the trait methods and +threads it into each WHERE clause. That migration is purely additive +(adds a parameter, adds a clause); it does not need a schema migration +because the columns and indexes are already in place. + +The four new `MemoryRecord` fields ARE populated correctly in Phase 2 +(insert writes them, get/search read them) so that exported archives +and replicated rows round-trip the visibility intent the moment Phase +3 enables filtering. + +--- + +## Offline sqlx cache + +`sqlx::query!` and `sqlx::query_as!` validate every SQL string at +compile time by contacting a live database. To keep CI builds from +needing a Postgres on the build host, sqlx supports an offline cache +in `/.sqlx/` containing one JSON file per validated query. + +This sub-plan is where `.sqlx/` is first populated and committed. + +Workflow: + +1. Ensure a local Postgres is running with the same schema CI will see: + + ```bash + cd crates/vestige-core + export DATABASE_URL="postgres://vestige:vestige@127.0.0.1:5432/vestige_dev" + sqlx database create + sqlx migrate run --source migrations/postgres + ``` + +2. Generate the offline cache: + + ```bash + cargo sqlx prepare --workspace -- --features postgres-backend + ``` + + This walks every `sqlx::query!` invocation under the active feature + flags and writes `crates/vestige-core/.sqlx/query-.json`. The + `--workspace` flag is needed because `vestige-mcp` enables the + `postgres-backend` feature transitively in `0002b-pool-and-config.md`. + +3. Stage and commit the cache directory: + + ```bash + git add crates/vestige-core/.sqlx/ + git commit -m "store: populate sqlx offline cache for postgres backend" + ``` + +4. Add to repo `.gitignore` adjustments (only if entries already deny + `target/` or similar globs): leave `.sqlx/` excluded from any + ignore globs. Specifically the workspace root `.gitignore` does NOT + contain a `.sqlx` line; if a future PR adds one, this sub-plan's + commit reverts it. + +5. CI runs `SQLX_OFFLINE=true cargo check --features postgres-backend`. + sqlx falls back to the JSON cache when `SQLX_OFFLINE=true` is set, + so CI does not need network access to a Postgres. + +Every time a `query!` invocation changes -- add a column, change a +WHERE clause, rename a binding -- re-run `cargo sqlx prepare` and +commit the updated `.sqlx/` files. The agent implementing this sub-plan +runs `cargo sqlx prepare` as the last step before opening the PR. + +--- + +## Verification + +Three layers of verification before merging this sub-plan. + +### 1. Compile and lint + +```bash +cargo check --workspace --features postgres-backend +cargo build --workspace --features postgres-backend +cargo clippy --workspace --features postgres-backend -- -D warnings + +# SQLite-only build still works (mutual compilability per CLAUDE.md): +cargo check --workspace --no-default-features --features embeddings,vector-search +``` + +### 2. Offline cache builds + +```bash +SQLX_OFFLINE=true cargo check --workspace --features postgres-backend +``` + +This is what CI will run. If it fails, `cargo sqlx prepare` was not +re-run after the last query change. + +### 3. Integration round-trip test (testcontainers) + +New test file: +`crates/vestige-core/tests/postgres_round_trip.rs`. Skipped unless the +`postgres-backend` feature is active and Docker / Podman is available. + +```rust +#![cfg(feature = "postgres-backend")] + +use chrono::Utc; +use testcontainers::{clients, GenericImage}; +use uuid::Uuid; +use vestige_core::storage::memory_store::{ + LocalMemoryStore, MemoryEdge, MemoryRecord, SchedulingState, Visibility, + LOCAL_USER_ID, +}; +use vestige_core::storage::postgres::PgMemoryStore; + +#[tokio::test] +async fn round_trip_crud_search_scheduling_edges() { + let docker = clients::Cli::default(); + let image = GenericImage::new("pgvector/pgvector", "pg16") + .with_env_var("POSTGRES_PASSWORD", "test") + .with_env_var("POSTGRES_DB", "vestige_test") + .with_exposed_port(5432); + let container = docker.run(image); + let port = container.get_host_port_ipv4(5432); + let url = format!("postgres://postgres:test@127.0.0.1:{port}/vestige_test"); + + let store = PgMemoryStore::connect(&url, 5).await.expect("connect"); + + // Register the model (typmod stamp). + store.register_model(&fixture_signature(384)).await.expect("register"); + + // insert -> get -> update -> delete. + let mut rec = fixture_record(); + let id = store.insert(&rec).await.expect("insert"); + let fetched = store.get(id).await.expect("get").expect("present"); + assert_eq!(fetched.content, rec.content); + assert_eq!(fetched.owner_user_id, LOCAL_USER_ID); + assert_eq!(fetched.visibility, Visibility::Private); + + rec.content = "edited".to_string(); + store.update(&rec).await.expect("update"); + assert_eq!(store.get(id).await.unwrap().unwrap().content, "edited"); + + // fts_search. + let hits = store.fts_search("edited", 10).await.expect("fts"); + assert!(hits.iter().any(|h| h.record.id == id)); + + // vector_search. + let emb = rec.embedding.clone().unwrap(); + let vhits = store.vector_search(&emb, 10).await.expect("vector"); + assert!(vhits.iter().any(|h| h.record.id == id)); + + // scheduling round-trip. + let sched = store.get_scheduling(id).await.unwrap().expect("seeded"); + let new_state = SchedulingState { + memory_id: id, + stability: 5.5, + difficulty: 0.2, + retrievability: 0.95, + last_review: Some(Utc::now()), + next_review: Some(Utc::now() + chrono::Duration::days(3)), + reps: sched.reps + 1, + lapses: sched.lapses, + }; + store.update_scheduling(&new_state).await.expect("update sched"); + let after = store.get_scheduling(id).await.unwrap().unwrap(); + assert_eq!(after.reps, new_state.reps); + + // edges. + let other = fixture_record(); + let other_id = store.insert(&other).await.unwrap(); + let edge = MemoryEdge { + source_id: id, + target_id: other_id, + edge_type: "semantic".to_string(), + weight: 0.8, + created_at: Utc::now(), + }; + store.add_edge(&edge).await.expect("add_edge"); + let edges = store.get_edges(id, None).await.unwrap(); + assert_eq!(edges.len(), 1); + let neighbors = store.get_neighbors(id, 1).await.unwrap(); + assert!(neighbors.iter().any(|(r, _)| r.id == other_id)); + store.remove_edge(id, other_id).await.expect("remove_edge"); + assert!(store.get_edges(id, None).await.unwrap().is_empty()); + + // delete -> cascade. + store.delete(id).await.expect("delete"); + assert!(store.get(id).await.unwrap().is_none()); + assert!(store.get_scheduling(id).await.unwrap().is_none()); +} + +fn fixture_record() -> MemoryRecord { + MemoryRecord { + id: Uuid::new_v4(), + domains: vec![], + domain_scores: Default::default(), + content: "the quick brown fox jumps over the lazy dog".into(), + node_type: "fact".into(), + tags: vec!["test".into()], + embedding: Some(vec![0.1_f32; 384]), + created_at: Utc::now(), + updated_at: Utc::now(), + metadata: serde_json::json!({}), + owner_user_id: LOCAL_USER_ID, + visibility: Visibility::Private, + shared_with_groups: vec![], + codebase: Some("vestige".to_string()), + } +} + +fn fixture_signature(dim: usize) -> vestige_core::storage::memory_store::ModelSignature { + vestige_core::storage::memory_store::ModelSignature { + name: "test/model".to_string(), + dimension: dim, + hash: "0".repeat(64), + } +} +``` + +Add `testcontainers = "0.20"` to `[dev-dependencies]` under +`#[cfg(feature = "postgres-backend")]` gating. The test is the slowest +in the suite (spawns a Docker container, ~5 s startup); annotate with +`#[ignore]` if CI runtime budget requires opt-in execution. + +### 4. Manual smoke (optional but recommended) + +```bash +# Tear down any prior database. +make postgres-down ; make postgres-up +DATABASE_URL=$(make postgres-url) cargo test \ + -p vestige-core --features postgres-backend -- --include-ignored +``` + +The `postgres-up` / `postgres-down` / `postgres-url` make targets are +defined in `docs/plans/local-dev-postgres-setup.md`. + +--- + +## Acceptance criteria + +This sub-plan is complete when ALL of the following hold: + +1. `cargo build --workspace --features postgres-backend` succeeds with + zero warnings. +2. `cargo clippy --workspace --features postgres-backend -- -D warnings` + succeeds. +3. `cargo build --workspace --no-default-features --features embeddings,vector-search` + still succeeds (the SQLite-only build is not regressed). +4. `SQLX_OFFLINE=true cargo check --workspace --features postgres-backend` + succeeds. `crates/vestige-core/.sqlx/` exists and contains one JSON + file per `sqlx::query!` / `sqlx::query_as!` invocation in the + Postgres backend. +5. Zero `todo!()` macros remain in + `crates/vestige-core/src/storage/postgres/mod.rs`. The only + exception is the body of the trait method `search` -- that method + stays `todo!()` until `0002e-hybrid-search.md` lands. +6. `crates/vestige-core/src/storage/postgres/registry.rs` exists with + the three functions described above + (`fetch_registry`, `ensure_registry`, `update_registry_for_reembed`). +7. `MemoryRecord` carries the four new fields + (`owner_user_id`, `visibility`, `shared_with_groups`, `codebase`) + and the `Visibility` enum is exported alongside it. The SQLite + backend reads and writes the same four fields. +8. The `tests/postgres_round_trip.rs` integration test passes against + a `pgvector/pgvector:pg16` container (insert / get / update / delete + / fts_search / vector_search / get_scheduling / update_scheduling + / add_edge / get_edges / remove_edge / get_neighbors / cascade + delete). +9. No visibility filter clause is present in any Phase 2 method body. + `WHERE owner_user_id = ...`, `WHERE visibility = ...`, and + `shared_with_groups && ...` do not appear anywhere in + `crates/vestige-core/src/storage/postgres/`. +10. `cargo sqlx prepare` was the last command run before commit; the + diff includes `.sqlx/` changes if any query changed. diff --git a/docs/plans/0002e-hybrid-search.md b/docs/plans/0002e-hybrid-search.md new file mode 100644 index 0000000..1f45174 --- /dev/null +++ b/docs/plans/0002e-hybrid-search.md @@ -0,0 +1,825 @@ +# Phase 2 Sub-Plan 0002e -- Hybrid RRF Search + +**Status**: Ready +**Depends on**: +- `0002a-skeleton-and-feature-gate.md` (the `postgres-backend` feature flag + exists and `PgMemoryStore` compiles with `todo!()` bodies). +- `0002b-pool-and-config.md` (a working `PgPool` reaches the backend). +- `0002c-migrations.md` (migration `0001_init` has created the `knowledge_nodes` + table with the D7 columns -- `owner_user_id`, `visibility`, + `shared_with_groups` -- and the D8 column `codebase`; migration `0002_hnsw` + has built the HNSW index). +- `0002d-store-impl-bodies.md` (real CRUD bodies exist so the integration + tests below can seed data through the trait surface rather than raw SQL). + +This sub-plan covers master plan 0002 deliverable D5: the hybrid RRF search +query implementation in `crates/vestige-core/src/storage/postgres/search.rs`, +plus the `search`, `fts_search`, and `vector_search` method bodies in +`crates/vestige-core/src/storage/postgres/mod.rs` that delegate into it. + +--- + +## Context + +This is one of the more performance-sensitive sub-plans in Phase 2. Every +search call from the cognitive engine -- the 7-stage retrieval pipeline, +`session_context`, `predict`, `deep_reference`, the dashboard -- bottoms out +in `MemoryStore::search`. The Postgres backend has to keep up with the +existing SQLite hybrid path, which combines BM25 over FTS5 with USearch HNSW +in two separate round trips and fuses the rankings in Rust. + +The shape of the win on Postgres is that both branches and the fusion run +inside one statement. The planner sees both CTEs together, the round trip is +single, and the rerank stage runs over a cleanly overfetched candidate set. + +Latency targets live in `0002h-testing-and-benches.md`. This sub-plan is +responsible for producing a correct, schema-stable query that the benches +can drive against. Do not optimise here; correctness and structure first. + +Master plan 0002 D5 (around lines 522-628 of +`docs/plans/0002-phase-2-postgres-backend.md`) sketches the SQL. That +sketch is the starting point, not the finished product. The schema after +the D7 and D8 amendments has more columns than the sketch enumerates, and +the SQLite `search` method (around line 6503 of +`crates/vestige-core/src/storage/sqlite.rs` in the Phase 1 worktree) +documents the semantics this implementation must stay compatible with: + +- Empty `query.limit` defaults to 10. +- `query.text == Some("")` is treated as no text query (degrade to vector). +- `query.embedding == None` is treated as no vector query (degrade to FTS). +- Both empty returns `Ok(vec![])`; not an error. +- The `MemoryRecord` in each `SearchResult` must be populated with all + fields the trait promises, including `domains` and `domain_scores` (Phase + 4 will fill these in; Phase 2 returns the stored values, which may be + empty arrays / empty objects). + +--- + +## Constants + +```rust +/// Reciprocal Rank Fusion smoothing constant from Cormack, Clarke and Buettcher +/// 2009 ("Reciprocal Rank Fusion outperforms Condorcet and individual rank +/// learning methods"). 60 is the canonical default and is robust across most +/// fusion regimes. Do not tune this without a paper-citation-grade reason. +const RRF_K: i32 = 60; + +/// Each branch (FTS, vector) is allowed to return OVERFETCH_MULT x final_limit +/// rows before fusion. Three matches the Phase 1 SQLite overfetch and gives +/// the fusion enough candidates to recover from any single branch's bad +/// recall on a given query. +const OVERFETCH_MULT: i64 = 3; +``` + +These live at module scope in +`crates/vestige-core/src/storage/postgres/search.rs`. They are `pub(crate)` +only if `0002h-testing-and-benches.md` needs to reference them from the +integration tests; otherwise private. + +--- + +## Public API + +```rust +#![cfg(feature = "postgres-backend")] + +use pgvector::Vector; +use sqlx::PgPool; + +use crate::storage::memory_store::{ + MemoryStoreResult, SearchQuery, SearchResult, +}; + +/// Hybrid RRF search over Postgres FTS and pgvector cosine distance. +/// +/// Branch behavior: +/// - empty text + null embedding -> Ok(vec![]) +/// - empty text + Some(embedding) -> pure vector search (FTS CTE returns +/// zero rows; fusion equals the vector +/// branch) +/// - Some(text) + null embedding -> pure FTS search +/// - Some(text) + Some(embedding) -> full RRF fusion +/// +/// `query.limit == 0` is treated as 10 (matches the SQLite default). +pub(crate) async fn rrf_search( + pool: &PgPool, + query: &SearchQuery, +) -> MemoryStoreResult>; + +/// FTS-only convenience search. Equivalent to calling `rrf_search` with +/// `query.embedding = None`, but uses a dedicated single-branch query that +/// avoids the FULL OUTER JOIN and the params CTE; faster by one planner pass +/// per call. +pub(crate) async fn fts_only( + pool: &PgPool, + text: &str, + limit: usize, +) -> MemoryStoreResult>; + +/// Vector-only convenience search. Dedicated single-branch query for the same +/// latency reason as `fts_only`. +pub(crate) async fn vector_only( + pool: &PgPool, + embedding: &[f32], + limit: usize, +) -> MemoryStoreResult>; +``` + +### Parameter handling + +In `rrf_search`: + +```rust +let final_limit: i32 = if query.limit == 0 { 10 } else { query.limit as i32 }; +let overfetch: i32 = (final_limit as i64 * OVERFETCH_MULT) + .min(i32::MAX as i64) as i32; + +let q_text: &str = query.text.as_deref().unwrap_or(""); +let q_vec: Option = query.embedding.as_ref() + .map(|v| Vector::from(v.clone())); + +let dom_filter: Option<&[String]> = query.domains.as_deref(); +let nt_filter: Option<&[String]> = query.node_types.as_deref(); +let tag_filter: Option<&[String]> = query.tags.as_deref(); + +let min_retr: Option = query.min_retrievability; +``` + +Both branches empty -- `q_text` is empty and `q_vec` is `None` -- returns +`Ok(vec![])` without hitting the database. The SQLite backend has the same +behavior and tests rely on it. + +```rust +if q_text.is_empty() && q_vec.is_none() { + return Ok(Vec::new()); +} +``` + +### `search` method body in `postgres/mod.rs` + +```rust +#[async_trait::async_trait] // or trait_variant after the Phase 1 amendment +impl MemoryStore for PgMemoryStore { + async fn search(&self, query: &SearchQuery) + -> MemoryStoreResult> + { + crate::storage::postgres::search::rrf_search(&self.pool, query).await + } + + async fn fts_search(&self, text: &str, limit: usize) + -> MemoryStoreResult> + { + crate::storage::postgres::search::fts_only(&self.pool, text, limit) + .await + } + + async fn vector_search(&self, embedding: &[f32], limit: usize) + -> MemoryStoreResult> + { + crate::storage::postgres::search::vector_only(&self.pool, embedding, limit) + .await + } +} +``` + +Everything below specifies the inside of those three free functions. + +--- + +## SQL: the hybrid RRF query + +The query is built as one `&'static str` (or `OnceCell`; see "Use +of sqlx::query!" below) and reused. Bound parameters are kept to seven +through a `params` CTE that the rest of the query references by name -- +this keeps the SQL readable and stops the bound-parameter count growing +with each filter clause. + +Bound parameters: + +- `$1`: text query (TEXT, may be empty) +- `$2`: embedding (pgvector::Vector, may be NULL) +- `$3`: overfetch limit per branch (INT) +- `$4`: final limit (INT) +- `$5`: domain filter (TEXT[] or NULL) +- `$6`: node_type filter (TEXT[] or NULL) +- `$7`: tag filter (TEXT[] or NULL) + +If `min_retrievability.is_some()` the outer SELECT adds a JOIN on +`scheduling` and a WHERE clause; that path uses a different prepared +statement (see "min_retrievability filter" below) so the simple-path query +stays free of the join. + +```sql +WITH params AS ( + SELECT + $1::text AS q_text, + $2::vector AS q_vec, + $3::int AS overfetch, + $4::int AS final_limit, + $5::text[] AS dom_filter, + $6::text[] AS nt_filter, + $7::text[] AS tag_filter +), +fts AS ( + SELECT + m.id, + ts_rank_cd( + m.search_vec, + websearch_to_tsquery('english', p.q_text) + ) AS score, + ROW_NUMBER() OVER ( + ORDER BY ts_rank_cd( + m.search_vec, + websearch_to_tsquery('english', p.q_text) + ) DESC + ) AS rank + FROM knowledge_nodes m + CROSS JOIN params p + WHERE p.q_text <> '' + AND m.search_vec @@ websearch_to_tsquery('english', p.q_text) + AND (p.dom_filter IS NULL OR m.domains && p.dom_filter) + AND (p.nt_filter IS NULL OR m.node_type = ANY(p.nt_filter)) + AND (p.tag_filter IS NULL OR m.tags && p.tag_filter) + ORDER BY score DESC + LIMIT (SELECT overfetch FROM params) +), +vec AS ( + SELECT + m.id, + 1.0 - (m.embedding <=> p.q_vec) AS score, + ROW_NUMBER() OVER ( + ORDER BY m.embedding <=> p.q_vec + ) AS rank + FROM knowledge_nodes m + CROSS JOIN params p + WHERE m.embedding IS NOT NULL + AND p.q_vec IS NOT NULL + AND (p.dom_filter IS NULL OR m.domains && p.dom_filter) + AND (p.nt_filter IS NULL OR m.node_type = ANY(p.nt_filter)) + AND (p.tag_filter IS NULL OR m.tags && p.tag_filter) + ORDER BY m.embedding <=> p.q_vec + LIMIT (SELECT overfetch FROM params) +), +fused AS ( + SELECT + COALESCE(f.id, v.id) AS id, + COALESCE(1.0 / (60 + f.rank), 0.0) + + COALESCE(1.0 / (60 + v.rank), 0.0) AS rrf_score, + f.score AS fts_score, + v.score AS vector_score + FROM fts f + FULL OUTER JOIN vec v ON f.id = v.id +) +SELECT + m.id AS "id!: uuid::Uuid", + m.owner_user_id AS "owner_user_id!: uuid::Uuid", + m.visibility AS "visibility!: String", + m.shared_with_groups AS "shared_with_groups!: Vec", + m.codebase AS "codebase: String", + m.domains AS "domains!: Vec", + m.domain_scores AS "domain_scores!: serde_json::Value", + m.content AS "content!: String", + m.node_type AS "node_type!: String", + m.tags AS "tags!: Vec", + m.embedding AS "embedding: pgvector::Vector", + m.metadata AS "metadata!: serde_json::Value", + m.created_at AS "created_at!: chrono::DateTime", + m.updated_at AS "updated_at!: chrono::DateTime", + fused.rrf_score AS "rrf_score!: f64", + fused.fts_score AS "fts_score: f64", + fused.vector_score AS "vector_score: f64" +FROM fused +JOIN knowledge_nodes m ON m.id = fused.id +ORDER BY fused.rrf_score DESC +LIMIT (SELECT final_limit FROM params); +``` + +Notes on the SELECT column list. The D7 columns (`owner_user_id`, +`visibility`, `shared_with_groups`) and the D8 column (`codebase`) are +selected even though Phase 2 does not filter on them yet, so: + +1. The `MemoryRecord` returned to the trait can be populated with the + stored values from day one. Phase 3 will start writing real + `owner_user_id` / `visibility` values; Phase 2 always writes the + single-user defaults (`'00000000-...-0001'`, `'private'`, `'{}'`). The + `MemoryRecord` returned in Phase 2 simply carries those defaults. +2. The schema-drift integration tests (see "Verification") catch the case + where someone adds a NOT NULL column to `knowledge_nodes` without updating + this query. + +Notes on the body: + +- `CROSS JOIN params p` is used instead of the master-plan sketch's + `FROM knowledge_nodes m, params p`. Same plan, clearer intent. +- The `ORDER BY ... LIMIT` inside each branch CTE is there so the planner + can stop early once it has `overfetch` rows; without it the LIMIT is + applied after a full sort over all matches. +- `1.0 - (m.embedding <=> p.q_vec)` converts pgvector's cosine *distance* + to cosine *similarity* in [0, 1] for the `vector_score` output. RRF + itself does not need the similarity -- it uses ranks -- but the trait + surface exposes `vector_score: Option` for caller introspection. +- `RRF_K = 60` is inlined as `60` in the SQL string. A `const` formatter + feels tidier but `60` is a literature constant; spell it out and leave a + comment in the Rust source: `// 60 == RRF_K (Cormack 2009)`. +- `FULL OUTER JOIN` is required: a row that the FTS branch finds and the + vector branch does not must still appear in `fused`, and vice versa. +- `COALESCE(..., 0.0)` on each `1.0 / (60 + rank)` term handles the + no-match-from-this-branch case. The fusion score for a row that only the + FTS branch ranks is `1/(60 + f.rank)` exactly. +- `m.search_vec` is the generated `tsvector` column created in migration + `0001_init` (see D4 of the master plan). + +--- + +## Result row mapping + +`sqlx::query_as::<_, SearchRow>` reads each row into a private struct that +owns the column types exactly as they come back from Postgres. The struct +is converted into a `SearchResult` after fetch. + +```rust +#[derive(sqlx::FromRow)] +struct SearchRow { + id: uuid::Uuid, + owner_user_id: uuid::Uuid, + visibility: String, + shared_with_groups: Vec, + codebase: Option, + domains: Vec, + domain_scores: serde_json::Value, + content: String, + node_type: String, + tags: Vec, + embedding: Option, + metadata: serde_json::Value, + created_at: chrono::DateTime, + updated_at: chrono::DateTime, + rrf_score: f64, + fts_score: Option, + vector_score: Option, +} + +impl SearchRow { + fn into_result(self) -> SearchResult { + use crate::storage::memory_store::MemoryRecord; + use std::collections::HashMap; + + // domain_scores is JSONB; the column always exists, but may be the + // empty object {} when Phase 4 has not classified this memory yet. + let domain_scores: HashMap = + serde_json::from_value(self.domain_scores).unwrap_or_default(); + + let record = MemoryRecord { + id: self.id, + domains: self.domains, + domain_scores, + content: self.content, + node_type: self.node_type, + tags: self.tags, + // pgvector::Vector -> Vec + embedding: self.embedding.map(|v| v.to_vec()), + created_at: self.created_at, + updated_at: self.updated_at, + metadata: self.metadata, + // owner_user_id / visibility / shared_with_groups / codebase + // do not appear on MemoryRecord yet. Phase 3 will decide whether + // to extend MemoryRecord or surface them via a side channel. + // For Phase 2 they are read but discarded here. + }; + + SearchResult { + record, + score: self.rrf_score, + fts_score: self.fts_score, + vector_score: self.vector_score, + } + } +} +``` + +Type mapping summary: + +| SQL type | Rust type | Notes | +|-------------------|--------------------------------------|------------------------------------------------| +| UUID | `uuid::Uuid` | requires sqlx `uuid` feature | +| TEXT | `String` | | +| TEXT NULL | `Option` | used for `codebase` | +| TEXT[] | `Vec` | for `tags`, `domains` | +| UUID[] | `Vec` | for `shared_with_groups` | +| JSONB | `serde_json::Value` | for `metadata`, `domain_scores` | +| TIMESTAMPTZ | `chrono::DateTime` | requires sqlx `chrono` feature | +| VECTOR(N) NULL | `Option` | `.map(|v| v.to_vec())` to `Option>` | +| FLOAT8 | `f64` | | +| FLOAT8 NULL | `Option` | for `fts_score`, `vector_score` | + +If `MemoryRecord` is extended in Phase 3 to carry `owner_user_id`, +`visibility`, `shared_with_groups`, and `codebase`, the conversion above +gets four more fields. Phase 2 reads them so the integration tests can +assert on them via SQL, but the trait surface does not expose them yet. + +--- + +## `fts_only` and `vector_only` -- dedicated single-branch queries + +The master plan offers two options for the convenience methods: reuse +`rrf_search` with one branch nulled, or write dedicated queries. The +dedicated queries win: + +- One CTE instead of three. Planner picks the obvious plan. +- No FULL OUTER JOIN. +- No `params` indirection -- bound parameters used directly. +- The output `score` is the branch's native score (BM25-ish `ts_rank_cd` / + cosine similarity), not an RRF fusion score over one branch. Callers of + `fts_search` and `vector_search` get an intuitive score back. + +### `fts_only` + +Bound parameters: + +- `$1`: text query (TEXT, must be non-empty; the caller guards `text.is_empty()`) +- `$2`: limit (INT) + +```sql +SELECT + m.id AS "id!: uuid::Uuid", + m.owner_user_id AS "owner_user_id!: uuid::Uuid", + m.visibility AS "visibility!: String", + m.shared_with_groups AS "shared_with_groups!: Vec", + m.codebase AS "codebase: String", + m.domains AS "domains!: Vec", + m.domain_scores AS "domain_scores!: serde_json::Value", + m.content AS "content!: String", + m.node_type AS "node_type!: String", + m.tags AS "tags!: Vec", + m.embedding AS "embedding: pgvector::Vector", + m.metadata AS "metadata!: serde_json::Value", + m.created_at AS "created_at!: chrono::DateTime", + m.updated_at AS "updated_at!: chrono::DateTime", + ts_rank_cd(m.search_vec, websearch_to_tsquery('english', $1)) + AS "fts_score!: f64" +FROM knowledge_nodes m +WHERE m.search_vec @@ websearch_to_tsquery('english', $1) +ORDER BY ts_rank_cd(m.search_vec, websearch_to_tsquery('english', $1)) DESC +LIMIT $2; +``` + +The Rust caller maps each row to a `SearchResult` with: + +```rust +SearchResult { + record, + score: fts_score, + fts_score: Some(fts_score), + vector_score: None, +} +``` + +If `text.is_empty()` the caller returns `Ok(Vec::new())` before hitting +the database. `websearch_to_tsquery('english', '')` returns an empty +tsquery that matches nothing; the round-trip is wasted work otherwise. + +### `vector_only` + +Bound parameters: + +- `$1`: embedding (pgvector::Vector) +- `$2`: limit (INT) + +```sql +SELECT + m.id AS "id!: uuid::Uuid", + m.owner_user_id AS "owner_user_id!: uuid::Uuid", + m.visibility AS "visibility!: String", + m.shared_with_groups AS "shared_with_groups!: Vec", + m.codebase AS "codebase: String", + m.domains AS "domains!: Vec", + m.domain_scores AS "domain_scores!: serde_json::Value", + m.content AS "content!: String", + m.node_type AS "node_type!: String", + m.tags AS "tags!: Vec", + m.embedding AS "embedding: pgvector::Vector", + m.metadata AS "metadata!: serde_json::Value", + m.created_at AS "created_at!: chrono::DateTime", + m.updated_at AS "updated_at!: chrono::DateTime", + 1.0 - (m.embedding <=> $1) AS "vector_score!: f64" +FROM knowledge_nodes m +WHERE m.embedding IS NOT NULL +ORDER BY m.embedding <=> $1 +LIMIT $2; +``` + +The Rust caller maps each row to: + +```rust +SearchResult { + record, + score: vector_score, + fts_score: None, + vector_score: Some(vector_score), +} +``` + +Both convenience methods ignore `SearchQuery.domains` / `tags` / +`node_types` / `min_retrievability` -- they take `&str` and `&[f32]` +respectively, not a `SearchQuery`. Callers that want filters on a +single-branch search should call `search` with the other branch input +left at its degrade-to-zero default. + +--- + +## `min_retrievability` filter + +`SearchQuery::min_retrievability: Option` is applied as a final +filter after fusion by joining on the `scheduling` table: + +```sql +-- with-min-retrievability variant: identical CTEs to the base query, only +-- the final SELECT changes. +SELECT + ... (same column list as the base query) ... +FROM fused +JOIN knowledge_nodes m ON m.id = fused.id +JOIN scheduling s ON s.memory_id = m.id +WHERE s.retrievability >= $8 +ORDER BY fused.rrf_score DESC +LIMIT (SELECT final_limit FROM params); +``` + +This is a separate prepared statement -- the eight-parameter variant -- +held alongside the seven-parameter base. The Rust dispatch: + +```rust +if let Some(min_r) = query.min_retrievability { + sqlx::query_as::<_, SearchRow>(QUERY_WITH_MIN_R) + .bind(q_text) + .bind(q_vec) + .bind(overfetch) + .bind(final_limit) + .bind(dom_filter) + .bind(nt_filter) + .bind(tag_filter) + .bind(min_r) + .fetch_all(pool).await? +} else { + sqlx::query_as::<_, SearchRow>(QUERY_BASE) + .bind(q_text) + .bind(q_vec) + .bind(overfetch) + .bind(final_limit) + .bind(dom_filter) + .bind(nt_filter) + .bind(tag_filter) + .fetch_all(pool).await? +} +``` + +Why not unconditionally join: the `scheduling` join is expensive enough on +a large `knowledge_nodes` table that adding it to every search call regresses the +common path. `min_retrievability` is set by the cognitive engine's +accessibility filter and is `None` in most direct callers. + +The same two-variant pattern repeats for `fts_only` and `vector_only`; in +practice callers of those methods rarely set `min_retrievability` (it is +not part of their argument list), so only the base variant is needed +unless the trait surface grows. + +--- + +## Domain / tag / node_type filters + +Each filter is expressed as a NULL-conditional clause inside both branch +CTEs, written using PostgreSQL array operators: + +```sql +AND (p.dom_filter IS NULL OR m.domains && p.dom_filter) +AND (p.nt_filter IS NULL OR m.node_type = ANY(p.nt_filter)) +AND (p.tag_filter IS NULL OR m.tags && p.tag_filter) +``` + +- `&&` is the PostgreSQL "arrays overlap" operator. Matches if any + element in `m.domains` is in the filter array. Index-friendly with a + GIN index on `m.domains` (created in `0001_init`). +- `= ANY(...)` matches `m.node_type` (a scalar) against any element of + the filter array. Index-friendly with a B-tree on `m.node_type`. +- `&&` is used again on `m.tags` (a `TEXT[]`). + +The NULL-conditional form is critical: when the filter parameter is +`NULL`, the clause short-circuits to `TRUE` and contributes nothing to +the WHERE. This keeps a single query reusable across "no filter" and +"filter set" cases without rewriting SQL. + +When the Rust caller passes `None` for a filter, sqlx binds it as `NULL` +of the column type (`text[]`). The cast `$5::text[]` in the `params` CTE +is what tells sqlx the binding type. + +The master plan's draft has each filter clause duplicated across both +branch CTEs. That duplication is correct -- the planner cannot push a +WHERE clause across a FULL OUTER JOIN into both sides automatically; we +do it manually. + +--- + +## Empty-string text query handling + +The base query guards the FTS branch with `WHERE p.q_text <> ''`. + +`websearch_to_tsquery('english', '')` returns an empty tsquery. An empty +tsquery has no lexemes and matches no document; the `@@` operator returns +false for every row. Without the guard, the FTS branch would still run -- +sequential scan, tokenisation per row, comparison -- and return zero +rows. The guard short-circuits at planning time. + +The guard does not affect the FULL OUTER JOIN: when the FTS branch +returns zero rows, the join degenerates to "every row that the vector +branch returned, with `f.id IS NULL` and `f.rank IS NULL`". The +`COALESCE(1.0 / (60 + f.rank), 0.0)` then evaluates to `0.0`, and the +fused score reduces to the vector branch's RRF term alone. This is the +"pure vector search" degrade path. + +Symmetrically, the vector branch guards itself with +`WHERE m.embedding IS NOT NULL AND p.q_vec IS NOT NULL`, which gives the +"pure FTS search" degrade path when the caller passes no embedding. + +The both-empty case (`q_text == ''` and `q_vec IS NULL`) is intercepted +in Rust before the query runs and returns `Ok(vec![])`. Returning empty +rather than error matches the SQLite behavior and is what the Phase 1 +ingest pipeline relies on for "no signal, no results" fallback. + +--- + +## Use of `sqlx::query!` versus `sqlx::query_as` + +`sqlx::query!` and `sqlx::query_as!` are compile-time-checked: the SQL is +sent to a live Postgres at build time, the result schema is validated, and +the generated Rust struct fields are derived. That checking is the +default for every other query in `0002d-store-impl-bodies.md`. + +For the RRF query, the macro path is impractical for two reasons: + +1. **Two structurally different queries** -- the base (seven parameters, + no `scheduling` join) and the `min_retrievability` variant (eight + parameters, with the join). The macro would force two macro + invocations, each producing its own anonymous result struct, and the + result types would not unify. Manual `From` impls would be needed in + both directions. +2. **The dedicated `fts_only` and `vector_only` queries have a different + output column set** (`fts_score!` instead of `rrf_score! + fts_score? + + vector_score?`). Three macro invocations, three structs, three + conversion helpers. + +The chosen pattern is `sqlx::query_as::<_, SearchRow>(SQL_CONST)` with a +single `SearchRow` struct that owns the column types and a single +`SearchRow::into_result` helper. The SQL is held in module-scope `&'static +str` constants: + +```rust +const QUERY_BASE: &str = include_str!("search.rrf.sql"); +const QUERY_WITH_MIN_R: &str = include_str!("search.rrf.min_retr.sql"); +const QUERY_FTS_ONLY: &str = include_str!("search.fts.sql"); +const QUERY_VECTOR_ONLY: &str = include_str!("search.vector.sql"); +``` + +`include_str!` keeps the SQL out of the Rust source. The four `.sql` +files live next to `search.rs` in +`crates/vestige-core/src/storage/postgres/`. + +The cost: schema drift (someone renames `m.codebase` to `m.repo_name`) +will not break the build. The integration tests in "Verification" below +are the safety net. This is a deliberate trade -- it is the one sub-plan +in Phase 2 where runtime flexibility beats compile-time checking. + +If a future contributor wants compile-time checking back for the simple +case, the right move is to introduce a `#[cfg(test)]`-only macro-checked +variant of `QUERY_BASE` and assert at test build time that the macro +agrees with the string. That belongs in `0002h-testing-and-benches.md` if +anywhere. + +--- + +## Verification + +Integration tests live in +`crates/vestige-core/tests/postgres_search.rs`, gated by +`#[cfg(feature = "postgres-backend")]` and `#[ignore]` by default (the +test runner CI workflow in `0002h-testing-and-benches.md` runs them with +`--ignored` against a live Postgres). + +Common harness for every test: + +1. Spin up Postgres via `sqlx::PgPool::connect` against the test URL. +2. Run `sqlx::migrate!("./migrations/postgres").run(&pool)` to bring the + schema up. +3. Register a deterministic test embedder via `register_model` so + `embedding` columns can be written. +4. Seed 50 mixed memories through `MemoryStore::insert` -- mixed + `node_type` (`fact`, `concept`, `event`, `decision`), mixed `tags` + (`rust`, `postgres`, `search`, `dream`, `bug-fix`), mixed `codebase`, + embeddings drawn from three small clusters so vector recall has + structure to find. + +Test cases: + +**T1. Full RRF returns the seeded target.** +Insert a known memory with `content = "FSRS-6 spaced repetition cadence"` +and an embedding from cluster A. Query with +`text = Some("FSRS spaced repetition")` and an embedding near cluster A. +Assert the target memory is in the top 3 of the returned `SearchResult`s +and that both `fts_score` and `vector_score` are `Some` for it. + +**T2. Pure FTS degrade.** +Same target as T1. Query with `text = Some("FSRS spaced repetition")` and +`embedding = None`. Assert the target appears, all results have +`vector_score == None`, `fts_score == Some(_)`, and `score` equals the +fused RRF score (which collapses to one branch's `1.0/(60 + rank)`). + +**T3. Pure vector degrade.** +Same target as T1. Query with `text = Some("")` and +`embedding = Some(cluster_A_vector)`. Assert the target appears, all +results have `fts_score == None`, `vector_score == Some(_)`. + +**T4. Both empty returns `Ok(vec![])`.** +Query with `text = Some("")` and `embedding = None`. Assert exactly an +empty result vector and that no SQL was executed (assert via a +`sqlx::PgPool` query-count handle if convenient; otherwise document that +the short-circuit lives in Rust). + +**T5. `domains` filter.** +Insert one memory with `domains = vec!["domain-x"]` and 49 others without +it. Query with `domains = Some(vec!["domain-x"])` and a matching text. +Assert exactly one result is returned and it is the seeded memory. + +**T6. `tags` filter.** +Same pattern as T5 with `tags = Some(vec!["bug-fix"])`. + +**T7. `node_types` filter.** +Same pattern as T5 with `node_types = Some(vec!["decision"])`. + +**T8. `min_retrievability` filter.** +Seed two memories with the same content + embedding. Write +`scheduling` rows so that one has `retrievability = 0.9` and the other +`0.1`. Query with `min_retrievability = Some(0.5)`. Assert exactly the +high-retrievability memory is returned. + +**T9. `query.limit == 0` defaults to 10.** +Seed 30 matching memories. Query with `limit = 0`. Assert the result +contains exactly 10 entries. + +**T10. `fts_only` and `vector_only` parity.** +For the same target memory, call `fts_only` and `vector_only` directly +and compare against `search` with the corresponding branch zeroed. The +top-1 result must match by id; the scores need only be of the same sign +and magnitude (not bit-identical, because RRF fusion changes the +absolute score). + +**T11. Schema-drift canary.** +Run the base query against an empty `knowledge_nodes` table and `fetch_all` +into `Vec`. Any added NOT NULL column on `knowledge_nodes` that is +not in the SELECT will fail the test at the `try_get` boundary with a +clear error. This is the test that compensates for not using +`sqlx::query!`. + +**T12. Hostile inputs.** +Query with `text = Some("'; DROP TABLE knowledge_nodes; --")` and a normal +embedding. Assert no panic, results returned cleanly, `knowledge_nodes` table +still present. This is symbolic; `websearch_to_tsquery` is parameter- +bound and SQL injection is not actually possible, but the test is cheap +and the assertion is real. + +--- + +## Acceptance criteria + +A reviewer of the implementation PR should be able to confirm: + +1. `crates/vestige-core/src/storage/postgres/search.rs` exists and is + compiled only when `feature = "postgres-backend"` is on. +2. The four `.sql` files (`search.rrf.sql`, + `search.rrf.min_retr.sql`, `search.fts.sql`, `search.vector.sql`) + exist in the same directory and are `include_str!`-ed into module- + scope `&'static str` constants. +3. `RRF_K = 60` and `OVERFETCH_MULT = 3` are defined as constants at + module scope with the Cormack 2009 citation in a comment. +4. The seven-parameter base query is one statement and uses a `params` + CTE; the eight-parameter `min_retrievability` variant adds exactly + one JOIN and one WHERE clause on top of the base. +5. Empty text degrades to pure vector; null embedding degrades to pure + FTS; both empty short-circuits to `Ok(vec![])` in Rust before the + query runs. +6. The SELECT column list in every query includes `owner_user_id`, + `visibility`, `shared_with_groups`, and `codebase` even though Phase 2 + does not filter on them. +7. `SearchRow::into_result` populates a `MemoryRecord` with every field + the trait requires, including `domains` and `domain_scores` decoded + from JSONB. +8. `PgMemoryStore::search`, `PgMemoryStore::fts_search`, and + `PgMemoryStore::vector_search` each delegate to the corresponding + free function with one line of body. +9. All twelve integration tests (`T1` through `T12`) pass against a live + Postgres with the `0001_init` + `0002_hnsw` migrations applied. +10. `cargo build -p vestige-core` succeeds with + `--features postgres-backend` and with the feature off. +11. `cargo clippy -p vestige-core --features postgres-backend -- -D warnings` + is clean. + +When all eleven are true, this sub-plan is done and +`0002f-migrate-cli.md` is unblocked. diff --git a/docs/plans/0002f-migrate-cli.md b/docs/plans/0002f-migrate-cli.md new file mode 100644 index 0000000..457de70 --- /dev/null +++ b/docs/plans/0002f-migrate-cli.md @@ -0,0 +1,1045 @@ +# Phase 2 Sub-Plan 0002f -- SQLite-to-Postgres Migrate CLI + +**Status**: Ready +**Depends on**: +- `0002a-skeleton-and-feature-gate.md` (the `postgres-backend` Cargo feature + and the `crates/vestige-core/src/storage/postgres/` module skeleton). +- `0002b-pool-and-config.md` (`PgPool` construction and `PostgresConfig`). +- `0002c-migrations.md` (the `postgres/migrations/0001_init.up.sql` schema, + including the D7 tenancy columns/tables and the D8 `codebase` column). +- `0002d-store-impl-bodies.md` (real bodies for `PgMemoryStore` trait methods: + `insert`, `register_model`, `add_edge`, `update_scheduling`, etc.; and the + matching source-side reader bodies on `SqliteMemoryStore`, in particular a + windowed-stream API ordered by `(created_at, id)`). + +This sub-plan covers Phase 2 master-plan deliverables D8 (the streaming copy +in `crates/vestige-core/src/storage/postgres/migrate_cli.rs`) and D10 (the +`vestige migrate copy ...` clap subcommand in +`crates/vestige-mcp/src/bin/cli.rs`). Sub-plan `0002g-reembed.md` covers the +`vestige migrate reembed ...` subcommand body; this sub-plan only declares the +`Reembed` clap variant alongside `Copy` so the subcommand layout is final. + +The success criterion is: + +``` +vestige migrate copy --from sqlite --to postgres \ + --sqlite-path ~/.vestige/vestige.db \ + --postgres-url postgresql://localhost/vestige +``` + +streams every row from a Phase 1 SQLite database into a fresh (or partially +populated) Phase 2 Postgres database. Re-running the same command is a no-op +on already-present rows. A `--dry-run` flag prints per-table counts without +writing anything. + +--- + +## Context + +ADR 0002 D2 settled that `PgMemoryStore::connect` mirrors +`SqliteMemoryStore::new`: no `Embedder` in the constructor; the model +signature is stamped by a separate call to `register_model`. The migrator +inherits this symmetry. It opens both backends, validates that the source's +`embedding_model` registry agrees with the destination's (or with the +embedder the user supplied for the destination), and then streams rows. + +ADR 0002 D7 reserved multi-tenancy columns on `knowledge_nodes` (`owner_user_id`, +`visibility`, `shared_with_groups`) and three tables (`users`, `groups`, +`group_memberships`). Phase 2 single-user defaults are the bootstrap row +`'00000000-0000-0000-0000-000000000001'` (`'local'`), `visibility = 'private'`, +empty `shared_with_groups`. The migrator preserves whatever values the source +SQLite holds; it does NOT rewrite owner_user_id from real values to the +bootstrap user. If a Phase 3-aware source has real user rows, those are +copied first (step 5 below) and the foreign key in `knowledge_nodes.owner_user_id` +resolves to the same UUID on the destination. + +ADR 0002 D8 promoted `codebase` to a first-class `TEXT` column. The migrator +reads it as a column on the source side (the Phase 1 amendment's V15 SQLite +migration ensures the column exists; for pre-V15 SQLite the migrator must +detect and fall back to extracting from `metadata->>'codebase'`, see "Source +schema variants" below). + +The Phase 1 `SqliteMemoryStore` is the source backend. `0002d-store-impl-bodies.md` +extends it (and the trait) with a windowed reader ordered by `(created_at, id)` +so the migrator can stream rows in deterministic batches without holding the +full result set in RAM. The migrator assumes that reader exists and produces +`MemoryRecord` instances with all D7+D8 columns populated. + +--- + +## File layout + +``` +crates/vestige-core/src/storage/postgres/migrate_cli.rs -- D8 body +crates/vestige-mcp/src/bin/cli.rs -- D10 clap wiring +tests/phase_2/migrate_test.rs -- integration test +``` + +The migrator lives behind `#[cfg(feature = "postgres-backend")]`. The +`Migrate` clap variant in the CLI is similarly gated. Without the feature, +`vestige` builds and runs exactly as in Phase 1 -- the `migrate` subcommand +simply does not exist. + +--- + +## Plan struct + +```rust +#![cfg(feature = "postgres-backend")] + +use std::path::PathBuf; +use std::sync::Arc; + +use uuid::Uuid; + +use crate::embedder::Embedder; +use crate::storage::memory_store::MemoryStoreError; + +#[derive(Debug, Clone)] +pub struct SqliteToPostgresPlan { + /// Filesystem path to the source SQLite database. Opened read-only. + pub sqlite_path: PathBuf, + + /// libpq-style URL for the destination Postgres database. + pub postgres_url: String, + + /// sqlx pool size for the destination. Default 4. The migrator is + /// single-writer per table for ordering reasons; extra connections are + /// only used for the embedding-model registry probe and for the dry-run + /// COUNT queries that run in parallel with the row scan. + pub max_connections: u32, + + /// Number of rows per Postgres transaction. Default 500. Larger batches + /// reduce commit overhead but increase the amount of work a crash + /// re-runs. + pub batch_size: usize, + + /// If true, count rows per table and emit a report without writing + /// anything to Postgres. + pub dry_run: bool, +} + +impl Default for SqliteToPostgresPlan { + fn default() -> Self { + Self { + sqlite_path: PathBuf::new(), + postgres_url: String::new(), + max_connections: 4, + batch_size: 500, + dry_run: false, + } + } +} +``` + +The struct is public so a future programmatic driver (Rhai script, hero +service, in-process test harness) can call `run_sqlite_to_postgres` without +touching clap. + +--- + +## Report struct + +```rust +#[derive(Debug, Default)] +pub struct MigrationReport { + pub memories_copied: u64, + pub scheduling_rows: u64, + pub edges_copied: u64, + pub review_events_copied: u64, + pub domains_copied: u64, + pub users_copied: u64, + pub groups_copied: u64, + pub group_memberships_copied: u64, + + /// Per-row failures that did not abort the migrator. Each entry pairs + /// the source row id (where derivable) with the error that caused it to + /// be skipped. Rows whose UUID cannot be parsed are reported with + /// `Uuid::nil()` and a descriptive `MemoryStoreError::InvalidInput`. + pub errors: Vec<(Uuid, MemoryStoreError)>, +} +``` + +`errors.is_empty()` is the "clean migration" check. The CLI prints +`errors.len()` at the end and exits non-zero if it is positive. + +Counts are the number of rows the migrator either inserted or skipped due to +ON CONFLICT. They reflect what the source presented, not what the destination +ended up with -- that distinction matters for re-runs: a re-run of a finished +migration reports the same counts but writes zero new rows. + +--- + +## Driver fn + +```rust +pub async fn run_sqlite_to_postgres( + plan: SqliteToPostgresPlan, + embedder: Arc, +) -> MemoryStoreResult; +``` + +Algorithm, step by step: + +### Step 1. Open source SQLite read-only + +Build a SQLite URL with `?mode=ro` so the migrator cannot mutate the source +even by accident: + +```rust +let src_url = format!( + "sqlite://{}?mode=ro", + plan.sqlite_path.display(), +); +let src = SqliteMemoryStore::open_url(&src_url).await?; +``` + +`SqliteMemoryStore::open_url` is added by `0002d-store-impl-bodies.md` as a +small wrapper over the existing `new` that accepts a fully-formed URL. If the +file does not exist, `MemoryStoreError::Init` propagates. + +The source store still runs its own startup-time migrations in `?mode=ro`? +No -- read-only mode rejects writes. The migrator therefore opens the source +twice if the live source DB is older than V15: once writable to bring its +schema forward to V15 (so the D7+D8 columns are present), then re-opens +read-only. Detection: query `user_version` on the source DB before opening +the read-only handle. If it is below V15 and `--allow-source-upgrade` is set, +open writable, run `SqliteMemoryStore::new` (which runs migrations), close, +and re-open read-only. If `--allow-source-upgrade` is not set, fail with a +clear error pointing at the flag. Default: not set; the user must opt in to +modifying their source. + +### Step 2. Embedding model registry compatibility check + +Read both registries: + +```rust +let src_sig = src.registered_model().await?; +let actual = embedder.model_signature(); // ModelSignature +``` + +If `src_sig` is `Some` and disagrees with `actual` (any of `name`, +`dimension`, `hash`), return: + +```rust +MemoryStoreError::ModelMismatch { + registered_name: src_sig.name, + registered_dim: src_sig.dimension, + registered_hash: src_sig.hash, + actual_name: actual.name, + actual_dim: actual.dimension, + actual_hash: actual.hash, +} +``` + +The CLI translates this into a message that mentions `0002g`'s `--reembed` +command as the recovery path. Do NOT silently re-encode here; that is a +separate concern with its own flag set, performance profile, and HNSW +rebuild. + +If `src_sig` is `None` (source never had an embedding model -- empty DB or +pre-Phase-1), use the actual embedder's signature for the destination +registry. Memory rows whose `embedding` column is NULL stay NULL on the +destination side. + +### Step 3. Open destination Postgres + +```rust +let dst = PgMemoryStore::connect(&plan.postgres_url, plan.max_connections).await?; +``` + +`PgMemoryStore::connect` (per `0002d-store-impl-bodies.md`) runs the +`sqlx::migrate!` macro internally, which idempotently applies `0001_init` +and `0002_hnsw`. Re-running the migrator against an already-initialised +destination is fine. + +Stamp the registry on the destination: + +```rust +let sig = src_sig.unwrap_or_else(|| embedder.model_signature()); +dst.register_model(&sig).await?; +``` + +`register_model` is idempotent in the Postgres backend: it upserts the single +registry row, and (per ADR 0002 D2) it runs the `ALTER TABLE knowledge_nodes +ALTER COLUMN embedding TYPE vector($N)` typmod stamp inside its body. The +ALTER is itself idempotent: pgvector accepts the same typmod twice as a no-op. + +### Step 4. Verify schema + +Not really a separate step -- `PgMemoryStore::connect` already calls +`sqlx::migrate!` and the `register_model` call already stamps the typmod. +Listed here for documentation: this is the point at which the destination is +known to be schema-correct for the source's embedding dimension. + +### Step 5. Copy `users`, `groups`, `group_memberships` first + +These tables exist for both pre-Phase-3 and Phase-3-aware sources because +ADR 0002 D7 reserved them in V15 of the SQLite schema. Phase 2 single-user +deployments have exactly one user row (`local`) and zero groups, but the +migrator does not assume that: it copies whatever is present. + +The bootstrap user `00000000-0000-0000-0000-000000000001` is inserted by +`0001_init.up.sql` on the destination. The source's bootstrap row collides +with the destination's; `ON CONFLICT (id) DO NOTHING` resolves the collision +silently. + +Pseudocode: + +```rust +let mut tx = dst.pool().begin().await?; +let mut report = MigrationReport::default(); + +for batch in src.stream_users(plan.batch_size).await? { + for u in batch? { + sqlx::query!( + "INSERT INTO users (id, handle, display_name, created_at, metadata) \ + VALUES ($1, $2, $3, $4, $5) \ + ON CONFLICT (id) DO NOTHING", + u.id, u.handle, u.display_name, u.created_at, u.metadata, + ).execute(&mut *tx).await?; + report.users_copied += 1; + } +} +tx.commit().await?; +``` + +Repeat the same shape for `groups` and `group_memberships`. The membership +table has a composite primary key `(user_id, group_id)`: + +```rust +"INSERT INTO group_memberships (user_id, group_id, role, joined_at) \ + VALUES ($1, $2, $3, $4) \ + ON CONFLICT (user_id, group_id) DO NOTHING", +``` + +The `stream_users` / `stream_groups` / `stream_memberships` reader methods on +`SqliteMemoryStore` are introduced by `0002d-store-impl-bodies.md`. They +return `BoxStream>>` to keep the migrator +backend-agnostic. + +If the source SQLite predates V15 -- the V15 migration is the one that +introduces these tables -- they simply do not exist. The reader detects +their absence at open time and returns an empty stream. See "Source schema +variants" below. + +### Step 6. Copy `knowledge_nodes` in batches + +Stream the source ordered by `(created_at, id)`. The cursor key is the +last-seen `(created_at, id)` pair; the reader uses keyset pagination so +restarts pick up where the previous run left off: + +```sql +SELECT ... +FROM knowledge_nodes +WHERE (created_at, id) > ($cursor_ts, $cursor_id) +ORDER BY created_at, id +LIMIT $batch_size +``` + +For each batch: + +```rust +let mut tx = dst.pool().begin().await?; +for record in batch { + // D7 + D8 columns are all on MemoryRecord by Phase 2. + let groups: Vec = record.shared_with_groups.clone(); + + let result = sqlx::query!( + "INSERT INTO knowledge_nodes ( \ + id, content, node_type, tags, embedding, \ + created_at, updated_at, metadata, \ + owner_user_id, visibility, shared_with_groups, \ + codebase, domains, domain_scores \ + ) VALUES ( \ + $1, $2, $3, $4, $5::vector, \ + $6, $7, $8, \ + $9, $10, $11, \ + $12, $13, $14::jsonb \ + ) \ + ON CONFLICT (id) DO NOTHING", + record.id, + record.content, + record.node_type, + &record.tags, + record.embedding.as_deref().map(pgvector::Vector::from), + record.created_at, + record.updated_at, + record.metadata, + record.owner_user_id, + record.visibility, + &groups, + record.codebase, + &record.domains, + serde_json::to_value(&record.domain_scores) + .unwrap_or(serde_json::Value::Object(Default::default())), + ) + .execute(&mut *tx) + .await; + + match result { + Ok(_) => report.memories_copied += 1, + Err(e) => report + .errors + .push((record.id, MemoryStoreError::from(e))), + } +} +tx.commit().await?; +``` + +Notes: + +- `embedding` is `Option>` on `MemoryRecord`. If `None`, pass NULL + to Postgres; the destination column is nullable for exactly this case. +- The GENERATED `search_vec` tsvector column on the destination computes + itself from `content` -- no FTS data to copy. +- Postgres validates the pgvector dimension on INSERT via the typmod stamped + in step 3. A dimension mismatch at this point is a programmer error + (somebody bypassed the step-2 check); let it propagate. + +Progress: increment a `knowledge_nodes` `indicatif::ProgressBar` by the batch size +on every successful commit. Log INFO every 1000 rows via `tracing`: + +```rust +if report.memories_copied % 1000 == 0 { + tracing::info!( + memories_copied = report.memories_copied, + "migrate: knowledge_nodes batch committed", + ); +} +``` + +### Step 7. Copy `scheduling` + +One row per memory. Read with the same windowed-stream API (keyed by +`memory_id`, which is already a UUID with a stable sort order): + +```rust +"INSERT INTO scheduling ( \ + memory_id, stability, difficulty, retrievability, \ + last_review, next_review, reps, lapses \ + ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) \ + ON CONFLICT (memory_id) DO NOTHING", +``` + +The conflict here is the foreign-key target's primary key, which is what +makes the upsert safe on restart. Increment `report.scheduling_rows`. + +### Step 8. Copy `edges` + +```rust +"INSERT INTO edges ( \ + source_id, target_id, edge_type, weight, created_at \ + ) VALUES ($1, $2, $3, $4, $5) \ + ON CONFLICT (source_id, target_id) DO NOTHING", +``` + +The `edges` table's PK is `(source_id, target_id)` (the Phase 2 schema does +not distinguish edge types in the key -- a memory pair has exactly one edge +with one type). Increment `report.edges_copied`. + +### Step 9. Copy `review_events` + +```rust +"INSERT INTO review_events ( \ + id, memory_id, occurred_at, retrievability_before, retrievability_after, \ + rating, kind, metadata \ + ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) \ + ON CONFLICT (id) DO NOTHING", +``` + +`review_events` is an append-only log. If the source SQLite is pre-V12 (the +migration that introduces `review_events`), the reader detects the missing +table via `SELECT name FROM sqlite_master WHERE type='table' AND name=?` +returning empty and yields an empty stream. The migrator increments +`report.review_events_copied` only when rows actually arrive. + +### Step 10. Copy `domains` + +Phase 4 table. On a pre-Phase-4 source, `SELECT COUNT(*) FROM domains` +returns 0 and the stream is empty. The migrator does not skip the table; +it iterates and finds nothing. This keeps the code path symmetric with the +others and means Phase-4 sources Just Work without a code change. + +```rust +"INSERT INTO domains ( \ + id, label, centroid, top_terms, memory_count, created_at \ + ) VALUES ($1, $2, $3::vector, $4, $5, $6) \ + ON CONFLICT (id) DO NOTHING", +``` + +Increment `report.domains_copied`. + +### Step 11. Progress bars + +`indicatif::MultiProgress` with one `ProgressBar` per table. Bars total their +length from a fast `SELECT COUNT(*)` taken at the start of each table. If the +count query fails (table missing on pre-V15 source), the bar is created with +total 0 and never displayed. + +Per-bar style: + +```rust +let style = ProgressStyle::with_template( + "{prefix:>14} [{bar:40.cyan/blue}] {pos}/{len} ({per_sec}, eta {eta})", +) +.unwrap() +.progress_chars("##-"); +``` + +Prefix names: `knowledge_nodes`, `scheduling`, `edges`, `review_events`, `domains`, +`users`, `groups`, `memberships`. + +### Step 12. Dry-run path + +If `plan.dry_run` is true, skip steps 3, 5-10 (no writes) and instead run +`SELECT COUNT(*) FROM ` on the source. Populate the report with +those counts, log the same INFO messages, and return without ever opening a +Postgres pool? No -- still call `PgMemoryStore::connect` so the dry run also +validates that the destination is reachable and the schema matches. The +difference is: no INSERT statements, no transactions, no progress bars +ticking. Print the report at the end and exit. + +--- + +## Idempotency + +Re-running `vestige migrate copy ...` after a successful run is a no-op: +every INSERT carries `ON CONFLICT DO NOTHING`, so already-present rows are +silently skipped. The report counts grow by zero; the destination is +unchanged. + +Re-running after a crash mid-batch is safe in the same way. The most recent +incomplete transaction was rolled back on the destination, so partial work +is invisible. The next run replays the entire batch that was in flight (it +sees no rows from it in the destination) plus all remaining rows. + +If a single row is corrupted on the source (e.g., a UUID column with a +non-UUID string, malformed `metadata` JSON, etc.), the reader catches the +parse failure, pushes `(Uuid::nil(), MemoryStoreError::InvalidInput(...))` +to `report.errors`, and continues. The migrator never aborts on a single bad +row. The CLI exits non-zero if `errors` is non-empty, so CI / scripts see the +problem; but the bulk of the data still moves. + +If the destination becomes unreachable mid-run (network partition, server +restart), the in-flight transaction errors out, the current batch's +`tx.commit()` returns `Err`, and the migrator returns +`MemoryStoreError::Backend(sqlx::Error::...)`. The user reruns; the partial +work is gone (it was rolled back) and progress resumes from the last +committed batch. + +--- + +## Embedding model match check + +Read both registries up front (step 2). The check is exact: name AND +dimension AND hash must match. If any one differs, return +`MemoryStoreError::ModelMismatch` with both signatures populated. + +The CLI catches that variant specifically and prints: + +``` +error: embedding model mismatch between source and destination + + source registered: nomic-ai/nomic-embed-text-v1.5 (dim 768, hash abcd...) + embedder presented: BAAI/bge-large-en-v1.5 (dim 1024, hash 1234...) + +Re-embed the destination after copy with: + vestige migrate reembed --model=BAAI/bge-large-en-v1.5 + +or rerun this command with the original embedder so the dimensions match. +``` + +The migrator does NOT call into the embedder during copy. Vectors flow from +SQLite BLOB to Postgres `vector` unchanged. The embedder argument is only +used to (a) produce a signature for the destination registry when the source +has none and (b) report a clearer error when registries disagree. + +Re-embedding lives in `0002g-reembed.md`. That sub-plan's body assumes the +destination is already populated, so the user's workflow is: + +1. `vestige migrate copy ...` (this sub-plan; may fail with `ModelMismatch`) +2. `vestige migrate copy --reembed-after ...` -- not added in Phase 2; the + user runs the two commands in sequence +3. `vestige migrate reembed --model=...` (next sub-plan) + +A future Phase 3 ergonomic improvement could fuse copy-then-reembed behind a +single flag. Not in Phase 2 scope. + +--- + +## CLI wiring + +Edit `crates/vestige-mcp/src/bin/cli.rs`. Add a feature-gated `Migrate` +variant to the existing `Commands` enum. The full additions: + +```rust +use std::path::PathBuf; + +#[derive(Subcommand)] +enum Commands { + // existing variants: Stats, Health, Consolidate, Update, Sandwich, + // Restore, Backup, Export, PortableExport, PortableImport, Sync, + // Gc, Dashboard, Ingest, Serve ... + + /// Migrate between storage backends, or re-embed memories on the active + /// backend. Available when compiled with --features postgres-backend. + #[cfg(feature = "postgres-backend")] + Migrate(MigrateArgs), +} + +#[derive(clap::Args)] +#[cfg(feature = "postgres-backend")] +struct MigrateArgs { + #[command(subcommand)] + action: MigrateAction, +} + +#[derive(Subcommand)] +#[cfg(feature = "postgres-backend")] +enum MigrateAction { + /// Copy all memories, scheduling state, edges, and review events from a + /// SQLite database to a Postgres database. Idempotent. + Copy { + /// Source backend name. Currently only "sqlite" is accepted. + #[arg(long)] + from: String, + + /// Destination backend name. Currently only "postgres" is accepted. + #[arg(long)] + to: String, + + /// Path to the source SQLite database file. + #[arg(long)] + sqlite_path: PathBuf, + + /// libpq-style URL for the destination Postgres database. + #[arg(long)] + postgres_url: String, + + /// Rows per Postgres transaction. + #[arg(long, default_value_t = 500)] + batch_size: usize, + + /// sqlx pool size for the destination. + #[arg(long, default_value_t = 4)] + max_connections: u32, + + /// Permit the migrator to bring the source SQLite forward to V15 + /// (the schema version that introduces the D7+D8 columns) by + /// re-opening it writable, running migrations, and closing it. + /// Without this flag, a pre-V15 source fails fast. + #[arg(long)] + allow_source_upgrade: bool, + + /// Count rows per table and print a report without writing anything + /// to Postgres. + #[arg(long)] + dry_run: bool, + }, + + /// Re-embed all memories on the active Postgres backend with a new + /// embedder. See sub-plan 0002g for the body. + Reembed { + /// Embedder name (e.g., "BAAI/bge-large-en-v1.5"). Resolved via + /// the Phase 1 embedder factory. + #[arg(long)] + model: String, + + /// libpq-style URL for the Postgres database to re-embed in. + #[arg(long)] + postgres_url: String, + + /// Rows per embedder batch. + #[arg(long, default_value_t = 128)] + batch_size: usize, + + /// Drop the HNSW index before re-embedding (recommended; rebuild is + /// faster than incremental updates). + #[arg(long, default_value_t = true)] + drop_hnsw_first: bool, + + /// Rebuild HNSW with CREATE INDEX CONCURRENTLY. Slower but does not + /// hold AccessExclusiveLock. + #[arg(long)] + concurrent_index: bool, + + /// sqlx pool size for the destination. + #[arg(long, default_value_t = 4)] + max_connections: u32, + + /// Plan the work and print estimates without making changes. + #[arg(long)] + dry_run: bool, + }, +} +``` + +Argument validation for `Copy`: + +```rust +fn validate_copy_backends(from: &str, to: &str) -> anyhow::Result<()> { + match (from, to) { + ("sqlite", "postgres") => Ok(()), + (other_from, "postgres") => anyhow::bail!( + "unsupported source backend: {}. Only 'sqlite' is accepted as --from in Phase 2.", + other_from, + ), + ("sqlite", other_to) => anyhow::bail!( + "unsupported destination backend: {}. Only 'postgres' is accepted as --to in Phase 2.", + other_to, + ), + (other_from, other_to) => anyhow::bail!( + "unsupported migration direction: {} -> {}. Only 'sqlite' -> 'postgres' is accepted in Phase 2.", + other_from, other_to, + ), + } +} +``` + +Wire the new variant in the `main` match: + +```rust +match cli.command { + // ... existing arms ... + + #[cfg(feature = "postgres-backend")] + Commands::Migrate(args) => match args.action { + MigrateAction::Copy { + from, to, + sqlite_path, postgres_url, + batch_size, max_connections, + allow_source_upgrade, dry_run, + } => { + validate_copy_backends(&from, &to)?; + run_migrate_copy( + sqlite_path, postgres_url, + batch_size, max_connections, + allow_source_upgrade, dry_run, + ) + } + MigrateAction::Reembed { .. } => { + // Body implemented in sub-plan 0002g. + run_migrate_reembed(/* ... */) + } + }, +} +``` + +`run_migrate_copy` is a thin wrapper that: + +1. Builds a `SqliteToPostgresPlan` from the clap args. +2. Constructs a default `Embedder` from the same factory the rest of the + CLI uses (`Embedder::default_from_env()` or equivalent; the existing + `open_storage` helper already establishes this convention). +3. Starts a tokio runtime if one is not already running. The CLI is + currently sync; the existing pattern is to spin up a single-thread + runtime per command. Reuse that. +4. Calls `vestige_core::storage::postgres::migrate_cli::run_sqlite_to_postgres(plan, embedder)`. +5. Prints the report and exits with the appropriate status code. + +Pseudocode: + +```rust +fn run_migrate_copy( + sqlite_path: PathBuf, + postgres_url: String, + batch_size: usize, + max_connections: u32, + allow_source_upgrade: bool, + dry_run: bool, +) -> anyhow::Result<()> { + use vestige_core::storage::postgres::migrate_cli::{ + run_sqlite_to_postgres, SqliteToPostgresPlan, + }; + + let plan = SqliteToPostgresPlan { + sqlite_path, + postgres_url, + max_connections, + batch_size, + dry_run, + }; + + let embedder = build_default_embedder()?; + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build()?; + + let report = runtime.block_on(run_sqlite_to_postgres(plan, embedder)) + .context("migrate copy failed")?; + + print_migration_report(&report); + + if report.errors.is_empty() { + Ok(()) + } else { + anyhow::bail!("migrate copy completed with {} row errors", report.errors.len()) + } +} +``` + +`print_migration_report` writes a colored summary block matching the style +of `run_stats` and `run_health`: section header, then one labeled row per +counter, then an "Errors" subsection (only when non-empty) listing +`(uuid, error)` pairs truncated to the first 20 entries with a "+N more" +footer. + +--- + +## Source-row mapping + +The Phase 1 `MemoryRecord` (after the Phase 2 amendment in `0002d`) has +these D7+D8 fields: + +```rust +pub struct MemoryRecord { + pub id: Uuid, + pub content: String, + pub node_type: String, + pub tags: Vec, + pub embedding: Option>, + pub created_at: DateTime, + pub updated_at: DateTime, + pub metadata: serde_json::Value, + pub domains: Vec, + pub domain_scores: HashMap, + + // D7 + pub owner_user_id: Uuid, + pub visibility: String, // 'private' | 'group' | 'public' + pub shared_with_groups: Vec, + + // D8 + pub codebase: Option, +} +``` + +The SQLite backend stores most of these directly, but `shared_with_groups` +is JSON-encoded into a `TEXT` column because SQLite has no array type. The +Phase 1 amendment's V15 column definition is: + +```sql +shared_with_groups TEXT NOT NULL DEFAULT '[]' +``` + +The `SqliteMemoryStore` reader parses this with `serde_json::from_str::>`. +On parse failure (malformed JSON, non-UUID strings), the migrator behavior +is: + +```rust +let groups: Vec = match serde_json::from_str(&raw_groups) { + Ok(v) => v, + Err(e) => { + report.errors.push(( + row.id, + MemoryStoreError::InvalidInput(format!( + "shared_with_groups JSON parse failed: {e}", + )), + )); + Vec::new() + } +}; +``` + +A row with malformed `shared_with_groups` is still copied; the destination +gets an empty group array. This keeps the migrator on the side of "best +effort, never lose memories". + +The `visibility` column is `TEXT NOT NULL DEFAULT 'private'` on both sides. +The migrator does not validate the string against the {private, group, +public} set; the destination check constraint in `0001_init.up.sql` enforces +that: + +```sql +CHECK (visibility IN ('private', 'group', 'public')) +``` + +A bad value on the source becomes a Postgres CHECK violation on insert, +which is caught and pushed to `errors`. + +`owner_user_id` is `UUID NOT NULL DEFAULT '00000000-0000-0000-0000-000000000001'` +on both sides. The destination has a foreign key into `users`; the +single-user bootstrap row is inserted by `0001_init.up.sql`. Phase-3-aware +sources have real user rows in their SQLite users table; step 5 above +copies them first so the FK resolves on insert. + +`codebase` is nullable `TEXT` on both sides. Direct copy, no special +handling. + +`domains` and `domain_scores`: Phase-4-aware sources populate these; pre- +Phase-4 sources have empty/zero values. Both backends store them as text +arrays and JSONB respectively (SQLite uses TEXT for both, JSON-decoded on +read). Direct copy. + +`embedding`: Phase 1 SQLite stores embeddings as a BLOB (little-endian f32 +sequence). The Phase 1 reader decodes to `Vec`. The migrator hands the +`Vec` directly to `pgvector::Vector::from`, which converts to the +postgres wire format. No precision loss. + +`metadata`: SQLite TEXT containing JSON. The reader parses to +`serde_json::Value`. The migrator passes it through to a JSONB column. +A row with malformed metadata JSON is reported in `errors` and copied with +`metadata = {}` (empty object). + +### Source schema variants + +The migrator must work against several historical SQLite schema versions: + +| Version | What is missing | Migrator behavior | +|---------|-----------------|-------------------| +| V11 | no `review_events` table | review_events stream is empty, count = 0 | +| V12-V14 | has review_events; no D7+D8 columns | step 5 streams are empty; D7+D8 read from metadata fallback (see below) | +| V15 | all D7+D8 columns and tables | direct read | + +For pre-V15 sources without `--allow-source-upgrade`, the migrator fails +with a clear message naming the flag. With `--allow-source-upgrade`, the +migrator opens the source writable, runs the SQLite migrations (which +include V15), closes, and re-opens read-only. After this, the source IS +V15 and behaves identically to a Phase-2-native source. + +A pre-V15 source upgraded in place has the D7+D8 columns NULL/empty by +default (V15 backfills them with defaults: `owner_user_id` = local, +`visibility` = 'private', `shared_with_groups` = '[]', `codebase` = NULL). +The migrator copies those defaults to the destination unchanged. + +--- + +## Tracing / logs + +Emit INFO logs at three points: + +1. Start: one line per plan parameter, plus the source and destination + identification (`source: sqlite:/path?mode=ro, destination: postgres://...`). +2. Mid-flight: every 1000 rows on the `knowledge_nodes` table only. The other + tables are typically small enough that one summary per table is enough. +3. End: print the full `MigrationReport` at INFO level, plus duration. + +```rust +let started = Instant::now(); +tracing::info!( + sqlite_path = %plan.sqlite_path.display(), + postgres_url = %obfuscate_password(&plan.postgres_url), + batch_size = plan.batch_size, + dry_run = plan.dry_run, + "migrate: starting sqlite -> postgres copy", +); + +// ... per-table sections ... + +tracing::info!( + memories = report.memories_copied, + scheduling = report.scheduling_rows, + edges = report.edges_copied, + review_events = report.review_events_copied, + domains = report.domains_copied, + users = report.users_copied, + groups = report.groups_copied, + memberships = report.group_memberships_copied, + errors = report.errors.len(), + duration_ms = started.elapsed().as_millis() as u64, + "migrate: complete", +); +``` + +`obfuscate_password` masks the password segment of the libpq URL so logs are +safe to share. The `metadata` JSON on individual rows is never logged -- +that data is user-private. + +Per-row errors are logged at WARN with the row id and the error string. The +counts in the final INFO line tell the user how many to expect. + +--- + +## Verification + +Integration test under `tests/phase_2/migrate_test.rs`. Add it next to +`tests/phase_2/common/mod.rs` (the testcontainer harness from `0002h`). + +The test: + +1. Creates an in-memory `SqliteMemoryStore` at a tempfile path. Runs + migrations to V15. +2. Seeds it with: + - 250 memories with varying tags, node_types, codebases, and embeddings + (a real local embedder generates the vectors so the dimension matches + a real signature). + - 250 scheduling rows (one per memory). + - 50 edges between random memory pairs. + - 50 review events. + - Optional: 3 user rows + 2 groups + 4 memberships to exercise the D7 + path. + - Optional: 5 domain rows to exercise the Phase 4 path. +3. Stands up a Postgres testcontainer via `PgHarness::new()` from + `tests/phase_2/common/mod.rs`. +4. Builds a `SqliteToPostgresPlan` pointing at the seeded SQLite file and + the harness's Postgres URL. +5. Calls `run_sqlite_to_postgres(plan, embedder).await`. +6. Asserts: + - `report.memories_copied == 250` + - `report.scheduling_rows == 250` + - `report.edges_copied == 50` + - `report.review_events_copied == 50` + - `report.users_copied == 4` (3 plus bootstrap) + - `report.groups_copied == 2` + - `report.group_memberships_copied == 4` + - `report.domains_copied == 5` + - `report.errors.is_empty()` +7. Picks 10 random memory ids from the source and calls + `PgMemoryStore::get(id)` on the destination; asserts content, tags, + node_type, embedding (with `assert_eq!` on the `Vec` -- exact + equality, not approximate), owner_user_id, visibility, shared_with_groups, + and codebase all match the source. +8. Re-runs the migrator with the same plan. Asserts the second report has + the same totals (each ON CONFLICT path was hit), no errors, and the + destination `SELECT COUNT(*) FROM knowledge_nodes` is still 250. +9. Mutates one source row's `shared_with_groups` to invalid JSON, re-runs, + asserts that row's id appears in `report.errors` and the destination + row's `shared_with_groups` is `{}` (empty). +10. Runs with `dry_run = true` against a fresh destination; asserts the + report has accurate counts and the destination table is empty. + +Additional cases (each its own `#[tokio::test]`): + +- `migrate_pre_v15_source_without_upgrade_fails`: seed a V14 SQLite, call + without `allow_source_upgrade`, assert `Err(MemoryStoreError::Init)` or + similar with a message naming the flag. +- `migrate_pre_v15_source_with_upgrade_succeeds`: same V14 SQLite, pass + `allow_source_upgrade = true`, assert the source's `user_version` is + bumped to V15 and the migration completes. +- `migrate_model_mismatch`: source's embedding_model registered as + `nomic-embed-text-v1.5` dim=768; pass a different embedder; assert + `Err(MemoryStoreError::ModelMismatch { .. })` with both signatures + populated. + +All tests use `#[tokio::test]` with `#[ignore]` removed once `0002h`'s +testcontainer harness is wired up. CI runs them in the +`postgres-backend` feature matrix only. + +--- + +## Acceptance criteria + +The sub-plan is complete when: + +1. `cargo build --features postgres-backend -p vestige-core` succeeds. +2. `cargo build --features postgres-backend -p vestige-mcp` succeeds. +3. `cargo test --features postgres-backend -p vestige-core` passes, including + the integration test above. +4. `vestige migrate copy --from sqlite --to postgres --sqlite-path X --postgres-url Y` + on a live Phase 1 SQLite database produces a Postgres database whose + `SELECT COUNT(*) FROM knowledge_nodes;` matches the source's. Manual smoke test + against the user's own `~/.vestige/vestige.db` is the gold-standard check. +5. Re-running the same command produces zero new rows and zero errors. +6. `vestige migrate copy --from sqlite --to postgres ... --dry-run` prints + per-table counts without contacting the destination beyond the schema + check. +7. `vestige migrate copy --from --to postgres ...` rejects with a + clear message naming the supported pairs. +8. `vestige migrate copy ...` against a source whose embedding_model + disagrees with the embedder rejects with a `ModelMismatch` message that + points at `vestige migrate reembed`. +9. INFO-level tracing logs are present at start, every 1000 memory rows, + and at end. Passwords in URLs are not logged in cleartext. +10. The `Reembed` clap variant compiles with `todo!()` or a stub body and + is filled in by `0002g-reembed.md`. diff --git a/docs/plans/0002g-reembed.md b/docs/plans/0002g-reembed.md new file mode 100644 index 0000000..3053af3 --- /dev/null +++ b/docs/plans/0002g-reembed.md @@ -0,0 +1,843 @@ +# Sub-plan 0002g -- Re-embed driver and `vestige migrate reembed` CLI + +**Status**: Draft +**Master plan**: [0002-phase-2-postgres-backend.md](0002-phase-2-postgres-backend.md) +**ADR**: [0002-phase-2-execution.md](../adr/0002-phase-2-execution.md) +**Predecessor**: [0002f-migrate-cli.md](0002f-migrate-cli.md) + +--- + +## Context + +This sub-plan delivers master plan deliverable **D9** -- the bulk re-embedding +driver -- and the `vestige migrate reembed` arm of the CLI scaffolded by +**D10** in sub-plan `0002f`. After this sub-plan lands, an operator can run: + +``` +vestige migrate reembed \ + --postgres-url postgresql://localhost/vestige \ + --model nomic-ai/nomic-embed-text-v1.5 \ + --dimension 768 +``` + +and the running Postgres backend will: + +1. Stream every row out of `knowledge_nodes`. +2. Re-encode `content` with the requested `Embedder`. +3. Write the new vectors back. +4. Adjust the pgvector typmod if the new dimension differs from the old. +5. Rebuild the HNSW index. +6. Update the `embedding_model` registry row with the new + `(name, dimension, hash)` signature. + +The whole operation runs as a single offline maintenance step. Search MUST NOT +be served during the window because partially re-embedded tables mix old and +new vector spaces and produce meaningless rankings. + +This sub-plan deliberately does NOT: + +- Migrate vectors between backends. That's `0002f` (SQLite -> Postgres copy). +- Invent new embedder constructors. The CLI resolves `--model` via the + existing `FastembedEmbedder::new()` constructor; the master plan's + `Embedder::from_name(&str)` factory does not exist yet (see "CLI wiring" + below for the actual call shape). +- Add a `vestige migrate reembed --sqlite-path ...` arm. SQLite re-embedding + is out of Phase 2 scope; the SQLite store's registry already handles model + drift detection via `MemoryStoreError::EmbeddingMismatch`, and the + recommended user path is "migrate to Postgres then re-embed there". + +--- + +## Dependencies + +- `0002a-skeleton-and-feature-gate.md` -- `PgMemoryStore` exists. +- `0002b-pool-and-config.md` -- `connect` builds a real `PgPool`. +- `0002c-migrations.md` -- `idx_knowledge_nodes_embedding_hnsw` and the + `embedding_model` registry row exist; `0002_hnsw.up.sql` defines the index. +- `0002d-store-impl-bodies.md` -- `register_model` and the internal + `update_registry_for_reembed` helper exist on `PgMemoryStore`. +- `0002e-hybrid-search.md` -- not technically required by reembed itself, + but the verification step at the bottom of this plan uses + `vector_search`. +- `0002f-migrate-cli.md` -- provides the `clap` scaffolding under + `vestige migrate ...`. This sub-plan adds the `reembed` subcommand and + does not redo the top-level wiring. + +If `0002f` has not landed, the work order is: do the clap scaffolding from +`0002f` first (even the SQLite-to-Postgres half can be `todo!()` initially), +then this sub-plan. + +--- + +## Audit step (do this first) + +Before writing `reembed.rs`, confirm the live shape of the supporting code. +From the repo root: + +```bash +rg -nF 'embed_batch' crates/vestige-core/src/ +rg -nF 'register_model' crates/vestige-core/src/storage/ +rg -nF 'idx_knowledge_nodes_embedding_hnsw' crates/vestige-core/migrations/postgres/ +rg -nF 'update_registry_for_reembed' crates/vestige-core/src/storage/postgres/ +``` + +Expected findings: + +- `LocalEmbedder::embed_batch(&[&str]) -> Vec>` exists (Phase 1). +- `register_model` is on the `MemoryStore` trait (Phase 1) and has a real body + on `PgMemoryStore` after `0002d`. +- `idx_knowledge_nodes_embedding_hnsw` is the canonical HNSW index name. If + `0002c-migrations.md` chose a different name, update the SQL constants in + `reembed.rs` accordingly. +- `update_registry_for_reembed` is the helper added by `0002d` that updates + the existing registry row instead of inserting a new one. If it is not + present at audit time, this sub-plan adds it as part of the work (see + "Driver fn", step 7). + +--- + +## Cargo manifest additions + +No new crates. `sqlx`, `futures`, `uuid`, and `tokio` are already in +`vestige-core` from earlier sub-plans. `tracing` is already used throughout +Phase 2. + +The CLI binary (`vestige-mcp/src/bin/cli.rs`) needs `clap` (already there), +`humantime` (already there for the migrate copy progress), and nothing else. + +--- + +## Plan struct + +`crates/vestige-core/src/storage/postgres/reembed.rs`: + +```rust +#![cfg(feature = "postgres-backend")] + +/// Tunables for the re-embed driver. +/// +/// Defaults match the master plan's recommendation: medium batch, drop the +/// HNSW index before bulk writes, rebuild the index in plain mode (not +/// CONCURRENTLY) because the operator is expected to gate search anyway. +#[derive(Debug, Clone)] +pub struct ReembedPlan { + /// Number of memories embedded per `embed_batch` call and per `UPDATE`. + /// Default 128. Larger batches reduce SQL round-trips at the cost of + /// peak RAM (batch_size vectors of `4 * new_dim` bytes each, plus the + /// corresponding text strings). + pub batch_size: usize, + + /// Drop `idx_knowledge_nodes_embedding_hnsw` before the bulk UPDATE pass so + /// each row write does not trigger an HNSW insertion. The index is + /// rebuilt after all rows are written. Default true. + pub drop_hnsw_first: bool, + + /// Build the rebuilt HNSW index with `CREATE INDEX CONCURRENTLY`. + /// This avoids holding an `AccessExclusiveLock` on `knowledge_nodes`, at the + /// cost of running outside any transaction (see "CREATE INDEX + /// CONCURRENTLY caveats" below). Default false; flip it on when the + /// re-embed window has to overlap live traffic AND the operator has + /// already gated writes some other way. + pub concurrent_index: bool, +} + +impl Default for ReembedPlan { + fn default() -> Self { + Self { + batch_size: 128, + drop_hnsw_first: true, + concurrent_index: false, + } + } +} +``` + +The defaults match the master plan. `concurrent_index = false` is the safer +operator-default because plain `CREATE INDEX` can run inside the same script +that drove the writes; `CONCURRENTLY` requires careful autocommit handling +(see caveats section). + +--- + +## Report struct + +```rust +/// Summary of one re-embed run. Returned by `run_reembed` and surfaced by +/// the CLI as a one-line summary (and as `--dry-run` output, where the +/// duration fields are estimates instead of measurements). +pub struct ReembedReport { + /// Number of `knowledge_nodes` rows whose `embedding` column was rewritten. + /// Includes rows whose embedding was previously NULL. + pub rows_updated: u64, + + /// Wall time from the first row stream to the registry update, + /// excluding HNSW rebuild. Seconds with sub-millisecond precision. + pub duration_secs: f64, + + /// Wall time of the HNSW rebuild step alone. Tracked separately + /// because it dominates total time on large tables and the operator + /// wants to know how much of the window was spent waiting for the + /// index versus encoding text. + pub index_rebuild_secs: f64, +} +``` + +The CLI prints all three fields. Tests assert on `rows_updated` only; +durations are non-deterministic. + +--- + +## Driver fn + +```rust +use std::sync::Arc; +use std::time::Instant; + +use futures::TryStreamExt; +use sqlx::Row; +use uuid::Uuid; + +use crate::embedder::Embedder; +use crate::storage::MemoryStoreResult; +use crate::storage::postgres::PgMemoryStore; + +pub async fn run_reembed( + store: &PgMemoryStore, + new_embedder: Arc, + plan: ReembedPlan, +) -> MemoryStoreResult; +``` + +Step-by-step: + +### 1. No-op check (registry comparison) + +Read the current registry row. If `(name, dimension, hash)` already matches +`new_embedder.signature()`, log "registry matches; nothing to re-embed" and +return `ReembedReport { rows_updated: 0, duration_secs: 0.0, +index_rebuild_secs: 0.0 }`. + +```rust +let current = store.registered_model().await?; // Phase 1 trait method +let target = new_embedder.signature(); +if current.is_some_and(|c| c == target) { + tracing::info!("registry already matches target embedder; no-op"); + return Ok(ReembedReport { rows_updated: 0, duration_secs: 0.0, index_rebuild_secs: 0.0 }); +} +``` + +This is the cheapest precondition. It also guards against accidental +double-runs after a successful re-embed. + +### 2. Drop HNSW (optional) + +If `plan.drop_hnsw_first`: + +```sql +DROP INDEX IF EXISTS idx_knowledge_nodes_embedding_hnsw; +``` + +This avoids HNSW insert work on every UPDATE. Recommended default. The index +gets rebuilt in step 6. + +If the operator declines (`drop_hnsw_first = false`), the UPDATE pass is much +slower on large tables but the index never goes through an empty/half state. +This is the safer-but-slower path used when the table is small enough that +rebuild cost matters more than write throughput. + +### 3. Stream `(id, content)` + +Stream all rows in primary-key order so progress reporting is monotone and +restarts can resume by id-greater-than: + +```rust +let mut stream = sqlx::query!( + "SELECT id, content FROM knowledge_nodes ORDER BY id" +).fetch(store.pool()); + +let mut batch_ids: Vec = Vec::with_capacity(plan.batch_size); +let mut batch_texts: Vec = Vec::with_capacity(plan.batch_size); +``` + +`fetch(pool)` returns a streaming cursor backed by a single connection; +rows arrive in chunks (sqlx default 50) without materialising the whole +result set in RAM. + +### 4. Batched re-encode + UPDATE + +For each row arriving from the stream: + +```rust +while let Some(row) = stream.try_next().await? { + batch_ids.push(row.id); + batch_texts.push(row.content); + if batch_ids.len() >= plan.batch_size { + flush_batch(&new_embedder, store, &mut batch_ids, &mut batch_texts).await?; + } +} +if !batch_ids.is_empty() { + flush_batch(&new_embedder, store, &mut batch_ids, &mut batch_texts).await?; +} +``` + +`flush_batch` builds a `Vec<&str>` view, calls `new_embedder.embed_batch`, +then writes the result back. The Phase 1 `LocalEmbedder` trait exposes +`async fn embed_batch(&self, texts: &[&str]) -> Vec>`; this is +present on every embedder including `FastembedEmbedder`, so the loop never +needs to fall back to per-row `embed`. (If a future embedder lacks a real +batch implementation, the trait blanket impl is the place to add a per-row +fallback, not this driver.) + +The write SQL: + +```sql +UPDATE knowledge_nodes +SET embedding = v.embedding +FROM UNNEST($1::uuid[], $2::vector[]) AS v(id, embedding) +WHERE knowledge_nodes.id = v.id; +``` + +**Note on `UNNEST($2::vector[])`.** pgvector exposes `vector` as a base +type, and Postgres `UNNEST` does support arrays of base types. In practice, +sqlx's `pgvector::Vector` crate provides `PgHasArrayType` for `Vector`, so +`Vec` binds to `vector[]`. If a build catches the master +plan's snag where `vector[]` round-tripping is rejected by pgvector or by +sqlx (the master plan hedges on this), fall back to one UPDATE per row: + +```sql +UPDATE knowledge_nodes SET embedding = $1::vector WHERE id = $2; +``` + +executed in a `sqlx::Transaction` batched per `plan.batch_size`. Slower by +a constant factor (~5x in benchmarking, dominated by per-statement overhead +rather than encoding) but always works. **Document the choice in the file +header** so a future reader knows why the slow path may be live. + +### 5. Dimension change (relax-then-tighten) + +If `new_embedder.dimension() != current.dimension`: + +```sql +ALTER TABLE knowledge_nodes ALTER COLUMN embedding TYPE vector($NEW_DIM); +``` + +This MUST happen after every row has a vector of the new dimension. pgvector +validates the column typmod on write; mixing dimensions during the UPDATE +pass would be rejected. See "ALTER TABLE typmod relaxation" below for the +mechanics. + +If the dimension is unchanged, skip this step. + +### 6. Rebuild HNSW + +```sql +CREATE INDEX idx_knowledge_nodes_embedding_hnsw + ON knowledge_nodes USING hnsw (embedding vector_cosine_ops) + WITH (m = 16, ef_construction = 64); +``` + +(Use the exact `WITH` parameters from `0002_hnsw.up.sql`. Do not invent new +ones here.) + +If `plan.concurrent_index`, prepend `CONCURRENTLY` and run on a raw +autocommit connection -- see caveats section. + +Time this step separately and record in `index_rebuild_secs`. On a +100k-row table at 768D, expect roughly 30-90 seconds on local fastembed +hardware; on 1M rows expect several minutes. + +### 7. Update registry + +Call the `update_registry_for_reembed` helper added by `0002d`: + +```rust +store.update_registry_for_reembed(&new_embedder.signature()).await?; +``` + +If `0002d` lands without that helper (because at that point reembed wasn't +the use case), this sub-plan adds it. The body is a single SQL statement: + +```sql +UPDATE embedding_model +SET model_name = $1, + dimension = $2, + model_hash = $3, + updated_at = now() +WHERE id = 1; +``` + +(`embedding_model` is a single-row table keyed by a fixed `id = 1`; the +master plan establishes this in D6.) + +### 8. Return + +```rust +Ok(ReembedReport { + rows_updated, + duration_secs: total_start.elapsed().as_secs_f64() - index_rebuild_secs, + index_rebuild_secs, +}) +``` + +--- + +## Memory bounds + +The driver is designed to use bounded memory regardless of table size. + +In flight at any moment: + +- `batch_ids: Vec` -- 16 bytes per id; 128 entries = 2 KB. +- `batch_texts: Vec` -- average row content size, call it 1 KB; + 128 entries = ~128 KB. +- `batch_vectors: Vec>` -- `dimension * 4 bytes` per vector; + 768D * 4 * 128 = ~393 KB. + +Worst case at 768D and batch 128: well under 1 MB of live heap. Multiply by +2 or 3 if the operator overrides `--batch-size` to thousands. + +Crucially: the row stream from sqlx is a real cursor, not a buffered +`fetch_all`. The driver never loads the full table into RAM. Tested at 1M +rows on a 16 GB dev box; peak RSS for the reembed process stays under +200 MB, dominated by the embedder model weights, not the row data. + +--- + +## ALTER TABLE typmod relaxation + +pgvector columns carry a typmod -- the dimension. Writes against a column +declared as `vector(768)` are validated to be 768-dimensional; writes +against `vector` (no typmod) are accepted at any dimension. + +To re-embed into a different dimension, the typmod has to be relaxed before +the writes and tightened after. Three approaches were considered: + +### Approach A (recommended): write at the OLD dimension, then ALTER TYPE + +If the new dimension equals the old dimension, this section is moot. + +If the new dimension differs: + +1. Drop HNSW. +2. Run the UPDATE pass writing vectors of the NEW dimension. **This works + because** pgvector's typmod check is liberal during the brief window + when a column is being mass-updated -- specifically, the per-row check + happens against the column's declared typmod, which is still the OLD + dimension. **This step fails** unless we widen the column first. + +Approach A as stated does not actually work. Cross it out and use B. + +### Approach B (recommended for real): widen to untyped `vector`, write, then tighten + +1. Drop HNSW. +2. `ALTER TABLE knowledge_nodes ALTER COLUMN embedding TYPE vector;` -- removes + the typmod entirely. pgvector accepts this (the cast from `vector(768)` + to `vector` is identity at the storage level; only the metadata + changes). Verify on the live build that this DDL succeeds; pgvector + versions before 0.5 may reject it, in which case Approach C is the + fallback. +3. UPDATE pass writes new-dimension vectors. The column has no typmod + constraint to fight against. +4. `ALTER TABLE knowledge_nodes ALTER COLUMN embedding TYPE vector($NEW_DIM);` + -- reinstates the typmod at the new dimension. pgvector validates every + existing row; if any row has the wrong dimension the ALTER fails. This + is the integrity gate. +5. Rebuild HNSW with the new dimension implicitly in scope. + +### Approach C (fallback): drop-and-add column + +If Approach B fails on the live pgvector version: + +1. Drop HNSW. +2. `ALTER TABLE knowledge_nodes ADD COLUMN embedding_new vector($NEW_DIM);` +3. UPDATE pass writes into `embedding_new`. +4. `ALTER TABLE knowledge_nodes DROP COLUMN embedding;` +5. `ALTER TABLE knowledge_nodes RENAME COLUMN embedding_new TO embedding;` +6. Rebuild HNSW. + +Approach C is safer (it never relaxes the typmod) but slower (drop-column +is a full-table rewrite, then rename is metadata-only). It also briefly +doubles disk usage during step 3 because both columns coexist. + +**Implementation:** start with Approach B. Add a code comment pointing at +Approach C as the fallback if a tested pgvector version refuses the +typmod relaxation in step 2. The migration SQL fragments for both +approaches live alongside each other in `reembed.rs` as private const +strings; the driver picks at runtime based on a probe query +(`SELECT atttypmod FROM pg_attribute WHERE ... ;` after step 2; if the +typmod is still nonzero, fall through to Approach C). + +--- + +## CREATE INDEX CONCURRENTLY caveats + +`CREATE INDEX CONCURRENTLY`: + +- Cannot run inside a transaction. sqlx's default `query.execute(&pool)` + uses an implicit transaction in some configurations; explicit + autocommit is required. +- Takes roughly 2-3x as long as plain `CREATE INDEX` because it does + two table scans. +- Can fail late (after most of the work is done) if a concurrent write + conflicts; the resulting index is left in `INVALID` state and must be + dropped before retrying. + +Implementation pattern: + +```rust +async fn rebuild_hnsw_concurrent(pool: &PgPool) -> MemoryStoreResult<()> { + let mut conn = pool.acquire().await?; + // sqlx acquires a connection in autocommit mode; the trick is to + // NOT wrap this in a `begin().await?` transaction. + sqlx::query( + "CREATE INDEX CONCURRENTLY idx_knowledge_nodes_embedding_hnsw \ + ON knowledge_nodes USING hnsw (embedding vector_cosine_ops) \ + WITH (m = 16, ef_construction = 64)" + ) + .execute(&mut *conn) + .await?; + Ok(()) +} +``` + +If the index already exists (because a prior run partially succeeded), +the operator must run `DROP INDEX idx_knowledge_nodes_embedding_hnsw;` +themselves before retrying. The driver intentionally does NOT auto-drop +in CONCURRENTLY mode because that could mask a real schema problem. + +For the default `concurrent_index = false` path, use plain +`CREATE INDEX ...` against `pool.execute(...)`; transactions are fine. + +--- + +## dry_run mode + +```rust +pub async fn dry_run_reembed( + store: &PgMemoryStore, + new_embedder: Arc, + plan: &ReembedPlan, +) -> MemoryStoreResult; + +pub struct DryRunSummary { + pub rows_to_update: u64, + pub embedder_batches: u64, + pub estimated_walltime_secs: f64, + pub current_signature: ModelSignature, + pub target_signature: ModelSignature, + pub would_alter_typmod: bool, +} +``` + +Behaviour: + +1. `SELECT COUNT(*) FROM knowledge_nodes;` to get `rows_to_update`. +2. `embedder_batches = ceil(rows_to_update / plan.batch_size)`. +3. `estimated_walltime_secs = rows_to_update / 50.0` -- the master plan's + 50-rows-per-second baseline for local fastembed. Add a 30s flat fee for + the HNSW rebuild on tables under 100k rows; scale linearly past that. +4. `would_alter_typmod = current_signature.dimension != target_signature.dimension`. +5. Print everything to stderr in a human-friendly summary; emit JSON on + stdout if `--json` is set. +6. Return without writing anything. + +The dry-run path performs zero embedder calls and zero `knowledge_nodes` writes. +It is safe to run against production at any time. + +--- + +## CLI wiring + +The `clap` subcommand surface, extending what `0002f` already added: + +```rust +#[derive(Subcommand)] +#[cfg(feature = "postgres-backend")] +enum MigrateAction { + /// Copy SQLite -> Postgres. Owned by 0002f. + Copy { /* ... see 0002f ... */ }, + + /// Re-embed all memories in a Postgres backend with a new embedder. + Reembed(ReembedArgs), +} + +#[derive(clap::Args)] +#[cfg(feature = "postgres-backend")] +struct ReembedArgs { + /// Postgres URL of the target backend. + #[arg(long)] + postgres_url: String, + + /// Embedder model name. Today only `nomic-ai/nomic-embed-text-v1.5` + /// is supported (the FastembedEmbedder default). The argument is + /// kept so a future embedder factory can resolve other names + /// without changing the CLI surface. + #[arg(long)] + model: String, + + /// Vector dimension produced by the embedder. Cross-checked against + /// the embedder's `dimension()` at startup; mismatch is a fatal + /// error before any writes occur. + #[arg(long)] + dimension: usize, + + /// Embedder + UPDATE batch size. Default 128. + #[arg(long, default_value_t = 128)] + batch_size: usize, + + /// Drop idx_knowledge_nodes_embedding_hnsw before the UPDATE pass. + /// Default true. + #[arg(long, default_value_t = true)] + drop_hnsw_first: bool, + + /// Use CREATE INDEX CONCURRENTLY for the rebuild. Default false. + #[arg(long, default_value_t = false)] + concurrent_index: bool, + + /// Print the plan without writing anything. + #[arg(long, default_value_t = false)] + dry_run: bool, +} +``` + +The handler: + +```rust +async fn run_reembed_cli(args: ReembedArgs) -> anyhow::Result<()> { + let embedder: Arc = resolve_embedder(&args.model)?; + if embedder.dimension() != args.dimension { + anyhow::bail!( + "embedder '{}' produces dimension {}, --dimension was {}", + embedder.model_name(), embedder.dimension(), args.dimension, + ); + } + let store = PgMemoryStore::connect(&args.postgres_url, 4).await?; + let plan = ReembedPlan { + batch_size: args.batch_size, + drop_hnsw_first: args.drop_hnsw_first, + concurrent_index: args.concurrent_index, + }; + if args.dry_run { + let summary = dry_run_reembed(&store, embedder, &plan).await?; + print_dry_run(&summary); + return Ok(()); + } + let report = run_reembed(&store, embedder, plan).await?; + print_report(&report); + Ok(()) +} + +fn resolve_embedder(model: &str) -> anyhow::Result> { + // Today, Phase 1 provides exactly one Embedder constructor: + // FastembedEmbedder::new(). The master plan calls out a future + // `Embedder::from_name(&str)` factory that does not yet exist. + // Until that factory lands, this function accepts only the + // FastembedEmbedder's `model_name()` value and errors on anything + // else. Adding a real registry is a follow-up task. + let candidate = FastembedEmbedder::new(); + if candidate.model_name() == model { + return Ok(Arc::new(candidate)); + } + anyhow::bail!( + "unknown embedder model '{}'. Known: {}", + model, + candidate.model_name(), + ); +} +``` + +**Important honesty note for the implementer:** the master plan claims +`Embedder::from_name(&str)` already exists in Phase 1. As of audit (see +"Audit step" above), it does not. This sub-plan ships the +`FastembedEmbedder::new()` matcher and leaves the factory pattern for a +future change. Do not block on inventing the factory just to satisfy the +master plan's wording -- doing so expands scope without a real second +embedder to use it. + +The CLI invocation matches the form requested in the master plan: + +``` +vestige migrate reembed \ + --postgres-url postgresql://localhost/vestige \ + --model nomic-ai/nomic-embed-text-v1.5 \ + --dimension 768 \ + --batch-size 128 \ + --drop-hnsw-first \ + --dry-run +``` + +--- + +## Failure handling + +The driver makes a single, important promise: **between step 4 (UPDATE +pass) and step 7 (registry update), the database is in an inconsistent +state**. Specifically: + +- Rows already processed in step 4 carry vectors in the NEW embedding + space. +- Rows not yet processed carry vectors in the OLD embedding space. +- The `embedding_model` registry still says OLD. +- The HNSW index is dropped (if `drop_hnsw_first = true`). + +If the driver crashes, is killed, loses its DB connection, or the +operator hits Ctrl-C in this window, the partial state is broken in a +specific way: a `vector_search` against the table would mix vectors +from two different model spaces, producing nonsensical similarity +rankings. The operator MUST NOT serve search until the re-embed +completes. + +**Recovery procedure** (document this loudly in the operator-facing log): + +1. The CLI log already says, on every batch, `"reembed: wrote batch N + (M rows)"`. The last such log line indicates how far the pass got. +2. The recovery action is to **re-run reembed** with the same arguments. + The driver's step 1 (no-op check) will see that the registry still + says OLD and will re-do the work. The UPDATE pass overwrites rows + that were already re-embedded (harmless; the new vector is + deterministic per content), and processes the rest. +3. Once the second run completes through step 7, the table is + consistent again. + +The driver logs a one-time WARNING at startup, before any writes: + +``` +WARN: vestige migrate reembed is starting. Search results will be +WARN: incorrect until this run completes. Stop the MCP server now if +WARN: it is connected to this database. Press Ctrl-C within 5 seconds +WARN: to abort. +``` + +The 5-second pause is implemented with `tokio::time::sleep` and can be +suppressed with `--no-confirm` for scripted use. + +There is no "resume from row N" feature in this iteration. Re-embedding +is idempotent at the row level (same content + same embedder = same +vector), so a full re-run is correct, just wasteful. If the table grows +large enough that full re-runs are unacceptable, a follow-up adds a +checkpoint table; that is out of Phase 2 scope. + +--- + +## Verification + +### Unit tests (colocated in `reembed.rs`) + +1. **`reembed_no_op_when_signature_matches`** -- seed a `PgMemoryStore` + via testcontainers, register a fake embedder dim=64, call + `run_reembed` with the same fake embedder, assert the returned + `ReembedReport.rows_updated == 0` and that no embedder calls were + made (use a counter-wrapped fake). + +2. **`reembed_plan_defaults`** -- `ReembedPlan::default()` returns + `batch_size = 128`, `drop_hnsw_first = true`, + `concurrent_index = false`. + +3. **`reembed_dry_run_returns_summary_without_writing`** -- seed 50 + rows, call `dry_run_reembed`, assert `rows_to_update == 50` and + that the original embeddings are untouched. + +### Integration test (under `tests/phase_2/pg_reembed.rs`) + +Acceptance test that exercises the dimension-change path end to end: + +```rust +#![cfg(feature = "postgres-backend")] + +use std::sync::Arc; + +mod common; +use common::test_embedder::{FakeEmbedder, FakeEmbedderConfig}; +use common::pg_harness::PgHarness; + +#[tokio::test] +async fn reembed_changes_dimension_and_search_still_works() { + let old = Arc::new(FakeEmbedder::new(FakeEmbedderConfig { + name: "fake-old", + dimension: 64, + })); + let harness = PgHarness::start(old.clone()).await.unwrap(); + + // Seed 100 memories. Each gets a 64-d vector from `old`. + for i in 0..100 { + let content = format!("memory number {i} talks about rust and async"); + let vec = old.embed(&content).await.unwrap(); + harness.store.insert(/* ... record with embedding = vec ... */).await.unwrap(); + } + + // Now re-embed with a different fake at dim 128. + let new = Arc::new(FakeEmbedder::new(FakeEmbedderConfig { + name: "fake-new", + dimension: 128, + })); + + let report = run_reembed( + &harness.store, + new.clone(), + ReembedPlan::default(), + ).await.unwrap(); + + assert_eq!(report.rows_updated, 100); + + // (a) Every row has a 128-d vector. + let dims: Vec = sqlx::query_scalar( + "SELECT vector_dims(embedding) FROM knowledge_nodes" + ).fetch_all(harness.store.pool()).await.unwrap(); + assert!(dims.iter().all(|&d| d == 128)); + + // (b) Registry reflects the new signature. + let sig = harness.store.registered_model().await.unwrap().unwrap(); + assert_eq!(sig.name, "fake-new"); + assert_eq!(sig.dimension, 128); + + // (c) vector_search returns results in the new space. + let probe = new.embed("memory number 5 talks about rust and async").await.unwrap(); + let results = harness.store.vector_search(&probe, 10).await.unwrap(); + assert!(!results.is_empty()); +} +``` + +The `FakeEmbedder` from `common/test_embedder.rs` produces deterministic +vectors by hashing the input; both the seed and the search probe use the +same hash, so the test does not depend on actual semantic similarity. + +### Bench (optional, not gating) + +A simple benchmark in `crates/vestige-core/benches/reembed.rs` reports +throughput at 100k rows with `FakeEmbedder`. Useful for catching +regressions in the UPDATE-pass batching pattern. Not part of CI. + +--- + +## Acceptance criteria + +This sub-plan is complete when: + +1. `crates/vestige-core/src/storage/postgres/reembed.rs` exists and + compiles under `--features postgres-backend`. +2. `ReembedPlan` and `ReembedReport` are public types matching the + shapes in this document. +3. `run_reembed` implements the eight numbered steps in the Driver fn + section, including the no-op short-circuit at step 1 and the + typmod relaxation logic at step 5. +4. `dry_run_reembed` returns counts and estimates without writing. +5. The `vestige migrate reembed ...` subcommand is wired through + `crates/vestige-mcp/src/bin/cli.rs`, gated on `--features + postgres-backend`, validating `--dimension` against + `embedder.dimension()`. +6. The three unit tests pass. +7. The `pg_reembed.rs` integration test passes against the + testcontainer harness from `0002h` (or against a locally provisioned + pgvector instance if `0002h` is not yet merged). +8. The operator-facing WARN banner is printed before any writes and + honours `--no-confirm`. +9. The recovery semantics from "Failure handling" are documented in + the module-level rustdoc of `reembed.rs`, so a future operator + reading `cargo doc` sees the "you must re-run to completion before + serving search" rule without finding this sub-plan first. +10. `cargo sqlx prepare --workspace` updates `.sqlx/` with the new + queries; the resulting JSON files are committed. + +When all ten items are checked, sub-plan `0002g` lands. Master plan +deliverable D9 is satisfied. The remaining Phase 2 work is `0002h` +(testing and benches) and `0002i` (runbook). diff --git a/docs/plans/0002h-testing-and-benches.md b/docs/plans/0002h-testing-and-benches.md new file mode 100644 index 0000000..d6bcebc --- /dev/null +++ b/docs/plans/0002h-testing-and-benches.md @@ -0,0 +1,1223 @@ +# Sub-plan 0002h -- Testing and benches for the Postgres backend + +**Status**: Draft +**Master plan**: [0002-phase-2-postgres-backend.md](0002-phase-2-postgres-backend.md) +**ADR**: [0002-phase-2-execution.md](../adr/0002-phase-2-execution.md) +**Predecessors**: `0002a` through `0002d` (skeleton, pool/config, migrations, +store impl bodies). `0002e` (hybrid search), `0002f` (migrate CLI), and `0002g` +(reembed) provide additional code under test but are not strict blockers -- +the search and migrate test files can be stubbed against the trait surface +and filled out as their implementations land. + +--- + +## Context + +This sub-plan covers master plan deliverables **D14** (six integration test +files under `tests/phase_2/`) and **D15** (Criterion benches for RRF search +at 1k and 100k memories). It can execute in parallel with `0002e`, `0002f`, +`0002g` once `0002d` is merged, because the trait surface they exercise is +frozen by Phase 1 and the directory layout is reserved by `0002a`. + +The deliverable is a Postgres-feature-gated test and bench suite that catches +regressions before they ship. Single goal: when somebody changes +`storage/postgres/`, `cargo test -p vestige-core --features postgres-backend` +either passes (change is safe) or fails fast with a clear localised error +(change broke something a reviewer can name). + +Scope: + +- Add the testcontainer harness in `tests/phase_2/common/`. +- Add six integration test files, each gated on `postgres-backend`. +- Add the Criterion bench `pg_hybrid_search.rs` with two bench groups. +- Wire dev-dependencies, `[[test]]`, and `[[bench]]` entries in + `crates/vestige-core/Cargo.toml`. +- Document how the suite is run locally and what CI must provide. + +Explicitly NOT in scope: + +- Trait-parity testing (`tests/phase_2/pg_trait_parity.rs` from the master + plan). That file's matrix is delegated to the larger Phase 2 parity push + and is tracked in the master plan's D14; this sub-plan ships six focused + files instead, listed below. +- Concurrency stress tests (`pg_concurrency.rs` from the master plan). + Deferred to a follow-up; the ingest/search code in `0002d`/`0002e` does + not change MVCC semantics, so a dedicated stress test is lower priority + than coverage. +- Re-embed integration tests beyond a smoke check. `0002g` ships its own + unit test against an in-memory plan; an end-to-end re-embed test is + worth a follow-up but not required to call Phase 2 done. + +The six test files in this sub-plan map to the methods most likely to +regress during Phase 2 commits: init/registry, CRUD with the new D7/D8 +columns, search, scheduling, graph, and the SQLite to Postgres migrator. + +--- + +## Prerequisites + +- `0002a` -- `crates/vestige-core/src/storage/postgres/mod.rs` exists, the + `postgres-backend` feature gate is declared, `PgMemoryStore` is a real + type. Method bodies may still be `todo!()` for the parts a given test + does not touch. +- `0002b` -- pool construction works; `PgMemoryStore::connect` and + `PgMemoryStore::from_pool` return real pools. +- `0002c` -- `sqlx::migrate!` wired; tests can call + `PgMemoryStore::run_migrations(&pool).await?` (or whatever the migration + helper ends up named in `0002c`) and reach a populated schema. +- `0002d` -- CRUD, scheduling, and graph method bodies are real (not + `todo!()`). Without `0002d` the CRUD/scheduling/graph tests cannot pass. +- `0002e` -- hybrid search body is real. The search test depends on it. + If `0002e` is not yet merged, the search test file can be stubbed + `#[ignore]` and unignored once `0002e` lands. +- `0002f` -- migrate CLI streaming copy is callable as a library function + (`run_sqlite_to_postgres` or equivalent). The migrate test depends on it + and follows the same stub/unignore pattern if needed. +- Docker or Podman is available at test time. CI must provide it. Local + developers without Docker skip the suite via the runtime check described + below. + +--- + +## Dev-dependencies + +Add `testcontainers` and `testcontainers-modules` as optional dev-deps +gated on the `postgres-backend` feature. `criterion` is already in +dev-dependencies from Phase 1 (`search_bench.rs` uses it). + +From the repo root, run: + +```bash +cargo add --package vestige-core --dev --optional testcontainers@0.22 +cargo add --package vestige-core --dev --optional \ + testcontainers-modules@0.10 --features postgres +cargo add --package vestige-core --dev anyhow +cargo add --package vestige-core --dev tokio --features rt-multi-thread,macros +cargo add --package vestige-core --dev rand@0.8 +``` + +`anyhow` is convenient for the harness's error type (`anyhow::Result<...>` +inside the `common/` helper matches master plan D12). `rand` provides the +deterministic seeded RNG used by the search and migrate tests. `tokio` may +already be in dev-deps via Phase 1 -- run `cargo add` anyway; cargo will +update the features in place rather than duplicate. + +Then mark the testcontainer deps as activated only when the +`postgres-backend` feature is on. Cargo does not have a direct +"dev-dependency required-features" syntax; the convention is to declare the +deps as `optional = true` in `[dev-dependencies]` and reference them inside +the new test files behind `#![cfg(feature = "postgres-backend")]`. The +resulting `Cargo.toml` block looks like: + +```toml +[dev-dependencies] +tempfile = "3" +criterion = { version = "0.5", features = ["html_reports"] } +anyhow = "1" +tokio = { version = "1", features = ["rt-multi-thread", "macros"] } +rand = "0.8" +testcontainers = { version = "0.22", optional = true } +testcontainers-modules = { version = "0.10", features = ["postgres"], optional = true } +``` + +The `optional = true` flag prevents `cargo test` (default features) from +pulling in 30+ MB of testcontainer transitive deps on every contributor +laptop. Activation happens via the `postgres-backend` feature itself; the +test files import `testcontainers::...` only under +`#[cfg(feature = "postgres-backend")]`, so the unused-dep warning is +suppressed by the gate. + +If a future reviewer pushes back on `optional = true` for dev-deps +(rustc/clippy gives `unused_optional_dependency` in some toolchain versions), +the fallback is to drop `optional = true` and accept the dev-dep weight; the +testcontainers crate is dev-only and never ships in a release build either +way. + +--- + +## Test container helper + +**File**: `crates/vestige-core/tests/phase_2/common/mod.rs` + +This is shared infrastructure for every test in `tests/phase_2/`. It is not +its own `[[test]]`; it is a `mod common;` import inside each test file. + +```rust +//! Shared testcontainer setup for Phase 2 Postgres integration tests. +#![cfg(feature = "postgres-backend")] + +use std::sync::Arc; + +use anyhow::Result; +use testcontainers::core::{ContainerPort, IntoContainerPort, WaitFor}; +use testcontainers::runners::AsyncRunner; +use testcontainers::{ContainerAsync, GenericImage, ImageExt}; +use testcontainers_modules::postgres::Postgres; + +use vestige_core::embedder::Embedder; +use vestige_core::storage::postgres::PgMemoryStore; + +/// Spin up a fresh pgvector-enabled Postgres container and return a fully +/// migrated PgMemoryStore connected to it. +/// +/// The ContainerAsync handle is returned alongside the store; callers must +/// keep it alive for the duration of the test. Dropping it tears the +/// container down. +pub async fn fresh_pg_store( + embedder: Arc, +) -> Result<(PgMemoryStore, ContainerAsync)> { + // pgvector/pgvector:pg16 is the official pgvector image built on the + // postgres:16 base. testcontainers-modules::postgres::Postgres targets + // the upstream postgres image by default; we override name + tag. + let container = Postgres::default() + .with_name("pgvector/pgvector") + .with_tag("pg16") + .start() + .await?; + + let port = container.get_host_port_ipv4(5432).await?; + let url = format!("postgresql://postgres:postgres@127.0.0.1:{port}/postgres"); + + // Pool size 4 is enough for tests and stays well below the container's + // default max_connections = 100. + let store = PgMemoryStore::connect(&url, 4).await?; + + // Run migrations. `0002c` decides the exact helper name. The canonical + // call point is whichever is true after that sub-plan; pseudocode here: + store.run_migrations().await?; + + // Register the embedder so the dimension typmod stamp is in place + // before any insert. `0002d` lands the real register_model body. + let sig = embedder.signature(); + store.register_model(&sig).await?; + + Ok((store, container)) +} + +/// Fixed embedder used by every test. Deterministic, no ONNX dependency, +/// returns a 768-dim vector hashed from input text. Lives in +/// `tests/phase_2/common/test_embedder.rs`. +pub use test_embedder::TestEmbedder; + +mod test_embedder; +``` + +**File**: `crates/vestige-core/tests/phase_2/common/test_embedder.rs` + +```rust +//! Deterministic hash-based embedder for tests. +//! +//! Avoids the fastembed/ONNX dependency in CI. Returns a 768-dim vector +//! built from a stable hash of the input text. Two equal strings produce +//! equal vectors; near-equal strings produce near-equal vectors only at +//! the trivial token-overlap level (good enough for a smoke check that +//! the vector pipeline is wired, not a real embedding quality test). +#![cfg(feature = "postgres-backend")] + +use std::sync::Arc; + +use async_trait::async_trait; + +use vestige_core::embedder::{Embedder, EmbedderError, ModelSignature}; + +pub struct TestEmbedder { + pub name: String, + pub dim: usize, +} + +impl TestEmbedder { + pub fn new_768() -> Arc { + Arc::new(Self { name: "test-768".into(), dim: 768 }) + } + pub fn new_1024() -> Arc { + Arc::new(Self { name: "test-1024".into(), dim: 1024 }) + } +} + +#[async_trait] +impl Embedder for TestEmbedder { + fn signature(&self) -> ModelSignature { + ModelSignature { + name: self.name.clone(), + dimension: self.dim, + hash: format!("{}-h", self.name), + } + } + + async fn embed(&self, text: &str) -> Result, EmbedderError> { + let mut v = vec![0.0f32; self.dim]; + let bytes = text.as_bytes(); + for (i, b) in bytes.iter().enumerate() { + v[i % self.dim] += (*b as f32) / 255.0; + } + // Normalize so cosine similarity is meaningful. + let norm: f32 = v.iter().map(|x| x * x).sum::().sqrt(); + if norm > 0.0 { + for x in &mut v { + *x /= norm; + } + } + Ok(v) + } +} +``` + +Notes: + +- The exact `Embedder` trait shape is owned by Phase 1; the example above + may need `embed_batch`, `dimension()`, etc. depending on the frozen + surface. Whoever lands this file mirrors whatever the Phase 1 trait + exposes. +- The container handle is returned, not stored in a `static`. Per-test + isolation matters: one failing test must not leak state into the next. +- A runtime Docker check is added inside `fresh_pg_store` if the + containers can't start: catch the connect error, downgrade it to a + `println!` plus `panic!("docker unreachable; skipping")`, and have each + test use `if docker_available()` to early-return. + +A small helper guards CI environments without Docker: + +```rust +/// Returns Ok if a `docker` or `podman` binary is on PATH and responds. +/// Tests that need a container call this first and `eprintln!`+`return` +/// rather than failing when Docker is absent. +pub fn docker_available() -> bool { + use std::process::Command; + for bin in ["docker", "podman"] { + if Command::new(bin).arg("info").output().map(|o| o.status.success()).unwrap_or(false) { + return true; + } + } + false +} +``` + +Each test starts with: + +```rust +if !common::docker_available() { + eprintln!("docker/podman not available; skipping {}", file!()); + return; +} +``` + +This is preferable to `#[ignore]` because the developer sees the skip in +test output rather than silently passing zero tests. + +--- + +## Six test files + +Each file is at `crates/vestige-core/tests/phase_2/.rs`, declares +`#![cfg(feature = "postgres-backend")]` at the top, imports +`mod common;`, and uses `#[tokio::test(flavor = "multi_thread")]`. + +Each file is also wired as a separate `[[test]]` entry in the Cargo.toml +(see "Cargo.toml" section below). This keeps `cargo test` parallelism +per-file and lets a developer run just one file with +`cargo test --features postgres-backend --test `. + +### 1. `tests/phase_2/init_test.rs` + +**Purpose**: verify the migration pipeline and the embedding registry +behave correctly on first connect, on idempotent reconnect, and on +embedder mismatch. + +**Tests**: + +```rust +#![cfg(feature = "postgres-backend")] + +mod common; +use common::{docker_available, fresh_pg_store, TestEmbedder}; + +#[tokio::test(flavor = "multi_thread")] +async fn migrations_apply_cleanly() { + if !docker_available() { eprintln!("docker unavailable; skip"); return; } + let embedder = TestEmbedder::new_768(); + let (_store, _container) = fresh_pg_store(embedder).await.unwrap(); + // If we reached here, sqlx::migrate! ran 0001_init + 0002_hnsw without + // error against a fresh pgvector container. +} + +#[tokio::test(flavor = "multi_thread")] +async fn registry_persists_after_first_connect() { + if !docker_available() { return; } + let embedder = TestEmbedder::new_768(); + let (store, _container) = fresh_pg_store(embedder.clone()).await.unwrap(); + let registered = store.registered_model().await.unwrap(); + assert!(registered.is_some()); + let sig = registered.unwrap(); + assert_eq!(sig.name, "test-768"); + assert_eq!(sig.dimension, 768); +} + +#[tokio::test(flavor = "multi_thread")] +async fn second_connect_with_same_embedder_is_idempotent() { + if !docker_available() { return; } + let embedder = TestEmbedder::new_768(); + let (store_a, container) = fresh_pg_store(embedder.clone()).await.unwrap(); + // Reuse the same container, build a second store against the same URL, + // call register_model again. Must not error. + let port = container.get_host_port_ipv4(5432).await.unwrap(); + let url = format!("postgresql://postgres:postgres@127.0.0.1:{port}/postgres"); + let store_b = vestige_core::storage::postgres::PgMemoryStore::connect(&url, 4).await.unwrap(); + store_b.register_model(&embedder.signature()).await.unwrap(); + assert_eq!( + store_a.registered_model().await.unwrap().unwrap().name, + store_b.registered_model().await.unwrap().unwrap().name, + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn second_connect_with_different_embedder_returns_mismatch() { + if !docker_available() { return; } + let e768 = TestEmbedder::new_768(); + let (_store, container) = fresh_pg_store(e768).await.unwrap(); + let port = container.get_host_port_ipv4(5432).await.unwrap(); + let url = format!("postgresql://postgres:postgres@127.0.0.1:{port}/postgres"); + let store2 = vestige_core::storage::postgres::PgMemoryStore::connect(&url, 4).await.unwrap(); + let e1024 = TestEmbedder::new_1024(); + let err = store2.register_model(&e1024.signature()).await; + assert!(matches!(err, Err(vestige_core::storage::MemoryStoreError::EmbeddingMismatch { .. }))); +} +``` + +### 2. `tests/phase_2/crud_test.rs` + +**Purpose**: insert + get + update + delete round-trip; non-existent id +returns `Ok(None)`; D7+D8 columns (`owner_user_id`, `visibility`, +`shared_with_groups`, `codebase`) round-trip correctly. + +**Tests**: + +```rust +#![cfg(feature = "postgres-backend")] + +mod common; +use common::{docker_available, fresh_pg_store, TestEmbedder}; +use vestige_core::memory::{MemoryRecord, Visibility}; +use uuid::Uuid; + +#[tokio::test(flavor = "multi_thread")] +async fn insert_get_update_delete_roundtrip() { + if !docker_available() { return; } + let embedder = TestEmbedder::new_768(); + let (store, _container) = fresh_pg_store(embedder.clone()).await.unwrap(); + + let mut rec = MemoryRecord::new("hello world"); + rec.tags = vec!["test".into(), "crud".into()]; + rec.embedding = Some(embedder.embed(&rec.content).await.unwrap()); + let id = store.insert(&rec).await.unwrap(); + + let got = store.get(&id).await.unwrap().unwrap(); + assert_eq!(got.content, "hello world"); + assert_eq!(got.tags, vec!["test", "crud"]); + + let mut updated = got.clone(); + updated.content = "hello updated".into(); + updated.embedding = Some(embedder.embed("hello updated").await.unwrap()); + store.update(&updated).await.unwrap(); + let after = store.get(&id).await.unwrap().unwrap(); + assert_eq!(after.content, "hello updated"); + + store.delete(&id).await.unwrap(); + assert!(store.get(&id).await.unwrap().is_none()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn get_nonexistent_returns_ok_none() { + if !docker_available() { return; } + let embedder = TestEmbedder::new_768(); + let (store, _container) = fresh_pg_store(embedder).await.unwrap(); + let missing = Uuid::new_v4(); + assert!(store.get(&missing).await.unwrap().is_none()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn update_nonexistent_returns_not_found() { + if !docker_available() { return; } + let embedder = TestEmbedder::new_768(); + let (store, _container) = fresh_pg_store(embedder.clone()).await.unwrap(); + let mut rec = MemoryRecord::new("ghost"); + rec.id = Uuid::new_v4(); + rec.embedding = Some(embedder.embed("ghost").await.unwrap()); + // Contract: update on a missing id is Err(NotFound) or Ok with + // rows_updated == 0. Whichever 0002d picks is what this test asserts. + let res = store.update(&rec).await; + // Adjust to actual contract once 0002d lands: + assert!(res.is_err() || res.is_ok()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn d7_d8_columns_roundtrip() { + if !docker_available() { return; } + let embedder = TestEmbedder::new_768(); + let (store, _container) = fresh_pg_store(embedder.clone()).await.unwrap(); + + let owner = Uuid::parse_str("00000000-0000-0000-0000-000000000001").unwrap(); + let group_a = Uuid::new_v4(); + let group_b = Uuid::new_v4(); + + let mut rec = MemoryRecord::new("contextful"); + rec.owner_user_id = owner; + rec.visibility = Visibility::Group; + rec.shared_with_groups = vec![group_a, group_b]; + rec.codebase = Some("vestige".to_string()); + rec.embedding = Some(embedder.embed(&rec.content).await.unwrap()); + + let id = store.insert(&rec).await.unwrap(); + let got = store.get(&id).await.unwrap().unwrap(); + + assert_eq!(got.owner_user_id, owner); + assert_eq!(got.visibility, Visibility::Group); + assert_eq!(got.shared_with_groups, vec![group_a, group_b]); + assert_eq!(got.codebase.as_deref(), Some("vestige")); +} +``` + +### 3. `tests/phase_2/search_test.rs` + +**Purpose**: exercise the three search modes (fts only, vector only, +hybrid), then the domain/tag/node_type/min_retrievability filters, then +the empty-query edge case. + +**Tests**: + +```rust +#![cfg(feature = "postgres-backend")] + +mod common; +use common::{docker_available, fresh_pg_store, TestEmbedder}; +use vestige_core::memory::MemoryRecord; +use vestige_core::storage::SearchQuery; + +async fn seed(store: &impl vestige_core::storage::MemoryStore, embedder: &(impl vestige_core::embedder::Embedder + ?Sized)) { + let seeds: &[(&str, &[&str], &str)] = &[ + ("rust async trait", &["rust", "async"], "code"), + ("postgres hnsw vector", &["postgres", "vector"], "code"), + ("fastembed onnx model", &["embeddings", "onnx"], "model"), + ("breakfast tacos recipe", &["food"], "note"), + ("morning bike commute", &["health"], "event"), + ]; + for (text, tags, node_type) in seeds { + let mut r = MemoryRecord::new(*text); + r.tags = tags.iter().map(|s| s.to_string()).collect(); + r.node_type = node_type.to_string(); + r.embedding = Some(embedder.embed(text).await.unwrap()); + store.insert(&r).await.unwrap(); + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn fts_only_returns_keyword_matches() { + if !docker_available() { return; } + let embedder = TestEmbedder::new_768(); + let (store, _c) = fresh_pg_store(embedder.clone()).await.unwrap(); + seed(&store, embedder.as_ref()).await; + + let q = SearchQuery { text: Some("rust".into()), embedding: None, limit: 10, ..Default::default() }; + let hits = store.search(&q).await.unwrap(); + assert!(hits.iter().any(|h| h.content.contains("rust async trait"))); +} + +#[tokio::test(flavor = "multi_thread")] +async fn vector_only_returns_semantic_matches() { + if !docker_available() { return; } + let embedder = TestEmbedder::new_768(); + let (store, _c) = fresh_pg_store(embedder.clone()).await.unwrap(); + seed(&store, embedder.as_ref()).await; + + let qe = embedder.embed("vector search").await.unwrap(); + let q = SearchQuery { text: None, embedding: Some(qe), limit: 10, ..Default::default() }; + let hits = store.search(&q).await.unwrap(); + assert!(!hits.is_empty()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn hybrid_returns_rrf_fused_results() { + if !docker_available() { return; } + let embedder = TestEmbedder::new_768(); + let (store, _c) = fresh_pg_store(embedder.clone()).await.unwrap(); + seed(&store, embedder.as_ref()).await; + + let qe = embedder.embed("postgres vector").await.unwrap(); + let q = SearchQuery { + text: Some("postgres".into()), + embedding: Some(qe), + limit: 10, + ..Default::default() + }; + let hits = store.search(&q).await.unwrap(); + let top = hits.first().unwrap(); + assert!(top.content.contains("postgres")); + // RRF score must be at least the floor of two contributions at rank 0. + assert!(top.score >= 1.0 / 61.0); +} + +#[tokio::test(flavor = "multi_thread")] +async fn filter_by_tag_and_node_type() { + if !docker_available() { return; } + let embedder = TestEmbedder::new_768(); + let (store, _c) = fresh_pg_store(embedder.clone()).await.unwrap(); + seed(&store, embedder.as_ref()).await; + + let q = SearchQuery { + text: Some("model".into()), + tags: vec!["embeddings".into()], + node_type: Some("model".into()), + limit: 10, + ..Default::default() + }; + let hits = store.search(&q).await.unwrap(); + assert!(hits.iter().all(|h| h.tags.contains(&"embeddings".into()))); + assert!(hits.iter().all(|h| h.node_type == "model")); +} + +#[tokio::test(flavor = "multi_thread")] +async fn min_retrievability_filter() { + // After 0002e ships the filter wiring this exercises it. For now, + // assert the empty / pass-through case: min_retrievability = 0.0 + // returns all results. + if !docker_available() { return; } + let embedder = TestEmbedder::new_768(); + let (store, _c) = fresh_pg_store(embedder.clone()).await.unwrap(); + seed(&store, embedder.as_ref()).await; + + let q = SearchQuery { text: Some("rust".into()), min_retrievability: 0.0, limit: 10, ..Default::default() }; + let hits = store.search(&q).await.unwrap(); + assert!(!hits.is_empty()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn empty_query_returns_ok_empty_or_all() { + // Contract chosen in 0002e; this test asserts whichever it picks. + if !docker_available() { return; } + let embedder = TestEmbedder::new_768(); + let (store, _c) = fresh_pg_store(embedder).await.unwrap(); + let q = SearchQuery { text: None, embedding: None, limit: 10, ..Default::default() }; + let hits = store.search(&q).await.unwrap(); + let _ = hits; // assert is intentionally weak until 0002e fixes the contract +} +``` + +### 4. `tests/phase_2/scheduling_test.rs` + +**Purpose**: FSRS state round-trip via `get_scheduling` / +`update_scheduling` with `ON CONFLICT DO UPDATE` semantics, and +`get_due_memories` paging. + +**Tests**: + +```rust +#![cfg(feature = "postgres-backend")] + +mod common; +use common::{docker_available, fresh_pg_store, TestEmbedder}; +use chrono::{Duration, Utc}; +use vestige_core::memory::MemoryRecord; +use vestige_core::scheduling::SchedulingState; + +#[tokio::test(flavor = "multi_thread")] +async fn scheduling_update_and_get_roundtrip() { + if !docker_available() { return; } + let embedder = TestEmbedder::new_768(); + let (store, _c) = fresh_pg_store(embedder.clone()).await.unwrap(); + + let mut rec = MemoryRecord::new("fsrs target"); + rec.embedding = Some(embedder.embed("fsrs target").await.unwrap()); + let id = store.insert(&rec).await.unwrap(); + + let s = SchedulingState { + memory_id: id, + stability: 2.5, + difficulty: 6.7, + reps: 1, + lapses: 0, + next_review: Utc::now() + Duration::days(1), + last_review: Some(Utc::now()), + }; + store.update_scheduling(&s).await.unwrap(); + + let back = store.get_scheduling(&id).await.unwrap().unwrap(); + assert!((back.stability - 2.5).abs() < 1e-6); + assert_eq!(back.reps, 1); +} + +#[tokio::test(flavor = "multi_thread")] +async fn scheduling_on_conflict_overwrites() { + if !docker_available() { return; } + let embedder = TestEmbedder::new_768(); + let (store, _c) = fresh_pg_store(embedder.clone()).await.unwrap(); + + let mut rec = MemoryRecord::new("repeating"); + rec.embedding = Some(embedder.embed("repeating").await.unwrap()); + let id = store.insert(&rec).await.unwrap(); + + for reps in [1u32, 2, 3] { + let s = SchedulingState { + memory_id: id, + stability: reps as f32, + difficulty: 5.0, + reps, + lapses: 0, + next_review: Utc::now() + Duration::days(reps as i64), + last_review: Some(Utc::now()), + }; + store.update_scheduling(&s).await.unwrap(); + } + let final_state = store.get_scheduling(&id).await.unwrap().unwrap(); + assert_eq!(final_state.reps, 3); +} + +#[tokio::test(flavor = "multi_thread")] +async fn get_due_memories_pages() { + if !docker_available() { return; } + let embedder = TestEmbedder::new_768(); + let (store, _c) = fresh_pg_store(embedder.clone()).await.unwrap(); + + let now = Utc::now(); + // Insert 25 due memories with next_review in the past. + for i in 0..25 { + let mut rec = MemoryRecord::new(format!("due {i}")); + rec.embedding = Some(embedder.embed(&rec.content).await.unwrap()); + let id = store.insert(&rec).await.unwrap(); + let s = SchedulingState { + memory_id: id, + stability: 1.0, + difficulty: 5.0, + reps: 1, + lapses: 0, + next_review: now - Duration::hours(i as i64 + 1), + last_review: Some(now - Duration::hours(i as i64 + 2)), + }; + store.update_scheduling(&s).await.unwrap(); + } + let page1 = store.get_due_memories(now, 10, 0).await.unwrap(); + let page2 = store.get_due_memories(now, 10, 10).await.unwrap(); + let page3 = store.get_due_memories(now, 10, 20).await.unwrap(); + assert_eq!(page1.len(), 10); + assert_eq!(page2.len(), 10); + assert_eq!(page3.len(), 5); +} +``` + +### 5. `tests/phase_2/graph_test.rs` + +**Purpose**: `add_edge`, `get_edges`, `remove_edge`, and `get_neighbors` +with a non-trivial depth. + +**Tests**: + +```rust +#![cfg(feature = "postgres-backend")] + +mod common; +use common::{docker_available, fresh_pg_store, TestEmbedder}; +use vestige_core::memory::MemoryRecord; +use vestige_core::storage::Edge; + +async fn insert_n(store: &impl vestige_core::storage::MemoryStore, embedder: &(impl vestige_core::embedder::Embedder + ?Sized), n: usize) -> Vec { + let mut ids = Vec::with_capacity(n); + for i in 0..n { + let mut r = MemoryRecord::new(format!("node {i}")); + r.embedding = Some(embedder.embed(&r.content).await.unwrap()); + ids.push(store.insert(&r).await.unwrap()); + } + ids +} + +#[tokio::test(flavor = "multi_thread")] +async fn add_get_remove_edge() { + if !docker_available() { return; } + let embedder = TestEmbedder::new_768(); + let (store, _c) = fresh_pg_store(embedder.clone()).await.unwrap(); + let ids = insert_n(&store, embedder.as_ref(), 3).await; + + let e = Edge { + source_id: ids[0], + target_id: ids[1], + edge_type: "semantic".into(), + strength: 0.8, + activation_count: 0, + created_at: chrono::Utc::now(), + last_activated: None, + }; + store.add_edge(&e).await.unwrap(); + + let edges = store.get_edges(&ids[0]).await.unwrap(); + assert_eq!(edges.len(), 1); + assert_eq!(edges[0].target_id, ids[1]); + + store.remove_edge(&ids[0], &ids[1], "semantic").await.unwrap(); + assert!(store.get_edges(&ids[0]).await.unwrap().is_empty()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn get_neighbors_with_depth() { + if !docker_available() { return; } + let embedder = TestEmbedder::new_768(); + let (store, _c) = fresh_pg_store(embedder.clone()).await.unwrap(); + let ids = insert_n(&store, embedder.as_ref(), 5).await; + + // Chain: 0 -> 1 -> 2 -> 3 -> 4 + for w in ids.windows(2) { + let e = Edge { + source_id: w[0], + target_id: w[1], + edge_type: "semantic".into(), + strength: 1.0, + activation_count: 0, + created_at: chrono::Utc::now(), + last_activated: None, + }; + store.add_edge(&e).await.unwrap(); + } + + let depth_1 = store.get_neighbors(&ids[0], 1).await.unwrap(); + let depth_2 = store.get_neighbors(&ids[0], 2).await.unwrap(); + let depth_4 = store.get_neighbors(&ids[0], 4).await.unwrap(); + + assert_eq!(depth_1.len(), 1); + assert_eq!(depth_2.len(), 2); + assert_eq!(depth_4.len(), 4); +} +``` + +### 6. `tests/phase_2/migrate_test.rs` + +**Purpose**: seed SQLite with a small dataset, run the migrator, verify +counts and a sample row. + +**Tests**: + +```rust +#![cfg(feature = "postgres-backend")] + +mod common; +use common::{docker_available, fresh_pg_store, TestEmbedder}; +use vestige_core::memory::MemoryRecord; +use vestige_core::storage::{SqliteMemoryStore, MemoryStore}; +use vestige_core::storage::postgres::migrate_cli::run_sqlite_to_postgres; + +#[tokio::test(flavor = "multi_thread")] +async fn sqlite_to_postgres_small_corpus() { + if !docker_available() { return; } + let embedder = TestEmbedder::new_768(); + + // Seed SQLite (in-memory or tempfile). + let tmp = tempfile::tempdir().unwrap(); + let sqlite_path = tmp.path().join("seed.db"); + let sqlite = SqliteMemoryStore::new(&sqlite_path).unwrap(); + sqlite.register_model(&embedder.signature()).await.unwrap(); + for i in 0..50 { + let mut r = MemoryRecord::new(format!("seed row {i}")); + r.tags = vec![format!("tag-{}", i % 3)]; + r.embedding = Some(embedder.embed(&r.content).await.unwrap()); + sqlite.insert(&r).await.unwrap(); + } + + // Spin up Postgres and migrate. + let (pg, _container) = fresh_pg_store(embedder.clone()).await.unwrap(); + let report = run_sqlite_to_postgres(&sqlite, &pg, embedder.clone()).await.unwrap(); + + assert_eq!(report.memories_copied, 50); + assert_eq!(pg.count().await.unwrap(), 50); + + // Spot-check a sample row. + let sample_id = sqlite.list_ids(1, 0).await.unwrap()[0]; + let from_sqlite = sqlite.get(&sample_id).await.unwrap().unwrap(); + let from_pg = pg.get(&sample_id).await.unwrap().unwrap(); + assert_eq!(from_sqlite.content, from_pg.content); + assert_eq!(from_sqlite.tags, from_pg.tags); +} +``` + +If `0002f` is not yet merged when this sub-plan executes, the test file is +still added but the body sits behind `#[ignore = "depends on 0002f"]`, +removed once `0002f` lands. + +--- + +## How tests are run + +```bash +# Run all six phase_2 integration tests: +cargo test -p vestige-core --features postgres-backend --test '*' + +# Run a single file: +cargo test -p vestige-core --features postgres-backend --test init_test +cargo test -p vestige-core --features postgres-backend --test crud_test +cargo test -p vestige-core --features postgres-backend --test search_test +cargo test -p vestige-core --features postgres-backend --test scheduling_test +cargo test -p vestige-core --features postgres-backend --test graph_test +cargo test -p vestige-core --features postgres-backend --test migrate_test + +# SQLite-only sanity check (must continue to pass, Phase 1 unchanged): +cargo test -p vestige-core +``` + +Requirements: + +- Docker or Podman must be reachable. `testcontainers` connects via the + default Docker socket (`/var/run/docker.sock` on Linux, `~/.docker/run/docker.sock` + or the Docker Desktop socket on macOS, the Podman REST socket if + `DOCKER_HOST` points there). +- On a developer machine without Docker, the suite skips at runtime via + the `docker_available()` check in `common/mod.rs`. The test output + includes a `docker unavailable; skip` line per test so the developer + knows the tests were not silently dropped. +- The pgvector image (`pgvector/pgvector:pg16`) is pulled on first run; + ~200 MB. A pre-pulled image keeps the per-run overhead at the cold-start + container boot (~2-5 seconds). + +--- + +## Benches + +**File**: `crates/vestige-core/benches/pg_hybrid_search.rs` + +Two Criterion benches: `search_1k` and `search_100k`. Both gated on the +`postgres-backend` feature via `required-features` in the bench entry and +via a top-of-file `#![cfg(feature = "postgres-backend")]`. + +```rust +//! Criterion benches for the Postgres backend's hybrid RRF search. +#![cfg(feature = "postgres-backend")] + +use std::sync::Arc; +use std::sync::OnceLock; + +use criterion::{black_box, criterion_group, criterion_main, Criterion}; +use rand::{rngs::StdRng, Rng, SeedableRng}; +use testcontainers::runners::AsyncRunner; +use testcontainers::{ContainerAsync, ImageExt}; +use testcontainers_modules::postgres::Postgres; +use tokio::runtime::Runtime; + +use vestige_core::embedder::Embedder; +use vestige_core::memory::MemoryRecord; +use vestige_core::storage::postgres::PgMemoryStore; +use vestige_core::storage::{MemoryStore, SearchQuery}; + +// Bench fixture lives in tests/phase_2/common/test_embedder.rs; +// duplicate the type here under benches/ so the bench compiles without +// depending on tests/. +mod test_embedder; +use test_embedder::TestEmbedder; + +struct Bench { + rt: Runtime, + store: PgMemoryStore, + embedder: Arc, + _container: ContainerAsync, + query_embedding: Vec, +} + +async fn build_bench(rows: usize) -> Bench { + let rt_handle = tokio::runtime::Handle::current(); + let _ = rt_handle; // proves we are inside an executor + let embedder = TestEmbedder::new_768(); + let container = Postgres::default() + .with_name("pgvector/pgvector") + .with_tag("pg16") + .start() + .await + .unwrap(); + let port = container.get_host_port_ipv4(5432).await.unwrap(); + let url = format!("postgresql://postgres:postgres@127.0.0.1:{port}/postgres"); + let store = PgMemoryStore::connect(&url, 8).await.unwrap(); + store.run_migrations().await.unwrap(); + store.register_model(&embedder.signature()).await.unwrap(); + + let mut rng = StdRng::seed_from_u64(0xc0ffee); + let vocab = [ + "rust", "postgres", "vector", "hnsw", "fastembed", "onnx", + "search", "memory", "fsrs", "consolidate", "graph", "edge", + "async", "trait", "tokio", "sqlx", "pgvector", "embedding", + ]; + for i in 0..rows { + let words: String = (0..8) + .map(|_| vocab[rng.gen_range(0..vocab.len())]) + .collect::>() + .join(" "); + let mut r = MemoryRecord::new(format!("{i}: {words}")); + r.tags = vec![format!("tag-{}", i % 7)]; + r.embedding = Some(embedder.embed(&r.content).await.unwrap()); + store.insert(&r).await.unwrap(); + } + let query_embedding = embedder.embed("postgres vector search").await.unwrap(); + Bench { + rt: tokio::runtime::Runtime::new().unwrap(), + store, + embedder, + _container: container, + query_embedding, + } +} + +fn bench_search_1k(c: &mut Criterion) { + let rt = tokio::runtime::Runtime::new().unwrap(); + let bench = rt.block_on(build_bench(1_000)); + c.bench_function("pg_search_1k", |b| { + b.iter(|| { + let q = SearchQuery { + text: Some("postgres vector".into()), + embedding: Some(bench.query_embedding.clone()), + limit: 10, + ..Default::default() + }; + let hits = bench.rt.block_on(bench.store.search(&q)).unwrap(); + black_box(hits); + }) + }); +} + +// Heavy: 100k rows; seed time runs into minutes. Gated by an env var so +// `cargo bench --features postgres-backend --bench pg_hybrid_search` does +// not pay the cost by default. +fn bench_search_100k(c: &mut Criterion) { + if std::env::var("VESTIGE_BENCH_HEAVY").is_err() { + eprintln!("skip pg_search_100k (set VESTIGE_BENCH_HEAVY=1 to enable)"); + return; + } + let rt = tokio::runtime::Runtime::new().unwrap(); + let bench = rt.block_on(build_bench(100_000)); + c.bench_function("pg_search_100k", |b| { + b.iter(|| { + let q = SearchQuery { + text: Some("postgres vector".into()), + embedding: Some(bench.query_embedding.clone()), + limit: 10, + ..Default::default() + }; + let hits = bench.rt.block_on(bench.store.search(&q)).unwrap(); + black_box(hits); + }) + }); +} + +criterion_group!(benches, bench_search_1k, bench_search_100k); +criterion_main!(benches); +``` + +**File**: `crates/vestige-core/benches/test_embedder.rs` + +Duplicate of `tests/phase_2/common/test_embedder.rs`. Cargo's bench target +cannot `mod` into `tests/`; the duplication is the standard fix. Keep both +files in sync; if either grows non-trivially, refactor into a shared +`pub(crate)` module under `src/embedder/test_support.rs` gated on +`#[cfg(any(test, feature = "test-support"))]`. + +`VESTIGE_BENCH_HEAVY` gate: the 100k seed step takes several minutes (one +`INSERT` per row plus HNSW upsert). Skipping by default keeps `cargo bench` +under a minute for the 1k bench. Document this gate in the runbook +(`0002i`). + +--- + +## Cargo.toml + +Final state of the relevant sections of +`crates/vestige-core/Cargo.toml` after this sub-plan lands: + +```toml +[dev-dependencies] +tempfile = "3" +criterion = { version = "0.5", features = ["html_reports"] } +anyhow = "1" +tokio = { version = "1", features = ["rt-multi-thread", "macros"] } +rand = "0.8" +testcontainers = { version = "0.22", optional = true } +testcontainers-modules = { version = "0.10", features = ["postgres"], optional = true } + +[[bench]] +name = "search_bench" +harness = false + +[[bench]] +name = "pg_hybrid_search" +harness = false +required-features = ["postgres-backend"] + +[[test]] +name = "init_test" +path = "tests/phase_2/init_test.rs" +required-features = ["postgres-backend"] + +[[test]] +name = "crud_test" +path = "tests/phase_2/crud_test.rs" +required-features = ["postgres-backend"] + +[[test]] +name = "search_test" +path = "tests/phase_2/search_test.rs" +required-features = ["postgres-backend"] + +[[test]] +name = "scheduling_test" +path = "tests/phase_2/scheduling_test.rs" +required-features = ["postgres-backend"] + +[[test]] +name = "graph_test" +path = "tests/phase_2/graph_test.rs" +required-features = ["postgres-backend"] + +[[test]] +name = "migrate_test" +path = "tests/phase_2/migrate_test.rs" +required-features = ["postgres-backend"] +``` + +Notes: + +- `required-features = ["postgres-backend"]` on each `[[test]]` ensures + the file is only built (and only counted by `cargo test`) when the + feature is on. Cargo silently skips it otherwise -- exactly the desired + behavior for default `cargo test` runs. +- The benches use the same `required-features` shape so default + `cargo bench` is unaffected. + +--- + +## CI considerations + +- GitHub Actions / Forgejo Actions runners need Docker available. Default + `ubuntu-latest` runners include Docker. Self-hosted Forgejo runners on + TFGrid VMs must install `docker.io` or run `podman` with the Docker + socket compatibility shim. Document the runner requirement in the + runbook (`0002i`). +- The Postgres feature tests should run in a separate CI matrix entry to + isolate failures and skip them entirely on platforms (Windows runners + if any) where the pgvector image is not available. +- Cache the `pgvector/pgvector:pg16` image between runs. The + `docker/setup-buildx-action` cache or a simple `docker pull` step before + the test step keeps cold-start under the existing CI time budget. +- Skip CI: contributors without Docker can still merge changes that do + not touch `storage/postgres/`. The pre-merge required check is "phase_2 + tests pass on the runner with Docker"; the local pre-commit hook does + not gate on it. +- Bench CI: do not run `pg_search_100k` in regular CI; only run it + manually or on a scheduled weekly job and post results to the PR + description / ADR comment trail. + +Recommended CI job shape (sketch): + +```yaml +jobs: + postgres-tests: + runs-on: ubuntu-latest + services: + # no `postgres` service block needed; testcontainers manages its own + steps: + - uses: actions/checkout@v4 + - run: docker pull pgvector/pgvector:pg16 + - uses: dtolnay/rust-toolchain@stable + - run: cargo test -p vestige-core --features postgres-backend --test '*' +``` + +--- + +## Verification + +After all files are in place: + +```bash +# Default build still clean (no postgres deps pulled in): +cargo build -p vestige-core +cargo test -p vestige-core + +# Postgres feature build + integration tests: +cargo build -p vestige-core --features postgres-backend +cargo test -p vestige-core --features postgres-backend + +# Just the new tests: +cargo test -p vestige-core --features postgres-backend --test '*' + +# Quick bench sanity check (1k only): +cargo bench -p vestige-core --features postgres-backend --bench pg_hybrid_search -- --quick + +# Heavy bench (manual, multi-minute seed step): +VESTIGE_BENCH_HEAVY=1 cargo bench -p vestige-core \ + --features postgres-backend \ + --bench pg_hybrid_search -- --quick + +# Clippy with everything on: +cargo clippy -p vestige-core --features postgres-backend --all-targets -- -D warnings +``` + +Expected results: + +- Default build is unchanged; no testcontainers deps in `Cargo.lock`'s + default resolution. +- With `--features postgres-backend`, all six integration tests pass on a + machine with Docker available, or each prints `docker unavailable; skip` + and exits 0. +- `cargo bench ... -- --quick` produces a `pg_search_1k` line with a + p50 below the master plan's 10 ms target on a developer laptop (looser + on a CI runner -- the target is informative, not gated). + +--- + +## Acceptance criteria + +- [ ] `crates/vestige-core/tests/phase_2/common/mod.rs` and + `test_embedder.rs` exist and compile under + `--features postgres-backend`. +- [ ] All six integration test files exist, each with + `#![cfg(feature = "postgres-backend")]` at the top. +- [ ] Each test file has a corresponding `[[test]]` entry in + `Cargo.toml` with `required-features = ["postgres-backend"]`. +- [ ] `crates/vestige-core/benches/pg_hybrid_search.rs` exists with + `search_1k` and `search_100k` benches, the latter gated on + `VESTIGE_BENCH_HEAVY`. +- [ ] `[[bench]] name = "pg_hybrid_search"` entry present with + `required-features = ["postgres-backend"]`. +- [ ] `testcontainers@0.22` and `testcontainers-modules@0.10` with the + `postgres` feature are in `[dev-dependencies]` of `vestige-core`. +- [ ] `anyhow`, `tokio`, `rand` are in `[dev-dependencies]`. +- [ ] `cargo build -p vestige-core` (default features) is unchanged: no + testcontainers in the build graph; no new warnings. +- [ ] `cargo test -p vestige-core` (default features) passes with no + changes to the Phase 1 test count beyond what `0002a..g` already + moved. +- [ ] `cargo test -p vestige-core --features postgres-backend --test '*'` + passes on a runner with Docker available, or skips cleanly with the + `docker unavailable; skip` lines. +- [ ] `cargo bench -p vestige-core --features postgres-backend + --bench pg_hybrid_search -- --quick` runs `pg_search_1k` to + completion and does NOT run `pg_search_100k` unless + `VESTIGE_BENCH_HEAVY=1`. +- [ ] `cargo clippy -p vestige-core --features postgres-backend + --all-targets -- -D warnings` is clean. +- [ ] The runbook (`0002i`) gets a one-paragraph "How to run the test + suite locally" callout referring back to this sub-plan's + "Verification" section. (`0002i` is owned separately; this sub-plan + just lists the dependency.) + +--- + +## Open questions for the implementer + +1. **Migration helper name.** `0002c` decides whether + `PgMemoryStore::run_migrations(&self)` or + `vestige_core::storage::postgres::migrations::run(&pool)` is the public + call. Update `common/mod.rs` to match. +2. **Update-on-missing contract.** `0002d` decides whether + `MemoryStore::update` returns `Err(NotFound)` or `Ok(())` with zero + affected rows when the id does not exist. The CRUD test stub here + accepts either; tighten the assert once the contract is fixed. +3. **Empty-query search contract.** `0002e` decides whether + `SearchQuery { text: None, embedding: None }` is `Ok(empty)` or an + error. Same tightening pattern as #2. +4. **Pool size for 100k bench.** Current value is 8; if the bench + bottlenecks on the pool, tune up to 16 or 32 and document in the + bench file's leading doc comment. +5. **Shared `TestEmbedder` location.** Currently duplicated between + `tests/phase_2/common/test_embedder.rs` and + `benches/test_embedder.rs`. If duplication bothers a reviewer, lift to + `crates/vestige-core/src/embedder/test_support.rs` behind a + `test-support` Cargo feature pulled in by both `tests` and `benches`. + Out of scope for this sub-plan; record as a follow-up. diff --git a/docs/plans/0002i-runbook.md b/docs/plans/0002i-runbook.md new file mode 100644 index 0000000..f63694f --- /dev/null +++ b/docs/plans/0002i-runbook.md @@ -0,0 +1,724 @@ +# Phase 2 Sub-Plan 0002i -- Postgres Ops Runbook + +**Status**: Ready +**Depends on**: Phase 2 sub-plans 0002a through 0002h merged (or at least +their interfaces stable). The runbook documents behaviour produced by those +sub-plans: feature gate, config schema, migrations, `vestige migrate` CLI, +hybrid search, and the test harness. Nothing in this sub-plan compiles or +runs; the deliverable is a single Markdown file. + +This sub-plan covers Phase 2 master-plan deliverable D16 only: a one-page +operator-facing runbook for deploying Vestige with the Postgres backend. + +--- + +## Context + +Why a runbook. The ADR (0002) and the master plan (0002) are written for +implementors. They settle execution-level decisions and itemise deliverables. +They are not deployable instructions. A separate document is needed for the +operator who has to install pgvector, take backups, recover from a failed +re-embed, and decide whether to roll a migration back. The runbook is that +document. + +Who reads it. Ops people, not developers. Concretely: someone who has a +shell on a Linux host, knows how to use `psql` and `systemctl`, and has been +handed a built `vestige-mcp` binary plus a `vestige.toml`. They are not +expected to read Rust source or follow internal Cargo features. They do +know what a backup is, what a connection pool is, and how to read a +PostgreSQL log. + +In scope: deployment of the Postgres backend on a single host or a small +cluster, day-to-day monitoring, scheduled and ad-hoc backups, embedding +migration via `vestige migrate reembed`, and troubleshooting the failure +modes most likely to land in an operator's lap. + +Out of scope: local development setup -- that lives in +`docs/plans/local-dev-postgres-setup.md` and the runbook links to it for +developer onboarding only. Network exposure of the Vestige HTTP API +(Phase 3), federation (Phase 5), Postgres TLS / certificate handling, and +multi-tenant operation are also out of scope; the runbook explicitly +flags them as "see Phase N" so operators do not improvise. + +This sub-plan is the plan for producing the runbook. It outlines the +runbook structure, inlines the runbook body as the canonical "this is what +the file should say" text, and lists acceptance criteria. The implementation +agent for D16 copies the inlined body into `docs/runbook/postgres.md`, +creating `docs/runbook/` if it does not already exist. No other files in the +repository are modified. + +--- + +## Deliverable + +The artifact produced by executing this sub-plan is exactly one new file: + +``` +docs/runbook/postgres.md +``` + +It is NOT under `docs/plans/`. Plans describe how Vestige gets built; +runbooks describe how Vestige gets operated. The two directories are +deliberately separated. + +Side effect: create the directory `docs/runbook/` if it does not exist. +Do not add an index file, README, or any other content under `docs/runbook/` +in this sub-plan -- only `postgres.md`. + +This sub-plan document (`docs/plans/0002i-runbook.md`) is itself NOT a +deliverable in the operator sense. It is the plan for producing the runbook, +and lives under `docs/plans/` with the other Phase 2 sub-plans. + +--- + +## Runbook structure + +The runbook is organised as a flat list of ten sections, in order. Operators +read it top to bottom on first deployment; subsequent visits jump to a +specific section. Section numbering matches the inlined body below. + +1. **Prerequisites** -- what must already be installed and available on the + host before Vestige even tries to connect. PostgreSQL 16 or newer + (18 on Arch is fine), pgvector >= 0.5, pgcrypto (for `gen_random_uuid`), + sufficient disk for the HNSW index, OS user permissions on the data + directory. + +2. **Initial setup** -- one-time tasks: create the database role, create + the database, install required extensions, and lay down an initial + `vestige.toml`. Includes the canonical `CREATE EXTENSION` calls and a + minimal config snippet. + +3. **First connect** -- what happens the first time `vestige-mcp` starts + against an empty `vestige` database: sqlx applies the bundled + migrations, `register_model` stamps the embedding column type, and the + registry row is written. How an operator verifies each step succeeded + using `psql`. + +4. **Connection pool tuning** -- default of 10 connections per + `vestige-mcp` instance, when to raise it, how to size the Postgres + server-side `max_connections` and `shared_buffers` accordingly. Cross- + reference to `vestige.toml` and to ADR 0002 D2 / open question Q5. + +5. **Backup discipline** -- `pg_dump` and `pg_restore` invocations, + recommended frequency, which tables matter (knowledge_nodes and scheduling + are critical and not regenerable; review_events is append-only and + replayable from clients; edges are reconstructable from spreading + activation runs; domains can be recomputed by Phase 4 once it ships). + Also covers backup verification (restore-to-tmp drill). + +6. **Migration between embeddings** -- the `vestige migrate reembed` + workflow: when an operator needs it (model upgrade, dim change), + downtime expectations, how to verify completion via the + `embedding_model` registry and HNSW presence, and how to recover from + an interrupted run. + +7. **Re-clustering domains** -- a brief forward reference. Domain + clustering is owned by Phase 4 (`docs/plans/0004-phase-4-emergent-domain-classification.md`); + until Phase 4 ships, operators should not invoke any re-clustering + workflow manually. The runbook section is intentionally one paragraph + long and points at the Phase 4 plan. + +8. **Monitoring** -- the small set of pg_catalog and pg_stat_* queries + that answer "is Vestige healthy?": `pg_stat_activity` for stuck queries, + `pg_stat_statements` for query patterns (if the extension is enabled), + index sizes for the HNSW, and how to spot a half-built HNSW after a + failed migration. + +9. **Troubleshooting** -- a table of common errors with the symptom and + the fix. Extension missing, pool exhausted, embedding dimension + mismatch, FTS language config (`'english'` vs `'simple'`), migrations + partially applied. + +10. **Rollback caveats** -- every `*.up.sql` has a `*.down.sql`, but + downgrades destroy data (HNSW gets dropped, vector column type + reverts, domain rows vanish). The runbook tells operators to always + take a backup before applying a new migration, even though sqlx will + do its best to be idempotent. + +--- + +## Runbook body + +The full text below is what should be copied verbatim into +`docs/runbook/postgres.md`. ASCII only. Code blocks use fenced syntax with +language hints. Operator-facing prose; second person ("you") for +instructions. Where a command requires sudo, the prompt shows it explicitly. + +```markdown +# Vestige Postgres Backend -- Operator Runbook + +This runbook covers deploying, operating, monitoring, and recovering a +Vestige installation that uses the Postgres backend. It is written for +operators handling a built `vestige-mcp` binary and a `vestige.toml`. + +For local development setup, see +`docs/plans/local-dev-postgres-setup.md`. For the architectural rationale, +see `docs/adr/0001-pluggable-storage-and-network-access.md` and +`docs/adr/0002-phase-2-execution.md`. For the deliverable-level plan, see +`docs/plans/0002-phase-2-postgres-backend.md`. + +--- + +## 1. Prerequisites + +Before Vestige can connect: + +- PostgreSQL server, version 16 or newer. Arch ships 18.x; Debian stable + ships 16.x; both work. +- `pgvector` extension, version 0.5 or newer. Distro packages: + `pgvector` on Arch, `postgresql-16-pgvector` on Debian/Ubuntu. +- `pgcrypto` extension, shipped with the PostgreSQL contrib package + (`postgresql-contrib` on Debian, included in the base `postgresql` + package on Arch). Vestige uses `gen_random_uuid()` from pgcrypto for + primary keys. +- Disk space: budget roughly 4x the size of your `knowledge_nodes.embedding` + column for the HNSW index. With 768-dim float32 vectors at 100k + memories, that is about 1.2 GB for the embeddings plus 4-5 GB for the + HNSW index. Plan accordingly. +- OS user: the `postgres` system user (or whatever user owns + `/var/lib/postgres/data`) must have read/write on the data directory. + Vestige itself does not need filesystem access to Postgres; it talks + TCP only. +- Network: Vestige and Postgres can be on the same host (loopback) or + different hosts. If different hosts, allow the Vestige host's IP in + `pg_hba.conf` and on any firewall. + +--- + +## 2. Initial setup + +These steps run once per Postgres cluster. + +### 2.1 Install extensions + +As the `postgres` superuser: + +```sh +sudo -u postgres psql -d vestige <<'SQL' +CREATE EXTENSION IF NOT EXISTS vector; +CREATE EXTENSION IF NOT EXISTS pgcrypto; +SQL +``` + +Verify: + +```sh +sudo -u postgres psql -d vestige -c \ + "SELECT extname, extversion FROM pg_extension WHERE extname IN ('vector','pgcrypto');" +``` + +You should see two rows. If `vector` is missing, the pgvector package was +not installed for the right PostgreSQL major version; reinstall it. + +### 2.2 Create the role and database + +The `vestige` role owns its own database; it does NOT need superuser. +Extensions must be installed by `postgres`, not by `vestige`. + +```sh +sudo -u postgres psql -v ON_ERROR_STOP=1 <<'SQL' +CREATE ROLE vestige WITH LOGIN CREATEDB PASSWORD 'CHANGE_ME'; +CREATE DATABASE vestige OWNER vestige ENCODING 'UTF8'; +GRANT ALL PRIVILEGES ON DATABASE vestige TO vestige; +SQL + +sudo -u postgres psql -d vestige -v ON_ERROR_STOP=1 <<'SQL' +GRANT ALL ON SCHEMA public TO vestige; +ALTER SCHEMA public OWNER TO vestige; +ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO vestige; +ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON SEQUENCES TO vestige; +ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON FUNCTIONS TO vestige; +SQL +``` + +Replace `CHANGE_ME` with a strong password and store it where Vestige can +read it (typically `~/.vestige_pg_pw`, mode 600, owned by the user running +`vestige-mcp`). + +### 2.3 Minimal `vestige.toml` + +```toml +[storage] +backend = "postgres" + +[storage.postgres] +url = "postgresql://vestige:CHANGE_ME@127.0.0.1:5432/vestige" +max_connections = 10 +``` + +The `url` field accepts a `${VAR}` placeholder; in practice operators +either inline the password or export `DATABASE_URL` and reference +`url = "${DATABASE_URL}"`. See `docs/CONFIGURATION.md` for the full +schema once Phase 3 lands. + +--- + +## 3. First connect + +When `vestige-mcp` starts against an empty `vestige` database, it: + +1. Builds a `PgPool` of `max_connections` (default 10) connections. +2. Runs every migration in `crates/vestige-core/migrations/postgres/` + in order. The bundled migrations are `0001_init` (tables, non-vector + indexes) and `0002_hnsw` (HNSW index on `knowledge_nodes.embedding`). +3. Calls `register_model` once it knows the active embedder's dimension. + This issues `ALTER TABLE knowledge_nodes ALTER COLUMN embedding TYPE + vector($N)` and inserts a row into `embedding_model`. +4. Begins accepting MCP requests. + +To verify after the first start: + +```sh +sudo -u postgres psql -d vestige <<'SQL' +-- All expected tables present. +\dt +-- embedding_model has exactly one row. +SELECT name, dimension, hash FROM embedding_model; +-- The HNSW index exists. +SELECT indexname FROM pg_indexes + WHERE tablename = 'knowledge_nodes' AND indexname LIKE '%hnsw%'; +SQL +``` + +Expected: `knowledge_nodes`, `scheduling`, `edges`, `domains`, `review_events`, +`embedding_model`, `users`, `groups`, `group_memberships`; one row in +`embedding_model`; one `idx_knowledge_nodes_embedding_hnsw` index. + +If a migration fails mid-way, the partial state lands in +`_sqlx_migrations`. See section 9 for recovery. + +--- + +## 4. Connection pool tuning + +Defaults: + +- Vestige client pool: `max_connections = 10` per `vestige-mcp` instance. +- Postgres server: `max_connections = 100` (default). + +Math: one MCP client with the default pool uses up to 10 server slots. +Five concurrent MCP clients use up to 50 slots. The remaining 50 cover +`psql` sessions, background workers, and headroom for replication or +backup processes. + +When to raise: + +- More than three MCP clients connecting to one Postgres instance. +- Long-running queries (above 500ms p99) showing pool wait time in + Vestige logs (look for `pool acquire timed out` warnings). +- A noticeable number of concurrent dream/consolidation runs. + +How to raise: + +```toml +[storage.postgres] +max_connections = 20 # client side, per vestige-mcp instance +``` + +And on the Postgres server, edit `postgresql.conf`: + +```conf +max_connections = 200 +shared_buffers = 2GB # roughly 25 percent of RAM, never above 8GB +``` + +Then restart Postgres (`sudo systemctl restart postgresql`). Vestige +clients pick up their own `max_connections` change on next restart. + +Do not raise pool sizes blindly. Past about 4x the CPU core count, +Postgres throughput drops; a small connection pooler (PgBouncer in +transaction mode) is the right answer above ~200 client connections, +but Vestige's expected scale rarely needs that. + +--- + +## 5. Backup discipline + +### 5.1 Which tables matter + +| Table | Backup priority | Regenerable? | +|-------|-----------------|--------------| +| `knowledge_nodes` | Critical | No | +| `scheduling` | Critical | No (FSRS state) | +| `embedding_model` | Critical | No (one row, but stamps the column type) | +| `users`, `groups`, `group_memberships` | Critical | No (Phase 3 will populate) | +| `review_events` | Important | Replayable by clients but tedious | +| `edges` | Optional | Yes (recomputed by spreading activation) | +| `domains` | Optional | Yes (Phase 4 recomputes by clustering) | + +For a typical single-operator install, dumping the whole database is +fastest and simplest. Skip the optional tables only if dump size becomes +a bandwidth problem. + +### 5.2 Full logical backup + +```sh +pg_dump --host=127.0.0.1 --username=vestige --format=custom \ + --file=vestige-$(date -u +%Y%m%dT%H%M%SZ).dump \ + vestige +``` + +The custom format compresses by default and works with parallel restore. +File size for 10k memories: roughly 80 MB. + +Frequency recommendations: + +- Daily for any installation with active ingest. +- Before every `vestige migrate reembed` run (see section 6). +- Before every Postgres major-version upgrade. +- Retain at least 7 daily, 4 weekly, 3 monthly dumps. Compress with + `--format=custom` (already gzipped) and keep them on different + storage from the database itself. + +### 5.3 Restore + +To a fresh database: + +```sh +sudo -u postgres createdb -O vestige vestige_restore +pg_restore --host=127.0.0.1 --username=vestige --dbname=vestige_restore \ + --jobs=4 vestige-20260301T030000Z.dump +``` + +To replace the live database (destructive; only after taking a fresh +dump): + +```sh +sudo systemctl stop vestige-mcp # or however the service is run +sudo -u postgres dropdb vestige +sudo -u postgres createdb -O vestige vestige +pg_restore --host=127.0.0.1 --username=vestige --dbname=vestige \ + --jobs=4 vestige-20260301T030000Z.dump +sudo systemctl start vestige-mcp +``` + +### 5.4 Restore drill + +Run a restore-to-throwaway-database every month and run `vestige search` +or a manual `psql` count against it. A backup you have not restored is a +backup you do not have. + +```sh +sudo -u postgres createdb -O vestige vestige_restore_drill +pg_restore --host=127.0.0.1 --username=vestige --dbname=vestige_restore_drill \ + --jobs=4 vestige-latest.dump +PGPASSWORD="$(cat ~/.vestige_pg_pw)" psql -h 127.0.0.1 -U vestige \ + -d vestige_restore_drill \ + -c 'SELECT count(*) FROM knowledge_nodes;' +sudo -u postgres dropdb vestige_restore_drill +``` + +--- + +## 6. Migration between embeddings + +Use `vestige migrate reembed` when: + +- Upgrading to a new embedding model that produces a different dimension + (for example, swapping from `nomic-embed-text-v1.5` 768D to a 1024D + model). +- Switching providers and the model hash differs even at the same + dimension. + +What it does: + +1. Reads every row from `knowledge_nodes`, re-encodes the `content` column + through the new embedder, and writes the new vector back. +2. Drops the HNSW index before the re-encode loop (this is the default; + `--concurrent-index` keeps it during the run at the cost of speed). +3. Updates the `embedding_model` row with the new name, dimension, and + hash. +4. Rebuilds the HNSW index with the new vectors. + +### 6.1 Before starting + +- Take a fresh backup (section 5.2). The tool refuses to start without a + `--yes` flag if it detects no recent backup; ignore at your peril. +- Stop ingest. Vestige's MCP server can stay running for read-only + access, but pause any client that calls `smart_ingest` or + `update_scheduling`. +- Have the new embedder model available locally. The CLI loads it + before the first row is touched; if loading fails, no data is changed. + +### 6.2 Running + +```sh +vestige migrate reembed --model= --yes +``` + +Add `--concurrent-index` if you cannot accept the brief window during +HNSW rebuild where queries do not use the index (sequential scan +fallback works but is slow). + +The tool prints a progress bar via `indicatif`. Expected throughput: +roughly 200 memories per second per CPU core for a 768D ONNX model. +10,000 memories on an 8-core box: about 6 seconds, plus HNSW rebuild +(another 30-90 seconds at that scale). + +### 6.3 Verifying completion + +```sh +sudo -u postgres psql -d vestige <<'SQL' +-- Registry reflects the new model. +SELECT name, dimension, hash FROM embedding_model; +-- HNSW index is present and not partial. +SELECT indexname, indexdef + FROM pg_indexes + WHERE tablename = 'knowledge_nodes' AND indexname LIKE '%hnsw%'; +-- All rows have a non-null embedding of the new dimension. +SELECT count(*) FILTER (WHERE embedding IS NULL) AS missing, + count(*) AS total + FROM knowledge_nodes; +SQL +``` + +Expected: registry shows the new model name and dimension, one HNSW +index, zero missing embeddings. + +### 6.4 Recovering from an interrupted run + +`vestige migrate reembed` is restartable. On interruption: + +- The `embedding_model` row may or may not have been updated. Check it + manually and roll forward by re-running with `--yes --resume` (the + tool detects the inconsistency and finishes the rows that still hold + old embeddings). +- The HNSW index may be missing. Re-running the command rebuilds it as + its last step. +- If the system is in a state the tool refuses to reason about, restore + from the backup taken in 6.1. + +--- + +## 7. Re-clustering domains + +Domain clustering is owned by Phase 4 +(`docs/plans/0004-phase-4-emergent-domain-classification.md`). Until +Phase 4 ships, the `domains` table is reserved schema and is populated +only by tests. Operators must not invoke any domain re-clustering +workflow manually; there is no supported one in Phase 2. + +When Phase 4 lands, this section is replaced with the real procedure. + +--- + +## 8. Monitoring + +### 8.1 Quick health check + +```sh +PGPASSWORD="$(cat ~/.vestige_pg_pw)" psql -h 127.0.0.1 -U vestige -d vestige <<'SQL' +SELECT count(*) AS memory_count FROM knowledge_nodes; +SELECT name, dimension FROM embedding_model; +SELECT pg_size_pretty(pg_database_size('vestige')) AS db_size; +SQL +``` + +### 8.2 In-flight queries + +```sql +SELECT pid, now() - query_start AS runtime, state, query + FROM pg_stat_activity + WHERE datname = 'vestige' AND state <> 'idle' + ORDER BY runtime DESC NULLS LAST; +``` + +Anything over 5 seconds with `state = 'active'` deserves a look. HNSW +search queries should land well under 100ms on properly-sized hardware. + +### 8.3 Query pattern analysis + +If `pg_stat_statements` is loaded (`shared_preload_libraries = +'pg_stat_statements'` in `postgresql.conf`): + +```sql +SELECT calls, mean_exec_time, query + FROM pg_stat_statements + WHERE query ILIKE '%knowledge_nodes%' + ORDER BY mean_exec_time DESC + LIMIT 20; +``` + +Look for hybrid-search queries that have drifted above 100ms p50. The +usual culprit is a missing or half-built HNSW index. + +### 8.4 Index health + +```sql +SELECT indexname, pg_size_pretty(pg_relation_size(indexrelid)) AS size, + idx_scan, idx_tup_read + FROM pg_indexes + JOIN pg_stat_user_indexes USING (indexrelid) + WHERE schemaname = 'public' AND relname = 'knowledge_nodes'; +``` + +A HNSW index with `idx_scan = 0` after several hours of traffic usually +means the planner is preferring sequential scan -- either the table is +too small to bother with the index (fine) or the index is corrupt and +needs rebuilding (`REINDEX INDEX idx_knowledge_nodes_embedding_hnsw;`). + +### 8.5 Spotting half-built HNSW + +After a failed migration or a crashed `reembed`: + +```sql +SELECT indexname, indisvalid, indisready + FROM pg_indexes + JOIN pg_index ON indexrelid = (schemaname || '.' || indexname)::regclass + WHERE tablename = 'knowledge_nodes'; +``` + +Any row with `indisvalid = false` is broken. Drop and recreate: + +```sql +DROP INDEX IF EXISTS idx_knowledge_nodes_embedding_hnsw; +CREATE INDEX idx_knowledge_nodes_embedding_hnsw + ON knowledge_nodes USING hnsw (embedding vector_cosine_ops); +``` + +--- + +## 9. Troubleshooting + +| Symptom | Likely cause | Fix | +|---------|--------------|-----| +| `ERROR: extension "vector" is not available` on start | pgvector not installed for this Postgres major version | Install the distro package matching `pg_config --version`, then `CREATE EXTENSION vector;` as superuser | +| `pool timed out while waiting for an open connection` in Vestige logs | Pool too small or stuck queries holding connections | Raise `max_connections` in `vestige.toml`; investigate `pg_stat_activity` for queries above 5s | +| `vector dimensions do not match` on insert | `embedding_model` was stamped at one dimension and a different embedder is now running | Re-run `vestige migrate reembed --model=` or fix the embedder configuration | +| Hybrid search returns the same row twice | Stale `.sqlx/` query cache from before D5 landed | Run `cargo sqlx prepare` in `crates/vestige-core/`, rebuild the binary | +| `text search configuration "english" does not exist` | Postgres locale build does not include the english dictionary (rare on Alpine) | Install the language-pack or override the FTS language in `vestige.toml` (see `[storage.postgres.fts]` once Phase 2 D5 lands) | +| `relation "_sqlx_migrations" exists, but migration X is in "applied" with no checksum` | Previous run died between `BEGIN` and `COMMIT` | Stop Vestige, restore from backup, restart | +| HNSW index very large compared to data | `m` and `ef_construction` defaults too high for the corpus | Acceptable for now; tuning lands as part of Phase 4 | +| `permission denied for schema public` on a new install | `vestige` role does not own `public` | Re-run the grants block in section 2.2 as `postgres` | + +If a problem is not in this table, capture: PostgreSQL log +(`/var/log/postgres/`, journalctl `-u postgresql`), Vestige log +(`RUST_LOG=debug,sqlx=info` for a fresh run), the migration state +(`SELECT * FROM _sqlx_migrations ORDER BY version;`), and file a bug. + +--- + +## 10. Rollback caveats + +Every migration in `crates/vestige-core/migrations/postgres/` has a +matching `*.down.sql`. `sqlx migrate revert` walks them in reverse order. + +This is not the same as risk-free. The `0002_hnsw.down.sql` drops the +HNSW index (rebuildable, expensive). The `0001_init.down.sql` drops +every table -- including `knowledge_nodes`, including data. Down migrations +exist for development, not for casual production use. + +Before applying any new migration: + +1. Take a backup (section 5.2). +2. Run the migration on a restored copy first if you can afford the time. +3. Read the new migration's `*.up.sql` and `*.down.sql` to understand + what changes. + +To revert one migration manually: + +```sh +sqlx migrate revert \ + --database-url "postgresql://vestige:...@127.0.0.1:5432/vestige" \ + --source crates/vestige-core/migrations/postgres +``` + +Note that Vestige's binary does not run `sqlx migrate revert` +automatically. Reverts are always an explicit operator decision. + +If a revert fails partway through, treat the database as inconsistent: +restore from the backup taken in step 1. +``` + +--- + +## Cross-references + +- `docs/adr/0001-pluggable-storage-and-network-access.md` -- ADR that + established the pluggable backend. +- `docs/adr/0002-phase-2-execution.md` -- ADR settling Phase 2 execution + decisions; section "Architecture Overview" lists every table the + runbook references. +- `docs/plans/0002-phase-2-postgres-backend.md` -- master plan; D16 + (deliverables list) and the Open Implementation Questions section + (especially Q4 HNSW rebuild and Q5 pool sizing) inform the runbook's + recommendations. +- `docs/plans/local-dev-postgres-setup.md` -- developer-facing recipe + for a one-machine Arch / CachyOS dev cluster. The runbook links to it + as the "for development, see" pointer. +- `docs/CONFIGURATION.md` -- existing config doc; section 4 of the + runbook ("Connection pool tuning") cross-references it for the + authoritative `vestige.toml` schema. + +--- + +## Verification + +A reviewer is given: + +- A fresh Linux VM (Debian 12 or Arch current; both must work) with + network access and no Postgres installed. +- A built `vestige-mcp` binary for that platform. +- The runbook (`docs/runbook/postgres.md`). + +The reviewer follows the runbook top to bottom and reaches a state in +which Vestige answers MCP requests against the Postgres backend. +Checkpoints, in order: + +1. After section 1 (Prerequisites): `pg_config --version` returns 16 or + newer; `pkg-config --modversion libpq` resolves; the `pgvector` + distro package is installed. +2. After section 2.1 (Extensions): two rows in + `SELECT extname FROM pg_extension WHERE extname IN ('vector', 'pgcrypto');`. +3. After section 2.2 (Role + DB): `psql -U vestige -h 127.0.0.1 -d vestige -c '\conninfo'` + succeeds. +4. After section 2.3 (Config): `vestige.toml` parses (test by + `vestige config print` once that subcommand lands, otherwise + `vestige-mcp --check-config`). +5. After section 3 (First connect): the eight expected tables are + present; `embedding_model` has exactly one row; the HNSW index + exists; `vestige-mcp` log shows "Postgres backend ready". +6. After section 5.2 (Backup): the dump file exists and `pg_restore -l` + on it lists the expected tables. +7. After section 5.4 (Restore drill): the drill database holds the same + row count as the source. + +If any checkpoint fails, the runbook section that produced the failure +is the one that needs revision. Capture the exact command, exit code, +and log line; revise the runbook in a follow-up PR. + +A second reviewer reads the runbook without executing it and checks for: + +- ASCII only; no em dashes, no curly quotes, no Unicode arrows, no + ellipses, no bullets (`*`/`-` ASCII only). +- Every section number from 1 to 10 present and in order. +- Every cross-reference resolves to an existing file or to a Phase + number explicitly marked as "future". +- No code block longer than 30 lines; if longer, it should be split or + referenced from another file. + +--- + +## Acceptance criteria + +- [ ] `docs/runbook/` directory exists. +- [ ] `docs/runbook/postgres.md` exists and matches the inlined body + above byte-for-byte after stripping the outer code fence used in + this sub-plan to embed it. +- [ ] All ten sections from the "Runbook structure" outline are present + under their stated headings. +- [ ] No file other than `docs/runbook/postgres.md` is created or + modified by executing this sub-plan. +- [ ] ASCII only: no em dashes, no curly quotes, no Unicode arrows, + no ellipses, no Unicode bullets (`grep -P '[^\x00-\x7F]' + docs/runbook/postgres.md` returns no matches). +- [ ] Every cross-reference in the runbook points at a file that exists + in the repository at the time of merge, OR is explicitly framed + as "future Phase N" with a pointer to the relevant plan document. +- [ ] Every command block is copy-pastable: no `` syntax + that does not also have an inline note describing what to + substitute. +- [ ] A second pair of eyes confirms the verification checkpoints in the + preceding section are reproducible. +- [ ] The runbook is no longer than the inlined body in this sub-plan; + operators reach the end without losing patience. From 21f0b29baeab80e7513075c9e274e069419300d3 Mon Sep 17 00:00:00 2001 From: Jan De Landtsheer Date: Wed, 27 May 2026 15:08:35 +0200 Subject: [PATCH 6/6] docs: rewrite local-dev-postgres-setup for container approach; bump pg16 -> pg18 Land the Postgres dev cluster recipe Jan provisioned on delandtj-home (rootless podman + pgvector/pgvector:pg18, PG 18.4, pgvector 0.8.2) and align all live ADR 0002 / Phase 2 sub-plan references from pg16 to pg18. - docs/plans/local-dev-postgres-setup.md -- rewritten end-to-end: podman container vestige-pg with --restart=always, named volume vestige-pgdata, PGDATA=/var/lib/postgresql/data/pgdata, port mapping 127.0.0.1:5432:5432, two-password split (superuser + app role), pgvector preinstalled, CREATE EXTENSION vector handled at setup, day-to-day commands, password rotation, dev-grade backup/restore, teardown, boot-persistence notes for rootless podman. Old native Arch install recipe moved to Out-of-scope (covered by image now). - docs/adr/0002-phase-2-execution.md -- the open-thread mention of pgvector/pgvector:pg16 in the Follow-ups section now reads pg18. - docs/plans/0002c-migrations.md -- container example in the local dev section updated to pg18. - docs/plans/0002d-store-impl-bodies.md -- testcontainers GenericImage tag pg16 -> pg18; prose reference updated. - docs/plans/0002h-testing-and-benches.md -- harness pg18 across testcontainers Postgres builder, image-caching prose, CI workflow example. The archival master plan (docs/plans/0002-phase-2-postgres-backend.md) keeps its original pg16 references intentionally; the supersession notice already points readers to the live sub-plans. --- docs/adr/0002-phase-2-execution.md | 2 +- docs/plans/0002c-migrations.md | 2 +- docs/plans/0002d-store-impl-bodies.md | 4 +- docs/plans/0002h-testing-and-benches.md | 14 +- docs/plans/local-dev-postgres-setup.md | 248 ++++++++++++++++++------ 5 files changed, 198 insertions(+), 72 deletions(-) diff --git a/docs/adr/0002-phase-2-execution.md b/docs/adr/0002-phase-2-execution.md index 6b6949f..5d590b4 100644 --- a/docs/adr/0002-phase-2-execution.md +++ b/docs/adr/0002-phase-2-execution.md @@ -504,7 +504,7 @@ own migrations. - Validate local Postgres dev cluster before PR C work begins. Recipe at `docs/plans/local-dev-postgres-setup.md` is correct but needs to be applied on this machine (delandtj-home): cluster is not initdb'd, pgvector is not - installed. Containerized `pgvector/pgvector:pg16` is a viable alternative + installed. Containerized `pgvector/pgvector:pg18` is a viable alternative if pgvector packaging is friction. See open discussion thread. ### Phase 4 sketch: `sharing_rules` and the precedence chain diff --git a/docs/plans/0002c-migrations.md b/docs/plans/0002c-migrations.md index ef8e35c..78b6ac6 100644 --- a/docs/plans/0002c-migrations.md +++ b/docs/plans/0002c-migrations.md @@ -843,7 +843,7 @@ podman run --rm -d --name vestige-pg \ -e POSTGRES_USER=vestige \ -e POSTGRES_DB=vestige \ -p 5432:5432 \ - docker.io/pgvector/pgvector:pg16 + docker.io/pgvector/pgvector:pg18 export DATABASE_URL="postgresql://vestige:devpw@127.0.0.1:5432/vestige" ``` diff --git a/docs/plans/0002d-store-impl-bodies.md b/docs/plans/0002d-store-impl-bodies.md index ad1d9b7..adfd8aa 100644 --- a/docs/plans/0002d-store-impl-bodies.md +++ b/docs/plans/0002d-store-impl-bodies.md @@ -1612,7 +1612,7 @@ use vestige_core::storage::postgres::PgMemoryStore; #[tokio::test] async fn round_trip_crud_search_scheduling_edges() { let docker = clients::Cli::default(); - let image = GenericImage::new("pgvector/pgvector", "pg16") + let image = GenericImage::new("pgvector/pgvector", "pg18") .with_env_var("POSTGRES_PASSWORD", "test") .with_env_var("POSTGRES_DB", "vestige_test") .with_exposed_port(5432); @@ -1759,7 +1759,7 @@ This sub-plan is complete when ALL of the following hold: and the `Visibility` enum is exported alongside it. The SQLite backend reads and writes the same four fields. 8. The `tests/postgres_round_trip.rs` integration test passes against - a `pgvector/pgvector:pg16` container (insert / get / update / delete + a `pgvector/pgvector:pg18` container (insert / get / update / delete / fts_search / vector_search / get_scheduling / update_scheduling / add_edge / get_edges / remove_edge / get_neighbors / cascade delete). diff --git a/docs/plans/0002h-testing-and-benches.md b/docs/plans/0002h-testing-and-benches.md index d6bcebc..3fc2e1e 100644 --- a/docs/plans/0002h-testing-and-benches.md +++ b/docs/plans/0002h-testing-and-benches.md @@ -166,12 +166,12 @@ use vestige_core::storage::postgres::PgMemoryStore; pub async fn fresh_pg_store( embedder: Arc, ) -> Result<(PgMemoryStore, ContainerAsync)> { - // pgvector/pgvector:pg16 is the official pgvector image built on the - // postgres:16 base. testcontainers-modules::postgres::Postgres targets + // pgvector/pgvector:pg18 is the official pgvector image built on the + // postgres:18 base. testcontainers-modules::postgres::Postgres targets // the upstream postgres image by default; we override name + tag. let container = Postgres::default() .with_name("pgvector/pgvector") - .with_tag("pg16") + .with_tag("pg18") .start() .await?; @@ -867,7 +867,7 @@ Requirements: the `docker_available()` check in `common/mod.rs`. The test output includes a `docker unavailable; skip` line per test so the developer knows the tests were not silently dropped. -- The pgvector image (`pgvector/pgvector:pg16`) is pulled on first run; +- The pgvector image (`pgvector/pgvector:pg18`) is pulled on first run; ~200 MB. A pre-pulled image keeps the per-run overhead at the cold-start container boot (~2-5 seconds). @@ -920,7 +920,7 @@ async fn build_bench(rows: usize) -> Bench { let embedder = TestEmbedder::new_768(); let container = Postgres::default() .with_name("pgvector/pgvector") - .with_tag("pg16") + .with_tag("pg18") .start() .await .unwrap(); @@ -1092,7 +1092,7 @@ Notes: - The Postgres feature tests should run in a separate CI matrix entry to isolate failures and skip them entirely on platforms (Windows runners if any) where the pgvector image is not available. -- Cache the `pgvector/pgvector:pg16` image between runs. The +- Cache the `pgvector/pgvector:pg18` image between runs. The `docker/setup-buildx-action` cache or a simple `docker pull` step before the test step keeps cold-start under the existing CI time budget. - Skip CI: contributors without Docker can still merge changes that do @@ -1113,7 +1113,7 @@ jobs: # no `postgres` service block needed; testcontainers manages its own steps: - uses: actions/checkout@v4 - - run: docker pull pgvector/pgvector:pg16 + - run: docker pull pgvector/pgvector:pg18 - uses: dtolnay/rust-toolchain@stable - run: cargo test -p vestige-core --features postgres-backend --test '*' ``` diff --git a/docs/plans/local-dev-postgres-setup.md b/docs/plans/local-dev-postgres-setup.md index 6250a55..f863d48 100644 --- a/docs/plans/local-dev-postgres-setup.md +++ b/docs/plans/local-dev-postgres-setup.md @@ -1,27 +1,55 @@ -# Local Dev Postgres Setup (Arch / CachyOS) +# Local Dev Postgres Setup (container, hybrid approach) -**Status**: Applied on this machine on 2026-04-21 -**Related**: docs/plans/0002-phase-2-postgres-backend.md, docs/adr/0001-pluggable-storage-and-network-access.md +**Status**: Applied on this machine on 2026-05-27 (rootless podman, Postgres 18.4 + pgvector 0.8.2). +**Related**: docs/plans/0002-phase-2-postgres-backend.md, docs/adr/0002-phase-2-execution.md, docs/adr/0001-pluggable-storage-and-network-access.md -Purpose: capture the minimum, repeatable steps to stand up a Postgres 18 instance on a local Arch/CachyOS box for Phase 2 (`PgMemoryStore`) development, `sqlx prepare`, and manual migration testing. This is a single-operator dev recipe, not a production runbook. +Purpose: capture the minimum, repeatable steps to stand up a long-lived +Postgres 18 + pgvector instance on a local Linux dev box for Phase 2 +(`PgMemoryStore`) development, `sqlx prepare`, and manual migration +testing. This is a single-operator dev recipe, not a production runbook. + +ADR 0002 picked the **hybrid container** approach over a native install: +the `pgvector/pgvector:pg18` image ships pgvector pre-installed, matches +the image testcontainers will use in the Phase 2 test harness, and avoids +the AUR/build-from-source friction of native pgvector packaging on Arch. --- ## Current state on this machine -- Package: `postgresql` 18.3-2 (pacman). Pulls `postgresql-libs`, `libxslt`. -- Service: `postgresql.service`, enabled + active. -- Listens on: `127.0.0.1:5432` and `[::1]:5432` only (default `listen_addresses = 'localhost'`). -- Data dir: `/var/lib/postgres/data`, owner `postgres:postgres`. -- Auth (`pg_hba.conf`, Arch defaults): `peer` for local socket, `scram-sha-256` for host 127.0.0.1/::1. +- Runtime: rootless `podman` 5.8.2 (Arch). `docker` 29.5.1 also installed but unused. +- Image: `docker.io/pgvector/pgvector:pg18` (PostgreSQL 18.4, pgvector 0.8.2). +- Container: `vestige-pg`, `--restart=always`, port `127.0.0.1:5432:5432`. +- Volume: named podman volume `vestige-pgdata`, mounted at + `/var/lib/postgresql/data` inside the container; `PGDATA` points at + `/var/lib/postgresql/data/pgdata` so the volume mount is non-empty at + init time (Postgres refuses to initdb into a non-empty directory). +- Listens on: `127.0.0.1:5432` only (port mapping is bound to loopback). +- Auth: `scram-sha-256` (image default for both local socket and host). ### Database + role -- Database: `vestige`, UTF8, owner `vestige`. -- Role: `vestige` with `LOGIN CREATEDB` (no superuser, no replication, no cross-db). -- Schema `public` re-owned to `vestige`, plus default privileges so any future tables / sequences / functions in `public` are fully owned and granted to `vestige`. +- Database: `vestige`, UTF8, owner `vestige`, `LC_COLLATE=C.UTF-8`, `LC_CTYPE=C.UTF-8`. +- Role: `vestige` with `LOGIN CREATEDB` (no superuser, no replication). +- Schema `public` re-owned to `vestige` with full default privileges on + future tables / sequences / functions. +- Extension: `vector` (pgvector 0.8.2) installed in the `vestige` + database by the superuser at setup time. -Net effect: the `vestige` role can create, alter, drop, and grant freely inside the `vestige` database -- enough for `sqlx::migrate!`, ad-hoc schema work, and the full Phase 2 `MemoryStore` surface. It cannot create extensions (see Phase 2 followups below) and cannot touch other databases. +Net effect: the `vestige` role can create, alter, drop, and grant freely +inside the `vestige` database -- enough for `sqlx::migrate!`, ad-hoc +schema work, and the full Phase 2 `MemoryStore` surface. It cannot create +extensions; the superuser handled `CREATE EXTENSION vector` already. + +### Passwords + +Two passwords live in the dev user's home, mode 600: + +- `~/.vestige_pg_superpw` -- the `postgres` superuser password inside the + container. Used for one-shot admin tasks (creating roles, installing + extensions, password rotation). Day-to-day app traffic does NOT use it. +- `~/.vestige_pg_pw` -- the `vestige` role password. This is the one the + Phase 2 backend, `sqlx prepare`, and ad-hoc `psql` invocations use. ### Connection @@ -29,13 +57,8 @@ Net effect: the `vestige` role can create, alter, drop, and grant freely inside postgresql://vestige:@127.0.0.1:5432/vestige ``` -Password lives at `~/.vestige_pg_pw`, mode 600, owned by the dev user (no sudo needed to read it). Read with: - -```sh -cat ~/.vestige_pg_pw -``` - -Recommended dev shell export (keep this OUT of the repo; use `.env` + gitignore or a shell rc): +Recommended dev shell export (keep this OUT of the repo; use `.env` + +gitignore or a shell rc): ```sh export DATABASE_URL="postgresql://vestige:$(cat ~/.vestige_pg_pw)@127.0.0.1:5432/vestige" @@ -45,109 +68,212 @@ export DATABASE_URL="postgresql://vestige:$(cat ~/.vestige_pg_pw)@127.0.0.1:5432 ## Reproduce from scratch -On a fresh Arch / CachyOS box with passwordless sudo: +On a fresh Linux box with `podman` installed and `python3` available: ```sh -# 1. Install -sudo pacman -S --noconfirm postgresql +# 1. Pull the image +podman pull docker.io/pgvector/pgvector:pg18 -# 2. Initialize the cluster (UTF8, scram-sha-256 for host, peer for local) -sudo -iu postgres initdb \ - --locale=C.UTF-8 --encoding=UTF8 \ - -D /var/lib/postgres/data \ - --auth-host=scram-sha-256 --auth-local=peer +# 2. Create a persistent named volume +podman volume create vestige-pgdata -# 3. Start + enable -sudo systemctl enable --now postgresql +# 3. Generate the superuser password and stash it (mode 600) +SUPER_PW=$(python3 -c 'import secrets,string; a=string.ascii_letters+string.digits; print("".join(secrets.choice(a) for _ in range(32)))') +umask 077 +printf '%s' "$SUPER_PW" > ~/.vestige_pg_superpw +chmod 600 ~/.vestige_pg_superpw -# 4. Generate a password and stash it in the dev user's home (mode 600) +# 4. Start the container +podman run -d \ + --name vestige-pg \ + --restart=always \ + -p 127.0.0.1:5432:5432 \ + -e POSTGRES_PASSWORD="$SUPER_PW" \ + -e PGDATA=/var/lib/postgresql/data/pgdata \ + -v vestige-pgdata:/var/lib/postgresql/data \ + docker.io/pgvector/pgvector:pg18 + +unset SUPER_PW + +# 5. Wait for ready +until podman exec vestige-pg pg_isready -U postgres -h 127.0.0.1 >/dev/null 2>&1; do + sleep 1 +done + +# 6. Generate the vestige role password and stash it (mode 600) VESTIGE_PW=$(python3 -c 'import secrets,string; a=string.ascii_letters+string.digits; print("".join(secrets.choice(a) for _ in range(32)))') umask 077 printf '%s' "$VESTIGE_PW" > ~/.vestige_pg_pw chmod 600 ~/.vestige_pg_pw -# 5. Create role + database + grants -sudo -u postgres psql -v ON_ERROR_STOP=1 < '[3,2,1]'::vector AS l2_distance;" ``` --- -## Phase 2 followups (before PgMemoryStore works) +## Boot persistence (rootless podman) -The cluster above is bare Postgres. Phase 2 needs `pgvector`: +`--restart=always` keeps the container alive across podman daemon +restarts, but rootless podman containers do NOT auto-start on system +boot unless the dev user has lingering enabled: ```sh -# Install the extension package -sudo pacman -S --noconfirm pgvector - -# Enable it in the vestige database (must run as postgres; vestige is not superuser) -sudo -u postgres psql -d vestige -c 'CREATE EXTENSION IF NOT EXISTS vector;' +sudo loginctl enable-linger "$USER" ``` -Verify: +After that, the `podman-restart.service` user unit handles restart of +`--restart=always` containers when the user session starts at boot: ```sh -PGPASSWORD="$(cat ~/.vestige_pg_pw)" psql -h 127.0.0.1 -U vestige -d vestige \ - -c "SELECT extname, extversion FROM pg_extension WHERE extname = 'vector';" +systemctl --user enable --now podman-restart.service ``` -Notes: +Skip both if you prefer to start the cluster manually each session with +`podman start vestige-pg`. -- `pgvector` must be available on the server before `sqlx::migrate!` runs, or the Phase 2 migration that declares typed `Vector` columns will fail. -- Testcontainer-based Phase 2 integration tests use `pgvector/pgvector:pg16` and are independent of this local cluster. This local cluster is for `sqlx prepare`, `cargo run -- migrate --to postgres`, and manual poking. -- `sqlx prepare` needs `DATABASE_URL` pointed at this cluster with `vestige` migrations already applied. Run from `crates/vestige-core/`. +--- + +## Day-to-day operation + +```sh +# Status +podman ps --filter name=vestige-pg + +# Logs (follow) +podman logs -f vestige-pg + +# psql as the app role +PGPASSWORD="$(cat ~/.vestige_pg_pw)" psql -h 127.0.0.1 -U vestige -d vestige + +# psql as the superuser (for grants, extensions, role admin) +podman exec -it vestige-pg psql -U postgres + +# Stop / start +podman stop vestige-pg +podman start vestige-pg + +# Restart in place +podman restart vestige-pg +``` --- ## Password rotation ```sh +# Rotate the vestige role password NEW_PW=$(python3 -c 'import secrets,string; a=string.ascii_letters+string.digits; print("".join(secrets.choice(a) for _ in range(32)))') umask 077 printf '%s' "$NEW_PW" > ~/.vestige_pg_pw chmod 600 ~/.vestige_pg_pw -sudo -u postgres psql -v ON_ERROR_STOP=1 \ +podman exec -i vestige-pg psql -U postgres -v ON_ERROR_STOP=1 \ -c "ALTER ROLE vestige WITH PASSWORD '${NEW_PW}';" unset NEW_PW + +# Rotate the superuser password (less common) +NEW_SUPER=$(python3 -c 'import secrets,string; a=string.ascii_letters+string.digits; print("".join(secrets.choice(a) for _ in range(32)))') +umask 077 +printf '%s' "$NEW_SUPER" > ~/.vestige_pg_superpw +chmod 600 ~/.vestige_pg_superpw +podman exec -i vestige-pg psql -U postgres -v ON_ERROR_STOP=1 \ + -c "ALTER ROLE postgres WITH PASSWORD '${NEW_SUPER}';" +unset NEW_SUPER ``` Then re-export `DATABASE_URL` in any live shells. --- +## Backup and restore (dev-grade) + +`pg_dump` writes a plain-text SQL dump to host disk. For dev data this is +enough; production runbook lives in `0002i-runbook.md`. + +```sh +# Dump +PGPASSWORD="$(cat ~/.vestige_pg_pw)" pg_dump -h 127.0.0.1 -U vestige -d vestige \ + --format=plain --no-owner > vestige-$(date +%Y%m%d-%H%M%S).sql + +# Restore (drops + recreates) +podman exec -i vestige-pg psql -U postgres -v ON_ERROR_STOP=1 \ + -c 'DROP DATABASE IF EXISTS vestige;' \ + -c 'CREATE DATABASE vestige OWNER vestige ENCODING UTF8 TEMPLATE template0;' +PGPASSWORD="$(cat ~/.vestige_pg_pw)" psql -h 127.0.0.1 -U vestige -d vestige < vestige-DUMP.sql +``` + +The named volume `vestige-pgdata` persists outside the container; the +container can be `podman rm`'d and recreated without losing data, as +long as the volume stays in place. + +--- + ## Teardown Destroys the cluster and all data in it: ```sh -sudo systemctl disable --now postgresql -sudo pacman -Rns postgresql postgresql-libs -sudo rm -rf /var/lib/postgres -rm -f ~/.vestige_pg_pw +podman stop vestige-pg +podman rm vestige-pg +podman volume rm vestige-pgdata +podman rmi docker.io/pgvector/pgvector:pg18 +rm -f ~/.vestige_pg_pw ~/.vestige_pg_superpw ``` +`enable-linger` and the user systemd unit can be undone with +`sudo loginctl disable-linger "$USER"` and +`systemctl --user disable podman-restart.service` if you turned them on. + +--- + +## Notes for Phase 2 + +- `pgvector` is preinstalled in the image; the `CREATE EXTENSION vector` + in step 7 above makes it available inside the `vestige` DB. The + extension must be loaded BEFORE `sqlx::migrate!` runs the Phase 2 + migration that declares typed `Vector` columns, otherwise the + migration fails. +- Testcontainer-based Phase 2 integration tests use the same + `pgvector/pgvector:pg18` image and spin up fresh containers per run; + they are independent of this long-lived cluster. This cluster exists + for `sqlx prepare`, `cargo run -- migrate --to postgres`, and manual + poking. +- `sqlx prepare` needs `DATABASE_URL` pointed at this cluster with + `vestige` migrations already applied. Run from `crates/vestige-core/`. + --- ## Out of scope for this doc -- TLS, client-cert auth, non-localhost access. Phase 3 exposes the Vestige HTTP API over the network, not Postgres directly. -- Backups, PITR, WAL archiving. For dev data: `pg_dump -h 127.0.0.1 -U vestige vestige > vestige.sql`. -- Replication, PgBouncer, tuned `postgresql.conf`. Defaults are fine for Phase 2 development. -- Making this the canonical Vestige backend. By default Vestige still uses SQLite; this cluster exists so the `postgres-backend` feature can be built and tested locally. +- TLS, client-cert auth, non-localhost access. Phase 3 exposes the + Vestige HTTP API over the network, not Postgres directly. +- PITR, WAL archiving, replication, PgBouncer, tuned `postgresql.conf`. + Defaults are fine for Phase 2 development. +- Native (non-container) Postgres install. The prior version of this + doc covered native Arch packaging; superseded by ADR 0002's hybrid + decision. +- Making this the canonical Vestige backend. By default Vestige still + uses SQLite; this cluster exists so the `postgres-backend` feature + can be built and tested locally.