# 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](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/session/operations.html#moving-a-conversation) 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 type | Records |
| --- | --- |
| `node.put`, `node.patch`, `node.delete` | A DAG node written, changed or removed |
| `node.stream` | What 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.patch` | Title, settings and other session metadata |
| `file.put` | A 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.rows` | Changes 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.

| Line | Holds | Left out, and where it comes from |
| --- | --- | --- |
| `turn.snapshot` | Once 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_stats` | After each provider request: the measured total, its basis, the estimate and the offset | The 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.

| Item | Role |
| --- | --- |
| `~/.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.jsonl` | Execution → session |
| `revisions.jsonl` | Workflow versions and approvals, and global budgets |
| Idle session | Leaves memory an hour after its last change, returns from its log |
| Function subprocess | Reads 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 run | A 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.lock` | Holder 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, reservations | Run tables, in the session's log |
| `usage.db` settlement | Event commits first, reservation settles after. Startup settles any reservation whose event exists, so nothing counts twice |

### What stays a database

| Store | Why |
| --- | --- |
| `usage.db` | Accounting only (events, requests, routes, probes), grouped by time, model and scope |
| `memory/index.sqlite` | Full-text search; rebuilt from the memory files |
| `processes.db` | Detached supervisors outlive the Worker and write the same record |
| `session-resources.db` | Tool processes report resources; Page state is shared across processes |
| `programs/.runtime/` | Application subprocesses share state with the host |
| `project-file-history/history.sqlite3` | A 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 progress | New Worker |
| --- | --- |
| Model call | Sends it again |
| Read-only tool | Runs it again |
| File edit | Compares the file's hash with the recorded before and after |
| Any other tool | Tells 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

| Field | Type | In registry | Meaning |
| --- | --- | --- | --- |
| `id` | str | Yes | Unique identifier |
| `agent_id` | str | Yes | Bound Agent |
| `title` | str | Yes | Display name |
| `created_at` | float | Yes | Creation time |
| `updated_at` | float | Yes | Last activity |
| `project_id` | str? | No | Bound project; listing adds `project` |
| `project_history` | list | No | Projects the conversation moved out of |
| `source` | str? | Yes | Origin: tui, web, wechat, … |
| `channel` | str? | Yes | Channel type |
| `account_id` | str? | Yes | Channel account |
| `peer_display` | str? | Yes | Peer display name |
| `peer_id` | str? | Yes | Peer ID |
| `pinned`, `archived` | bool | Yes | Flags |
| `group` | str? | Yes | Group label |
| `status` | str | Yes | See below |
| `unread` | bool | Yes | Unread marker |
| `sort_at` | float | Yes | [Place in the project list](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/session/operations.html#place-in-project-list); 0 = none |
| `sort_since` | float | Yes | `updated_at` when placed; later activity ends it |
| `_auto_titled` | bool | No | Internal, never returned to the frontend |
| `preview` | str | Only there | Last user message, at most 80 characters |

### Status

| Value | Meaning | Sidebar |
| --- | --- | --- |
| `idle` | No turn executing | Gray dot |
| `running` | A turn is executing | Green spinning arc |
| `needs_input` | The Agent waits for the user | Amber dot |
| `done` | Background task finished | Blue dot with `unread` |
| `failed` | Turn failed | Red dot with `unread`; gray once opened |
| `interrupted` | The Worker died mid-turn | Gray dot, not run-active |
| `cancelling`, `cancelled` | A 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](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/session/operations.html)
