feat: full system update — cockpit, local-first extraction, self-learning, self-update
- cockpit/ UI (FastAPI): live agent switching, sequential chat, Femida goddess voice, Apple aesthetics, generic Themis branding - extraction: Apple Vision OCR + markitdown + whisper, mixed-PDF, requisites sidecar, adaptive OCR (Ollama removed) - self-learning: redline (baseline diff → knowledge/redlines.md) + error analysis - /themis-update skill: pull latest logic from GitHub without touching cases/ or knowledge/ - portable paths (THEMIS_HOME env), bundled vision-ocr.swift built by install.sh - comprehensive install.sh, README with screenshot, LICENSE (MIT), CONTRIBUTING - synthetic example case (ivanov-ivan); zero client data
This commit is contained in:
@@ -1,320 +1,115 @@
|
||||
# Themis — AI-Powered Legal Case Management System
|
||||
<div align="center">
|
||||
|
||||
Themis is a multi-agent AI system for managing litigation in Russian courts, built on Claude Code. It automates the full pipeline from document ingestion to court-ready submissions — case mapping, legal research, council deliberation, drafting, review, and PDF signing.
|
||||
<img src="cockpit/static/logo.png" alt="Themis" width="220"/>
|
||||
|
||||
# Themis (Фемида)
|
||||
|
||||
**Мультиагентная ИИ-система ведения российских судебных дел на Claude Code.**
|
||||
13 агентов-юристов, рой охотников за практикой, Ареопаг из 5 правоведов,
|
||||
локальное извлечение первички ($0), самообучение на правках, и cockpit —
|
||||
интерфейс уровня Apple, где юристы «обсуждают» дело вживую.
|
||||
|
||||
*Multi-agent AI system for Russian litigation. 13 lawyer-agents, practice hunters,
|
||||
a 5-jurist council, local-first OCR, self-learning, and an Apple-grade cockpit UI.*
|
||||
|
||||
</div>
|
||||
|
||||

|
||||
|
||||
---
|
||||
|
||||
## What Themis Does
|
||||
## Что это
|
||||
|
||||
Themis ведёт судебные дела как живая юрфирма из ИИ-агентов под управлением
|
||||
единого ассистента — **Фемиды, богини правосудия**. Она картирует дело, читает и
|
||||
сверяет материалы, ищет и проверяет судебную практику (за позицию и против),
|
||||
вырабатывает правовую позицию через совет, составляет процессуальные документы
|
||||
готовыми к подаче и готовит юриста к заседанию. Главная ценность — не скорость
|
||||
текста, а **встроенная многоуровневая верификация**: ни факт, ни позиция, ни
|
||||
документ не идут дальше без подтверждения независимыми агентами.
|
||||
|
||||
## Ключевое
|
||||
|
||||
- **🏛 13 агентов-юристов** — канцелярия, картограф, читатели, сверка, три охотника
|
||||
за практикой, Ареопаг (совет 5 правоведов), составитель, ревизор, подготовка к суду.
|
||||
- **🔒 Local-first извлечение ($0)** — Apple Vision OCR (русский точно, локально),
|
||||
markitdown (текст), whisper (аудио/видео). Смешанный PDF извлекается полностью.
|
||||
Авто-реквизиты (ИНН/№ дела/суммы) в сайдкар. **Никакого Ollama, никакого облака
|
||||
на основном проходе.**
|
||||
- **🧠 Самообучение** — правишь готовый `.docx`, Фемида сравнивает «до/после»
|
||||
(содержание И форматирование) и больше не повторяет огрехи.
|
||||
- **🖥 Cockpit** — локальный UI (FastAPI), где агенты переключаются вживую, чат
|
||||
ведётся последовательно, Фемида говорит женским голосом богини. Apple-эстетика.
|
||||
- **🔗 Граф знаний** — `/graphify` вскрывает межкейсовые связи (общий оппонент,
|
||||
один объект, переиспользуемые аргументы) — экономия токенов на росте базы.
|
||||
- **🔄 Самообновление** — `/themis-update` тянет последнюю логику с GitHub, **не
|
||||
трогая твои дела и базу знаний**.
|
||||
- **🛡 Приватность** — данные клиентов (`cases/`) всегда локально, в публику не уходят.
|
||||
|
||||
## Архитектура агентов
|
||||
|
||||
```
|
||||
Incoming files
|
||||
↓
|
||||
Грузенберг mv → 00_intake/
|
||||
↓
|
||||
Мейер (case-mapper) parallel readers → knowledge-map.md
|
||||
├── Покровский (DOCX, text-PDF → markitdown)
|
||||
├── Гольмстен (scan-PDF → OCR)
|
||||
└── Буринский (images → vision)
|
||||
↓ Шершеневич (reconciler, 2 rounds)
|
||||
↓
|
||||
Three practice hunters (parallel, L2/L3):
|
||||
├── Спасович (authoritative: Пленум ВС → Коллегии → округа)
|
||||
├── Карабчевский (adversarial: practice against us)
|
||||
└── Плевако (procedural: deadlines, evidence, jurisdiction)
|
||||
↓ /askacouncil (anonymous cross-review → practice.md)
|
||||
↓
|
||||
/council — Ареопаг (5 jurists, 3 rounds → positions.md):
|
||||
├── Муравьев (Prosecutor — max aggression)
|
||||
├── Маклаков (Devil's Advocate — find weaknesses)
|
||||
├── Фойницкий (Proceduralist — form & deadlines)
|
||||
├── Владимиров (Evidence specialist — what's proven)
|
||||
└── Урусов (Tactician, chair — final word)
|
||||
↓
|
||||
Сперанский (doc-drafter) → .md + .docx in 02_hearings/
|
||||
↓
|
||||
Кони (doc-reviewer) → 7-block verification
|
||||
↓
|
||||
/finalize → PDF + signature overlay
|
||||
Шаг 0 База знаний → practice_index.md (свериться перед внешним поиском)
|
||||
Шаг 1 Картирование → Грузенберг (канцелярия) → Мейер (карта) + читатели
|
||||
(Гольмстен/Буринский/Покровский) → Шершеневич (сверка)
|
||||
Шаг 2 Практика → Спасович · Плевако · Карабчевский (охотники) → Ареопаг
|
||||
Шаг 3 Позиция → Совет 5 правоведов (Урусов, Маклаков, Фойницкий…)
|
||||
Шаг 4 Документ → Сперанский → .md + .docx (источник в каждом утверждении)
|
||||
Шаг 5 Проверка → Кони (структура, реквизиты, форматирование)
|
||||
Шаг 6 Самоконтроль → разбор ошибок → журнал уроков
|
||||
```
|
||||
|
||||
---
|
||||
Каждый шаг закрывается маркером консенсуса; без маркера система не идёт дальше.
|
||||
|
||||
## Case Levels
|
||||
## Установка
|
||||
|
||||
| Level | When | Hunters | /askacouncil | /council | Model |
|
||||
|-------|------|---------|--------------|----------|-------|
|
||||
| L1 | Simple, 1 issue | Tactical only | — | — | Sonnet |
|
||||
| L2 | Standard claim, 2-3 issues | All three | ✓ | ✓ (skippable) | Opus |
|
||||
| L3 | Cassation, КАС, lost case | All three | ✓ | Required | Opus |
|
||||
|
||||
---
|
||||
|
||||
## Agents (13)
|
||||
|
||||
| Pseudonym | Agent | Model | Role |
|
||||
|-----------|-------|-------|------|
|
||||
| Грузенберг | inbox-triage | Haiku | mv files from Desktop/inbox/ → 00_intake/ |
|
||||
| Мейер | case-mapper | Sonnet | Orchestrates parallel reading + reconciliation |
|
||||
| Покровский | docx-reader | Haiku | DOCX, XLSX, text-PDF via markitdown |
|
||||
| Гольмстен | pdf-reader | Sonnet | Scan-PDF: render → OCR via vision |
|
||||
| Буринский | image-reader | Sonnet | JPG/PNG/TIFF via vision |
|
||||
| Шершеневич | case-reconciler | Sonnet | Conflict resolution, up to 2 rounds |
|
||||
| Спасович | practice-hunter-classic | Sonnet | Authoritative practice in our favor |
|
||||
| Карабчевский | practice-hunter-skeptic | Opus | Adversarial — practice against us |
|
||||
| Плевако | practice-hunter-tactical | Sonnet | Procedural: deadlines, evidence, jurisdiction |
|
||||
| Рождественский | archivist | Haiku | Maintains global practice index + client profiles |
|
||||
| Сперанский | doc-drafter | Opus/Sonnet | Drafts court documents |
|
||||
| Кони | doc-reviewer | Sonnet | 7-block pre-submission verification |
|
||||
| Андреевский | hearing-prep | Sonnet | Prepares for court hearings |
|
||||
|
||||
---
|
||||
|
||||
## Knowledge Base
|
||||
|
||||
Themis builds a cross-case practice database that grows over time:
|
||||
|
||||
```
|
||||
knowledge/
|
||||
practice_index.md ← global index, auto-updated by Рождественский
|
||||
after each hunt and /askacouncil
|
||||
|
||||
cases/{client}/
|
||||
_client.md ← live client profile (family, business, assets, all cases)
|
||||
|
||||
cases/
|
||||
_clients.md ← lightweight routing registry
|
||||
_relationships.md ← cross-client connection matrix
|
||||
```
|
||||
|
||||
**Practice search order (within each hunter leaf):**
|
||||
1. `practice_context.md` — per-case extract from global index
|
||||
2. `grep knowledge/practice_index.md` — direct global search
|
||||
3. External: Firecrawl → ScrapeGraphAI → WebSearch
|
||||
|
||||
---
|
||||
|
||||
## Document Pipeline
|
||||
|
||||
```
|
||||
03_drafts/ ← working files only (v1, v2, iterations)
|
||||
{document}_v1.md
|
||||
{document}_v1.docx
|
||||
|
||||
02_hearings/{date}/ ← final files only (after Кони: ГОТОВ К ПОДАЧЕ)
|
||||
{document}.md
|
||||
{document}.docx
|
||||
{document}.pdf ← after /finalize (Word export + signature overlay)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Commands
|
||||
|
||||
| Command | Function |
|
||||
|---------|----------|
|
||||
| `/new-case {client} {case}` | Create case structure, move inbox, run case-mapper |
|
||||
| `/new-event` | Create hearing folder in 02_hearings/ |
|
||||
| `/draft {type} for {client}/{case}` | Draft court document (checks consensus markers) |
|
||||
| `/finalize {docx_path}` | Export to PDF + overlay signature |
|
||||
| `/askacouncil {case_path}` | Anonymous cross-review of hunter reports → practice.md |
|
||||
| `/council {case_path}` | Five-jurist council → positions.md |
|
||||
| `/init-cases` | Build knowledge maps for unmapped cases |
|
||||
| `/init-practice` | Run hunters for cases without practice.md |
|
||||
| `/close-case` | Archive case, update indices |
|
||||
|
||||
---
|
||||
|
||||
## Case Structure
|
||||
|
||||
```
|
||||
cases/
|
||||
{client}/
|
||||
_client.md ← live client profile
|
||||
{case}/
|
||||
00_intake/ ← source files (immutable)
|
||||
01_context/
|
||||
_working/ ← reader fragments, reconcile reports
|
||||
_practice/ ← hunter_*.md
|
||||
_council/ ← council round files
|
||||
knowledge-map.md ← [КАРТА ГОТОВА ✓]
|
||||
practice_context.md ← per-case extract from global index
|
||||
practice.md ← [СОВЕТ ЗАВЕРШЁН ✓]
|
||||
positions.md ← [СОГЛАСОВАНО СОВЕТОМ]
|
||||
02_hearings/
|
||||
{date}_name/
|
||||
_event.md
|
||||
{document}.md
|
||||
{document}.docx
|
||||
{document}.pdf
|
||||
03_drafts/ ← working versions
|
||||
04_archive/
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Consensus Markers (enforced by doc-drafter)
|
||||
|
||||
| Marker | File | Required for |
|
||||
|--------|------|--------------|
|
||||
| `## КАРТА ГОТОВА ✓` | knowledge-map.md | Always |
|
||||
| `## СОВЕТ ЗАВЕРШЁН ✓` | practice.md | Always |
|
||||
| `СОГЛАСОВАНО СОВЕТОМ` | positions.md | L2/L3 only |
|
||||
|
||||
---
|
||||
|
||||
## Full Dependency Stack
|
||||
|
||||
Themis builds on top of several tools. Everything below is required for full functionality.
|
||||
|
||||
---
|
||||
|
||||
### 1. Claude Code
|
||||
Требования: **macOS** (Apple Vision OCR), Python 3.11+, Xcode CLT (`xcode-select --install`),
|
||||
[Claude Code](https://claude.com/claude-code).
|
||||
|
||||
```bash
|
||||
npm install -g @anthropic-ai/claude-code
|
||||
git clone https://github.com/7teenno1-art/themis.git
|
||||
cd themis
|
||||
bash install.sh
|
||||
```
|
||||
|
||||
Models used:
|
||||
| Agent | Model |
|
||||
|-------|-------|
|
||||
| doc-drafter (L2/L3), practice-hunter-skeptic | `claude-opus-4-8` |
|
||||
| case-mapper, hunters, reviewers | `claude-sonnet-4-6` |
|
||||
| readers, archivist (leaf workers) | `claude-haiku-4-5` |
|
||||
`install.sh` ставит Python-зависимости, собирает Apple Vision OCR из исходника,
|
||||
ставит whisper+ffmpeg, готовит директории и проверяет Claude Code CLI.
|
||||
|
||||
---
|
||||
## Использование
|
||||
|
||||
### 2. Python Packages
|
||||
**Через Claude Code:** открой проект, скажи
|
||||
> «Новое дело: Иванов, раздел квартиры после развода. Нужно исковое».
|
||||
|
||||
Фемида прогонит протокол Шаг 0→5 и выдаст документ.
|
||||
|
||||
**Через Cockpit (UI):**
|
||||
```bash
|
||||
pip install pymupdf Pillow markitdown python-docx
|
||||
python3 cockpit/app.py # → http://localhost:8800
|
||||
```
|
||||
Перетащи документы в окно или напиши задачу — увидишь, как юристы переключаются.
|
||||
|
||||
| Package | Source | Used for |
|
||||
|---------|--------|---------|
|
||||
| [pymupdf](https://github.com/pymupdf/PyMuPDF) | pip | Scan-PDF rendering, signature overlay |
|
||||
| [Pillow](https://github.com/python-pillow/Pillow) | pip | Signature image processing |
|
||||
| [markitdown](https://github.com/microsoft/markitdown) | pip (Microsoft) | DOCX/XLSX/PPTX/PDF/HTML → Markdown, zero tokens |
|
||||
| [python-docx](https://github.com/python-openxml/python-docx) | pip | DOCX reading |
|
||||
|
||||
---
|
||||
|
||||
### 3. Claude Code Community Skills
|
||||
|
||||
Two skills control how all 13 agents communicate and write. **Required.**
|
||||
|
||||
#### [caveman](https://github.com/eastcoastcode/ecc) — token-efficient communication
|
||||
Compresses agent output ~65–75% while keeping full technical accuracy. Used for all inter-agent and user communication.
|
||||
|
||||
**Обновление:**
|
||||
```bash
|
||||
npx skills add caveman
|
||||
/themis-update # тянет последнюю логику, данные не трогает
|
||||
```
|
||||
|
||||
#### humanizer — professional legal language
|
||||
Transforms AI output into authentic professional prose. Used when writing court documents, practice reports, and case maps.
|
||||
## Структура
|
||||
|
||||
```bash
|
||||
npx skills add humanizer
|
||||
```
|
||||
.claude/agents/ 13 агентов дела cockpit/ UI (FastAPI + статика)
|
||||
.claude/skills/ askacouncil, doc-drafter scripts/ извлечение, генерация docx, OCR
|
||||
.claude/commands/ слэш-команды knowledge/ practice_index, redlines, уроки
|
||||
.claude/CLAUDE.md протокол Фемиды cases/ ДЕЛА — локально, не в git
|
||||
AGENTS.md зеркало для Codex bin/ vision-ocr.swift (OCR-движок)
|
||||
templates/ шаблоны документов docs/ скриншоты, описание
|
||||
```
|
||||
|
||||
> Both skills are part of the **ECC (Engineering Claude Code)** skill pack.
|
||||
> If `npx skills add` is unavailable, copy the skill folders manually to `~/.claude/skills/`.
|
||||
## Приватность
|
||||
|
||||
---
|
||||
`cases/` (материалы дел клиентов) — в `.gitignore`, **никогда не публикуются**.
|
||||
Извлечение локальное ($0), документы остаются на твоём Mac. В репозитории — только
|
||||
синтетический пример (`cases/ivanov-ivan`).
|
||||
|
||||
### 4. MCP Servers
|
||||
## Лицензия
|
||||
|
||||
Configure in `~/.claude/mcp.json`.
|
||||
|
||||
#### Firecrawl — primary web search (required for practice hunters)
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"firecrawl-mcp": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "firecrawl-mcp@latest"],
|
||||
"env": { "FIRECRAWL_API_KEY": "YOUR_KEY_HERE" }
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Get API key: [firecrawl.dev](https://firecrawl.dev)
|
||||
|
||||
#### ScrapeGraphAI — fallback search
|
||||
|
||||
```bash
|
||||
pip install scrapegraphai
|
||||
# CLI: sgai validate --json
|
||||
```
|
||||
|
||||
Get API key: [scrapegraphai.com](https://scrapegraphai.com) → store in `~/.scrapegraphai/config.json`
|
||||
|
||||
#### markitdown MCP (optional — adds MCP-based document conversion)
|
||||
|
||||
```bash
|
||||
pip install markitdown-mcp
|
||||
```
|
||||
|
||||
Add to `~/.claude/mcp.json`:
|
||||
```json
|
||||
"markitdown": { "command": "python3", "args": ["-m", "markitdown_mcp"] }
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 5. Microsoft Word (macOS)
|
||||
|
||||
Required for `/finalize` — exports `.docx` → `.pdf` via AppleScript.
|
||||
`Microsoft Word.app` must be installed in `/Applications/`.
|
||||
|
||||
**Linux/Windows alternative** — replace AppleScript block in `scripts/sign_and_pdf.py`:
|
||||
```python
|
||||
subprocess.run(["libreoffice", "--headless", "--convert-to", "pdf", docx_path])
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 6. Anthropic Built-in Skill
|
||||
|
||||
`anthropic-skills:docx` is used by the doc-drafter to generate `.docx` files.
|
||||
Bundled with Claude Code — no separate install.
|
||||
|
||||
---
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
git clone https://github.com/your-username/themis.git my-legal-practice
|
||||
cd my-legal-practice
|
||||
|
||||
# 1. Python dependencies + directory setup
|
||||
bash setup.sh
|
||||
|
||||
# 2. Community skills
|
||||
npx skills add caveman
|
||||
npx skills add humanizer
|
||||
|
||||
# 3. Configure MCP servers in ~/.claude/mcp.json (see above)
|
||||
|
||||
# 4. Signature for /finalize (optional)
|
||||
# Photograph your signature → crop → save as PNG:
|
||||
# cases/_assets/подпись.png (~400×130px, transparent background)
|
||||
|
||||
# 5. Start
|
||||
claude
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Enforcement
|
||||
|
||||
Themis enforces the full workflow. At session start it reads the last error log and reports pending fixes. At session end it analyzes errors, formatting issues, and failed steps — and proposes specific file-level corrections.
|
||||
|
||||
Doc formatting is strictly enforced: Times New Roman, 14/13/12pt, margins 30/15/20/20mm, justified body, right-aligned signature. Кони verifies formatting as block 6 before any document is declared final.
|
||||
|
||||
---
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
MIT — см. [LICENSE](LICENSE). Построено на [Claude Code](https://claude.com/claude-code).
|
||||
|
||||
Reference in New Issue
Block a user