Skip to main content
Glama
README.md
# TimeReverse

[![Release](https://img.shields.io/github/v/release/964nbtrkhb-eng/TimeReverse)](https://github.com/964nbtrkhb-eng/TimeReverse/releases/latest)
[![Tests](https://github.com/964nbtrkhb-eng/TimeReverse/actions/workflows/test.yml/badge.svg)](https://github.com/964nbtrkhb-eng/TimeReverse/actions/workflows/test.yml)
[![Python](https://img.shields.io/badge/Python-3.11%2B-blue)](https://www.python.org/)
[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)

## Codex забыл старый чат? Новый чат продолжит работу без повторных объяснений.

TimeReverse сохраняет решения, задачи, ограничения и состояние вашего проекта локально, а затем передаёт их новому чату Codex через MCP.

> **Не пересказывайте проект заново.** Сохраните контекст один раз — и продолжайте работу в следующем чате.

| Без TimeReverse | С TimeReverse |
|---|---|
| Новый чат ничего не знает | Новый чат получает компактное состояние проекта |
| Вы повторяете архитектуру и прошлые решения | Решения и ограничения уже перечислены |
| Неудачные попытки повторяются | Агент видит, что уже пробовали и почему отказались |
| История остаётся внутри одного чата | Контекст хранится локально и доступен через MCP |

```mermaid
flowchart LR
    A["Старый чат Codex"] --> B["TimeReverse: локальная SQLite-память"]
    B --> C["Проверяемый context pack"]
    C --> D["Новый чат Codex продолжает работу"]
```

### Проверьте результат за 60 секунд

После установки выполните в папке своего проекта:

```powershell
timereverse capture codex
timereverse install codex
```

Откройте новую задачу Codex в той же папке и напишите:

```text
Вызови context_resume и кратко расскажи, что уже известно о проекте.
```

Если новый чат пересказал предыдущую работу — перенос контекста работает.

### Кому пригодится

- Вы ведёте проект в Codex дольше одного чата.
- Часто достигаете лимита контекста или начинаете новую задачу.
- Хотите сохранить архитектурные решения и незаконченные задачи.
- Не хотите повторять неудачные подходы в каждом новом чате.
- Хотите контролировать AI-память локально: просматривать, искать и удалять записи.

### Что работает сейчас

- Автоматический импорт локальных сессий **Codex**.
- Структурированные handoff-пакеты вместо копирования всего чата.
- Проверка фактов по файлам, Git и записанным результатам тестов.
- Независимая память нескольких проектов.
- Checkpoints, сравнение состояний, CLI, MCP и Windows-autostart.
- Локальное хранение без аккаунта TimeReverse и без отправки истории в облако.

### Честные ограничения

- Автоматические импортёры Claude Code, Cursor и Gemini CLI пока не реализованы.
- TimeReverse предназначен прежде всего для coding-agent workflows, а не для обычных бытовых чатов.
- Распознавание упомянутых в тексте путей эвристическое; важные файлы можно указать явно в metadata.
- Пакет пока распространяется через GitHub Release, а не PyPI.

> **English:** TimeReverse is a local, inspectable memory bridge for Codex. It captures project conversations, turns durable facts into compact provenance-aware handoffs, and lets a fresh Codex task continue without re-explaining the project. Start with the [latest release](https://github.com/964nbtrkhb-eng/TimeReverse/releases/latest), install with `pip install -e ".[mcp]"`, then run `timereverse capture codex` and `timereverse install codex`. Codex transcript import is supported today; other agent importers are planned.

> Status: `v0.5.0`. TimeReverse creates compact, provenance-aware handoffs verified against files, Git, and recorded test results. Structured memory, multiple projects, checkpoints, MCP, and Windows automation are included.

TimeReverse keeps an append-only SQLite event log and produces a compact Markdown context pack for a new chat. It does not upload conversations or require an LLM.

## Простое объяснение для новичков

### Что это такое

Представьте, что вы долго работали с Codex в одном чате. Вы обсудили архитектуру, выбрали технологии, исправили ошибки и составили список следующих задач. Затем вы открываете новый чат — и обычно приходится объяснять всё заново.

TimeReverse сохраняет полезную историю проекта на вашем компьютере. Новый чат Codex может прочитать её и продолжить работу с того места, где закончился старый.

```text
Старый чат Codex -> TimeReverse сохраняет контекст -> Новый чат продолжает работу
```

### Что вы получите

- Не нужно заново пересказывать новому чату историю проекта.
- Codex вспомнит предыдущие решения, задачи и ограничения.
- История хранится локально на вашем компьютере, а не в облаке TimeReverse.
- Можно посмотреть, найти или удалить любую сохранённую запись.
- Повторное сохранение не создаёт копии одних и тех же сообщений.
- В Windows история может сохраняться автоматически в фоне.

### Что понадобится

1. Windows, Linux или macOS.
2. Python 3.11 или новее. Скачать его можно с [python.org](https://www.python.org/downloads/). На Windows при установке отметьте **Add Python to PATH**.
3. Установленный Codex.
4. Проект, который вы открываете в Codex.

### Установка без Git

1. Откройте [страницу проекта](https://github.com/964nbtrkhb-eng/TimeReverse).
2. Нажмите зелёную кнопку **Code**.
3. Выберите **Download ZIP**.
4. Распакуйте архив.
5. Откройте распакованную папку, щёлкните по пустому месту правой кнопкой и выберите **Open in Terminal**.
6. Выполните:

```powershell
python -m pip install -e ".[mcp]"
```

Если команда `python` не найдена, попробуйте:

```powershell
py -m pip install -e ".[mcp]"
```

### Первое использование

Откройте терминал в папке своего проекта — не в папке TimeReverse — и выполните:

```powershell
timereverse init
timereverse capture codex
timereverse install codex
```

Закройте текущий чат Codex и откройте новую задачу в той же папке проекта. Напишите:

```text
Вызови context_resume и кратко расскажи, что ты знаешь о проекте.
```

Если Codex пересказал предыдущую работу, всё настроено правильно.

### Автоматическое сохранение в Windows

Сначала установите короткую команду для текущего проекта:

```powershell
timereverse install windows
```

Откройте новое окно PowerShell и включите автозапуск:

```powershell
timereverse install autostart
```

После следующего входа в Windows TimeReverse будет незаметно проверять новые сообщения Codex каждые пять секунд. Отключить автозапуск можно командой:

```powershell
timereverse uninstall autostart
```

### Полезные команды

```powershell
timereverse status                 # сколько записей сохранено
timereverse capture codex          # сохранить последний чат вручную
timereverse search "авторизация"   # найти запись по тексту
timereverse resume                 # показать контекст для нового чата
timereverse forget evt_123         # удалить запись по её ID
timereverse watch codex            # сохранять новые сообщения, пока команда работает
```

TimeReverse automatically finds the nearest project from any nested working directory. The Windows launcher uses the current directory, while autostart watches every registered project.

View or manage the local project registry:

```powershell
timereverse projects list
timereverse projects add C:\work\another-project
timereverse projects remove PROJECT_ID
```

Each project keeps its own `.timereverse/context.db`. A stable ID in `.timereverse/project.json` lets the registry follow a project after its folder is moved or renamed; run `projects add` from the new location to update it.

## Checkpoints

Checkpoints preserve the active structured context at a named moment without changing the append-only event history:

```bash
timereverse checkpoint create before-refactor
timereverse checkpoint list
timereverse checkpoint show before-refactor
timereverse checkpoint diff before-refactor after-refactor
```

The diff reports added, removed, and superseded decisions, constraints, and tasks. MCP clients receive equivalent `context_checkpoint`, `context_checkpoints`, `context_checkpoint_resume`, and `context_checkpoint_diff` tools.

## Verifiable handoffs

Store confirmed facts and explicit assumptions separately. File paths mentioned in facts are checked when a handoff is rendered:

```bash
timereverse remember --type fact "src/auth.py implements login"
timereverse remember --type assumption "Users prefer passwordless login"
timereverse test python -m unittest discover -s tests -v
timereverse resume --budget 6000
```

Each item is labeled `verified`, `unverified`, `assumption`, or `stale`. Missing referenced files are shown. The handoff header records the Git branch, commit, and whether the working tree is dirty. Test output is capped before local storage; complete tool output is never added to the context pack.

Diagnose the project database, schema, registry, and Git integration:

```bash
timereverse doctor
```

Codex/MCP clients also receive `context_record_test` and `context_doctor`.

## Upgrading

Install the newer package and run any TimeReverse command in the project. SQLite schema migrations run automatically and preserve the append-only event journal. Back up `.timereverse/` before downgrading; older versions intentionally refuse databases with a newer schema.

## Quick install for experienced users

```bash
git clone https://github.com/964nbtrkhb-eng/TimeReverse.git
cd TimeReverse
pip install -e ".[mcp]"
timereverse init
```

Save only information worth carrying forward:

```bash
timereverse remember --type decision "Use SQLite, not a vector database"
timereverse remember --type objective "Ship a local-first context handoff"
timereverse remember --type task "Add a Claude Code transcript importer"
timereverse resume
timereverse search "SQLite"
timereverse status
```

Every search result includes its event ID. Delete a private or incorrect item with `timereverse forget evt_...`.

`resume` returns structured facts by default and leaves raw chat out. Every item includes its source, timestamp, and event ID. Use `--budget 6000` to cap the context pack or `--include-messages` when a raw transcript is explicitly needed. Replace a stale fact without deleting history:

```bash
timereverse remember --type decision --supersedes evt_old "Use SQLite"
```

Capture the newest Codex task that belongs to the current project:

```bash
timereverse capture codex
timereverse resume --output handoff.md
```

Or keep TimeReverse running while you work and capture new messages automatically:

```bash
timereverse watch codex
```

The watcher polls the local append-only Codex journal every five seconds and relies on deterministic IDs, so repeated scans do not duplicate messages. Stop it with `Ctrl+C`.

Start the watcher silently whenever you sign in to Windows:

```powershell
timereverse install autostart
```

Disable it with `timereverse uninstall autostart`. Installation only creates `TimeReverse.vbs` in the current user's Startup folder; it does not require administrator rights.

TimeReverse reads Codex rollout JSONL files from `CODEX_HOME/sessions` (normally `~/.codex/sessions`). It imports user messages and final answers, while excluding hidden instructions, reasoning, token telemetry, and tool output. Use `--file path/to/rollout.jsonl` to select a specific task.

Import normalized JSONL (safe to repeat; event IDs are deterministic):

```json
{"type":"decision","content":"Keep all data local","source":"claude-code","session":"abc"}
{"type":"blocker","content":"Codex transcript format is not yet stable","source":"codex"}
```

```bash
timereverse import events.jsonl
timereverse export --output handoff.md
```

## MCP

```bash
pip install -e ".[mcp]"
timereverse-mcp
```

Configure that stdio command in Claude Code, Codex, Cursor, or another MCP host. It exposes `context_remember`, `context_resume`, `context_search`, and `context_forget`.

For Codex, install the project MCP configuration and durable instructions automatically:

```bash
pip install -e ".[mcp]"
timereverse install codex
```

This updates only TimeReverse-managed blocks in `.codex/config.toml` and `AGENTS.md`. Restart Codex or open a new task afterward.

On Windows, install a short command that works from any new PowerShell window:

```powershell
python -m timereverse --path C:\path\to\project install windows
timereverse status
```

The launcher discovers the project from the current directory and adds `%LOCALAPPDATA%\TimeReverse\bin` to the current user's `PATH` without administrator rights.

## Data

Project state lives in `.timereverse/context.db`. Add `.timereverse/` to `.gitignore` when chat context must stay private.

## Scope

The MVP supports local Codex rollout journals. Other MCP clients can read and write TimeReverse memory, but provider-specific transcript importers for Claude and other agents are not implemented yet.

It intentionally has no cloud sync, embeddings, web UI, accounts, or automatic upload. Provider-specific importers can normalize exported transcripts into the documented JSONL format.

## Privacy and security

- All context is stored locally in `.timereverse/context.db`.
- Codex capture excludes hidden instructions, reasoning, token telemetry, and tool output.
- `.timereverse/` is ignored by Git by default.
- Review memories with `search` or `resume` before sharing them.
- Delete individual records with `forget`; delete `.timereverse/` to erase the project database.

See [SECURITY.md](SECURITY.md) for reporting vulnerabilities.

## Development

```bash
python -m unittest discover -s tests -v
python -m pip wheel . --no-deps
```

See [CONTRIBUTING.md](CONTRIBUTING.md) before opening a pull request.