feat(assessment): find the attempt behind a leaked task text

This commit is contained in:
shira committed 2026-10-11 13:19:38 +03:00
1 parent bb917bf62e
commit 5a731c25b7
26 files changed
+2500

No files matched your search

+10
View File
@@ -725,6 +725,16 @@ Implemented for real attempts (root and corrective). A training run (`demo_expre
- Limits of the rule. It is a one-page-at-a-time rule, not a security boundary: a client that never holds the session is refused only while another page holds it, a candidate can always continue after the hold is released or has expired, and two windows of one candidate are not told from two people. The hold is renewed by a page timer, so a browser that throttles a background tab to one tick a minute still renews within the two minutes.
- Operator reading. `make -C backend assessment-review ARGS='inspect ...'` prints the new counts `extra_agents`, `client_screenshot_keys`, and `client_devtools_opens` next to the old ones; the note at its end repeats that browser signals can be forged and that a screenshot or a phone photo cannot be prevented or seen by the page.
### Leak trace
Implemented as a local operator command, `assessment-leak-trace`, that finds the real attempt behind a leaked task text. It reads text and nothing else: a screenshot or a photo must be read by an OCR tool first, and OCR itself is outside this project (the command accepts any UTF-8 text of at most 64 KiB from a file or standard input, and a visible code that the operator read by eye). The result is a hint for a manual review and an appeal. It is never shown to an employer (no HTTP operation serves it), it changes no score, category, or quota (the command writes nothing but its own audit), and it never names an attempt on a guess. Code: `backend/cmd/assessment-leak-trace/`, `backend/internal/adapter/primary/cli/leaktrace/command.go`, `LeakTracer` in `backend/internal/usecase/assessment/leak_trace.go`, `AssessmentLeakAlignment` and `AssessmentTextPiecesBetweenPhrases` in `domain/assessment_wording.go`, `domain/assessment_leak_trace.go`, migration `backend/db/migrations/00051_create_assessment_leak_traces.sql`, and the queries `backend/db/queries/assessment_leak_traces.sql`.
- Methods, strongest first. (1) The invisible mark: intact runs of zero-width characters decode to the code of an attempt (50 keyed bits), so one attempt behind one code is a finding on its own. (2) The visible code: the code of the tile, found in the text of a screenshot as two groups of five characters (or ten characters followed by the date and time of the tile) or given with `--code`; one character that the recognizer misread is tolerated (45 bits), two are not. The time on the tile is compared with the life of the attempt (an hour of slack) and reported as a note, never as a verdict, because it is the clock of a device. (3) The statement and its wording: the stored, unmarked statements of real attempts are searched for pieces of the text, the attempts that were served that statement are told apart from other variants of the same family by how far the text follows their statement, and among those by the phrase forms the text shows (about one bit per phrase group; only the phrases aligned with the stored statement are read, so words around the statement in a message are ignored). A statement counts only when the text is a copy of it, whole or cut where the text stops: other words where the statement continues mean that another variant of the same family, which shares only its fixed text, is not the source. A statement text that only one attempt was served names that attempt by the variant alone when the text shows no phrase group, and is excluded when the text shows phrases that contradict the attempt, because the leak may come from an attempt that was deleted.
- The code of an attempt is computed, never stored, so no lookup table exists: the command walks every real attempt (5000 per page), computes its code from `IDENTITY_KEY_SECRET`, and compares. The work is linear in the number of attempts and fine for an operator command. The command therefore needs the secret of the server that served the attempts; a rotated secret makes older codes and marks unreadable, and then the search can still use the statement text.
- Outcomes. `found` names one attempt, the method, and the strength in bits, with notes such as whether the statement text matches the attempt (a mark attached to another text is flagged). `ambiguous` means that the evidence leaves several attempts in play (two attempts behind the codes, a mark and a visible code that name different attempts, or attempts that were served the same statement and chose the same phrases) and names none. `not_found` is an honest answer when the data is not enough: no mark, no code, no stretch of at least 24 characters free of interchangeable phrases, no statement that contains the text, a text that more than 200 statements contain (generic), or a wording that contradicts every holder.
- Audit. Every search writes one row to `assessment_leak_traces` in the same transaction as the search, before a result is printed: the operator handle (`operator:<handle>`, not authentication), the database time, a keyed digest of the normalized text (HMAC-SHA-256 under a key derived from `IDENTITY_KEY_SECRET`, label `lincodex/assessment/leak-text/v1`), its length, the outcome, the method, the attempt for a found search, and the counts. The text is never stored or printed, the table refuses UPDATE, DELETE, and TRUNCATE, and the attempt is not a foreign key, so the audit outlives an account deletion. Rolling migration 51 back is refused while the audit holds a row.
- What it cannot do. A leak with the mark and the tile gone, retyped in own words, or photographed so that no tile is legible leaves only the wording and the variant, which name one attempt only when few attempts were served the same statement. The text of a screenshot depends on the OCR tool. A text that was edited breaks the alignment. A watermark cannot prevent a leak, and the result is evidence for a person, not a decision. The command and its audit are described in [Operating the leak trace](DEPLOY.md#leak-trace).
### Skill evidence
Implemented as a stored projection of the immutable assessment results, with two reads: the candidate's own list and the permitted projection of a currently visible card. The match search reads the organization projection (see [Matching and explanations](#matching-and-explanations)); no percentile reads it yet.
+17
View File
@@ -445,6 +445,23 @@ make -C backend assessment-review ARGS='inspect --attempt <uuid> --actor operato
- To use thresholds other than the demo values, publish a policy version with an `assessment.signals` section through the policy publisher. `DemoProductPolicyV3` is the demo example and is published only explicitly (the isolated browser fixture does so); the startup seed publishes version 1 only. Attempts that already started keep the version they started with. The demo duplicate thresholds assume a population: a copied pair is flagged only from about 26 answers per family (attention) and 61 (review) at 13 items, or 9 and 14 at 23 items. To try the feature on a smaller stand, publish a policy version with lower `duplicate_bits_attention` and `duplicate_bits_review` (the integration tests use 4 and 6); do not edit the demo policy. A review is a point-in-time evaluation, run again by the job at the deadline. The job logs one line per run with the number of reviews and its duration (`assessment review job finished`).
- The rows hold counts, durations, and keyed digests (HMAC-SHA-256 under keys derived from `IDENTITY_KEY_SECRET`, each with a key version) and no answer text. Rotating the secret keeps the stored rows but makes new fingerprints incomparable with old ones. Deleting an account deletes its attempts and, by cascade, their facts and reviews; the audit rows keep only the attempt ID and the handle. The digests are kept for the lifetime of the attempt; no retention period is defined yet.
## Leak trace
An operator finds the attempt behind a leaked task text with a local command (see [ARCHITECTURE.md](ARCHITECTURE.md#leak-trace) for how it decides). It takes text; a screenshot has to be read by an OCR tool first, which is not part of this project:
```sh
make -C backend assessment-leak-trace ARGS='search --actor operator:<handle> --file leaked.txt'
pbpaste | make -C backend assessment-leak-trace ARGS='search --actor operator:<handle> --stdin'
make -C backend assessment-leak-trace ARGS='search --actor operator:<handle> --code 7K3QD-9XM2T'
```
- The command needs `DATABASE_URL` and `IDENTITY_KEY_SECRET`, and reads nothing else from the environment or a dotenv file. The secret must be the one of the server that served the attempts: the codes and marks are computed from it, so a different secret finds nothing, and the command refuses an unset, placeholder, or short secret and never prints it. `make -C backend assessment-leak-trace-build` builds `backend/bin/assessment-leak-trace`.
- Put the text in a file or on standard input, not in a command-line argument, so that it stays out of the shell history and the process list. The text is at most 64 KiB of UTF-8; a longer one is refused, and a document can be searched in pieces. `--code` takes a visible code that was read from a screenshot by eye, with or without the hyphen and in either case.
- It prints the search ID, `found`, `ambiguous`, or `not_found`, and for a found search the method (`invisible_mark`, `visible_code`, `wording`, or `variant`), the attempt ID, and the strength in bits, with notes that never quote the text. `not_found` is a normal outcome, not an error: the data was not enough to name an attempt.
- Every search is recorded in `assessment_leak_traces` (operator handle, database time, a keyed digest and the length of the text, the outcome, the method, the attempt of a found search, and counts) before a result is printed, whatever it finds. The table refuses UPDATE, DELETE, and TRUNCATE, keeps no text, and outlives the attempt it names. The handle is an audit label, not authentication: any holder of the database credential can type any handle. Rolling migration 51 back is refused while the audit holds a row.
- The result goes to the operator only. No HTTP operation serves it, an employer never sees it, and it changes no score, category, or quota. It is a hint for a manual review and an appeal, not a decision.
- The command reads every real attempt to compute its code and searches the stored statements, so it is meant for an operator and not for a request path; its cost grows linearly with the number of attempts.
## Demonstration categories on a stand
A category from a `demo_basic` result is assigned only on an isolated synthetic stand. It is not calibrated and must not appear in an environment with real candidates. Two independent steps enable it on a stand:
+4
View File
@@ -558,6 +558,10 @@ Over HTTP with PostgreSQL. `TestAssessmentWorkSessionOverHTTP` creates a real at
Frontend. Vitest covers the key rules (`capture-keys.test.ts`), the heuristic and its watcher with fake windows and timers (`devtools-heuristic.test.ts`), the collector (one event for a press and its release, no cancelling, no event without an item), the session wiring of the watcher, the work session controller (held, busy, lost at a renewal, a network gap, a release during a renewal, the renewal bounds, `work-session.test.ts`), the page identifier header of the answer command, and the notice version 4 text. `e2e/assessment-capture.spec.ts` runs against the mocked API (also on the Vite server, `E2E_BASE_URL=http://localhost:5173 pnpm exec playwright test e2e/assessment-capture.spec.ts --project=chromium`): PrintScreen and Cmd+Shift+4 are recorded as `screenshot_key` events with no key or image, the key event is not cancelled and the test goes on to an answer; a faked docked panel is recorded as `devtools_open`; a second tab opened on the attempt is refused with the explanation and shows no task, nothing is started in it, the first tab is undisturbed, and after the first tab leaves the second continues; `pagehide` releases the session; a tab that loses the session at a renewal stops and says so. These tests do not show behavior in other browsers or on a phone, whether the operating system hands a shortcut to the page, what a real screenshot looks like, or how often the heuristic is wrong on real windows; the mock server stands for the rules of the real one, which the HTTP test covers.
## Assessment leak trace tests
`backend/internal/usecase/assessment/leak_trace_test.go` runs the tracer against in-memory repositories with real watermarks: the leaked text of a variant, among other words, finds the right one of three attempts that were served the same statement (by the invisible mark); with the invisible characters removed, the visible code of the tile text finds the attempt, and the wording alone separates the attempts that were served the same statement and chose different phrases; the visible code tolerates one misread character and not two; unrelated text, a text that is too short, and a mark of no attempt are not found and say why; a statement that only one attempt holds is found by the variant and excluded when its wording contradicts the text; attempts that chose the same phrases, or a text with no phrase group, are ambiguous without naming one; a mark attached to another text is found and flagged; a mark and a visible code that name different attempts are ambiguous; another variant of the same family does not compete with the leaked one, and the leak of a deleted attempt is not attributed to the variant of its family that is left; a leak cut inside the statement is found, while other words where the statement continues are not; every search is audited with a keyed digest and no part of the text, the same text gives the same digest, and a failed audit fails the search; bad requests are refused without quoting the text. `domain/assessment_watermark_test.go` covers the alignment and the wording agreement (only the phrases aligned with the stored statement are read, a fragment, unrelated text, another variant aligning for fewer characters), `domain/assessment_leak_trace_test.go` the audit record, `usecase/identity/keyring_test.go` the keyed text digest, `config/identity_test.go` the secret reader, and `adapter/primary/cli/leaktrace/command_test.go` the argument rules, the file and standard input reading with its limit, the output (the outcome and fixed notes, never the text, an honest not found), safe error messages, and that the environment is not read before the arguments are valid. `TestAssessmentLeakTraceOverHTTP` (PostgreSQL) creates two real attempts over HTTP and checks that the marked prompt finds the first by its mark, the prompt without invisible characters finds the second by its statement, the text of a screenshot with the tile finds the first by its visible code and the tile time, unrelated and short text are not found, a search changes no attempt version or state and no review or result, every search is audited without the text, the audit refuses UPDATE, DELETE, and TRUNCATE and a found row without an attempt, the audit outlives a deleted attempt (which is then not found), and the command with the secret of the server finds the attempt while one with another secret does not read the mark. They do not run an OCR tool, so what the command does with the real recognition errors of a screenshot, and how well the wording separates attempts on a real bank, are not measured here.
## Internal notification tests
Unit tests (`make -C backend test`, `make -C frontend test`):
+10
View File
@@ -725,6 +725,16 @@ contact_grant относится к паре кандидат-компания
- Пределы правила. Это правило "одна страница за раз", а не граница безопасности: клиент, который никогда не занимает сеанс, получает отказ только пока его занимает другая страница, кандидат всегда может продолжить после освобождения или истечения, а два окна одного кандидата не отличаются от двух людей. Занятие продлевает таймер страницы, поэтому браузер, который замедляет фоновую вкладку до одного такта в минуту, все равно продлевает его в пределах двух минут.
- Чтение оператором. `make -C backend assessment-review ARGS='inspect ...'` печатает новые счетчики `extra_agents`, `client_screenshot_keys` и `client_devtools_opens` рядом со старыми; примечание в конце вывода повторяет, что браузерные сигналы можно подделать и что снимок экрана или фото телефоном предотвратить нельзя и страница их не видит.
### Поиск источника утечки
Реализован как локальная операторская команда `assessment-leak-trace`, которая находит реальную попытку, из которой утек текст задания. Она читает текст и больше ничего: снимок или фото сначала должен прочитать инструмент распознавания текста, а само распознавание в проект не входит (команда принимает любой текст UTF-8 до 64 КиБ из файла или стандартного ввода и видимый код, который оператор прочитал глазами). Результат - подсказка для ручной проверки и апелляции. Его никогда не видит работодатель (ни одна HTTP-операция его не отдает), он не меняет балл, категорию и квоты (команда ничего не пишет, кроме собственного журнала) и никогда не называет попытку наугад. Код: `backend/cmd/assessment-leak-trace/`, `backend/internal/adapter/primary/cli/leaktrace/command.go`, `LeakTracer` в `backend/internal/usecase/assessment/leak_trace.go`, `AssessmentLeakAlignment` и `AssessmentTextPiecesBetweenPhrases` в `domain/assessment_wording.go`, `domain/assessment_leak_trace.go`, миграция `backend/db/migrations/00051_create_assessment_leak_traces.sql` и запросы `backend/db/queries/assessment_leak_traces.sql`.
- Способы, от сильного к слабому. (1) Невидимая метка: целые запуски символов нулевой ширины декодируются в код попытки (50 ключевых бит), поэтому одна попытка за одним кодом - находка сама по себе. (2) Видимый код: код плитки, найденный в тексте снимка как две группы по пять символов (или десять символов, за которыми идут дата и время плитки), либо переданный через `--code`; один символ, который распознавание прочитало неверно, допускается (45 бит), два - нет. Время на плитке сравнивается с временем жизни попытки (с запасом в час) и сообщается как примечание, но не как вердикт, потому что это часы устройства. (3) Условие и формулировки: в сохраненных условиях реальных попыток без метки ищутся куски текста, попытки, которым выдано это условие, отделяются от других вариантов того же семейства по тому, насколько далеко текст следует их условию, а среди них - по формам оборотов, которые показывает текст (около одного бита на группу оборотов; читаются только обороты, выровненные с сохраненным условием, поэтому слова вокруг условия в сообщении игнорируются). Условие учитывается, только если текст - его копия, целая или обрезанная там, где текст кончается: другие слова там, где условие продолжается, означают, что другой вариант того же семейства, у которого совпадает лишь неизменный текст, не является источником. Текст условия, выданный только одной попытке, называет эту попытку одним лишь вариантом, если в тексте нет групп оборотов, и исключает ее, если обороты текста противоречат попытке, потому что утечка могла прийти из удаленной попытки.
- Код попытки вычисляется и нигде не хранится, поэтому таблицы поиска нет: команда обходит все реальные попытки (по 5000 на страницу), вычисляет их коды из `IDENTITY_KEY_SECRET` и сравнивает. Работа линейна по числу попыток и приемлема для команды оператора. Поэтому команде нужен секрет сервера, который выдавал попытки; после смены секрета старые коды и метки нечитаемы, и поиск остается возможным только по тексту условия.
- Исходы. `found` называет одну попытку, способ и силу в битах с примечаниями, например совпадает ли текст условия с попыткой (метка, приклеенная к другому тексту, помечается). `ambiguous` означает, что доказательства оставляют в игре несколько попыток (две попытки за кодами, метка и видимый код, называющие разные попытки, или попытки, которым выдано одно условие и которые выбрали одинаковые обороты), и не называет ни одной. `not_found` - честный ответ, когда данных мало: нет метки, нет кода, нет куска минимум из 24 символов без взаимозаменяемых оборотов, нет условия, которое содержит текст, текст содержат больше 200 условий (общий) или формулировки противоречат каждой подходящей попытке.
- Журнал. Каждый поиск пишет одну строку в `assessment_leak_traces` в той же транзакции, что и поиск, до вывода результата: обозначение оператора (`operator:<handle>`, не аутентификация), время базы данных, ключевой отпечаток нормализованного текста (HMAC-SHA-256 под ключом, выведенным из `IDENTITY_KEY_SECRET`, метка `lincodex/assessment/leak-text/v1`), его длину, исход, способ, попытку для найденного поиска и счетчики. Текст никогда не хранится и не печатается, таблица отклоняет UPDATE, DELETE и TRUNCATE, а попытка не является внешним ключом, поэтому журнал переживает удаление аккаунта. Откат миграции 51 отклоняется, пока в журнале есть строка.
- Чего команда не умеет. Утечка без метки и плитки, пересказанная своими словами или сфотографированная так, что плитка не читается, оставляет только формулировки и вариант, которые называют одну попытку лишь тогда, когда одно условие выдано немногим попыткам. Текст снимка зависит от инструмента распознавания. Отредактированный текст ломает выравнивание. Водяной знак не может предотвратить утечку, а результат - доказательство для человека, а не решение. Команда и ее журнал описаны в [Работе с поиском источника утечки](DEPLOY.md#поиск-источника-утечки).
### Доказательства навыков
Реализовано как сохраняемая проекция неизменяемых результатов оценки с двумя чтениями: собственный список кандидата и разрешенная проекция сейчас видимой карточки. Проекцию для организации читает поиск (см. [Подбор и объяснение](#подбор-и-объяснение)); перцентиль ее пока не читает.
+17
View File
@@ -447,6 +447,23 @@ make -C backend assessment-review ARGS='inspect --attempt <uuid> --actor operato
- Чтобы использовать пороги, отличные от демо, опубликуйте версию политики с разделом `assessment.signals` через публикатор политик. `DemoProductPolicyV3` - демо-пример, он публикуется только явно (так делает изолированная браузерная фикстура); стартовый seed публикует только версию 1. Попытки, которые уже начались, сохраняют версию, с которой начались. Демо-пороги дубликатов рассчитаны на совокупность: скопированная пара помечается лишь примерно от 26 ответов на семейство («внимание») и 61 («проверить») при 13 заданиях или от 9 и 14 при 23. Чтобы попробовать функцию на меньшем стенде, опубликуйте версию политики с меньшими `duplicate_bits_attention` и `duplicate_bits_review` (интеграционные тесты используют 4 и 6); демо-политику не редактируйте. Проверка - оценка на момент, задание на дедлайне запускает ее снова. Задание пишет в журнал одну строку на запуск с числом проверок и длительностью (`assessment review job finished`).
- Строки хранят числа, длительности и ключевые дайджесты (HMAC-SHA-256 под ключами, выведенными из `IDENTITY_KEY_SECRET`, у каждого есть версия ключа) и не хранят текст ответа. Смена секрета сохраняет строки, но делает новые отпечатки несравнимыми со старыми. Удаление аккаунта удаляет его попытки и каскадом их факты и проверки; строки аудита хранят только идентификатор попытки и имя. Дайджесты хранятся столько же, сколько попытка; срок хранения пока не определен.
## Поиск источника утечки
Оператор находит попытку, из которой утек текст задания, локальной командой (как она решает, см. в [ARCHITECTURE.md](ARCHITECTURE.md#поиск-источника-утечки)). Команда принимает текст; снимок экрана сначала должен прочитать инструмент распознавания текста, который в этот проект не входит:
```sh
make -C backend assessment-leak-trace ARGS='search --actor operator:<handle> --file leaked.txt'
pbpaste | make -C backend assessment-leak-trace ARGS='search --actor operator:<handle> --stdin'
make -C backend assessment-leak-trace ARGS='search --actor operator:<handle> --code 7K3QD-9XM2T'
```
- Команде нужны `DATABASE_URL` и `IDENTITY_KEY_SECRET`, больше она ничего не читает из окружения и dotenv-файла. Секрет должен быть тем, которым пользовался сервер, выдавший попытки: коды и метки вычисляются из него, поэтому другой секрет ничего не найдет, а команда отклоняет незаданный, шаблонный или короткий секрет и никогда его не печатает. `make -C backend assessment-leak-trace-build` собирает `backend/bin/assessment-leak-trace`.
- Текст передавайте файлом или через стандартный ввод, а не аргументом командной строки, чтобы он не попал в историю оболочки и список процессов. Текст - до 64 КиБ UTF-8; более длинный отклоняется, документ можно искать частями. `--code` принимает видимый код, прочитанный со снимка глазами, с дефисом или без и в любом регистре.
- Команда печатает ID поиска, `found`, `ambiguous` или `not_found`, а для найденного поиска способ (`invisible_mark`, `visible_code`, `wording` или `variant`), ID попытки и силу в битах, с примечаниями, которые никогда не цитируют текст. `not_found` - обычный исход, а не ошибка: данных не хватило, чтобы назвать попытку.
- Каждый поиск записывается в `assessment_leak_traces` (обозначение оператора, время базы данных, ключевой отпечаток и длина текста, исход, способ, попытка найденного поиска и счетчики) до вывода результата, что бы он ни нашел. Таблица отклоняет UPDATE, DELETE и TRUNCATE, не хранит текст и переживает попытку, которую называет. Обозначение - метка журнала, а не аутентификация: любой владелец доступа к базе может ввести любое обозначение. Откат миграции 51 отклоняется, пока в журнале есть строка.
- Результат получает только оператор. Ни одна HTTP-операция его не отдает, работодатель его не видит, он не меняет балл, категорию и квоты. Это подсказка для ручной проверки и апелляции, а не решение.
- Команда читает все реальные попытки, чтобы вычислить их коды, и ищет по сохраненным условиям, поэтому она предназначена для оператора, а не для пути запроса; ее стоимость растет линейно с числом попыток.
## Демонстрационные категории на стенде
Категория по результату `demo_basic` присваивается только на изолированном синтетическом стенде. Она не калибрована и не должна появляться в рабочей среде с реальными кандидатами. Чтобы включить ее на стенде, нужны два независимых шага:
+4
View File
@@ -558,6 +558,10 @@ Vitest работает в Node без DOM, поэтому ограничени
Фронтенд. Vitest покрывает правила клавиш (`capture-keys.test.ts`), эвристику и ее наблюдателя с поддельными окнами и таймерами (`devtools-heuristic.test.ts`), сборщик (одно событие на нажатие и отпускание, без отмены, без события без задания), подключение наблюдателя к сеансу, контроллер рабочего сеанса (занято, свободно, потеряно при продлении, обрыв сети, освобождение во время продления, границы продления, `work-session.test.ts`), заголовок идентификатора страницы в команде ответа и текст версии 4 уведомления. `e2e/assessment-capture.spec.ts` работает с подставным API (и на сервере Vite, `E2E_BASE_URL=http://localhost:5173 pnpm exec playwright test e2e/assessment-capture.spec.ts --project=chromium`): PrintScreen и Cmd+Shift+4 записываются как события `screenshot_key` без клавиши и изображения, событие клавиши не отменяется, и тест доходит до ответа; подставная пристыкованная панель записывается как `devtools_open`; вторая вкладка с той же попыткой получает отказ с объяснением и не показывает задание, в ней ничего не начинается, первая вкладка не нарушена, а после ухода первой вкладки вторая продолжает; `pagehide` освобождает сеанс; вкладка, потерявшая сеанс при продлении, останавливается и говорит об этом. Эти тесты не показывают поведение в других браузерах и на телефоне, отдает ли операционная система сочетание странице, как выглядит настоящий снимок и как часто эвристика ошибается на настоящих окнах; подставной сервер изображает правила настоящего, которые покрывает тест HTTP.
## Тесты поиска источника утечки
`backend/internal/usecase/assessment/leak_trace_test.go` запускает поиск на репозиториях в памяти с настоящими водяными знаками: утекший текст варианта среди других слов находит правильную из трех попыток, которым выдано одно условие (по невидимой метке); без невидимых символов видимый код из текста плитки находит попытку, а одни формулировки различают попытки, которым выдано одно условие и которые выбрали разные обороты; видимый код допускает один неверно прочитанный символ, но не два; посторонний текст, слишком короткий текст и метка несуществующей попытки не находятся и объясняют причину; условие, выданное одной попытке, находится по варианту и исключается, если ее формулировки противоречат тексту; попытки с одинаковыми оборотами или текст без групп оборотов дают ambiguous без названия попытки; метка, приклеенная к другому тексту, находится с пометкой; метка и видимый код, называющие разные попытки, дают ambiguous; другой вариант того же семейства не конкурирует с утекшим, а утечка удаленной попытки не приписывается оставшемуся варианту ее семейства; утечка, оборванная внутри условия, находится, а другие слова там, где условие продолжается, - нет; каждый поиск попадает в журнал с ключевым отпечатком и без какой-либо части текста, один и тот же текст дает один отпечаток, а неудача записи в журнал проваливает поиск; неверные запросы отклоняются без цитирования текста. `domain/assessment_watermark_test.go` покрывает выравнивание и согласование формулировок (читаются только обороты, выровненные с сохраненным условием, фрагмент, посторонний текст, другой вариант, выравнивающийся на меньшее число символов), `domain/assessment_leak_trace_test.go` - запись журнала, `usecase/identity/keyring_test.go` - ключевой отпечаток текста, `config/identity_test.go` - чтение секрета, а `adapter/primary/cli/leaktrace/command_test.go` - правила аргументов, чтение из файла и стандартного ввода с ограничением, вывод (исход и фиксированные примечания, никогда не текст, честный not found), безопасные сообщения об ошибках и то, что окружение не читается, пока аргументы неверны. `TestAssessmentLeakTraceOverHTTP` (PostgreSQL) создает по HTTP две реальные попытки и проверяет, что текст задания с меткой находит первую по метке, текст без невидимых символов находит вторую по условию, текст снимка с плиткой находит первую по видимому коду и времени плитки, посторонний и короткий текст не находятся, поиск не меняет ни версию и состояние попыток, ни проверки и результаты, каждый поиск попадает в журнал без текста, журнал отклоняет UPDATE, DELETE, TRUNCATE и найденную строку без попытки, журнал переживает удаленную попытку (которая после этого не находится), а команда с секретом сервера находит попытку, тогда как с другим секретом метку не читает. Они не запускают инструмент распознавания, поэтому здесь не измерено, как команда справляется с настоящими ошибками распознаванияLine truncated
## Тесты внутренних уведомлений
Модульные тесты (`make -C backend test`, `make -C frontend test`):