Skip to main content

Module storage

Module storage 

Source

Re-exports§

pub use migrations::current_schema_version_for_tests;
pub use migrations::pre_migration_backup_infix_for_tests;

Modules§

migration_meta
ARCH-8 (FX-C4-batch2, 2026-05-26) — per-migration metadata matrix.
migrations
SQLite schema definition + migration ladder. v0.7.0 L0.5-3 extracted the SCHEMA constant, the MIGRATION_V*_SQLITE include-bytes constants, the CURRENT_SCHEMA_VERSION parallel constant, and the migrate function out of src/db.rs into this sub-module. Pure refactor — semantics unchanged. The MAX_SUPPORTED_SCHEMA constant in cli::boot must still bump in lockstep with [CURRENT_SCHEMA_VERSION] (current value: 57). Versions 45/46 are reserved for sibling provenance-write landings (Gaps 1+2, #884/#885); this crate jumps 44 → 47 for Gap 3 (#886). v48 (Track D #933) adds the federation_push_dlq table so quorum- broadcast fanout failures can be replayed by the new replay_federation_push_dlq worker. v51 (#1255) adds the federation_nonce_cache table so the FederationNonceCache LRU persists across daemon restarts — pre-#1255 every restart opened a fresh replay window for any (body, sig, nonce) tuple captured before the restart. v52 (#1389) adds the transcript_line_dedup table backing the sha256-keyed idempotency layer for the four-layer capture architecture (L2 recover-on-boot + L3 substrate watcher + L4 memory_capture_turn MCP tool). Closes the #1388 substrate failure mode at the storage layer.

Structs§

BudgetOutcome
Phase P6 — outcome of applying a token budget to a ranked recall list. Carries everything mcp::handle_recall needs to populate the new RecallMeta block (budget_tokens_used, budget_tokens_remaining, memories_dropped, budget_overflow).
CapabilityExpansionRow
Maximum sync-clock skew in seconds across the sync_state table — the largest gap between last_pulled_at (when this peer last heard from a peer) and last_seen_at (the peer’s own updated_at advance). Returns Ok(None) when sync_state is empty or the columns are missing on a pre-T3 schema.
ConflictError
Typed error returned by insert_with_conflict under ConflictMode::Error when a (title, namespace) row already exists. Carries the existing row’s id so callers can surface a well-shaped diagnostic instead of leaking a generic SQL string.
EmbeddingDimMismatch
v0.6.3.1 P2 (G4): error returned by set_embedding when a write would introduce a new embedding dimensionality into a namespace that has already established one via an earlier write. Surfaced as a typed error so the MCP/HTTP handlers can map it to a 409 Conflict rather than letting cosine silently return 0.0 on every subsequent recall.
ForgetMatch
#1602 — one row of a forget preview / deletion audit listing.
GovernanceRefusal
Typed substrate-layer marker error for the pre-write hook refusal path. Wrapped in anyhow::Error so the existing anyhow::Result<String> return shape of storage::insert* stays unchanged — the handler layer downcasts via MemoryError::from(anyhow::Error) (see src/errors.rs) to map the refusal to HTTP 403 FORBIDDEN + code GOVERNANCE_REFUSED.
InvalidateResult
Outcome of invalidate_link (Pillar 2 / Stream C — memory_kg_invalidate). valid_until is the timestamp now stored on the link; previous_valid_until is the prior value, or None if this was the first invalidation. Callers can use the prior value to distinguish a fresh supersession from an idempotent retry.
LinkVerifyRecord
v0.7 H4 — full row-projection used by the memory_verify MCP tool.
ProactiveConflict
Result envelope returned by proactive_conflict_check when an existing memory near-duplicates AND textually contradicts the incoming write.
ReflectHooks
v0.7.0 recursive-learning Task 6/8 — optional in-substrate hook callbacks fired by reflect_with_hooks. Bundled into a single struct so the substrate signature stays compact and so future callbacks (e.g. on-rollback) can land without churning every call site.
ReflectInput
Input bundle for reflect. Holds every caller-tunable field of the new reflection memory plus the source-id list. Defaults mirror the MCP tool schema (tier=mid, priority=5, confidence=1.0, source=DEFAULT_NHI_SOURCE per crate::validate::DEFAULT_NHI_SOURCE = "nhi" post-#1175 — pre-#1175 this defaulted to "claude", a heterogeneous-NHI monoculture defect that #1175 closed) so the dispatch layer can build this from the raw JSON arguments without further fixup.
ReflectOutcome
Outcome of a successful reflect write. Mirrors the MCP memory_reflect wire shape so the dispatch layer is a thin serialization wrapper.
ReflectionDepthRow
One namespace’s reflection-depth distribution row returned by doctor_reflection_depth_distribution.
SupersedeResult
v0.7.0 Provenance Gap 5 (issue #888) — append-and-archive result returned by update_with_archive_on_supersede.
VersionConflict
Update a memory by ID. Returns (found, content_changed) so callers can re-generate embeddings when the searchable text has changed. v0.7.0 Provenance Gap 1 (issue #884) — typed optimistic-concurrency error returned by update_with_expected_version when the caller passed expected_version and the stored row’s current version has drifted. Carries both expected + current so the caller can surface a useful diagnostic and choose between re-read+re-apply or bubbling CONFLICT upstream.

Enums§

ApproveOutcome
Task 1.10 — outcome of an approver-aware approve call.
ConflictMode
v0.7.0 fix campaign R1-M3 (#690) — substrate-side on_conflict policy for insert_with_conflict.
LinkEnd
Identifies which end of a link a missing-memory refusal refers to. None is reserved for memory-not-found errors that are not part of a link operation. The Source and Target variants preserve the pre-#962 user-facing error prefixes (“source memory not found: …” / “target memory not found: …”) so existing string-matching consumers keep working through the typed enum’s Display impl.
ReflectError
Typed substrate-level error surface for reflect. Kept distinct from crate::errors::MemoryError so the SQLite substrate layer stays free of HTTP-status concerns; the caller at the MCP / HTTP boundary maps these into the wire-shaped variant. Task 5/8 matches on ReflectError::DepthExceeded here (and the equivalent MemoryError::ReflectionDepthExceeded variant) to emit the signed_events audit record for the refusal decision.
ReflectHookDecision
v0.7.0 recursive-learning Task 6/8 — substrate-level decision surface returned by a pre_reflect hook callback.
StorageError
Typed substrate-layer error categories. Each variant maps to a canonical HTTP status via MemoryError::from(anyhow::Error) and preserves the original bail!() message verbatim via Display so downstream .to_string().starts_with(...) and .contains(...) consumers keep working through the typed layer.

Constants§

ARCHIVE_DEFAULT_PAGE_LIMIT
Default page size for archive listings (HTTP /api/v1/archive and MCP memory_archive_list) when the caller passes no explicit limit — one knob so both surfaces page identically.
CONSOLIDATION_SOURCE
#1558 batch 5 wave 3 — canonical source value stamped on rows minted by consolidate (MCP memory_consolidate + the HTTP power-consolidation handler pass it verbatim). Listed in validate::VALID_SOURCES; one spelling, hoist-only.
DEFAULT_DB_MMAP_SIZE_BYTES
#1579 B7 — default PRAGMA mmap_size in bytes (256 MiB).
DUPLICATE_THRESHOLD_DEFAULT
Default cosine similarity threshold for declaring a candidate a duplicate. Empirically tuned for MiniLM-L6-v2 (the local embedder): near-paraphrases of the same memory tend to land at 0.88+, while loosely related content sits well below 0.85. Callers can override.
DUPLICATE_THRESHOLD_MIN
Hard floor for duplicate-check threshold. Below this, anything can match random unrelated content — refuse to honor the lookup so callers don’t silently get garbage merge suggestions.
FIND_PATHS_DEFAULT_DEPTH
Default depth used when the caller omits max_depth. Mirrors the v0.7 J7 charter’s “shallow by default, opt-in deep traversal” rule.
FIND_PATHS_DEFAULT_LIMIT
Default cap on paths returned by find_paths when the caller does not specify one. Matches the v0.7 J7 charter.
FIND_PATHS_MAX_DEPTH
Hard ceiling on traversal depth supported by find_paths. Distinct from KG_QUERY_MAX_SUPPORTED_DEPTH because path enumeration is more expensive than reachability — we can afford a slightly deeper budget for the BFS but not by much.
FIND_PATHS_MAX_LIMIT
Hard ceiling on paths returned by find_paths. A crafted call asking for more than this many paths is clamped down. Matches the v0.7 J7 charter.
KG_QUERY_DEFAULT_LIMIT
Default cap on rows returned by kg_query when the caller does not specify one (Pillar 2 / Stream C). Mirrors kg_timeline’s default so the two traversal tools behave consistently for agents driving them.
KG_QUERY_MAX_LIMIT
Hard ceiling on kg_query rows. Matches kg_timeline and the existing list/recall caps to keep traversal bounded against pathological fan-out.
KG_QUERY_MAX_SUPPORTED_DEPTH
Maximum traversal depth supported by kg_query. The recursive-CTE implementation enforces an explicit ceiling so a crafted call cannot run an unbounded traversal; the charter (v0.6.3-grand-slam.md § Performance Budgets) sets the published budget at depth ≤ 5.
KG_TIMELINE_DEFAULT_LIMIT
Default cap on rows returned by kg_timeline when the caller does not specify one (Pillar 2 / Stream C). Sized to fit a reasonable agent context window without paging — callers needing more should pass an explicit limit.
KG_TIMELINE_MAX_LIMIT
Hard ceiling on kg_timeline rows. Matches the existing list/recall caps to keep the timeline bounded against pathological entities.
LINK_CYCLE_ERR_PREFIX
Error prefix emitted when validate_link_pre_create rejects a reflects_on edge that would close a cycle in the reflection graph. HTTP / SAL response mappers look for this prefix to surface 409 CONFLICT; MCP surfaces it as a plain text error. Centralised so all three entry points stay in lockstep with StorageError::LinkReflectionCycle.
LINK_PERMISSION_DENIED_ERR_PREFIX
Error prefix emitted when the K9 permission pipeline returns Deny for a link write. HTTP / SAL response mappers translate this to 403 FORBIDDEN. Paired with StorageError::LinkPermissionDenied.
LIST_DEFAULT_CAP
Default row cap for memory list/search surfaces when the caller passes no explicit limit. Mirrored by the postgres SAL adapter (src/store/postgres.rs::list_by_source_uri) so both backends page identically.
LIST_FALLBACK_LIMIT
Post-clamp usize → i64 conversion fallback for list/query limits. Unreachable in practice (values are already clamped to at most LIST_MAX_LIMIT, which always fits i64); kept as a named knob so the fallback page size is explicit rather than magic.
LIST_MAX_LIMIT
Hard ceiling on rows returned by the memory list/search surfaces. One shared knob across the sqlite + postgres SAL adapters; same family as KG_TIMELINE_MAX_LIMIT / KG_QUERY_MAX_LIMIT.
PENDING_DEFAULT_PAGE_LIMIT
Default page size for governance pending-action listings (MCP memory_pending_list / subscription approval feeds).
PROACTIVE_CONFLICT_CONTENT_JACCARD_FLOOR
#1579 A5 — minimum Jaccard token overlap between the incoming content and a cosine-near-duplicate candidate’s content for the pair to be classified as a proactive conflict.
PROACTIVE_CONFLICT_INDEX_K
#1579 A5 — k requested from the HNSW index by proactive_conflict_check_with_index. Deliberately larger than PROACTIVE_CONFLICT_TOP_K because the index is global while the conflict check is namespace-scoped: the namespace filter is applied AFTER the ANN search (post-filter semantics), so foreign-namespace hits consume slots. 32 gives the in-namespace pool ample headroom (the ≥ 0.95 cosine gate means only near-identical vectors matter, and > 32 near-identical foreign-namespace rows crowding out an in-namespace conflict is a pathology the bounded fallback’s advisory contract already tolerates — see PROACTIVE_CONFLICT_SCAN_LIMIT).
PROACTIVE_CONFLICT_SCAN_LIMIT
#1579 A5 — row cap on the bounded fallback scan in proactive_conflict_check (most-recently-updated rows first).
PROACTIVE_CONFLICT_SIM_THRESHOLD
Cosine-similarity threshold above which a candidate is treated as a near-duplicate for the purpose of proactive_conflict_check.
PROACTIVE_CONFLICT_TOP_K
Top-K cap for the candidate pool inspected by proactive_conflict_check. Bounded so the per-write cost is O(K) rather than O(namespace_size).
TAXONOMY_DEFAULT_LIMIT
Default group budget for taxonomy listings when the caller passes no explicit limit (HTTP /api/v1/namespaces, MCP memory_get_taxonomy).
TAXONOMY_MAX_LIMIT
Hard cap on input groups walked when assembling a taxonomy tree. Even when callers pass a wildly large limit, we never walk more than this many (namespace, count) rows — bounds memory + time. Shared by the sqlite + postgres taxonomy paths and the HTTP / MCP taxonomy surfaces so all four clamp identically.

Statics§

GOVERNANCE_PRE_WRITE
Optional governance pre-write hook. When Some, every substrate INSERT path consults the closure BEFORE the SQL write; an Err(reason) short-circuits the write with no row touched.

Functions§

agent_pubkey
Fetch the Ed25519 public key bound to agent_id, if any (#626 Layer-3, Task 1.3 / C3).
apply_token_budget
Phase P6 (R1) — context-budget greedy fill. Iterates over scored candidates in rank order; stops at the first memory whose inclusion would exceed the budget — UNLESS the output is still empty, in which case the highest-ranked memory is returned anyway with budget_overflow = true. This preserves the R1 guarantee that a successful recall always returns at least one result when any matched, even if the user supplied an unrealistically tight budget.
approve_with_approver_type
Task 1.10 — approver-type aware approve. Enforces the metadata.governance.approver of the pending action’s namespace.
archive_memory
Move a memory from memories to archived_memories. Used by the HTTP /api/v1/archive explicit-archive endpoint (S29) and by sync_push when a peer pushes an archives: [id] record.
archive_memory_for_caller
#940 (security-high, 2026-05-20) — caller-scoped archive variant. Mirrors archive_memory but constrains the soft-move to rows in the live memories table whose metadata->'agent_id' JSON field matches caller (with the inbox-target carve-out: metadata->'target_agent_id' == caller is also archivable by the inbox owner, matching [crate::store::is_visible_to_caller]).
archive_stats
auto_purge_archive
Purge old archives if archive_max_days is configured.
bind_agent_pubkey
Bind (or rotate) an agent’s Ed25519 public key into its _agents registration row metadata (#626 Layer-3, Task 1.3 / C3).
build_list_query
#1579 A2 — build the sargable list SQL + parameter vector.
build_namespace_chain
Build the namespace inheritance chain in top-down order (["*", root, ..., leaf]). Mirrors and replaces the historical mcp::build_namespace_chain so non-MCP call sites (db-layer governance enforcement, HTTP handlers, future hook pipelines) can reuse the same walk.
canonical_cbor_reflection_depth_exceeded
v0.7.0 recursive-learning Task 5/8 — canonical-CBOR encoding of the reflection.depth_exceeded audit payload.
canonical_content_hash
Canonical hash used by check_duplicate_with_text to detect byte-identical title + content pairs even when the embedding pipeline (lower-casing, prefix tagging, etc.) prevents the cosine similarity from saturating at 1.0.
capture_turn_idempotent
v0.7.0 #1416 / RFC-0001 — sqlite SSOT for the L4 layered-capture idempotent write. Both the MCP memory_capture_turn handler (which holds a raw &rusqlite::Connection) and SqliteStore:: capture_turn_idempotent (the SAL trait surface) call through here, so the dedup-lookup + atomic three-row insert exists in exactly one place on the sqlite path.
check_duplicate
Find the nearest-neighbor live memory by cosine similarity (Pillar 2 / Stream D — memory_check_duplicate).
check_duplicate_with_text
v0.7.0 F18 — exact-match-aware nearest-neighbor duplicate check.
checkpoint
Checkpoint WAL for clean shutdown.
clear_namespace_standard
Clear the standard for a namespace.
consolidate
Consolidate multiple memories into one. Returns the new memory ID. Deletes the source memories and creates links from new → old (derived_from).
count_active_governance_rules
v0.6.3 (capabilities schema v2): count namespace standards whose metadata.governance is non-null. A “rule” here means a namespace has an explicit governance policy attached to its standard memory. The count is a transparent passthrough — the full permission system arrives in v0.7 (arch-enhancement-spec §3).
count_embedded_memories
#1579 B3 — count of rows carrying a stored embedding. Cheap probe (no blob decode, no row materialisation) used by the CLI recall path to decide whether a one-shot invocation should pay the HNSW graph-construction cost at all (see crate::hnsw::CLI_HNSW_BUILD_MIN_ENTRIES).
count_memory_tokens
Phase P6 — token cost of a memory’s content only (not title), per the R1 spec which budgets against the LLM context window. Title and metadata are caller-side ornament; content is what gets stuffed into the prompt.
count_pending_actions_by_status
v0.6.3 (capabilities schema v2): count pending_actions rows whose status matches the predicate. Used by handle_capabilities to surface live approval queue depth.
count_subscriptions
v0.6.3 (capabilities schema v2): count rows in the subscriptions table. Used by handle_capabilities as a proxy for “registered hooks” — the hook pipeline itself is v0.7 Bucket 0 work.
count_tokens_cl100k
Phase P6 (R1) — count tokens in text using OpenAI’s cl100k_base BPE encoding. This is the de-facto standard for Claude / GPT context budgeting and is shipped with tiktoken-rs (the BPE table is embedded in the crate, ~1.7 MB, so the count is offline-deterministic across all hosts). The encoder is built lazily and cached process-wide via OnceLockcl100k_base() itself parses the embedded table on every call, which adds a few ms; we pay that cost once.
create_link
Insert a directional (source_id, target_id, relation) link.
create_link_inbound
v0.7 H3 — insert an inbound (federation-replicated) link with a pre-computed signature and attest level.
create_link_signed
v0.7 H2 — link write that optionally signs with the active agent’s Ed25519 keypair.
decide_pending_action
Mark a pending action as approved or rejected. Returns true on status transition. Does NOT execute the action itself — the caller replays the payload on approval (the db layer doesn’t know how to execute cross-interface write semantics).
delete
delete_link
dim_violations
Count rows whose stored embedding_dim does not match what the BLOB contains (or where the column is missing while a BLOB exists). Surfaced in Stats::dim_violations and consumed by P7 doctor.
distinct_embedding_dims
#1598 — distinct embedding dimensionalities currently stored, optionally namespace-filtered, for the reembed pre-flight banner (the loud “old dims vs target dim” disclosure before a vector-space migration). Prefers the declared embedding_dim column and falls back to deriving from the BLOB length for legacy rows — 4n+1 bytes is the v17 headed form ((len-1)/4 floats), 4n the legacy unheaded form (len/4), mirroring dim_violations.
doctor_dim_violations
Count rows whose embedding_dim (post-P2) does not match the modal dim within their namespace. On pre-P2 schemas the embedding_dim column doesn’t exist; the function returns Ok(None) so the doctor can render “not yet observed (pre-P2 schema)”.
doctor_governance_coverage
Count of namespaces that have a standard registered with a non-null metadata.governance block, and the count without (just a standard memory but no policy attached).
doctor_governance_depth_distribution
Distribution of the parent_namespace chain depth across namespace_meta rows. Returns a Vec where index i is the count of namespaces with chain depth i (depth 0 = no parent).
doctor_max_sync_skew_secs
doctor_oldest_pending_age_secs
Age in seconds of the oldest pending row in pending_actions, or None if the queue is empty (or the column is unparseable). The doctor uses this to flag a backlog older than 24h as critical.
doctor_reflection_depth_distribution
Depth distribution across all namespaces that hold at least one memory with reflection_depth > 0, plus the _global_ aggregate.
doctor_reflection_depth_exceeded_count
Count of reflection.depth_exceeded audit events in signed_events within a given look-back window.
doctor_reflection_totals_by_namespace
Reflection totals per namespace: memories created in the last 24h, 7d, and all-time that have reflection_depth > 0.
doctor_webhook_delivery_totals
Sum of subscriptions.dispatch_count and subscriptions.failure_count across all rows. Returns (dispatched, failed). Used by the doctor to estimate webhook delivery success rate.
embedding_coverage
#1598 — (total_rows, rows_with_embeddings) for the reembed dry-run plan, optionally namespace-filtered. COUNT(embedding) counts non-NULL values, so the missing count is the difference.
enforce_governance
Enforce governance for a GovernedAction. On GovernanceDecision::Pending, a row is inserted into pending_actions and the returned pending_id is embedded in the decision.
entity_get_by_alias
Resolve an alias to its registered entity (Pillar 2 / Stream B).
entity_register
Register an entity (canonical name + aliases) under a namespace (Pillar 2 / Stream B).
estimate_memory_tokens
Phase P6 — kept for backward compatibility with the Task 1.11 byte- heuristic surface. New code should use count_memory_tokens. The returned value is now BPE-accurate (cl100k_base) rather than the prior len/4 estimate, so callers reading this through the public API get the more accurate value automatically.
execute_pending_action
Task 1.10 — Execute an approved pending action’s payload. Callers invoke this after approve_with_approver_type returns Approved. Returns the affected memory id (new id for store, existing id for delete/promote).
export_all
export_links
find_by_title_namespace
v0.6.3.1 P2 (G6) — quick existence check for (title, namespace). Used by on_conflict='error' callers to short-circuit before the full upsert machinery runs. Returns the existing row id if there is one.
find_contradictions
Detect potential contradictions: memories in same namespace with similar titles.
find_paths
v0.7 J7 — enumerate up to N undirected paths between two memories.
find_synthesis_candidates
Stage-1-only FTS5 candidate recall for the Form 1 synthesis curator path.
forget
Forget by pattern — delete memories matching namespace + FTS pattern + tier. If archive is true, archives memories before deletion.
forget_count
Count memories that would be deleted by forget (for dry_run).
forget_matches
#1602 — list the rows the forget filters currently match, capped at limit.
gc
gc_if_needed
Run GC if there are any expired memories. Lightweight check first.
get
get_all_embeddings
Get all stored embeddings as (id, embedding) pairs for building the HNSW index.
get_by_prefix
Look up a memory by ID prefix. Returns the memory if exactly one match is found. Returns Ok(None) if no matches. Returns an error if the prefix is ambiguous (>1 match).
get_embedding
Load an embedding vector for a memory. Returns None if not set.
get_link_for_verify
Fetch the single link identified by the (source_id, target_id, relation) composite primary key — the only unique identifier memory_links exposes today.
get_links
get_many
Batch-fetch memories by ID. Mirrors get but issues a single WHERE id IN (?, ?, ...) SELECT instead of N per-id round-trips.
get_memory_texts_batch
#1598 — keyset-paginated scan over ALL live memories (embedded or not), optionally namespace-filtered, for the ai-memory reembed full-corpus sweep. Same cursor semantics as get_unembedded_ids_batch_after: at most limit (id, title, content) triples with id strictly after after_id, in id order. Four distinct prepared shapes (namespace × cursor) keep the scan sargable (v55/v56 discipline).
get_namespace_meta_entry
v0.6.2 (S35): read the full namespace_meta row for a namespace so the caller can fan it out to peers. Returns None when no standard is set. Mirrors the (namespace, standard_id, parent_namespace, updated_at) tuple used by set_namespace_standard.
get_namespace_parent
Get the parent namespace for a given namespace.
get_namespace_standard
Get the standard memory ID for a namespace.
get_pending_action
get_taxonomy
Build a hierarchical namespace taxonomy (Pillar 1 / Stream A).
get_unembedded_ids
Get all memory IDs that are missing embeddings.
get_unembedded_ids_batch
#1579 B6 (F5.6) — bounded variant of get_unembedded_ids.
get_unembedded_ids_batch_after
#1595 — keyset-paginated variant of get_unembedded_ids_batch.
health_check
Deep health check — verifies DB is accessible and FTS is functional.
insert
Insert with upsert on title+namespace. Returns the ID (existing or new).
insert_if_newer
Insert with timestamp-aware conflict resolution for sync. Only overwrites if the incoming memory is newer (by updated_at, tiebroken by memory.id for a total order across peers — ultrareview #344, #345).
insert_with_conflict
v0.7.0 fix campaign R1-M3 (#690) — insert a memory under an explicit ConflictMode.
invalidate_link
Mark a KG link as superseded by setting its valid_until column (Pillar 2 / Stream C — memory_kg_invalidate). Returns Ok(None) when the (source_id, target_id, relation) triple does not match an existing link. The supplied valid_until defaults to the current wall-clock time in RFC3339 form when omitted; callers needing historical or future supersession can pass an explicit value.
is_namespace_standard
Check if a memory ID is a namespace standard (used by consolidate to warn).
is_registered_agent
Return true if agent_id matches a registered agent in _agents.
kg_query
Outbound KG traversal from a source memory (Pillar 2 / Stream C — memory_kg_query). Returns one row per link reachable within max_depth hops, filtered by:
kg_timeline
Ordered fact timeline for an entity (Pillar 2 / Stream C — memory_kg_timeline). Returns outbound assertions from source_id, ordered by valid_from ASC and tie-broken by created_at ASC for deterministic display.
list
list_active_governance_policies
v0.7.0 K5 — enumerate every namespace whose standard memory carries an explicit metadata.governance policy and return (namespace, policy) pairs sorted lexicographically by namespace.
list_agents
List every registered agent. Rows are drawn from the _agents namespace and parsed out of each memory’s metadata.
list_archived
list_by_source_uri
v0.7.0 Provenance Gap 6 (issue #889) — list every memory carrying the supplied source_uri. Bypasses the FTS layer so callers that want the full reciprocal set (“every memory from this document”) don’t need to type a query. Hits the partial idx_memories_source_uri index directly. Pure read.
list_capability_expansions
List recent capability-expansion rows, newest first. limit clamps the row count.
list_namespaces
list_pending_actions
memories_updated_since
Return memories whose updated_at > since, ordered by updated_at ascending. Used by GET /api/v1/sync/since to stream incremental updates to a peer. Caps at limit rows (caller-chosen pagination).
namespace_embedding_dim
Lookup the embedding dimensionality already established for namespace. Returns Ok(None) when no row in that namespace has an embedding yet.
next_versioned_title
Errors
open
proactive_conflict_check
v0.7.0 (issue #519) — proactive contradiction detection on the memory_store write path.
proactive_conflict_check_candidates
#1579 A5 — verify an ANN-derived candidate id list against the DB and apply the conflict verdict. Fetches only the named rows (point lookups by PK), re-applies the live/namespace filters the table scan used, and recomputes EXACT cosine from the stored embedding blob so the decision function is identical to the scan path.
proactive_conflict_check_with_index
#1579 A5 — HNSW-routed entry point for the proactive conflict check. This is the production write-path dispatcher:
promote_to_namespace
Task 1.7 — vertical memory promotion.
proximity_boost
Task 1.12 — proximity boost applied to a memory’s score based on its depth distance from the queried agent namespace. Uses the formula 1 / (1 + depth_distance * 0.3) per spec. Distance 0 = full strength (1.0), each step up the hierarchy dampens linearly.
purge_archive
purge_archive_for_caller
#936 (security-critical, 2026-05-20) — caller-scoped purge variant. Mirrors purge_archive but constrains the DELETE to rows whose metadata->'agent_id' JSON field matches caller (with the inbox-target carve-out: rows whose metadata->'target_agent_id' matches caller are also purgeable by the inbox owner, matching the SAL [crate::store::is_visible_to_caller] visibility predicate).
queue_pending_action
Insert a pending_actions row and return its id.
recall
recall_hybrid
Hybrid recall — FTS5 keyword search + semantic cosine similarity. Returns memories ranked by a blended score of keyword and semantic relevance. When an HNSW vector_index is provided, uses approximate nearest-neighbor search instead of scanning all embeddings linearly. v0.6.3.1 (P3): hybrid recall preserving the existing 2-tuple return shape for HTTP / CLI / bench callers. Delegates to recall_hybrid_with_telemetry and discards the telemetry. Kept so the dozen-plus call sites need no churn for a feature only MCP handle_recall consumes.
recall_hybrid_precomputed_hnsw
FX-4 / PERF-2 (2026-05-26) — convenience wrapper for the HTTP recall handler. Same return shape as recall_hybrid but accepts a pre-computed HNSW hit slice (caller ran idx.search() outside the DB lock) so the DB-mutex hold window does not cover the CPU-bound ANN walk. Telemetry is dropped on this path; the HTTP surface does not consume it today.
recall_hybrid_with_telemetry
recall_hybrid_with_telemetry_precomputed_hnsw
FX-4 / PERF-2 (2026-05-26) — variant of recall_hybrid_with_telemetry that accepts a pre-computed slice of HNSW hits in place of the in-pipeline idx.search() call. The HTTP recall handler runs the ANN walk OUTSIDE the DB mutex (the HNSW index lives behind its own vector_index mutex; the DB lock is not required for the search) and passes the result here so the DB-mutex hold window covers only the FTS5 query + the batched get_many fetch + the touch ops. Concurrent recalls overlap their CPU-bound ANN walks instead of serialising behind the single shared connection.
recall_with_telemetry
Recall — fuzzy OR search + touch + auto-promote + TTL extension. Task 1.11: after ranking, applies optional budget_tokens cap. Phase P6: returns the full BudgetOutcome (tokens_used, tokens_remaining, memories_dropped, budget_overflow) instead of just the prior bare tokens_used. Callers that only need tokens_used read outcome.tokens_used. v0.6.3.1 (P3): keyword-only recall with retrieval-stage telemetry.
record_capability_expansion
Record a capability-expansion attempt. Used by handle_capabilities_family after the allowlist decision is made. Records BOTH grant and deny outcomes so operators can see attempted access patterns even when the gate refused.
reflect
v0.7.0 recursive-learning Task 4/8 (issue #655) — substrate-native reflection primitive.
reflect_with_hooks
v0.7.0 recursive-learning Task 6/8 — variant of reflect with in-substrate hook callbacks. See reflect for the full step list; the only deltas are:
register_agent
Register or refresh an agent in the reserved _agents namespace.
resolve_governance_policy
Resolve the governance policy that gates actions in namespace.
resolve_id
Resolve an ID that may be a prefix. Tries exact match first, then prefix match.
resolve_require_approval_above_depth
v0.7.0 L1-8 — read governance.require_approval_above_depth from the namespace’s most-specific governance metadata blob, leaf-first.
resolve_skill_promotion_min_depth
v0.7.0 L2-6 — read governance.skill_promotion_min_depth from the namespace’s most-specific governance metadata blob, leaf-first.
restore_archived
restore_archived_for_caller
#940 (security-high, 2026-05-20) — caller-scoped restore variant. Mirrors restore_archived but constrains the INSERT-SELECT to rows whose metadata->'agent_id' JSON field matches caller (with the inbox-target carve-out: rows whose metadata->'target_agent_id' matches caller are also restorable by the inbox owner, matching the SAL [crate::store::is_visible_to_caller] visibility predicate).
revoke_agent_pubkey
Clear the Ed25519 public key bound to agent_id (#626 Layer-3, Task 1.3 / C5 — key revocation).
search
search_with_source_uri
v0.7.0 Provenance Gap 6 (issue #889) — search with optional reciprocal source_uri filter. When source_uri is Some(uri), the FTS search is post-filtered (in SQL) to memories whose source_uri column equals the supplied value verbatim. The partial idx_memories_source_uri index (created at v38) covers the lookup, keeping it O(log N) over the URI-keyed subspace.
set_db_mmap_size
Seed the process-wide mmap size for every subsequent open. Idempotent — first writer wins; later calls are no-ops (matches crate::quotas::set_quota_defaults).
set_embedding
Store an embedding vector for a memory.
set_embeddings_batch
v0.7.0 Wave-2 A5 (issue #853) — batched embedding writer.
set_embeddings_batch_reembed
#1598 — REPLACE-semantics sibling of set_embeddings_batch for the ai-memory reembed vector-space migration.
set_namespace_standard
Set the standard memory for a namespace, with optional parent for rule layering.
stats
strongest_attest_level_for_source
v0.7.0 issue #812 / #813 — return the strongest attest_level label across every outbound link rooted at source_id.
sweep_pending_action_timeouts
v0.7.0 K2 — pending_actions timeout sweeper.
sync_state_last_pushed
Look up this peer’s last-push watermark for peer_id. Returns None if we’ve never successfully pushed to them (foundation-era rows also return None because the column was added in schema v12).
sync_state_load
Load the full vector clock for agent_id — the set of (peer_id -> last_seen_at) this local agent tracks.
sync_state_observe
Record the latest updated_at this local agent has observed from peer_id. Monotonic by timestamp — older writes do not overwrite newer ones. Lazily creates the row on first observation.
sync_state_record_push
Record that local memories up to updated_at = pushed_at have been accepted by peer_id. Creates the row if it doesn’t exist; monotonic.
touch
Bump access count, extend TTL, auto-promote — atomic via transaction.
touch_many
Cluster-F PERF-6 — batched touch.
truncate_to_microseconds
v0.7.0 H6 (round-2) — truncate a DateTime<Utc> to microsecond precision. Companion of the same-named helper in store/postgres.rs:3539 (G3 fix); both ends of the link sign/verify roundtrip now collapse sub-microsecond digits BEFORE CBOR canonicalisation. PostgreSQL’s TIMESTAMPTZ stores microseconds — the SQLite path was lossless, but a link created on SQLite and later re-verified on Postgres (or vice versa via federation) would see the canonical RFC3339 string change shape on the storage hop and break the Ed25519 signature. Truncating at write time makes the shape stable across adapters. See store/postgres.rs:3520-3543 for the full design context.
update
update_with_archive_on_supersede
v0.7.0 Provenance Gap 5 (issue #888) — append-and-archive write path. Used by the MCP memory_update tool when the caller passes edit_source of llm or hook. Atomic: every step runs inside a BEGIN IMMEDIATE / COMMIT pair so a failure mid-way leaves the old row live (no partial supersede).
update_with_expected_version
v0.7.0 Provenance Gap 1 (issue #884) — optimistic-concurrency aware variant of update. When expected_version is Some(v), the update fails with a typed VersionConflict error if the stored row’s version is not equal to v. When None, the legacy last-write-wins behaviour is preserved (still bumps version on success). On a successful mutation the row’s version is monotonically incremented; the new value is observable on the subsequent read.
upsert_pending_action
v0.6.2 (S34): upsert a pending_actions row from a canonical PendingAction struct — used by sync_push to apply a peer-originated pending row so governance state is cluster-consistent. Preserves approvals and decision fields verbatim so re-plays converge. Uses INSERT ... ON CONFLICT(id) DO UPDATE because the originator’s id is stable across peers (unlike queue_pending_action which mints a fresh UUID per queue call).
validate_link_pre_create
v0.7.0 fix-campaign A3 (LINK-PARITY) — shared pre-create validator invoked by every link-write entry point.