cell_memory library

The Durable Memory Surface of the Cell framework — the Hippocampus where a reactive signal becomes a stable, replayable record.

Memory retains the latest value; the ledger retains causality. A MemoryCell is itself a Cell — it loads stored data, receives pulses through the framework, and emits MemoryPulses downstream. Backends implement MemoryStore; this library ships the pure-Dart surface plus InMemoryMemoryStore. The dart:io-based FileMemoryStore lives in package:cell_memory/cell_memory_io.dart, so importing this library never pulls dart:io into a web build.

In the framework's biological metaphor, this is the Hippocampus: where short-lived signal activity is consolidated into a long-lived engram that survives the process. The cell package is the nervous system; this package is the durable trace it leaves.

When to use

Import package:cell_memory/cell_memory.dart when the app needs a reactive value to survive a process restart: remembered settings, a last-known selection, a persisted counter, an offline-tolerant cache of the latest read from a remote source.

Use remember for the one-call open + seed + attach shape; use MemoryCell.open followed by MemoryCell.attach when the seed step needs to run between open and attach, or when the cell is bound to an already-running domain.

For a pure-in-memory test double, InMemoryMemoryStore from this library is enough. For disk, add cell_memory_io.dart and use FileMemoryStore. For cloud, add the Firestore backend package; the MemoryStore contract is the same.

How it works

  1. Open — MemoryCell.open takes the source cell and a MemoryRecord (stable id, store, codec) plus optional MemoryStrategy, MemoryLifecycle, MemoryInfrastructure, and MemoryGovernance objects. It reads the last envelope (unless the mode is MemoryOpenMode.seed or MemoryOpenMode.dormant), decodes the payload, and emits one MemoryPulse of MemoryEvent.loaded.
  2. Ingest — Accepted pulses from an attached upstream cell, from remember's domain binding, or from direct ingress are encoded, adopted as the in-memory value, and a write is scheduled according to the policy. Every value movement is broadcast as a MemoryPulse — MemoryEvent.applied for an update, MemoryEvent.stored for a successful write.
  3. Commit — A write goes through MemoryStore.write under compare-and-swap. The record's revision advances; its generation is preserved (replaced only on delete-and-recreate).
  4. Replay — MemoryWritePolicy.replay (a policy with enabled: false) together with MemoryOpenMode.dormant lets a Causal Replay host run historical pulses through the cell without writing them back to the store.

Non-obvious

  • Stable ids, not Cell.id. The memory id is a durable name chosen by the caller. Cell.id is assigned per process and would rename the record on every restart. The two namespaces are unrelated; the id passed to MemoryCell.open is what names the record.
  • Revision vs. generation. revision is monotonic per id and advances on every successful write. generation is minted once per record life and copied on every revision, so a delete-and-recreate cannot be masqueraded by a stale writer as a normal update. See MemoryCas.
  • Codec-owned equality. A cell is dirty when the codec's encoded payload differs from what is stored — not when T.== says so. Two domain objects that compare equal as Dart values can still differ once encoded, and vice versa.
  • Shutdown is a barrier. A store call that was admitted finishes even if close() is called while it is queued; a call that arrives after close() throws. list() returns a settled snapshot. See MemoryStore.close for the per-backend semantics.

See also:

  • MemoryCell — the durable cell this library exists to provide.
  • MemoryStore — the backend contract every store implements.
  • MemoryEnvelope — the JSON document a backend persists.
  • MemoryIdGrammar — the stable-id law shared by every backend.
  • MemoryWritePolicy — when a write is scheduled (immediate, debounced, explicit, replay).
  • remember — one-call sugar for open + attach + seed.

AI Agent Guide

Layer: Memory — this is the persistence seam. Not a Cell factory, not a Flow operator, not a Tissue book. Memory retains the latest value; the ledger retains the causality; this library durably persists that latest value. When to use: a BRD says "remember this across restarts", "persist this setting", or "load the last known value on boot". When NOT to use:

  • for causal history (that is the ledger);
  • for optimistic concurrency across many records (that is a Firestore transaction, not a per-id CAS);
  • when the value is genuinely ephemeral — a Cell.state with no durability requirement is simpler;
  • as a substitute for a cell_tissue book — memory stores one value per id, not a collection. Live signature: library cell_memory; — pinned at cell_memory: 1.0.1. Do NOT confuse with: the core cell library (reactive graph, no persistence), cell_memory_io (the dart:io backend split), or cell_tissue (collection history, not single-value durability). Guide: see the memory HowTo for "choosing a store backend" and "when to use remember vs. MemoryCell.open + attach". Example: example/cell_memory.dart. Cross-layer: a Cell.observe side effect that writes into a MemoryCell is the Flow → Memory glue for persistence; the decision about what to persist stays in a cell_flow instruction. Minimal compilable example
final store = InMemoryMemoryStore();
final counter = await MemoryCell.open<int>(
  Cell.state<int>(initial: 0).cell,
  record: MemoryRecord<int>(
    id: 'counter',
    store: store,
    codec: JsonMemoryCodec<int>.identity(),
  ),
);
print(counter.loaded); // true
await counter.close();
await store.close();

Classes

ApplyInstruction<T>
The MemoryAction.apply capability: synchronous state adoption.
AttachInstruction<T>
The MemoryAction.attach capability: wire the upstream domain.
CloseInstruction<T>
The MemoryAction.close capability: final flush and shutdown.
CollectiveMemoryPulse<T>
A bundle of memory pulses travelling as one wave.
DetachInstruction<T>
The MemoryAction.detach capability: stop the upstream wiring.
InMemoryMemoryStore
A volatile, in-memory implementation of MemoryStore.
JsonListMemoryCodec<E>
A typed-list MemoryCodec: List<E> values load from a stored JSON array with elements cast to E.
JsonMapMemoryCodec<V>
A typed-map MemoryCodec: Map<String, V> values load from a stored JSON object with values cast to V.
JsonMemoryCodec<T>
The standard MemoryCodec implementation for JSON data structures.
JsonPayloadKey
A utility for consistent payload comparison and serialization.
LoadInstruction<T>
The MemoryAction.load capability: recovery and hydration.
LoadResult<T>
The result of MemoryCell.load().
ManualMemoryClock
A deterministic clock for tests.
ManualScheduler
A deterministic, virtual-time scheduler for tests.
MemoryCas
The pure compare-and-swap rule engine every store runs inside its atomic section.
MemoryCasAlreadyApplied
The store already holds this exact content: treat the write as having succeeded and return stored.
MemoryCasCommit
Commit the draft as revision nextRevision.
MemoryCasConflict
The write cannot proceed. stored carries the row the store holds, when the backend has it in hand.
MemoryCasResult
The result of one compare-and-swap decision.
MemoryCell<T> Getting Started Features Architecture
A durable Cell implementation that persists its state to a MemoryStore.
MemoryCellNucleus<T>
The Nucleus blueprint of a MemoryCell.
MemoryClock
A wall-clock seam for memory writes.
MemoryCodec<T>
A translation layer that converts application types to and from the JSON-compatible formats stored in a MemoryEnvelope.
MemoryConflictPolicy
How a memory cell reacts when its write loses the compare-and-swap race.
MemoryDraft
The document a writer proposes before the store assigns the next revision.
MemoryEnvelope
The standardized data container for all MemoryStore persistence operations.
MemoryFlushContext<T>
The durability context handed to a SaveInstruction.writeTurn override.
MemoryGovernance
The governance surface of a MemoryCell: the quartet MemoryCell.open and MemoryCell.deputy both declare.
MemoryIdGrammar
A utility class for validating the structure of memory identifiers.
MemoryInfrastructure
The system-level resources a MemoryCell runs on.
MemoryInstructionBase<T>
The subclassable base of the nine durability instructions.
MemoryLifecycle<T>
How a MemoryCell couples to the live value and to the store at open time.
MemoryPulse<T>
The structural signal emitted by a MemoryCell.
MemoryRecord<T>
The durable record a MemoryCell is opened around.
MemoryResolution
A manual conflict resolution: the same actions the conflict rules take, performed by the caller through resolve.
MemoryRetry
How a failed write is retried.
MemoryRuntime<T>
The one mutable holder of a MemoryCell's durability state.
MemoryScheduler
A timer seam for memory writes.
MemorySnapshot
A point-in-time view of the record a MemoryCell owns.
MemoryStore
The durable backend contract for cell_memory.
MemoryStoreCapabilities
What a store backend can actually guarantee.
MemoryStrategy
The durability rules of a MemoryCell: when writes happen, how conflicts resolve, and how long a stored record lives.
MemoryTimerHandle
A handle to one scheduled timer.
MemoryWritePolicy
The write-through configuration of a memory cell.
RemoveInstruction<T>
The MemoryAction.remove capability: delete the durable record.
ResolveInstruction<T>
The MemoryAction.resolve capability: conflict resolution.
SaveInstruction<T>
The MemoryAction.save capability: persistence and CAS logic.
SystemMemoryClock
A clock backed by the system wall clock.
TimerScheduler
A scheduler backed by real Timers.
UnloadInstruction<T>
The MemoryAction.unload capability: flush, detach, stop emitting.

Enums

MemoryAction
The durability actions a MemoryCell routes through its receptor chain.
MemoryEvent
What a MemoryCell just did. One event per emitted pulse.
MemoryOpenMode
What MemoryCell.open does about the store before the returned future completes.
MemoryStatus
The lifecycle state of a memory cell's record.
MemoryWriteMode
When an accepted pulse schedules its store write.

Functions

memoryApplied<T>({required MemoryCell<T> source, required T? value, required int revision, DateTime? timestamp}) → MemoryPulse<T>
Builds a MemoryEvent.applied pulse for source carrying value.
memoryLoaded<T>({required MemoryCell<T> source, required T? value, required int revision, DateTime? timestamp}) → MemoryPulse<T>
Builds a MemoryEvent.loaded pulse for source carrying value.
memoryRemoved<T>({required MemoryCell<T> source, required T? value, DateTime? timestamp}) → MemoryPulse<T>
Builds a MemoryEvent.removed pulse for source carrying value.
memoryStored<T>({required MemoryCell<T> source, required T? value, required int revision, DateTime? timestamp}) → MemoryPulse<T>
Builds a MemoryEvent.stored pulse for source carrying value.
memoryUnloaded<T>({required MemoryCell<T> source, required T? value, required int revision, DateTime? timestamp}) → MemoryPulse<T>
Builds a MemoryEvent.unloaded pulse for source carrying value.
remember<T>(Cell domain, {required MemoryRecord<T> record, MemoryStrategy strategy = const MemoryStrategy(), MemoryLifecycle<T> lifecycle = const MemoryLifecycle<Never>(), MemoryInfrastructure infrastructure = const MemoryInfrastructure(), MemoryGovernance governance = const MemoryGovernance()}) → Future<MemoryCell<T>>
A high-level utility that links a reactive Cell to a persistent MemoryStore.
rememberState<T>(StateHandle<T> state, {required MemoryRecord<T> record, T? project(Pulse pulse)?, MemoryStrategy strategy = const MemoryStrategy(), MemoryInfrastructure infrastructure = const MemoryInfrastructure(), MemoryGovernance governance = const MemoryGovernance()}) → Future<MemoryCell<T>>
Opens a memory cell around a Cell.state and wires it in both directions.

Typedefs

MemoryCellSlots<T> = ({Map<MemoryAction, Instruction<MemoryCell<T>, Pulse, Pulse>> catalog, MemoryClock clock, MemoryCodec<T> codec, FutureOr<bool> Function(T value)? hydrate, String memoryId, MemoryConflictPolicy onConflict, bool ownsStore, MemoryWritePolicy policy, T? Function(Pulse pulse)? project, T? Function()? read, MemoryRuntime<T> runtime, MemoryScheduler scheduler, Cell source, MemoryStore store, Duration? ttl})
The immutable per-open configuration of a MemoryCell, plus the single mutable holder.
MemoryVersion = ({String generation, int revision})
A revision-generation pair naming the exact record a writer read.

Exceptions / Errors

MemoryConflict
The store holds a different version than the writer expected.
MemoryCorrupt
Stored data is unreadable: bad JSON, an unknown schema, a decode failure, or an envelope that fails strict validation.
MemoryIoException
A file or backend IO failure, wrapped with the path when known.
MemoryNotSerializable
An exception thrown when a value cannot be serialized into a JSON-compatible format.
MemoryStoreException
Base type of the store exception hierarchy.