Branches for agent memory: fork, review, merge back
lat.md/branching.md. If you see a hole, please open an issue. The last section lists the questions we most want answered.add-memory-rebase.Tiramemsu 0.13 can tag a moment, diff two moments and revert. That gives an agent a way back. It does not give it a way sideways: try something next to the real memory, let the real memory keep working, and later decide what to keep. That is a branch.
This article explains why agent memory needs branches, why we put them in separate files instead of inside one, and how a branch comes back. That last step, the merge, is the part most products skip, and the part we most want reviewed.
- Why agent memory needs branches
- What the store will not give up
- The shape: one file per branch, two ways back
- Forking a memory
- Merge-back: bringing a fork home
- A worked example
- Rebase: catching up with the parent
- Who is allowed to merge
- Sync: peers that keep exchanging
- Erasure across forks
- What we rejected
- Open questions
1. Why agent memory needs branches
An agent's memory changes for many reasons: it imports a document, reasons its way to conclusions, corrects a fact, or follows a plan that turns out to be wrong. Some of those changes should not land in the main memory straight away:
- Risky imports. Load a large source, look at what it did to the facts you already had, then decide.
- Exploration. Let an agent pursue two hypotheses at once, each in its own copy, and keep the one that held up.
- Reasoning runs. Materialize a new rule set against real data without the conclusions appearing in answers before anyone has checked them.
- Review. Let an agent work unsupervised, then have a person or a policy approve what it learned before it becomes shared memory.
Checkpoints cover part of this. You can tag, try, and revert. But while you try, the memory is the experiment. Every other reader sees it, and every other writer has to wait or write into it.
Tools that work with agents have already reached this conclusion. LangGraph forks a run from any checkpoint, E2B forks sandboxes, Neon sells database branches as agent checkpoints, and AWS previewed branching for Aurora PostgreSQL in December 2026. What they mostly lack is a way back. A branch is something you keep or throw away; its changes do not merge into the original. Memory products such as Mem0 and Zep keep history, but have neither rollback nor branches.
For memory, the way back matters most. The point of letting an agent explore is to keep what it found. So the design question is not "can we copy a database" (we can) but "can a copy's changes come back safely, with nothing replaced behind anyone's back".
2. What the store will not give up
Three properties of tiramemsu shape everything below.
- Never forget. No row is ever deleted or rewritten. A retraction sets
t_retonce, and history stays readable withasOf. A merge therefore cannot "move a branch pointer" or drop the losing side. It has to be an ordinary transaction that asserts and retracts. - Every statement has an id. Layers, provenance and citations point at statement ids (eids), and agents quote them as IRIs such as
urn:tiramemsu:stmt:42. A merge must not leave a citation pointing at the wrong statement. - Grounded memory. A live statement never rests on a retracted one: retracting a fact retracts what was built on it, in the same transaction. A merge has to keep that true even when the two sides disagree about what is retracted.
There is also a performance rule. Reads come first. Every scan already filters by transaction time and valid time, and we did not want to add a third filter, "which branch am I on", to every query.
3. The shape: one file per branch, two ways back
A branch is a separate file. A tiramemsu memory is one SQLite or redb file, so a fork is a second file that starts as a copy. There are no branch heads inside a file. Decision D18 ("no persistent branches inside a file") stays, and the read path is untouched.
There are two ways back, because forks have two kinds of life.
| Merge-back (squash) | Sync | |
|---|---|---|
| For | A sandbox: forked for one task, merged into its parent once or a few times, then discarded | Long-lived peers that keep exchanging changes: laptop and server, a team of agents |
| Direction | Child into its own parent | Any peer to any peer, relaying through others |
| Statement ids | The parent gives the child's new statements fresh ids and remembers the mapping | One id per statement in every peer |
| Costs an origin number | No | Yes, one of 4 095, for life |
| Change | add-memory-merge-back | add-memory-merge |
The split comes from a number. In 2026 we reserved 12 bits in every allocated id for an origin, so that a statement could keep one id across merged files (Origin Bits). Twelve bits give 4 095 origins. Our first merge design gave every file that merges an origin, permanently. With agents that fork once per task, a busy deployment would run out, and numbers cannot be recycled, because ids carrying them may already exist elsewhere. Most forks are sandboxes. A sandbox only ever talks to its parent, so it does not need a global name at all.
The work is four changes, built in order: add-memory-fork, add-memory-merge-back, add-memory-rebase, then add-memory-merge (sync).
4. Forking a memory
Identity
Today a copied file cannot be told apart from its source. Both will allocate statement 101 next, for different statements, and any later merge sees conflicts that are not real. So the first thing forks add is identity. A small lineage table, created by a format migration that touches no graph row, holds the file's UUID. In a fork it also holds the parent's UUID, the parent transaction it was forked at (fork_t), and the high-water marks: the highest statement, node and blank-node numbers the parent had allocated at that moment.
Those marks are the key to everything that follows. In a fork, every id at or below the marks is the parent's own id, because the fork is a copy. Every id above them is new.
The fork itself
# proposed API, not released
info = db.fork("forks/plan-a.tm", label="plan-a", expires="7d")
child = Db.open(info.path)
Db::fork takes the writer lock and makes the file durable: SQLite checkpoints its write-ahead log, and redb syncs any pending commits. It then clones the file with clonefile on macOS or a FICLONE reflink on Linux, so a large memory forks in milliseconds and shares disk blocks until the copies diverge. Where the file system cannot clone, it falls back to a full copy, unless you asked it not to. It then gives the clone a new UUID and its parent record.
Finally the parent records the fork as history, with engine-owned statements nobody else may write:
(tx:41 sys:forkedTo <urn:tiramemsu:fork:6f1c…>)
(<urn:tiramemsu:fork:6f1c…> sys:forkLabel "plan-a")
(<urn:tiramemsu:fork:6f1c…> sys:forkExpires "2026-12-11T…"^^xsd:dateTime)
Because lineage is made of statements, it shows up in asOf, in diffs and in SPARQL like everything else. Later events add sys:mergedBack and sys:discarded. db.forks() lists forks with a state (active, expired, merged or discarded). With the child open, it also reports how many transactions the child is ahead and the parent is behind.
Failure cases
- A crash after the clone but before the parent records it leaves a child the parent does not list. Merge-back refuses it (
UnknownFork). - A file copied with
cpkeeps its source's UUID. Any merge between the two fails withSameIdentityinstead of producing false conflicts. - Over MCP, an agent can fork, but only into the server's fork directory, under a generated name, and never in read-only mode.
5. Merge-back: bringing a fork home
Merge-back takes the child's net change since the fork (or since the last merge-back of that child) and applies it to the parent as one ordinary transaction. Each rule below answers a specific way a naive merge goes wrong.
Inherited ids stay, new ids are mapped
A child that retracts or annotates statement 12, where 12 is below the marks, is talking about the parent's statement 12, so merge-back applies the change to that id. A child that creates statement 101 gets a fresh parent id for it, because the parent may have used 101 for something else since. References are rewritten in the same pass, inserting each statement after everything it references. Revert already does this when it restores statements with fresh ids.
The mapping is kept in an append-only merge_map table. A second merge-back of the same child therefore knows which parent statement child statement 101 became, and does not insert it twice.
Only the net change
The child's change is read with the same diff that checkpoints use. It reads only the rows with an event in the range, never the whole database. Statements the child created and then retracted are left out. A child that retracted an inherited fact and then reverted cancels out, because content mode sees through sys:restoredFrom links. A fork where an agent tried something, regretted it and reverted therefore merges as nothing.
Nothing is replaced silently
This is the rule we care most about. Suppose v:age allows one value per subject. Before the fork, Alice's age was 30. The child changed it to 31, and meanwhile the parent changed it to 32. A plain replay of the child's write would retract 32 as an ordinary cardinality replacement. The parent's value would disappear, and the only trace would be that a later merge happened to win.
Merge-back does not let a child's value replace a parent value written after the fork. You choose what happens instead:
KeepBoth(the default): 31 and 32 both stay live, and the merge reports a conflict. Tiramemsu already lists conflicting values with their evidence, so the disagreement is visible.PreferParent: 31 is recorded and immediately retracted, so it stays in history but is not live.PreferChild: 32 is retracted as a cardinality replacement.
A value that must be unique cannot keep both, so a clash on a unique value fails the merge unless you set a preference.
Late arrivals are kept, but not live
The child added a note to statement 12, and meanwhile the parent retracted 12. Inserting the note live would leave a live statement on a retracted base, which breaks grounded memory. Dropping it would lose work without a trace. Merge-back inserts the note and retracts it with kind Cascade in the same transaction, and reports it. The note stays in history, so someone who disagrees with the parent's retraction can bring both back.
Tags and transaction metadata stay home
Tag names are unique among live tags, so a child tag baseline would collide with the parent's baseline. Child transaction numbers mean nothing in the parent either. Revert already leaves this bookkeeping alone, and merge-back does the same. Provenance is not lost: for each statement it merges, the parent records in an append-only merge_source table which fork it came from, the child's statement and transaction, the instant, and the author and reason the child recorded.
Derivations are reused
If the parent and the child each derived the same conclusion from the same supporting facts, the parent should end up with one conclusion, not two. Derived statements therefore merge through the same derive call that created them, with remapped supports, and derive already returns the existing conclusion when the support set matches.
Every merge-back can be undone
Before applying, merge-back tags the parent's previous transaction (merge-back/plan-a/1 by default). A revert_to that tag undoes the merge. The mapped statements stay retracted, so merging the same child again does not quietly bring them back.
6. A worked example
Here is the whole flow with the Alice example. This is a sketch of the proposed API; the names may change during review.
# parent, transaction 40: Alice is 30
info = db.fork("forks/fix-ages.tm", label="fix-ages")
child = Db.open(info.path)
child.transact([assert_(alice, age, 31)]) # child: 30 → 31
child.transact([note(stmt_12, "checked by agent")]) # layer on inherited stmt 12
db.transact([assert_(alice, age, 32)]) # parent, meanwhile: 30 → 32
db.transact([retract(stmt_12)]) # parent drops stmt 12
report = db.preview_merge_back(child)
# inserted: age 31 (new parent id), the note
# retracted: age 30 (already retracted in the parent: no-op)
# cascaded: the note (its base, stmt 12, is retracted in the parent)
# conflicts: alice age 31 vs 32
# clean: False
db.merge_back(child, on_conflict="prefer_child")
# tags merge-back/fix-ages/1, retracts 32, inserts 31, keeps the note in history
The preview runs the real merge inside a transaction that is rolled back, the same way revert and bundle previews work. What it reports is exactly what the apply does, provided nothing commits in between.
7. Rebase: catching up with the parent
A fork that lives for days drifts. The parent keeps learning while the fork reasons over an older picture of the world. Without rebase, every disagreement waits until merge-back and lands in the parent, where a reviewer has to settle conflicts that the agent never saw while it worked. The only alternative is to fork again and lose the work.
Rebase replays the fork's work onto the parent's present state, as git rebase does. The way it does this follows from the id scheme.
Re-fork and replay, not an in-place pull
The obvious design pulls the parent's new statements into the existing fork. It breaks the one rule everything else relies on. After the fork, the parent's new statements got ids above the fork's high-water marks, and so did the fork's own new statements. Pulling the parent's statements in would need fresh ids for them, plus a map back to their parent ids, plus a way for every later merge-back to tell "pulled from the parent" apart from "created here". A second pull would add a second map.
Rebase sidesteps all of that:
- Fork the parent now. The new fork's high-water marks are the parent's present ones, so everything the parent knows is inherited.
- Replay the old fork's net change into the new fork, using exactly the merge-back rules: inherited ids by id, the fork's own statements re-minted and mapped, net change only, late arrivals cascaded, derivations reused. Merge-back and rebase are one replay function with two targets: the parent, or a fresh fork of it.
- Record
(<new fork> sys:rebasedFrom <old fork>)in the parent. The old fork is listed asrebased, and merging it back fails withForkRebased, so the same work cannot be merged twice.
# proposed API, not released
report = db.preview_rebase(child) # replays into a temporary fork, writes nothing
info = db.rebase(child, "forks/fix-ages-2.tm")
child2 = Db.open(info.path) # the old file is untouched
Conflicts land in the branch
In the Alice example, rebasing the fork gives a new fork in which 31 (the fork's value) and 32 (the parent's newer value) are both live, and the rebase report lists the conflict. The parent is unchanged. The agent, or a reviewer, settles it in the branch with an ordinary write. A later merge-back then carries one answer instead of a conflict. Because a rebase writes no belief into the parent, only lineage, an agent may rebase with the same permission it needs to fork. If the resolution retracts a parent fact, merge-back still sends it to review.
What a rebase changes
- Inherited ids never change. A note on inherited statement 12 still points at 12.
- Ids the fork created do change, the way a git rebase gives commits new hashes. The new fork keeps a
rebase_map, andresolve_rebasedtranslates an old citation such asurn:tiramemsu:stmt:105to its new statement. Keeping the old ids would mean holes in the counters and a second high-water mark, which is the in-place complexity again. - Provenance names the first writer. Every replayed statement records the transaction, instant, author and reason that first wrote it. A later merge-back carries that record into the parent, so after any number of rebases the parent still knows that
v:agent7wrote the statement on Tuesday. - Tags do not move. They name transactions of the old file. The report lists them, and the old fork keeps them until it is discarded.
- Undo is cheap. The old fork file is never written. Discard the new fork and the old one is
activeagain.
8. Who is allowed to merge
Agents should be able to explore freely and should not be able to rewrite shared memory on their own. So merging is gated by policy:
- Any agent may fork and preview.
- A merge-back applies automatically only when its preview is clean: no conflicts, no failed checks (schema, Datalog or ELPI constraints), no retraction of a parent statement, and no cascade into one.
- Anything else waits for a reviewer, who applies it with
tm merge-backand an explicit conflict preference. - Over MCP,
preview_merge_backis always available.merge_backappears only when the server runs with--allow-merge, applies only clean previews, and is refused in read-only mode. This follows the pattern of--allow-revert.
"No retraction of a parent statement" is strict on purpose: a sandbox that deletes the parent's facts always needs a human or a policy to sign off. Whether that is too strict is one of the open questions below.
9. Sync: peers that keep exchanging
Some memories are not sandboxes. An agent on a laptop and the same agent on a server, or a team of agents, keep learning separately and keep exchanging. For them, re-minting ids is wrong. A statement cited as stmt:42 in one file must mean the same statement in the other, and changes must be able to pass through a third peer.
Sync uses the origin bits. A peer's local ids stay origin 0 on disk, and foreign statements are stored with their origin, rendered as urn:tiramemsu:stmt:2.7. Every IRI already cited keeps working. The data model is already a CRDT: content never changes, ids are never reused, and a retraction is set once. A sync merge is therefore the union of statements plus the earliest retraction of each, and the result does not depend on the order or number of merges.
This revision changes three things in the earlier sync design:
- Origins come from the parent. The first design had an operator assign numbers to files. That was wrong for forks: a fork's pre-fork statements would have been claimed under the fork's own origin, duplicating the shared history at the first sync. Now
make_peerassigns a number from the parent, and records inherited ranges: ids up to the fork's high-water marks belong to the parent's origin, or through the parent's own ranges to an ancestor's. A fork that was squash-merged cannot later become a peer, and a peer is not squash-merged, so the two modes never mix ids. - Late arrivals converge. If peer C receives a retraction before a note on the retracted statement, and peer D receives them the other way round, both must end in the same state. The late-arrival rule above (insert, then cascade) gives that.
- Convergence is stated honestly. A merge runs the receiving file's constraints at commit, and a merge they reject fails as a whole. Peers with the same constraints converge. Peers with different constraints can differ, and the preview shows the refusal before anything is written.
Across origins, values that are meant to be single are a read policy, not a merge-time decision: picking a winner during the merge would make the order matter. Conflicts are listed with each value's origin, and a view can rank origins (origin_precedence) to show one value. Tags, transaction metadata and lineage are not exchanged. Equal derivations made independently by two peers both stay, because choosing which one survives would depend on what each peer had seen.
10. Erasure across forks
Erasure (crypto-shredding, planned) destroys a per-subject key so that a subject's sensitive values become unreadable while every row stays. A fork copies the parent's keys. Destroying the key in the parent therefore leaves a readable copy in every fork made before the erasure. We cannot fix that inside one file, so the design makes it visible:
erase_subjectreports every live fork that still holds the subject's key, so the operator can erase in each fork or discard it.- Merge-back re-seals the child's new sensitive values under the parent's key. An erasure done in the child reaches the parent only when you ask for it explicitly.
- Sealed values compare by their stored ciphertext. An erased copy and an intact copy of the same inherited statement are therefore the same content, not a conflict.
11. What we rejected
- Branch heads inside one file. Every scan would need a branch filter, on both engines and in the query planner, and reads come first. A copy-on-write file gives the same isolation at almost no cost.
- Thin branches (a view of the parent at time t plus a small delta file). Every read would have to combine two stores. That is branches-inside-a-file with extra steps.
- An origin number for every fork. It runs out, and every child id would cost an 8-byte varint in the parent instead of a short one.
- Last writer wins. Wrong for memory: the losing value is a belief someone held, and should be visible as a disagreement, not quietly lost.
- Treating speculation as a branch.
db.with(…)runs a change and throws it away. Turning that into a reviewable proposal against the parent is planned as its own phase, built on the merge-back preview. - Rebase as an in-place pull of the parent's changes into the fork file. Each pull would add an id map, and merge-back would have to tell pulled statements from the fork's own. Re-forking keeps the rule that ids at or below a fork's marks are the parent's.
- Adopting an unmanaged copy as a fork. We would have to guess where the two files diverged. They are refused instead.
12. Open questions
These are the decisions we would most like outside opinions on before writing code:
- How strict is "clean"? Today, any retraction of a parent statement sends a merge to review. That includes an agent correcting a value it was explicitly asked to correct. Should a policy allow a bounded number of such retractions, or only for certain predicates?
- Child tags. Drop them (current design), or bring them back with a prefix such as
plan-a/baseline? - Tags across a rebase. Should rebase re-create the old fork's live tags in the new fork with a prefix (
rebased/<name>), so a fork keeps its named moments, or is the old file enough? - Old forks after rebase. Delete the old fork automatically once the rebased fork is merged back, or always leave that to an explicit discard?
- Conflicts as records. Should
KeepBothconflicts also be written as review statements, so a later reviewer finds them without the merge report? - Discarding forks with unmerged work. Should deleting such a fork require
force? - Sync reads. Should
origin_precedencealso resolve unique values, by hiding lower-ranked subjects that hold the same value?
The specifications are in the repository: add-memory-fork, add-memory-merge-back, add-memory-rebase and add-memory-merge, each with a proposal, a design, requirements with scenarios, and tasks. The decisions and their reasons are D61–D77 in lat.md/branching.md. Comments are welcome as GitHub issues, or on Bluesky and Mastodon below.