# Knowing which turns memory has written

A session is a [DAG](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/dag/overview.html): 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.

1. **Trunk** m1 to m9, all marked
2. Branch forks at m3
3. **b1, b2** unmarked
4. **Walk back from b2** collects b2, b1; stops at marked m3

## The mark

```
{"id": "a3f1c2", "role": "user", "predecessor": "9d0e77",
 "metadata": {"memory_written_scriptorium": "w-4f21c8e0"}}
```

| Part | Why |
| --- | --- |
| Key names the provider | The 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 workspace | Session 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 with | `SessionStore.merge_node_metadata_batch`, one `node.patch` log record per node via `SessionLog.patch_node` |

## Which turns are unwritten

| Step | Rule |
| --- | --- |
| Filter | `writing._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. |
| Walk | `online.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 boundary | `session_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 result | Audit test | Batch |
| --- | --- | --- |
| 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 `commit` | Marked. Unmarked it would return forever and read as `WRITER_NO_PROGRESS`. |
| Anything else | Closure returns `None` | Not 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

| Concern | Fact |
| --- | --- |
| Memory revision | `workspace_revision` hashes the memory workspace, disjoint from `chats`, so a mark never reads as a concurrent memory write |
| Index cache | Another process rebuilds its index once: 14–50 ms for 289 nodes, 4.2 MB (measured). `mark_synced` keeps it from repeating |
| Log growth | One 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_at` | The 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 9 | Rows (shared + own) | Cursor offers | Mark offers |
| --- | --- | --- | --- |
| short | 5 (3 + 2) | 0 | both own turns |
| long | 11 (3 + 8) | the last 2, then records all as written | all 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 node | Set of ids |
| --- | --- | --- |
| Finding unwritten | Walk from the tip to the first mark | Walk the branch, subtract the set |
| At a fork | Shared prefix is marked, walk stops | Prefix ids are skipped |
| Stored | One field on an existing node | One file per thread, every id ever written |
| Growth | None | One entry per message, for the session's life |
| One read | A few steps from the tip | The thread's whole list |
| Migration | None: offered whole once | None: the set starts empty |
| Lost entry | Walk stops early, older turns stranded | That turn is offered again |
| Coupling | Memory writes one field into the session store | Memory 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.

| Framework | Shape | Memory | Record | At a fork |
| --- | --- | --- | --- | --- |
| codex-cli | Line per rollout; a fork is a new thread | Per-rollout extraction, then consolidation | `jobs.input_watermark`, `last_success_watermark`, lease, in `memories_1.sqlite` by `thread_id` | New thread, no row: prefix extracted twice |
| openclaw | DAG, `id`/`parentId`, one JSONL | `dreaming-phases`, `short-term-promotion` | `lastContentLine` and `seenMessages` in `session-ingestion.json`; `promotedAt` on derived candidates | New file from line 0: prefix ingested twice. Retry changes the hash and rescans |
| hermes-agent | Line per session in SQLite; `/branch` copies rows | `MEMORY.md`/`USER.md`, eight providers | None for memory: `sync_all` per turn. `_last_flushed_db_idx` for SQLite | Each fork site re-baselines by hand; seven of eight providers skip `on_session_switch` |
| pi-mono | DAG, append-only; `label` and `leaf` entries | No | Branch summaries walk the tree at navigation | Nothing to go stale |
| opencode | Line, SQLite `seq` | No | — | `revert` then the next prompt deletes later messages |
| pi-ai | Stateless client | No | — | No branches |
| weclaw | Cached downstream ids; HTTP keeps 20 turns | No | — | 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

| Case | Behaviour |
| --- | --- |
| Prefix assumption | Online writes keep oldest-first batches; nothing checks that every earlier turn is marked |
| Abandoned branches | Written 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 files | The topic format cannot say two claims are alternatives; retrieval returns both |
| Cross-session spawn | Each half is written under its own session, once; no link says the sub-agent continues the caller |
| Compaction summaries | A 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 meaning | Handed 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**

| Shape | Gain | In the way |
| --- | --- | --- |
| Memory's own citations are the record: unwritten means reachable and cited by nothing | Cannot disagree with memory, needs no workspace id, has no lost-mark case | Cited 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 branch | Retrieval prefers the reader's branch; contradictions show as forks | Topic format, `retrieval/` filter and the reorganize prompt all lack it; wrong only when branches disagree |
| Memory is told, not polled | Abandoned branches are written promptly | The five head-setting paths; nothing is lost by waiting |

[Memory overview](https://fzkuji.github.io/OpenProgram/docs/reference/design/memory/overview.html)
