OpenProgram Docs

Data model

On disk

<state>/projects/
├── projects.json                       project registry
├── <project_id>/                       `default` is the home project
│   ├── settings.json                   project defaults
│   ├── memory/                         the project's memory workspace
│   └── chats/
│       ├── <session_id>/
│       │   ├── main.jsonl              the session's log, written by the Worker
│       │   ├── agents/<pid>-<id>.jsonl log of another writing process
│       │   ├── functions/<id>.jsonl    one durable function's completed steps
│       │   ├── large_nodes/            bodies too large for a log line
│       │   ├── context/                persisted context artifacts
│       │   └── workdir/attachments/    uploaded files
│       └── .file-recovery/<session_id>/<turn>/   per-turn file undo
├── .chats-index.json                   registry (summary cache)
├── .chats-locations.json               durable session-id → directory map
├── .migration/                         migration journal and staging
├── .deleted/                           durable delete intents
├── .quarantine/                        log-less shells moved at startup
└── .locks/ .session-locks/             inter-process coordination
  • A session with no project lands under default/chats/. A store opened on another root (application runs, an embedding host) uses the same placement.
  • Moving renames the directory and records it in .chats-locations.json, the durable authority during migration or relocation.
  • A working folder is never the conversation directory. <project>/.openprogram/sessions/<id>/ is read only as a legacy migration source.
  • projects.json is published whole by rename. A change holds the registry lock for its read-modify-write; a lookup takes no lock and parses a published file once.

The session log

Each line is {"ts", "type", "data", "crc"}: nanosecond timestamp, CRC of the line. Lines are only appended.

Line typeRecords
node.put, node.patch, node.deleteA DAG node written, changed or removed
node.streamWhat a streaming reply added since its last line: the open block's new text, or the blocks from the first one that changed, and the output's new tail
meta.patchTitle, settings and other session metadata
file.putA whole small document: jobs.json, notices.json, inbox.json, todos.json, open_work.json, always_on.json, always_on_reports.jsonl
turn.*Agent journal: snapshot, model decisions, tools started and their results
turn.rowsChanges to the run tables
function.*In functions/: a durable function's steps, requests and saved state
  • One writer per file: the Worker writes main.jsonl, any other process its own file under agents/.
  • Reading folds every file in timestamp order and skips a line whose crc fails, which only a stopped writer's last line can be.
  • A process keeps its fold and reads what was appended since. It refolds from the start if a known file was replaced or shrank, or a new line sorts before what it has.
  • A reply's trace (metadata.extra) is worked out once, when the fold is handed out: from the last line that stored it whole (compressed when large) and the node.stream lines after it. A version a later line replaced is never decompressed or parsed.
  • A read for a fold hands a replaced version back without its trace, so the copies of one growing trace are not held together. Log files are read a line at a time.
  • Text that node.stream lines add to a block or to the output is kept as pieces and joined once, there. Folding a reply costs its length, however many lines it streamed in.
  • A fold that read at least 4 MB, and at least as much as the last checkpoint weighs, writes checkpoint/fold.json (folded nodes, metadata, state files, run rows) and checkpoint/records.json (state files and run rows). Each records, per file, the offset it covers and the bytes that end there. Checkpoints never cost more than twice the log they cover.
  • A cold open reads the checkpoint and only the lines after it. A file whose inode, length or covered end no longer matches is read from the start.
  • State files and run rows are read together, in one pass over only their lines, from the records checkpoint on. A first read that went through at least 256 KB of log writes checkpoint/records.json itself: a conversation too small for a fold's checkpoint is otherwise read whole by every process that looks for its jobs.
  • Only realtime push fragments are not kept.

Streaming once rewrote the reply's whole trace on every delta: one log reached 731 MB, 675 MB of it rewrites, and a cold open took 8 s. Now a line holds what was added. pi-mono, Claude Code and Codex write one line per finished entry and opencode updates a part in place; none rewrites a message per delta.

Logs written before that keep the rewrites. log_compaction.compact_session removes them from a session nothing is writing:

  • In each file, every node.patch that sets a trace loses it, except a node's last one. A patch that sets the trace replaces what came before, so the fold is the same.
  • The new file is written beside the old one. The whole session is folded from the old files and from the new ones, and a file is replaced only when both folds are equal.
  • The checkpoint is removed; the next open writes one for the new files.

Measured on a copy of one profile: 66 conversations, 2621 MB to 693 MB in 30 s, every fold equal. It is the one place a log file is rewritten, which is why it never runs under a Worker.

What a turn adds besides its reply

A line holds what cannot be worked out again, once.

LineHoldsLeft out, and where it comes from
turn.snapshotOnce per turn: model, request settings, the prompt or its hash, and per tool its name with two digests, declaration_sha256 (description, parameters, cache control, permission, approval) and implementation_sha256 (the code that runs)Tool descriptions and schemas. A resume resolves the live tools again and compares digests; a mismatch names the tool and which of the two changed
meta.patch _last_context_statsAfter each provider request: the measured total, its basis, the estimate and the offsetThe per-category breakdown with its tool and prompt rows. It is counted from the conversation's nodes, prompt and tools; a first open counts it again and the panel fetches it

Measured on a turn of six provider requests with 81 tools: 27 KB beyond the reply and its journal, 18 KB of it the snapshot and 4 KB the context stats. With tool schemas and the breakdown copied into these lines the same turn writes 224 KB (127 KB and 97 KB).

Codex writes a small turn_context line per turn (model, working directory, policies) and its instructions once per session; Claude Code's transcript lines carry a message and its usage, and /context is counted when asked. Neither records tool schemas or a context breakdown per request, so neither does this log.

Digests per tool are kept, not one digest for the catalog, because a refused resume has to say which tool changed, and a durable function's code may change while its declaration may not.

Run state

Executions, attempts, effects, waits and commands are folded from the same logs into plain Python tables in the Worker's memory, with their own transactions, undo and uniqueness rules. No database. A committed change is a turn.rows line.

ItemRole
~/.openprogram/active/<session>Marks unfinished runs; folded at startup. Others fold when first asked for: startup reads no conversation, and a conversation is read the first time it is opened. Deleting a conversation removes its marker, and startup drops one that names a deleted conversation
run_index.jsonlExecution → session
revisions.jsonlWorkflow versions and approvals, and global budgets
Idle sessionLeaves memory an hour after its last change, returns from its log
Function subprocessReads tables only. Steps go to its log under functions/; run-state changes (sub-agent start, Auto review verdict, pause, question) go to its parent via runtime/execution/worker_calls.py
Scheduled runA task's turn runs in a process of its own and writes that turn's rows to its own file under agents/. Sub-agents it starts go to the Worker through worker_calls.py, and the Worker runs them. The Worker reads the turn's rows again when the process ends
worker.lockHolder owns every run except a turn whose lease names another process (a scheduled run, ACP, MCP). No heartbeats; the OS releases it on exit
Job admissions, reservationsRun tables, in the session's log
usage.db settlementEvent commits first, reservation settles after. Startup settles any reservation whose event exists, so nothing counts twice

What stays a database

StoreWhy
usage.dbAccounting only (events, requests, routes, probes), grouped by time, model and scope
memory/index.sqliteFull-text search; rebuilt from the memory files
processes.dbDetached supervisors outlive the Worker and write the same record
session-resources.dbTool processes report resources; Page state is shared across processes
programs/.runtime/Application subprocesses share state with the host
project-file-history/history.sqlite3A version and its group commit together

Small stores read by key (user_errors.jsonl, file_operations.jsonl) are keyed append-only logs through state/store/record_log.py.

After the Worker stops

In progressNew Worker
Model callSends it again
Read-only toolRuns it again
File editCompares the file's hash with the recorded before and after
Any other toolTells the model it was interrupted and may or may not have finished; the model checks

An interruption is what the log shows when a turn has no final line, not a stored state. Planned upgrades wait for runs first.

Session fields

FieldTypeIn registryMeaning
idstrYesUnique identifier
agent_idstrYesBound Agent
titlestrYesDisplay name
created_atfloatYesCreation time
updated_atfloatYesLast activity
project_idstr?NoBound project; listing adds project
project_historylistNoProjects the conversation moved out of
sourcestr?YesOrigin: tui, web, wechat, …
channelstr?YesChannel type
account_idstr?YesChannel account
peer_displaystr?YesPeer display name
peer_idstr?YesPeer ID
pinned, archivedboolYesFlags
groupstr?YesGroup label
statusstrYesSee below
unreadboolYesUnread marker
sort_atfloatYesPlace in the project list; 0 = none
sort_sincefloatYesupdated_at when placed; later activity ends it
_auto_titledboolNoInternal, never returned to the frontend
previewstrOnly thereLast user message, at most 80 characters

Status

ValueMeaningSidebar
idleNo turn executingGray dot
runningA turn is executingGreen spinning arc
needs_inputThe Agent waits for the userAmber dot
doneBackground task finishedBlue dot with unread
failedTurn failedRed dot with unread; gray once opened
interruptedThe Worker died mid-turnGray dot, not run-active
cancelling, cancelledA cancel in progress, or finished across a restart

A killed Worker never clears running, which would pin the chat at data-run-active="true". Registry load resets running to idle; reconcile_interrupted_runs() then turns a row still running into interrupted and cancelling into cancelled, separately from the node sweep, because a Worker killed between the status write and the placeholder leaves a running row with no running node.

Moving HEAD

_set_active_head (interfaces/server/server_runtime/session_persistence.py) coordinates an explicit checkout. SessionStore owns HEAD; _save_session does not write the mirror’s head or messages back.

  1. Atomically compare the source head, branch identity and settings, then save the source configuration and select the destination. The expected settings are read from disk in their stored form, so a record that has no agent_id yet (one first written by a model pin) still compares equal.
  2. Under the mirror lock, re-read current branch settings, head and messages. Branch references retain independent settings even at the same head.
  3. Drop the message cache.
  • Used by retry, edit, sibling checkout, deepest-leaf jump, branch checkout, branch delete, attach, rewind.
  • Refused while a run is in flight (_is_run_active): RUN_ACTIVE_ERROR, code: "run_active". Otherwise a reply lands on a branch the user left, or on a tail being deleted.

Cache and attachments

  • SessionStore holds lazy (SessionLog, SessionMemoryIndex) pairs in a bounded LRU cache. SessionLog owns the files; the index holds folded nodes, edges and active head.
  • Browser uploads are copied to workdir/attachments/ before dispatch, and markers keep the saved absolute path.
  • Channel files stay in <state>/channels/*/accounts/*/attachments, separately readable by the attachment path policy.
  • Only the exact shape <project>/.openprogram/sessions/<session_id>/workdir/attachments/<relative> may be rebased to that session's current directory (attachment UI, file reader, send_file). The result must stay under an allowed root, with no .. or symlink escape. Other old paths are never remapped.

Interface

class SessionStore:
    def create_session(session_id, agent_id, *, title="", source=None, **meta) -> None
    def get_session(session_id) -> dict | None
    def update_session(session_id, **fields) -> None
    def delete_session(session_id) -> None
    def list_sessions(*, limit=100, offset=0, include_archived=False, **filters) -> list[dict]
    def get_branch(session_id, head_id=None) -> list[dict]
    def append_message(session_id, msg) -> None
    def latest_user_text(session_id) -> str | None
    def move_session(session_id, project_id) -> dict
    def set_archived(session_id, archived) -> bool

Operations

Last updated · 2026-11-25