Skip to content
Back to search

AuraSDK

Local cognitive memory runtime for AI agents — durable recall, temporal versioning, provenance, contradiction governance, and portable encrypted storage. Pure Rust, offline-first, with no required LLM or cloud. Patent pending.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/teolex2020--aurasdk/badge.svg)](/listings/teolex2020--aurasdk)

HTML

<a href="/listings/teolex2020--aurasdk"><img src="/api/listings/teolex2020--aurasdk/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

Trust & Provenance

from aura import Aura, TrustConfig

brain = Aura("./data")

tc = TrustConfig()
tc.source_trust = {"user": 1.0, "api": 0.8, "web_scrape": 0.5}
brain.set_trust_config(tc)

# User facts always rank higher than scraped data in recall
brain.store("User is vegan", channel="user")
brain.store("User might like steak restaurants", channel="web_scrape")

results = brain.recall_structured("food preferences", top_k=5)
# -> "User is vegan" scores higher, always

Pluggable Embeddings (Optional)

from aura import Aura

brain = Aura("./data")

# Plug in any embedding function: OpenAI, Ollama, sentence-transformers, etc.
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("all-MiniLM-L6-v2")
brain.set_embedding_fn(lambda text: model.encode(text).tolist())

# Now "login problems" matches "Authentication failed" via semantic similarity
brain.store("Authentication failed for user admin")
results = brain.recall_structured("login problems", top_k=5)

Without embeddings, Aura continues to use its local recall pipeline - still fast, still effective.

Claim Certainty (Optional LLM)

Aura records whether each memory is first-hand (`asserted`), qualified (`hedged`), a guess (`speculative`), or relayed from someone else (`hearsay`). Relayed and uncertain claims are still stored, but with lower confidence, and they never count as first-hand evidence for advice.

Built-in rules catch obvious phrasings without any model. For better coverage, plug in a small local LLM:

import json, urllib.request

PROMPT = (
    "Classify what kind of claim the sentence makes. Answer with exactly one word: "
    "asserted, hearsay, hedged or speculative.\nSentence: {text}\nAnswer:"
)

def classify(text):
    body = json.dumps({"model": "qwen3:4b-instruct", "prompt": PROMPT.format(text=text),
                       "stream": False, "options": {"temperature": 0, "num_predict": 8}}).encode()
    req = urllib.request.Request("http://127.0.0.1:11434/api/generate", data=body,
                                 headers={"Content-Type": "application/json"})
    answer = json.loads(urllib.request.urlopen(req).read())["response"].strip().lower()
    return next((l for l in ("asserted", "hearsay", "hedged", "speculative") if l in answer), None)

brain.set_claim_classifier(classify)   # returning None falls back to the built-in rules
brain.store("I was born on May 12")    # asserted, Identity level
brain.store("I heard the plant closed") # hearsay, lower confidence

On an independent test set, `qwen3:4b-instruct` via this hook reached hearsay recall 0.88 and precision 0.92 without demoting any first-hand statement (~0.3 s per write); the built-in rules alone reached recall 0.53. Those numbers were measured with the longer prompt that defines each label, in `experiments/claim_certainty/llm_eval.py`; the short prompt above is only an illustration. See `experiments/claim_certainty` for the full evaluation.

Encryption

brain = Aura("./secret_data", password="my-secure-password")
brain.store("Top secret information")
assert brain.is_encrypted()  # ChaCha20-Poly1305 + Argon2id

Password protection now covers the cognitive journal and snapshots, audit entries, derived cognitive state, recall replay history, and stored embeddings. Reopening requires the correct password and the original `memory.key` file. Back up that wrapped key separately: portable containers intentionally exclude key material.

Use a new, empty directory when enabling encryption. Adding a password to an existing store is rejected because its journals, snapshots, and backups may already contain plaintext. Existing unencrypted stores remain readable without a password; moving them to encrypted storage requires an explicit migration. Older password-created stores did not protect all cognitive data and must also be migrated. Explicit JSON exports return plaintext to the caller.

Deletion and managed purge

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 1,337 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. <p align="center">
  2. <h1 align="center">Aura Memory</h1>
  3. <p align="center"><strong>Aura turns fragile prompt-only agents into auditable, memory-aware, production-ready systems</strong></p>
  4. <p align="center">
  5. Deterministic · No fine-tuning · No cloud training · Local recall · No required embeddings
  6. </p>
  7. </p>
  8. <p align="center">
  9. <a href="https://github.com/teolex2020/aura-memory/actions/workflows/test.yml"><img src="https://github.com/teolex2020/aura-memory/actions/workflows/test.yml/badge.svg" alt="CI"></a>
  10. <a href="https://pypi.org/project/aura-memory/"><img src="https://img.shields.io/pypi/v/aura-memory.svg" alt="PyPI"></a>
  11. <a href="https://pypi.org/project/aura-memory/"><img src="https://img.shields.io/pypi/dm/aura-memory.svg" alt="Downloads"></a>
  12. <a href="https://github.com/teolex2020/aura-memory/stargazers"><img src="https://img.shields.io/github/stars/teolex2020/aura-memory?style=social" alt="GitHub stars"></a>
  13. <a href="https://opensource.org/licenses/MIT"><img src="https://img.shields.io/badge/License-MIT-yellow.svg" alt="License: MIT"></a>
  14. </p>
  15. <p align="center">
  16. <a href="https://colab.research.google.com/github/teolex2020/aura-memory/blob/main/examples/colab_quickstart.ipynb"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"></a>&nbsp;&nbsp;
  17. <a href="https://www.youtube.com/watch?v=ZyE9P2_uKxg"><img src="https://img.shields.io/badge/YouTube-Demo_30s-red?logo=youtube" alt="Demo Video"></a>&nbsp;&nbsp;
  18. <a href="https://aurasdk.dev"><img src="https://img.shields.io/badge/Web-aurasdk.dev-blue" alt="Website"></a>
  19. </p>
  20. ---
  21. Your AI model is smart. But it forgets everything after every conversation.
  22. > **New: [Aura for Windows](https://www.aurasdk.dev/desktop)** — a free desktop app built on this library that gives Claude Code, Cursor, Codex, Copilot and other AI tools one shared local memory.
  23. Aura is a local cognitive runtime that runs alongside any frozen model. It gives agents durable memory, explainability, governed correction, bounded recall reranking, and bounded self-adaptation through experience — all locally, without fine-tuning or cloud training.
  24. ```bash
  25. pip install aura-memory
  26. ```
  27. ```python
  28. from aura import Aura, Level
  29. brain = Aura("./agent_memory")
  30. brain.enable_full_cognitive_stack() # activate all four bounded reranking overlays
  31. # store what happens
  32. brain.store("User always deploys to staging first", level=Level.Domain, tags=["workflow"])
  33. brain.store("Staging deploy prevented 3 production incidents", level=Level.Domain, tags=["workflow"])
  34. # recall — local retrieval with optional bounded cognitive reranking
  35. context = brain.recall("deployment decision") # local retrieval, no API call
  36. # advisory hints are derived during maintenance once enough evidence accumulates
  37. brain.run_maintenance()
  38. for hint in brain.get_surfaced_policy_hints():
  39. print(hint.action_kind, hint.domain, hint.recommendation)
  40. # → prefer workflow deploy to staging first (only after repeated, consistent evidence)
  41. ```
  42. No API keys. No embeddings required. No cloud. The model stays the same — the cognitive layer becomes more structured, more inspectable, and more useful over time.
  43. ### What's new in 1.61
  44. - **Your words stay apart from outside text.** `recall()` now returns the provenance context by default: first-hand memory first, then web, document and tool content fenced and quoted as data. The fence stops ordinary instructions hidden in that content; text written to pose as the user can still steer a model (`experiments/mcp_gateway_fence_robustness`, `experiments/agentdojo_fence`). **Upgrade note:** code that parses the old `=== COGNITIVE CONTEXT ===` text should pass `format="levels"`.
  45. - **Security profiles.** `Aura(path, security="strict")`, `set_security_profile()` and `security_report()`. Memories written by a model through MCP are stored as `inferred`, not as the user's word. One untrusted source repeating a claim can no longer crowd out a first-hand fact.
  46. - **Better recall context.** A short block of lasting facts about the user, event dates on first-hand memory, and relevance-trimmed context.
  47. - **One memory for many AI tools.** The Rust features `mcp-http` and `mcp-bridge` add a token-protected loopback MCP server and the `aura-bridge` stdio bridge, so several clients share one store. This is what the [Aura for Windows](https://www.aurasdk.dev/desktop) app runs on.
  48. - **Conversation capture.** `python -m aura capture` is a Claude Code hook that keeps the user's words as first-hand memory.
  49. - **Safer HTTP server.** `python -m aura serve` refuses to listen beyond localhost without an API key. Install it with `pip install "aura-memory[http]"`.
  50. - **Plain MIT.** The license-enforcement module is gone.
  51. The full list is in the [changelog](CHANGELOG.md).
  52. > **⭐ If Aura is useful to you, a [GitHub star](https://github.com/teolex2020/aura-memory) helps us get funding to continue development from Kyiv.**
  53. ---
  54. ## Why Aura?
  55. | Property | Aura |
  56. |---|---|
  57. | Architecture | Five-layer cognitive engine, with Belief→Concept→Causal→Policy derivation |
  58. | Memory operations | Local Rust computation; no required LLM or embedding API |
  59. | Recall latency | 11.61 ms median, distinct uncached top-10 queries on 5K records; see [Performance](#performance) |
  60. | Offline use | Supported without a cloud service |
  61. | API fee for memory operations | None required; local compute and storage still have costs |
  62. | Package size | 2.77 MB Windows CPython 3.13 wheel<sup>1</sup> |
  63. | Lifecycle and governance | Built-in decay/promotion, provenance, contradiction controls, purge/freeze |
  64. | Encryption at rest | Optional ChaCha20-Poly1305 with Argon2id key derivation |
  65. We do not publish unmeasured speed, cost, or feature rankings against other
  66. memory products. Their deployment modes and search outputs differ; a meaningful
  67. comparison needs matched data, workload, and quality criteria.
  68. ### The Core Idea: Cheap Model + Aura > Expensive Model Alone
  69. Fine-tuning costs thousands of dollars and weeks of work. RAG requires embeddings and a vector database. Context windows are expensive per token.
  70. Aura gives you a third path: **a local cognitive runtime that accumulates structured experience between conversations** — free and local.
  71. ```
  72. Week 1: GPT-4o-mini + Aura Week 1: GPT-4 alone
  73. → average answers → average answers
  74. Week 4: GPT-4o-mini + Aura Week 4: GPT-4 alone
  75. → recalls your workflow → still forgets everything
  76. → surfaces patterns you repeat → same cost per token
  77. → exposes explainability + correction → no improvement
  78. → boundedly adapts from experience → no durable learning
  79. → no required external API cost → still billing per call
  80. ```
  81. The model stays the same. The cognitive layer gets stronger. That's Aura.
  82. ### Performance
  83. **Current local measurement (Aura `1.60.0`).** On Windows 10, AMD Ryzen 5
  84. 5600X, and CPython 3.13.14, we stored the first 5,000 dialogue turns from
  85. LoCoMo (median 154 bytes per turn). Recall used 100 distinct natural-language
  86. questions, `recall_structured(top_k=10)`, and no repeated-query cache hits.
  87. One sequential local run, measured on 2026-09-25:
  88. | Operation | Median | P95 |
  89. |-----------|-------:|----:|
  90. | Store one turn | 5.66 ms | 10.10 ms |
  91. | Structured recall, distinct uncached query | 11.61 ms | 18.95 ms |
  92. | Get record by known ID | 0.0033 ms | 0.0083 ms |
  93. Local MCP stdio added about 0.04 ms to mean recall time in a separate
  94. same-query round-trip comparison. This is not a network benchmark. A lexical
  95. SQLite FTS5 index on the same 5,000 turns searched in 1.13 ms median, but it
  96. does not provide the same cognitive functions. On the first 100 LoCoMo
  97. evidence questions, Aura found all annotated evidence for 36 questions and
  98. SQLite FTS5 for 39; this narrow slice does not establish a quality advantage
  99. for either system. Do not interpret fast `get(id)` or cache-hit times as
  100. uncached natural-language recall.
  101. **Historical 1K measurement (Aura `1.58.0`).** The release wheel measured
  102. 2.483 ms median / 4.035 ms p95 for uncached structured recall, and 8.2 µs
  103. median for a formatted cache hit, on the same CPU with 1,000 different
  104. records. See [`benchmarks/results.json`](benchmarks/results.json) and reproduce
  105. that historical test with `python benchmarks/bench_all.py 1000`. The 1K and
  106. 5K runs use different content and questions, so they do **not** demonstrate
  107. a version-to-version slowdown.
  108. All figures are observations, not guarantees. Corpus size, query shape,
  109. cache state, enabled features, and background load affect latency. Aura recall
  110. uses local computation and needs no embedding or LLM API call. No
  111. cross-product speedup is claimed without matched data, deployment, and quality
  112. targets.
  113. Retrieval quality is measured separately from speed. The checked-in synthetic
  114. development evaluation compares recent history, token overlap, and Aura on a
  115. primarily English suite with small multilingual diagnostic slices, paraphrases,
  116. code identifiers, temporal updates, negation, multi-evidence recall, tenant
  117. interference, and restart consistency.
  118. Its current machine-readable result and limitations are documented in
  119. [`experiments/memory_quality_eval`](experiments/memory_quality_eval/README.md).
  120. This development set is not presented as a competitor benchmark.
  121. <sub><sup>1</sup> The measured Aura 1.58 Windows CPython 3.13 wheel was
  122. 2,772,715 bytes; installed size and artifacts for other Python versions,
  123. platforms, and releases vary.</sub>
  124. ---
  125. ## What Ships Today
  126. Aura's full cognitive recall pipeline is active and bounded:
  127. `Record → Belief (±5%) → Concept (±4%) → Causal (±3%) → Policy (±2%)`
  128. Enable everything in one call:
  129. ```python
  130. brain.enable_full_cognitive_stack() # activates all four bounded reranking phases
  131. brain.disable_full_cognitive_stack() # back to raw RRF baseline
  132. ```
  133. Or configure individual phases:
  134. ```python
  135. brain.set_belief_rerank_mode("limited") # belief-aware ranking
  136. brain.set_concept_surface_mode("limited") # concept annotations + bounded concept reranking
  137. brain.set_causal_rerank_mode("limited") # causal chain boost
  138. brain.set_policy_rerank_mode("limited") # policy hint shaping
  139. ```
  140. Higher layers also expose advisory surfaced output:
  141. - `get_surfaced_concepts()` — stable concept abstractions over repeated beliefs
  142. - `get_surfaced_causal_patterns()` — learned cause→effect patterns
  143. - `get_surfaced_policy_hints()` — advisory recommendations (Prefer / Avoid / Warn)
  144. - no automatic behavior influence — all output is advisory and read-only
  145. Aura also ships operator-facing and plasticity-facing surfaces:
  146. - explainability:
  147. - `explain_recall()`
  148. - `explain_record()`
  149. - `provenance_chain()`
  150. - `explainability_bundle()`
  151. - governed correction:
  152. - targeted retract/deprecate APIs
  153. - persistent correction log
  154. - correction review queue
  155. - suggested corrections without auto-apply
  156. - bounded autonomous plasticity:
  157. - `capture_experience()`
  158. - `ingest_experience_batch()`
  159. - maintenance-phase integration
  160. - anti-hallucination guards
  161. - plasticity risk scoring
  162. - purge / freeze controls
  163. - bounded v6 cognitive guidance:
  164. - salience:
  165. - `mark_record_salience()`
  166. - `get_high_salience_records()`
  167. - `get_salience_summary()`
  168. - reflection:
  169. - `get_reflection_summaries()`
  170. - `get_latest_reflection_digest()`
  171. - `get_reflection_digest()`
  172. - contradiction and instability:
  173. - `get_belief_instability_summary()`
  174. - `get_contradiction_clusters()`
  175. - `get_contradiction_review_queue()`
  176. - honest explainability support:
  177. - unresolved-evidence markers in recall explanations
  178. - bounded answer-support phrasing for agent / UI layers
  179. ---
  180. ## How Memory Works
  181. Aura organizes memories into four levels across two active tiers. Maintenance is
  182. event-driven: one maintenance call is one decay opportunity, not a calendar TTL.
  183. Importance, evidence state, explicit pins, and archival policy decide what stays
  184. active; wall-clock time is used only by configured age/completion rules.
  185. ```
  186. CORE TIER
  187. Identity Anchored identity and operator-protected knowledge.
  188. Domain Learned facts and domain knowledge.
  189. COGNITIVE TIER
  190. Decisions Choices made and action items.
  191. Working Current tasks and recent context.
  192. CONSEQUENCE ROUTE STATE (maintenance retention)
  193. candidate Fastest decay while usefulness is still unverified.
  194. evidence debt Slower decay while an outcome remains unresolved.
  195. confirmed Longest ordinary retention after supporting outcomes.
  196. refuted scar No field decay; preserved against later positive noise.
  197. OPERATOR PIN
  198. pinned No field decay or automatic archival.
  199. ```
  200. One call runs the lifecycle — decay, promotion, consolidation, and archival:
  201. ```python
  202. report = brain.run_maintenance() # background memory maintenance
  203. ```
  204. Weak records leave active RAM and fast indexes but keep a crash-safe journal
  205. trace. They stay cold after restart. Automatic text-query reactivation from the
  206. cold journal is not part of the current API.
  207. ---
  208. ## Key Features
  209. ### Evidence & Decision Audit Graph
  210. Aura can preserve the complete chain from evidence to a verified outcome as a
  211. small, deterministic read-model over the existing local store. It does not
  212. require a graph database, an LLM, or a cloud service:
  213. ```python
  214. source_id = brain.store("Canary telemetry is healthy", source_type="retrieved")
  215. claim_id = brain.store("The canary is healthy", semantic_type="fact")
  216. decision_id = brain.store(
  217. "Proceed with the bounded rollout",
  218. level=Level.Decisions,
  219. semantic_type="decision",
  220. )
  221. brain.annotate_audit_entity(source_id, "source", "observed", "deploy/source")
  222. brain.annotate_audit_entity(claim_id, "claim", "accepted", "deploy/claim")
  223. brain.annotate_audit_entity(decision_id, "decision", "decided", "deploy/decision")
  224. brain.link_audit_entities("deploy/source", "deploy/claim", "supports")
  225. brain.link_audit_entities("deploy/claim", "deploy/decision", "recalled_for")
  226. explanation = brain.explain_decision("deploy/decision")
  227. history = brain.audit_graph(namespace="default", valid_at=timestamp)
  228. conflicts = brain.find_claim_conflicts("deploy/claim")
  229. ```
  230. Directed relations cover `supports`, `refutes`, `contradicts`, `supersedes`,
  231. `derived_from`, `recalled_for`, `used_evidence`, `used_by`, `caused`,
  232. `produced`, and `verified_by`. Entity status is append-only and bitemporal;
  233. historical graph reconstruction uses both recording time and business-time
  234. validity. Conflict recommendations are advisory and never rewrite memory.
  235. The graph is rebuilt from reserved `aura.audit.v1.*` record metadata, while
  236. links are committed atomically with Aura's existing typed connections. Compact
  237. JSON export is available in Rust through `AuditGraph::to_compact_json()`.
  238. ### Observational Outcome Receipts
  239. Aura can collect the exact evidence needed to evaluate future adaptive memory
  240. policies without changing memory behavior today. A receipt records candidate
  241. record IDs, selected IDs, and a categorical external outcome; it never stores
  242. the prompt, answer, task text, or memory payload:
  243. ```python
  244. receipt = brain.capture_outcome_receipt(
  245. task_id="deploy-184",
  246. lineage_id="deploy-canary",
  247. attempt_id="attempt-1",
  248. candidate_record_ids=[runbook_id, incident_id],
  249. selected_record_ids=[runbook_id],
  250. outcome="helpful",
  251. namespace="operations",
  252. provenance=["host:task-runner"],
  253. # Optional: exact evidence for later offline evaluation.
  254. logging_policy_id="bounded-exploration-v1",
  255. selected_set_probability_bps=2500, # probability of the selected set
  256. candidate_verdicts={
  257. runbook_id: "helpful",
  258. incident_id: "unhelpful",
  259. },
  260. verifier_id="terminal-check-v1",
  261. )
  262. history = brain.outcome_receipts(
  263. namespace="operations",
  264. lineage_id="deploy-canary",
  265. )
  266. ```
  267. Omit the optional evaluation fields to keep the schema-v1 receipt. Supplying a
  268. logging policy and exact selected-set probability, explicit per-candidate verifier
  269. verdicts, or both creates a schema-v2 receipt. These fields are integrity-protected
  270. and observational: Aura does not use them for recall, importance, decay, retention,
  271. consolidation, or forgetting.
  272. The key `(namespace, task_id, attempt_id)` is idempotent; a conflicting retry is
  273. rejected. Candidate records must exist in the same namespace, selected IDs must
  274. be a subset, and persisted receipts carry an integrity digest. Receipts live in
  275. the managed audit journal, remain outside cognitive records, and have no effect
  276. on recall, strength, retention, consolidation, or forgetting. A full `history`
  277. purge removes receipts that reference the purged record.
  278. This API passed a frozen 96-case contract experiment. Using receipts to alter
  279. ranking or retention remains gated on a separate temporal holdout with real,
  280. verified outcomes.
  281. ### Immutable Evidence Lineage
  282. Aura's cognitive provenance explains how a memory was formed and used. The
  283. evidence substrate additionally binds an extracted claim to the exact bytes of
  284. an immutable source revision:
  285. ```rust
  286. use aura::{admission_decision, verify_lineage, AnswerPermission, EvidenceClaim,
  287. SourceDocument, SourceSpan, VerificationStatus};
  288. let bytes = b"Verified value: 42";
  289. let document = SourceDocument::from_bytes("report", "v1", "file:///report.txt", bytes);
  290. let span = SourceSpan::from_document(&document, bytes, 0, bytes.len())?;
  291. let integrity = verify_lineage(&document, bytes, &span);
  292. ```
  293. `VerificationStatus` and `AnswerPermission` are independent gates. A high
  294. confidence score never overrides a changed source hash, a superseded claim, or
  295. a blocked citation. New `Record` fields remain backward-compatible with older
  296. serialized records.
  297. Evidence-aware research reports are composed only from admitted findings.
  298. Free-form synthesis is omitted until the synthesis itself can carry claim-level
  299. lineage, preventing blocked source material from being reintroduced indirectly.
  300. ### Context Capsules
  301. Agents can request a deterministic hot-context projection without maintaining a
  302. separate wiki or mutating memory through recall activation:
  303. ```python
  304. capsule = brain.build_context_capsule(
  305. purpose="continue the current institute research",
  306. token_budget=2000,
  307. namespace="ask-institute",
  308. )
  309. ```
  310. The bounded capsule prioritizes refutation scars, open evidence debt, active
  311. goals, contradictions, outcomes, decisions, and durable domain/identity
  312. records. It returns an estimated token count, omitted-record count, selection
  313. reasons, and a stable content hash. Blocked records and superseded versions
  314. outside their validity interval are never surfaced.
  315. When the prompt budget is tight, agents can opt into deterministic loss-aware
  316. packing:
  317. ```python
  318. result = brain.build_compacted_context_capsule(
  319. purpose="continue the current institute research",
  320. token_budget=2000,
  321. namespace="ask-institute",
  322. )
  323. entries = result["entries"]
  324. report = result["compaction"]
  325. print(report["additional_entry_count"], report["saved_tokens"])
  326. ```
  327. This mode removes exact sentence duplication and safe discourse prefixes before
  328. packing, without calling an LLM or changing stored records. Active goals and
  329. non-text payloads are excluded from compaction because local-model evaluation
  330. showed that removing apparently redundant emphasis from an active instruction
  331. can change a smaller model's answer. The normal token-budget truncation can
  332. still apply to an oversized final entry. Every returned entry retains its
  333. original `record_id`, so the full stored record remains available through
  334. `brain.get(record_id)`. The existing `build_context_capsule()` behavior is
  335. unchanged.
  336. ### Citation-Locked Retrieval Episodes
  337. For answers that must be auditable, Aura can track which evidence was actually
  338. opened during one retrieval episode and require every atomic answer claim to be
  339. covered by an opened, citable source:
  340. ```python
  341. source = b"The current launch date is September 24."
  342. episode = brain.start_retrieval_episode(
  343. "What is the current launch date?",
  344. candidate_ids=[launch_record_id],
  345. routes=["timeline"],
  346. )
  347. episode.open_verified_evidence(
  348. record_id=launch_record_id,
  349. claim_id="claim-launch-date",
  350. claim_text="The current launch date is September 24.",
  351. route="timeline",
  352. support_keys=["launch-date"],
  353. document_id="launch-plan",
  354. revision_id="rev-2",
  355. uri="memory://launch-plan",
  356. registered_source_bytes=source,
  357. current_source_bytes=source,
  358. byte_start=0,
  359. byte_end=len(source),
  360. verification_status="verified",
  361. answer_permission="cite",
  362. )
  363. gate = episode.finalize(
  364. answer_present=True,
  365. citations=[launch_record_id],
  366. atomic_claim_keys=["launch-date"],
  367. )
  368. if not gate["answer_permitted"]:
  369. answer = "UNKNOWN"
  370. ```
  371. `registered_source_bytes` establish the immutable document revision and span;
  372. `current_source_bytes` are rechecked when the agent opens the evidence. Changed,
  373. superseded, contested, context-only, blocked, unopened, or partially supporting
  374. evidence cannot authorize an answer. `brain.suggest_memory_intent(query)` offers
  375. a deterministic advisory route, while unknown queries conservatively retain all
  376. routes. Hosts supply trusted source snapshots, verification status and claim-support
  377. keys. The gate checks byte lineage and declared coverage; hosts remain responsible
  378. for semantic support and access authorization. It does not independently verify
  379. that a source entails the answer or is still current after opening.
  380. Retrieval episodes are ephemeral and read-only: they do not activate or
  381. rewrite stored records, and the existing recall APIs remain unchanged.
  382. ### Context-Aware Applicability
  383. Semantic relevance does not guarantee that an old experience is safe to reuse
  384. in the agent's current situation. Experience records can declare hard,
  385. model-independent preconditions in metadata:
  386. ```python
  387. experience = brain.store(
  388. "Refresh the expired token and retry deployment",
  389. level=Level.DECISIONS,
  390. semantic_type="decision",
  391. metadata={
  392. "applicability.require.cause": "expired_token",
  393. "applicability.require.environment": "ready",
  394. },
  395. )
  396. results = brain.recall_with_applicability(
  397. "deployment authentication recovery",
  398. current_state={
  399. "cause": ["permission_denied"],
  400. "environment": ["ready"],
  401. },
  402. top_k=5,
  403. )
  404. print(results[0]["applicability"]["decision"])
  405. ```
  406. Every recalled record is annotated as `use`, `reject`, or `unknown`, with
  407. matched, missing, conflicting, and mismatched fields. Aura does not filter or
  408. rerank the results and never guesses missing state. The host agent remains in
  409. control of whether to adapt an `unknown` memory. Existing `recall()` and
  410. `recall_structured()` behavior is unchanged.
  411. ### Portable Store Containers
  412. Aura can package its durable memory artifacts into one portable `.aura` file:
  413. ```python
  414. report = brain.export_container("./snapshots/agent-memory.aura")
  415. # For provenance-sensitive backups, keep the private key outside the Aura
  416. # store and create a signed chain from generation one.
  417. keys = Aura.generate_container_signing_key()
  418. signed = brain.export_signed_container(
  419. "./snapshots/agent-memory-signed.aura",
  420. keys["private_key"],
  421. )
  422. auth = Aura.verify_container_authenticity(
  423. "./snapshots/agent-memory-signed.aura",
  424. trusted_public_key=keys["public_key"],
  425. require_all_signed=True,
  426. )
  427. print(auth["public_key"], auth["latest_manifest_sha256"])
  428. Aura.update_container_authenticity_checkpoint(
  429. "./snapshots/agent-memory-signed.aura",
  430. "./trusted-state/agent-memory.checkpoint.json",
  431. trusted_public_key=keys["public_key"],
  432. )
  433. Aura.verify_container_authenticity_checkpoint(
  434. "./snapshots/agent-memory-signed.aura",
  435. "./trusted-state/agent-memory.checkpoint.json",
  436. )
  437. Aura.import_authenticated_container(
  438. "./snapshots/agent-memory-signed.aura",
  439. "./trusted-restore",
  440. trusted_public_key=keys["public_key"],
  441. require_all_signed=True,
  442. )
  443. # Later snapshots append only changed artifacts. Unchanged segments are
  444. # referenced from the previous committed generation.
  445. delta = brain.append_container("./snapshots/agent-memory.aura")
  446. print(delta["generation"], delta["changed_segment_count"])
  447. signed_delta = brain.append_signed_container(
  448. "./snapshots/agent-memory-signed.aura",
  449. keys["private_key"],
  450. )
  451. # Inspect retention history and garbage-collect unreachable generations.
  452. history = Aura.list_container_generations("./snapshots/agent-memory.aura")
  453. change = Aura.diff_container_generations(
  454. "./snapshots/agent-memory.aura",
  455. from_generation=7,
  456. to_generation=8,
  457. )
  458. Aura.import_container_generation(
  459. "./snapshots/agent-memory.aura",
  460. "./restored-generation-7",
  461. generation=7,
  462. )
  463. gc = Aura.compact_container(
  464. "./snapshots/agent-memory.aura",
  465. keep_last=10,
  466. )
  467. print(gc["kept_generations"], gc["reclaimed_bytes"])
  468. policy = Aura.apply_container_retention(
  469. "./snapshots/agent-memory.aura",
  470. min_generations=2,
  471. max_generations=20,
  472. max_age_seconds=30 * 24 * 60 * 60,
  473. max_size_bytes=512 * 1024 * 1024,
  474. )
  475. print(policy["selected_keep_last"], policy["size_target_met"])
  476. # Dry-run makes no filesystem changes.
  477. plan = Aura.plan_container_retention(
  478. "./snapshots/agent-memory.aura",
  479. min_generations=2,
  480. max_generations=20,
  481. max_age_seconds=30 * 24 * 60 * 60,
  482. max_size_bytes=512 * 1024 * 1024,
  483. )
  484. print(plan["keep_generations"], plan["drop_generations"])
  485. # Legal holds are persisted as append-only control generations.
  486. Aura.hold_container_generation(
  487. "./snapshots/agent-memory.aura",
  488. generation=7,
  489. label="legal-case-42",
  490. )
  491. Aura.release_container_generation_hold(
  492. "./snapshots/agent-memory.aura",
  493. generation=7,
  494. )
  495. # Signed chains require signed control generations too.
  496. Aura.hold_signed_container_generation(
  497. "./snapshots/agent-memory-signed.aura",
  498. generation=1,
  499. label="legal-case-42",
  500. signing_key=keys["private_key"],
  501. )
  502. # Or enforce the same policy automatically after every committed append.
  503. managed = brain.append_container_with_retention(
  504. "./snapshots/agent-memory.aura",
  505. min_generations=2,
  506. max_generations=20,
  507. max_age_seconds=30 * 24 * 60 * 60,
  508. max_size_bytes=512 * 1024 * 1024,
  509. )
  510. # One scheduler can run per Aura instance and stops when Aura closes.
  511. brain.start_container_retention_scheduler(
  512. "./snapshots/agent-memory.aura",
  513. interval_seconds=3600,
  514. min_generations=2,
  515. max_generations=20,
  516. max_age_seconds=30 * 24 * 60 * 60,
  517. max_size_bytes=512 * 1024 * 1024,
  518. )
  519. # Inspection reads only the checksummed table of contents; verification also
  520. # decompresses every segment and checks its SHA-256 digest.
  521. toc = Aura.inspect_container("./snapshots/agent-memory.aura")
  522. Aura.verify_container("./snapshots/agent-memory.aura")
  523. # Read, verify, or extract only selected logical segments.
  524. brain_log = Aura.read_container_segment(
  525. "./snapshots/agent-memory.aura", "brain.cog"
  526. )
  527. Aura.verify_container_segments(
  528. "./snapshots/agent-memory.aura", ["brain.cog", "index/sdr.idx"]
  529. )
  530. Aura.extract_container_segments(
  531. "./snapshots/agent-memory.aura",
  532. "./diagnostic-extract",
  533. ["brain.cog"],
  534. )
  535. # Import is deliberately restore-only: the target path must not exist.
  536. Aura.import_container("./snapshots/agent-memory.aura", "./restored-memory")
  537. restored = Aura("./restored-memory")
  538. ```
  539. The versioned container uses independently compressed Zstd segments, bounded
  540. sizes, a checksummed table of contents, and per-segment SHA-256 integrity.
  541. Version 2 stores append-only generation frames: a generation becomes visible
  542. only after its frame header is committed, so an interrupted append falls back
  543. to the previous valid generation. Unchanged segments retain their original
  544. offsets, removed artifacts disappear from the latest logical TOC, and a no-op
  545. append adds no bytes. Version 1 containers remain readable; incremental append
  546. requires a v2 container created by the current exporter.
  547. Compaction retains the latest `N` committed generations with their original
  548. generation numbers, verifies every reachable segment while rebuilding, and
  549. replaces the old file only after the compacted container passes validation.
  550. Unreachable payloads, dropped TOCs, and incomplete trailing frames are removed.
  551. `keep_last` must be at least one; if the container already satisfies the
  552. retention policy, compaction is a no-op. Version 1 containers must first be
  553. restored and exported as v2 before they can be compacted.
  554. Retained generations can be independently inspected, SHA-256 verified, read,
  555. diffed, or restored to a new directory. Generation diffs deterministically
  556. separate added, removed, content-changed, and unchanged artifacts.
  557. Automatic retention combines generation-count, wall-clock age, and estimated
  558. compacted-size limits by selecting the most restrictive contiguous suffix.
  559. `min_generations` is a hard floor (default `1`), and at least one maximum must
  560. be configured. If even the minimum retained snapshot exceeds
  561. `max_size_bytes`, compaction still preserves the floor and returns
  562. `size_target_met=False` instead of deleting required history.
  563. `append_container_with_retention()` commits the new generation first and then
  564. applies the policy. If retention fails, the append remains valid and its error
  565. is returned; a later policy run can safely retry cleanup.
  566. Dry-run plans report exact keep/drop generation IDs, estimated compacted size,
  567. active holds, and whether policy limits are blocked by a hold. Legal holds are
  568. stored inside the container as append-only control generations and propagate
  569. through later snapshots. Because generations form a contiguous chain, holding
  570. generation `N` preserves the full suffix from `N` through the latest
  571. generation. Manual compaction and automatic retention both honor that floor.
  572. The optional background scheduler uses the same mutation lock as export,
  573. append, compaction, retention, and hold operations, records its last run/error,
  574. and can be stopped without waiting for the interval. Mutations are serialized
  575. both between threads and between cooperating OS processes through an advisory
  576. sidecar lock such as `agent-memory.aura.lock`. Lock acquisition times out after
  577. 30 seconds with an explicit error. The zero-content sidecar is intentionally
  578. kept after release so that concurrent processes always address the same OS lock
  579. object; it does not indicate that a lock is currently held. Processes that
  580. modify `.aura` files without using Aura APIs must coordinate on the same lock.
  581. Signed containers use Ed25519 over a canonical logical generation manifest:
  582. generation metadata, legal holds, and each artifact's name, original size, and
  583. SHA-256 digest. Physical segment offsets are excluded, so verified compaction
  584. preserves existing signatures. Each signed manifest commits to the preceding
  585. signed manifest digest. `inspect`, `verify`, and import reject invalid
  586. signatures automatically; `verify_container_authenticity()` additionally pins
  587. the expected public key and can require every retained generation to be signed.
  588. An existing unsigned v2 container can start a signed epoch with a signed append,
  589. even when no artifact changed. After that, unsigned append and unsigned hold
  590. operations are rejected. Retention may leave the first retained signature with
  591. a detached predecessor digest, reported as `detached_prefix=True`.
  592. Keep signing private keys outside the Aura store and portable containers.
  593. Signatures authenticate retained history but cannot by themselves detect
  594. rollback to an older, otherwise valid signed container. For anti-rollback,
  595. persist and compare `latest_manifest_sha256` in an external trusted system.
  596. Aura's optional authenticity checkpoint automates this comparison: it pins the
  597. signing identity plus the highest accepted generation and manifest digest,
  598. rejects older generations and same-generation forks, and advances atomically.
  599. Store the checkpoint outside the Aura memory directory with trusted filesystem
  600. permissions; deleting or modifying both the container and its checkpoint is
  601. outside this local protection model. None of this is enabled or required for
  602. ordinary unsigned `export_container()` / `import_container()` usage.
  603. Extraction rejects absolute paths, traversal, duplicate names, overlapping
  604. ranges, corruption, and existing destinations. It is an additive snapshot
  605. format, not the live storage backend. Credential files, RBAC secrets, API keys,
  606. and encryption key material are intentionally excluded and must be managed
  607. separately. In Rust this support is controlled by the `capsule` feature and is
  608. included in the default `full` build.
  609. ### Temporal Memory Versioning
  610. Context answers what an agent needs now; memory also needs to preserve which
  611. version of a fact was valid at a particular time. Aura records business-time
  612. validity separately from the system time at which a replacement was recorded:
  613. ```python
  614. old_id = brain.store(
  615. "The refund window is 30 days",
  616. namespace="shop-a",
  617. valid_from=1_735_689_600,
  618. )
  619. new_id = brain.supersede(
  620. old_id,
  621. "The refund window is 14 days",
  622. namespace="shop-a",
  623. effective_at=1_751_328_000,
  624. )
  625. historical = brain.recall_as_of(
  626. "refund window",
  627. timestamp=1_743_811_200,
  628. namespace="shop-a",
  629. )
  630. ```
  631. Validity intervals are half-open: `valid_from <= time < valid_until`. Ordinary
  632. recall, search, and context capsules return only records valid now; expired and
  633. future versions remain available for audit through `get()`, `history()`,
  634. `version_chain()`, and `recall_as_of()`. `recall_at()` retains its system-time
  635. knowledge cutoff, while `recall_as_of()` answers the business-time question
  636. using everything Aura knows now. Namespace isolation applies to both paths.
  637. Supersession is committed as one durable cognitive-journal frame: the old
  638. validity boundary, successor, and causal links either replay together or do not
  639. apply. On startup Aura also repairs the `pending` marker written by older
  640. releases after an interrupted replacement.
  641. ### Inspectable Memory Decisions
  642. `explain_recall()` uses the same retrieval and bounded-reranking pipeline as
  643. normal recall, but does not activate or mutate records. In addition to the
  644. selected items and their existing score/provenance traces, it reports relevant
  645. candidates rejected by memory gates:
  646. ```python
  647. decision = brain.explain_recall(
  648. "refund window",
  649. top_k=5,
  650. namespace="shop-a",
  651. )
  652. print(decision["trace_id"])
  653. print(decision["decision_summary"]["rejection_counts"])
  654. for candidate in decision["rejected_candidates"]:
  655. print(candidate["record_id"], candidate["reasons"])
  656. ```
  657. Current rejection reasons are `expired`, `not_yet_valid`,
  658. `invalid_temporal_bounds`, `below_strength_threshold`, `outside_top_k`, and
  659. `suppressed_by_belief_resolution`. For belief competition, selected and
  660. rejected entries expose the candidate hypothesis, winning hypothesis, both
  661. scores, and whether the record belongs to the winning side. Rejected output is
  662. bounded and includes omission counts. Candidate discovery is performed only
  663. inside the requested namespace scope: records belonging to another tenant are
  664. never represented in the trace, even by ID. The generated `memory_trace_id`,
  665. selected count, and rejected count are also attached to the existing
  666. OpenTelemetry span without logging the query or record contents.
  667. ### Governed Promotion and Contradiction Safety
  668. Memory level controls retention, not truth. Aura therefore uses one governed
  669. policy for automatic reflection and promotion-candidate surfaces:
  670. - Working records may graduate to Decisions through repeated use.
  671. - Promotion into Domain or Identity pauses when a record is an explicit
  672. contradiction, carries conflict mass, or has volatility of `0.20` or more.
  673. - Domain-to-Identity promotion additionally requires at least 20 activations
  674. and `0.90` strength.
  675. - Expired and not-yet-valid versions are never promoted.
  676. During maintenance, conflict and volatility are refreshed before promotion.
  677. Explicit `contradicts`/`conflict` links form competing belief hypotheses rather
  678. than collapsing both sides into one bucket. Hypothesis recency uses business
  679. validity (`valid_from`) or creation time—not `last_activated`—so retrieving a
  680. stale rule cannot make its evidence fresh again. When a belief is resolved,
  681. the winning hypothesis is admitted to current recall and the losing side stays
  682. available through history and `explain_recall()` as suppressed evidence.
  683. Aura only resolves an explicit conflict graph as two competing sides when the
  684. graph is one connected bipartite component. Odd cycles, multiple independent
  685. components, isolated claims, and conflict sets without a defensible binary
  686. topology remain `Unresolved`; no record receives a synthetic winning vote.
  687. Use `promotion_block_reason(record_id)` to inspect why a record cannot advance.
  688. For a genuine rule replacement, prefer `supersede(..., effective_at=...)`; use
  689. an explicit `contradicts` relationship when both claims must remain auditable
  690. as competing evidence.
  691. **Core Cognitive Runtime**
  692. - **Fast Local Recall** - Multi-signal SDR + BM25 + N-gram + tag ranking with optional embedding support
  693. - **Two-Tier Memory** — Cognitive (ephemeral) + Core (permanent) with decay, promotion, and archival
  694. - **Semantic Memory Types** — 6 roles (`fact`, `decision`, `trend`, `preference`, `contradiction`, `serendipity`) that influence memory behavior and insighting
  695. - **Phase-Based Insights** — Detects conflicts, trends, preference patterns, and cross-domain links
  696. - **Background Maintenance** — Continuous memory hygiene: decay, reflect, insights, consolidation, archival
  697. - **Namespace Isolation** — `namespace="sandbox"` keeps test data invisible to production recall
  698. - **Pluggable Embeddings** - Optional embedding support: bring your own embedding function
  699. **Trust & Safety**
  700. - **Trust & Provenance** — Source authority scoring: user input outranks web scrapes, automatically
  701. - **Source Type Tracking** — Every memory carries provenance: `recorded`, `retrieved`, `inferred`, `generated`
  702. - **Auto-Protect Guards** — Detects phone numbers, emails, wallets, API keys automatically
  703. - **Encryption** — ChaCha20-Poly1305 with Argon2id key derivation
  704. **Adaptive Memory**
  705. - **Portable `.aura` Containers** — single-file, Zstd-compressed, SHA-256-verified store snapshots with restore-only safe import
  706. - **Feedback Learning** — `brain.feedback(id, useful=True)` boosts useful memories, weakens noise
  707. - **Temporal Semantic Versioning** — `brain.supersede(old_id, new_content, effective_at=...)` with validity intervals and full version chains
  708. - **Snapshots & Rollback** — `brain.snapshot("v1")` / `brain.rollback("v1")` / `brain.diff("v1","v2")`
  709. - **Agent-to-Agent Sharing** — `export_context()` / `import_context()` with trust metadata
  710. **Enterprise & Integrations**
  711. - **Multimodal Stubs** — `store_image()` / `store_audio_transcript()` with media provenance
  712. - **Prometheus Metrics** — `/metrics` endpoint with 10+ business-level counters and histograms
  713. - **OpenTelemetry** — `telemetry` feature flag with OTLP export and 17 instrumented spans
  714. - **MCP Server** — Claude Desktop integration out of the box
  715. - **WASM-Ready** — `StorageBackend` trait abstraction (`FsBackend` + `MemoryBackend`)
  716. - **Pure Rust Core** — No Python dependencies, no external services
  717. ---
  718. **Advisory Cognitive Overlays**
  719. - **Belief-Aware Recall Rerank** — bounded production influence with strict guardrails
  720. - **Concept Overlay** — surfaced concepts, per-record annotations, and optional bounded concept-aware reranking
  721. - **Causal / Policy Overlays** — advisory surfaced output only, no automatic control path
  722. - **Cross-Namespace Analytics** — read-only digest for tags, concepts, structural overlap, and canonical causal signatures across namespaces
  723. **Explainability & Governed Adaptation**
  724. - **Explainability APIs** — inspectable selected/rejected decisions through `explain_recall()`, including per-signal BM25 traces, plus `explain_record()`, `provenance_chain()`, and `explainability_bundle()`
  725. - **Durable recall replay** — `replay_recall(trace_id)` reruns one of the latest 128 persisted traces and reports ranking additions, removals, moves, and score drift
  726. - **Permission-aware retrieval** — per-record public/restricted ACLs with role, group, and principal allow-lists plus `audit` and deny-by-default `enforce` modes
  727. - **Correction Governance** — correction log, correction review queue, suggested corrections, namespace governance status
  728. - **Autonomous Cognitive Plasticity** — extraction → ingest → maintenance loop for bounded self-adaptation without changing model weights
  729. - **Plasticity Safety Bounds** — generated-confidence ceiling, risk throttling, purge/freeze controls, operator-visible risk state
  730. **Cognitive Guidance**
  731. - **Salience Layer** — bounded significance weighting for preservation, reminders, ranking, and operator review
  732. - **Maintenance Reflection** — bounded reflection summaries and digests produced inside the normal maintenance pipeline
  733. - **Contradiction Governance** — instability summaries, contradiction clusters, and bounded operator review queues for unresolved evidence
  734. - **Honest Answer Support** — non-anthropomorphic phrasing hints for significance, uncertainty, contradiction, and reflection context
  735. ## Quick Start
  736. ### Trust & Provenance
  737. ```python
  738. from aura import Aura, TrustConfig
  739. brain = Aura("./data")
  740. tc = TrustConfig()
  741. tc.source_trust = {"user": 1.0, "api": 0.8, "web_scrape": 0.5}
  742. brain.set_trust_config(tc)
  743. # User facts always rank higher than scraped data in recall
  744. brain.store("User is vegan", channel="user")
  745. brain.store("User might like steak restaurants", channel="web_scrape")
  746. results = brain.recall_structured("food preferences", top_k=5)
  747. # -> "User is vegan" scores higher, always
  748. ```
  749. ### Pluggable Embeddings (Optional)
  750. ```python
  751. from aura import Aura
  752. brain = Aura("./data")
  753. # Plug in any embedding function: OpenAI, Ollama, sentence-transformers, etc.
  754. from sentence_transformers import SentenceTransformer
  755. model = SentenceTransformer("all-MiniLM-L6-v2")
  756. brain.set_embedding_fn(lambda text: model.encode(text).tolist())
  757. # Now "login problems" matches "Authentication failed" via semantic similarity
  758. brain.store("Authentication failed for user admin")
  759. results = brain.recall_structured("login problems", top_k=5)
  760. ```
  761. Without embeddings, Aura continues to use its local recall pipeline - still fast, still effective.
  762. ### Claim Certainty (Optional LLM)
  763. Aura records whether each memory is first-hand (`asserted`), qualified (`hedged`),
  764. a guess (`speculative`), or relayed from someone else (`hearsay`). Relayed and
  765. uncertain claims are still stored, but with lower confidence, and they never
  766. count as first-hand evidence for advice.
  767. Built-in rules catch obvious phrasings without any model. For better coverage,
  768. plug in a small local LLM:
  769. ```python
  770. import json, urllib.request
  771. PROMPT = (
  772. "Classify what kind of claim the sentence makes. Answer with exactly one word: "
  773. "asserted, hearsay, hedged or speculative.\nSentence: {text}\nAnswer:"
  774. )
  775. def classify(text):
  776. body = json.dumps({"model": "qwen3:4b-instruct", "prompt": PROMPT.format(text=text),
  777. "stream": False, "options": {"temperature": 0, "num_predict": 8}}).encode()
  778. req = urllib.request.Request("http://127.0.0.1:11434/api/generate", data=body,
  779. headers={"Content-Type": "application/json"})
  780. answer = json.loads(urllib.request.urlopen(req).read())["response"].strip().lower()
  781. return next((l for l in ("asserted", "hearsay", "hedged", "speculative") if l in answer), None)
  782. brain.set_claim_classifier(classify) # returning None falls back to the built-in rules
  783. brain.store("I was born on May 12") # asserted, Identity level
  784. brain.store("I heard the plant closed") # hearsay, lower confidence
  785. ```
  786. On an independent test set, `qwen3:4b-instruct` via this hook reached hearsay
  787. recall 0.88 and precision 0.92 without demoting any first-hand statement
  788. (~0.3 s per write); the built-in rules alone reached recall 0.53. Those numbers
  789. were measured with the longer prompt that defines each label, in
  790. `experiments/claim_certainty/llm_eval.py`; the short prompt above is only an
  791. illustration. See `experiments/claim_certainty` for the full evaluation.
  792. ### Encryption
  793. ```python
  794. brain = Aura("./secret_data", password="my-secure-password")
  795. brain.store("Top secret information")
  796. assert brain.is_encrypted() # ChaCha20-Poly1305 + Argon2id
  797. ```
  798. Password protection now covers the cognitive journal and snapshots, audit entries,
  799. derived cognitive state, recall replay history, and stored embeddings. Reopening
  800. requires the correct password and the original `memory.key` file. Back up that
  801. wrapped key separately: portable containers intentionally exclude key material.
  802. Use a new, empty directory when enabling encryption. Adding a password to an
  803. existing store is rejected because its journals, snapshots, and backups may
  804. already contain plaintext. Existing unencrypted stores remain readable without a
  805. password; moving them to encrypted storage requires an explicit migration. Older
  806. password-created stores did not protect all cognitive data and must also be
  807. migrated. Explicit JSON exports return plaintext to the caller.
  808. ### Deletion and managed purge
  809. `delete(record_id)` is the ordinary explicit deletion path. Aura durably writes
  810. the tombstone before removing the record from active recall and invalidates
  811. beliefs, concepts, causal patterns, policy hints, topology, reflections, and
  812. replay baselines that depended on it. Natural cognitive forgetting is unchanged:
  813. cold traces and refuted consequence scars still follow the normal retention
  814. policy.
  815. Use `purge_record` when bytes must also be removed from managed storage. The
  816. scope is required and cumulative: `active`, `derived`, `current_storage`,
  817. or `history`. The `history` scope rewrites Aura's current stores, audit
  818. rotations, and named snapshots, and leaves a receipt containing only a SHA-256
  819. record digest and the completed surfaces.
  820. ```python
  821. receipt = brain.purge_record(record_id, "history")
  822. print(receipt["record_digest"], receipt["removed_surfaces"])
  823. ```
  824. Files exported or copied outside the Aura brain directory are not managed by
  825. this call and must be removed by their owner.
  826. Externally supplied embeddings persist across restart. Re-register a Python
  827. embedding callback after reopening to compute query vectors with the same model.
  828. Embedding writes reject empty, non-finite, or incompatible-dimensional vectors;
  829. Rust callers should handle the returned `Result` from `store_embedding` and
  830. `remove_embedding`.
  831. ### Semantic Memory Types
  832. ```python
  833. brain = Aura("./data")
  834. # Decisions are treated as higher-value memory
  835. brain.store("Use PostgreSQL over MySQL", semantic_type="decision", tags=["db"])
  836. # Preferences persist longer than generic working notes
  837. brain.store("User prefers dark mode", semantic_type="preference", tags=["ui"])
  838. # Contradictions are preserved for conflict analysis
  839. brain.store("User said vegan but ordered steak", semantic_type="contradiction")
  840. # Search by semantic type
  841. decisions = brain.search(semantic_type="decision")
  842. # Cross-domain insights surface higher-level patterns
  843. insights = brain.insights(phase=2)
  844. # Example:
  845. # [{'insight_type': 'preference_pattern', 'description': 'Preference cluster around ui', ...}]
  846. ```
  847. ### Namespace Isolation
  848. ```python
  849. brain = Aura("./data")
  850. brain.store("Real preference: dark mode", namespace="default")
  851. brain.store("Test: user likes light mode", namespace="sandbox")
  852. # Recall only sees "default" namespace — sandbox is invisible
  853. results = brain.recall_structured("user preference", top_k=5)
  854. ```
  855. ### Cross-Namespace Digest
  856. Use this when you need inspection-only analytics across isolated namespaces without changing recall behavior.
  857. ```python
  858. brain = Aura("./data")
  859. digest = brain.cross_namespace_digest(
  860. namespaces=["default", "sandbox"],
  861. top_concepts_limit=3,
  862. )
  863. # Top concepts per namespace
  864. print(digest["namespaces"][0]["top_concepts"])
  865. # Pairwise overlap
  866. print(digest["pairs"][0]["shared_tags"])
  867. print(digest["pairs"][0]["shared_concept_signatures"])
  868. print(digest["pairs"][0]["shared_causal_signatures"])
  869. ```
  870. HTTP server:
  871. ```text
  872. GET /cross-namespace-digest?namespaces=default,sandbox&top_concepts_limit=3
  873. ```
  874. MCP tool:
  875. ```json
  876. {
  877. "tool": "cross_namespace_digest",
  878. "arguments": {
  879. "namespaces": ["default", "sandbox"],
  880. "top_concepts_limit": 3
  881. }
  882. }
  883. ```
  884. The digest is read-only. It does not bypass namespace isolation in recall and does not feed training or inference by default.
  885. For richer operator-facing workflows, see [`examples/V3_OPERATOR_WORKFLOWS.md`](examples/V3_OPERATOR_WORKFLOWS.md).
  886. ### Autonomous Cognitive Plasticity
  887. Aura can also observe model output and feed bounded experience back into the cognitive substrate, without retraining the model.
  888. ```python
  889. from aura import Aura
  890. brain = Aura("./data")
  891. brain.set_plasticity_mode("limited")
  892. capture = brain.capture_experience(
  893. prompt="How should we deploy this release?",
  894. retrieved_context=[],
  895. model_response="Deploy to staging first, then verify health checks before production.",
  896. session_id="deploy-session-1",
  897. source="model_inference",
  898. )
  899. brain.ingest_experience_batch([capture])
  900. brain.run_maintenance() # queued experience enters the normal cognitive pipeline
  901. ```
  902. This stays bounded and operator-visible:
  903. - the model remains frozen
  904. - generated claims stay capped and guarded
  905. - adaptation can be inspected, restricted, purged, or frozen per namespace
  906. Recent operator HTTP endpoints:
  907. - `GET /explain-record`
  908. - `GET /explain-recall`
  909. - `GET /explainability-bundle`
  910. - `GET /correction-log`
  911. - `GET /cross-namespace-digest`
  912. - `GET /memory-health`
  913. - `GET /belief-instability`
  914. - `GET /policy-lifecycle`
  915. - `GET /correction-review-queue`
  916. - `GET /suggested-corrections`
  917. - `GET /namespace-governance-status`
  918. ---
  919. ## Cookbook: Personal Assistant That Remembers
  920. The killer use case: an agent that remembers your preferences after a week offline, with zero API calls.
  921. See [`examples/personal_assistant.py`](examples/personal_assistant.py) for the full runnable script.
  922. ```python
  923. from aura import Aura, Level
  924. brain = Aura("./assistant_memory")
  925. # Day 1: User tells the agent about themselves
  926. brain.store("User is vegan", level=Level.Identity, tags=["diet"])
  927. brain.store("User loves jazz music", level=Level.Identity, tags=["music"])
  928. brain.store("User works 10am-6pm", level=Level.Identity, tags=["schedule"])
  929. brain.store("Discuss quarterly report tomorrow", level=Level.Working, tags=["task"])
  930. # Simulate a week passing — run maintenance cycles
  931. for _ in range(7):
  932. brain.run_maintenance() # decay + reflect + consolidate + archive
  933. # Day 8: What does the agent remember?
  934. context = brain.recall("user preferences and personality")
  935. # -> Still remembers: vegan, jazz, schedule (Identity, strength ~0.93)
  936. # -> "quarterly report" decayed heavily (Working, strength ~0.21)
  937. ```
  938. Identity persists. Tasks fade. Important patterns get promoted. Like a real brain.
  939. ---
  940. ## MCP Server — Claude Desktop · Cursor · VS Code · any MCP client
  941. Aura's local stdio server has no Python dependencies beyond `aura-memory`.
  942. Install it, validate it, then generate the client-specific JSON:
  943. ```bash
  944. python -m pip install --upgrade aura-memory
  945. python -m aura mcp ./aura_brain --check
  946. python -m aura mcp ./aura_brain --print-config claude
  947. ```
  948. Use `cursor`, `vscode`, or `generic` instead of `claude` for another
  949. client. The generator writes an absolute brain path and the exact Python
  950. interpreter that owns Aura, so desktop applications do not depend on their
  951. `PATH` configuration. Paste the printed JSON into the client configuration.
  952. For an encrypted brain, set `AURA_PASSWORD` in the client's environment rather
  953. than placing the password in command-line arguments.
  954. The wheel also installs a direct command:
  955. ```bash
  956. aura-mcp ./aura_brain --check
  957. aura-mcp ./aura_brain
  958. ```
  959. Once connected, the client receives 11 tools:
  960. | Tool | Purpose |
  961. |------|---------|
  962. | `recall` | Retrieve relevant memories before answering |
  963. | `recall_structured` | Get memories with scores and metadata |
  964. | `store` | Save a fact, note, or context |
  965. | `store_code` | Save a code snippet at Domain level |
  966. | `store_decision` | Save a decision with reasoning |
  967. | `search` | Filter memories by level or tags |
  968. | `insights` | Memory health stats |
  969. | `consolidate` | Merge similar records |
  970. | `get` | Fetch a specific record by ID |
  971. | `delete` | Remove a record by ID |
  972. | `maintain` | Run a full maintenance cycle |
  973. > After connecting, tell the agent: *"Before answering, recall relevant context
  974. > from Aura. Store only durable facts, decisions, and useful patterns."*
  975. ### Automatic capture in Claude Code
  976. The MCP tools store only what the model decides to store. To remember every
  977. conversation instead, add Aura as a Claude Code hook:
  978. ```bash
  979. python -m aura capture ./aura_brain --print-config
  980. ```
  981. Merge the printed `hooks` block into `~/.claude/settings.json` (all projects)
  982. or `.claude/settings.json` (one project). Each turn is then stored verbatim,
  983. with its source taken from where it came from, never from what it says:
  984. | Event | Stored as |
  985. |------|---------|
  986. | your prompt | first-hand (`user-claude-code`) |
  987. | a tool's output — web page, file, MCP tool | untrusted data (`web`, `file`, `mcp:<server>`, `tool`) |
  988. | Claude's reply | model-written (`agent-claude-code`) |
  989. | Aura's own tool results | not stored |
  990. The hooks run in the background and only drop each event into
  991. `<brain>.inbox/`; the Aura MCP server stores them before its next tool call
  992. (or the hook does, when no server holds the brain). On 264 attack and utility
  993. cases, capture through the hooks matched direct role-split writes: injected
  994. content steered 10.5% of later answers (mem0 with the same capture: 30.5%),
  995. and every prompt was kept verbatim as first-hand
  996. (`experiments/hook_capture`, `experiments/auto_capture`).
  997. For remote automation, `aura serve` exposes REST plus the legacy HTTP+SSE MCP
  998. transport. Install its optional dependencies with
  999. `python -m pip install "aura-memory[http]"`. New local MCP integrations should
  1000. use stdio; the legacy HTTP+SSE transport is retained for existing Make.com and
  1001. n8n workflows.
  1002. `aura serve` binds `127.0.0.1` by default. To expose it on another interface,
  1003. set an API key (`--api-key` or `AURA_API_KEY`); clients then send
  1004. `Authorization: Bearer <key>`. Browser cross-origin access is off unless
  1005. `AURA_CORS_ORIGINS` lists allowed origins.
  1006. ### Windows test note
  1007. If `cargo test` intermittently fails on Windows with `LNK1104` for `target\debug\deps\aura-...exe`, a stale test process is usually holding the file open. Run:
  1008. ```powershell
  1009. powershell -ExecutionPolicy Bypass -File .\scripts\cleanup_windows_test_lock.ps1
  1010. ```
  1011. Then rerun the test command.
  1012. ---
  1013. ## Dashboard UI
  1014. Aura includes a standalone web dashboard for visual memory management. Download from [GitHub Releases](https://github.com/teolex2020/aura-memory/releases).
  1015. ```bash
  1016. ./aura-dashboard ./my_brain --port 8000
  1017. ```
  1018. **Features:** Analytics · Memory Explorer with filtering · Recall Console with live scoring · Batch ingest
  1019. | Platform | Binary |
  1020. |----------|--------|
  1021. | Windows x64 | `aura-dashboard-windows-x64.exe` |
  1022. | Linux x64 | `aura-dashboard-linux-x64` |
  1023. | macOS ARM | `aura-dashboard-macos-arm64` |
  1024. | macOS x64 | `aura-dashboard-macos-x64` |
  1025. ---
  1026. ## Integrations & Examples
  1027. **Try now:** [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/teolex2020/aura-memory/blob/main/examples/colab_quickstart.ipynb) — zero install, runs in browser
  1028. | Integration | Description | Link |
  1029. |-------------|-------------|------|
  1030. | Ollama | Fully local AI assistant, no API key needed | [`ollama_agent.py`](examples/ollama_agent.py) |
  1031. | LangChain | Drop-in Memory class + prompt injection | [`langchain_agent.py`](examples/langchain_agent.py) |
  1032. | LlamaIndex | Chat engine with persistent memory recall | [`llamaindex_agent.py`](examples/llamaindex_agent.py) |
  1033. | OpenAI Agents | Dynamic instructions with persistent memory | [`openai_agents.py`](examples/openai_agents.py) |
  1034. | Claude SDK | System prompt injection + tool use patterns | [`claude_sdk_agent.py`](examples/claude_sdk_agent.py) |
  1035. | CrewAI | Tool-based recall/store for crew agents | [`crewai_agent.py`](examples/crewai_agent.py) |
  1036. | AutoGen | Memory protocol implementation | [`autogen_agent.py`](examples/autogen_agent.py) |
  1037. | FastAPI | Per-user memory middleware with namespace isolation | [`fastapi_middleware.py`](examples/fastapi_middleware.py) |
  1038. **FFI (C/Go/C#):** [`aura.h`](examples/aura.h) · [`go/main.go`](examples/go/main.go) · [`csharp/Program.cs`](examples/csharp/Program.cs)
  1039. **More examples:** [`basic_usage.py`](examples/basic_usage.py) · [`encryption.py`](examples/encryption.py) · [`agent_memory.py`](examples/agent_memory.py) · [`edge_device.py`](examples/edge_device.py) · [`maintenance_daemon.py`](examples/maintenance_daemon.py) · [`research_bot.py`](examples/research_bot.py)
  1040. ---
  1041. ## Architecture
  1042. Aura uses a Rust core with Python bindings and a local-first memory runtime.
  1043. Publicly documented concepts are:
  1044. - Two-tier memory: cognitive + core
  1045. - Semantic roles for records
  1046. - Local multi-signal recall
  1047. - Belief-aware bounded reranking
  1048. - Trust, provenance, and namespace isolation
  1049. - Maintenance, insights, consolidation, and versioning
  1050. Higher cognitive layers may be present in the SDK as bounded reranking overlays and advisory inspection surfaces. They are not default runtime decision-making or behavior control.
  1051. The public repository documents the user-facing behavior and integration surface. Detailed internal architecture, tuning, and research notes are intentionally not published.
  1052. ---
  1053. ## Resources
  1054. - [Demo Video (30s)](https://www.youtube.com/watch?v=ZyE9P2_uKxg) — Quick overview
  1055. - [Examples](examples/) — Ready-to-run scripts
  1056. - [Landing Page](https://aurasdk.dev) — Project overview
  1057. ---
  1058. ## Contributing
  1059. Contributions welcome! See [CONTRIBUTING.md](CONTRIBUTING.md) for setup instructions and guidelines, or check the [open issues](https://github.com/teolex2020/aura-memory/issues).
  1060. ⭐ **If Aura saves you time, a [GitHub star](https://github.com/teolex2020/aura-memory) helps others discover it and helps us continue development.**
  1061. ---
  1062. ## License
  1063. MIT — see [LICENSE](LICENSE). There are no patent or commercial-licensing terms: use Aura in any project, including commercial ones.
  1064. ---
  1065. <p align="center">
  1066. Built in Kyiv, Ukraine 🇺🇦 — including during power outages.<br>
  1067. <sub>Solo developer project. If you find this useful, your star means more than you think.</sub>
  1068. </p>

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.