Engineering/AI documentation
Memory Health
Memory health surfaces status and quality signals for memory or retrieval infrastructure.
Concepts: rag
Implementation Summary
Memory health surfaces status and quality signals for memory or retrieval infrastructure in the active project.
Frontend Surface
frontend/src/components/memory/MemoryView.tsxbackend/app/core/vector_health.py
State, API, And Backend Contracts
Stores
- None recorded.
API And Backend
backend/app/api/routes/memory.py
Embeddings Gateway Migration (Pi Replacement W8)
#### Pi-owned embedding profile (2026-08 migration)
- Pi Model Management owns one persisted, versioned, immutable
EmbeddingProfile. Startup loads or
creates version 1 immediately after database initialization and before any embedding or vector-health
probe. Version 1 captures the exact previously effective model/endpoint/cache identity once; later
changes to classical chat-provider settings cannot mutate runtime selection or public metadata.
- Every engine choice—including Istara/legacy loop—uses the profile model and exact endpoint through
PiModelManager. There is no direct legacy Ollama provisioning path. A missing endpoint, endpoint
model mismatch, or caller model override fails typed; model-name equality alone is insufficient.
- Cache keys and learned dimensions use the profile's
cache_namespace. Version 1 preserves the old
model-name namespace, so bootstrap does not invalidate compatible entries. Profile id/version are
emitted in gateway outcomes and safe profile metadata is exposed without URLs, keys, or tokens.
- Every project Lance index has an authoritative
.embedding-profile.jsonbinding. Existing stores
may be adopted only by version 1; reads and writes fail closed after any profile/model/cache/
dimension/dtype/normalization mismatch. New rows also carry profile metadata when their table schema
supports it. Vector health reports profile_mismatch and requires governed re-indexing rather than
suggesting that a dimension-only match is sufficient.
- Pi Replacement wave W8 (master plan
docs/build-stream/plans/2026-07-20-pi-full-replacement-master-plan.md§5.2.3/§5.5, spec CF-SPEC-8) gives the Pi engine its own embeddings plane. pi-ai cannot execute embeddings, so the newbackend/app/core/pi_runtime/embeddings_gateway.pycalls the embedding endpoint directly over HTTP (httpx) while staying under Pi identity management: the endpoint is resolved byPiModelManager.resolve_embed(model), which treats a concrete requested embedding model as an exact capability requirement, prefers the active local provider when it advertises that model, and allows a configured remoteopenai_compatendpoint with the requested model to win over unrelated local entries. When the model isdefault, the active local provider anchors the vector space; an anthropic-only or otherwise incompatible catalog fails closed withPiEndpointResolutionErrorrather than silently falling back to the legacy plane, and response cardinality is validated (PiEmbeddingError) so a malformed endpoint response cannot poison the vector store. - The dispatcher's
embedverb (backend/app/core/agentic/dispatcher.py) routes by resolved engine: Pi goes to the gateway — constructed lazily from the new publicPiExecutionService.model_manager()accessor and injectable via the dispatcher'sembeddings_gateway=constructor kwarg — while legacy keeps the unchangedollama.embed*plane inbackend/app/core/agentic/legacy.py. Gateway failures raise typed errors and never fall back to legacy; the W1 fail-closed stubpi_embed_gateway_unavailableis retired. W8 also fixed a latent W1 bug wherelegacy._embedpassedproject_id=toOllamaClient.embed_batch, which takes no such kwarg and would have raisedTypeErroron the real client. - Usage-ledger accounting keeps the dispatcher's one-row-per-dispatch contract (master plan §5.5):
AgenticDispatcher.embedrecords the singlepurpose="embed"accounting row and the gateway never writes rows itself, so a cache-miss embed is counted exactly once regardless of engine. - Embedding accounting preserves provider-reported token usage and cost when an OpenAI-compatible response supplies them, including endpoint-rate pricing when token usage is present but provider cost is omitted. Local or remote responses without usage are recorded as governed estimates (with estimated input tokens and cost when configured), never as exact zero consumption.
- The shared embedding wrappers in
backend/app/core/embeddings.pykeepembedding_cachein front and route cache misses throughagentic.embed. Model, cache namespace, and provisioning now come fromEmbeddingProfilefor every engine; engine selection cannot change vector identity.backend/app/core/validation.py_get_embeddingsremains project-scoped and degrades to[]on failure. - The new provisioner
backend/app/core/pi_runtime/model_manager_provisioning.py(master plan §5.2.3) exposesensure_endpoint_model(endpoint, model): remote endpoints are a no-op (False),kind=localOllama entries go throughOllamaClient.ensure_model(list + pull), LM Studio entries use the existingComputeNode.load_modelJIT-load contract, and a disabled, unavailable, or false LM Studio load fails typed rather than being ignored. Unknown local planes fail typed (provision_unsupported_local_endpoint:<id>). - Vector-space invariant:
assert_vector_space_invariant()is an async startup gate that reusesvector_health.check_embedding_dimensions()to probe the legacy and Pi dispatcher paths independently with the configured model. It compares the provider-produced dimensions and model identity, raisesVectorSpaceInvariantErroron mismatch or an unusable probe, andbackend/app/main.pyconverts that failure into a startup refusal. Gateway, dispatcher-wrapper, and cache writes reject empty, ragged, non-numeric, and non-finite vectors before they can poison stored vectors. - Engine rollback changes orchestration behavior, not embedding authority. Istara and Pi loop choices
share the active Pi-owned profile; changing the profile itself is not a rollback control and remains
blocked until a governed re-embed/re-index/activation workflow is available.
Evidence Provenance And Embedder Identity (2026-09-25)
- **Provenance invariant (measurement 5).** Every source chunk should carry the evidence unit it
was cut from, so a retrieved passage can be followed to its source span and coding state.
retrieval_provenance.provenance_coverage() counts source-table rows with an evidence_unit_id
(filtered counts, no table load); derived rows (agent notes, skill output) are excluded and older
derived rows in the source table are reported separately. GET /api/memory/{project_id}/stats
returns it as provenance (source_chunks, with_evidence_unit, coverage,
legacy_derived_rows, status = ok | degraded | empty | unavailable).
- **Evidence Provenance card.** The Health tab renders that object: the percentage, the count behind
it, an honest empty state, "Needs re-index" with the reprocess remedy when degraded, and a note for
legacy derived rows. Uploads, audio transcripts, document sync, knowledge sync and the file watcher
all index through index_document_source_chunks, so a fresh upload reads 100%.
- **Embedder identity (F11).** Embeddings fingerprint the model that actually serves (a hash of the
vectors a fixed probe produces). The cache is keyed by namespace#fingerprint, a store is bound to
the fingerprint it was written with, and vector health reports fingerprint_mismatch when a
same-dimension model swap would otherwise mix two vector spaces silently.
- **Layout.** The Memory tab row wraps at narrow widths (375 px) and marks the selected tab with
aria-pressed; dark-theme labels meet WCAG AA contrast.
- Verified by
tests/test_spine_evidence_provenance.py,tests/test_spine_embedding_identity.py
and simulation scenario 86-evidence-provenance-health (roles, keyboard, 375 px, light/dark, axe).
Architecture Notes
- The feature is mounted through
frontend/src/components/memory/MemoryView.tsxand the UI navigation path recorded in the inventory. - Health statistics are read through the project-scoped memory route after project visibility is verified.
MemoryViewremounts the Health tab on active-project changes so one project's memory statistics do not linger in another project view.- The frontmatter and manifest entries are the durable contract for agents updating this page after code changes.
- When the referenced component, store, route, agent, skill, or test behavior changes, regenerate and validate the feature documentation.
Agents, Skills, LLM, MCP, And Permissions
- RAG-related behavior depends on project context, documents, memory, or retrieval material referenced by the cited stores and routes.
Tests And Verification
tests/test_memory.pytests/pi_production/test_embedding_profile_authority.pycovers persistence, provider independence,
exact endpoint pinning, startup ordering, safe metadata, Lance binding, and profile-mismatch health.
tests/pi_production/test_w8_embeddings_gateway.pyverifies the W8 embeddings plane: MockTransport gateway HTTP behavior,resolve_embedordering and anthropic-only fail-closed resolution, independent legacy/Pi startup probes and dimension mismatch refusal, malformed-vector rejection before cache writes, wrapper cache-in-front dispatch throughagentic.embed, project-scoped validation embedding, provisioner behavior per endpoint kind, DB-projection reset, the merged settings model catalog,ProjectUpdate.agentic_enginevalidation, and static wiring checks.tests/pi_production/test_w1_dispatcher_authority.pyandtests/pi_production/test_w1_agentic_contract.pyassert embed dispatch now reaches the gateway on the Pi engine instead of the retiredpi_embed_gateway_unavailablestub.tests/test_validation_project_scope.pyasserts validation embedding project scope through theagentic.embedspy.tests/pi_migration/test_count_to_zero.pykeeps the legacy allowlist ratchet green at 0; only permanent infrastructure entries remain allowlisted.- Regenerate and validate the machine manifests and static site with
python scripts/feature_docs.py --seed-missing --generate-site --check.
Related Features
Related Concepts
Compass Evidence
- Spec/task: CF-SPEC-60 / CF-757; CF-SPEC-8 (Pi replacement W8 embeddings gateway + vector-space invariant)
- Inventory source:
docs/features/inventory.json
When To Update
- Update this page whenever the listed UI components, stores, routes, model behavior, permissions, or tests change.
- Regenerate the site and machine manifests with
python scripts/feature_docs.py --seed-missing --generate-site --check.