One pass, only once memory.writer.trigger_tokens have accumulated (8,000, 16,000 or 32,000; default 16,000)
Session idle
state/memory/session_watcher: idle after 30 minutes; scans when the next known conversation goes idle or a retry is due, at most 5 minutes apart
write(…, force=True)
Passes until nothing remains. A finished session has no later batch.
Daily at 03:00
state/memory/scheduler; by hand openprogram memory sleep
reorganize(model=…)
Reorganizes Topics on disk, adds no content
Writes reread the session store through get_branch. Nothing is buffered in the process, so a restart loses nothing and every message keeps a stable ID. Only user messages and assistant replies count: tool calls and results, runtime-scheduled turns (subagent reports, branch-merge notices) and empty messages never enter memory.
Five write steps
One pass, under a cross-process write lock. The threshold decides whether a model is called, not how much one call writes.
Select every branch message without a written marker, minus tool calls and runtime-scheduled turns (runtime.pending()).
Batch from the oldest message up to the token threshold. The rest waits for the next pass.
Edit: the writer gets the batch text and the directory structure, and edits topics/ in staging.
Organize after 5 batches or 40,000 tokens, and again once a day has passed since global organization with new commits. Skipped otherwise.
Commit the transaction, then mark the nodes. The batch stays in chat history; footnotes link its messages, so nothing is copied.
Validation before install
Rule
Behaviour
Uncited prose
Normalization gives every paragraph of a file the write wrote a block ID, cited or not. The commit then refuses an uncited paragraph an automatic writer or the organizer added or reworded (MISSING_SOURCE); a person's save keeps it, and keeps a Topic left with headings only. A writer's edit still prunes sections and Topics it left empty.
On rejection
Committed Topics, Runtime state, revision and Git history are unchanged.
Pre-install callback
An instance-owned trusted callback records autosave or restore history after validation and stage preparation, before files move. Invalid edits create no checkpoint; a callback failure installs nothing. A valid edit records the exact pre-edit snapshot and the existing checkpoint deadline. Tools and request text cannot supply it.
Transactions: stage, validate, install
Copybaseline read first, then to system temp
Editonly staged topics/ is writable
Validatefour checks, see below
First rejection: restore staging, one repair with rule-specific guidance. Second rejection: COMMIT_REJECTED, repository untouched
Installback up, install all, rebuild views, Git
Check
Requirement
Format
The files this write wrote have the structure: every paragraph a block with an ^id, each ID held once, every cited footnote defined. A file the write left alone, or one written outside OpenProgram, is read as it is and fails nothing
Block IDs
Other paragraphs, Timeline and relations locate a paragraph by this ID. A writer or organizer may delete a block, since Git keeps it; a record edit or a save in Settings may remove only the IDs it deletes by name, or those of the Topic it deletes. Paragraphs may be rewritten, merged or moved.
Links
Cross-Topic links target #^ block IDs and none dangle, so deleting a block that is still linked is refused
Citations
Checked by author, on the paragraphs this write added or reworded: an automatic writer's or the organizer's must cite a message of this execution and batch (MISSING_SOURCE, SOURCE_NOT_ALLOWED); a person's may cite nothing, and what it does cite must be citable
Outside files
A file installed.json calls outside is not changed, deleted or linked into by anyone but a person saving it; filing it into a folder moves it with every byte kept (OUTSIDE_FILE_READ_ONLY, and nothing of the write installs)
Changes beside the write
Under the write lock, each file changed on disk since staging is compared: one the write left alone is taken in from disk and installed as it is, whatever it holds. One the write changed too, the cursor, or a file taken in that leaves one of our links dangling is CONCURRENT_UPDATE. A retrieval cache or anything else the stage does not install is ignored.
Why this order
The baseline is read before copying: read later, an edit would compare with itself and lost block IDs would go unseen. The second attempt after a rejection takes a fresh baseline for the same reason.
A second rejection keeps the turns pending and the markers unset. Reporting success would let the caller pass content never installed.
Human edits of Topics use the same staging and validation; invalid ones are rejected at once.
Every install records each Topic file's hash, its block IDs and its origin in installed.json in the runtime directory: runtime for a file one of our transactions wrote, or one edited elsewhere that kept every ID we installed; outside for a file that appeared without us, or lost IDs we installed.
A file never recorded is ours only when every paragraph cites a chat message. ownership.outside_paths reads the record at every stage, so the rules in Files written outside OpenProgram act on it; paths compare case-folded on macOS and Windows.
Written markers: identity, not position
A session is a graph. Re-asking, retrying or spawning a subagent makes a branch. Each branch's messages enter memory; shared prefixes do not enter twice.
m1 to m9written, marked
Branch from m3: b4 to b9unmarked, pending; head is b9
Walk back from headstop at the first marker (m3)
Aspect
Rule
Where
Node metadata, key WRITTEN_NODE_MARKER in writing.py. The value names the memory workspace, so exported sessions keep markers without passing for another workspace.
When
After the transaction installs and the pass changed files. A crash between the two leaves no marker and the same batch pending. Marking first would lose turns silently.
Prefix
Branches need no ordering: the first writer marks shared messages; the next walk stops there.
Assumption
Traversal treats markers as a prefix, which relies on each batch taking the oldest turns.
Session store
Markers must not change updated_at, which the idle watcher reads, and do not use the mark-synchronized path.
Cost
Only the current batch is marked. Rescanning would make Git growth quadratic, since the session directory runs git add -A per turn and a changed node is a new blob. The session-index rebuild measured 14–50 ms for 289 nodes, 4.2 MB.
Why not an ordinal or an ID set
An ordinal describes one expansion of a linked structure into a list, not a message.
A five-turn branch looks empty; an eleven-turn branch writes only its last two turns
Aspect
Node marker
ID set in memory
Pending
Walk back to the first marker
Traverse the branch, subtract the set
Storage
One field on an existing node
One file per thread with every written ID
Growth
None; each read walks a few nodes
One entry per message; reads load the list
Missing entry
Walk stops early, older content stays pending
Exactly that turn becomes pending
Coupling
Memory writes a field into session storage, as provenance, display kind, branch root and rewind state already do
Memory owns files, migration and permanent retention
Across nine frameworks, three store branching conversations (Claude Code, OpenClaw, pi-mono: append-only files with parent pointers), three are linear, one rewrites the session on retry and destroys the old branch, and two do not store conversations. None marks turns as consumed by memory.
Framework
Approach
Codex
Forks into a new file; extraction uses thread-level watermarks and leases
pi-mono
Records are immutable; annotations and cursor moves append references, and branch summaries compute coverage from the tree when switching
Claude Code
Cursor in process memory; reprocesses the session when the referenced message is missing
OpenClaw
Writes promotedAt on derived records; its memory hook reads the last fifteen lines as a flat list
The resident block
Core is the block injected at each session's start: the core section of MEMORY.md.
Aspect
Role
Size
topics/core.md
Source of truth; writers and nightly organization edit only this
No limit
Rendered core section
Rebuilt after each install
2,000-token budget (core_max_tokens)
The budget limits rendering, not writes. A block past the budget is left out of that injection, stays in the source and remains reachable through search and memory_get. To keep a paragraph visible, move it earlier. An 11,883-token source blocks no write and renders 1,983 tokens.
Why a derived view
A write-path gate would stop stable facts and reject unrelated transactions once the file is full. Clipping a writable file could remove unique block IDs and fail validation; rendered IDs are always a subset of source IDs. Clipping also needs no human-versus-automatic split, because the full source survives.
Core in Web, Writer and Organizer
Surface
Requirement
GET /api/memory/core
Reads a complete snapshot under the workspace lock. content, size, mtime mean the source; also returns rendered content, effective injection after memory.core.inject, the switch, tokens and budget.
Memory, Core
Defaults to the read-only injected view with tokens and budget, and shows an empty injection when disabled. Source records open for editing and save through compare-and-set transactions. Drafts typed during a save survive refresh. Previews share one sanitizer.
Writer prompt
Reads everything, records only what stays useful: no repeated status checks, unchanged measurements, one-off tool processes or details recoverable from project files. Project progress goes to that project's Topic, not Core.
Organizer prompt
In topics/core.md, moves project-specific, stale or duplicate content to Topics or deletes it, keeping rules, preferences and identity facts most future sessions need. Deleted content stays in Git history.
Nine interface methods
The sole interface between memory and the agent runtime, in state/memory/backend.py. Every method but name has a default.
Method
When
Runtime caller
name
Identifies a backend
Read as a property
is_available()
Can this backend be activated
Readiness checks and the channel provider route
system_prompt(tier=…)
Session start: injects MEMORY.md in memory-context, apart from user input
Connected
search(query)
Before each turn; default BM25, top 5, tight time budget
Connected
write(…)
After each turn and on idle; only force differs
Connected
reorganize()
Daily at 03:00 and openprogram memory sleep
Connected
initialize(…)
Once at session start
Only forwarded by the policy wrapper; no runtime call
extract_before_discard()
Compaction asks what the summary should keep; stores nothing
Only forwarded by the policy wrapper; no runtime call
shutdown()
After the last turn; the idle watcher finalizes through write(force=True) today
Only forwarded by the policy wrapper; no runtime call
The three unconnected methods are extension points for third-party systems that need connections, final flushes or pre-compaction saves; the built-in backend needs none. Recalled text is wrapped in <memory-context> where it is produced. There is no tool-registration method: a memory system with tools is a plugin.
Failure behaviour
write() returns
Cases
Idle watcher
Nothing
Written, or below threshold
Marks handled, skips next poll
Failure, retryable
Lock held or a file this write changed was changed elsewhere; vector backend, model or writer process unavailable; edits refused
Unmarked, and kept at the scope of its cause (below)
Failure, not retryable
Both edits rejected (COMMIT_REJECTED); unavailable source or invalid patch; no session ID
Marks handled and publishes memory.ingest_ended with ok: false. Same content, same rejection. A failure in the sign-in or the memory is kept at its scope instead.
The idle watcher keeps all of its bookkeeping in one file, ingest-state.json in the personal memory's runtime directory, because a conversation can move between projects. A failure is recorded at the scope of its cause:
Scope
Causes
Rule
Lifted by
Conversation
Any cause not listed below
Keyed by the conversation's updated_at. At most three failures, an hour apart; a transient failure between them neither spends nor resets them and sets only its own doubling wait
The conversation changing. A successful write elsewhere does not count
Memory
WRITER_PRECONDITION_FAILED, GIT_COMMIT_FAILED
Recorded once for the target memory; every conversation writing there is passed over
An edit to that memory, a configuration change, or a restart
Written to that memory's writer status as not retryable, announced once per cause
Writer status
Keeps its fields: retries.max_identical_failures is the three tries
Bad sign-in, twenty idle conversations
An hour of polls makes one model call, where it made twenty and gave up on all twenty
Entries from the replaced files
Come over unstopped: a sign-in or memory cause is dropped so the conversation is offered once more, any other keeps one try
Rule
Detail
Silence means success
Forgetting a return also returns nothing, and the opposite reading would retry forever
Failures
The closed MemoryWriteFailureCode set; unclassified exceptions do not retry
Per-turn path
Logs pending content at debug level and retries next turn
Lock contention
A failure, not an unmet threshold
Conversation
Memory failures never fail it: each hook catches and logs its own exceptions
Branch handling
Case
Today
Gap
Other branches
Forced boundary writes take head, then other unarchived tips; markers dedupe prefixes. Within a turn only head is written.
Triggered by the idle watcher, not by head changes
Exclusive branches
Flask on one branch, FastAPI on another: adjacent paragraphs in one Topic
The Topic format cannot say they conflict; retrieval returns both and organization may merge them
Cross-session spawn
Each half keeps its own bookkeeping; nothing lost or duplicated. Spawn branches in one session share node marks.
No link says one continues the other
Compaction summary as head
Normally a side branch off the first summarized turn's predecessor
If head moves onto it, the summary counts as an unwritten assistant turn and repeats facts in new words
Memory Web page
Four sections (Topics, Timeline, Recent, Core) on existing APIs, in apps/web/components/memory/: index.tsx, parts.tsx, memory-page.module.css, and a Markdown helper that reuses the existing renderer and sanitizer.
Area
Structure
Avoids
Top bar
Page title, Memory settings, and from /api/memory/status a writer-failure row, a "writing paused" row (this memory's or the sign-in's stop in ingest-state.json) and a "not text" row naming Topic files that do not decode
Totals the APIs cannot count
Secondary sidebar
Folder, Topic, Timeline year/month/day, Recent and Core rows: 36px height, 10px horizontal padding, 8px radius, 13px text. Shared 14×14 ChevronRight and numeric badges; hierarchy by indentation only.
Tiny triangles; topics/core.md listed twice
Content header
Name, type, path, modified time, view and actions in one 76px area; Recent shows records / memory.recent.limit
A separate metadata strip; record counts confused with token budget
Body
Preview, Timeline, Recent, Core: centred, at most 780px. Edit: full-width monospace.
Over-wide text
Markdown preview
Obsidian Flavored Markdown through marked and the sanitizer. Named and inline footnotes become numbered superscripts and an end list, with two-space continuation. A trailing ^block-id becomes an invisible anchor. Code and escaped syntax stay literal.
Internal IDs in prose; changes to the source on disk
Below 720px
Section icons, then one page of list or detail with Back. Core, Timeline and Recent go straight to content. Section labels hide first; width priority is detail, list, labels. Window width never rewrites sidebar state.
Three stacked panes, overlap
Boundaries
Timeline stays a derived view, collapsing by year, month and day. It adds no event times and never shows rebuild time as record time.
Kept: Core compare-and-set saves, partial Timeline dates, keyboard focus, settings navigation. Footnote transformation runs before sanitizing, so generated links and anchors pass the same sanitizer; arbitrary input cannot collide with internal placeholders.
Not included: home dashboard, charts, Topic wizard, drag sorting, bulk editing, automatic sidebar collapse, new APIs, new dependencies, new persisted UI state, or a source-browsing API. Commitments and Scheduler state are not shown. Empty selection shows a short prompt and the settings entry.
Two ways to say a change, one path: Runtime staging, normalization, citation and relation checks, Timeline/Recent/Relations/Core rebuild, atomic install, Git. Git failure after install does not pretend to roll back: results carry memory_committed and git_committed.
Way
Who
How
Edit files
Background writers, organizers, Web and CLI file edits (staged_edit)
Edit topics/**/*.md in staging, cite as [short keyword](/s/<session>#<message>), then commit_edits
Structured
Model tools memory_update and owner POST /api/memory/changes
memory_changes[]; each request picks one of memory_changes, whole-Topic changes[path/action/content] or unified patch, all ending in MemoryWorkspace.update
Structured operations
Operation
Required
Runtime
create_record
Final content, time (undated in the model schema; owner REST also accepts null), non-empty sources[{source,label}], destination (topic_path, headings, position)
Validates Topic, position and each new citation; keeps the label verbatim; allocates block and evidence IDs
update_record
memory_id plus complete final content, time, sources
Replaces paragraph and evidence definition; keeps block ID and position
delete_record
memory_id
Deletes record and unused evidence; rejects all if a block link would dangle
move_records
Ordered non-empty memory_ids, same destination
Moves in that order, keeping IDs, content, time, citations, creation order
Sources and labels
Field
Rule
source
Chat link /s/<session>#<message>, its ref openprogram/<session>/<message>, or current for this turn's user message. A record with no sources cites that message. source_refs: [string] accepts the same links. Callers cannot submit provenance or owner identity.
label
Display text for this one citation, made in the same write call. Prompts and schemas ask for short contextual keywords, no Markdown, URLs, IDs, speaker names or time templates. Runtime requires only a non-empty string and never truncates or rewrites it.
Output
{"content":"…","sources":[{"source":"/s/session#message","label":"research scope"}]} becomes [research scope](/s/session#message). The parser reads the target, never the display text.
Old workspaces
A workspace with an old sources/ copy is converted once by store.cite_chats_directly.
Position, composition and conflicts
Topic
Rule
Position
start, end, before, after. An anchor needs anchor_memory_id, in the destination's Topic and heading chain, outside the move set. Each ID takes at most one content operation and one move; delete and move cannot share an ID.
Composition
Merge: one update, several deletes, moves as needed. Split: one update, several creates, moves as needed. No merge_records, split_record, place_records or reorder_records.
Cleanup
Runtime removes heading chains with no records and Topic files with none.
Legacy records
mem_* keep their IDs. All IDs sharing one physical paragraph move together, contiguously, in paragraph order.
Evidence conflict
Same evidence label with different time or citation across Topics: all rejected with INVALID_ARGUMENT. Different relative paths alone are no conflict.
Old inputs
Earlier create, update and delete inputs are converted; schemas expose only the four names.
Scheduler
Local-owner prompt tasks may call memory_search, memory_get, memory_update; the service does not dual-write. A deleted memory_id returns NOT_FOUND, with no placeholder.
Model scope
Interactive models, writers and organizers can rewrite, merge, split or delete. Deleting a block means fixing links to it in the same transaction. Committed citations are not re-checked.
Reading
One reader, read_topic_tree, reads each topics/**/*.md file (any case) on its own; read_checked_tree holds only the files a write wrote to the strict structure. BOM and CRLF are dropped and front matter is not prose. A paragraph without an ^id, or whose ID an earlier file holds, gets one derived from path and text. A bad footnote reads as text; a non-UTF-8 file yields nothing; no file stops the rest.
Retrieval
BM25 and embedding both index every unit the reader returns: one event per cited claim, and one per paragraph that cites nothing, under its own ID with an origin. BM25 keeps no disk cache: reading the largest workspace takes tens of milliseconds, and in-process indexes are reused by Topic file signature; embedding reuses parsed events and vectors. Time, size or inode changes invalidate them.
Record CRUD plus the batch move multi-file Topics need
Files written outside OpenProgram
Whatever a Topic file holds is memory. Another tool's notes, a person's paragraph without a citation and a file the chat agent wrote with its file tools are all read, indexed and found. What differs is who may change them and how they are labelled.
Topic
Design
Follows
Where sources are checked
Once, in commit_edits (_check_block_references), on the paragraphs a write added or reworded, by author. The parser's strict form checks structure only
Grok Build (checks on the write path), Maka (sources are a property of the writer)
Outside files
Read in place, never rewritten: normalization, link rewriting and the organizer skip them, a writer's edit to one is refused, nothing links into them. A regroup may move one whole: the commit matches the new path to the old by hash, keeps its origin and carries its first-seen days. A person's save in Settings makes the file ours (runtime) and normalization gives its paragraphs IDs. Our file reordered elsewhere with every ID kept stays ours
Claude Code and Oh My Pi (read in place, the organizer leaves it alone); Codex for taking a person's edit of our file
A broken file
Spoils only itself. No repair agent, nothing held aside: a file that does not decode is named once under "not text"
Every peer: none repairs with a model; Grok Build closest
Labels
origin on each unit: cited, person (ours, no citation) or outside. Search results say source: outside file or source: added by person instead of refs; the editor shows a Nova badge by a person's paragraph and one by the title of an outside file, worded to need no hover text
Maka (origin per item), Codex (source class told to the model)
Map
An "Other files" list after the agents' map in the prompt, generated by code into the runtime directory (outside-map.md): at most a quarter of GUIDE_MAX_BYTES, titled entries (front matter name, first heading) in three quarters of that, bare paths after, then "N more files are not listed". Redrawn only at installs and at Worker start; MEMORY.md stays the agents'
Grok Build (generated manifest, the 3/4 split, regenerated at session boundaries)
Timeline
A paragraph that cites nothing is filed under the day memory first read it, from first-seen.json (keyed by paragraph ID), shown "recorded <date>". A file already in Git takes the day it was first added; otherwise today. A reworded paragraph is new and gets a new day
Grok Build (time first indexed); not Claude Code's modification time
The chat agent's file tools
Not routed into a transaction: a file it writes into topics/ is an outside file. MEMORY.md's layout tells it to use memory_update to remember
Claude Code (file tools write memory), Codex (point the model at the memory tool)
Derived IDs
~<6 hex of path>-<12 hex of path and text>. A stale one given to memory_get returns its file's current paragraphs with a note, found by the path part
Codex and Grok Build (locate by file or position, no stability across edits)
Memory turned off mid-conversation
Recall already shown stays in the history until the next compaction; only new recall and the memory tools stop (the cache-prefix design implements this)
Hermes, Codex, Claude Code: none withdraws what was sent
Why this design
Sources by author, at commit
Compared: the parser requiring a footnote in every file, against the commit checking who wrote what. A format rule on the read side let one file from another tool fail every write, which is how memory stopped growing.
Checked when written
Claude Code, Codex and Grok Build all check the writer at the moment it writes; our exact citations stay required of the automatic writers, where the execution policy depends on them.
Outside files read-only in place
Compared: rewriting them into our format, copying them into an inbox (Codex's ad-hoc notes), and reading them in place. Another tool rewrites its own files at any time, so IDs and links we add break; a copy diverges and duplicates. Reading in place is the only option with neither.
Ours by the set of IDs
Judging "still ours" by the set of IDs, not their order, covers an editor that reorders paragraphs.
No repair agent
A repair could never succeed on another tool's prose, since no chat message stands behind it, and it ran 127 times against 36 writes in the measured period. Once format no longer decides what is memory, nothing needs holding aside.
Origin labels
"No source" says what is missing, not where a paragraph came from; the reader and the model need to know how far to trust it. The origin is derived from installed.json and the footnotes, so nothing new is stored.
Map redrawn at installs
Compared with throttling the memory note (every 10% or every 5 turns), which no peer does. Tying the list to our own installs means the memory section changes at most once per write, the rate the writer already changes the map at, and search finds a new file the moment it lands.
First-seen day, not modification time
Copying, syncing and formatting move a modification time, so the same sentence would change days. The day we record is stable and honest: it says when memory learned it, labelled "recorded", apart from the event dates of cited paragraphs.
File tools left alone
Grok Build routes them into its memory policy because its organizer owns every topic and would overwrite them. Ours leaves outside files alone, so a direct write is already safe, and requiring citations there would give the model a failure Write and Edit cannot avoid.
Unstable derived IDs
A stable ID could only live in the file, which the read-only rule forbids; outside paragraphs are never link targets, so only a one-off reference in a chat is affected, and falling back to the file serves it.
Implementation status
Status
Items
Implemented
Both write entries, staged transactions, written markers, live-branch enumeration at session boundaries, rendered Core, default-Agent writer with memory.writer.model, writer status in tools, CLI and Web, memory.backend=none rejecting CLI verbs and /api/memory/* before a workspace exists, structured changes and source labels
Implemented in the redesign
One lenient reader for both indexes, with per-file isolation; deletion rules stated as they are enforced; changes beside a write taken in; the watcher's failures kept by scope in ingest-state.json, which replaced session-end.json and session-end-retries.json on first load; the installed.json origin record; everything in Files written outside OpenProgram
Measured after deployment
On the dev instance: no repair-format run in 24 hours (there is no such stage any more), and how often memory.ingest_ended fires in an hour with an invalid writer key; a real-model writer pass and 03:00 pass leaving every outside file byte for byte. These need real model requests and a running instance
Before it ships
Before-and-after screenshots of the editor's origin badges and the two status rows, for approval