diff --git a/README.md b/README.md
index f35c6c8..e05ab84 100644
--- a/README.md
+++ b/README.md
@@ -1,22 +1,49 @@
+
+
# EpochSim
-Deterministic tick simulation engine for .NET 10.
+**A deterministic tick simulation engine for .NET 10.**
+Run a simulation from a seed, record fingerprints and events, then verify, replay and bisect any run.
+
+**English** · [Русский](README.ru.md)
+
+[](https://www.nuget.org/packages/EpochSim)
+[](https://github.com/Echways/EpochSim/actions/workflows/ci.yml)
+[](LICENSE)
+
+
+
+## Why EpochSim
-Recommended package for embedding:
+A simulation that cannot be reproduced cannot be debugged. EpochSim fixes the inputs of every tick, so the same seed and the same commands always produce the same state, and a divergence can be located to a single tick.
+
+- **Deterministic by construction.** A run is defined by its state, seed and ordered input. Systems execute in a fixed order on one simulation thread.
+- **Run presets.** `QuickRun`, `RecommendedRun` and `DebugRun` cover smoke tests, production diagnostics and strict invariant hunting with one call.
+- **Artifacts for every run.** Manifest, per-tick state fingerprints and an optional event log are written to disk and readable from code.
+- **Replay and bisect.** Verify a run against its recorded fingerprints and find the first tick where two runs diverge.
+- **Deterministic input.** `CommandInbox` and `ScheduledCommandInbox` feed commands from HTTP, UI or queues in a stable order.
+- **Long-lived sessions.** `SimulationSession` supports games, servers and interactive stepping.
+- **A CLI for the whole workflow.** Run, list, inspect, validate, replay, bisect and reproduce runs from the terminal.
+
+## Installation
```bash
dotnet add package EpochSim
```
-`EpochSim.All` is useful when you want one dependency that brings the full module graph (`EpochSim`, `Execution`, `Serialization`, `Observability`, `Kernel`):
+Requires .NET 10. `EpochSim.All` brings the full module graph (`EpochSim`, `Execution`, `Serialization`, `Observability`, `Kernel`) as a single dependency:
```bash
dotnet add package EpochSim.All
```
-Russian version: [README.ru.md](README.ru.md)
+The command-line tool is installed separately:
+
+```bash
+dotnet tool install --global EpochSim.Cli
+```
-## State-Only Quickstart (No Events, No Codecs)
+## Quick start
```csharp
using EpochSim;
@@ -36,46 +63,37 @@ public sealed class WorldState
}
```
-> **Note**: always call `run.RunTicks(engine, ...)` — not `engine.RunTicks(state, ...)` — to avoid
-> silently passing a different state instance than the one the run scope was built with.
+Always call `run.RunTicks(engine, ...)` rather than `engine.RunTicks(state, ...)`, so the state passed in is the one the run scope was built with.
-This is the fastest path: useful artifacts, deterministic run, almost zero wiring.
+More in [Embedding](docs/en/embedding.md).
-## Preset Cost Table
+## Run presets
-| Preset | Fingerprint cadence | Mutation guard | Typical use |
-|---|---|---|---|
-| `QuickRun` | every tick | ✗ | First use, CI smoke test |
-| `RecommendedRun` | every 50 ticks | ✗ | Production debugging |
-| `DebugRun` | every tick | ✓ | Invariant hunting, strict mode |
+| Preset | Fingerprint cadence | Mutation guard | Typical use |
+| ---------------- | ------------------- | -------------- | ------------------------------ |
+| `QuickRun` | every tick | No | First use, CI smoke test |
+| `RecommendedRun` | every 50 ticks | No | Production diagnostics |
+| `DebugRun` | every tick | Yes | Invariant hunting, strict mode |
-**Mutation guard** serialises state before and after each system tick and throws
-`InvalidOperationException` if the fingerprint changes. Useful for finding systems that
-mutate state outside of event handlers, but has significant serialisation overhead — keep
-it in `DebugRun` only.
+The mutation guard serializes state before and after each system and throws `InvalidOperationException` when the fingerprint changes. It finds systems that mutate state outside event handlers, at a significant serialization cost: use it in `DebugRun` only.
```csharp
-// QuickRun — zero-config, no codec needed
-using var run = Epoch.QuickRun(state, rootDir: "artifacts");
-run.RunTicks(engine, seed: 1, endTickInclusive: 100);
+using var quick = Epoch.QuickRun(state, rootDir: "artifacts");
+quick.RunTicks(engine, seed: 1, endTickInclusive: 100);
-// RecommendedRun — adds profiling + failure artifacts
-using var run = Epoch.RecommendedRun(state, rootDir: "artifacts");
-run.RunTicks(engine, seed: 1, endTickInclusive: 1000);
+using var recommended = Epoch.RecommendedRun(state, rootDir: "artifacts");
+recommended.RunTicks(engine, seed: 1, endTickInclusive: 1000);
-// DebugRun — every-tick fingerprinting + mutation guard
var serializer = Epoch.JsonStateSerializer();
-using var run = Epoch.DebugRun(state, serializer, rootDir: "artifacts");
-run.RunTicks(engine, seed: 1, endTickInclusive: 200);
+using var debug = Epoch.DebugRun(state, serializer, rootDir: "artifacts");
+debug.RunTicks(engine, seed: 1, endTickInclusive: 200);
```
-Advanced overloads stay available when you want full control:
-- `Epoch.RecommendedRun(state, codec, serializer, rootDir, invariants)`
-- `EpochSimRun.For(state)...Build()`
+For full control use `Epoch.RecommendedRun(state, codec, serializer, rootDir, invariants)` or `EpochSimRun.For(state)...Build()`.
-## Event Log / Replay (Use When You Need Replay/Bisect)
+## Event log and replay
-Event log is optional and intended for replay workflows (`verify-run`, `bisect`, `fast-replay`).
+The event log is optional and required for `verify-run`, `bisect` and `fast-replay`.
```csharp
using EpochSim;
@@ -85,30 +103,20 @@ var codec = Epoch.JsonCodecFromAssembly(t => t == typeof(Changed));
var serializer = Epoch.JsonStateSerializer();
using var run = Epoch.RecommendedRun(state, codec, serializer, rootDir: "artifacts");
-```
-```csharp
[MessageKind("Changed")]
public sealed record Changed(int Delta) : IEvent;
```
-## Reading Artifacts In-Process
+## Reading artifacts
-After a run completes you can read artifacts directly from the run paths without going
-through the CLI:
+Artifacts are plain files in the run directory and can be read in-process:
```csharp
using EpochSim;
using EpochSim.Execution.RunArtifacts;
using EpochSim.Execution.StateFingerprint;
-using EpochSim.Serialization.EventLog; // EventLogReader, EventLogEntryV2
-using EpochSim.Serialization.State;
-
-var state = new WorldState();
-var serializer = Epoch.JsonStateSerializer();
-var codec = Epoch.JsonCodecFromAssembly(t => t == typeof(Changed));
-var engine = Epoch.CreateEngine();
-engine.AddSystem("World", tick: ctx => ctx.State.Population++);
+using EpochSim.Serialization.EventLog;
string runDir;
using (var run = Epoch.RecommendedRun(state, codec, serializer, rootDir: "artifacts"))
@@ -117,28 +125,18 @@ using (var run = Epoch.RecommendedRun(state, codec, serializer, rootDir: "artifa
runDir = run.Paths.RunDir;
}
-// Read the manifest written by Dispose()
var manifest = RunManifestReader.TryRead(Path.Combine(runDir, "manifest.json"));
-Console.WriteLine($"EndTick={manifest?.EndTick}");
-
-// Read per-tick fingerprints
var fingerprints = JsonlStateFingerprintWriter.ReadAll(Path.Combine(runDir, "statefp.jsonl"));
-Console.WriteLine($"Fingerprints recorded: {fingerprints.Count}");
-
-// Read event log entries
var entries = EventLogReader.ReadAll(Path.Combine(runDir, "events.jsonl"));
-Console.WriteLine($"Events logged: {entries.Count}");
+
+Console.WriteLine($"EndTick={manifest?.EndTick}, fingerprints={fingerprints.Count}, events={entries.Count}");
```
-## RunTicks vs Session
+Layout and formats are described in [Artifacts](docs/en/artifacts.md).
-Use `RunTicks` for batch jobs:
+## Sessions and external input
-```csharp
-run.RunTicks(engine, seed: 1, endTickInclusive: 1000);
-```
-
-Use `SimulationSession` for long-lived loops (games, servers, interactive stepping):
+`RunTicks` fits batch jobs. `SimulationSession` fits long-lived loops:
```csharp
var inbox = new CommandInbox();
@@ -148,22 +146,15 @@ using var session = engine.CreateSession(state, seed: 1, startTick: 0);
inbox.Enqueue(new AddPopulation(5));
session.TickOnce();
session.RunUntil(100);
-```
-```csharp
-using EpochSim.Kernel.Messaging;
[MessageKind("AddPopulation")]
public sealed record AddPopulation(int Delta) : ICommand;
```
-## External Input Pattern (HTTP/UI/Queue -> Sim)
-
-Use inboxes to feed external commands deterministically into the sim thread:
+Inboxes feed external commands into the simulation thread deterministically:
- `CommandInbox`: commands for the next tick.
-- `ScheduledCommandInbox`: commands scheduled at a specific tick with stable ordering:
- - primary key: tick ascending
- - secondary key: insertion order
+- `ScheduledCommandInbox`: commands for a specific tick, ordered by tick ascending, then by insertion order.
```csharp
var scheduled = new ScheduledCommandInbox();
@@ -174,54 +165,64 @@ scheduled.Enqueue(10, new AddPopulation(7));
scheduled.Enqueue(12, new AddPopulation(1));
```
-See full integration recipes: [Embedding](docs/Embedding.md)
-
-## CLI Onboarding
+More in [Sessions](docs/en/sessions.md).
-Create a starter app:
+## Command line
```bash
-dotnet run --project src/EpochSim.Cli -- init .
-```
-
-Run and inspect artifacts:
-
-```bash
-dotnet run --project src/EpochSim.Cli -- run artifacts
-dotnet run --project src/EpochSim.Cli -- list-runs artifacts
-dotnet run --project src/EpochSim.Cli -- inspect-run artifacts
+epochsim init .
+epochsim run artifacts
+epochsim list-runs artifacts
+epochsim inspect-run artifacts
```
Determinism debugging:
```bash
-dotnet run --project src/EpochSim.Cli -- verify-run artifacts
-dotnet run --project src/EpochSim.Cli -- bisect artifacts
+epochsim verify-run artifacts
+epochsim bisect artifacts
```
+| Command | Purpose |
+| -------------------------------------------------- | ------------------------------------------ |
+| `init`, `run` | Create a starter app, run it |
+| `list-runs`, `inspect-run`, `pretty-inspect` | Browse and inspect recorded runs |
+| `validate-run`, `verify-run` | Check artifacts and fingerprints |
+| `fast-replay`, `bisect`, `repro` | Replay a run, find the first divergence |
+| `event-stats`, `timeline`, `list-adapters` | Analyze events and list available adapters |
+
+## What is included
+
+| Area | Highlights |
+| ------------- | ----------------------------------------------------------------------------- |
+| Engine | Ordered systems, seeded runs, tick and session execution. |
+| Presets | `QuickRun`, `RecommendedRun`, `DebugRun`, builder for custom setups. |
+| Input | `CommandInbox`, `ScheduledCommandInbox` with stable ordering. |
+| Artifacts | Manifest, state fingerprints, event log, failure artifacts, profiling. |
+| Serialization | JSON state serializer and message codec discovered from an assembly. |
+| Diagnostics | Mutation guard, invariants, replay verification, bisect. |
+| CLI | `epochsim` .NET tool covering the whole run lifecycle. |
+
+## Documentation
+
+| | |
+| --------------------------------- | ---------------------------------------------------- |
+| [Embedding](docs/en/embedding.md) | Integration recipes: hosts, servers, external input |
+| [Artifacts](docs/en/artifacts.md) | Run directory layout and file formats |
+| [Sessions](docs/en/sessions.md) | Long-lived loops and stepping |
+| [Determinism](docs/en/determinism.md) | Rules that keep runs reproducible |
+
## Samples
-- Recommended simple sample: [QuickstartSample](src/EpochSim.Samples/Quickstart/QuickstartSample.cs)
-- Advanced/legacy domain sample: [Event-heavy diagnostic domain](src/EpochSim.Samples/Population/)
+[QuickstartSample](src/EpochSim.Samples/Quickstart/QuickstartSample.cs) is the minimal starting point. [Population](src/EpochSim.Samples/Population/) is an event-heavy domain with invariants and replay.
-## Build and Test
+## Build and test
```bash
dotnet build EpochSim.slnx -m:1
dotnet test EpochSim.slnx -m:1
```
-## Docs
-
-English:
-- [Embedding](docs/Embedding.md)
-- [Artifacts](docs/Artifacts.md)
-- [Sessions](docs/Sessions.md)
-- [Determinism](docs/Determinism.md)
+## License
-Russian:
-- [README.ru.md](README.ru.md)
-- [Embedding.ru](docs/Embedding.ru.md)
-- [Artifacts.ru](docs/Artifacts.ru.md)
-- [Sessions.ru](docs/Sessions.ru.md)
-- [Determinism.ru](docs/Determinism.ru.md)
+[MIT](LICENSE)
diff --git a/README.ru.md b/README.ru.md
index 71c6ce3..ba599aa 100644
--- a/README.ru.md
+++ b/README.ru.md
@@ -1,22 +1,49 @@
+
+
# EpochSim
-Детерминированный движок тиковых симуляций для .NET 10.
+**Детерминированный движок тиковых симуляций для .NET 10.**
+Запускайте симуляцию по seed, записывайте fingerprint'ы и события, затем проверяйте, воспроизводите и бисектите любой прогон.
+
+[English](README.md) · **Русский**
+
+[](https://www.nuget.org/packages/EpochSim)
+[](https://github.com/Echways/EpochSim/actions/workflows/ci.yml)
+[](LICENSE)
+
+
+
+## Зачем нужен EpochSim
-Рекомендуемый пакет для встраивания:
+Симуляцию, которую нельзя воспроизвести, нельзя отладить. EpochSim фиксирует входы каждого тика: один и тот же seed и те же команды всегда дают то же состояние, а расхождение локализуется до одного тика.
+
+- **Детерминизм по построению.** Прогон определяется состоянием, seed и упорядоченным входом. Системы выполняются в фиксированном порядке в одном потоке симуляции.
+- **Пресеты запуска.** `QuickRun`, `RecommendedRun` и `DebugRun` закрывают smoke-тесты, диагностику в production и строгий поиск нарушений инвариантов одним вызовом.
+- **Артефакты каждого прогона.** Манифест, fingerprint'ы состояния по тикам и необязательный лог событий пишутся на диск и читаются из кода.
+- **Replay и bisect.** Проверка прогона по записанным fingerprint'ам и поиск первого тика, на котором два прогона расходятся.
+- **Детерминированный ввод.** `CommandInbox` и `ScheduledCommandInbox` передают команды из HTTP, UI или очередей в стабильном порядке.
+- **Долгоживущие сессии.** `SimulationSession` для игр, серверов и пошагового режима.
+- **CLI для всего процесса.** Запуск, список, инспекция, валидация, replay, bisect и воспроизведение прогонов из терминала.
+
+## Установка
```bash
dotnet add package EpochSim
```
-`EpochSim.All` полезен, когда нужен полный граф модулей одной зависимостью:
+Требуется .NET 10. `EpochSim.All` приносит весь граф модулей (`EpochSim`, `Execution`, `Serialization`, `Observability`, `Kernel`) одной зависимостью:
```bash
dotnet add package EpochSim.All
```
-English version: [README.md](README.md)
+Утилита командной строки ставится отдельно:
-## Быстрый старт только со State (без Event/Codec)
+```bash
+dotnet tool install --global EpochSim.Cli
+```
+
+## Быстрый старт
```csharp
using EpochSim;
@@ -36,46 +63,37 @@ public sealed class WorldState
}
```
-> **Важно**: всегда вызывайте `run.RunTicks(engine, ...)`, а не `engine.RunTicks(state, ...)` —
-> иначе можно передать другой экземпляр state, чем тот, с которым был создан run scope.
+Всегда вызывайте `run.RunTicks(engine, ...)`, а не `engine.RunTicks(state, ...)`: так передаётся тот же state, с которым создан run scope.
-Это самый быстрый путь: полезные артефакты и детерминированный запуск почти без обвязки.
+Подробнее в [Embedding](docs/ru/embedding.md).
-## Таблица стоимости пресетов
+## Пресеты запуска
-| Пресет | Каденция fingerprint | Mutation guard | Когда использовать |
-|---|---|---|---|
-| `QuickRun` | каждый тик | ✗ | Первый запуск, CI smoke |
-| `RecommendedRun` | каждые 50 тиков | ✗ | Production-отладка |
-| `DebugRun` | каждый тик | ✓ | Поиск инвариантов, строгий режим |
+| Пресет | Каденция fingerprint | Mutation guard | Когда использовать |
+| ---------------- | -------------------- | -------------- | --------------------------------- |
+| `QuickRun` | каждый тик | Нет | Первый запуск, CI smoke |
+| `RecommendedRun` | каждые 50 тиков | Нет | Диагностика в production |
+| `DebugRun` | каждый тик | Да | Поиск инвариантов, строгий режим |
-**Mutation guard** сериализует state до и после каждого тика системы и бросает
-`InvalidOperationException` при изменении fingerprint. Полезен для нахождения систем,
-мутирующих state вне event handlers, но имеет значительный overhead по сериализации —
-используйте только в `DebugRun`.
+Mutation guard сериализует state до и после каждой системы и бросает `InvalidOperationException`, если fingerprint изменился. Он находит системы, меняющие state вне обработчиков событий, но заметно замедляет прогон: используйте его только в `DebugRun`.
```csharp
-// QuickRun — без конфигурации, кодек не нужен
-using var run = Epoch.QuickRun(state, rootDir: "artifacts");
-run.RunTicks(engine, seed: 1, endTickInclusive: 100);
+using var quick = Epoch.QuickRun(state, rootDir: "artifacts");
+quick.RunTicks(engine, seed: 1, endTickInclusive: 100);
-// RecommendedRun — добавляет profiling + failure artifacts
-using var run = Epoch.RecommendedRun(state, rootDir: "artifacts");
-run.RunTicks(engine, seed: 1, endTickInclusive: 1000);
+using var recommended = Epoch.RecommendedRun(state, rootDir: "artifacts");
+recommended.RunTicks(engine, seed: 1, endTickInclusive: 1000);
-// DebugRun — fingerprint каждый тик + mutation guard
var serializer = Epoch.JsonStateSerializer();
-using var run = Epoch.DebugRun(state, serializer, rootDir: "artifacts");
-run.RunTicks(engine, seed: 1, endTickInclusive: 200);
+using var debug = Epoch.DebugRun(state, serializer, rootDir: "artifacts");
+debug.RunTicks(engine, seed: 1, endTickInclusive: 200);
```
-Продвинутые варианты:
-- `Epoch.RecommendedRun(state, codec, serializer, rootDir, invariants)`
-- `EpochSimRun.For(state)...Build()`
+Для полного контроля: `Epoch.RecommendedRun(state, codec, serializer, rootDir, invariants)` или `EpochSimRun.For(state)...Build()`.
-## Event log / Replay (когда действительно нужно)
+## Лог событий и replay
-Event log нужен для replay/bisect (`verify-run`, `bisect`, `fast-replay`):
+Лог событий необязателен и нужен для `verify-run`, `bisect` и `fast-replay`.
```csharp
using EpochSim;
@@ -85,29 +103,20 @@ var codec = Epoch.JsonCodecFromAssembly(t => t == typeof(Changed));
var serializer = Epoch.JsonStateSerializer();
using var run = Epoch.RecommendedRun(state, codec, serializer, rootDir: "artifacts");
-```
-```csharp
[MessageKind("Changed")]
public sealed record Changed(int Delta) : IEvent;
```
-## Чтение артефактов из кода
+## Чтение артефактов
-После завершения прогона артефакты можно читать непосредственно из кода, без CLI:
+Артефакты лежат обычными файлами в каталоге прогона и читаются из кода:
```csharp
using EpochSim;
using EpochSim.Execution.RunArtifacts;
using EpochSim.Execution.StateFingerprint;
using EpochSim.Serialization.EventLog;
-using EpochSim.Serialization.State;
-
-var state = new WorldState();
-var serializer = Epoch.JsonStateSerializer();
-var codec = Epoch.JsonCodecFromAssembly(t => t == typeof(Changed));
-var engine = Epoch.CreateEngine();
-engine.AddSystem("World", tick: ctx => ctx.State.Population++);
string runDir;
using (var run = Epoch.RecommendedRun(state, codec, serializer, rootDir: "artifacts"))
@@ -116,28 +125,18 @@ using (var run = Epoch.RecommendedRun(state, codec, serializer, rootDir: "artifa
runDir = run.Paths.RunDir;
}
-// Читаем манифест, записанный при Dispose()
var manifest = RunManifestReader.TryRead(Path.Combine(runDir, "manifest.json"));
-Console.WriteLine($"EndTick={manifest?.EndTick}");
-
-// Читаем per-tick fingerprints
var fingerprints = JsonlStateFingerprintWriter.ReadAll(Path.Combine(runDir, "statefp.jsonl"));
-Console.WriteLine($"Fingerprints recorded: {fingerprints.Count}");
-
-// Читаем лог событий
var entries = EventLogReader.ReadAll(Path.Combine(runDir, "events.jsonl"));
-Console.WriteLine($"Events logged: {entries.Count}");
-```
-## RunTicks и Session
+Console.WriteLine($"EndTick={manifest?.EndTick}, fingerprints={fingerprints.Count}, events={entries.Count}");
+```
-`RunTicks` для batch-прогонов:
+Структура и форматы описаны в [Artifacts](docs/ru/artifacts.md).
-```csharp
-run.RunTicks(engine, seed: 1, endTickInclusive: 1000);
-```
+## Сессии и внешний ввод
-`SimulationSession` для долгоживущих циклов:
+`RunTicks` подходит для batch-прогонов. `SimulationSession` подходит для долгоживущих циклов:
```csharp
var inbox = new CommandInbox();
@@ -147,21 +146,15 @@ using var session = engine.CreateSession(state, seed: 1, startTick: 0);
inbox.Enqueue(new AddPopulation(5));
session.TickOnce();
session.RunUntil(100);
-```
-```csharp
-using EpochSim.Kernel.Messaging;
[MessageKind("AddPopulation")]
public sealed record AddPopulation(int Delta) : ICommand;
```
-## Паттерн внешних входов (HTTP/UI/Queue -> sim)
+Inbox'ы детерминированно передают внешние команды в поток симуляции:
-Используйте inbox’ы для детерминированного ввода команд в тике симуляции:
- `CommandInbox`: команды на ближайший тик.
-- `ScheduledCommandInbox`: команды на заданный тик со стабильным порядком:
- - сначала `tick` по возрастанию;
- - затем порядок добавления.
+- `ScheduledCommandInbox`: команды на заданный тик, порядок: сначала тик по возрастанию, затем порядок добавления.
```csharp
var scheduled = new ScheduledCommandInbox();
@@ -172,27 +165,56 @@ scheduled.Enqueue(10, new AddPopulation(7));
scheduled.Enqueue(12, new AddPopulation(1));
```
-Полные рецепты: [Embedding](docs/Embedding.ru.md)
+Подробнее в [Sessions](docs/ru/sessions.md).
-## CLI старт
+## Командная строка
```bash
-dotnet run --project src/EpochSim.Cli -- init .
-dotnet run --project src/EpochSim.Cli -- run artifacts
-dotnet run --project src/EpochSim.Cli -- list-runs artifacts
+epochsim init .
+epochsim run artifacts
+epochsim list-runs artifacts
+epochsim inspect-run artifacts
```
Отладка детерминизма:
```bash
-dotnet run --project src/EpochSim.Cli -- verify-run artifacts
-dotnet run --project src/EpochSim.Cli -- bisect artifacts
+epochsim verify-run artifacts
+epochsim bisect artifacts
```
+| Команда | Назначение |
+| -------------------------------------------- | ----------------------------------------------- |
+| `init`, `run` | Создать стартовое приложение, запустить его |
+| `list-runs`, `inspect-run`, `pretty-inspect` | Просмотр и инспекция записанных прогонов |
+| `validate-run`, `verify-run` | Проверка артефактов и fingerprint'ов |
+| `fast-replay`, `bisect`, `repro` | Replay прогона, поиск первого расхождения |
+| `event-stats`, `timeline`, `list-adapters` | Анализ событий и список доступных адаптеров |
+
+## Состав
+
+| Область | Возможности |
+| ------------- | ------------------------------------------------------------------------------ |
+| Движок | Упорядоченные системы, прогоны по seed, выполнение по тикам и сессиям. |
+| Пресеты | `QuickRun`, `RecommendedRun`, `DebugRun`, builder для своих конфигураций. |
+| Ввод | `CommandInbox`, `ScheduledCommandInbox` со стабильным порядком. |
+| Артефакты | Манифест, fingerprint'ы состояния, лог событий, артефакты сбоев, профилирование. |
+| Сериализация | JSON-сериализатор состояния и кодек сообщений, находимых в сборке. |
+| Диагностика | Mutation guard, инварианты, проверка replay, bisect. |
+| CLI | .NET-утилита `epochsim` для всего жизненного цикла прогона. |
+
+## Документация
+
+| | |
+| ---------------------------------- | ------------------------------------------------------ |
+| [Embedding](docs/ru/embedding.md) | Рецепты интеграции: хосты, серверы, внешний ввод |
+| [Artifacts](docs/ru/artifacts.md) | Структура каталога прогона и форматы файлов |
+| [Sessions](docs/ru/sessions.md) | Долгоживущие циклы и пошаговый режим |
+| [Determinism](docs/ru/determinism.md) | Правила, сохраняющие воспроизводимость прогонов |
+
## Примеры
-- Простой пример уровня README: [QuickstartSample](src/EpochSim.Samples/Quickstart/QuickstartSample.cs)
-- Продвинутый/legacy пример домена: [Population](src/EpochSim.Samples/Population)
+[QuickstartSample](src/EpochSim.Samples/Quickstart/QuickstartSample.cs) — минимальная отправная точка. [Population](src/EpochSim.Samples/Population/) — событийный домен с инвариантами и replay.
## Сборка и тесты
@@ -201,17 +223,6 @@ dotnet build EpochSim.slnx -m:1
dotnet test EpochSim.slnx -m:1
```
-## Документация
+## Лицензия
-Русская:
-- [Embedding.ru](docs/Embedding.ru.md)
-- [Artifacts.ru](docs/Artifacts.ru.md)
-- [Sessions.ru](docs/Sessions.ru.md)
-- [Determinism.ru](docs/Determinism.ru.md)
-
-English:
-- [README.md](README.md)
-- [Embedding](docs/Embedding.md)
-- [Artifacts](docs/Artifacts.md)
-- [Sessions](docs/Sessions.md)
-- [Determinism](docs/Determinism.md)
+[MIT](LICENSE)
diff --git a/docs/Artifacts.md b/docs/Artifacts.md
deleted file mode 100644
index 363079b..0000000
--- a/docs/Artifacts.md
+++ /dev/null
@@ -1,26 +0,0 @@
-# Artifacts
-
-EpochSim uses `RunPaths` as the single source of naming for artifacts.
-
-Run directory:
-- `artifacts//`
-
-Core files:
-- `events.jsonl` or `events.jsonl.gz`: event log
-- `trace.jsonl` or `trace.jsonl.gz`: trace stream
-- `profile.jsonl` or `profile.jsonl.gz`: profiling stream
-- `statefp.jsonl`: state fingerprints
-- `manifest.json`: run manifest
-- `meta.txt`: compact run metadata
-
-Directories:
-- `snapshots/`: periodic state snapshots
-- `dumps/`: violation and fail-fast dumps
-
-Failure artifacts (when run fails):
-- `failure-report.json`
-- `failure-snapshot.json` (if snapshot output enabled)
-
-## Note about finalization
-
-`manifest.json` and `meta.txt` are finalized on `EpochSimRunScope.Dispose()`.
diff --git a/docs/Artifacts.ru.md b/docs/Artifacts.ru.md
deleted file mode 100644
index 680b7b3..0000000
--- a/docs/Artifacts.ru.md
+++ /dev/null
@@ -1,26 +0,0 @@
-# Артефакты
-
-В EpochSim имена артефактов централизованы через `RunPaths`.
-
-Каталог запуска:
-- `artifacts//`
-
-Основные файлы:
-- `events.jsonl` или `events.jsonl.gz`: журнал событий
-- `trace.jsonl` или `trace.jsonl.gz`: трассировка
-- `profile.jsonl` или `profile.jsonl.gz`: профилирование
-- `statefp.jsonl`: отпечатки состояния
-- `manifest.json`: манифест запуска
-- `meta.txt`: компактные метаданные запуска
-
-Каталоги:
-- `snapshots/`: периодические снимки состояния
-- `dumps/`: дампы нарушений инвариантов и fail-fast
-
-Файлы при падении запуска:
-- `failure-report.json`
-- `failure-snapshot.json` (если включены snapshot-артефакты)
-
-## Когда пишутся финальные файлы
-
-`manifest.json` и `meta.txt` финализируются при `Dispose()` у `EpochSimRunScope`.
diff --git a/docs/Determinism.md b/docs/Determinism.md
deleted file mode 100644
index 0c60d47..0000000
--- a/docs/Determinism.md
+++ /dev/null
@@ -1,62 +0,0 @@
-# Determinism
-
-Avoid non-deterministic sources inside systems and handlers.
-
-## Common pitfalls
-
-- `DateTime.Now` / `DateTime.UtcNow`
-- `Random` instead of `ctx.Rng`
-- `Guid.NewGuid()` in simulation logic
-- relying on hash-collection iteration order
-- hidden thread races affecting event order
-- uncontrolled floating-point behavior
-
-## Recommended practices
-
-- use only `ctx.Rng` for domain randomness
-- keep command/event handlers explicit and side-effect controlled
-- persist `statefp.jsonl` for run-to-run comparison
-- enable snapshots for fast deterministic replay
-
-## Determinism Rules
-
-EpochSim guarantees deterministic execution for identical inputs (initial state, seed, systems, commands/events, options). The rules below define expected behavior.
-
-### 1) Run lifecycle
-
-- `OnRunStart` is called exactly once before tick processing starts.
-- `OnRunEnd` is always called exactly once, even on failures.
-- If an exception is thrown, `OnRunFailed` is called once before rethrow.
-
-### 2) Tick order
-
-- For each tick `T`, `OnTickStart(T)` is called first.
-- No events for tick `T` are dispatched before `OnTickStart(T)`.
-- `OnTickEnd(T)` is called after command/event processing is complete.
-
-### 3) System order
-
-- Systems tick in registration order.
-- `OnSystemTickStart(T, system)` / `OnSystemTickEnd(T, system)` wrap each `Tick` call.
-- Event handling (`Handle`) also runs in system registration order.
-
-### 4) Scheduler rules
-
-- During tick `T`, only events scheduled for `T` are processed.
-- Events scheduled for the same tick are processed in insertion order (stable queue).
-- Events beyond `endTickInclusive` are not dispatched.
-
-### 5) Command/event pump loop
-
-Within each tick, the engine repeats until both queues are empty:
-
-1. Drain and process all commands (FIFO), adding events to the queue.
-2. Drain and process all events (FIFO) for all systems in registration order.
-
-### 6) Middleware order
-
-- Middleware callbacks are invoked in middleware registration order for each hook.
-- The sequence `OnRunStart` -> ticks -> `OnRunEnd` is stable.
-- `OnRunFailed` is called exactly once.
-
-Any deviation from these rules is considered a correctness regression.
diff --git a/docs/Determinism.ru.md b/docs/Determinism.ru.md
deleted file mode 100644
index 314ee54..0000000
--- a/docs/Determinism.ru.md
+++ /dev/null
@@ -1,62 +0,0 @@
-# Детерминизм
-
-Избегайте недетерминированных источников внутри систем и обработчиков.
-
-## Частые ошибки
-
-- `DateTime.Now` / `DateTime.UtcNow`
-- `Random` вместо `ctx.Rng`
-- `Guid.NewGuid()` в логике симуляции
-- зависимость от порядка обхода hash-коллекций
-- скрытые гонки потоков, меняющие порядок событий
-- неконтролируемое поведение с плавающей точкой
-
-## Рекомендации
-
-- использовать только `ctx.Rng` для доменной случайности
-- держать обработчики команд/событий явными и контролируемыми по побочным эффектам
-- сохранять `statefp.jsonl` для сравнения прогонов
-- включать snapshots для быстрого детерминированного replay
-
-## Правила детерминизма
-
-EpochSim гарантирует детерминированное выполнение при одинаковых входных данных (начальное состояние, seed, системы, команды/события, опции). Ниже зафиксированные правила поведения.
-
-### 1) Жизненный цикл запуска
-
-- `OnRunStart` вызывается ровно один раз до начала обработки тиков.
-- `OnRunEnd` вызывается всегда и ровно один раз, даже при ошибке.
-- Если происходит исключение, `OnRunFailed` вызывается один раз перед повторным выбросом.
-
-### 2) Порядок тиков
-
-- Для каждого тика `T` сначала вызывается `OnTickStart(T)`.
-- Никакие события тика `T` не диспетчатся до `OnTickStart(T)`.
-- После завершения обработки команд/событий вызывается `OnTickEnd(T)`.
-
-### 3) Порядок систем
-
-- Системы тикаются в порядке регистрации.
-- Для каждой системы `OnSystemTickStart(T, system)` и `OnSystemTickEnd(T, system)` обрамляют вызов `Tick`.
-- Обработка событий (`Handle`) тоже идёт в порядке регистрации систем.
-
-### 4) Правила планировщика
-
-- За тик `T` обрабатываются только события, запланированные на `T`.
-- События, запланированные на один и тот же тик, обрабатываются в порядке добавления (стабильная очередь).
-- События за пределами `endTickInclusive` не диспетчатся.
-
-### 5) Pump-цикл команд/событий
-
-Внутри каждого тика движок повторяет шаги, пока обе очереди не пусты:
-
-1. Сливает и обрабатывает все команды (FIFO), добавляя события в очередь.
-2. Сливает и обрабатывает все события (FIFO) для всех систем в порядке регистрации.
-
-### 6) Порядок middleware
-
-- Все callbacks middleware вызываются в порядке регистрации для каждого hook.
-- Порядок `OnRunStart` -> тики -> `OnRunEnd` стабилен.
-- `OnRunFailed` вызывается ровно один раз.
-
-Любое отклонение от этих правил считается регрессией корректности.
diff --git a/docs/Embedding.md b/docs/Embedding.md
deleted file mode 100644
index 0f8ecef..0000000
--- a/docs/Embedding.md
+++ /dev/null
@@ -1,144 +0,0 @@
-# Embedding EpochSim
-
-This guide is about application integration, not low-level builder details.
-
-## RunTicks vs Session
-
-Use `RunTicks` when you want a bounded batch run:
-
-```csharp
-engine.RunTicks(state, seed: 1, endTickInclusive: 10_000);
-```
-
-Use `CreateSession` when your app is long-lived (server/game/interactive):
-
-```csharp
-using var session = engine.CreateSession(state, seed: 1, startTick: 0);
-session.TickOnce();
-session.RunUntil(1_000);
-```
-
-`Session` keeps RNG and scheduler continuity across many `TickOnce` calls.
-
-## Where State Lives
-
-- Runtime state is in memory (`TState`) and is mutated deterministically by your systems/handlers.
-- Persistent state is optional and produced via artifacts:
- - `statefp.jsonl` for lightweight fingerprints.
- - `snapshots/` for point-in-time state persistence.
-- `manifest.json` + `meta.txt` describe run settings and lifecycle.
-
-Quick integration (no codecs/events needed):
-
-```csharp
-var state = new WorldState();
-var engine = Epoch.CreateEngine();
-engine.AddSystem("World", tick: ctx => ctx.State.Population++);
-
-using var run = Epoch.QuickRun(state, rootDir: "artifacts");
-engine.Attach(run);
-engine.RunTicks(state, seed: 1, endTickInclusive: 100);
-```
-
-## External Inputs and Command Flow
-
-Pattern:
-1. Producers (HTTP endpoints, queues, UI) enqueue commands.
-2. Simulation thread drains inbox at tick boundaries.
-3. Commands are processed in the deterministic engine pump.
-
-### Recipe: Single-Thread App Loop
-
-```csharp
-using EpochSim;
-using EpochSim.Kernel.Messaging;
-
-var state = new WorldState();
-var engine = Epoch.CreateEngine();
-var inbox = new CommandInbox();
-
-engine.AttachInbox(inbox);
-engine.OnCommand((s, cmd, _) => s.Population += cmd.Delta);
-
-using var run = Epoch.QuickRun(state, "artifacts");
-engine.Attach(run);
-
-using var session = engine.CreateSession(state, seed: 1, startTick: 0);
-inbox.Enqueue(new AddPopulation(5));
-session.TickOnce();
-```
-
-### Recipe: Server Pattern with Scheduled Inputs
-
-```csharp
-using EpochSim;
-using EpochSim.Kernel.Messaging;
-
-var state = new WorldState();
-var engine = Epoch.CreateEngine();
-var scheduledInbox = new ScheduledCommandInbox();
-
-engine.AttachScheduledInbox(scheduledInbox);
-engine.OnCommand((s, cmd, _) => s.Population += cmd.Delta);
-
-using var session = engine.CreateSession(state, seed: 1, startTick: 0);
-
-scheduledInbox.Enqueue(10, new AddPopulation(2));
-scheduledInbox.Enqueue(10, new AddPopulation(3));
-scheduledInbox.Enqueue(11, new AddPopulation(1));
-
-session.RunUntil(20);
-```
-
-`ScheduledCommandInbox` order is deterministic:
-- tick ascending
-- insertion order within the same tick
-
-## Artifacts to Enable in Production
-
-Default advice:
-- `QuickRun`: local integration and smoke checks.
-- `RecommendedRun`: service debugging baseline.
-
-`RecommendedRun` gives:
-- fingerprints (every tick)
-- snapshots (periodic)
-- trace + profiling streams
-- failure artifacts on crashes
-
-Enable event log only when you need replay/bisect workflows.
-
-## Debugging Determinism with CLI
-
-Run a simulation:
-
-```bash
-dotnet run --project src/EpochSim.Cli -- run artifacts
-```
-
-Verify fingerprint equivalence:
-
-```bash
-dotnet run --project src/EpochSim.Cli -- verify-run artifacts
-```
-
-Find the first mismatch tick:
-
-```bash
-dotnet run --project src/EpochSim.Cli -- bisect artifacts
-```
-
-Replay from best snapshot + events:
-
-```bash
-dotnet run --project src/EpochSim.Cli -- fast-replay artifacts
-```
-
-## Advanced Wiring
-
-Use `Epoch.RecommendedRun(state, codec, serializer, ...)` or `EpochSimRun.For(state)` when you need explicit event codec control, custom run IDs, and per-artifact toggles.
-
-Related docs:
-- [Artifacts](Artifacts.md)
-- [Sessions](Sessions.md)
-- [Determinism](Determinism.md)
diff --git a/docs/Embedding.ru.md b/docs/Embedding.ru.md
deleted file mode 100644
index 59ab3cb..0000000
--- a/docs/Embedding.ru.md
+++ /dev/null
@@ -1,144 +0,0 @@
-# Встраивание EpochSim
-
-Этот документ про интеграцию в приложение, а не про низкоуровневую настройку builder.
-
-## RunTicks vs Session
-
-`RunTicks` для ограниченного batch-прогона:
-
-```csharp
-engine.RunTicks(state, seed: 1, endTickInclusive: 10_000);
-```
-
-`CreateSession` для долгоживущих процессов (серверы/игры/интерактив):
-
-```csharp
-using var session = engine.CreateSession(state, seed: 1, startTick: 0);
-session.TickOnce();
-session.RunUntil(1_000);
-```
-
-`Session` сохраняет непрерывность RNG и scheduler между многими `TickOnce`.
-
-## Где живет состояние
-
-- Runtime-state живет в памяти (`TState`).
-- Persisted state опционален и идет через артефакты:
- - `statefp.jsonl` для легкого сравнения прогонов;
- - `snapshots/` для точек восстановления.
-- `manifest.json` и `meta.txt` фиксируют конфигурацию запуска.
-
-Минимальная интеграция (без codec/event):
-
-```csharp
-var state = new WorldState();
-var engine = Epoch.CreateEngine();
-engine.AddSystem("World", tick: ctx => ctx.State.Population++);
-
-using var run = Epoch.QuickRun(state, rootDir: "artifacts");
-engine.Attach(run);
-engine.RunTicks(state, seed: 1, endTickInclusive: 100);
-```
-
-## Внешние входы и поток команд
-
-Паттерн:
-1. Продюсеры (HTTP/UI/queue) кладут команды в inbox.
-2. Поток симуляции дренирует inbox в начале тика.
-3. Команды обрабатываются в детерминированном pump-цикле.
-
-### Рецепт: single-thread loop
-
-```csharp
-using EpochSim;
-using EpochSim.Kernel.Messaging;
-
-var state = new WorldState();
-var engine = Epoch.CreateEngine();
-var inbox = new CommandInbox();
-
-engine.AttachInbox(inbox);
-engine.OnCommand((s, cmd, _) => s.Population += cmd.Delta);
-
-using var run = Epoch.QuickRun(state, "artifacts");
-engine.Attach(run);
-
-using var session = engine.CreateSession(state, seed: 1, startTick: 0);
-inbox.Enqueue(new AddPopulation(5));
-session.TickOnce();
-```
-
-### Рецепт: server pattern с расписанием по тикам
-
-```csharp
-using EpochSim;
-using EpochSim.Kernel.Messaging;
-
-var state = new WorldState();
-var engine = Epoch.CreateEngine();
-var scheduledInbox = new ScheduledCommandInbox();
-
-engine.AttachScheduledInbox(scheduledInbox);
-engine.OnCommand((s, cmd, _) => s.Population += cmd.Delta);
-
-using var session = engine.CreateSession(state, seed: 1, startTick: 0);
-
-scheduledInbox.Enqueue(10, new AddPopulation(2));
-scheduledInbox.Enqueue(10, new AddPopulation(3));
-scheduledInbox.Enqueue(11, new AddPopulation(1));
-
-session.RunUntil(20);
-```
-
-`ScheduledCommandInbox` гарантирует порядок:
-- `tick` по возрастанию;
-- затем порядок добавления.
-
-## Какие артефакты включать в проде
-
-Рекомендация:
-- `QuickRun`: локальный smoke/integration.
-- `RecommendedRun`: базовый набор для отладки сервиса.
-
-`RecommendedRun` включает:
-- fingerprints каждый тик;
-- snapshots по интервалу;
-- trace + profiling;
-- failure artifacts при падениях.
-
-Event log включайте только когда нужен replay/bisect workflow.
-
-## Отладка детерминизма через CLI
-
-Запуск:
-
-```bash
-dotnet run --project src/EpochSim.Cli -- run artifacts
-```
-
-Проверка fingerprint-эквивалентности:
-
-```bash
-dotnet run --project src/EpochSim.Cli -- verify-run artifacts
-```
-
-Поиск первого тика расхождения:
-
-```bash
-dotnet run --project src/EpochSim.Cli -- bisect artifacts
-```
-
-Replay от лучшего snapshot + events:
-
-```bash
-dotnet run --project src/EpochSim.Cli -- fast-replay artifacts
-```
-
-## Продвинутая настройка
-
-Используйте `Epoch.RecommendedRun(state, codec, serializer, ...)` или `EpochSimRun.For(state)`, когда нужен явный контроль codec/runId/настроек артефактов.
-
-Связанные документы:
-- [Artifacts.ru](Artifacts.ru.md)
-- [Sessions.ru](Sessions.ru.md)
-- [Determinism.ru](Determinism.ru.md)
diff --git a/docs/Sessions.md b/docs/Sessions.md
deleted file mode 100644
index 6c8deaf..0000000
--- a/docs/Sessions.md
+++ /dev/null
@@ -1,26 +0,0 @@
-# Sessions
-
-`SimulationSession` is for step-by-step and long-lived simulation loops.
-
-## API
-
-- `SimTime CurrentTime { get; }`
-- `bool TickOnce(CancellationToken ct = default)`
-- `void RunUntil(SimTime endInclusive, CancellationToken ct = default)`
-- `Dispose()`
-
-## Example
-
-```csharp
-using var session = engine.CreateSession(state, seed: 12345, start: SimTime.Zero);
-
-while (session.CurrentTime.Tick <= 10)
- session.TickOnce();
-
-session.RunUntil(new SimTime(500));
-```
-
-## Behavior
-
-- `CurrentTime` points to the next tick to execute.
-- `RunTicks` is implemented on top of session internals.
diff --git a/docs/Sessions.ru.md b/docs/Sessions.ru.md
deleted file mode 100644
index 0be8291..0000000
--- a/docs/Sessions.ru.md
+++ /dev/null
@@ -1,26 +0,0 @@
-# Сессии
-
-`SimulationSession` нужен для пошагового и долгоживущего выполнения симуляции.
-
-## API
-
-- `SimTime CurrentTime { get; }`
-- `bool TickOnce(CancellationToken ct = default)`
-- `void RunUntil(SimTime endInclusive, CancellationToken ct = default)`
-- `Dispose()`
-
-## Пример
-
-```csharp
-using var session = engine.CreateSession(state, seed: 12345, start: SimTime.Zero);
-
-while (session.CurrentTime.Tick <= 10)
- session.TickOnce();
-
-session.RunUntil(new SimTime(500));
-```
-
-## Поведение
-
-- `CurrentTime` указывает на следующий тик к выполнению.
-- `RunTicks` реализован поверх внутренних механизмов сессии.
diff --git a/docs/en/artifacts.md b/docs/en/artifacts.md
new file mode 100644
index 0000000..3126df2
--- /dev/null
+++ b/docs/en/artifacts.md
@@ -0,0 +1,38 @@
+# Artifacts
+
+`RunPaths` is the single source of artifact naming. Every run writes to its own directory:
+
+```
+artifacts//
+```
+
+## Files
+
+| File | Content |
+| --------------------------------------- | -------------------------- |
+| `events.jsonl`, `events.jsonl.gz` | Event log |
+| `trace.jsonl`, `trace.jsonl.gz` | Trace stream |
+| `profile.jsonl`, `profile.jsonl.gz` | Profiling stream |
+| `statefp.jsonl` | State fingerprints |
+| `manifest.json` | Run manifest |
+| `meta.txt` | Compact run metadata |
+
+The `.gz` variants are written when compression is enabled.
+
+## Directories
+
+| Directory | Content |
+| ------------ | -------------------------------------------- |
+| `snapshots/` | Periodic state snapshots |
+| `dumps/` | Invariant violation and fail-fast dumps |
+
+## Failure artifacts
+
+Written when a run fails:
+
+- `failure-report.json`
+- `failure-snapshot.json`, when snapshot output is enabled
+
+## Finalization
+
+`manifest.json` and `meta.txt` are finalized in `EpochSimRunScope.Dispose()`. Dispose the run scope before reading them.
diff --git a/docs/en/determinism.md b/docs/en/determinism.md
new file mode 100644
index 0000000..182a6e6
--- /dev/null
+++ b/docs/en/determinism.md
@@ -0,0 +1,60 @@
+# Determinism
+
+EpochSim guarantees deterministic execution for identical inputs: initial state, seed, systems, commands and events, and options. Systems and handlers must not introduce other sources of variation.
+
+## Common pitfalls
+
+- `DateTime.Now`, `DateTime.UtcNow`
+- `Random` instead of `ctx.Rng`
+- `Guid.NewGuid()` in simulation logic
+- iteration order of hash collections
+- thread races that change event order
+- uncontrolled floating-point behavior
+
+## Recommended practices
+
+- Use only `ctx.Rng` for domain randomness.
+- Keep command and event handlers explicit, with controlled side effects.
+- Keep `statefp.jsonl` to compare runs.
+- Enable snapshots for fast deterministic replay.
+
+## Rules
+
+Any deviation from these rules is a correctness regression.
+
+### 1. Run lifecycle
+
+- `OnRunStart` is called exactly once before tick processing starts.
+- `OnRunEnd` is called exactly once, including on failure.
+- On an exception, `OnRunFailed` is called once before the exception is rethrown.
+
+### 2. Tick order
+
+- For each tick `T`, `OnTickStart(T)` is called first.
+- No events for tick `T` are dispatched before `OnTickStart(T)`.
+- `OnTickEnd(T)` is called after command and event processing completes.
+
+### 3. System order
+
+- Systems tick in registration order.
+- `OnSystemTickStart(T, system)` and `OnSystemTickEnd(T, system)` wrap each `Tick` call.
+- Event handling (`Handle`) also runs in system registration order.
+
+### 4. Scheduler
+
+- During tick `T`, only events scheduled for `T` are processed.
+- Events scheduled for the same tick are processed in insertion order.
+- Events beyond `endTickInclusive` are not dispatched.
+
+### 5. Command and event pump
+
+Within each tick the engine repeats until both queues are empty:
+
+1. Drain and process all commands in FIFO order, adding events to the queue.
+2. Drain and process all events in FIFO order, for all systems in registration order.
+
+### 6. Middleware
+
+- Middleware callbacks run in registration order for each hook.
+- The sequence `OnRunStart`, ticks, `OnRunEnd` is stable.
+- `OnRunFailed` is called exactly once.
diff --git a/docs/en/embedding.md b/docs/en/embedding.md
new file mode 100644
index 0000000..8971215
--- /dev/null
+++ b/docs/en/embedding.md
@@ -0,0 +1,143 @@
+# Embedding
+
+Integrating EpochSim into an application: execution model, external input and diagnostics.
+
+## Batch runs and sessions
+
+`RunTicks` executes a bounded batch run:
+
+```csharp
+engine.RunTicks(state, seed: 1, endTickInclusive: 10_000);
+```
+
+`CreateSession` serves long-lived applications such as servers, games and interactive tools:
+
+```csharp
+using var session = engine.CreateSession(state, seed: 1, startTick: 0);
+session.TickOnce();
+session.RunUntil(1_000);
+```
+
+A session keeps random number generator and scheduler continuity across `TickOnce` calls. See [Sessions](sessions.md).
+
+## State and persistence
+
+- Runtime state is an in-memory `TState`, mutated deterministically by systems and handlers.
+- Persistent state is optional and produced as run artifacts: `statefp.jsonl` for fingerprints and `snapshots/` for point-in-time state.
+- `manifest.json` and `meta.txt` describe the run settings and lifecycle.
+
+Minimal integration needs no codec and no events:
+
+```csharp
+var state = new WorldState();
+var engine = Epoch.CreateEngine();
+engine.AddSystem("World", tick: ctx => ctx.State.Population++);
+
+using var run = Epoch.QuickRun(state, rootDir: "artifacts");
+run.RunTicks(engine, seed: 1, endTickInclusive: 100);
+```
+
+Run through `run.RunTicks(engine, ...)` so the state is the one the run scope was built with. A different instance attached to the same engine fails with a state mismatch error.
+
+## External input
+
+1. Producers such as HTTP endpoints, queues and UI enqueue commands.
+2. The simulation thread drains the inbox at tick boundaries.
+3. The engine processes commands inside its deterministic pump.
+
+### Single-thread loop
+
+```csharp
+using EpochSim;
+using EpochSim.Kernel.Messaging;
+
+var state = new WorldState();
+var engine = Epoch.CreateEngine();
+var inbox = new CommandInbox();
+
+engine.AttachInbox(inbox);
+engine.OnCommand((s, cmd, _) => s.Population += cmd.Delta);
+
+using var run = Epoch.QuickRun(state, "artifacts");
+engine.Attach(run);
+
+using var session = engine.CreateSession(state, seed: 1, startTick: 0);
+inbox.Enqueue(new AddPopulation(5));
+session.TickOnce();
+```
+
+### Server with scheduled input
+
+```csharp
+using EpochSim;
+using EpochSim.Kernel.Messaging;
+
+var state = new WorldState();
+var engine = Epoch.CreateEngine();
+var scheduledInbox = new ScheduledCommandInbox();
+
+engine.AttachScheduledInbox(scheduledInbox);
+engine.OnCommand((s, cmd, _) => s.Population += cmd.Delta);
+
+using var session = engine.CreateSession(state, seed: 1, startTick: 0);
+
+scheduledInbox.Enqueue(10, new AddPopulation(2));
+scheduledInbox.Enqueue(10, new AddPopulation(3));
+scheduledInbox.Enqueue(11, new AddPopulation(1));
+
+session.RunUntil(20);
+```
+
+`ScheduledCommandInbox` order is deterministic: tick ascending, then insertion order within a tick.
+
+## Choosing a preset
+
+| Preset | Use |
+| ---------------- | --------------------------------------------- |
+| `QuickRun` | Local integration and smoke checks |
+| `RecommendedRun` | Baseline for services and production diagnostics |
+| `DebugRun` | Per-tick fingerprints and mutation guard |
+
+`RecommendedRun` enables:
+
+- compressed artifacts
+- state fingerprints every 50 ticks
+- snapshots every 50 ticks
+- trace and profiling streams
+- failure artifacts on crashes
+- the event log, when a codec is supplied
+- invariant checks every tick, when invariants are supplied
+
+Enable the event log only when replay or bisect is needed. For explicit control over the codec, run identifier and individual artifacts use `Epoch.RecommendedRun(state, codec, serializer, ...)` or `EpochSimRun.For(state)`.
+
+## Debugging determinism
+
+Run a simulation:
+
+```bash
+epochsim run artifacts
+```
+
+Verify fingerprints against the recorded run:
+
+```bash
+epochsim verify-run artifacts
+```
+
+Find the first tick where runs diverge:
+
+```bash
+epochsim bisect artifacts
+```
+
+Replay from the nearest snapshot and the event log:
+
+```bash
+epochsim fast-replay artifacts
+```
+
+## Related
+
+- [Artifacts](artifacts.md)
+- [Sessions](sessions.md)
+- [Determinism](determinism.md)
diff --git a/docs/en/sessions.md b/docs/en/sessions.md
new file mode 100644
index 0000000..e310d86
--- /dev/null
+++ b/docs/en/sessions.md
@@ -0,0 +1,29 @@
+# Sessions
+
+`SimulationSession` runs a simulation step by step and suits long-lived loops.
+
+## API
+
+| Member | Description |
+| ---------------------------------------------------------------- | ---------------------------------- |
+| `SimTime CurrentTime { get; }` | Next tick to execute |
+| `bool TickOnce(CancellationToken ct = default)` | Execute one tick |
+| `void RunUntil(SimTime endInclusive, CancellationToken ct = default)` | Execute up to and including the tick |
+| `void RunUntil(long endTickInclusive, CancellationToken ct = default)` | Same, from a tick number |
+| `Dispose()` | Release the session |
+
+## Example
+
+```csharp
+using var session = engine.CreateSession(state, seed: 12345, start: SimTime.Zero);
+
+while (session.CurrentTime.Tick <= 10)
+ session.TickOnce();
+
+session.RunUntil(new SimTime(500));
+```
+
+## Behavior
+
+- `CurrentTime` points to the next tick to execute.
+- `RunTicks` is implemented on top of the session.
diff --git a/docs/ru/artifacts.md b/docs/ru/artifacts.md
new file mode 100644
index 0000000..fc81c5d
--- /dev/null
+++ b/docs/ru/artifacts.md
@@ -0,0 +1,38 @@
+# Артефакты
+
+`RunPaths` — единственный источник имён артефактов. Каждый прогон пишет в свой каталог:
+
+```
+artifacts//
+```
+
+## Файлы
+
+| Файл | Содержимое |
+| --------------------------------------- | --------------------------- |
+| `events.jsonl`, `events.jsonl.gz` | Лог событий |
+| `trace.jsonl`, `trace.jsonl.gz` | Поток трассировки |
+| `profile.jsonl`, `profile.jsonl.gz` | Поток профилирования |
+| `statefp.jsonl` | Fingerprint'ы состояния |
+| `manifest.json` | Манифест прогона |
+| `meta.txt` | Компактные метаданные |
+
+Варианты `.gz` пишутся при включённом сжатии.
+
+## Каталоги
+
+| Каталог | Содержимое |
+| ------------ | --------------------------------------------------- |
+| `snapshots/` | Периодические снимки состояния |
+| `dumps/` | Дампы нарушений инвариантов и fail-fast |
+
+## Артефакты сбоя
+
+Пишутся при падении прогона:
+
+- `failure-report.json`
+- `failure-snapshot.json`, если включён вывод снимков
+
+## Финализация
+
+`manifest.json` и `meta.txt` финализируются в `EpochSimRunScope.Dispose()`. Освободите run scope до чтения этих файлов.
diff --git a/docs/ru/determinism.md b/docs/ru/determinism.md
new file mode 100644
index 0000000..ecf3c9a
--- /dev/null
+++ b/docs/ru/determinism.md
@@ -0,0 +1,60 @@
+# Детерминизм
+
+EpochSim гарантирует детерминированное выполнение при одинаковых входных данных: начальное состояние, seed, системы, команды и события, опции. Системы и обработчики не должны добавлять другие источники вариативности.
+
+## Частые ошибки
+
+- `DateTime.Now`, `DateTime.UtcNow`
+- `Random` вместо `ctx.Rng`
+- `Guid.NewGuid()` в логике симуляции
+- порядок обхода hash-коллекций
+- гонки потоков, меняющие порядок событий
+- неконтролируемое поведение с плавающей точкой
+
+## Рекомендации
+
+- Используйте только `ctx.Rng` для доменной случайности.
+- Держите обработчики команд и событий явными, с контролируемыми побочными эффектами.
+- Сохраняйте `statefp.jsonl` для сравнения прогонов.
+- Включайте снимки для быстрого детерминированного replay.
+
+## Правила
+
+Любое отклонение от этих правил считается регрессией корректности.
+
+### 1. Жизненный цикл прогона
+
+- `OnRunStart` вызывается ровно один раз до начала обработки тиков.
+- `OnRunEnd` вызывается ровно один раз, в том числе при ошибке.
+- При исключении `OnRunFailed` вызывается один раз перед повторным выбросом исключения.
+
+### 2. Порядок тиков
+
+- Для каждого тика `T` первым вызывается `OnTickStart(T)`.
+- События тика `T` не диспетчатся до `OnTickStart(T)`.
+- `OnTickEnd(T)` вызывается после завершения обработки команд и событий.
+
+### 3. Порядок систем
+
+- Системы тикаются в порядке регистрации.
+- `OnSystemTickStart(T, system)` и `OnSystemTickEnd(T, system)` обрамляют каждый вызов `Tick`.
+- Обработка событий (`Handle`) тоже идёт в порядке регистрации систем.
+
+### 4. Планировщик
+
+- За тик `T` обрабатываются только события, запланированные на `T`.
+- События одного тика обрабатываются в порядке добавления.
+- События за пределами `endTickInclusive` не диспетчатся.
+
+### 5. Цикл команд и событий
+
+Внутри каждого тика движок повторяет шаги, пока обе очереди не пусты:
+
+1. Забирает и обрабатывает все команды в порядке FIFO, добавляя события в очередь.
+2. Забирает и обрабатывает все события в порядке FIFO для всех систем в порядке регистрации.
+
+### 6. Middleware
+
+- Callbacks middleware вызываются в порядке регистрации для каждого hook.
+- Последовательность `OnRunStart`, тики, `OnRunEnd` стабильна.
+- `OnRunFailed` вызывается ровно один раз.
diff --git a/docs/ru/embedding.md b/docs/ru/embedding.md
new file mode 100644
index 0000000..b178a19
--- /dev/null
+++ b/docs/ru/embedding.md
@@ -0,0 +1,143 @@
+# Встраивание
+
+Интеграция EpochSim в приложение: модель выполнения, внешний ввод и диагностика.
+
+## Batch-прогоны и сессии
+
+`RunTicks` выполняет ограниченный batch-прогон:
+
+```csharp
+engine.RunTicks(state, seed: 1, endTickInclusive: 10_000);
+```
+
+`CreateSession` подходит для долгоживущих приложений: серверов, игр и интерактивных инструментов:
+
+```csharp
+using var session = engine.CreateSession(state, seed: 1, startTick: 0);
+session.TickOnce();
+session.RunUntil(1_000);
+```
+
+Сессия сохраняет непрерывность генератора случайных чисел и планировщика между вызовами `TickOnce`. См. [Sessions](sessions.md).
+
+## Состояние и хранение
+
+- Рабочее состояние — это `TState` в памяти, детерминированно изменяемый системами и обработчиками.
+- Постоянное хранение необязательно и выполняется через артефакты прогона: `statefp.jsonl` для fingerprint'ов и `snapshots/` для снимков состояния.
+- `manifest.json` и `meta.txt` описывают настройки и жизненный цикл прогона.
+
+Минимальной интеграции не нужны ни кодек, ни события:
+
+```csharp
+var state = new WorldState();
+var engine = Epoch.CreateEngine();
+engine.AddSystem("World", tick: ctx => ctx.State.Population++);
+
+using var run = Epoch.QuickRun(state, rootDir: "artifacts");
+run.RunTicks(engine, seed: 1, endTickInclusive: 100);
+```
+
+Запускайте через `run.RunTicks(engine, ...)`, чтобы использовался тот state, с которым создан run scope. Другой экземпляр, переданный тому же движку, приведёт к ошибке несоответствия state.
+
+## Внешний ввод
+
+1. Источники — HTTP-эндпоинты, очереди, UI — помещают команды в inbox.
+2. Поток симуляции забирает inbox на границах тиков.
+3. Движок обрабатывает команды внутри своего детерминированного цикла.
+
+### Цикл в одном потоке
+
+```csharp
+using EpochSim;
+using EpochSim.Kernel.Messaging;
+
+var state = new WorldState();
+var engine = Epoch.CreateEngine();
+var inbox = new CommandInbox();
+
+engine.AttachInbox(inbox);
+engine.OnCommand((s, cmd, _) => s.Population += cmd.Delta);
+
+using var run = Epoch.QuickRun(state, "artifacts");
+engine.Attach(run);
+
+using var session = engine.CreateSession(state, seed: 1, startTick: 0);
+inbox.Enqueue(new AddPopulation(5));
+session.TickOnce();
+```
+
+### Сервер с отложенным вводом
+
+```csharp
+using EpochSim;
+using EpochSim.Kernel.Messaging;
+
+var state = new WorldState();
+var engine = Epoch.CreateEngine();
+var scheduledInbox = new ScheduledCommandInbox();
+
+engine.AttachScheduledInbox(scheduledInbox);
+engine.OnCommand((s, cmd, _) => s.Population += cmd.Delta);
+
+using var session = engine.CreateSession(state, seed: 1, startTick: 0);
+
+scheduledInbox.Enqueue(10, new AddPopulation(2));
+scheduledInbox.Enqueue(10, new AddPopulation(3));
+scheduledInbox.Enqueue(11, new AddPopulation(1));
+
+session.RunUntil(20);
+```
+
+Порядок `ScheduledCommandInbox` детерминирован: сначала тик по возрастанию, затем порядок добавления внутри тика.
+
+## Выбор пресета
+
+| Пресет | Назначение |
+| ---------------- | ------------------------------------------------- |
+| `QuickRun` | Локальная интеграция и smoke-проверки |
+| `RecommendedRun` | База для сервисов и диагностики в production |
+| `DebugRun` | Fingerprint'ы каждый тик и mutation guard |
+
+`RecommendedRun` включает:
+
+- сжатие артефактов
+- fingerprint'ы состояния каждые 50 тиков
+- снимки каждые 50 тиков
+- потоки trace и profiling
+- артефакты сбоев при падении
+- лог событий, если передан кодек
+- проверку инвариантов каждый тик, если переданы инварианты
+
+Включайте лог событий только когда нужны replay или bisect. Для явного управления кодеком, идентификатором прогона и отдельными артефактами используйте `Epoch.RecommendedRun(state, codec, serializer, ...)` или `EpochSimRun.For(state)`.
+
+## Отладка детерминизма
+
+Запустить симуляцию:
+
+```bash
+epochsim run artifacts
+```
+
+Сверить fingerprint'ы с записанным прогоном:
+
+```bash
+epochsim verify-run artifacts
+```
+
+Найти первый тик расхождения прогонов:
+
+```bash
+epochsim bisect artifacts
+```
+
+Воспроизвести от ближайшего снимка и по логу событий:
+
+```bash
+epochsim fast-replay artifacts
+```
+
+## См. также
+
+- [Artifacts](artifacts.md)
+- [Sessions](sessions.md)
+- [Determinism](determinism.md)
diff --git a/docs/ru/sessions.md b/docs/ru/sessions.md
new file mode 100644
index 0000000..17636e5
--- /dev/null
+++ b/docs/ru/sessions.md
@@ -0,0 +1,29 @@
+# Сессии
+
+`SimulationSession` выполняет симуляцию пошагово и подходит для долгоживущих циклов.
+
+## API
+
+| Член | Описание |
+| ---------------------------------------------------------------------- | ------------------------------------- |
+| `SimTime CurrentTime { get; }` | Следующий тик к выполнению |
+| `bool TickOnce(CancellationToken ct = default)` | Выполнить один тик |
+| `void RunUntil(SimTime endInclusive, CancellationToken ct = default)` | Выполнять до тика включительно |
+| `void RunUntil(long endTickInclusive, CancellationToken ct = default)` | То же, по номеру тика |
+| `Dispose()` | Освободить сессию |
+
+## Пример
+
+```csharp
+using var session = engine.CreateSession(state, seed: 12345, start: SimTime.Zero);
+
+while (session.CurrentTime.Tick <= 10)
+ session.TickOnce();
+
+session.RunUntil(new SimTime(500));
+```
+
+## Поведение
+
+- `CurrentTime` указывает на следующий тик к выполнению.
+- `RunTicks` реализован поверх сессии.