locus-sdk
SDK-first STTP memory primitives and AI provider abstraction.
locus-sdk is the transport-agnostic core for STTP memory operations. It provides typed memory primitives, AI provider capability routing, and composition workflows that can be reused from MCP, HTTP, gRPC, CLI, or local applications.
Why This Crate Exists
Historically, much of STTP memory behavior lived in transport layers. This crate moves core behavior into one SDK so the same semantics are shared everywhere.
Core goals:
- Primitive-first API surface.
- Transport-neutral contracts.
- Deterministic policy behavior.
- Composable workflows over stable primitives.
- Single provider orchestration surface for embeddings and AVEC tasks.
Current Scope
Implemented primitives and services:
- memory_find
- memory_recall
- memory_aggregate
- memory_transform
- memory_explain
- memory_schema
Implemented composition workflows:
- recall_with_explain
- daily_rollup
- transform_then_recall_verify
- capability_bundle
- build_content_from_text (recursive deterministic node-from-text composite)
Primitive Matrix
This matrix is intended as a fast contract reference for users, maintainers, and assistants.
| Primitive | Primary Input | Primary Output | Deterministic Guarantee |
|---|---|---|---|
| memory_find | scope + filter + sort + page | filtered nodes + cursor state | Non-ranked filtering and stable sort semantics |
| memory_recall | scope/filter/page + current_avec + optional query_text/query_embedding + scoring policy | ranked nodes + psi range + retrieval path | Policy-driven fallback behavior with explicit retrieval path |
| memory_aggregate | scope/filter + group_by + limits | grouped stats and totals | Stable grouping and bounded aggregation windows |
| memory_transform | selector + operation + dry_run + execution controls | mutation execution summary + failures | Explicit dry-run and bounded batch execution |
| memory_explain | recall request payload | stage counts + fallback reason + scoring profile | Explain trace derived from the same recall contract |
| memory_schema | none | supported fields, modes, and operations | Introspection is explicit and versioned |
Composition Matrix
| Workflow | Uses | Best For |
|---|---|---|
| recall_with_explain | memory_recall + memory_explain | ranked retrieval with transparent reasoning |
| daily_rollup | memory_aggregate grouped by day | timeline summaries and dashboards |
| transform_then_recall_verify | memory_transform + memory_recall | migration/backfill verification loops |
| capability_bundle | memory_schema | dynamic client and agent capability discovery |
| build_content_from_text | manual_compression + composition policy resolver | recursive deterministic content-layer construction from role-tagged text |
Deterministic Compression and Composite Construction
This SDK supports deterministic text-to-content construction for STTP workflows without requiring model summarization for the core compression path.
Key building blocks:
- Manual compression service with pluggable lexicon provider trait.
- Request-level lexicon overrides (stopwords/fillers/negations add/remove).
- Recursive composition workflow that builds spec-safe content payloads from role-tagged text input.
Core AVEC resolution chain in composite workflow:
- item-level override
- role-level override
- global override
- optional LLM fallback if enabled
- explicit failure when unresolved and fallback disabled
Recursion guarantees:
- Recursion depth is clamped to [1, 5].
- Depth overflow fails fast.
- Output content is structured for strict parser and validator compatibility.
Full guide:
Crate Features
Default features:
- genai-provider
Feature flags:
- genai-provider: enables genai-based external provider adapter support.
Architecture
Module layout:
- domain
- application
- infrastructure
- interface
- prelude
Layer intent:
- domain: contracts, enums, request/response models, policy types.
- application: primitive services and composition orchestration.
- infrastructure: provider adapters and registries.
- interface: transport-friendly DTOs and conversion glue.
- prelude: ergonomic re-exports for SDK consumers.
Quick Start
Add dependency from workspace:
[]
= { = "../locus-sdk" }
= { = "../locus-core-rs" }
= { = "1", = ["macros", "rt-multi-thread"] }
Example: recall from an in-memory store
use Arc;
use Result;
use ;
use ;
async
Full End-to-End Example
Run a complete in-memory workflow that exercises the core primitives:
- memory_find
- memory_recall
- memory_explain
- memory_aggregate
- memory_transform (dry-run then apply)
- memory_schema
- recall_with_explain composition
Command:
Human and Assistant Collaboration Guide
This SDK is intentionally designed to be usable by both application developers and model-driven collaborators.
Recommended collaboration pattern:
- Use DTOs at transport boundaries and domain models inside application logic.
- Keep policy explicit in request payloads, especially fallback_policy and strictness.
- Prefer composition services when you need traceable, multi-step memory workflows.
- Treat memory_schema as the contract source for dynamic UIs and agent tool planning.
Assistant-safe request construction checklist:
- Always set an explicit page.limit.
- Provide scoring.alpha and scoring.beta when semantic retrieval is used.
- Choose fallback_policy intentionally, do not rely on hidden defaults in transport wrappers.
- Capture retrieval_path and explain stages when decisions must be auditable.
Determinism tips:
- Use strict filters and narrow scope for reproducible retrieval windows.
- Keep tier and date ranges explicit.
- Preserve request payloads in logs when debugging ranking behavior.
Model-First Playbook
This section is for assistants and collaborative agents that need reliable primitive selection and predictable payload construction.
Primitive Selection Decision Tree
Use this order:
- Need direct filtering without ranking: use memory_find.
- Need ranked retrieval by AVEC and optional semantic signal: use memory_recall.
- Need grouped statistics or rollups: use memory_aggregate.
- Need bulk mutation or embedding backfill/reindex: use memory_transform.
- Need retrieval reasoning trace: use memory_explain or recall_with_explain.
- Need runtime capability discovery: use memory_schema or capability_bundle.
- Need a multi-step verification flow: use composition workflows.
Prompt Templates for Assistants
Template: deterministic recall
Goal: Retrieve top memory nodes with deterministic policy behavior.
Constraints:
1. Explicit limit and scope.
2. Explicit alpha/beta.
3. Explicit fallback_policy.
4. Return retrieval_path and psi_range.
Action:
1. Build MemoryRecallRequest.
2. Execute MemoryRecallService.
3. If auditability required, execute MemoryExplainService with the same recall payload.
Template: migration verification
Goal: Run embedding backfill and verify retrieval quality did not regress.
Action:
1. Execute transform_then_recall_verify.
2. Inspect transform.updated, transform.failed.
3. Inspect recall.retrieved and retrieval_path.
4. Record failures and fallback behavior.
Template: dynamic client introspection
Goal: Build client-side controls from SDK capabilities.
Action:
1. Execute capability_bundle.
2. Populate UI controls from sort_fields, filter_fields, group_by_fields.
3. Populate policy selectors from fallback_policies and strictness_modes.
Payload Examples
Example: MemoryRecallRequest payload (json-style)
Example: MemoryTransformThenRecallRequest payload (json-style)
Assistant Reliability Checklist
- Never omit page.limit.
- Keep scope bounded whenever possible.
- Set fallback_policy explicitly.
- Log retrieval_path for every recall execution.
- Use explain for user-facing rationale.
- Use schema to avoid hardcoding enum assumptions.
Composition Example
Use the composition service for higher-level workflows:
- recall with explain trace.
- daily rollups.
- transform then verify via recall.
See runnable examples:
- examples/provider_registry_setup.rs
- examples/memory_composition.rs
- examples/recursive_composite_pipeline.rs
Primitive-oriented implementation references:
- src/application/memory_find.rs
- src/application/memory_recall.rs
- src/application/memory_aggregate.rs
- src/application/memory_transform.rs
- src/application/memory_explain.rs
- src/application/memory_schema.rs
- src/application/memory_composition.rs
- src/application/manual_compression.rs
Synthetic fixture generator:
AI Provider Model
Provider orchestration is capability-driven.
Capabilities:
- SemanticEmbedding
- AvecEmbedding
- AvecScoring
Tasks and provider selection are expressed through typed contracts:
- AiTask
- ProviderPolicy
- EmbedRequest
- ScoreAvecRequest
- AiProvider and AiProviderRegistry
Public Surface
Import from prelude for most use cases:
use *;
prelude exports include:
- primitive request models.
- primitive services.
- composition services and request/result types.
- DTOs for transport integration.
- provider contracts and registry adapters.
Primitive Recipes
Use these as tiny patterns when composing workflows.
Recipe: Find Nodes
use ;
let service = new;
let result = service.execute.await?;
Recipe: Recall with Explicit Fallback Policy
use ;
let service = new;
let request = MemoryRecallRequest ;
let result = service.execute.await?;
Recipe: Transform then Verify
use ;
let composition = new;
let verify = composition
.transform_then_recall_verify
.await?;
Recipe: Build Recursive Content from Text
use AvecState;
use ;
let composition = new;
let request = CompositeNodeFromTextRequest ;
let result = composition.build_content_from_text?;
println!;
println!;
Behavior Notes
- Memory recall supports policy-controlled lexical fallback behavior.
- Explain returns stage-level visibility into retrieval pipeline behavior.
- Schema exposes discoverable primitive capabilities for dynamic clients.
- Transform supports dry-run and batch controls for safer bulk operations.
Development
From crate root:
Generate synthetic JSONL fixtures:
Integration Status
As of 2026-05-03:
- SDK phases 0 through 4 are complete.
- Composition layer and DTO surface are in place, including recursive node-from-text composite contracts.
- Deterministic manual compression is implemented with trait-based lexicon customization.
- Transport migration has started in MCP and Gateway using SDK-backed retrieval paths.
Architecture and rollout plan:
Transport Migration Cookbook
This section is for MCP and Gateway maintainers adopting SDK primitives behind existing endpoints.
Migration strategy:
- Keep external endpoint shapes stable.
- Map transport request models into SDK domain requests.
- Execute SDK services in handlers.
- Map SDK results back to existing response models.
- Preserve compatibility wrappers until at least one release cycle after migration.
Suggested order:
- get_context -> memory_recall
- list_nodes -> memory_find
- rollup endpoints -> memory_aggregate composition recipes
- embedding migration endpoints -> memory_transform
- explain and schema endpoints -> memory_explain and memory_schema
Mapping checklist per endpoint:
- scope: tenant/session/tier/time fields map to MemoryScope.
- pagination: map limit/cursor to MemoryPage.
- scoring: map alpha/beta/fallback policy to MemoryScoring.
- filters: map typed ranges to MemoryFilter.
- response: preserve previous wire fields while sourcing values from SDK results.
Acceptance checklist:
- Existing endpoint tests still pass.
- Retrieval path and fallback behavior are explicit in logs.
- New integration tests validate parity between old and SDK-backed behavior.
- Feature flags or rollout toggles are available for controlled cutover.
Non-Goals for This Crate
- Storage backend implementation details.
- Transport endpoint definitions.
- STTP typed IR grammar or parser conformance logic.
For typed IR language and grammar contract work, refer to: