# Operations

- **Session directory**: `<state>/projects/<project_id>/chats/<session_id>/` (project `default` when unbound)
- **Metadata**: `id`, `agent_id`, `title`, `created_at`, `updated_at`, `source`, `status="idle"`, …

| Call | Session on disk | Registry `_index` | Frame |
| --- | --- | --- | --- |
| `create_session` | Directory and metadata created | Row added, written at once | None; found through `list_sessions` |
| `append_message` | Node line in the log; metadata, with head when the chain advances | `updated_at`. User message: `preview`, 77 characters + "…" when over 80. Flushed within 5 seconds. | None; content streams separately |
| `update_session` | Only the given fields | Same fields, `updated_at` untouched, written at once | `session_updated`, changed fields only; the frontend patches |
| `list_sessions` | Not read | Rows copied, archived dropped, filtered, by `updated_at` descending, paged by offset and limit | `sessions_list`: registry fields, `preview`, `project` from the project directory |
| `delete_session` | Destroyed under session locks | Row removed, written at once; location forgotten, project unbound | `session_deleted` |
| `set_archived` | A metadata boolean | Same boolean | `session_updated`; returns `False` for an unknown id |

Registry writes go through a temporary file and rename, and flush on exit. After SIGKILL it rebuilds from logs, losing at most 5 seconds of preview. `commit_turn` makes the fields durable at the turn boundary. Frames come from the WebSocket handler.

Archiving deletes, moves and appends nothing, so `updated_at` holds and an unarchived session returns to its place ([storage consistency](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/session/storage-consistency.html)); `get_messages` keeps working.

**Entry points and filters**

| Entry | Behaviour |
| --- | --- |
| `dispatcher.process_user_turn`, channel handler | Create for an unknown session, then `append_message` at once: no shell |
| `session_context` | Creates when CLI or harness enters with an unknown id. Exit before a message leaves an empty conversation until deleted; startup keeps it, since it has its log. |
| `include_archived=True` | Both. Passed by passes visiting everything: memory scan, run-state repair, "clear all", channel-binding lookup, Agent addressing. |
| `archived=True` | Only archived |
| Sidebar payload | Every row: the client switches active, archived, all without a round trip |
| Archive, WebSocket | `{"action": "update_session_flags", "session_id": ..., "archived": true}` |
| Archive, REST | `POST /api/sessions/archive`, `POST /api/sessions/unarchive`, body `{"session_id": ...}` |
| Archive, CLI | `openprogram sessions archive <id>`, `openprogram sessions unarchive <id>` |
| Delete, on disk | Delete intent in `.deleted/`; session directory and recorded other location destroyed; run tables forgotten; `.file-recovery/<id>` removed; file history released; lock files removed. See [after a delete](#after-delete) |

## Startup

1. Load `.chats-index.json` into `_index`. Missing or unparsable: scan project layouts and durable locations, rebuild from each log's metadata, write it.
2. Reset `running` rows to `idle`; execution recovery is separate.
3. Clean up unarchived rows older than one hour:

| Session directory | Result |
| --- | --- |
| Has `main.jsonl` | Kept |
| Absent at the default placement, no layout holds it | Summary row dropped; project bindings and locations stay |
| Has `agents` or `events.jsonl`, no main log | Kept with a warning |
| Otherwise (a shell) | Moved under the session lock to `.quarantine/<id>-<time>/session/` with `reason.json`; row dropped. Never outside the store root. |

Retained when uncertain: no `created_at`, archived or tombstoned, unreachable non-default placement, migration row not `done` or `deleted`, unreadable journal (pass skipped), busy lock, filesystem error. Files are never deleted; `.quarantine` stays until removed by hand. No expiry or session-count limit.

## After a delete

A delete is final: there is no undo and no trash folder. One small file stays.

| Left by the conversation | After the delete |
| --- | --- |
| Delete mark, `.deleted/<id>` | Kept for good: about 80 bytes, read by name, never listed. It is what refuses a late writer, a migration, a channel route or a stale copy that would bring the id back |
| Lock files: `.locks/<id>.lock`, `.locks/.operations-<id>.lock`, `.locks/.migration-<id>.lock`, `.goal-locks/<hash>.lock` | Removed by the delete, under the conversation's lock, after the mark is written |
| File history, `shadow-git/<hash>/` | The repository belongs to a directory. It lists the conversations that committed into it in `.git/openprogram-sessions/` and is removed when the last one listed is deleted. Removing the emptied list is the claim: it fails while a conversation is listed, so one that lists itself at that moment keeps the repository |
| REST reads of the id | `404 session_not_found` on `/context`, `/tokens`, `/branches/tokens`, `/context-range` and `/dag`, as for an id nobody created. A conversation the server holds in memory is known, so a draft's first Send is answered |

A store that opens removes the idle lock files of ids it has no conversation for, and releases the file history of a delete that stopped half way. A held lock file stays.

| The sweep | How |
| --- | --- |
| Where it runs | Opening reads the names in `.locks/` and `.goal-locks/`. The removals run on a thread of their own, so a store opened on the server's event loop does not wait for them |
| A conversation the index missed | Loses nothing. Only an idle lock file can go, it holds no state, and the next lock of the id makes it again |
| File history | Removed only when every conversation listed in it has a delete mark in this store. A repository with no list, or one listing an id of another store, stays |
| Reach | The store's own root and the `shadow-git/` folder of its state directory, both fixed when the store opens. Another profile's state directory is never read |

**Why this design**

| Decision | Reasoning |
| --- | --- |
| The mark has no expiry | Removing lock files is safe only because whoever takes the lock next finds the mark and stops. An expired mark would let a waiter or a leftover copy write the id again. Claude Code and OpenCode delete in place with no mark, and keep one copy of a conversation in one place; here a second process, a channel route and a moved placement can each write an id again |
| Lock files are removable | Every acquisition checks, after locking, that the path still names the file it locked, and opens the path again when it does not. Without that check a removed lock file gives two holders, which is why the files used to stay |
| File history lives as long as its writers | Claude Code keeps file history per conversation and removes it with the transcript. OpenCode keeps one snapshot repository per project and prunes by age. A repository shared by a directory cannot drop one conversation's commits, since the others' diffs are read from the same history, so it goes with its last writer |

## Main project binding

1. **Draft** composer chip, nothing sent
2. **First frame** carries project_id
3. **handle_chat** creates with project
4. **Frozen** chat_ack labels, indexes the binding

- **Main directory**: The project's path. Conversations sit under application state by stable project id, so a path change touches neither binding nor repository. [Additional directories](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/session/additional-working-directories.html) stay editable.
- **Draft state**: Held in `pendingProjectsByChat[chatKey]` until `chat_ack`; that send of `set_session_project` is idempotent
- **Settings-only repository**: Can exist before creation without an `id`. `handle_chat` asks `is_created` (metadata `id`, or history); `create_session` moves it to the project's placement, keeping settings.
- **After the first turn**: `set_session_project` accepts only the current project, else `project is frozen after the first turn` (`FROZEN_ERROR`). The chip is read-only with a session id.

|  | Move to another project | Repair a missing directory |
| --- | --- | --- |
| User | Drags a chat row onto a project, or **Move to project** | Folder moved or renamed on disk, then picks it again |
| Action | `move_session_to_project {session_id, project_id}` | `relocate_project {session_id, project_id, path}` |
| Changes | The session's project. `SessionStore.move_session`, under session locks: cached repository dropped; `projects/<old>/chats/<id>` and `.file-recovery/<id>` renamed to `projects/<new>/chats/`; location recorded, registry rebound, `meta.project_id` set; old project appended to `meta.project_history` | The project's path, never the binding, so legal after the freeze. `project_store.relocate_project` validates, rewrites the path, keeps the id. |
| Refused | While a turn runs (`RUNNING_ERROR`); destination exists; folder [held by another program](#held-folder). Same project: no change, no node. | Default project: its display path returns to home on every `get_default_project` read, and it has no project Git repository |
| Reply | `projects_changed` to every client first, then `session_moved {ok, from_project_id, project_id, node_id}` and a fresh `projects_list` to the requester | `projects_changed` to every client first, then `project_relocated {ok, old_path, path, node_id}` and a fresh `projects_list` to the requester |
| Node `name` | `project/move`, by `record_move` | `project/relocate`, by `record_relocate` |
| `output` | Old project name → new project name | Old path → new path |
| `metadata` | `old_project_id`, `new_project_id` | `display: "runtime"`, `project_id`, `old_path`, `new_path` |

Both nodes: `role` `code`, `caller` `ROOT`, `predecessor` `None`; shape of `context/system_prompt`; code in `state/store/project/relocate_node.py`. `caller` keeps head where it is. Not under `context/`, hidden from the transcript: this is a user action worth seeing.

### A held conversation folder

Windows refuses to rename a folder while any file inside it is open. The Worker keeps none open between writes, so the holder is a reader in another process, an indexer, an antivirus scan, or a command running in the work folder. `move_session_folder` retries for one second, then raises `SessionFolderBusy`. A folder is never copied instead.

| Rename | When the folder stays held |
| --- | --- |
| Move to another project | `session_moved` carries `ok: false` and the error; folder, recovery tree, binding and turns are unchanged. If the recovery tree is the held one, the conversation is renamed back first |
| Binding a draft | `set_session_project`: the binding changes and the folder stays, recorded in the location map. First message: the create fails and the draft keeps its settings |
| Startup quarantine | The shell stays and the empty quarantine entry is removed |
| Publishing a migrated copy | The journal row is `failed` with the error; the source is untouched, and the next run publishes the verified copy |

If the conversation cannot be renamed back either, the location map names its new folder so it stays readable, and the error names both folders. Moving it to the same project again finishes the move: the recovery tree joins the conversation, then the binding changes.

Archiving sets a field and deleting removes files in place; neither renames a folder. A conversation id never changes.

| After | Effect |
| --- | --- |
| Next turn after a move | New project's path: `project_workdir_for` resolves fresh every call |
| Memory after a move | `project_layer.left_workspace_ids` maps `project_history` to workspaces; `write_target` counts turns they marked, so the new project's memory takes only what follows. The home project works the same with the personal workspace. |
| Settings after a move | Each branch's Agent, model and permission mode travel with the metadata; project defaults (`settings.json`) come from the new project |
| Directory missing | `project_workdir_for` returns `None`, never the default project's home. New bound work blocked while missing, replaced, pending, migrating or unavailable. The session stays readable; the UI gets location state and missing path. |

**Following a folder move automatically**

| Mechanism | Rule |
| --- | --- |
| Identity | The stable id; the path is an attribute. Codex matches recorded cwd against recent turn context, DeepSeek validates against an immutable session header cwd; neither tracks arbitrary folder moves. |
| Native identity | On startup, access, volume reconnect, or a directory or ancestor event, resolve a stored bookmark or inode; a match updates the path. No walk of HOME. |
| Application-owned placement | `projects/<project-id>/chats/<session-id>/`: relocating moves no chat files. Legacy copies migrate through a journal. Undo recovery stays in the sibling `.file-recovery/<session_id>/<turn>/`. |
| No auto-adoption | Names, Git remotes, contents and leftover `.openprogram/sessions` prove nothing |
| **Locate folder** | May replace identity after showing the expected old path and revision. Refuses a destination owned by another project, unless the located project is missing with no conversations: then it folds into the owner, which the picker selects. |
| Surfaces | The draft picker lists `path_missing` projects (a click opens the locate flow); `/projects` shows the warning with "Locate folder…" |
| Not a shell | A project-bound session with an unreachable location or unsettled journal |

**Attachments and migration**

| Item | Rule |
| --- | --- |
| Browser uploads | Decoded and saved before dispatch under `<session directory>/workdir/attachments/`; the path goes in the user message marker |
| IndexedDB | Only unsent composer drafts; cleared after publication |
| Legacy migration | Inventories any external recovery tree, copies session and recovery data under `<state>/projects/.migration/staging/`, verifies, publishes to `projects/<project_id>/chats/<session_id>/` and its sibling `.file-recovery`, then updates the location authority. A failed publication keeps the project non-available. |
| Old markers | [The storage rule](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/session/storage.html#cache-and-attachments) |

## A place in the project list

- **Written by**: `update_session_flags` with `sort_at` (seconds), stored with `sort_since` (its `updated_at` then). `sort_at` 0 clears both.
- **Picked by the client**: A time between the neighbours, or now at the top
- **Holds until**: `updated_at` passes `sort_since`: its own next turn. Others' activity can still pass it.

## When status is written

| Moment | Value |
| --- | --- |
| Turn start | `running` |
| Turn ends | `done`; `unread` unless on screen (a quiet turn leaves the dot) |
| Turn fails | `failed`; `unread` unless on screen |
| Cancelled, nothing else running | `idle` |
| Background turn | Not written |

Clients also accept `needs_input` (amber dot); the server does not write it to the session.

## Naming

One implementation, `turn_runtime/titles.py`: WS, fn-form, channel, CLI and spawn all reach `finalize_turn end → _maybe_auto_title`. Channels add only a brand logo in the sidebar, chats page and command palette.

| Marker | Meaning | Set by |
| --- | --- | --- |
| `_user_titled` | The user typed it: permanent lock | Only rename: set for a typed name, cleared for a generated one |
| `_auto_titled` | An automatic title exists: do not truncate again. Apart from the lock, since truncation is expected to be superseded. | `_maybe_auto_title`, rename for a generated name |
| `_title_gen_count` | Which `_RETITLE_AT_TURNS` entry was hit | Internal to `_maybe_auto_title` |

| Case | Rule |
| --- | --- |
| When | Replies 1, 6, 16, 40; also 2, 3 when the first user message is small talk. Never with `_user_titled`. |
| Reply 1, at once | `_title_from_text(first user message)`: markers stripped, first line, 50 characters + "…"; `_auto_titled=True`, `_title_gen_count=1` |
| Then, in the background | LLM title over the noted title, `_title_gen_count=N+1`, broadcast `session_updated`. Gives up if `_user_titled` appeared or the title changed. |
| Excerpt | `build_title_context(get_branch(id))`, within 1,000 characters (`2 × _MAX_INPUT_CHARS`). User text and each turn's final assistant text; no tool records, attachment markers or `<think>`. |
| Small talk | Greeting, thanks, acknowledgement, or one or two characters such as `hl`. Opening small-talk turns drop with their replies; a later low-content message drops, its reply stays. All small talk: everything stays. |
| Always included | First substantive turn and latest turn. Others fill newest first; `…` marks a gap. |
| Typed rename | `update_session(title, _user_titled=True)` |
| **Auto rename** (empty title) | `_llm_rename()` → `_user_titled=False`, `_auto_titled=True`, `_title_gen_count=max(1, N)`. If the title or lock changed meanwhile: `superseded`, not written. |

[LLM title generation](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/session/name.html)
