Skip to main content

Crate ai_memory

Crate ai_memory 

Source

Re-exports§

pub use crate::quotas::GLOBAL_NAMESPACE;
pub use storage as db;
pub use governance as permissions;

Modules§

approvals
v0.7.0 K10 — Approval API (HTTP + SSE + MCP).
atomisation
v0.7.0 WT-1-B — substrate-level atomisation engine.
audit
Enterprise audit trail (PR-5 of issue #487).
autonomy
Full-autonomy loop — stacks on the Track A curator daemon (#278).
background
v0.7.0 QW-3 — daemon-side background tasks landed for the context-offload substrate primitive.
bench
Pillar 3 / Stream E — ai-memory bench workload runner.
cli
CLI command modules. Wave 5a (v0.6.3) extracted these out of main.rs so each handler can be unit-tested by capturing output into a Vec<u8> via CliOutput instead of literal println!s.
color
ANSI color output for CLI — zero dependencies.
confidence
v0.7.0 Form 5 (issue #758) — auto-confidence + shadow-mode + freshness-decay + calibration tooling. Closes the FORM 5 PARTIAL audit finding by adding deterministic auto-derivation, opt-in shadow-mode telemetry, half-life-driven freshness decay, and a per-source baseline calibration sweep on top of the legacy caller-provided confidence field. v0.7.0 Form 5 — auto-confidence + shadow-mode + calibration tooling (issue #758).
config
curator
Autonomous curator daemon (v0.6.1).
daemon_runtime
Daemon runtime — orchestration shell for the ai-memory binary.
embeddings
encryption
v0.7.0 (issue #228) — E2E memory content encryption at rest.
errors
federation
Federation autonomy — wires the quorum primitives from replication into the HTTP write path (v0.7 track C, PR 2 of N).
forensic
v0.7.0 L2-5 — forensic evidence bundle assembly + verification.
governance
handlers
HTTP handler module index. Per-domain handler code lives in the sibling sub-modules; this file is the public-facing re-export surface plus the inline test scaffolding.
harness
v0.7 Track B (B4) — Harness detection from MCP clientInfo.name.
hnsw
HNSW (Hierarchical Navigable Small World) vector index for fast approximate nearest-neighbor search over memory embeddings.
hooks
identity
Non-Human Identity (NHI) resolution for agent_id.
inference
Pluggable inference backend trait — issue #651 (RFC pulled forward from v0.8 per operator directive 28860423-d12c-4959-bc8b-8fa9a94a33d9, 2026-05-18).
kg
Knowledge-graph helpers — substrate-level graph utilities that operate directly on the memory_links table.
llm
LLM client — provider-agnostic chat + embedding surface.
llm_cli_wrap
Per-CLI-binary WrapStrategy table for the ai-memory wrap <agent> subcommand.
log_paths
User-configurable log directory resolution (PR-5 addendum, issue #487).
logging
Operational logging facility (PR-5 of issue #487).
mcp
MCP (Model Context Protocol) server for ai-memory. Exposes memory operations as tools for any MCP-compatible AI client over stdio JSON-RPC.
metrics
v0.6.0.0 Prometheus metrics. Exposed at GET /metrics by the daemon.
mine
Retroactive conversation import from Claude, ChatGPT, and Slack exports.
models
multistep_ingest
v0.7.0 Form 3 — multi-step ingest orchestrator (issue #756).
notification
v0.7.0 L2-3 (issue #668) — Reflection invalidation propagation.
observations
v0.7.0 Gap 3 (#886) — recall-consumption observation tier.
offload
v0.7.0 QW-3 — context-offload substrate primitive.
parsing
Input parsing modules for the Agent Skills substrate and future structured-document ingestion pipelines.
persona
v0.7.0 QW-2 — Persona-as-artifact engine.
profile
v0.6.4-001 — Profile resolution for the MCP tool surface.
quotas
v0.7.0 Track K, Task K8 — per-agent + per-namespace rate limits + storage caps.
recover
ai-memory recover-previous-session — fail-safe recovery of agent context from host-written transcript files.
replication
W-of-N quorum-write layer for the peer-mesh sync (v0.7 track C).
reranker
Cross-encoder reranking for search results.
runtime_context
v0.7.x (issue #1174 follow-up #1192 / #1196) — cross-surface RuntimeContext for substrate state that spans the HTTP daemon, the MCP stdio binary, and the CLI.
signed_events
v0.7.0 / H-track substrate — append-only signed_events audit table.
sizes
v0.6.4-005 — Static schema-size table.
storage
subscriptions
v0.6.0.0 — webhook subscriptions.
synthesis
v0.7.x Form 1 — online dedup-and-synthesis (Batman framework Form 1).
tls
TLS / mTLS configuration and verifiers for the HTTP daemon.
toon
TOON (Token-Oriented Object Notation) serializer for ai-memory.
transcripts
v0.7.0 / I-track substrate — compressed transcript storage.
validate
visibility
#951 (Track A QC sweep, 2026-05-20) — canonical is_visible_to_caller helper, non-sal-gated so both feature flag profiles share the same predicate. See module docstring for the drift history that motivated the consolidation. v0.7.0 #951 (Track A QC sweep, 2026-05-20) — single canonical is_visible_to_caller helper, available on both sal and non-sal builds.

Constants§

AI_MEMORY_HOME_DIR_NAME
Per-user ai-memory data directory name (~/.ai-memory) — home of reflection exports + persona artefacts (#1558 batch 6).
DEFAULT_NAMESPACE
v0.7.x (issue #1174 PR5 — pm-v3.1 namespace-sentinel sweep) — the default namespace for AI-NHI memory writes when the caller omits the namespace parameter. Bare value: "global".
EXPECTED_CLI_SUBCOMMANDS_DEFAULT
Variants in pub enum Command (src/daemon_runtime.rs) that COMPILE under the default build. The source file declares 82 variants; two (Migrate, SchemaInit) are #[cfg(feature = "sal")]-gated and excluded from default builds, leaving 80. (v0.7.0 #1443 added Expand for the ai-memory expand CLI parity surface, bumping 78 → 79; #1598 added Reembed for the ai-memory reembed vector-space migration, bumping 79 → 80.)
EXPECTED_CLI_SUBCOMMANDS_SAL
Variants in pub enum Command that COMPILE under --features sal (or sal-postgres, which implies sal in Cargo.toml). Equals the awk-canonical source-file count: every variant declared in the enum body (including Migrate + SchemaInit). v0.7.0 #1443 added Expand, bumping 80 → 81; #1598 added Reembed, bumping 81 → 82.
EXPECTED_PRODUCTION_ROUTES_COUNT
EXPECTED_PRODUCTION_UNIQUE_PATHS_COUNT
Number of distinct URL paths (multi-line-aware) registered by the production router. Derived via awk '/\.route\(/{in=1}in&&/"\/[^"]*"/{match($0,/"\/[^"]*"/);print substr($0,RSTART,RLENGTH);in=0}' src/lib.rs | sort -u | wc -l excluding the #[cfg(test)]-gated /slow slowloris route. Pinned by tests/route_count_invariant.rs so the docs surface count cannot drift silently. v0.7.0 multi-agent literal-sweep (scanner A, finding F-A4.1) — previously the 73 unique URL paths count was cited in 30+ doc sites with no const.
EXPECTED_TEST_ROUTES_COUNT
GIB
HEADER_AGENT_ID
HEADER_AI_MEMORY_SIGNATURE
HMAC signature header on signed webhook/approval callbacks (subscriptions.rs dispatch ⇄ handlers/approvals.rs verify).
HEADER_AI_MEMORY_TIMESTAMP
Timestamp header paired with HEADER_AI_MEMORY_SIGNATURE for HMAC replay-window checks.
HEADER_API_KEY
API-key auth header consumed by the HTTP daemon’s auth middleware (handlers/transport.rs) and SENT by every internal client (federation push/receive, CLI remote commands). Client and server must agree byte-for-byte — a drifted copy is a silent auth break (#1558 batch 4).
HEADER_CONTENT_TYPE
HTTP_BODY_LIMIT_BYTES
F-B6 — Axum production request-body cap (2 MiB).
INBOX_NAMESPACE_PREFIX
_inbox/ namespace prefix for agent-to-agent notification routing. Reserved-namespace convention; the recipient’s target_agent id is appended to form the canonical inbox namespace (_inbox/<target>).
KIB
META_KEY_AGENT_ID
metadata.agent_id — the NHI identity stamp written on every substrate row per CLAUDE.md §“Agent Identity”. Read by visibility predicates, governance rule evaluator, federation peer attestation, audit chain. Immutable post-write (preserved across update / dedup / import / sync / consolidate per identity::preserve_agent_id).
META_KEY_CONSOLIDATED_FROM_AGENTS
metadata.consolidated_from_agents — array of source authors, preserved on memory_consolidate (the consolidator’s id becomes agent_id; the original authors stay readable from this array). Documented at CLAUDE.md §“Agent Identity (NHI)” → “Special metadata keys”.
META_KEY_GOVERNANCE
metadata.governance — embedded governance policy blob (GovernancePolicy::from_metadata). Read by the substrate governance engine (db::enforce_governance) to evaluate rules before the canonical write path; honoured by Allow / Deny / Pending decision tree.
META_KEY_IMPORTED_FROM_AGENT_ID
metadata.imported_from_agent_id — original NHI claim preserved when ai-memory import restamps agent_id with the importing caller’s id (absent when --trust-source is passed). Documented at CLAUDE.md §“Agent Identity (NHI)” → “Special metadata keys”.
META_KEY_MINED_FROM
metadata.mined_from — source-format tag (claude / chatgpt / slack) stamped by ai-memory mine alongside the caller’s agent_id. Documented at CLAUDE.md §“Agent Identity (NHI)” → “Special metadata keys”.
META_KEY_SCOPE
metadata.scope — visibility marker (one of [MemoryScope::all_strs] at crate::models::namespace::MemoryScope). Controls which agents can see a memory via hierarchical namespace matching per Task 1.5. Memories without this key are treated as "private" by the query layer (see crate::models::namespace::MemoryScope::default()).
META_KEY_TARGET_AGENT_ID
metadata.target_agent_id — recipient NHI for memories that represent agent-to-agent shares / notifications. Read by the canonical visibility predicate is_visible_to_caller to permit the named target to see otherwise-private rows alongside the owner.
METHOD_INITIALIZE
METHOD_PROMPTS_GET
METHOD_PROMPTS_LIST
METHOD_RESOURCES_LIST
METHOD_RESOURCES_READ
METHOD_TOOLS_CALL
METHOD_TOOLS_LIST
MIB
MILLIS_PER_SEC
Milliseconds per second — for secs→ms conversions feeding wire/SQL surfaces that take milliseconds (e.g. postgres statement_timeout). u64 matches the *_timeout_secs config field type; i64/u128 callers cast at the use site like the SECS_PER_* family above.
MIME_JSON
PKG_VERSION
The crate version (compile-time CARGO_PKG_VERSION) as one named const — wire surfaces (capabilities, serverInfo, backup manifests, boot banners, webhook user-agent) all report it from here instead of nine scattered env! calls (#1558 batch 5).
RECALL_COSINE_GATE
F-B10 — recall cosine-similarity gate (relaxed 0.3 → 0.2 in v0.6.2 Patch 2, scenario-18; load-bearing per CLAUDE.md §“Recall Pipeline”).
RECALL_PRIMARY_CTX_BLEND
F-B9 — recall primary-context semantic blend weight. Named to disambiguate from ConfidenceTier::LIKELY_MIN (also 0.7, a different concept).
REDACTED_PLACEHOLDER
#1558 batch 5 wave 3 — canonical secret-redaction placeholder rendered by every Debug impl that masks credential material (AppConfig.api_key, [llm].api_key, ResolvedLlm.api_key, HooksSubscriptionConfig.hmac_secret, x25519 Keypair.secret, RuntimeContext.hooks_hmac_secret). One spelling, hoist-only; src/llm.rs keeps its own site per the vendor carve-out.
ROUTE_ARCHIVE
ROUTE_CAPABILITIES
ROUTE_HEALTH
ROUTE_INBOX
ROUTE_LINKS
ROUTE_MEMORIES
ROUTE_MEMORIES_BULK
ROUTE_MEMORY_BY_ID_TEMPLATE
ROUTE_METRICS
ROUTE_METRICS_V1
ROUTE_NAMESPACES
ROUTE_NOTIFY
ROUTE_PROMOTE_TEMPLATE
ROUTE_RECALL
ROUTE_SEARCH
ROUTE_SESSION_START
ROUTE_SUBSCRIPTIONS
ROUTE_SYNC_PUSH
ROUTE_SYNC_SINCE
SCORE_DISPLAY_ROUND_FACTOR
Rounding factor for similarity/score values surfaced on wire responses (HTTP handlers + MCP tools) — 1000.0 keeps three decimal places via (score * FACTOR).round() / FACTOR.
SECS_PER_DAY
SECS_PER_HOUR
SECS_PER_MINUTE
SECS_PER_WEEK
TEST_BODY_READ_CAP
F-B6 — test-side body read cap; pinned equal to the production limit so tests exercise the full 0..=2 MiB envelope production accepts (was an asymmetric 1 MiB across 90+ to_bytes(.., 1024 * 1024) call sites).

Functions§

ai_memory_version
FFI: returns the substrate’s Cargo.toml version field as a NUL-terminated UTF-8 C string with 'static lifetime.
build_router
Build the daemon’s HTTP axum::Router from the API-key middleware state and the composite app state.
build_router_with_timeout
v0.7.0 H7 (round-2) — variant of build_router that takes an explicit per-request wall-clock timeout. Composes a per-request timeout middleware so a slow-POST (slowloris-style) attacker cannot keep a handler scope alive indefinitely. Requests that exceed the timeout get a 504 Gateway Timeout response with a {"error":"request timed out"} body. The production daemon calls this with the value resolved from AppConfig::effective_request_timeout_secs (default 60 s); tests pass a short timeout to drive the timeout edge directly.
inbox_namespace
Build the canonical inbox namespace for a target agent id. Returns "_inbox/<target>" formatted via the INBOX_NAMESPACE_PREFIX const. Use this in place of inline format!("_inbox/{target}") so a future rename of the prefix (or addition of validation, normalization, etc.) touches one place. Closes scanner E finding F-E5 (#1436).