docs: подробное описание работы системы — русское и английское

README остаётся витриной; подробный разбор ушёл в docs/HOW-IT-WORKS.ru.md и
docs/HOW-IT-WORKS.en.md, из обеих языковых половин README на них ведёт ссылка.

Правило текста: утверждение без запуска не пишется. Каждый факт в обоих файлах
проверен командой в этой сессии, числа взяты из замера, а не из памяти:
OCR 1,3-1,6 с на страницу, кеш 0,19 с против 2,04 с на повторном чтении,
селфтесты сторожей 126/48/43/30/30/18/5, сводка дела 1 868 знаков.

Что НЕ подтвердилось — в описание не попало, а названо честно отдельным
разделом: корпус кодексов на машине пуст, поэтому cite.py не отдаёт статей и
госпошлина не считается; поиск практики зависит от чужого сайта и в день замера
отвечал HTTP 500; распознавание сканов работает только на macOS; корпус права и
индекс практики не приезжают с репозиторием.

Английский — самостоятельный текст, а не подстрочник: русские реалии (ГПК,
Пленум, госпошлина) поясняются, а не транслитерируются, и оговорено, что вывод
приборов в примерах переведён, а в терминале он русский.

Примеры обезличены: только синтетический cases/ivanov-ivan и вымышленный
testfam-ab.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Зарубин Филипп
2026-08-21 12:30:17 +03:00
co-authored by Claude Opus 5
parent 564b8bde79
commit 9a3b167c17
3 changed files with 976 additions and 0 deletions
+498
View File
@@ -0,0 +1,498 @@
# How Themis actually works
This is the engine room, not the showroom. Every claim below was checked by running
it on a real machine on 21 August 2026, and the command sits next to the claim so
you can repeat it instead of trusting me. Where something is broken, missing, or
needs your hands, it says so. There is a whole section for that near the end.
The reader I have in mind is a working litigator, not a developer.
One practical note before we start: the tools speak Russian. The command output
quoted throughout this document is translated so it reads, but what appears in your
terminal is the Russian original. Flag names and file paths are shown verbatim.
A note on jurisdiction: Themis is built for Russian civil litigation. A few local
terms show up below, and I explain them where they appear rather than leaving them
transliterated.
---
## 1. What happens when you hand it a case
A case is a folder. It has two faces: one turned toward you, one toward the machine.
```
cases/<client>/<case>/
_case.md the case card — you read this one
00_intake/ what the client brought in. Untouchable
02_hearings/ events, and documents already filed with the court
GOTOVO/ finished documents — the reason you came here
.agent/ the kitchen: case map, case law, legal position, drafts
```
`.agent/` is hidden behind a dot on purpose. Watching a draft being drafted is not
your job. The layout lives in exactly one file
([`scripts/case_paths.py`](../scripts/case_paths.py)) rather than scattered across
the codebase, so every agent understands it the same way.
From there the work moves in steps, and the order is not a suggestion.
**Step 0, check what we already know.** Before going anywhere, the system looks at
its own index of previously researched questions. If the question is already
answered, it reuses the answer. On a fresh install that index is empty. It is not
shipped; it accumulates as you work, and the longer you use the system, the more
often step 2 is skipped outright.
**Step 1, map the case.** A cartographer agent reads the materials and reduces
them to one document: facts, parties, subject matter, chronology, evidence. No map,
no further movement.
**Step 2, the case law.** Hunters go looking for precedent. On a hard case there are
three of them, and they argue (more on that below).
**Step 3, the legal position.** A council of jurists works out the position.
**Step 4, the document.** A drafter writes it, working from the map, the case law
and the position.
**Step 5, review.** A separate reviewer takes the document apart across seven
checkpoints and issues a verdict. The `.docx` is built exactly once, after the
verdict says "ready to file", and lands in `GOTOVO/`.
Where you currently stand is answered by one command rather than by reading half a
dozen files:
```bash
python3 scripts/themis_status.py cases/<client>/<case> --brief
```
It prints the case details, the next hearing, how much material is in, the state of
every step, and a line that says NEXT STEP. That line is not advice. It is the only
step the system will let you take.
**Skipping a step is physically impossible.** Not discouraged. Impossible. Trying
to write the legal position before the case law is ready:
```
$ echo '{"tool_name":"Write","tool_input":{"file_path":".../positions.md"}}' | python3 scripts/claude_guard.py
PROTOCOL BLOCK: positions.md may only be written after Step 2 — practice.md
carries neither consensus marker.
```
The reasoning is dull and important. A model follows written instructions
probabilistically; a guard follows them every time. So anything declared an
iron rule here is enforced by code, not by good intentions.
---
## 2. How the material gets read, and why it costs nothing
All extraction happens on your machine. Nobody is billed for reading a scan and
nothing is uploaded to read it.
**Scans go through Apple Vision**, the same engine macOS uses to pull text out of
an image. It is compiled into [`bin/vision-doc`](../bin) and called locally.
Measured on three A4 pages of Russian text at 200 dpi:
```
$ /usr/bin/time -p bin/vision-doc page-1.png
real 1.62 # then 1.31 and 1.33
```
Call it a second and a half per page. Accuracy on Russian is good: on a control
page of forty lines, forty matched. The only casualty was the `№` sign, which came
back as `Nº`.
**Text documents are never OCR'd at all.** If a PDF, DOCX or XLSX already carries a
text layer, the text is simply lifted out. Faster and more accurate than any
recognition.
Which of the two paths applies is decided by a router
([`scripts/markdown_extract.py`](../scripts/markdown_extract.py)), not by a person:
```
$ python3 scripts/markdown_extract.py contract.pdf --json-meta
{"route": "text-pdf", "pages": 3, "cache": "miss", ...}
```
```
$ python3 scripts/markdown_extract.py scan.pdf --json-meta --render-dir /tmp/case
{"route": "scan", "ocr_pages": 3, ...
"note": "Apple Vision OCR (local, $0): 3 pages → page_NNN.txt (0 empty)"}
```
Every scanned page becomes its own file: `page_001.txt`, `page_002.txt`, and so on.
That is not fussiness. It means a brief can honestly cite "page 82" and page 82 is
really there.
**Mixed PDFs do not lose pages.** When half a document is real text and half is a
pasted-in scan, the text pages are read as text and the scanned pages are recognised.
Nothing quietly falls out.
**Details are picked up automatically.** Alongside the extracted text the router
writes down what it found: tax numbers, company registration numbers, case numbers,
sums, passport and account numbers.
```
"requisites": {"inn": ["7707083893"], "case_soyu": ["2-45/2026"]}
```
(`INN` is the Russian taxpayer number, the thing you check a counterparty by.)
Nobody has to hunt for them by eye.
**Reading the same file again is free, and that is measurable.** Results are cached
under `~/.cache/legal_extract`, keyed by the file's fingerprint:
```
first call: real 2.04 "cache": "miss"
second call: real 0.19 "cache": "hit"
```
No model call, two tenths of a second. Which is why re-reading case materials is
cheap here. What is expensive is recognising them twice, and the system refuses to.
### When it does reach for the cloud
Three situations, all narrow:
1. recognition came back empty or obviously garbled;
2. a critical detail is in dispute — a case number, a tax number, a sum, a name —
and wants a second pair of eyes;
3. handwriting, stamps, faded text.
Everything else stays local. And if the local engine is unavailable, the system
stops and says so rather than silently switching to the cloud. Quiet degradation is
worse than a refusal: you would never learn that the bill went up while the quality
went down.
---
## 3. Why there are thirteen agents rather than one
An agent here is a narrow role with its own tools. There are thirteen of them
(`ls .claude/agents/` returns exactly thirteen), and the split is functional.
**Intake** moves new material from the inbox into the right case.
**The cartographer** builds the case map, delegating to readers when the case is big.
**Three readers**, one per material type: scanned PDF, photograph, text document.
They are separate because each has a different source of truth and a different cost
of being wrong.
**The reconciler** compares the readers' reports against each other: details, dates,
names, amounts. If two readers saw different sums in the same document, nothing
moves forward until that is settled.
**Three case-law hunters, and this is where it gets useful.**
The classicist builds the argument for you. The sceptic hunts for precedent
*against* you: the brief is to think like the other side's best counsel and come
back with a risk map, each risk paired with its counter-argument. The tactician
works the procedural angles: limitation periods, admissibility, jurisdiction,
interim relief.
The point is that they are not asked to agree. A single model told to "find
supporting case law" will find supporting case law; that is what searching for a
conclusion does. Three roles with genuinely opposed briefs hand you what opposing
counsel will say, before you hear it in the courtroom.
**A council of five jurists** argues the position over several rounds and reduces
the argument to one document.
**The drafter** writes. **The reviewer is a different agent**, deliberately: whoever
wrote the document does not get to mark their own work. The reviewer reads it cold
against a seven-part checklist and issues a verdict.
**The hearing preparer** assembles the pack: objective, what to bring, arguments
with sources, likely questions from the bench, weak spots. **The archivist** files
what was learned so the next similar case does not start from zero.
---
## 4. Where the system checks itself
This is the least familiar part. Most AI tools answer and stop. Here there are
several guards standing between the answer and you, and each one is code rather
than intention.
**An acceptance suite.** The system carries its own test of 117 checks:
```
$ python3 scripts/stage9_spec.py
checks passed: 117/117
```
It does not ask "does the script run". It asks whether the promises hold: that the
documentation does not describe tools which do not exist, that rules declared
iron are actually enforced by something, that a fresh install can produce a
document.
**A path guard** refuses to destroy client material:
```
$ rm -rf cases/<case>/00_intake
BLOCKED: deletion touches cases/, 00_intake/ or _baselines/.
Case materials are untouchable. If you truly need this — do it by hand.
```
The same guard refuses to open a binary document directly, bypassing the router and
the cache. Otherwise the same page would get recognised ten times over.
**A personal-data guard** sits on every commit and every push. It reads the client
folder names off the disk at the moment it runs and stores none of them. When it
finds something it reports "file, line, length of match" and never prints the value
itself: a guard must not become the second leak.
This is not hypothetical. On 4 August 2026 a case folder name, which is to say a
real person's surname, reached a public repository through a code comment. The
guard was written afterwards, because of that.
**A format guard** signs off the `.docx` instead of a human eye:
```
$ python3 scripts/document_guard.py claim.docx --md claim.md
```
Margins, point sizes, line spacing, a single typeface throughout, page numbers,
justification, exhibit numbering, and whether every exhibit is actually referenced
in the body. Exit 0 means accepted; exit 1 comes with the list of what to fix.
This comparison used to be done by the model, which spent reasoning on arithmetic
and raised false alarms doing it.
**Amounts in words are checked against the figure.** "350,000 (three hundred and
fifty thousand) roubles". The words have to match the number, not merely be
present. The numerals are generated by dedicated code, with the grammatical gender
and case Russian requires.
**Prompt injection hidden in case material.** Evidence is data, not instructions.
If a scan contains something like "ignore your previous instructions", a separate
guard catches it. What it looks for is not the imperative mood — legal writing is
full of imperatives — but a form of address to the executor. A court document
never calls the model by name, and that turns out to be a reliable axis.
**A document cannot be assembled around the review.** Until the reviewer rules,
there is no `.docx`:
```
$ python3 scripts/verdict.py claim.md --check
BUILD REFUSED — claim.md has no verdict at all; it never went through review
```
The verdict is bound to a specific revision of the text. Edit the document after
approval and the approval lapses.
**Every guard tests itself, and they are all green:**
| Guard | What it holds | Self-test |
|---|---|---|
| `claude_guard.py` | paths, step order, reads that bypass the router | 126/126 |
| `document_guard.py` | `.docx` formatting, `.docx` matches `.md` | 48/48 |
| `pd_guard.py` | client data never reaches a public repository | 43/43 |
| `quality_gate.py` | OCR completeness, tables, figures, checksums | 30/30 |
| `instruction_guard.py` | injection inside case material | 30/30 |
| `money_rule.py` | money, currencies, verbatim quotations | 18/18 |
| `table_guard.py` | tables lost during extraction | 5/5 |
| `pii_gate.py` | redaction before anything leaves the case | fail-closed |
`pii_gate` deserves its own sentence. It redacts a fragment of the case before that
fragment goes anywhere external. And if it finds nothing, it does not report
"clean", it refuses. Legal text almost always contains at least one name; an empty
result more often means the search failed than that there was nothing to find.
---
## 5. Why it is cheap to run
Not because the model is cheap. Because it gets called less.
**Cases are triaged by difficulty before any work starts.** Three modes. A routine
document on a question already answered is not run like a Supreme Court appeal: no
map is built, details are taken from what was already extracted, the hunters do not
run at all. A straightforward case gets one hunter instead of three and no councils.
A hard case gets the full cast. When in doubt the cheaper mode wins, because
escalating later is always possible.
**The model for a step follows from the difficulty of the case, not from habit.**
The drafter defaults to the strongest model, because on a serious case drafting is
the most consequential work in the pipeline. On a routine document that same default
would mean paying five times over for the same page. So
[`scripts/model_policy.py`](../scripts/model_policy.py) decides:
| Work | Routine case | Hard case |
|---|---|---|
| drafting | mid-tier model | top-tier |
| review | mid-tier | top-tier |
| hunting case law | does not run | mid-tier |
| council members | does not run | mid-tier; chair is top-tier |
| reading text, sorting | cheap tier | cheap tier |
Gathering and mechanics go to the cheap model. Synthesis, drafting and the final
pass go to the strong one.
**Anything an ordinary program can compute is never given to a model.** This is the
largest saving and the dullest.
Statutory interest under article 395 of the Civil Code is computed in code, with the
central bank rate table, a period-by-period breakdown and the total spelled out in
words:
```
$ python3 scripts/calc395.py --dolg 350000 --s 01.02.2026 --po 01.08.2026
01.02.2026 — 15.02.2026 15 d. 16.00% /365 2 301.37
...
TOTAL INTEREST: 25 911,99 (twenty-five thousand nine hundred eleven roubles
ninety-nine kopecks)
```
Procedural deadlines are code too, and they cite the provision they rely on:
```
$ python3 scripts/sroki.py --ot 21.08.2026 --mesyacev 1
time starts running 22.08.2026 [art. 107(3) Code of Civil Procedure]
plus 1 month → 21.09.2026 [art. 108(1); Supreme Court Plenum ruling
of 22.06.2021 no. 16, para. 16]
LAST DAY: 21.09.2026 (Monday)
```
(A *Plenum ruling* is guidance issued by the Supreme Court on how lower courts must
apply a provision. In practice you cite it the way a common-law lawyer cites binding
authority.)
Taxpayer numbers are validated by checksum, locally, for nothing. A digit garbled
during recognition almost never produces a valid checksum:
```
$ python3 scripts/verify_inn.py 7707083893
7707083893: valid
$ python3 scripts/verify_inn.py 7707083894
7707083894: INVALID — no such taxpayer number exists; re-check against the scan
```
Plenum rulings are quoted verbatim from disk, without going online:
```
$ python3 scripts/cite.py "para. 21 of Plenum ruling of 19.06.2012 no. 13"
### para. 21
Courts must bear in mind that, within the meaning of art. 327...
Source: knowledge/plenumy/plenum-ot-19062012.md
Ready to paste: (Supreme Court Plenum ruling of 19.06.2012 no. 13, para. 21)
```
The corpus does not ship with the repository. You fetch it yourself with one
command (`python3 scripts/update_legal_corpus.py --plenums`), after which it lives
on your disk and refreshes monthly via a scheduled job. On the machine these
measurements were taken, it holds 342 rulings.
Cost is not the whole of it. A web lookup once mangled the text of article 683 of
the Civil Code, and since then provisions come from disk or they do not come at all.
**What has been read is not read again.** An opened file stays in play for the rest
of the session and is paid for again with every subsequent model call. So the state
of a case is asked of a program rather than reconstructed by eye: the `--brief`
summary on the bundled example case is 1,868 characters and is computed locally,
which is to say free. The owner's measurement on a live case, 4 August 2026: the
old start-of-session ritual pulled in roughly 34,900 characters, and paid for them
again on every following call.
---
## 6. What it does not do, and where you are still required
Without this section everything above would be advertising.
**It does not replace a lawyer and it decides nothing about your case.** It reads,
cross-checks, researches, drafts and checks form. What position to take, what to
file and when, remains yours. No document leaves for a court on its own.
**It stops and asks.** If an agent is missing, if the acceptance suite is red, if a
guard blocked a write, if spending ran past the expected envelope, work halts and
you are told. Quietly substituting a general-purpose model for a specialist is
forbidden.
**Scan recognition is macOS-only.** Apple Vision is an Apple system framework; on
Linux and Windows it does not exist. Text PDFs, DOCX and XLSX still read fine there;
scans and photographs of documents do not. The environment check does not paper over
this. It names the gap and the substitutions out loud, for instance moving scheduled
jobs from launchd to systemd timers and checking that the locale is UTF-8, without
which Cyrillic folder names arrive mangled.
**After installation the system is not ready yet, and it tells you so:**
```
$ python3 scripts/setup_doctor.py
✓ scan OCR (Apple Vision): bin/vision-doc responds
✓ legal corpus: Supreme Court Plenum rulings: 342 files
✗ legal corpus: codes: 0 files
→ fetch: python3 scripts/update_legal_corpus.py --init
Total: critical 1, warnings 0, checks 17.
SYSTEM NOT READY.
```
That is real output from a real machine, not an illustration. The corpus of statutes
has to be fetched once, by hand. Without it verbatim quotation of code provisions is
unavailable, and the court-fee calculator — which reads its rates from chapter 25.3
of the Tax Code — honestly answers "article 333.19 is not in the corpus" instead of
computing from memory.
**Case-law search depends on somebody else's website.** The free search hits an
external resource, and that resource goes down. On the day of this measurement it
was returning errors:
```
$ python3 scripts/practice_search.py "division of marital property" --law "38 SK RF"
... responded HTTP 500 — response discarded, not cached.
Nothing found. SEARCH DID NOT COMPLETE (timeout or source unavailable)
```
Notice what matters there: the tool said it had failed and invented nothing. Russia
has no free government API for court decisions. This was tested; the endpoints
either return errors or do not answer.
**Things you have to do yourself:** install Claude Code, build the recogniser during
setup, fetch the legal corpus, register your own Telegram bot if you want one, and —
above all — read the document before you file it. The reviewer catches form, figures
and citations. A missed limitation period and a provision that does not apply are
caught by a lawyer.
---
## 7. Privacy
**Case material never leaves your machine.** Client folders are excluded from
publication at the repository level; what goes up is templates and one synthetic
example. Extraction and recognition are local.
**The Telegram bot is a remote control, not a shop window.** It is optional: no
configuration, no bot, and the system runs regardless. When it is on, what goes out
is dates, counts and the word "done". Everything else is held back by an outbound
guard, and that is testable:
```
$ python3 scripts/themis_bot.py --check-out message.txt # "Hearing 25.09.2026 at 10:00, document ready"
clean — the bot will send this
$ python3 scripts/themis_bot.py --check-out other.txt # with a name, a case number and a sum
will not go out: PD (CASE), PD (NAME), PD (NAME?), sum (350 000 rub.)
```
The principle is worth saying plainly: anything sent to Telegram has been disclosed
to Telegram. So the bot does not forward documents. It hands you a link back into
your own network. Voice notes are transcribed on your machine, because dictation is
full of names and amounts.
**What goes out for research goes out redacted**, through the gate described above,
the one that refuses to report "clean" when it found nothing.
**Working logs stay local.** Case names appear in them as a matter of course, which
is fine; what would not be fine is those logs reaching the repository, and a separate
check watches exactly that.
---
## Further reading
- [README](../README.md) — the short version, and how to install.
- [`scripts/setup_doctor.py`](../scripts/setup_doctor.py) — an honest answer to
"what is broken on my machine".
- [`scripts/themis_status.py`](../scripts/themis_status.py) — where am I in this case.
- [Русская версия](HOW-IT-WORKS.ru.md).
+468
View File
@@ -0,0 +1,468 @@
# Как Фемида работает на самом деле
Это не витрина, а разбор внутренностей. Всё, что здесь написано, проверено запуском
на машине 21.08.2026, и команды стоят рядом с утверждениями, чтобы вы могли
повторить и не поверить на слово. Там, где что-то не работает или требует ваших
рук, так и написано: отдельным разделом в конце.
Читатель — практикующий юрист, а не программист. Терминов ровно столько, сколько
нужно, чтобы понять, за что вы отвечаете, а за что машина.
---
## 1. Что происходит, когда вы приносите дело
Дело — это папка. Внутри две половины: одна повёрнута к человеку, вторая к машине.
```
cases/<клиент>/<дело>/
_case.md карточка дела — её читаете вы
00_intake/ то, что принёс доверитель. Неприкосновенно
02_hearings/ события и уже поданные документы
GOTOVO/ готовые документы — то, за чем вы сюда пришли
.agent/ кухня: карта дела, практика, позиция, черновики
```
`.agent/` спрятана под точку намеренно: разглядывать черновой процесс — не ваша
работа. Раскладка задана одним файлом ([`scripts/case_paths.py`](../scripts/case_paths.py)),
а не разбросана по коду, поэтому все агенты понимают её одинаково.
Дальше работа идёт по шагам, и порядок здесь не пожелание.
**Шаг 0. Своя база.** Прежде чем куда-то идти, система смотрит, не решала ли она
уже такой вопрос: `knowledge/practice_index.md`. Если решала, берёт готовое.
У нового пользователя этот индекс пуст: он не поставляется с репозиторием, а
накапливается по мере работы, и чем дольше вы работаете, тем чаще шаг 2
пропускается целиком.
**Шаг 1. Карта дела.** Агент-картограф читает материалы и сводит их в один файл:
факты, стороны, предмет, хронология, доказательства. Пока карты нет, дальше
хода нет.
**Шаг 2. Практика.** Охотники ищут судебную практику. На сложном деле их трое, и
они спорят между собой (об этом ниже). Итог — `practice.md`.
**Шаг 3. Позиция.** Совет юристов вырабатывает правовую позицию — `positions.md`.
**Шаг 4. Документ.** Составитель пишет `.md`, опираясь на карту, практику и позицию.
**Шаг 5. Проверка.** Рецензент разбирает документ по семи блокам и выносит вердикт.
`.docx` собирается один раз — после «ГОТОВ К ПОДАЧЕ» — и ложится в `GOTOVO/`.
Где вы находитесь, показывает одна команда, а не чтение полудюжины файлов:
```bash
python3 scripts/themis_status.py cases/<клиент>/<дело> --brief
```
Она печатает реквизиты, ближайшее заседание, объём материалов, состояние всех
шагов и — главное — строку «СЛЕДУЮЩИЙ ШАГ». Это не подсказка, а единственный
разрешённый следующий шаг.
**Через шаг перепрыгнуть физически нельзя.** Не «не рекомендуется» — нельзя.
Попытка записать позицию до того, как готова практика:
```
$ echo '{"tool_name":"Write","tool_input":{"file_path":"cases/testfam-ab/delo-2026/.agent/context/positions.md"}}' | python3 scripts/claude_guard.py
БЛОК ПРОТОКОЛА: positions.md пишется только после Шага 2 — в practice.md нет
ни «## СОВЕТ ЗАВЕРШЕН», ни «## FAST-СИНТЕЗ ФЕМИДЫ».
```
Причина простая: текстовую инструкцию модель исполняет вероятностно, а сторож
всегда. Всё, что объявлено железным правилом, держит код.
---
## 2. Чем читаются материалы и почему это ничего не стоит
Всё извлечение идёт на вашей машине. За распознавание никто не платит и никуда
ничего не отправляется.
**Сканы распознаёт Apple Vision**, тот же движок, что в macOS достаёт текст из
картинки. Он собран в [`bin/vision-doc`](../bin) и вызывается локально.
Замер на трёх страницах А4 (200 dpi, русский текст):
```
$ /usr/bin/time -p bin/vision-doc page-1.png
real 1.62 # дальше 1.31 и 1.33
```
Порядка полутора секунд на страницу. Русский берёт дословно: на контрольной
странице из сорока строк совпали все сорок. Разошёлся только знак `№`: Vision
отдал его как `Nº`.
**Текстовые документы не распознаются вовсе.** Если внутри PDF, docx или xlsx уже
лежит текстовый слой, его просто достают. Быстрее и точнее любого OCR.
Кто из двух путей нужен, решает не человек, а роутер
[`scripts/markdown_extract.py`](../scripts/markdown_extract.py). Он смотрит файл и
объявляет маршрут:
```
$ python3 scripts/markdown_extract.py dogovor.pdf --json-meta
{"route": "text-pdf", "pages": 3, "cache": "miss", ...}
```
```
$ python3 scripts/markdown_extract.py skan.pdf --json-meta --render-dir /tmp/delo
{"route": "scan", "ocr_pages": 3, ...
"note": "Apple Vision OCR (локально, $0): 3 стр → page_NNN.txt (0 пустых)"}
```
Каждая страница скана ложится отдельным файлом `page_001.txt`, `page_002.txt` и
так далее. Это не педантизм: так в документе можно честно написать «страница 82»
и знать, что там действительно она.
**Смешанный PDF не теряет страниц.** Когда полдокумента — текст, а полдокумента —
вклеенный скан, текстовые страницы берутся текстом, а скан-страницы дораспознаются.
Ни одна не выпадает молча.
**Реквизиты система вынимает сама.** Рядом с извлечённым текстом кладётся файл с
находками — ИНН, ОГРН, номера дел, суммы, паспорта, счета:
```
"requisites": {"inn": ["7707083893"], "case_soyu": ["2-45/2026"]}
```
Их не приходится выискивать глазами по тексту.
**Повторное чтение бесплатно, и это измеримо.** Результат кладётся в кеш
`~/.cache/legal_extract` под отпечатком файла. Тот же файл второй раз:
```
первый вызов: real 2.04 "cache": "miss"
второй вызов: real 0.19 "cache": "hit"
```
Ноль обращений к модели, десятая доля секунды. Поэтому перечитывать материалы дела
не страшно. Страшно распознавать их заново, а этого система не делает.
### Когда она всё-таки идёт в облако
Три случая, и все три — точечные:
1. распознавание вернуло пустую или явно мусорную страницу;
2. спорный критичный реквизит — номер дела, ИНН, сумма, ФИО — нужно сверить глазами;
3. рукопись, печать, угасший текст.
Всё остальное идёт локально. Если локальный движок вдруг недоступен, система
останавливается и говорит об этом, а не переключается на облако молча. Тихая
деградация хуже отказа: вы бы не узнали, что счёт вырос, а качество упало.
---
## 3. Кто такие агенты и зачем их много
Агент — это роль с узкой задачей и своим набором инструментов. Их тринадцать
(`ls .claude/agents/` — ровно тринадцать файлов), и разделены они не для красоты.
**Канцелярия** забирает новые материалы из входящей папки и кладёт их в дело.
**Картограф** строит карту дела. На сложном деле он не читает всё сам, а
раздаёт материалы читателям.
**Три читателя** — по типу материала: скан-PDF, картинка, текстовый документ.
Разделены потому, что у каждого свой источник правды и своя цена ошибки.
**Сверщик** сличает отчёты читателей между собой: реквизиты, даты, ФИО, суммы.
Если два читателя увидели в документе разные суммы, дальше это не поедет.
**Три охотника за практикой — и вот здесь начинается интересное.**
Классик строит позицию за вас. Скептик ищет практику *против* вас: он думает как
лучший адвокат оппонента и собирает карту рисков с контраргументом на каждый.
Тактик занимается процессуальным — давность, доказательства, подсудность.
Смысл в том, что они не согласуют выводы между собой. Одна модель, которой велено
«найти практику», найдёт подтверждающую: так устроен любой поиск под задачу.
Три роли с несовпадающими интересами дают вам то, что вы услышите от оппонента,
до того, как услышите это в заседании.
**Совет из пяти правоведов** спорит о позиции в несколько раундов и сводит спор
в один документ.
**Составитель** пишет документ. **Рецензент — отдельный агент**, и это принципиально:
тот, кто писал, свой текст не проверяет. Проверяющий читает документ заново, по
чек-листу из семи блоков, и выносит вердикт.
**Готовящий к заседанию** собирает пакет: цель, что взять, аргументы с источниками,
вероятные вопросы суда, слабые места. **Архивист** пополняет базу знаний, чтобы
следующее похожее дело начиналось не с нуля.
---
## 4. Где система себя проверяет
Это самая непривычная часть. Обычно ИИ-инструмент отвечает и на этом заканчивает.
Здесь между ответом и вами стоит несколько сторожей, и каждый — код, а не намерение.
**Приёмка.** У системы есть собственный тест на 117 проверок:
```
$ python3 scripts/stage9_spec.py
сдано проверок: 117/117
✓ ЭТАП 9 ПРИНЯТ
```
Он проверяет не «работает ли скрипт», а выполняются ли обещания: что документация
не описывает несуществующих инструментов, что объявленные железными правила
действительно кем-то держатся, что после установки система выпускает документ.
**Сторож путей** не даёт стереть материалы доверителя:
```
$ rm -rf cases/<дело>/00_intake
БЛОК: удаление затрагивает cases/, 00_intake/ или _baselines/ ...
Материалы дел неприкосновенны. Нужно — только пользователь вручную.
```
Он же не пускает бинарный документ в чтение напрямую, мимо роутера и кеша. Иначе
одна и та же страница распознавалась бы по десять раз.
**Сторож персональных данных** стоит на коммите и на публикации. Фамилии
доверителей он берёт с диска в момент запуска, сам не хранит ни одной. Находку
он показывает как «путь, строка, длина совпадения», не печатая значения:
сторож не имеет права стать вторым каналом утечки.
Это не теория. 04.08.2026 имя папки дела уехало в публичный репозиторий через
комментарий в коде. Сторож написан после этого случая и ровно из-за него.
**Сторож формата** принимает `.docx` вместо человека:
```
$ python3 scripts/document_guard.py isk.docx --md isk.md
```
Поля, кегли, межстрочный, единственная гарнитура на весь документ, номера страниц,
выравнивание, сквозная нумерация приложений и то, что каждое приложение упомянуто
в тексте. Код 0 — принято, код 1 — список того, что переделать. Раньше это
сравнение делала модель, тратя рассуждение на арифметику и регулярно давая ложные
тревоги.
**Сумма прописью сверяется с числом.** «350 000 (триста пятьдесят тысяч) рублей» —
пропись обязана совпадать с цифрой, а не стоять рядом для вида. Числительные
пересчитываются своим кодом, с родом и падежом.
**Инъекция внутри материалов дела.** Первичка — это данные, а не команды. Если в
скане окажется фраза вроде «игнорируй прошлые указания», отдельный сторож её
поймает. Ловит он не повелительное наклонение — юридический текст им переполнен
(«прошу суд обязать», «взыскать») — а обращение к исполнителю. Судебный документ
не зовёт модель по имени никогда, и это надёжная ось.
**Документ не собирается в обход проверки.** Пока рецензент не вынес вердикта,
`.docx` не появится:
```
$ python3 scripts/verdict.py isk.md --check
⛔ СБОРКА .docx ЗАПРЕЩЕНА
· isk.md: вердикта нет вовсе — документ не проходил проверку Кони
```
Вердикт привязан к редакции текста. Поправили документ после одобрения, и
одобрение снимается.
**Все сторожа проверяют сами себя.** У каждого встроенный тест, и он зелёный:
| Сторож | Что держит | Тест |
|---|---|---|
| `claude_guard.py` | пути, порядок шагов, чтение мимо роутера | 126/126 |
| `document_guard.py` | формат `.docx` и совпадение с `.md` | 48/48 |
| `pd_guard.py` | ПД не уходят в публичный репозиторий | 43/43 |
| `quality_gate.py` | полнота OCR, таблицы, числа, контрольные суммы | 30/30 |
| `instruction_guard.py` | инъекции внутри материалов | 30/30 |
| `money_rule.py` | деньги, валюты, цитаты | 18/18 |
| `table_guard.py` | потерянные таблицы | 5/5 |
| `pii_gate.py` | обезличивание перед выходом наружу | fail-closed |
`pii_gate` отдельно стоит объяснить. Он обезличивает текст, если фрагмент дела
надо отправить наружу. И если он ничего не нашёл, он не говорит «чисто», а
отказывается работать. Юридический текст почти всегда содержит хотя бы одно ФИО;
пустой результат чаще значит «поиск не сработал», чем «искать было нечего».
---
## 5. Почему это дёшево
Не потому, что модель дешёвая, а потому, что её зовут реже.
**Дело сортируется по сложности до начала работы.** Три режима. Типовой документ
по уже решённому вопросу не гоняют как кассацию в Верховный Суд: карта не строится,
реквизиты берутся готовыми, охотники не запускаются вовсе. Простое дело — один
охотник вместо трёх и без советов. Сложное — полный состав. Сомнение решается в
пользу более дешёвого режима, а подниматься можно всегда.
**Модель шага выводится из уровня дела, а не прибита к агенту.** Составитель по
умолчанию работает сильнейшей моделью, потому что на серьёзном деле это самая
ответственная работа. Но на типовом документе тот же выбор означал бы
пятикратную цену за ту же страницу. Поэтому уровень решает
[`scripts/model_policy.py`](../scripts/model_policy.py), а не привычка:
| Работа | Простое дело | Сложное дело |
|---|---|---|
| составление документа | средняя модель | сильная |
| проверка документа | средняя | сильная |
| охота за практикой | не запускается | средняя |
| роли в совете | не запускается | средняя, председатель — сильная |
| чтение текста, сортировка | дешёвая | дешёвая |
Сбор и механика — дешёвой моделью. Синтез, составление и финальный пас — сильной.
**Что может посчитать обычная программа, модели не поручают.** Это самая крупная
экономия, и она же самая скучная.
Проценты по статье 395 ГК считает код: с таблицей ключевой ставки, разбивкой по
периодам и суммой прописью.
```
$ python3 scripts/calc395.py --dolg 350000 --s 01.02.2026 --po 01.08.2026
01.02.2026 — 15.02.2026 15 дн. 16.00% /365 2 301.37
...
ИТОГО процентов: 25 911,99 (двадцать пять тысяч девятьсот одиннадцать рублей
девяносто девять копеек)
```
Процессуальный срок — тоже код, и со ссылкой на норму:
```
$ python3 scripts/sroki.py --ot 21.08.2026 --mesyacev 1
течение срока начинается 22.08.2026 [ч. 3 ст. 107 ГПК РФ]
плюс 1 мес. → 21.09.2026 [ч. 1 ст. 108 ГПК РФ; п. 16 Пленума ВС РФ
от 22.06.2021 № 16]
ПОСЛЕДНИЙ ДЕНЬ СРОКА: 21.09.2026 (понедельник)
```
ИНН проверяется контрольной суммой локально, без сети и без копейки затрат.
Подменённая при распознавании цифра почти никогда не даёт валидную сумму:
```
$ python3 scripts/verify_inn.py 7707083893
7707083893: валиден · ок
$ python3 scripts/verify_inn.py 7707083894
7707083894: НЕВАЛИДЕН · ОШИБКА РЕКВИЗИТА — такого ИНН не существует
```
Постановления Пленума цитируются с диска, дословно, без похода в интернет:
```
$ python3 scripts/cite.py "п. 21 Пленума ВС РФ от 19.06.2012 № 13"
### п. 21
Судам необходимо учитывать, что по смыслу статьи 327 ГПК РФ...
Источник: knowledge/plenumy/plenum-ot-19062012.md
Для вставки: (Постановление Пленума Верховного Суда РФ от 19.06.2012 N 13, п. 21)
```
Корпус не приезжает вместе с репозиторием. Вы выгружаете его к себе одной
командой (`python3 scripts/update_legal_corpus.py --plenums`), после чего он лежит
у вас и обновляется раз в месяц фоновым заданием. На машине, где делался этот
замер, в нём 342 постановления.
Дело не в одних деньгах. Однажды пересказ нормы из интернета исказил текст
статьи 683 ГК, и с тех пор нормы берутся с диска или не берутся вовсе.
**Прочитанное не перечитывается.** Открытый файл остаётся в работе до конца
сессии, и каждое следующее обращение к модели оплачивается вместе с ним. Поэтому
состояние дела спрашивают у программы, а не вычитывают глазами: сводка `--brief`
по делу-примеру занимает 1 868 знаков и считается локально, то есть даром.
Замер владельца от 04.08.2026 на боевом деле: прежний ритуал старта заносил
около 34 900 знаков, и они переоплачивались каждым следующим вызовом.
---
## 6. Чего система не делает и где нужны вы
Без этого раздела всё вышенаписанное было бы рекламой.
**Она не заменяет юриста и не принимает решений по делу.** Она читает, сверяет,
ищет практику, пишет черновик и проверяет форму. Решение о позиции, о том, что
подавать и когда, остаётся за вами. Ни один документ не уходит в суд сам.
**Она останавливается и спрашивает.** Если агента нет на месте, если приёмка
красная, если сторож заблокировал запись, если расход вышел за ожидаемый, работа
встаёт и вам об этом говорят. Молча подменять специалиста обычной моделью
запрещено.
**Распознавание сканов работает только на macOS.** Apple Vision — системный
фреймворк Apple, на Linux и Windows его нет. Текстовые PDF, DOCX и XLSX там
читаются по-прежнему, а сканы и фото документов — нет; притворяться, что есть,
нечестно. Проверка окружения это не замалчивает, а называет вслух вместе с
заменами — например, фоновые задания там придётся перенести с launchd на
systemd-таймеры, а локаль проверить на UTF-8, иначе кириллические имена папок
приезжают битыми.
**После установки система ещё не готова, и сама вам это говорит.** Проверка
окружения выдаёт честный список:
```
$ python3 scripts/setup_doctor.py
✓ OCR сканов (Apple Vision): bin/vision-doc отвечает
✓ корпус права: Пленумы ВС РФ: 342 файлов
✗ корпус права: кодексы: 0 файлов
→ выгрузить: python3 scripts/update_legal_corpus.py --init
Итого: критично 1, предупреждений 0, проверок 17.
СИСТЕМА НЕ ГОТОВА.
```
Это вывод с реальной машины, не пример. Корпус кодексов надо выгрузить один раз
руками. Без него дословные цитаты статей не отдаются, а расчёт госпошлины,
который берёт ставки из главы 25.3 НК, честно отвечает «нет статьи 333.19 в
корпусе» вместо того, чтобы посчитать по памяти.
**Поиск практики зависит от чужого сайта.** Бесплатный поиск ходит на внешний
ресурс, и ресурс бывает недоступен. В день этого замера он отвечал ошибкой:
```
$ python3 scripts/practice_search.py "раздел совместно нажитого имущества" --law "38 СК РФ"
... ответил HTTP 500 — ответ отброшен, не кеширую.
Ничего не найдено. ПОИСК НЕ ЗАВЕРШЕН (таймаут либо источник недоступен)
```
Обратите внимание, что здесь важно: инструмент сказал «не завершён» и ничего не
выдумал. Бесплатного государственного API для судебной практики в России нет:
проверялось, отвечают ошибками или не отвечают вовсе.
**Своими руками нужно:** поставить Claude Code, собрать распознаватель при
установке, выгрузить корпус права, завести своего Telegram-бота, если он нужен,
и — самое главное — прочитать документ перед подачей. Рецензент ловит форму,
числа и ссылки; месяц пропущенного срока и неприменимость нормы ловит юрист.
---
## 7. Приватность
**Материалы дел не покидают вашу машину.** Папки доверителей закрыты от
публикации на уровне репозитория; наверх уходят только шаблоны и один
синтетический пример. Извлечение и распознавание — локальные.
**Telegram-бот — пульт, а не витрина.** Он не обязателен: нет настройки — нет
бота, система работает. Если он включён, наружу уходят даты, счёт и слово
«готово». Всё остальное держит сторож на выходе, и это проверяется:
```
$ python3 scripts/themis_bot.py --check-out soobshenie.txt # «Заседание 25.09.2026 в 10:00, документ готов»
чисто — такой текст бот отправит
$ python3 scripts/themis_bot.py --check-out drugoe.txt # с фамилией, номером дела и суммой
наружу не уйдёт: ПД (ДЕЛО), ПД (ФИО), ПД (ФИО?), сумма (350 000 руб.)
```
Логика здесь простая и стоит того, чтобы её произнести: всё, что ушло в Telegram,
разглашено Telegram. Поэтому документ бот не пересылает, а даёт ссылку внутрь
вашей сети. Голосовые расшифровываются на вашей машине: в надиктовке звучат
фамилии и суммы.
**Наружу за практикой уходит обезличенный текст.** Перед выходом фрагмент проходит
через маскировку, и, как сказано выше, она устроена так, что молчаливого «чисто»
не бывает.
**Рабочие журналы остаются локальными.** В них имена дел пишутся по работе, и это
нормально; ненормально было бы, если бы они уехали в репозиторий, и отдельная
проверка следит именно за этим.
---
## Что почитать дальше
- [README](../README.md) — короткая витрина и установка.
- [`scripts/setup_doctor.py`](../scripts/setup_doctor.py) — честный ответ на вопрос
«а что у меня не работает».
- [`scripts/themis_status.py`](../scripts/themis_status.py) — где я в этом деле.
- [English version](HOW-IT-WORKS.en.md).