# Memory lifecycle
Enable `memory`. It builds on [`versioning`](VERSIONING.md), [`reasoning`](REASONING.md) and [`evidence-freshness`](EVIDENCE-FRESHNESS.md). It adds no dependency, no model and no background work. The application decides what to remember, what counts as a contradiction and when to remove records. AIRust applies those decisions explicitly. The call that causes them reports conflicts, new supersession markers and removals; [re-evaluated markers](#lifetime-of-a-supersession-marker) are visible through two accessors.
```rust
use airust::{KnowledgeEntry, evidence_freshness::SourceVersion, reasoning::Statement,
memory::{ConflictPolicy, Freshness, MemoryStore, RetentionPolicy, SourceCatalog},
versioning::{ChangeMetadata, ExpectedRevision}};
# fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut memory = MemoryStore::new()
.with_policy(ConflictPolicy::Report)
.with_single_valued(["capital"])?
.with_history_limit(64);
memory.remember(KnowledgeEntry::new("a", "The capital of France is Paris."),
vec![SourceVersion::new("atlas", "rev-1")?],
vec![Statement::new("france", "capital", "paris")?],
ExpectedRevision::Absent, ChangeMetadata::default(), 100)?;
let outcome = memory.remember(KnowledgeEntry::new("b", "The capital of France is Lyon."),
vec![SourceVersion::new("notes", "rev-7")?],
vec![Statement::new("france", "capital", "lyon")?],
ExpectedRevision::Absent, ChangeMetadata::default(), 200)?;
assert_eq!(outcome.conflicts.len(), 1);
let catalog = SourceCatalog::new([SourceVersion::new("atlas", "rev-2")?,
SourceVersion::new("notes", "rev-7")?])?;
assert!(matches!(memory.freshness("a", &catalog), Some(Freshness::Stale { .. })));
assert_eq!(memory.freshness("b", &catalog), Some(Freshness::Current));
let report = memory.apply_retention(&RetentionPolicy { max_records: Some(1), max_age_seconds: None }, 300, true)?;
assert_eq!(report.removed.len(), 1);
assert_eq!(memory.len(), 2);
# Ok(()) }
```
## What a memory record is
A record is a `KnowledgeEntry` in a `VersionedIndex`, plus:
- **Provenance.** Zero to 16 `SourceVersion` values, for example a document revision hash.
- **Claims.** Zero to 32 caller-supplied `reasoning::Statement` values (subject, predicate, object, negative). AIRust never extracts claims from text.
- **Times.** `created_at` and `updated_at`, from the caller-supplied `now` (seconds on any monotone caller clock). The library reads no system clock.
- **Flags.** `pinned` (exempt from retention) and `superseded_by` (set by `SupersedeOlder`).
`remember` takes the same `ExpectedRevision` as `versioning`, so concurrent writers detect stale expectations. `forget` is a versioned deletion; with a history limit, the deleted state stays in history.
## Conflicts
Two claims conflict in either of two cases:
- They are **explicit opposites**: the same statement with opposite `negative`.
- The predicate is declared **single-valued** with `with_single_valued`, and the claims have the same subject and predicate but different objects.
Free text without claims is never compared. Records already superseded do not raise new conflicts.
| Policy | Behavior on conflict |
| --- | --- |
| `Report` (default) | Stores the record and returns all conflicts in `RememberOutcome` |
| `Reject` | Returns `MemoryError::Rejected` with the conflicts and changes nothing |
| `SupersedeOlder` | Stores the record and marks every conflicting older record `superseded_by` the new ID. The older records stay searchable and in history. |
No policy decides which statement is true.
### Lifetime of a supersession marker
A `superseded_by` marker follows its superseding record. When that record is forgotten, removed by retention or stored again, every record it had superseded is evaluated again:
- The marker stays while the superseding record exists and still conflicts with the marked record.
- Otherwise, under `SupersedeOlder`, the marker moves to the most recently written record that was written after the marked record and conflicts with it.
- Without such a record, and always under `Report` and `Reject`, the marker is cleared and the record raises conflicts again.
"Written after" is the order of the `versioning` revisions, not the caller-supplied time. Storing the marked record itself again also clears its marker, as before.
These changes are not part of a return value. `superseded_records(id)` lists the records currently marked as superseded by `id`: call it before `forget`, before storing `id` again, or for each ID of a retention dry run, to see which markers will be evaluated, and read `superseded_by` afterwards. An evaluation compares one record with the records that share a subject and predicate with one of its claims, so its cost grows with that number.
Versions 0.6.4 and 0.6.5 kept a marker when its superseding record was removed or stopped conflicting. A snapshot written by them can therefore contain a marker that names a missing record. It is restored unchanged, the marked record raises no conflicts, and `superseded_records` lists it under the missing ID. Store the marked record again to evaluate it.
## Retention
`apply_retention(&policy, now, dry_run)` removes records only when the caller calls it.
- **Order.** Records older than `max_age_seconds` (by `updated_at`) go first. If more than `max_records` remain, the oldest unpinned records go next, ordered by `updated_at`, then ID.
- **Pinned records** are never removed.
- **Every removal** is listed in the `RetentionReport` with reason `Age` or `Capacity`, and is recorded as a versioned deletion with change reason `retention`.
- **`dry_run`** reports the same list and changes nothing.
## Freshness
`freshness(id, &SourceCatalog)` compares a record's provenance with a caller-supplied current catalog and returns one of:
- `Current`
- `Stale { changed }`
- `MissingSource { missing, changed }`
- `Unverifiable` (a record without provenance is never current)
`freshness_report` returns the status for every record. `search_with_status` returns the ordinary lexical search hits, each with its freshness and `superseded_by` marker; ranking is unchanged.
Staleness is reported, never repaired. A matching version label is the caller's assertion, not proof that the source is authentic or true.
## Persistence and bounds
`to_json` and `from_json` / `from_json_with_limit` (64 MiB default) store format 1, which embeds the versioned snapshot plus provenance, claims, times, pins, supersession markers, the policy and the single-valued predicates.
Import validates all of the following and rejects unknown fields:
- that records and metadata agree exactly;
- the provenance and claim limits;
- time order;
- statement labels;
- that no record supersedes itself.
Import does not change supersession markers; see [their lifetime](#lifetime-of-a-supersession-marker) for markers of earlier versions.
`MemoryLimits` bounds records (default 1,000,000), provenance items per record, claims per record and single-valued predicates. These bound the representation, not exact RAM use. All operations are synchronous.
The limits are not stored in the snapshot. `from_json` and `from_json_with_limit` validate against the default limits and return a store with the default limits. A store that was configured with `with_limits` is restored with `from_json_with_limits(input, max_bytes, limits)`: the snapshot is validated against the supplied limits and the restored store keeps them. A snapshot written under raised limits is rejected by the default-limit functions and stays readable through this one.
## Scope
This is a record-level lifecycle, not a truth engine. The following remain application responsibilities:
- extracting claims from text;
- semantic contradiction detection;
- source synchronization, embedding refresh and database transactions.
Criteria, measurements and limits for this feature are in the [0.6.4 scope](validation-0.6.4/SCOPE.md).