Reading the log back - `sdk/src/context.rs`, `sdk/src/cursor.rs`, `sdk/src/memory.rs`, `sdk/src/state_store.rs`, `sdk/src/agent/state.rs`, `sdk/src/poll.rs`. Use when changing context assembly, a `ContextPolicy` (LastN/RoleFilter), the `Cursor` stream reader, the `StateStore` seam (`InMemoryStore`/`FileStore`/`Kv`), the `Memory` trait, `LogMemory` or the semantic `VectorMemory`/`Embedder` seam, memory scoping (stream/agent/conversation), tombstone/forget, or `ConversationState` replay.
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Context And Memory?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/laserdata-context-and-memory)
---
name: context-and-memory
description: Reading the log back - `sdk/src/context.rs`, `sdk/src/cursor.rs`, `sdk/src/memory.rs`, `sdk/src/state_store.rs`, `sdk/src/agent/state.rs`, `sdk/src/poll.rs`. Use when changing context assembly, a `ContextPolicy` (LastN/RoleFilter), the `Cursor` stream reader, the `StateStore` seam (`InMemoryStore`/`FileStore`/`Kv`), the `Memory` trait, `LogMemory` or the semantic `VectorMemory`/`Embedder` seam, memory scoping (stream/agent/conversation), tombstone/forget, or `ConversationState` replay.
---
# Context and memory
The TypeScript peer lives under `foreign/typescript/src/context*`, `conversation-state.ts`, `snapshot.ts`, and `memory/`. The Go peer is `foreign/go/laser/context.go`, `context_scope.go`, `conversation_state.go`, `snapshot.go` and the `memory*.go` files.
These modules reconstruct state from the durable log: assemble an ordered window of a conversation, fold it into state, or recall scoped memory items. Load [laser-sdk-overview](../laser-sdk-overview/SKILL.md) first. Repo rules in [AGENTS.md](../../../AGENTS.md).
Iggy provides the VSR transport and AGDX command classifier. Context assembly, cursors, conversation-state replay, topic snapshots, and folded `LogMemory` use standard append and poll commands. KV-backed recall, query, graph, and other managed memory composition use the non-replicated extension path. Callers must keep capability and `Unsupported` handling for an Iggy server that does not serve AGDX.
## STOP and ask the user before
- Changing the cross-topic ordering key in `ContextAssembler::assemble` (`(timestamp, topic_index, partition, offset)`) - it defines what an LLM is fed.
- Changing the `MemoryLogEntry` framing (the typed `Item`/`Forget`/`Feedback` records `LogMemory` writes to the audit topic) - it is the wire format of a memory record on the log.
- Changing how `recall` scopes results (agent, user, and application filters, plus the conversation and lifetime).
## Key files and symbols
- `poll.rs` - `drain_partition(client, stream, topic, consumer, DrainRange { partition, from, end }, batch) -> PartitionBatch { messages, next_offset }`. The single shared batched-drain used by both context and the reply scanner. Reuse it, do not hand-roll another poll loop.
- `ContextAssembler` uses a bon builder for `conversation_id`, `across_subconversations`, `topics` (default `agent.sessions`, a repeated topic is read once), and `policy`. It reads topic partitions through the shared bounded reader, filters conversation or ancestry, orders results deterministically, and applies `ContextPolicy`. Policies include `LastN`, `TokenBudget`, `RoleFilter`, and `Chain`. `ContextPolicy` also has `name()`, `version()`, and `selection(history) -> Selection { kept, dropped, reason }`, which a context manifest records. `ContextMessage` carries `topic`, `timestamp_micros` (the server append time), `stream_id`, and `topic_id`, so a reader can build a `SourceRef::Message` without a lookup. Use `AgentTopic::as_identifier()` on read paths. Each partition read is tail anchored to the newest `laser_sdk::context::CONTEXT_READ_WINDOW` (10,000) raw records, or the window ending at a `to_checkpoint`, before the conversation filter runs. The window applies to context reads and to `ReplayBound::Last(n)` only. Python and TypeScript mirror the same constant and window.
Context assembly is stateless between calls. It uses `tail_anchored_offset` for a recent bounded window and can accept `from_offsets`. `Cursor` and folded `LogMemory` retain offsets for incremental reads. Do not describe every read as a full history scan.
- `memory.rs` defines `Memory` with `remember`, `recall`, `improve`, and `forget`. `LogMemory` records durable changes, and `VectorMemory` supports local similarity reads. `MemoryKind`, `MemoryClass`, `Lifetime`, `RecallStrategy`, `Feedback`, and `MemoryScope` define SDK behavior. Scope includes user, agent, conversation, app, and stream. `MemoryId::content` hashes stream, agent, user, app, and conversation (each followed by a zero byte), the kind code, and the body through `laser_wire::hashing::content_id`, so IDs match across clients and the same body in two conversations is two items.
Applications supply `Embedder`, `Reranker`, `Summarizer`, and `Consolidator`. `RerankedMemory` adds a second ranking stage. Shared forms are `SharedEmbedder`, `SharedReranker`, and `SharedConsolidator`. `MaybeEmbedder` reports missing configuration only when an embedding is needed. `RecallSignal` and `MemoryItem.signals` retain strategy, rank, and original score. Built-in vector Hybrid adds active feedback, cosine, and keyword scores. `fuse_reciprocal_rank` is a separate application-controlled ranking helper.
Memory adds no separate wire command group. It combines publication, query, and graph operations. Read [wire-contract](../wire-contract/SKILL.md) and the memory section in `docs/agdx.md`.
- Memory namespaces are stream scoped like KV: under `ResourceNaming::Stream` the namespace is `stream:<stream>/<namespace>` with the stream the memory records ride (the default stream unless `LogMemory::on_stream_topic` names another), in the `agdx.mem.ns` header, the read view, the fold filter, and the lens `stream`. `ResourceNaming::Bare` keeps 0.6 names.
- `LogMemory` writes `MemoryLogEntry::Item`, `Feedback`, and `Forget` records to the memory topic, with `AgentTopic::Memory` (`agent.memory`) as the default. An item may carry `origin: SourceRef` and `producer: ProducerInfo`. `ScopedMemory::with_lineage(origin, producer)` stamps them, and `Session::linked_memory()` does so for the session's current record and agent. A `Forget` or `Feedback` with a `conversation` acts only on an item remembered in that conversation, and `ScopedMemory::forget` and `improve` always pass theirs. A `Forget` is a tombstone with its record's server append time: the fold and the managed view drop writes at or before it from any partition and keep later ones. A write, forget, or feedback whose scope names a stream other than the handle's fails with `LaserError::Invalid`. It uses named-field CBOR through `laser_wire::framing`. Default `recall` and `fetch_named` read the managed KV view on a deployment that serves it (`capabilities.kv.available`) and fold the topic in process on one that does not. On the view, a default recall waits until the view shows this connection's own writes: `LaserInner` keeps an `OwnWrites` record of the ids each connection remembered (must appear) and forgot (must be gone, in the forget's conversation), shared by every handle built from that `Laser`, and `recall_own_writes` scans again with a 50 ms to 500 ms backoff for up to 10 s, then fails with `LaserError::Timeout`. Rows outside the recall's lenses are not waited for. The first write to a missing memory stream or topic creates it (one partition, the 30 day expiry) and sends again.
`recall_kv` decodes `KvEntry.scope`, filters the requested scope, and orders items by arrival: `(timestamp, topic, partition, offset, id)` from the view row's `timestamp_micros`, never by content id alone. Every strategy except `Recent` ranks by the row's folded feedback `weight`, which the fold sums per item, with an `Auto` signal. `Semantic`, `Hybrid`, and `Auto` with query text add the word overlap (`keyword_score`) to that weight and keep every item, with a `Keyword` signal, while `Keyword`, `Graph`, and `Temporal` keep only the items that share a query word (`QueryWords` in `memory.rs`, the same rule on the view and the fold). `MemoryKind::from_word` and typed ID parsers check the stored metadata. `update_named` folds locally before a merge.
`RememberBuilder` and `RecallBuilder` set the `MemoryScope` user and application with `.user(..)` and `.application(..)`. `RecallBuilder::block(token_budget)` recalls and renders the prompt block through `to_context_block`. `MemoryHandle::supersede(old_id, payload)` returns a `SupersedeBuilder` with the remember scope setters: it remembers the correction first, then forgets `old_id` with no conversation limit, so a recall for the user in any conversation never returns the old fact. Local folding is explicit through `RecallBuilder::folded()`, `MemoryHandle::recall_folded`, `fetch_folded`, `LogMemory::recall_folded`, or `fetch_named_folded`. It retains a `Projection` and partition offsets under a Tokio mutex. `catch_up` reads only new records through `poll::drain_partition` and drains again while any partition fills a drain, so a folded read covers the whole retained history. Topic access remains controlled by Iggy permissions.
- `VectorMemory<E: Embedder>` stores local vectors. `remember` embeds a payload. `recall` combines cosine similarity, `keyword_score`, and feedback according to `query.strategy`. `Keyword` needs no embedding, and `Hybrid` combines active signals. Scope filters include conversation, agent, user, and app. Without a signal, it returns recent items. `Recent` orders by recency alone, so feedback never reorders it. That holds in every backend and every SDK. Feedback signals report `RecallStrategy::Auto`.
`Laser::memory_with(.., Vector)`, Python `VectorMemory.governed(laser, embedder)` and `laser.memory_with(namespace, "vector", embedder=)`, and TypeScript `laser.memoryWith(namespace, "vector", embedder)` retain the creating Laser governor. `MemoryHandle::vector(embedder)` builds a standalone vector handle with no connection, which Python `MemoryHandle.vector` and TypeScript `MemoryHandle.vector` match. Python `MemoryHandle` is the base class of `LogMemory`, `VectorMemory`, and `RerankedMemory`. Apply policy before local mutations and present the proposed body to that policy. Preserve content IDs from `.dedup()`. `VectorMemory::new` is standalone, and `VectorMemory::governed` selects explicit low-level governance. Use `RerankedMemory` for another ranking stage. Embed the query before taking the item lock.
- `MemoryHandle` is the common memory interface. `Laser::memory(ns)` selects log-based memory. `Laser::memory_on_topic(name, stream)` selects an existing topic, `None` keeping the default stream. `Laser::memory_topic(name).stream(s).partitions(n).ttl(d)` and `.no_expiry().build()` configure topic storage. The default `DEFAULT_MEMORY_TOPIC_TTL` is 30 days, separate from read-view retention.
`MemoryBackend` variants are `Auto`, `Log`, and `Vector`. `memory_with(ns, MemoryBackend::Vector).embedder(..)` selects local vectors, and `.reranker(..)` adds reranking. Builders include `remember(payload).scope(c).kind(..).dedup().send()` and `recall(c).semantic(..)`, `.keyword(..)`, `.hybrid(..)`, `.strategy(..)`, `.limit(n)`, and `.fetch()`. `context(conversation, token_budget)` renders memory for a context. `consolidate(scope, max_items)` runs consolidation.
- TypeScript keeps the same topology with language-specific names: `laser.memory(namespace)`, `laser.memoryOnTopic(topic, stream?)`, and `laser.memoryTopic(topic).stream(name).partitions(n).ttl(ttlMs)/.noExpiry().build()`. `laser.context(conversation).memory(handle)` binds the exact topic-backed handle. A recalled log-memory item carries its message source when the transport resolves stream and topic IDs.
- `DefaultConsolidator<M, S>::new(memory, max_items)` keeps the newest items by ULID `MemoryId`. `.with_summarizer(..)` folds the Message-kind items in the scope into one durable `Summary` per conversation, stored under the consolidation scope narrowed to that conversation. The summary id is `MemoryId::content` over that scope, `Summary`, and the covered turn ids as sorted 16-byte big-endian values, so a pass whose turns already have their summary skips the summarizer. `.prune_summarized()` forgets those source turns. The prune to `max_items` stays scope-wide. `Agent::builder().consolidate_every(d)` with `.consolidator(SharedConsolidator::new(..))` runs consolidation outside the handler loop over the agent's own memory: the scope carries the agent id and nothing else. The task stops with the agent. Further fact-invalidation behavior remains application policy.
- `MemoryQuery` supports `token_budget` and `limit`. `to_context_block(items, token_budget)` renders items in rank order and adds `[..., N more omitted ...]` when needed. `estimate_tokens` is the shared wire `laser_wire::agent::estimate_tokens`: the byte count divided by four, rounded up, pinned by `wire/fixtures/token_estimates.json` and used by every SDK and the session index. It does not invoke a tokenizer. The first item always renders, so this estimate is not a strict model-token limit.
- `GraphHandle` in `sdk/src/graph.rs` requires `graph` and is returned by `Laser::graph(name)`. `upsert` writes content-addressed nodes and edges. `GraphEdge::relate(..).valid(from,to)` adds a valid-time window. `neighbors(node, dir, edge_type, depth)` reads adjacent paths. Traversal builders combine `start_ids`, `start_match`, `start_nearest`, `out`, `incoming`, `both`, `hop(dir, edge_type, max)`, `node_filter`, `edge_filter`, `return_edges`, `return_paths`, `.as_of(micros)`, `into_query`, and `fetch`. `link` opens the edge at call time, `relink` closes and opens at one instant, and the deployment keeps a closed interval when a later `link` reopens it.
The managed engine supports nodes, edges, paths, and triplets with ID, predicate, or nearest-vector starts. `GraphNode::entity`, `GraphEdge::relate`, `NodeId::content`, and `EdgeId::content` use the wire `content_id`. `SourceRef` records origin without changing identity. Nodes retain the first source, and edges retain the latest. `GraphEdge::with_source` sets that metadata.
`SourceRef::Message` can carry conversation identity. `.conversation(id)` restricts graph reads by that metadata. `Laser::projections().register_graph(..)` and `drop_graph(..)` manage graph projections. Unsupported deployments return `Unsupported`. Missing managed grants return `GraphError::Unauthorized`.
- `MemoryHandle::{set, fetch, update, remove}` addresses items by a caller-provided key. `set` publishes `laser_wire::memory::MemoryRecord::Item` under `"<namespace>/<key>"`, and `remove` publishes `Forget`. `update` reads the current value, applies RFC-7386 through `merge_named`, and republishes. Default `fetch` reads the managed KV view. `fetch_folded` reads locally from the retained topic. Named operations do not write directly to KV.
- `ConversationState::load(laser, conversation, topics, bound, init, fold)` in `agent/state.rs` rebuilds state under an explicit `ReplayBound`. Bounds include `FromOffsets(map)`, `FromCheckpoint(checkpoint)`, `At(checkpoint)`, `Last(n)`, and `Full`. `load_with(store, ..)` can seed state from `SnapshotStore`. `Full`, `FromOffsets`, `FromCheckpoint`, and `At` fold the whole requested range in bounded chunks, up to the tail seen when the replay starts or up to the checkpoint. Only `Last(n)` reads the context window. Keep full-history and bounded-replay behavior distinct.
A `Checkpoint` in `context.rs` records the next offset per topic partition. `ContextScope::checkpoint(topics)` captures it with topic keys from `AgentTopic::topic_string`, including custom topics. `to_checkpoint` excludes the recorded offset and treats absent partitions as empty. `from_checkpoint` resumes at the recorded offset. `ContextMessage.topic` identifies the source topic.
- Sessions read the same machinery. `Session::context`, `checkpoint`, `turns_at`, `turns_since`, `state_at`, and `replay` read the lane on `agent.sessions`. `Session::assemble(policy)` returns `AssembledContext { fragments, manifest, text() }` and writes nothing. The policy selects from the session's conversation records only (lifecycle, chunks, state, context events, and the session's own recorded model requests are dropped first), `text()`, manifest sizes, and the default `TokenBudget` estimate count `ContextMessage::body()` (the envelope body, else the payload), and a selection over `MAX_MANIFEST_FRAGMENTS` is refused before any write. `Session::record_retrieval(query, items)` writes `event(context_retrieved)` and `record_compaction(ContextCompaction)` writes `event(context_compacted)`. `SessionState::get` folds `state_snapshot` and `state_delta` from the whole retained lane (`Session::lane_records`, `ContextAssembler::replay` over the session's partitions and declared topics), skips an undecodable state record, counts a snapshot after the baseline only at the reached revision with a document equal to the folded one (`equal_json`, numbers by value), and reports `complete: false` without a baseline. State writes hold the cursor's async lock across the publish, and a failed delta clears the cursor so the next write reseeds from the fold. Session state is distinct from `StateStore`, which stays the agent-private point store.
- `cursor.rs` - `Topic::replay()` -> `Cursor`: resumable, offset-addressable read over a topic. `poll` drains every partition from where it stopped (only new messages), `offsets()` exposes the per-partition cursor and `from_offsets(..)` resumes it. Offsets are caller-owned: checkpoint them into any `StateStore` to survive a restart. Yields `Message` (raw payload + headers, no `Provenance` coupling - works on any topic). This is the open primitive the `Agent` runtime (consumer groups) sits above. Reuses `poll::drain_partition`.
- `StateStore` defines `get`, `set`, and `delete` for offsets, duplicate keys, and application state. `Kv` implements the same interface. Local implementations are `InMemoryStore` and `FileStore`. `FileStore` encodes keys as hexadecimal filenames and writes through unique `<file>.<ulid>.tmp` files before rename. This prevents path traversal and partial-file reads during replacement.
## Rules specific to this area
- Ordering across topics is best-effort: deterministic but not strictly chronological for same-microsecond messages on different topics (Apache Iggy has independent offset spaces). State this. Do not pretend it is total order.
- `recall` honors the scope it was stored under. If you add a scope dimension, stamp it in `remember`'s provenance and filter it in `recall` - do not leave a scope field unused.
- `LogMemory::recall_folded` returns the last `query.limit` matching items. It retains a `Projection` and partition offsets and reads only new records. Keep its result equivalent to applying the same records in a full fold. Default `LogMemory::recall` reads the managed KV view. `ContextAssembler` remains stateless between calls.
## Review smells
- A second copy of the partition-drain loop instead of `poll::drain_partition`.
- A `MemoryScope` field written on `remember` but ignored by `recall` (or vice versa) - the original scope/query mismatch bug.
- Ordering code that assumes cross-topic chronological order.
## Cross-SDK parity
Python and TypeScript match the Rust memory and context surface. Remember takes `kind`, `dedup`, `durable`, `stream`, `user`, and `application` in all three. Scoped memory provides `block` and `consolidate` in all three. Named facts `set`, `fetch`, `fetch_folded`, `update`, and `remove` live on the handle in all three. `LogMemory` spells them `set_named`, `fetch_named`, `fetch_named_folded`, `update_named`, and `forget_named` in Rust and Python, and `setNamed`, `fetchNamed`, `fetchNamedFolded`, `updateNamed`, and `forgetNamed` in TypeScript. Context scopes provide `fetch_with` with `LastN`, `TokenBudget` with an optional estimator, `RoleFilter`, and `Chain`, plus `state`, `state_with`, and `checkpoint`. The [cross-SDK parity matrix](../../../docs/parity.md) lists each spelling.
## Rerankers, custom backends, and summaries
Rerankers work in all three SDKs (Python takes a `(query, items) -> items` callable or an object with `rerank(query, items)`, sync or async). `memory_custom` plugs a custom backend into Rust, Python, and TypeScript. `MemoryHandle.backend` reports the backend kind in Python and TypeScript. Rust `ScopedMemory::forget(id)` and `improve(feedback)` match the Python and TypeScript scoped memory. Python `Session.context_with(policy)` and `Session.graph(name)` match Rust and TypeScript.
All clients expose summarizers, `MemoryHandler` (it stamps the handling agent from the context, never the sender, and reports a failed write as a warning), and the four `ConsolidationReport` counts (`summarized`, `reweighted`, `pruned`, `derived`). Reranked wrappers must keep explicit kinds and content IDs. Custom backends keep the custom trait contract. The Python module function `to_context_block` renders the recalled items it is given, in order. Consolidation and recall behavior shared by all clients is in [client behavior](../../../docs/client-behavior.md).