Skip to main content

Crate lunaris

Crate lunaris 

Source
Expand description

lunaris — umbrella crate. Re-exports lunaris_core types, exposes the open(url) URL-scheme dispatcher AND the higher-level Lunaris handle that drives the Phase 2 ingest hot path.

§Two construction paths

  • open() — returns Arc<dyn StoragePort> for callers that just want raw storage access (Plan 5 conformance harness, low-level tests).
  • Lunaris::open — returns a high-level handle wired with a default Embedder + HlcClock so callers can call lunaris.ingest(episode).await? without manually plumbing the Phase 2 pipeline. This is what Helios uses.

§Prelude

For day-to-day use, glob-import the curated common surface:

use lunaris::prelude::*;

See prelude for the exact list — it intentionally stays small (handle, scope, episode builder, retrieval DSL, the pluggable trait + Noop* pairs, and the umbrella error type).

Re-exports§

pub use consolidator_pipeline::ConsolidatorPipelineHandle;
pub use consolidator_pipeline::ENABLED_ENV_VAR as CONSOLIDATE_ENABLED_ENV_VAR;
pub use digest::recent_by_source;
pub use episode_builder::EpisodeBuilder;
pub use forget::ForgetConfirmation;
pub use forget::ForgetReceipt;
pub use forget::ForgetTarget;
pub use forget::IndexKind;
pub use forget::ScopeSpec;
pub use graph_pipeline::ENABLED_ENV_VAR as GRAPH_ENABLED_ENV_VAR;
pub use graph_pipeline::GraphPipelineHandle;
pub use handle::DegradationNotice;
pub use handle::EmbedderBackend;
pub use handle::IngestKind;
pub use handle::Lunaris;
pub use handle::SUPPRESS_DEGRADED_WARNING_ENV;
pub use handle::ScopedLunaris;
pub use handle::VerifyAgendaEntry;
pub use handle::degradation_notice;
pub use handle::lazy_default_embedder;
pub use handle::resolve_default_embedder;
pub use handle::resolve_default_reranker;
pub use handle::resolved_embedder_backend;
pub use recall_rerank::RECALL_RERANK_ENV_VAR;
pub use recall_rerank::RECALL_RERANK_TOP_IN_ENV_VAR;
pub use recall_rerank::RecallRerankConfig;
pub use structured_ingest::EntityInput;
pub use structured_ingest::FactInput;
pub use structured_ingest::RelationInput;
pub use structured_ingest::StructuredIngest;
pub use primitives::WorkingMemory;
pub use logging::init as init_logging;
pub use open::open;
pub use recipes::HeliosScratchpad;Deprecated
pub use recipes::AsOfScratchpad;
pub use recipes::CodingSessionMemory;
pub use verify_pipeline::ENABLED_ENV_VAR as VERIFY_ENABLED_ENV_VAR;
pub use verify_pipeline::VerifierPipelineHandle;

Modules§

activation
ADD task activation-ledger — the persistent per-memory activation ledger.
audit
Plan 13-01 — re-export shim for the canonical audit types that now live in lunaris-core::audit. This file preserves the old use crate::audit::* import surface so crates/lunaris/src/forget.rs and every downstream test keeps compiling without modification.
bitemporal
Bi-temporal validity stamp per blueprint §3.3.
circuit_breaker
RFC 0007 — per-provider circuit breaker for Fallback* combinators.
consolidator_pipeline
Plan 04-04: Runtime toggle for the ACT-R Consolidator worker.
digest
Recency-ordered, source-filtered episode recall for the SessionStart digest.
embedder
Embedder trait + a deterministic stub impl returning 768-dim vectors.
episode_builder
EpisodeBuilder — scope-less payload builder for lunaris_core::Episode.
error
Error taxonomy — one umbrella enum, one sub-enum per subsystem.
forget
Plan 04-05 — Lunaris::forget(target) -> ForgetReceipt.
graph_pipeline
Plan 03-03: Runtime toggle for the graph extraction pipeline.
handle
Lunaris — the high-level memory-engine handle (Phase 2 surface).
hlc
Hybrid Logical Clock — wall-time millis + monotonic counter + node id.
ingest
Lunaris::ingest — Phase 3 dispatcher.
json_repair
Repair JSON numbers that lost their integer-ness in transit.
keyspace
Storage-agnostic primitive KV key helpers — RFC 0001 §3.6 (Wave 2.5B).
logging
Plan 05-05 OPS-08 — structured logging defaults to JSON in production, pretty in dev (CONTEXT.md D-26 verbatim).
models
The GGUF model catalogue — one place that names the artifacts.
open
lunaris::open(url) — single entry point for the storage backend.
prelude
Glob-import the common surface: use lunaris::prelude::*;.
primitives
Phase 10/11/12 Option-A relocation — primitives that must live in the umbrella lunaris crate because Phase 12 CodingSessionMemory (also in lunaris) composes over them. Previously these lived in lunaris-recipes, but lunaris-recipes → lunaris dependency direction made the reverse import impossible. Moving them down (crate-wise) breaks the cycle without touching the public Phase 9 fluent API — the recipes crate re-exports these names so use lunaris_recipes::WorkingMemory; keeps compiling.
recall
Lunaris::recall — the public Phase 2 retrieve entry point.
recall_rerank
GA-1 — opt-in cross-encoder rerank stage on the production recall root.
recipes
Plan 05-04 — opinionated v0 recipes (helios-rfc §5.3 surface).
reconcile
Cross-episode memory-convergence reconciliation — the pure decision core.
retention
W4.6 / D6.4 — enforcing a scope’s RetentionPolicy.
scope
Scope newtype — the primary partition key for multi-agent / multi-tenant isolation in Lunaris v0.2 (RFC 0001).
scope_resolver
Scope derivation — shared between lunaris-mcp and lunaris-hook.
snapshot
Plan 08-00 — Lunaris::snapshot() monotonic LSN marker.
snippet
LLM-optimized snippet rendering for stored episode content.
storage
Storage abstraction — the trait, supporting types, and capability reporting.
store_discovery
Contextd store discovery — shared by lunaris-hook and lunaris-mcp.
structured_ingest
Phase 23 — agent-facing structured ingest.
verify_pipeline
Plan 04-04: Runtime toggle for the slow-path Verifier worker.

Structs§

ActRConsolidator
Production ACT-R consolidator — composes ActRScorer into a concrete impl Consolidator that the worker can iterate against.
AndRetriever
.and(A, B) — concurrent fan-out, concatenated output (with per-source tag preserved).
BiTemporal
Chunk
CircuitBreaker
Per-provider circuit breaker (RFC 0007 §3.2).
CircuitConfig
CloudApiExtractor
Cloud-API extractor — wraps lunaris_llm::CloudBackend per chunk and emits the D-21 sentinel on retry exhaust.
CloudApiExtractorOpts
Construction options for CloudApiExtractor.
CloudApiVerifier
Cloud-API verifier (Anthropic / OpenAI / Gemini). Phase 12b wraps CloudBackend (lunaris-llm) + LlmVerifier.
CloudApiVerifierOpts
Construction options for CloudApiVerifier.
Community
CypherQuery
DegradedFallbackRetriever
degraded_fallback(primary, fallback) operator.
DreamAgenda
Output of one build_dream_agenda call.
DreamCluster
One candidate distillation cluster.
DreamConfig
Tunables for one build_dream_agenda call.
Entity
EntityId
Deterministic 16-byte content-hash identifier per D-06.
Episode
Fact
FailingEmbedder
Always-failing Embedder for use in unit tests that must verify error propagation. Every embed_batch call returns LunarisError::Storage(StorageError::Backend(...)).
FlooredTopRetriever
TopRetriever with a reserved per-leg floor — see floored_top for the selection contract and the displacement regression it closes.
FuseRrfRetriever
Reciprocal Rank Fusion operator.
Graph
Graph-anchored retrieval operator.
GraphDecay
Recency-decay parameters for graph traversal (ADD task graph-decay-recency, contract v1). Maps to Moon’s GRAPH.QUERY ... --decay <λ> [--time-weight <w>] read-path clause: effective edge cost = |weight| + λ·w·age_seconds.
GraphResult
Dynamic header-keyed result table returned by StoragePort::graph_traverse.
Hit
Final hydrated retrieval hit returned to the caller.
Hlc
HlcClock
HotKey
One entry from a backend’s hot-key sketch (StoragePort::hot_keys).
Keyword
Keyword (BM25) retrieval operator.
KeywordHit
One keyword search hit.
LlmReflectSupervisor
LLM-backed reflect supervisor. Wraps any Arc<dyn LlmBackend> — same trait the extract + verify pipelines consume — so a single candle Gemma-3 4B handle can serve all three when the unified config wires it that way.
Lsn
Log sequence number returned by atomic_write.
MoonStorage
StoragePort backed by a single Moon RESP connection manager.
Navigate
Graph-expanded vector retrieval operator.
NavigateHit
A single hit returned by StoragePort::vector_navigate.
NavigateSpec
Parameters for graph-expanded vector retrieval (ADD task ft-navigate-recall, contract v1). Maps to Moon’s FT.NAVIGATE ... HOPS <n> [HOP_PENALTY <p>] [DECAY <λ>].
NoopConsolidator
Default consolidator when the pipeline is OFF (Plan 04-04) or when the caller has not installed a real consolidator via with_consolidator.
NoopEmbedder
Zero-vector Embedder of caller-configured dim. Used when no real embedder backend is wired (air-gapped builds, metadata-only ingest, tests that need a working Arc<dyn Embedder> without similarity semantics).
NoopExtractor
Default extractor when graph pipeline is OFF (Plan 03-03) or when no remote backend cache is missing. Returns one empty RawExtraction per input chunk so the per-chunk index alignment downstream still holds.
NoopReflectSupervisor
Noop reflect supervisor — always returns an empty ReflectOutput. Default for Lunaris::with_reflect when the umbrella ships reflect-OFF (mirrors blueprint §5.1 default-OFF for verify).
NoopReranker
NO-OP reranker. Used as the default fallback when crate::BgeRerankerV2M3 weights are missing. Production code wires this via Lunaris::open(url) automatically when the cache is empty.
NoopVerifier
Default verifier when the pipeline is OFF (Plan 04-04) or when no remote backend cache is missing. Returns a VerifyDecision::deferred so the worker treats the item as “abstain — leave the underlying primitive row untouched”.
OllamaExtractor
Ollama-backed extractor — thin wrapper over LlmExtractor.
OllamaExtractorOpts
Construction options for OllamaExtractor.
OllamaVerifier
Ollama-backed verifier. Phase 12b wraps OllamaBackend + LlmVerifier.
OllamaVerifierOpts
Construction options for OllamaVerifier.
Page
One page of scan_page results.
Query
One retrieval query.
QueueMsg
A single message yielded by subscribe. offset is the broker-assigned monotonic offset within (topic, partition).
RawHit
One pre-hydration retrieval hit. Operators flow these around between each other; the final stage hydrates them into Hits.
ReflectInput
Input snapshot the reflection LLM sees. Caller assembles this from the just-finished turn’s ingest + recall state. The fields are intentionally minimal — wider context (full chunk text, full recall hits) belongs in the prompt the reflection wrapper builds.
ReflectOpts
Construction options.
ReflectOutput
Output the reflection LLM emits. All three fields are advisory — nothing in this commit applies them. Wire-up to the storage layer is a follow-up.
Relation
RerankCandidate
One pre-rerank candidate. The operator hydrates the chunk text BEFORE calling the reranker (see lunaris_retrieve::hydrate::partial_hydrate_text) so the cross-encoder can pair-encode (query, doc.text) for scoring.
RerankRetriever
rerank(model) operator — wraps an upstream retriever with a cross-encoder rerank pass. See module-level rustdoc for the partial-hydration + hit-count contracts.
RetrievalBuilder
Builder returned by Lunaris::recall().
RetrievalService
tower::Service adapter wrapping a built operator tree.
Row
A single MVCC row returned by read_as_of. bt carries the bi-temporal stamp the row was visible under at the snapshot time.
Scope
A partition key for multi-agent / multi-tenant isolation.
ScopePage
One page of scope identifiers returned by StoragePort::list_scopes.
StorageCapabilities
StubEmbedder
TopRetriever
Cap the result list to n hits after the upstream operator resolves.
Tree
RAPTOR tree retrieval operator.
ValidatedExtraction
What validate produces. The entities/relations/facts lists hold items that passed validation and are safe to write to storage; the needs_review list holds items that failed with a structured reason so the ingest fan-out can publish them to the verify queue (D-19).
Vector
Vector retrieval operator.
VectorHit
A single vector_search result.
VerifyDecision
One verifier arbitration decision. winner_id / loser_id are Option because a “deferred” decision (NoopVerifier short-circuit, or cloud-api D-21 transient-after-retry) carries no arbitration pair — the worker treats such decisions as “skip this item”.

Enums§

AuditEvent
Canonical typed audit event. Externally-tagged so the JSON wire shape carries "kind": "<variant-name>" for grep-friendly ops triage.
CircuitState
State machine for the circuit breaker. Encoded as u8 so the state fits in an atomic without a Mutex<State> outer layer; the failure-window counter still lives behind a Mutex because it needs the wall-clock to age entries out.
CloudProvider
Selectable provider per D-01. Reads from LUNARIS_EXTRACT_PROVIDER env (case-insensitive) at CloudApiExtractorOpts::default time.
ConsolError
CypherDialect
Cypher dialect tier the backend’s graph executor accepts.
ExtractError
Filter
Filter expression passed to vector_search. v0 supports a small algebra; the backend translates it to its native filter language (FT.SEARCH ... FILTER ... on Moon).
ListError
Failure modes of scan_page. ListError::code is the stable wire string.
LunarisError
Top-level error type returned by every public lunaris API.
MemoryLevel
The canonical memory-partition levels, composed UNDER the JWT base scope in this fixed order (UserAgentSession). Each carries a one-char disambiguating tag so the composed scope is self-describing and collision-resistant: {base}.u-{user}.a-{agent}.s-{session}, including only the levels whose id is present.
NeedsReviewItem
One failed extraction with the reason it was demoted. Preserves the raw item so the Phase 4 Verifier (Plan 04-XX) can re-extract / arbitrate.
NeedsReviewReason
Structured reason explaining why an extraction was routed to ValidatedExtraction::needs_review. Each variant maps onto a blueprint §5.2 / D-08 / D-21 NeedsReview class.
Plan
Retrieval plan picked by the v0 query planner.
PlanError
Why a JSON plan could not be turned into a retriever.
RetrieveError
RrfFusion
RRF (Reciprocal Rank Fusion) mode for the retrieval DSL.
ScopeError
Error returned when constructing an invalid Scope.
SourceOp
What kind of operator produced a RawHit. RRF fusion groups raw hits by this tag so per-branch rankings stay isolated when computing 1 / (k + rank_i).
StorageError
Subsystem
Coarse subsystem tag for a LunarisError — one classifying match, inside the crate that owns the enum.
ValidateError
VerifierBackend
Provider tag for audit records. Serialized with default enum tagging (externally tagged → "Ollama" / "CloudAnthropic" / etc.) so the audit schema is grep-friendly in ops tooling.
VerifyNeedsReviewItem
One failed extraction with the reason it was demoted. Preserves the raw item so the Phase 4 Verifier (Plan 04-XX) can re-extract / arbitrate.
WriteOp
One operation in an atomic_write batch.

Constants§

AUDIT_TOPIC
Unified audit topic. Every publisher in the workspace emits here.
DEFAULT_GRAPH_HOPS
Default hops per ROADMAP Phase 3 success criterion #3.
DEFAULT_GRAPH_K
Default candidate count for graph traversal (matches Vector/Keyword default of 30).
LUNARIS_GRAPH_NAME
Graph name Lunaris traverses — the <graph> argument of Moon’s GRAPH.QUERY <graph> "...". Held as a constant (rather than inlined at each call site) so a future backend can be pointed at the same graph identifier and keep the Cypher template portable; with_graph() overrides it per tenant.
MAX_GRAPH_HOPS
Hard cap on hops to prevent runaway BFS (D-14). Caller-supplied hops greater than 5 clamps to 5; hops == 0 clamps up to 1 so the BFS always runs at least one edge step (zero-hop traversal would only return the anchor entities themselves, which the caller already has).
MAX_PAGE
Hard upper bound on a single page (contract v1). A limit above this is rejected.
NOOP_DEFAULT_DIM
Default dim for NoopEmbedder when no override is supplied. Matches the historical EmbeddingGemma 300M / granite-r2 output width (768) so an operator who flips to the noop backend doesn’t have to re-create their FT.CREATE HNSW index.

Traits§

Consolidator
Object-safe async consolidator.
Embedder
Extractor
Object-safe async extractor.
Key
User-defined typed key. Implementors define how to serialize the key to bytes for KvPut / KvDelete write ops; trait is object-safe-by-design (no generic methods).
KeywordPort
BM25 keyword search extension trait.
ReflectSupervisor
Object-safe async reflection supervisor.
Reranker
Async cross-encoder reranker.
Retriever
Object-safe async retriever.
StoragePort
The storage abstraction for Lunaris.
Verifier
Object-safe async verifier.

Functions§

compose_levels
Compose the JWT-bound base scope with optional user/agent/session ids, in the canonical MemoryLevel order, into the bound partition.
degraded_fallback
Builder-friendly factory: degraded_fallback(primary, fallback).
det_vec
Deterministic stand-in for a real embedding: unit-norm and clustered.
filter_str
Parse the v0 string DSL into a Filter AST.
floored_top
Chunk-superset floored top-k selection (pure function; the policy behind FlooredTopRetriever).
hybrid_root
The fused hybrid root: (Vector ∧ BM25)("chunks") ∧ (Navigate ∧ BM25)("facts") → fuse_rrf(60).
plan_query
Run the v0 planner heuristic.
publish_audit_event
Fire-and-forget audit publish. Mirrors the pre-refactor helper at crates/lunaris/src/audit.rs:99-117 verbatim:
rerank
Builder-friendly factory: rerank(upstream, reranker). Mirrors the fuse_rrf(inner, k) shape from operators/fuse.rs so callers can chain via either method-style or function-style composition.
retriever_from_json
Build a retriever tree from a JSON plan node. See the module docs for the accepted shape.
sanitize_graph_ident
Sanitize free-form text into a Cypher-safe identifier for WriteOp::GraphNode::label / WriteOp::GraphEdge::rel.
scan_page
Read one page of primitives of type T under prefix, scope-bound, ULID-ascending.