Features topic

cell_memory — Feature catalog

Author: Lee Man Hoi Simon (see AUTHORS)

Catalog of cell_memory entry points and configuration surfaces. Design intent lives in ARCHITECTURE-Memory.md. Machinery deep dive: guide/HowTo-Memory.md. Application view from the Cell side: packages/cell/guide/HowTo-Memory.md.

Import once:

import 'package:cell_memory/cell_memory.dart';
import 'package:cell_memory/cell_memory_io.dart'; // FileMemoryStore only

The domain cell owns the value; the memory cell owns the record. MemoryCell.snapshot is a MemorySnapshot — never the T.


1. Entry points

Feature API Notes
State sugar rememberState(StateHandle<T>, {record, project, strategy, infrastructure, governance}) Both directions wired: state → store, store → state
Cell sugar remember(Cell, {record, strategy, lifecycle, infrastructure, governance}) Attaches in one call
Full open MemoryCell.open(Cell, {record, strategy, lifecycle, infrastructure, governance}) The five config pillars; open modes on lifecycle.mode
Surface reconstruction MemoryCell.fromNucleus(MemoryCellNucleus<T>, {catalog}) Same-link views; catalog = derivative capability view
The surface MemoryCell<T> interface class — implementable externally, extendable in-library
Narrowed views await cell.deputy({ephemeralPolicy, context, testRule, synapses}), cell.unmodifiable Deputies share the runtime and can only narrow; the unmodifiable view rejects durability futures with UnsupportedError

2. Configuration

Feature API Notes
Record MemoryRecord<T>({required id, required store, required codec}) Validates the id grammar at construction
Strategy MemoryStrategy({write, conflict, ttl}) Write cadence, conflict rule, expiry
Lifecycle MemoryLifecycle<T>({read, hydrate, project, mode}) read defaults to the domain ValueCell.value; hydrate is the only store→domain path
Open mode MemoryOpenMode.load / seed / loadOrSeed / dormant One closed enum — no invalid boolean pairs
Infrastructure MemoryInfrastructure({scheduler, clock, ownsStore, customCatalog}) Time, scheduling, ownership, instruction overrides
Governance MemoryGovernance({context, testRule, synapses, ephemeralPolicy}) The framework quartet on top of the domain's own gate
Write policy MemoryWritePolicy({mode, debounce, maxWait, retry}) immediate (default, coalesced) / debounced / explicit / disabled
Retry MemoryRetry({attempts, delay}) Transient MemoryIoException only — conflicts never retry through IO
Conflict policy MemoryConflictPolicy.fail() / overwrite() / adopt() / merge(fn) adopt and merge require hydrate
Resolution MemoryResolution.takeLocal / takeRemote / adopt(...) Closes a fail-policy conflict; resumes autosave
TTL MemoryStrategy(ttl: Duration(...)) Stamps expiresAt; expired reads as absent; purgeExpired clears rows

3. Codecs

Feature API Notes
Contract MemoryCodec<T> name + version + encode + decode(fromVersion:); verifyOnWrite round-trip guard
Primitives JsonMemoryCodec<int>.value() / .identity() Plain JSON values
Lists JsonListMemoryCodec<E>() List<E> snapshots
Maps JsonMapMemoryCodec<V>() Map<String, V>
Models JsonMemoryCodec<T>.mapped(toJson:, fromJson:) Typed model boundary
Versioning JsonMemoryCodec<T>.of(..., migrations: {...}) fromVersion → value migrations
Payload equality JsonPayloadKey Canonical keys decide dirtiness and CAS equality — never T.==

4. Record surface

Feature API Notes
Snapshot MemorySnapshot get snapshot status, revision, generation, loaded, dirty, attached, lastError, conflict — a flyweight, compare fields
Status MemoryStatus.unloaded / clean / dirty / saving / conflicted / failed / closed One closed enum
Flags bool get loaded, dirty, attached, closed Live flags
Identity String get memoryId, bool get ownsStore The record id; store ownership
Errors Stream<Object> get errors Write failures and ingress encoding failures — reported, never thrown through observers
Conflict row MemoryEnvelope? get conflict The stored row held while conflicted
Events MemoryEvent.loaded / applied / stored / conflicted / resolved / failed / unloaded / removed Via Cell.observe<MemoryPulse<T>>

5. Turns

Feature API Notes
Load Future<void> load() Restores through hydrate; miss = no-op
Save Future<void> save() Flush barrier; no-op on a fresh untouched cell
Resolve Future<void> resolve(MemoryResolution) Closes a conflict; takeRemote hydrates the stored row
Attach Future<void> attach(Cell upstream, {project}) Observer wiring; project overrides the lifecycle projector
Detach Future<void> detach() Unwires the observer
Unload Future<void> unload() Flush-if-dirty, detach, forget baseline; the record remains
Close Future<void> close() Idempotent; drains; closes an owned store exactly once
Remove Future<void> remove({bool detach = true, MemoryVersion? ifVersion}) Deletes the record; a fresh generation for the next life

All turns run on one FIFO mailbox; every admitted future completes exactly once.


6. Stores

Feature API Notes
Contract MemoryStore C1–C8: typed errors, id grammar first, MemoryCas inside the atomic section, expired-is-absent, idempotent draining close
Capabilities MemoryStoreCapabilities({crossProcessCas, serverClock, nativeTtl, recommendedPolicy}) What the backend actually guarantees
Draft MemoryDraft({id, generation, codec, codecVersion, payload, expiresAt, sourceCellId, meta}) What a writer proposes
Version MemoryVersion = ({int revision, String generation}) What the writer read
Rule engine MemoryCas.decide(...) → MemoryCasCommit / MemoryCasAlreadyApplied / MemoryCasConflict One pure engine; the store assigns revisions
In-memory InMemoryMemoryStore({clock}) The reference implementation
File FileMemoryStore.directory(root, {clock}) / .file(file) One JSON file per id; dart:io only
Firestore FirebaseMemoryStore(firestore:, uid:), firestoreWritePolicy package:cell_memory_firebase, Flutter only
SQLite SqliteMemoryStore.open({path, clock}) package:cell_memory_sqlite, Flutter only; BEGIN IMMEDIATE CAS

7. Customization

Feature API Notes
Actions MemoryAction.apply / load / save / resolve / attach / detach / unload / close / remove One instruction class per action
Catalog injection MemoryInfrastructure(customCatalog: {MemoryAction.save: mySave}) Override one entry; the other eight keep defaults
Instruction base MemoryInstructionBase<T> The subclassable wrapper: override handle or the turn seam
Turn seams adopt / loadTurn / writeTurn(cell, flush, {allowCreate}) / resolveTurn / attachTurn / detachTurn / unloadTurn / closeTurn / removeTurn Interpose with super, replace wholesale without it
Flush context MemoryFlushContext<T> Per-turn toolkit: memoryId, store, codec, policy, onConflict, ttl, clock, read, hydrate; baseline handles; encode, payloadKey, mintGeneration, reportError, emit, scheduleWrite; adoptCommitted, adoptRemote, suspendConflict
Partial catalogs MemoryCell.fromNucleus(nucleus, catalog: {...}) Fail-closed capability views: a missing action → StateError; missing apply drops ingress
Composition parts MemoryCellNucleus<T>, MemoryCellSlots<T>, MemoryRuntime<T> Build a link from parts; fromNucleus activates it
Capability hiding final Cell view = memory; The static Cell type hides the durability members

Governance always sits above the catalog: the cell's TestCell vets a command before any custom instruction runs.


8. Testing utilities

Feature API Notes
Scheduler ManualScheduler() — pendingCount, elapse() Deterministic debounce/maxWait tests
Clock ManualMemoryClock() — now(), advance(...) Deterministic TTL tests
Conformance battery runStoreContractSuite(name, create, {createWithClock, createAsync, createAsyncWithClock}) C1–C8 for every backend
Fuzz harness test/fuzz_test.dart Eight fixed seeds, seven invariants every step
Guide mirrors test/guide_snippet_test.dart Every full-program snippet in guide/HowTo-Memory.md

9. Cross-package surfaces

Feature API Package
Tissue collections MemoryTissue.rememberList / openList / openSet / openQueue cell_tissue_memory
Tissue scalars MemoryTissueValue.remember / open, MemoryTissueMap.remember / open cell_tissue_memory
Tissue reconstruction MemoryTissue.fromNucleus (+ value/map twins) cell_tissue_memory
Firestore backend FirebaseMemoryStore, firestoreWritePolicy cell_memory_firebase
SQLite backend SqliteMemoryStore cell_memory_sqlite
Live demo Two-kiosk hydrate/conflict/replay demo cell_memory_live_demo

Classes

MemoryCell<T> Getting Started Features Architecture
A durable Cell implementation that persists its state to a MemoryStore.