anda_brain 0.13.4

🧠 Anda Brain (ε€§θ„‘) β€” Autonomous Graph Memory for AI Agents
docs.rs failed to build anda_brain-0.13.4
Please check the build logs for more information.
See Builds for ideas on how to fix a failed build, or Metadata for how to configure docs.rs builds.
If you believe this is docs.rs' fault, open an issue.
Visit the last successful build: anda_brain-0.13.3

Anda Brain β€” Technical Documentation

Cloudflare Worker parity and limits are documented in the commit audit and trusted host contracts. The Worker supports source records, reviewed changes, recovery and processing fences; budgeted Recall, Wiki and learning runtimes remain unavailable. Worker-specific operation receipts, nullable usage, shared model deadlines and maintenance acknowledgements are documented in its host contracts; Rust API shapes are unchanged.

A dedicated LLM-powered memory management service that maintains a persistent Cognitive Nexus on behalf of business AI agents via KIP 2.0 (Knowledge Interaction Protocol).

Business agents interact entirely through natural language and a REST API β€” no KIP knowledge required.

Anda Brain is designed to be self-hosted (the hosted cloud service has been discontinued). For a complete agent built on Anda Brain, see Anda Bot.

Operational SleepTask and Watch updates require version guards. Failed host passes reach the model in assessment.settlement_errors.

Trusted host memory product contracts (v0.12.1)

The Rust product module provides Assertion-backed MemoryRecord projections, stable native revisions, explicit stance/lifecycle/storage state and typed Evidence source references. Space::product_records, product_record and product_source do not authenticate a user. The embedding host must enforce owner/source visibility before returning any record, preview, dependent identifier or source quote. A matching source digest is provenance, not proof that an inference is correct.

Space::ingest_product accepts a bounded, trusted SourceIdentity with parent conversation/session keys. Natural-language input cannot set that identity. product_prepare, product_commit, product_change and product_discard implement caller/operation-scoped immutable requests, fixed revision/preview digests and ten-minute previews. Correct supersedes the caller's wrong claim with a new one that keeps the corrected world interval; WorldChange adds one claim from now and lets temporal succession end the old value; Misrecorded is refused (unsupported_capability) here: recording repair runs through the Memory Interface revise intent. Each writes a user-statement Evidence and an Activity; none rewrites a Concept label or creates an illegal cross-Proposition supersession. Undo is another conditional change.

Suppress archives and Delete purges the declared bounded closure: selected Proposition/Assertions, cited inputs and recorded referrers. Unknown sources, Concept cascades, retention holds and closures above 128 elements are rejected. A durable source exclusion and processing epoch are admitted before mutation; tracked native work survives a cancelled API waiter and resumes before a reloaded Space is exposed. Stale Formation/Maintenance/Notes writes are fenced. Managed changes clear processing Notes and miss caches, stop old processor histories from entering new contexts and restrict automatic KIP readers to current active state. Trusted owner audit APIs remain distinct. Recall rechecks its captured epoch before returning context.

Managed changes also exclude history from budgeted Recall and fence timeout/turn-limit outputs. Pagination started before the change must restart; newer continuations remain usable. Deletion clears copies of erased content from saved previews/corrections and discards affected uncommitted intents while retaining operation identities and digests. An independent correction whose claim and Evidence survive keeps its source text. Correction-source reads check that the Evidence still exists with the matching payload. Source-backed status verifies the captured conversation message and observation time, or a confirmed correction receipt; a matching client-key spelling alone is insufficient. Direct /memory/forget also clears saved previews that refer to the purged graph elements.

Removal does not erase an embedding application's original chat/files/logs/backups, other independent graph records, already delivered context or provider copies. Minimal source keys/digests survive for replay suppression. Replacing the database with an old backup without its current exclusions is not a supported deletion-preserving rollback. The host must also reset its own injected Notes and prevent excluded sources from being imported through later conversation chains.

MemoryRuntime::{create_record_watch,record_watch,cancel_record_watch} is a narrow recipient-owned subscription adapter using an opaque authenticated RuntimeCaller. Creation persists identity and arms only the initial generation. It provisions a cancellation grant restricted to that one Watch for the configured controller, with a durable no-regrant marker. Cancellation archives the Watch rather than forging its protected status; retries never re-arm it. Already delivered questions are separate work and remain visible. A revoked grant is not restored by subscription retry or bootstrap. These Rust methods are not new generic model tools or native HTTP product routes.

RuntimeConfig::validate performs static validation without loading a Space, running models, probing services or provisioning grants. The optional learning runtime reports product_readiness for installed isolated workflow bindings, including missing services, mismatched pins, missing reviewed calibration and approval gates. Ready is not business deployment authority; native per-item service/permission checks remain mandatory.

Anda Bot consumes these contracts from the published crate and keeps one shared DB/KIP/Core type identity. No empirical learning improvement or full cost accounting is implied by these mechanism tests.

KIP 2.0 update

The service tracks KIP 11a82ec and kip://profiles/cognitive-memory@2.0.0 (revision sha256:734aa0fd…; only the digest names the revision). Rust uses anda_kip, Cognitive Nexus and AndaDB 0.14; the Worker uses @ldclabs/kip-do 0.14. Spaces activated under the earlier 2.1.0 draft are not migrated. A changed world is one new Assertion and temporal succession ends the old value; claims carry asserted_at from their source's observation time; options are Concepts typed by their kind (the Profile has no Preference type); decay is computed at read time rather than swept; Skills point at current_trial / current_evaluation. Skill behavior is an immutable SkillRevision; Watch progress and task leases use protected Nexus operations. The former family-rate Skill promotion rule has been removed. Without configured independent observers, frozen trials and replayable evaluations, procedures remain unproven and skills.unsupported_reason reports the limitation. Existing Brain endpoints remain available. Both adapters now also serve the KIP Memory Interface at the memory_basic level β€” POST /v1/{space_id}/memory with the five intents observe, recall, revise, feedback, forget, staged sources, idempotent receipts, after barriers, seven-channel coverage, recording repair for a misrecording and governed forgetting (see API). memory_experience, memory_learning and durable_brain_runtime are not advertised. Scoped feedback remains in scope; source erasure includes owned narrative memory and reports incomplete ownership explicitly. Recall discards summaries based on invalidated reads.

Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   Business Agent    β”‚  ← Focuses on business logic & user interaction
β”‚  (No KIP knowledge) β”‚    Only speaks natural language
β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
         β”‚ Natural Language / REST API
         β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚      Brain          β”‚  ← The ONLY layer that understands KIP
β”‚   (LLM + KIP)       β”‚    Three agents: Formation / Recall / Maintenance
β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
         β”‚ KIP (KQL / KML / META)
         β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  Cognitive Nexus    β”‚  ← Persistent Knowledge Graph (backed by AndaDB)
β”‚  (Knowledge Graph)  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Features

  • Zero KIP knowledge required β€” Business agents interact through natural language and a simple REST API.
  • Persistent, structured memory β€” Facts, preferences, relationships, events, and patterns encoded into a knowledge graph.
  • Three operational modes β€” Formation (encoding), Recall (retrieval), and Maintenance (consolidation & pruning).
  • Multi-space isolation β€” Each space has its own independent database, knowledge graph, and conversation history.
  • Triple serialization β€” Supports JSON, CBOR, and Markdown for request/response payloads (negotiated via Content-Type / Accept headers).
  • Built-in MCP server β€” MCP-capable agents can use Anda Brain through Streamable HTTP or stdio tools without writing REST glue code.
  • Pluggable storage backends β€” Local filesystem, AWS S3, or in-memory (for development/testing).
  • MIB offline regression β€” Product timelines and business outcomes are evaluated by the independent MIB runner; Brain retains online diagnostics and native learning-mechanism tests.

Versioned wiki (wiki feature)

Wiki stores immutable Markdown versions with CAS updates and verifiable byte-range citations. ACL checks and content selection share one document snapshot; search candidates are checked against current document state. Published parent chains define history. Native wiki writes survive cancelled request waiters and drain before Space close or eviction.

Document outlines follow ATX headings (#–######) independently of BM25 chunks. Sections include child headings, and all text reads are capped at 256 KiB. OKF import/export preserves unknown YAML values through edits; comments, ordering and formatting are canonicalized. Imports replace file-owned fields and preserve native ACLs and unrelated host metadata.

Optional WikiDigest remains disabled by default. It reconciles durable document generations, including archive/restore and ACL changes, and reports failed documents without retiring their pending work. Metadata-only edits reuse prior results. Old claims are withdrawn only after explicit absence reviews covering every body batch, or withdrawal of the source; omitted or unknown model output is not negative evidence. Concurrent edits fence out stale writes. This is a mechanism contract, not a real-model quality claim. See the English API and δΈ­ζ–‡ζŽ₯口.

Agents

Formation β€” Memory Encoding (formation_memory)

Receives conversation messages and encodes them into structured memory within the Cognitive Nexus via KIP.

System prompt: BrainFormation.md

Processing pipeline:

  1. Receives FormationInput (messages + optional context + timestamp).
  2. Creates a tracked Conversation record (status: Submitted β†’ Working β†’ Completed | Failed).
  3. LLM classifies what the conversation is worth keeping, into the products the Cognitive Memory Profile defines: Evidence for what was observed, Proposition + Assertion for a truth-sensitive claim and whose stance it is, Event for what happened, Experience + steps when the process itself can teach future behavior, Commitment for a future obligation, and Insight / SelfModel candidates. The empty write is a valid answer.
  4. Grounds against existing memory before writing (SEARCH before CREATE).
  5. Encodes it through the execute_kip tool, which on this path accepts KQL and META in full and only the cognition subset of KML β€” administering memory in bulk (UPDATE, SET RETENTION, PURGE, MERGE CONCEPT, and TRANSITION to archived or tombstoned) is refused to a pass whose whole input is an untrusted conversation.

Key behaviors:

  • Sequential processing with automatic queue draining β€” new conversations are picked up after the current one completes.
  • Atomic single-conversation processing via processing_conversation flag.
  • Inputs of at least 10,000 estimated tokens receive one focused semantic review before completion, within the same turn/time budgets. It reuses tool receipts, reads only unresolved records, and repairs demonstrated omissions or misrepresentation. No changes is a valid result; missing source context is reported as a coverage limit. This self-review does not guarantee exhaustive processing or establish measured accuracy gains.
  • New vocabulary is a draft (KIP Β§20.16). A command naming an undefined type or predicate is refused with SchemaSymbolNotFound, so Formation sends DEFINE CONCEPT TYPE / DEFINE PREDICATE with a literal name and description in a request of its own, before the MUTATE that uses the symbol. The host checks the name's shape, caps a space at 512 symbols of its own, runs the request's DEFINEs independently (a name that already resolves answers SchemaSymbolConflict and stops nothing), and queues one review_schema SleepTask per new symbol. The declare_memory_symbols tool remains for one release as a deprecated shortcut that drafts bare names the same way.
  • Claims taken from a captured message carry that message's time: the gate refuses an Assertion citing :msgN without at (or valid.from), except the Brain's own inferences. A MnemonicState.memory_strength must be written with last_metabolized_at and the host-bound :strength_policy, so the engine can compute effective_strength.

Recall β€” Memory Retrieval (recall_memory)

The optional RecallInput.budget (or an enforced memory_policy.recall_budget) selects a host-packed JSON memory response instead of free-form synthesis. The whole packet and cumulative normalized planning input use the pinned o200k_base@tiktoken-rs-0.12 counter. Required commitments/warnings precede optional items, failed coverage is explicit, and diagnostic histories/artifacts cannot bypass the packet limit. Existing requests without a budget policy keep the normal flow below. Question-specific search supplies candidates before selection. Compact views keep provenance and detail references; terminal commitments no longer consume mandatory space. Small budgets can deliver partial candidates with explicit coverage/warnings while preserving required constraints. See Recall budget contract.

Translates natural language queries into knowledge graph lookups and returns synthesized answers.

System prompt: BrainRecall.md

Processing pipeline:

  1. Receives RecallInput (query + optional context).
  2. Analyzes query intent (entity lookup, relationship traversal, attribute query, event recall, pattern detection, etc.).
  3. Grounds entities to actual graph nodes (resolves ambiguity).
  4. Executes structured KQL/META reads; belief questions go through BELIEF projection rather than raw FIND, because a Proposition existing is not the Proposition being true.
  5. Iterative deepening β€” follows up with additional queries if needed, up to the space's recall_max_rounds (default 7).
  6. Synthesizes results into a coherent natural language answer, reporting contested as contested and insufficient as insufficient.

Available tools:

  • execute_kip_readonly β€” KQL and META only, enforced on what each command parses to. Recall has no write tool at all, and reading never reinforces what it read.
  • wiki_search / wiki_read β€” with the wiki feature; absent otherwise.

Maintenance β€” Memory Metabolism (maintenance_memory)

Consolidates, prunes, and optimizes the knowledge graph during scheduled or on-demand cycles.

System prompt: BrainMaintenance.md

Processing phases (full scope):

  1. Assessment β€” Audit memory health (read-only): DESCRIBE PRIMER, pending SleepTasks, unconsolidated Events and Experiences, orphans, stale events, plus the runtime's own assessment block (per-predicate census, correction tallies, armed and fired Watches, the current space_seq).
  2. SleepTask Processing β€” Handle queued work under the Profile's classes: consolidate, review_conflict, review_skill, resolve_identity, review_retention, review_derived, refresh_self_model, inspect_quarantine.
  3. Semantic consolidation β€” Compress clusters of Events, Experiences and Evidence into derived Assertions, keeping Activity lineage back to the sources. A summary is not a new epistemic root.
  4. Procedural consolidation β€” Compare successful and failed Experiences and compile an unproven Skill with an immutable SkillRevision. Its task_family identifies comparison candidates; only a configured trial/evaluation pipeline can confer validated standing.
  5. Identity review β€” Review same_as suspicions, then MERGE CONCEPT, which is non-destructive: the source survives as merged historical identity.
  6. Contradiction and derivation review β€” Different actors' disagreement coexists; only an actor's own revision supersedes. After a revision, the settlement walks LIST DEPENDENTS and hands the agent each revised root with its dependents (assessment.revised_roots); the agent flags what no longer holds stale.
  7. Mnemonic metabolism β€” decay is computed, not written: the engine derives strength at read time from memory_strength (base), last_metabolized_at (anchor) and a pinned strength_policy, and a missing input is unknown. The agent writes a new base only on an explicit signal (a decision's used_refs, a correction). Never confidence; a fact nobody has asked about lately is no less credible.
  8. Commitments and Watches β€” Review outstanding obligations and attention. The settlement raises each due pending/blocked Commitment without a Watch natively, with one commitment_review Activity keyed commitment_review:<id>:<due_at>: a replay raises nothing and only a new due_at raises it again. Maintenance reviews review_schema tasks and proposes promotions; it never defines or promotes a symbol. Nexus advances structured Watches under generation/CAS/coverage checks; prose conditions remain deferred without a semantic evaluator. No model completion attests change-stream consumption. See the Watch contract below.
  9. SelfModel and WorkingState refresh β€” Consolidate identity from evidence rather than from the latest conversation, and rebuild the digest the next waking session resumes from, stamped with the basis_seq it was built at.
  10. Retention review β€” Decide what should carry an expiry and write it with SET RETENTION; the full settlement's sweep is what makes that write mean something. See "Retention expiry" below.

Skill lifecycle transitions require the explicitly configured protected host evaluation pipeline. Standard model-driven maintenance does not grant standing. See "Procedural candidates remain unproven" below.

Key behaviors:

  • Single-execution guard β€” only one maintenance cycle can run at a time per space.
  • Non-destructive principle β€” archives before deleting, and weakens mnemonic accessibility rather than removing (never epistemic confidence).
  • Async execution β€” returns immediately with conversation ID; actual processing in background.
  • Two triggers, not one. Counting formation conversations paces a space that is being written to (daydream every 21, quick every 42, full every 168); a 24-hour clock covers one that is not. Without the clock a space that stopped ingesting stopped metabolizing entirely β€” no Commitment review, no retention expiry, no self-test β€” which is not what "scheduled, threshold, or change-driven" means. The clock fires from the background flush pass for resident spaces and on load for spaces that had been evicted; a space that has never formed anything is never due.

Memory policy: each space carries an evolvable MemoryPolicy (stored in the memory_policy extension, set via update_space) that holds the numeric knobs of memory behavior β€” stale-event threshold, backlog targets, and (from later phases) self-test and recall parameters. The former decay factor and floor are still accepted for stored-policy compatibility but nothing reads them. Maintenance cycles without explicit parameters run under the space's policy; an absent policy means the compiled-in defaults, so setting nothing changes nothing. The policy is the evolution genome of docs/memory_evolution_plan_cn.md (module M-P).

Deterministic settlement: before each maintenance cycle the runtime records newly superseded Assertions as corrections and aggregates them per asserting actor into the source_reliability extension; full cycles also refresh the per-predicate census and archive records whose retention expired. Both reach the Maintenance prompt as its assessment block. There is no disuse sweep: decay is computed from base, anchor and a pinned strength policy when a read is evaluated (KIP Spec Β§59.1, Profile Β§6.1, Β§18), so idle memory costs no writes, and a missing strength is unknown rather than a 0.5 default. Nothing ever decays an Assertion's confidence: a fact nobody has asked about in a month is no less credible. The last settlement report is stored in the memory_settlement extension.

Reading does not reinforce. Every completed recall still records which graph entities it surfaced, into an off-graph usage ledger (memory_usage collection) that the dream self-test, the health metrics and the scenario diagnostic inspection reads. That record stops there. An earlier design closed the loop β€” settlement raised the recalled Concepts' memory_strength by a recall_reinforcement gain β€” and that is precisely what the reference Recall policy forbids (Β§1 "MUST NOT ... change memory_strength, increment recall counters", Β§32, invariant 2 "Read does not reinforce memory"). Deferring the write to maintenance did not make reading stop reinforcing; it only moved where the reinforcement was written from. So the writeback is gone: a recalled memory earns no gain and buys no exemption from the next sweep. Retrieval is observed, not rewarded β€” which is also the difference between a memory system and a popularity contest. The recall_reinforcement policy knob is retained for stored-policy compatibility and does nothing.

Watch progress is protected Nexus state. Create a Watch as disarmed, then call the internal memory_runtime tool with arm_watch, its exact id and current _system.version. Arming captures an authorization view and creates a fresh WatchState.arm_generation. Settlement advances structured selectors through a bounded authorized change page using the current overall version and generation. Silence requires complete coverage through the deadline; a matching silence Watch ends as expired, counted in the legacy disarmed report field. Native advancement atomically commits fired, a watch_fire Activity and a protected wake in Nexus. Its response retains status/coverage/receipt and identifies the fire and wake. Repeated native requests replay the same receipt; silence uses a fixed deadline sequence. An independent, bounded scheduler now discovers registered Spaces through a persistent directory, resumes after eviction/restart, and uses the same service as the maintenance sweep. Explicitly installed ActionBindings add bounded four-way decisions and fenced dispatch; without bindings there are no action model calls or outward sends. Semantic Watch models have a separate explicit binding. See runtime setup, action contracts and recovery. The runtime API exposes authenticated inbox/response/outcome routes plus MCP read/response tools. BRAIN_RUNTIME_CONFIG selects a compiled durable inbox adapter; observation intake requires separately mapped signed observer credentials and preserves learning's single-writer/cutoff rules. Native wake leases and completion are trusted host APIs. Spaces containing native attention state cannot be forked with those operational identities; eviction/reopening the same Space remains supported. Text conditions, including mixed selector/text objects, stay deferred without a configured semantic evaluator. The semantic Watch runtime provides a bounded, pinned Chat Completions adapter and trusted callback interface using immutable native pages outside the Nexus lock. Unknown/omitted/timeout/truncated results retain the original coverage; replay and purge follow native Artifact permissions. See SEMANTIC_WATCH_RUNTIME.md and semantic.runtime.example.json. A completed maintenance model call never advances a Space-wide consumption watermark. An armed Watch without WatchState needs a reviewed re-arm; the scheduler never auto-rearms it. Firing grants no external authority.

Procedural candidates remain unproven. Skill.current_revision selects an immutable SkillRevision whose revision_of points back to the Skill. Both can be created atomically. The internal memory_runtime tool computes the canonical SHA-256 digest of all revision attributes except behavior_digest; Nexus verifies it. No model plan can write TrialRecord, EvaluationRecord, AttemptRecord, OutcomeRecord, the computed GradingState, a Skill's current_trial / current_evaluation, or the computed lineage fields. Same-family outcomes are merely comparison candidates; no automatic baseline or grade is inferred. Settlement preserves the historical counter fields at zero because Full Maintenance does not execute business trials. skills.unsupported_reason explains the boundary, while configured deployments also return the independent scheduler's skills.runtime status. Historic counters or adopted labels are not validated learning evidence.

Contextual source trust

The optional trust startup binding uses independently verified, context-tagged source Assertions to prepare reviewable calibration proposals. The first method measures binary factual accuracy, not operational success or forecast probabilities. There are no statistical defaults or implicit governance grants. A qualified governor can apply one exact actor/predicate/context rule through the native atomic proposal/control/audit API; other settings and Assertion confidence remain intact. Duplicate roots/claims, missing material, corrections, revocation and version conflicts cannot silently create another trust step. Restoration appends a new protected version. See TRUST_RUNTIME.md and the disabled template. Real instrument/method calibration remains a separate MIB validation gate.

Native learning contracts

With the Rust learning feature, anda_brain::learning provides PairedTrialPlan, ExecutionContract, PairedRule, and register_paired_rule. A trusted host freezes the plan as an artifact before baseline execution, uses its pin for both arms' AttemptRecord.selection_policy and TrialRecord.parameters, and registers the rule once per Nexus instance (including after restart). attempt_context() and comparability() build the pinned KIP fields.

The anda-brain:paired-bounded-v2 rule compares one candidate revision against a stable task policy with the same factual memory, model, tools, budget and task/state/seed pairs. It requires the entire predeclared cohort and a one-sided Hoeffding lower bound above the positive practical-improvement margin, and an absolute candidate failure-rate ceiling. The observer configuration binds the workflow contract and the complete attempt budget. Missing treatment outcomes count as failure; missing or unknown control outcomes leave the comparison insufficient. Duplicate pairs/observations, changed pins, or extra applied Skill revisions are rejected. A new monitoring trial retains the original acquisition through AdoptionBasis; native tests verify adoption, subsequent revocation and rejection of re-entry using the old trial. Multi-Skill bundles, adaptive stopping and filtering a window out of one trial's ledger are not supported. Parameters have no production defaults and require calibration.

ExecutionContract pins tool/time/token ceilings, cutoff and the review deadline. The host must call validate_settlement() before a final verdict and enforce expiry at read time: the current Nexus evaluator input does not contain the EvaluationRecord cutoff. OutcomeRecord has no custom cost fields, so the trusted verifier checks bounded success and retains measurements in Evidence payloads. workflow_contract() supplies the first resettable task-family contract. See the frozen workflow contract. The previous v1 evaluator digest is rejected rather than assigned these new semantics.

Space::learning() now provides explicit registration, frozen enrollment, persistent dispatch/recovery and separately authenticated Outcome ingestion. It uses native leases and dispatch authority checks; no executable authority or Skill standing is assigned automatically. The host supplies the real executor and observer. It can call the bounded drive step directly or install explicit automatic bindings through runtime startup configuration. Compilation deploys no binding. The host's settle step now performs fixed-cutoff native comparison and atomic standing updates. Persistent reviews, new monitoring trials, independently authenticated safety revocation, and current read-time recommendation checks are implemented. Recall's internal read-only check_procedure_status tool reports these checks and does not grant execution authority. The learning runtime guide documents the compiled HTTP adapter, calibration approval, separate scheduler, 1–32 hot job capacity, retained history pages and terminal archival. Archived records remain available for applicability, review and safety revocation. The runtime implementation exposes the trusted host interfaces. The native tests use deterministic fixture outcomes to verify KIP transactions, not to claim empirical learning. Run them without a model provider:

RUST_MIN_STACK=16777216 cargo test -p anda_brain --lib --features learning learning::

Isolated experiments

With the Rust experiments feature, the host-only Experiment owner supplies isolated stores, quiescent immutable snapshots, per-conversation completion waits, monotonic business time, session boundaries, and cost receipts with explicit unknown values. It enables Nexus's non-default simulation host API for lifecycle expiry; authentication, lease and audit clocks remain real. No HTTP/MCP clock override or MIB adapter is exposed. Notes now persist under each Space's engine/ object-store prefix and are included in experiment snapshots. See the experiment API and MIB integration.

Experiment::create_with_recall_budget pins a forced Recall-budget policy before the run is exposed, including across snapshot forks and session boundaries. audit_procedures() supplies a bounded native inventory for evaluator-side before/after checks. It does not establish applicability or execution permission. See validation and remaining bindings.

MIB integration

The sibling Anda Bot mib feature provides an isolated loopback host before production home/daemon initialization. Its agent endpoint is /mib-agent/v0.1; its memory backend endpoint is /mib-memory/v0.1. Each run has a separate store and business clock. Formation/Maintenance wait for exact terminal records, repeated requests preserve their original result, and current-task tool replies remain available in no-memory mode. See the Bot host contract and MIB backend contract.

The longitudinal harness requires explicit normal/no-memory/ungated capabilities, matched business identities and fixed budgets. The current Bot provides persistent/no-memory modes; native normal/ungated business bindings remain pending. Unknown costs stay unknown, and engineering fixtures never establish model-learning success. The evaluator-only learning_audit reads bounded native inventories (256 items per kind, 4 MiB total projection); an incomplete count cannot prove absence. It never grants applicability or execution permission and is not fed back to Formation. Complete accounting and real provider calibration are separate acceptance work.

Task work requires a lease. The internal tool's lease_task operation acquires or renews a five-minute lease under the runtime Principal. After re-reading the version, maintenance commits terminal task state and outputs in one guarded MUTATE. WatchState and LeaseState cannot be written by model KML. External dispatch uses explicit Rust host bindings and the separate action gate; none are installed by default. memory_runtime/status reports current configuration. Runtime authentication, tool capabilities and evaluator code never come from model-generated content.

Current basis matters. Recall loads a fresh Primer because policy, trust and identity can change independently of vocabulary. A stored WorkingState or bare basis_seq cannot override computed dependency validity. Derived refreshes must retain their actual read pins, context and ProjectionBasis; incomplete coverage or unavailable replay material remains explicit. Every Formation, Recall and Maintenance model call includes the complete anda_kip::KIP_SYNTAX, Cognitive Memory Profile, applicable role cards and deployment policy in its system prompt. The same assembly applies to budgeted Recall and instance-specific section A overrides; experiment prompt identities include this assembled static content. The syntax comes directly from the pinned crate, without hand-maintained copies. This adds about 40 KiB of syntax text to each request. Budgeted Recall counts the entire system prompt on every planning pass toward its cumulative input budget; if it cannot fit, it reports recall_context_budget_exhausted without calling the model or dropping the syntax. The full language reference grants no additional permissions: Recall remains read-only and model writes retain their host gates. All three agents can read additional compiled-in KIP documentation through the internal, read-only kip_reference tool. Markdown paths are source citations; they do not require files beside the executable or network access. document=index lists document IDs, section=index lists exact Markdown headings, and section=null reads a document. Syntax topics also accept kql, kml, meta, and envelope. Start at offset=0, then follow next_offset with the same document/section; each page contains at most 8 KiB of UTF-8 text. The catalogue includes the specification, consistency contracts, invariants, learning architecture, grammars and wire schemas; unlisted background/translation links are citations only. Reading a reference grants no host capability. Budgeted Recall counts these calls and their planning input against its existing limits; reference pages never become memory packet items or attest retrieval coverage. The legacy memory_runtime syntax operation remains available to writing agents.

The reference supplement is generated from anda_kip 0.14.0, the release Cargo.lock resolves; public crate constants are reused instead of copied. To refresh the supplementary files, set ANDA_KIP_SOURCE to the matching published crate directory (the script refuses one that differs from Cargo.lock) and run node scripts/sync-kip-reference.mjs (or --check to verify without writing). The generated manifest records source hashes, and tests check both the supplement and exported crate documents against it. Do not hand-edit these reference assets.

Retention expiry: two clocks say when something should stop being kept, and they are not the same clock. An Assertion whose valid_time.until has passed is expired for a read at a later time β€” computed when the read is evaluated (Β§14.3), never stored and never swept, so FOR TIME in the past still sees it. A full settlement acts on the other clock: an element whose retention.expires_at has passed is archived: out of ordinary recall, still readable, still referenced. Purge is deliberately unreachable from here β€” erasure over a set nobody enumerated is the largest irreversible action this service can take, and a scheduled cycle is not where that decision belongs; POST /memory/forget enumerates its target and purges that. A legal hold stops the sweep that authorized it, and the retention block of the settlement report says how many were held, refused and left for the next cycle rather than reporting only what it managed to archive.

The explicit forget endpoint accepts all five KIP element kinds (C-*, P-*, A-*, E-*, X-*), including captured message Evidence. Its report counts each purged kind and retains per-entity refusals such as legal holds. It erases selected graph records; conversation, wiki and external copies retain their own lifecycles.

Known scale ceiling: the correction discovery and self-test sampling passes use unconstrained full-scan KQL, and the engine caps full-scan solutions at 65,536 regardless of LIMIT. On graphs past ~65k propositions these passes stop working; the failure is loud (log::error + correction_scan_error in the settlement report and memory_status), but the fix β€” predicate-sharded scans β€” is not implemented yet. Watch those report fields in production.

Single writer per space: the usage ledger, settlement, self-test, shadow, and negative-cache locks are in-process (tokio::Mutex / atomics), like the formation processing flag they follow. Sharding assigns each space to exactly one process β€” do not point two instances at the same space's storage: concurrent ledger writes can duplicate rows, and the miss-cache clear race guard does not cross processes. (The graph-side correction_settled fence stays safe either way.)

Dream self-test (self-repair): after each maintenance cycle completes, the runtime samples recent memories with no usage evidence, generates one natural probe query per memory (a single LLM call, budgeted by MemoryPolicy.self_test_queries_per_cycle), and checks deterministically whether search actually surfaces them. Unfindable memories become pending review SleepTasks (source memory_self_test) that the next full cycle re-encodes with aliases and richer descriptions. Self-test retrievals count only into the ledger's isolated self_test_count β€” the brain testing itself never reinforces its own memories. The pass report lives in the memory_self_test extension and surfaces as the groundability graph stat.

Metamemory: search_exhaustive reports optional search-window coverage; missing coverage is unknown. A search miss is not a negative BELIEF, and only explicit exhaustive misses enter the cache. POST /v1/{space_id}/probe answers "do I know anything about this?" with pure search β€” no LLM, no recall cost. Queries that find nothing are remembered in a negative-knowledge cache (cleared whenever formation completes, 1h TTL backstop), so agents stop paying to hit the same wall. The intended contract: probe first, and only pay for a full recall when found is true.

Memory observability: GET /v1/{space_id}/memory_status returns incrementally-maintained counters (recalls, probe hits/misses, self-test groundability, corrections, decay, forget) plus derived rates (probe hit rate, correction rate, mean self-reported uncertainty, maintenance tokens per recall β€” the memory-ROI proxy), graph counts including the predicate_types schema-sprawl indicator, and the latest settlement / self-test / shadow reports. Writers bump counters at write time; reading the status never runs heavy queries. Full-scope settlements also refresh a per-predicate link census, reported as last_schema_audit and handed to the Maintenance prompt as assessment.predicates β€” with the per-actor correction tallies as assessment.source_reliability β€” so the predicate-merge and contradiction guidance has real numbers rather than the model's impression of them.

Shadow evaluation (safe policy canary): POST /v1/{space_id}/management/shadow_eval compares a candidate MemoryPolicy against the current one on the production distribution: the space is forked twice into isolated in-memory stores (baseline vs candidate policy), both forks are settled, recent real recall queries are replayed on each, and the judge blind-compares the answers with deterministic A/B order alternation. The live space is only read β€” replays can never pollute its conversations, usage ledger, or metrics. The report (wins/ties/samples/usage) persists in the shadow_report extension; promotion stays human: read the report, then update_space with the candidate policy if it won.

Offline regression and instance configuration

The Rust anda_brain::eval API and the anda_brain eval CLI, including --optimize, --mine, validation/report modes and their fixture profiles, have been retired. MIB owns the migrated product regressions. Brain retains its online self-test, /probe, citations/metadata, usage and correction ledgers, shadow diagnostics, isolated experiment controls and native learning runtime. The separate wiki retrieval corpus remains at evals/wiki/retrieval.json.

From the sibling MIB checkout, run the public regression contracts without a model:

python scripts/check-brain-product-regression.py --output-dir /tmp/brain-product-regression

For a configured business Agent, use MIB's normal submission path:

python -m mib_runner benchmark \
  --profile profiles/MIB-Brain-Product-Regression-0.1-Dev.json \
  --schema schemas/mib-scenario.schema.json \
  --submission /absolute/path/agent.json \
  --output-report /tmp/product-real.report.json
python -m mib_runner verify-score /tmp/product-real.report.json

The contract fixture verifies the harness and its oracle, not model quality. The actual normal/ungated learning bindings and three-arm provider runs remain separate pending work. The MIB migration guide records the nine product goals, removed Rust APIs and validation evidence.

Memory policies come only from each Space's persisted MemoryPolicy or the compiled defaults. UpdateSpaceInput.memory_policy remains the configuration entry point; there is no process-global policy override. Trusted Rust hosts can configure deployment prompts before sharing an AppState or opening a Space:

use anda_brain::agents::prompts::{AgentPrompts, PromptTarget};

let prompts = AgentPrompts::default().with_deployment_section(
    PromptTarget::Recall,
    "# A. Deployment contract\nYour reviewed deployment instructions here.",
)?;
let app = app.with_agent_prompts(prompts)?;

The supplied text replaces only section A, is limited to 128 KiB, and must start with # A.. The compiled KIP reference prefix is retained verbatim. The prompt configuration is immutable and inherited by agent instances and isolated forks; snapshot identity checks include its actual contents. active_prompt() now returns compiled defaults only. No HTTP/MCP prompt mutation endpoint is added. Prompt configuration is host-owned and must be supplied again at startup; per-Space MemoryPolicy remains persisted.

API Endpoints

Detailed API docs (with TypeScript request/response types):

Method Path Description Auth Scope
GET /favicon.ico Favicon β€”
GET /apple-touch-icon.webp Apple touch icon β€”
GET /info Service info (name, version, sharding) β€”
GET /SKILL.md Skill description (Markdown) β€”
GET /v1/{space_id}/info Get space status & statistics read (CWT or space token)
GET /v1/{space_id}/formation_status Get formation status (lightweight endpoint for monitoring formation progress) read (CWT or space token)
POST /v1/{space_id}/formation Submit messages for memory encoding write (CWT or space token)
POST /v1/{space_id}/recall Query memory with natural language read (CWT or space token)
POST /v1/{space_id}/recall_structured Recall with machine-readable provenance (citations, found, uncertainty) read (CWT or space token)
POST /v1/{space_id}/probe LLM-free metamemory existence check with negative-knowledge caching read (CWT or space token)
POST /v1/{space_id}/memory/pin Pin/unpin a memory (a pinned retention class) write (CWT or space token)
POST /v1/{space_id}/memory Memory Interface: observe / recall / revise / feedback / forget recall read; others write
POST /v1/{space_id}/memory/sources Stage a captured source for the Memory Interface write (CWT or space token)
GET /v1/{space_id}/memory/receipts/{receipt_ref} A Memory Interface receipt's current progress read (CWT or space token)
GET /v1/{space_id}/memory/plans/{plan_ref} A forget's ErasurePlan and host surfaces read (CWT or space token)
GET /v1/{space_id}/memory/attention Attention recall: fired Watches and due Commitments after a kept cursor read (public read allowed)
POST /v1/{space_id}/memory/forget Privacy-grade deletion (dry-run supported; physically removes, not archives) write (CWT or space token)
GET /v1/{space_id}/memory_status Memory observability: usage/probe/self-test counters, rates, graph counts read (CWT or space token)
POST /v1/{space_id}/management/shadow_eval Compare a candidate memory policy on forked copies (recent-recall replay) write (CWT)
POST /v1/{space_id}/maintenance Trigger maintenance cycle write (CWT or space token)
POST /v1/{space_id}/execute_kip_readonly Execute a KIP request (read-only mode, suitable for queries) read (CWT or space token)
GET /v1/{space_id}/conversations/{conversation_id} Get one conversation detail read (CWT or space token)
GET /v1/{space_id}/conversations/{conversation_id}/delta Get incremental conversation updates read (CWT or space token)
GET /v1/{space_id}/conversations List conversations (cursor pagination) read (CWT or space token)
GET /v1/{space_id}/management/space_tokens List space tokens write (CWT)
POST /v1/{space_id}/management/add_space_token Add a space token write (CWT)
POST /v1/{space_id}/management/revoke_space_token Revoke a space token write (CWT)
PATCH /v1/{space_id}/management/update_space Update space information (name, description, public/private, memory policy) write (CWT)
PATCH /v1/{space_id}/management/restart_formation Restart a formation task write (CWT)
GET /v1/{space_id}/management/space_byok Get BYOK (Bring Your Own Key) configuration write (CWT)
PATCH /v1/{space_id}/management/space_byok Update BYOK (Bring Your Own Key) configuration write (CWT)
POST /admin/{space_id}/update_space_tier Update a space tier (manager only) write (CWT)
POST /admin/create_space Create a new space (manager only) write (CWT)

MCP Server

When the HTTP service starts, Anda Brain also exposes a Streamable HTTP MCP endpoint:

https://your-brain-host/mcp/{space_id}

Use this for multi-user deployments where each employee or agent team receives a dedicated Brain space. MCP clients should send the same CWT or space token used by REST as Authorization: Bearer <token>. Read-only tools can access public spaces without a token.

For local desktop or development clients, Anda Brain can also run as a stdio MCP server:

MCP_AUTH_TOKEN="$SPACE_TOKEN" \
  cargo run -p anda_brain --features mcp,wiki -- mcp --space-id my_space_001 local --db ./data

Both MCP modes use the same storage/model configuration as the HTTP service and expose these tools:

Tool Purpose Scope
anda_brain_memory The Memory Interface: one observe/recall/revise/feedback/forget request recall read; others write
anda_brain_stage_memory_source Stage observed messages and get a source_ref write
anda_brain_memory_receipt Read a Memory Interface receipt's progress read
anda_brain_remember_conversation Encode conversation messages into memory write
anda_brain_recall_memory Ask natural-language questions against memory read
anda_brain_run_maintenance Trigger memory consolidation/pruning write
anda_brain_get_space_info Read space statistics and metadata read
anda_brain_get_formation_status Read formation/maintenance progress read
anda_brain_execute_kip_readonly Run read-only KIP for advanced graph inspection read
anda_brain_get_or_init_user Get or create a counterparty concept write
anda_brain_list_conversations Page through tracked conversations read
anda_brain_get_conversation Read one tracked conversation or delta read

If authentication is enabled, pass a CWT or space token. Remote MCP reads it from the HTTP Authorization header; stdio reads it from MCP_AUTH_TOKEN or --mcp-auth-token. For local-only development with auth disabled, the token can be omitted. Remote MCP auto-create requires ED25519_PUBKEYS plus a write CWT for the target space before the missing space is created. Use MCP_HTTP_ALLOWED_HOSTS when exposing remote MCP behind a company domain or reverse proxy.

Content Negotiation

Triple serialization via Content-Type / Accept headers:

  • application/json β€” JSON (default)
  • application/cbor β€” CBOR (binary, more compact)
  • text/markdown β€” Markdown (human-readable text)

All responses use an RPC envelope:

{"result": { ... }, "error": null}

Authentication

All endpoints (except /, /info and /SKILL.md) require a Bearer token:

Authorization: Bearer <base64_encoded_cose_sign1_token>

If ED25519_PUBKEYS is not provided (empty), authentication is effectively disabled: API requests are accepted without signature verification.

Token format: COSE Sign1 message signed with Ed25519 keys, containing CWT claims:

Claim Purpose
sub Principal ID (who is making the request)
aud Audience β€” the space ID being accessed (or * for any)
scope Permission level: read, write (or * for any)

POST /admin/create_space

Create a new isolated memory space. Requires manager principal.

Request:

{
  "user": "<owner_principal_id>",
  "space_id": "my_space_001",
  "tier": 0
}

Response:

{
  "result": {
    "space_id": "my_space_001",
    "owner": "owner_principal_id",
    ...
  }
}

POST /v1/{space_id}/formation

Submit conversation messages for memory encoding. Processing is asynchronous β€” returns immediately while encoding continues in the background.

RFC 3339 observation times are normalized to UTC milliseconds. Invalid or missing timestamp strings use the durable conversation creation time, including on retries; the original input is retained. Markdown raw text is captured as one user message with the same Evidence binding. Looking up an existing counterparty without a name preserves its current display name.

Request:

{
  "messages": [
    {
      "role": "user",
      "content": "I prefer dark mode. My timezone is UTC+8.",
      "name": "Alice"
    },
    {
      "role": "assistant",
      "content": "Got it! I've noted your preferences."
    }
  ],
  "context": {
    "counterparty": "alice_principal_id",
    "agent": "customer_bot_001",
    "source": "source_123",
    "topic": "settings"
  },
  "timestamp": "2026-03-09T10:30:00.000Z"
}
Field Type Required Description
messages Message[] Yes Conversation messages (role: user / assistant / system)
context.counterparty string No User identifier
context.agent string No Calling agent identifier
context.source string No Identifier of the source of the current interaction content
context.topic string No Conversation topic
timestamp string No (recommended) RFC 3339; normalized, or receipt time if invalid/missing

Response:

{
  "result": {
    "conversation": 1,
    ...
  }
}

POST /v1/{space_id}/recall

Query memory with natural language. Returns a synthesized answer from the knowledge graph and conversation history.

Request:

{
  "query": "What are Alice's preferences?",
  "context": {
    "counterparty": "alice_principal_id",
    "topic": "settings"
  }
}
Field Type Required Description
query string Yes Natural language question
context.counterparty string No User identifier
context.agent string No Calling agent identifier
context.topic string No Topic hint for disambiguation

Response:

{
  "result": {
    "content": "Alice prefers dark mode and operates in UTC+8 timezone.",
    ...
  }
}

POST /v1/{space_id}/maintenance

Trigger a memory maintenance cycle. Runs asynchronously with single-execution guard.

Request:

{
  "trigger": "on_demand",
  "scope": "daydream",
  "timestamp": "2026-03-10T03:00:00.000Z",
  "parameters": {
    "stale_event_threshold_days": 7,
    "unconsolidated_max_backlog": 20,
    "orphan_max_count": 10
  }
}
Field Type Required Description
trigger string No scheduled / threshold / on_demand (default: on_demand)
scope string No full (all phases) / quick (assessment + urgent tasks) / daydream (idle-time salience scoring & micro-consolidation, default)
timestamp string No Canonical UTC timestamp (YYYY-MM-DDTHH:mm:ss.SSSZ)
parameters.stale_event_threshold_days u32 No Days before events are considered stale (default: 7)
parameters.memory_strength_decay_factor f64 No Deprecated and ignored. Decay is computed at read time from a pinned strength policy; no sweep applies a factor. Still range-checked in (0, 1] and accepted as confidence_decay_factor, so existing callers are not rejected.
parameters.unconsolidated_max_backlog u32 No Events and Experiences no formation or consolidation Activity has taken as input yet (default: 20). Accepted as unsorted_max_backlog.
parameters.orphan_max_count u32 No Max orphans to process (default: 10)

The parameters are targets to work toward, not commands. The runtime fills an assessment block into the same input β€” the per-predicate census, correction tallies, armed and fired Watches, and the current space_seq β€” and overwrites whatever a caller sent there: a request body must not be able to tell the Brain what its own graph looks like.

Response:

{
  "result": {
    "conversation": 8,
    ...
  }
}

GET /v1/{space_id}/info

Get space statistics and health information.

Response:

{
  "result": {
    "space_id": "my_space_001",
    "owner": "principal_id",
    "db_stats": { "total_items": 150, "total_bytes": 524288 },
    "concepts": 85,
    "propositions": 120,
    "conversations": 12,
    ...
  }
}

Recall Function Definition

Business agents can register the Recall endpoint as an LLM tool/function call. See RecallFunctionDefinition.json for the OpenAI function-calling format.

Memory Space Lifecycle

Creation

  1. Creates a new AndaDB instance.
  2. Initializes CognitiveNexus.
  3. Activates the KIP 2.0 Cognitive Memory Profile plus this space's own vocabulary package.
  4. Stores creator/owner principal IDs.

Upgrading a space written by a KIP 1.x build

Migration runs when a space is first opened, after the Brain activates its Schema. Stop the old writer, take a consistent backup, and rehearse against a copy before changing production. The two old graph collections are replaced in place; rollback requires the pre-upgrade backup, not an older binary pointed at the migrated store. Upgrade one space at a time and check its results before opening the next.

The migration persists extraction and vocabulary checkpoints before switching collections. It can resume between either collection deletion and between loading records and committing the completion marker. Original rows remain in kip_legacy_v1. LegacyRecord Facets preserve source data for audit, including the published v1 a / m attribute and metadata fields.

v1 data v2 representation
(type, name) identity Immutable Concept key; standard Person / Event / Insight / Commitment / SleepTask fields are normalized; a 1.x Preference keeps an open legacy type (the Profile has none)
Insight description; SleepTask reason / requested_action Native summary / task class; interrupted tasks become blocked without a fabricated lease
A recorded claim Proposition + mode: "imported" Assertion; recorded confidence and resolvable author are preserved
Retracted or superseded claim Native lifecycle where the same-actor, same-Proposition revision is reconstructible; otherwise archived with its original annotations, never revived as current belief
valid_from / valid_until; expires_at Assertion valid time; record retention, respectively
pinned; mnemonic values Pinned retention class; MnemonicState, never copied from Assertion confidence
Unsupported old learning/runtime artifacts Distinct Legacy* types under kip://legacy/nexus@1.1.0; they acquire neither learning standing nor operational leases
Legacy relation with incompatible native endpoints A distinct legacy predicate for that tuple; compatible tuples keep the native predicate

Unresolvable attribution and privacy annotations remain source data, not verified identity, trust or Governance permission. Invalid optional native values remain available in LegacyRecord. Malformed identifiers or dangling references can still stop migration; inspect the reported source row and retry on the backup copy rather than treating an unopened space as empty memory.

The service removes old-id usage rows and resets miss caches, derived metrics and scan cursors once. It preserves conversations, tokens, policies, wiki records and any already-recorded v2 usage. The migration is tested against a complete object-store snapshot produced by the published v0.11 runtime packages; see the fixture generator.

Runtime

  • Spaces are lazy-loaded on first access via OnceCell.
  • In-memory cache with access tracking.
  • 5-minute interval: Flush active spaces to storage.
  • 9-minute idle timeout: Evict unused spaces from cache (skipped while a space is pinned, processing, or still referenced by requests).
  • Graceful shutdown: Close all space databases before exit.

Memory Elements in the Cognitive Nexus

KIP 2.0 separates things KIP 1.x kept in one graph. The distinction the rest follows from is that a Proposition existing is not the Proposition being true:

Element What it is
Concept A referable entity: schema_ref, immutable key, mutable name, attributes
Proposition A truth-neutral (subject, predicate, object) tuple
Assertion One actor's stance about a Proposition: asserted_by, mode, confidence
Evidence An observed artifact β€” a message, a tool result, a document passage
Activity The provenance of a process: consolidation, revision, import

What is currently believed is projected from Assertions under a named policy (BELIEF), never stored. Mnemonic state β€” how available and how noteworthy a memory is β€” lives in the MnemonicState Facet, and is not confidence.

Schema is not graph state. Types and predicates are resolved from immutable, versioned Schema Packages, so a write cannot change what a type means. This space activates the standard Cognitive Memory Profile. When Formation meets vocabulary the profile lacks, it drafts it with DEFINE into the space's draft vocabulary kip://local/draft@0.0.0 (KIP Β§20.16): additive, never changed afterwards, and under the host's name checks and 512-symbol cap. Each new symbol queues a review_schema task; GET /v1/{space_id}/schema/drafts lists the drafts, and the owner promotes one onto an installed symbol with POST /v1/{space_id}/schema/promote. Spaces that grew vocabulary earlier keep their kip://anda-brain/memory package in force; nothing is added to it any more.

Configuration

CLI Arguments / Environment Variables

Env Variable CLI Flag Default Description
LISTEN_ADDR --addr 127.0.0.1:8042 Listen address
ED25519_PUBKEYS --ed25519-pubkeys β€” Comma-separated Base64 Ed25519 public keys; if empty, API authentication is disabled
MODEL_FAMILY --model-family anthropic Model family to use for encoding and recall (e.g., gemini, anthropic, openai)
MODEL_API_KEY --model-api-key β€” API key for the configured model provider
MODEL_API_BASE --model-api-base https://api.deepseek.com/anthropic Model API base URL
MODEL_NAME --model-name deepseek-v4-pro LLM model for agents
MODEL_CONTEXT_WINDOW --model-context-window 400000 Model context window size (tokens)
MODEL_MAX_OUTPUT --model-max-output 384000 Model max output size (tokens)
HTTPS_PROXY --https-proxy β€” HTTPS proxy URL
SHARDING_IDX --sharding-idx 0 Shard index for this instance
MANAGERS --managers β€” Comma-separated manager principal IDs
CORS_ORIGINS --cors-origins β€” CORS allowed origins: empty = disabled, * = allow all, or comma-separated origins
MCP_HTTP_ENABLED --mcp-http-enabled true Mount Streamable HTTP MCP with the HTTP service
MCP_HTTP_PATH_PREFIX --mcp-http-path-prefix /mcp Remote MCP prefix; clients connect to {prefix}/{space_id}
MCP_HTTP_ALLOWED_HOSTS --mcp-http-allowed-hosts β€” Comma-separated Host allowlist for remote MCP; use * only behind trusted controls
MCP_HTTP_ALLOWED_ORIGINS --mcp-http-allowed-origins β€” Comma-separated browser Origin allowlist for remote MCP
MCP_HTTP_AUTO_CREATE_SPACE --mcp-http-auto-create-space false Create remote MCP spaces on first use after a valid write CWT
MCP_HTTP_AUTO_CREATE_TIER --mcp-http-auto-create-tier 1 Tier used for remote MCP auto-created spaces
MCP_SPACE_ID mcp --space-id β€” Space exposed by the MCP stdio server
MCP_AUTH_TOKEN mcp --mcp-auth-token β€” CWT or space token used by MCP tools
MCP_AUTO_CREATE_SPACE mcp --mcp-auto-create-space false Create the MCP space if it does not exist
MCP_AUTO_CREATE_TIER mcp --mcp-auto-create-tier 1 Tier used for MCP auto-created spaces

CORS_ORIGINS examples:

  • "" (empty): CORS disabled
  • "*": allow all origins
  • "https://app.example.com,https://admin.example.com": allow specific origins

Storage Backends

Subcommand Description Key Env Variables
(none) In-memory storage (dev/testing) β€”
local Local filesystem storage LOCAL_DB_PATH (default ./db)
aws AWS S3 storage AWS_BUCKET, AWS_REGION, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY

Cargo Features

The library ships memory only by default β€” formation, recall, maintenance, and their HTTP routes. Everything else is opt-in:

Feature Adds
wiki The structured wiki (documents, versions, ACL-scoped reads, OKF import/export), the wiki_search/wiki_read/wiki_commit agent tools, WikiDigest graph extraction, and the /v1/{space_id}/wiki/* routes. Also adds the wiki_* fields of SpaceInfo and UpdateSpaceInput.
mcp The MCP channel: the stdio server and the Streamable HTTP service. With wiki on as well, the wiki tools join the MCP tool router.
experiments Isolated Rust host runs, immutable snapshots, business time, session boundaries and cost receipts. Enables Nexus simulation, without changing production clocks or enabling learning.
learning Paired contracts/evaluator, native records, persistent host trial/settlement/review runtime, and a read-only Recall applicability tool. Explicit executor/observer/source/calibration bindings and automatic switches are required; The learning runtime provides a compiled HTTP adapter and bounded scheduler, without model standing writes.
# Embedding the library: memory only
anda_brain = "0.13"

# …or the full surface
anda_brain = { version = "0.13", features = ["mcp", "wiki"] }

To use development APIs before a crate release, build this checkout. Trusted experiment hosts add experiments; it is independent of the learning feature.

The anda_brain binary is the full product and declares required-features = ["mcp", "wiki"], so every command below passes --features mcp,wiki. Without them Cargo skips the binary target.

Running

# Development (in-memory storage)
cargo run -p anda_brain --features mcp,wiki

# Local filesystem storage
cargo run -p anda_brain --features mcp,wiki -- local --db ./data

# HTTP service also serves remote MCP at /mcp/{space_id}
MCP_HTTP_ALLOWED_HOSTS="brain.example.com" \
  cargo run -p anda_brain --features mcp,wiki -- local --db ./data

# AWS S3 storage
cargo run -p anda_brain --features mcp,wiki -- aws --bucket my-bucket --region us-east-1

# MCP stdio server for local MCP clients
MCP_AUTH_TOKEN="$SPACE_TOKEN" \
  cargo run -p anda_brain --features mcp,wiki -- mcp --space-id my_space_001 local --db ./data

Run with Docker image

# Pull image
docker pull ghcr.io/ldclabs/anda_brain_amd64:latest

# Run with ENV (in-memory by default)
docker run --rm -p 8042:8042 \
  -e LISTEN_ADDR=0.0.0.0:8042 \
  -e MODEL_API_KEY=your_key \
  ghcr.io/ldclabs/anda_brain_amd64:latest

# Override startup args (example: local storage)
docker run --rm -p 8042:8042 \
  -v $(pwd)/data:/data \
  ghcr.io/ldclabs/anda_brain_amd64:latest local --db /data

# Override startup args (example: AWS S3 storage)
docker run --rm -p 8042:8042 \
  -e AWS_ACCESS_KEY_ID=your_ak \
  -e AWS_SECRET_ACCESS_KEY=your_sk \
  ghcr.io/ldclabs/anda_brain_amd64:latest aws --bucket my-bucket --region us-east-1

Dependencies

Key crates from the Anda ecosystem:

Crate Purpose
anda_core Core traits (Agent, Tool, AgentContext) and types
anda_engine Agent engine, model integration, memory management
anda_db Persistent database layer (AndaDB) with configurable storage
anda_kip KIP 2.0 protocol: parser, error registry, request envelope
anda_cognitive_nexus Cognitive Nexus knowledge graph implementation
object_store Object store abstraction

License

Copyright Β© LDC Labs

Licensed under the Apache License, Version 2.0.

Memory utility

Space::recall_receipts() retains delivery hashes, actual element versions, basis, coverage and budgets outside the cognitive graph. Structured Recall returns a recall_receipt handle; Action decisions can bind one through ContextRequest. Space::utility() provides trusted attribution/calibration APIs. Startup config selects single_contribution_v1 or the paired-trial-backed paired_revision_v1 and separate automatic/apply/rank switches. Parameters and approval have no empirical defaults. Required constraints, native uncertainty, procedure eligibility and execution authority retain priority. Read the bilingual utility guide and disabled configuration template.

Runtime limits and recovery

Formation and Maintenance now share library-level writer admission, and model-call concurrency covers background work and compaction. Eviction retains failed-close owners and does not hold the global Space lock during database I/O. Self-test supports persisted 30-day retesting and bounds its actual host request plus requested output. See execution limits for provider-accounting and independent-runtime boundaries.