Skip to content

IMPORTANT

AI Context & Knowledge Heritage

  • Subsystem: Architecture & Documentation / Core Docs / Knowledge_Memory
  • Architecture: @docs ARCHITECTURE:Documentation
  • Failure Path: Information drift, legacy terminology, or documentation mismatch.
  • Observability: Traceability via execution/parity_guard.py

🧠 Knowledge & Memory: Hybrid Retrieval Architecture ​

Intelligence Level: High (ECC Optimized) Last Hardened: 2026-08-18 (GraphRAG & Vector Feature-Flag Rationale)

@docs ARCHITECTURE:Retrieval

Tadpole OS combines durable SQLite records, structural graph lookup, BM25 lexical search, and optional vector search. The default build omits the optional LanceDB vector-memory dependencies.


πŸ—οΈ Memory Strategy: Deterministic vs. Graph vs. Semantic ​

Full cognitive autonomy requires three complementary retrieval primitives:

LayerTechnologyData TypePurpose & Scope
Durable RecordsSQLite (sqlx)Logs, Budgets, Registries, OKF MetadataPersistent application state; audit guarantees depend on the specific ledger and verification path
Structural GraphGraph Intelligence (petgraph, SQLite GraphStore)AST Symbol Callers/Callees, Server-Side LPA Communities (community), TrustGraph, OKF NodesDependency traversal, deterministic Mulberry32 Label Propagation modularity clustering, and code navigation; results do not guarantee model correctness
Lexical EngineBM25 (bm25)Exact tokens, error slugs, function identifiersInstant in-memory search with mtime-aware caching to eliminate redundant disk I/O
Dense Semantic VectorLanceDB (lancedb + Apache Arrow)Embeddings (768-dim), episodic mission monologuesConceptual fuzzy discovery, cross-mission semantic intuition

βš–οΈ Architectural Decision: Why vector-memory is a Feature Flag ​

In server-rs/Cargo.toml, vector database integration is encapsulated under the optional vector-memory build flag:

toml
[features]
default = []
vector-memory = ["dep:lancedb", "dep:arrow-schema", "dep:arrow-array"]

Why Default Builds Omit vector-memory (Default-Off Rationale) ​

  1. Fewer Optional Native Dependencies:
    • The default build omits LanceDB and Arrow dependencies, avoiding their additional build requirements. Supported targets still depend on the repository's Rust toolchain and platform configuration.
  2. Offline Operation Option:
    • Graph + BM25 codebase and SOP search does not require cloud embedding API keys or a local GPU. A disconnected deployment still requires local models and dependencies plus host/network egress controls. The global Privacy Shield monitor attempts periodic reachability probes and is not itself an air-gap control.
  3. Decoupled Upstream Versioning:
    • LanceDB bundles deep Apache Arrow and DataFusion execution kernels. Isolating LanceDB behind a feature flag ensures core server routing and governance evolve without upstream Arrow version locksteps.

Why You Enable vector-memory (When to Turn It On) ​

  1. Episodic Monologue & Dialogue Search:
    • As swarms execute hundreds of multi-turn missions, agents generate extensive conversational context. Storing dense embeddings in LanceDB enables fuzzy recall of past debugging experiences and solution patterns.
  2. Latent Concept & Template Discovery:
    • Natural language prompts (e.g., "Set up wholesale escrow fulfillment") can retrieve matching Industry Templates (Wholesale & Distribution) even when zero exact keyword overlap exists with template identifiers.
  3. Multimodal Future-Proofing:
    • LanceDB's Apache Arrow format natively supports multimodal vector representations (audio embeddings, UI screenshot vectors) alongside text.

πŸ•ΈοΈ The GraphRAG Synergy: Graphs vs. Vectors ​

Graphs and Vector DBs are not mutually exclusive; they solve orthogonal retrieval problems:

mermaid
flowchart TD
    Query["User / Agent Prompt"] --> Router{"Hybrid Retrieval Router"}

    Router -->|Exact Tokens| BM25["BM25 Index<br/>(Exact Symbols & Error Codes)"]
    Router -->|Semantic Concepts| LanceDB["LanceDB Vectors<br/>(Episodic Memories & Monologues)"]
    Router -->|Structural Lookups| Graph["Symbol / Trust Graph<br/>(AST Dependencies & Governance)"]

    BM25 --> Synthesis["Context Synthesis Layer<br/>(Merged RAG Context)"]
    LanceDB --> Synthesis
    Graph --> Synthesis

    Synthesis --> LLM["Agent Execution Engine"]
  • Graphs tell the agent where components live, who has permission, and what downstream code breaks.
  • LanceDB tells the agent what past mission experiences or unstructured documents feel conceptually related.
  • BM25 tells the agent exact token matches for IDs, environment variables, and error slugs.

πŸ›°οΈ The Data Ingestion Pipeline (4-Phase Model) ​

The engine converts raw documents into "Intelligence Assets" through a disciplined background pipeline:

Phase 1: Multi-Factor Scoring (MFS) ​

Tadpole OS uses a Multi-Factor Scoring (MFS) engine to rank context snippets based on three primary signals:

  1. Vector Similarity: Uses cosine distance (via LanceDB) for high-dimensional semantic mapping.
  2. Mission Affinity: Contextually boosts results that match the active Mission-ID, ensuring relevant domain knowledge is prioritized.
  3. Temporal Recency: Applies a decay factor to older memories, ensuring the agent uses the most up-to-date information while retaining long-term historical context.

The MFS engine combines these signals into a relevance score ($0.0 - 1.0$) before passing top-K snippets to the LLM. Recency and mission affinity influence ranking; neither guarantees that every result is current or relevant.

Phase 2: Automated Connectors (connectors.rs) ​

Configured ingestion sources are processed by background workers:

  • IngestionWorker: A Tokio worker that processes configured sources; available source types and scheduling depend on the configured connector path.
  • Incremental Sync: Uses MD5-checksums to avoid re-embedding unchanged files.
  • Connectors: Supports File-system watching with absolute path validation.

Phase 3: Deterministic SOP Workflows (workflows.rs) ​

Beyond fuzzy RAG, the engine can execute Structured SOPs:

  • Markdown-to-State: Parses .md files into executable steps.
  • Sequential Execution: Ensures compliance-heavy tasks follow a strict order of operations.

Phase 4: Layout-Aware Parsing & Dual-Write Atomicity (store.rs) ​

  • Transactional Dual-Write Atomicity: add_entry wraps SQLite metadata inserts in an explicit transaction (pool.begin()) and commits only after LanceDB vector storage succeeds. If vector storage fails, the SQLite transaction rolls back, eliminating orphaned "ghost" metadata entries.
  • Vector Predicate Sanitization: get_peers enforces strict input ID character validation (c.is_alphanumeric() || c == '-' || c == '_') before constructing LanceDB filter predicates, preventing injection attacks.
  • Bounded OKF Playbook Cache (okf_gate.rs): Enforces maximum cache capacity (MAX_CACHE_ENTRIES = 256) with automatic TTL eviction for playbook requirements, eliminating static map memory leaks during large-scale swarm runs.
  • Zero-Allocation Requirement Parser: Hot-loop allocation-free requirement extraction using precomputed static matchers (pattern_colon, pattern_space).

πŸ§ͺ Vector Memory Management ​

LanceDB + Apache Arrow ​

  • Columnar Data Layout: Uses Apache Arrow record batches for vector data. Actual search latency depends on the workload, index, and hardware.
  • Orphan Sweeping & Scope Cleanup: A background daemon purges mission-specific temporary vector "scopes" once tasks are complete to prevent disk bloat. In server-rs/src/agent/memory.rs, vector scope cleanup is encapsulated in cleanup_cluster_mission_scopes, flattening recursive directory walks into a resilient two-level traversal with error isolation.
  • Unified Duplicate Detection: In server-rs/src/agent/memory.rs, the check_memory_duplicate routine unifies vector similarity checks under a clean abstraction, falling back gracefully to exact content hashing when vector-memory is disabled, eliminating nested #[cfg] cascades.

Embedding Provider Data Path ​

Vector memory is optional in the default build. When embeddings are enabled, the knowledge store currently calls Gemini text-embedding-004, while connector ingestion resolves an embedding provider from the agent model configuration. Embedding text may therefore leave the engine for a configured provider. The current code does not use BGE-Small-EN-v1.5 via ONNX as its default text embedder; use Graph + BM25 for the default local search path or verify the selected embedding provider before processing sensitive content.

Swarm Context Compaction ​

To avoid token bloat and CPU load spikes during long-running agent missions, dialogue compaction is performed dynamically:

  • $O(N)$ Linear Compactor: Iteratively filters dialogue history in linear time, stripping large codeblocks from older messages while preserving the last 4 reasoning turns fully intact.
  • Resilient Fallback: Falls back to a regex-based parser if LLM summarization fails. The fallback preserves message structure where it can parse it; it does not guarantee that all semantic detail is retained.

Sovereign Intelligence Architecture.