OpenProgram Docs

Knowing which turns memory has written

A session is a DAG: re-asking, retrying and spawning fork it. Every branch belongs in memory; a shared prefix belongs there once. The record of what is written is a mark on the turn's own node.

Marked turns are shaded m1 m2 m3 m4 m5 m6 m7 m8 m9 b1 b2 branch tip, unmarked Walk back from the tip, stop at the first mark offers b1 and b2, oldest first
  1. Trunkm1 to m9, all marked
  2. Branch forks at m3
  3. b1, b2unmarked
  4. Walk back from b2collects b2, b1; stops at marked m3

The mark

{"id": "a3f1c2", "role": "user", "predecessor": "9d0e77",
 "metadata": {"memory_written_scriptorium": "w-4f21c8e0"}}
PartWhy
Key names the providerThe memory interface is pluggable; a shared boolean breaks with a second provider. The name is historical and stays: changing it would orphan marked nodes. Must not collide with a message field, because _node_to_msg spreads metadata to the top level.
Value names the workspaceSession directories are self-describing and move by copying. A walk stops only on its own workspace id (store.workspace_id()) or one in project_layer.written_elsewhere(), so a restored backup keeps its marks and a session copied in from elsewhere is written from the start. A turn is written to one layer only, so switching project writes on or off copies nothing.
Stored withSessionStore.merge_node_metadata_batch, one node.patch log record per node via SessionLog.patch_node

Which turns are unwritten

StepRule
Filterwriting._records: user and assistant text from citable speakers; tool rows and runtime-scheduled turns never enter, so they are stepped over for free. A row with no stable id raises.
Walkonline.unwritten_turns: the trailing run with no mark, oldest first
Batch_first_batch: leading turns that reach the threshold, so a day-long backlog takes several passes
Per turn_memory_write in conversation/turn_runtime: the branch ending at the head
Session boundarysession_watcher (30 minutes idle, looked at when that deadline comes, at most 5 minutes apart) forces write: the head's branch first, however short, then each other live, unarchived tip from list_branches once its unwritten text reaches the threshold

The idle allowance in should_incremental_write does not apply to abandoned tips: their last message is old by definition and every retry would pass. Rewound turns never arrive; get_branch filters them.

When a batch is marked

Writer resultAudit testBatch
Changed a topic file_changed_files: a commit entry with status == "ok"Marked
Judged nothing worth keeping_declined: closing agent entry, and no failed Write, Edit, shell or commitMarked. Unmarked it would return forever and read as WRITER_NO_PROGRESS.
Anything elseClosure returns NoneNot marked, retried

The absence of an error is not a product. Measured: twenty turns on one rejected edit, a successful return, a one-byte topic file.

  1. Install the topic files in a transaction, whole or not at all. Footnotes link the chat messages, so no evidence is copied.
  2. Mark the batch. A crash between the two is a redo; the reverse order would lose turns silently.

Lost marks and bad bookkeeping

Reprocess rather than go silent. An unreadable runtime.json loads as an empty state. A walk that meets no mark offers the whole branch; the writer sees existing topic files, so a known fact is left or merged.

The legacy cursors field is ignored and nothing seeds marks from it: its ordinal is the value forks corrupted. An upgraded session costs one larger write.

What marks cost the session store

ConcernFact
Memory revisionworkspace_revision hashes the memory workspace, disjoint from chats, so a mark never reads as a concurrent memory write
Index cacheAnother process rebuilds its index once: 14–50 ms for 289 nodes, 4.2 MB (measured). mark_synced keeps it from repeating
Log growthOne record per marked node. Marks go on the batch, never a full pass, which would be quadratic over a session's life
Must not move updated_atThe idle watcher compares that exact value; moving it forces a write and a model call. So the path avoids append_message and SessionNodeWriter.append
Must not claim foreign writes as synced_open rebuilds a stale index first; _mark_own_write absorbs only the process's own append

Why a mark

Why not a position cursor

One ordinal per session, compared against a row's position in the flattened branch. An ordinal describes the flattening, not the message: the same message gets two numbers on two lines, different messages at one depth share a number, and rewind or compaction shifts every later row. It also counts rows memory skips, so the figures below are measurements.

Branch forked at m3, stored ordinal 9Rows (shared + own)Cursor offersMark offers
short5 (3 + 2)0both own turns
long11 (3 + 8)the last 2, then records all as writtenall 8 own turns

The long case is worse: a fragment starting mid-conversation, reported as success. A monotonic counter cannot go back to a fork point, and a counter and a branching conversation are different shapes.

Why not a set of ids beside memory
Mark on the nodeSet of ids
Finding unwrittenWalk from the tip to the first markWalk the branch, subtract the set
At a forkShared prefix is marked, walk stopsPrefix ids are skipped
StoredOne field on an existing nodeOne file per thread, every id ever written
GrowthNoneOne entry per message, for the session's life
One readA few steps from the tipThe thread's whole list
MigrationNone: offered whole onceNone: the set starts empty
Lost entryWalk stops early, older turns strandedThat turn is offered again
CouplingMemory writes one field into the session storeMemory keeps its own books
  • The set is more exact: the walk assumes marks form a prefix, which holds because batches are oldest-first but is not checked.
  • Its cost decides it: sessions already record per node where a turn came from and whether rewind retired it.
  • A marker node pointing at the turn (pi-mono's shape) would put a node in the graph per batch for every reader to skip.
What other agent frameworks do

Seven frameworks under references/ carry an answer; claude-code/ holds one tool and no session code.

FrameworkShapeMemoryRecordAt a fork
codex-cliLine per rollout; a fork is a new threadPer-rollout extraction, then consolidationjobs.input_watermark, last_success_watermark, lease, in memories_1.sqlite by thread_idNew thread, no row: prefix extracted twice
openclawDAG, id/parentId, one JSONLdreaming-phases, short-term-promotionlastContentLine and seenMessages in session-ingestion.json; promotedAt on derived candidatesNew file from line 0: prefix ingested twice. Retry changes the hash and rescans
hermes-agentLine per session in SQLite; /branch copies rowsMEMORY.md/USER.md, eight providersNone for memory: sync_all per turn. _last_flushed_db_idx for SQLiteEach fork site re-baselines by hand; seven of eight providers skip on_session_switch
pi-monoDAG, append-only; label and leaf entriesNoBranch summaries walk the tree at navigationNothing to go stale
opencodeLine, SQLite seqNo—revert then the next prompt deletes later messages
pi-aiStateless clientNo—No branches
weclawCached downstream ids; HTTP keeps 20 turnsNo—No forks
  • Nobody puts the record on the turn. openclaw's promotedAt comes closest, on a derived record.
  • Two shapes are in use: coarsen the unit until branching stops mattering (codex-cli, openclaw, hermes-agent), or derive the delta from the tree (pi-mono). Coarsening gives up writing from a live session.
  • Their fork failure is duplication, which nightly reorganize can merge. A position cursor's is omission, which nothing recovers.
  • Taken: reprocess rather than go silent. A lost position counts everything again, because counting nothing would stop extraction for good.

Open boundaries

CaseBehaviour
Prefix assumptionOnline writes keep oldest-first batches; nothing checks that every earlier turn is marked
Abandoned branchesWritten only at the session boundary. The head is set in five places, their shared function discards the old value, and no event announces a move
Two branches, one set of topic filesThe topic format cannot say two claims are alternatives; retrieval returns both
Cross-session spawnEach half is written under its own session, once; no link says the sub-agent continues the caller
Compaction summariesA summary is a sibling of the head's line, so raw turns are written. A head moving onto the summary's line makes it an unwritten assistant turn restating memory
Mark meaningHanded to the writer, not cited: a batch folded to one citation marks all its turns

Implementation status

Implemented: marks, branch walk, evidence-based marking, boundary pass. Tests: tests/component/memory/test_memory_written_marker.py.

Not built, and not scheduled
ShapeGainIn the way
Memory's own citations are the record: unwritten means reachable and cited by nothingCannot disagree with memory, needs no workspace id, has no lost-mark caseCited is not read: a greeting or merged correction is cited by nothing and returns every pass. The footnote index would become required for correctness
A record knows its branchRetrieval prefers the reader's branch; contradictions show as forksTopic format, retrieval/ filter and the reorganize prompt all lack it; wrong only when branches disagree
Memory is told, not polledAbandoned branches are written promptlyThe five head-setting paths; nothing is lost by waiting

Memory overview

Last updated · 2026-11-25