# Entity memory on Git

Deferred proposal. Entity memory is an immutable record of what happened, traceable step by step: Session-Git stores what was said, Project-Git what was changed. The active Memory is the Source, Topic and Core workspace in [Overview](https://fzkuji.github.io/OpenProgram/docs/reference/design/memory/overview.html); current persistence is in [Session storage](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/session/storage.html).

|  | Proposed | Built today |
| --- | --- | --- |
| Session record | One Git repository per conversation, one commit per turn | No repository. `<state>/projects/<project-id>/chats/<session-id>/main.jsonl`; `commit_turn` makes the session's fields durable. |
| Valid session | `meta.json` exists and parses | `main.jsonl` or `agents/` exists |
| Location index | `locations.json` | `.chats-locations.json` at the store root, beside `.chats-index.json` |
| Agent file history | Commits in the user's repository | Shadow Git at `~/.openprogram/shadow-git/<project-hash>/`, leaving the user's `.git` alone. Project-Git auto-commit exists but is deprecated and off by default. |
| Dirty tree | Skip when the tree was not clean before the agent | Baseline of dirty paths at turn start; refuse with a `project_commit_skipped` notice if those changes remain |
| Project registry, panel, chat indicator | As below | Built: `projects.json`, WS `list_projects` and `create_project`, Projects in the sidebar |
| Replay UI, session Git WS actions, backfill | As below | Not built |

## Storage layout

```
~/.openprogram/                        get_state_dir()
├── sessions/
│   ├── <session_id>/                  one Session-Git repository
│   │   ├── .git/
│   │   ├── meta.json                  title, agent_id, project_id, created_at
│   │   ├── history/                   DAG node files
│   │   │   ├── 000001-u-<id>.json     user message
│   │   │   ├── 000002-a-<id>.json     assistant message
│   │   │   └── 000003-t-<id>.json     tool result, called_by = assistant
│   │   ├── context/commits/<commit_id>.json   per-turn LLM context view
│   │   └── workdir/                   temporary working directory
│   └── locations.json                 in-project session to real path
├── projects/projects.json             project registry
└── memory/                            abstract memory

<user working directory>/
├── .git/                              Project-Git, reused or initialized
└── .openprogram/sessions/<id>/        session repository bound to this project
```

## Session-Git lifecycle

| Stage | Proposal |
| --- | --- |
| Create | Lazily on the first message (`SessionStore._open(id, create_if_missing=True)`): `git init`, write `meta.json`, create `history/`, `context/`, `workdir/`. A working directory binds the real project and places the repository inside it; otherwise `project_id="default"` at the home root. |
| Validity | Directory exists and `meta.json` parses as JSON. Anything else (test leftovers, unrelated directories, corruption) is skipped silently. |
| Discovery | Scan every `<state>/projects/<project_id>/chats/` plus the location index; merge, deduplicate, sort by `updated_at` descending. Sidebar and Chats page share the rule. |
| Write | `append_message` writes `history/NNNN-<role>-<id>.json` synchronously and updates the in-memory index; `commit_turn` commits once at turn end. |
| Read | `get_branch(session_id, head_id)` walks `parent_id` to a message list; `get_nodes` returns raw `Call` objects; `session_commits` returns the turn-level log. |
| Branch, retry | DAG retry is git branch `retry-<assistant_id>`; switching DAG head is git checkout. |
| Metadata, binding | `update_session(session_id, title=..., project_id=...)` writes `meta.json` and the index. `project_id` holds the binding. |
| Cache | In-memory LRU of `SessionLog` and `SessionMemoryIndex`, cap 256 (`OPENPROGRAM_SESSION_CACHE_CAP`), rebuilt from disk after eviction; per-session lock plus store lock. |
| Delete | `delete_session`: drop from cache, close the runtime, remove the directory including `.git/` and any location entry. Sidebar menu; Chats page right-click not yet. Provenance pointers dangle and are skipped on query, so the virtual layer needs no cleanup. |
| Garbage collection | Without `meta.json`: skipped. Empty with a default title: listed. Long-inactive: never deleted automatically; any space policy belongs to user configuration, not the store. |

### Turn commits

One commit when `dispatcher.process_user_turn()` returns a `TurnResult`: one user message, one assistant message, N tool results.

```
turn <N>: <first 60 chars of user msg>

assistant: <first 80 chars of reply>
tools: read, grep × 3, list

[meta: turn took 12.3s, 18 tools, 4521 tokens]
```

### Replay

```
[← prev turn]  Turn 7 / 12  [next turn →]    [view full history]
```

| Control | Action |
| --- | --- |
| prev | `git checkout HEAD~1`, replay the UI |
| next | Walk the reflog backward |
| view full history | Timeline, one line per commit; click for message content |
| WS | `git_history(session_id)`, `git_checkout(session_id, commit_sha)`. The dispatcher continues the next message on that commit. |

### Dual write

The dispatcher writes the DAG. After a turn, its nodes are serialized to the repository on a background thread, because a commit takes about 100 to 500 ms. One repository per session and serial commits make conflicts rare; a file lock is the fallback. On startup, sessions without a repository are backfilled once, turn by turn in `seq` order.

## Project-Git lifecycle

| Stage | Proposal |
| --- | --- |
| Create | `resolve_project(path, name)` when a directory is bound: reuse `.git/` or `git init`, register in `projects.json`. |
| Auto-commit | At turn end for a bound session whose agent changed files, committed under an agent `user.name` so it differs from the user's commits. A clean start alone does not prove ownership when the user edits concurrently, so agent-owned changes must be identified. |
| Read | `ProjectGit.log(limit)`; `project_commits(project_id)` for the provenance layer. |
| Unbind | Removes the registration only. The user's `.git/` stays; the session's `project_id` stays as a historical pointer; the session repository stays in the project. |

```
git commit -c user.name="agent (<model> via OpenProgram)"
           -m "[agent <session_id>] turn <N>: <user msg first 60 chars>"
```

**Built auto-commit, off by default**

| Item | Behaviour |
| --- | --- |
| Enable | `project_auto_commit` in `config.json` or `OPENPROGRAM_PROJECT_AUTOCOMMIT=1` |
| Message | `[agent <first 8 of session id>] <first 60 chars of the user's first line>` |
| Not a repository | At turn start: a baseline commit of the existing files, so agent commits are honest diffs. Refused with a notice if a dependency or build directory such as `node_modules` or `.venv` would bloat it. |
| Active worktree | Yields; the worktree has its own merge and discard lifecycle. |
| Home project | No-op; it has no bound directory. |

## Project metadata and presentation

A session may have no project. With one, its agent's file commits land in the project repository, and the session's metadata carries `project_id`.

```
Project: id, name, workdir, sessions, status (active | paused | done), created_at
```

| Surface | Content |
| --- | --- |
| Projects section, left sidebar | Name, session count, status, New Project |
| Project page | Name, workdir, sessions, commit history, abstract-memory entry |
| New project | Pick a directory, name it, create or reuse a repository, optionally associate the current session |
| Top of chat | Project name and abbreviated workdir, linking to the project page |

## Key invariants

- The DAG is the source of truth; Git is the mirror. A Git failure does not affect the DAG. A commit without a DAG write is dirty data.
- One Session-Git commit per turn, not per message.
- The agent never pollutes the user's working tree: with uncommitted user changes, it skips the commit.
- Replay is a read-only view; a new message after checkout forks the DAG from that commit.
- Abstract memory builds on entity memory, never the reverse.

### Project registry safety (built)

The worker, CLI and agent subprocesses all write `projects.json`.

| Case | Handling |
| --- | --- |
| Read-modify-write | Held under the cross-process lock `<state>/projects/.locks/.projects-registry.lock` |
| Publish | Unique temporary file, then rename; readers see the old or new file whole |
| Read error | Raises, because an empty result would be written back and erase every binding |
| Not a JSON object | Moved aside as `projects.json.unreadable-<time>-<id>`; the registry restarts empty |

## Risks

| Risk | Mitigation |
| --- | --- |
| Async commit fails unseen | Background retry; on startup compare DAG `seq` with commit count and backfill on mismatch |
| Workdir is not a repository | `git init` on the agent's first commit; reuse an existing one |
| Several sessions edit one project | File lock serializes project commits; at worst a queue |
| Going back to turn 5 and sending a message | Fork, not overwrite: the DAG's retry, mapped to a Git branch |

## Relationships

| With | Relationship |
| --- | --- |
| Commit chain | No conflict. DAG nodes mirror to Git commits, the history that happened. The ContextCommit chain, what the LLM saw, stays out of Git as derived and recomputable; a commit may be exported on request. |
| Abstract memory | Entity memory is its single source. Distillation reads Session-Git nodes and Project-Git commits into the timeline and graph. Each memory carries a `Provenance` pointer back; see [Virtual memory](https://fzkuji.github.io/OpenProgram/docs/reference/design/memory/virtual-memory.html). |
| External tools | This proposal exposes Git log and diff history. Any feature comparison with another tool must be verified before it informs implementation. |

```
@dataclass
class Provenance:
    project_id: str
    session_id: str
    node_ids: tuple[str, ...]
    commit: str | None
    event_time: float
    ingestion_time: float
```

## Session titles (built)

| Priority | Rule |
| --- | --- |
| 1. Typed name | `/rename` or the UI. Never overwritten. "Generate a name" clears the lock, so later retitles can still improve it. |
| 2. Model title | Background call for 3 to 7 words, sentence case, in the conversation's language, up to 80 characters, through structured output. Runs at turns 1, 6, 16 and 40, and at 2 and 3 after a small-talk opener. Input is an excerpt of the current branch, at most 1000 characters. Failures are logged only. A retitle replaces only the title it started from; the sidebar updates through `session_updated`. |
| 3. Excerpt | Set immediately at the first turn: first line of the first user message, 50 characters, so the sidebar is never empty while the model works. |
| 4. Preview | At listing time, a session with no usable title shows a preview of its first user message. |

All valid sessions are listed; there is no empty-placeholder filter.

**Proposed build order**

1. Session-Git: `openprogram/state/memory/session_git/` (init, commit, log, checkout), a background commit at the end of `dispatcher.process_user_turn`, a backfill script, WS `git_session_log` and `git_session_checkout`.
2. Project schema and UI: registry, `project_id` in session metadata, WS `list_projects`, `create_project`, `add_session_to_project`, Projects in the sidebar.
3. Project-Git auto-commit: post-turn hook for bound sessions, commit when clean, warn when dirty, a warning banner.
4. Replay UI: prev and next at the top of chat, timeline view, WS action calling checkout.
5. Data migration: backfill existing sessions; import existing Git projects as Projects.
