feat(assessment): watermark the task text of real attempts

This commit is contained in:
shira committed 2026-10-11 10:44:30 +03:00
1 parent 24b64d698a
commit c975a0d506
57 files changed
+2429 -92

No files matched your search

+13
View File
@@ -697,6 +697,19 @@ Code: migration `backend/db/migrations/00033_create_assessment_signal_review.sql
- When and how. The review never runs in a candidate's transaction. The first accepted answer schedules the job `assessment.signal_review` with the key `<attempt>:deadline`, due one minute after the deadline of the attempt (so an answer committed right at the deadline is in its facts), and finalization schedules `<attempt>:ended`, due at once; both are inserts into `scheduled_jobs` in the transaction of the answer or the finalization, and repeats do nothing. The deadline job also covers an attempt that expires or is abandoned, however and whenever its state changes. A review is a point-in-time evaluation: it describes the facts committed when its job ran, and the job at the deadline runs it again for a finalized attempt, which picks up later matches. The job computes the review of its attempt and refreshes the review of every other attempt that has ended (terminal state or past its deadline) and shares answers with it at the attention level or above, at most 50 per job; a ring of more than 50 attempts that share answers is covered because each member runs its own deadline job and sees the others. An attempt that is still running is flagged by its own job when it ends and sees the other facts then. Writers are ordered by a transaction-scoped advisory lock per review: the job locks the review of every attempt it will write, in ascending attempt order, before it reads any fact, so the later of two jobs over one attempt waits and then reads what the earlier committed (no lost update, and no lock cycle). The times of a review come from the database clock inside the upsert and the update time never falls behind the stored times. Nothing else is locked: the facts are append-only and a job is scheduled after its facts are committed. A failure is retried by the runner with backoff and can never block or change a result; without the worker (`JOBS_ENABLED=false`) reviews wait with their jobs. The only review statement in a candidate's transaction is the insert of the job (and the two counter updates of the answer). The job logs one line with the number of reviews it wrote and its duration, and no answer, address, or candidate. Applicability bound: the share is read from the counters in constant time, but the comparison joins the answers of the attempt with the answers that hold the same values, so its cost grows with the number of holders of popular values, at most 23 items times the holders of each; it is fine for background jobs on populations of up to about 100,000 answers per family and needs sampling or a cap above that.
- Limits. Browser signals can be forged or suppressed, so they are a hint only. The client measures of the attempt page (fullscreen, covering the task, blocking copy, selection, print, and paste) stop only the casual route: the task text is in the candidate's browser, so a screenshot, a second device, or an extension takes it out, and they change no score by themselves. A helper such as an LLM on another device is not visible. False positives are possible: a shared or changing network (mobile data, NAT), a reload, two tabs, copying the task text, and coinciding answers of a small answer space. The retention period of these facts, whether collecting them needs a separate consent beyond the notice, and who calibrates the thresholds are not decided.
### Watermark of the task text
Implemented for real attempts (root and corrective). A training run (`demo_express`) carries no watermark. The watermark ties a leaked statement, a screenshot, or a photo of the screen back to an attempt so that a person can review it; it does not stop any of them. Code: `backend/internal/domain/assessment_watermark.go` and `assessment_wording.go` (the mark and the table of interchangeable phrases), `backend/internal/usecase/assessment/watermark.go` (`Watermarker`), `Keyring.AssessmentWatermarkSeed` in `usecase/identity/keyring.go`, the hook `AssessmentHandler.WithPresenter` in the HTTP adapter, and `frontend/src/features/assessment-watermark/`.
- Where the mark is made. Only in the response, never in storage: the stored variant, its reference answer, and the retained idempotent responses stay unmarked, and grading reads the stored variant. Every response that carries an attempt (creation, read, session start, answer, finalize) passes the presenter, so one attempt shows the same code and the same marked text on every read and replay. If the mark cannot be made the response is a 500 and never an unmarked task text.
- The key. The seed of an attempt is HMAC-SHA-256 of the attempt identifier under a key derived from `IDENTITY_KEY_SECRET` with its own label (`lincodex/assessment/watermark/v1`); no new secret exists. The code, the invisible mark, and the choice of wordings are all read from this seed on the server, and neither the seed nor the key is sent to a client. Changing `IDENTITY_KEY_SECRET` changes the code and the wordings of every attempt, so a text or a screenshot of an attempt issued before the change can no longer be traced.
- Visible channel. `AssessmentAttempt.watermark.code` is 10 symbols of Crockford base32 (50 bits of the seed) shown as `XXXXX-XXXXX`. It is a pseudonym: it holds no name, contact, or identifier of the account and cannot be computed without the secret. The attempt page draws it with the time (UTC, to the minute, from the clock of the device) as a faint tile over the whole task screen: fixed, opacity 0.07, no pointer events, hidden from assistive technology. It survives a screenshot or a photo and is removed by a tool that edits the page.
- Invisible channel. The statement carries the same code as 25 base-4 digits and one check digit written in four zero-width characters (U+200B, U+200C, U+200D, U+2060), repeated after the first space and at the start of each following sentence (at most 8 copies), so a copy of a paragraph keeps a whole run and a damaged run is ignored. It survives a copy of the page text, a saved page, and an API response. Many chat, mail, and OCR tools drop zero-width characters, and a retyped text has none.
- Wording channel. `assessmentWordingGroups` lists about 18 groups of interchangeable phrases of plain connective prose (`at most` and `no more than` before a number, `is not` and `isn't`, `non-decreasing` and `nondecreasing`, and the like, with Russian groups). Each attempt writes every group in the form its seed picks. The table is append-only because reordering it changes the choice of attempts already served; a group avoids terms that a statement defines and then reuses, and the number groups apply only before a digit. The channel survives retyping and OCR, and it is weak: a statement holds a few groups, and a group is worth about one bit, so it only tells attempts apart that were served the same variant text.
- The meaning does not change. The tests compare the canonical text of two attempts that were served one variant (the mark and the phrases removed or mapped back) and find them equal, check that the reference answer belongs to the variant and is not touched by marking, that marking twice gives the same text, and that the number and data tokens of the statement stay in the accessible text.
- Accessibility. Some speech synthesizers and braille displays may announce zero-width characters or break a word at them; this was not tested with a real screen reader. The page therefore puts every run of invisible characters in an `aria-hidden` element: the accessibility tree holds the words only (a Playwright check reads the tree with `ariaSnapshot`, and a Vitest check strips the hidden elements from the markup), while the document keeps the characters so that anything copied from it carries the mark. The wordings are ordinary words, and no whitespace variants are used, because a non-breaking space is not guaranteed to be silent everywhere.
- What it does not do. A screenshot, a photo of the screen, or retyping cannot be prevented in a browser. The watermark is evidence for a manual review and an appeal, never an automatic decision; no operation shows it to an employer, and the candidate sees only the code of their own attempt.
### 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.
+6 -2
View File
@@ -540,11 +540,15 @@ The tests prove the stored facts, the policy pinning, the job-based computation,
## Assessment lockdown tests
Vitest runs in Node without a DOM, so the lockdown is checked in parts. `frontend/src/features/assessment-lockdown/model/fullscreen.test.ts` covers support detection (including a browser without element fullscreen, such as iPhone Safari), that the request is issued synchronously inside the call so it stays in the click, and that a refusal is a result and not an exception. `model/cover.test.ts` is the table of when the task is covered: fullscreen exit, a hidden tab, a window without focus, a request in flight, and the mode without fullscreen. `ui/protected-region.test.tsx` renders the region with a fake lockdown and checks that a covered task leaves no text of the prompt or the options in the markup, that a cover for a left tab has no fullscreen button, and the explanation shown for an unsupported browser; `features/answer-assessment/ui/answer-form.test.tsx` checks that a concealed form renders nothing. The notice text version 2 and its list of measures are checked in `features/assessment-signals/ui/signal-notice.test.tsx`. In the backend, `usecase/assessment/signal_notice_test.go` checks that every version except the current one is refused, and `TestAssessmentSignalNoticeOverHTTP` checks over HTTP with PostgreSQL that a stored acknowledgement of version 1 does not count for version 2.
Vitest runs in Node without a DOM, so the lockdown is checked in parts. `frontend/src/features/assessment-lockdown/model/fullscreen.test.ts` covers support detection (including a browser without element fullscreen, such as iPhone Safari), that the request is issued synchronously inside the call so it stays in the click, and that a refusal is a result and not an exception. `model/cover.test.ts` is the table of when the task is covered: fullscreen exit, a hidden tab, a window without focus, a request in flight, and the mode without fullscreen. `ui/protected-region.test.tsx` renders the region with a fake lockdown and checks that a covered task leaves no text of the prompt or the options in the markup, that a cover for a left tab has no fullscreen button, and the explanation shown for an unsupported browser; `features/answer-assessment/ui/answer-form.test.tsx` checks that a concealed form renders nothing. The notice text version 3 and its list of measures are checked in `features/assessment-signals/ui/signal-notice.test.tsx`. In the backend, `usecase/assessment/signal_notice_test.go` checks that every version except the current one is refused, and `TestAssessmentSignalNoticeOverHTTP` checks over HTTP with PostgreSQL that a stored acknowledgement of version 1 does not count for the current version, and its versions follow `CurrentSignalNoticeVersion`.
Unit tests of the task protection: `model/task-guard.test.ts` runs the rules with small fake elements and events: selection, the context menu, and drag are cancelled on the task text and left alone in a field, a drop never fills a field, paste is refused in answer fields (and reported, so the screen can say so) and allowed in the code editor, the `beforeinput` routes of paste and drop are closed while typing and composing are never touched, and a copy or cut is refused when the target or the selection reaches into the task but not when it is inside a field. `features/answer-assessment/ui/answer-form.test.tsx` checks that only the code editor carries the paste exception.
Two browser specs run against a mocked API, so they need no backend data and also run against the Vite server (`E2E_BASE_URL=http://localhost:5173 pnpm exec playwright test e2e/assessment-lockdown.spec.ts e2e/assessment-task-protection.spec.ts --project=chromium`) as well as in `make -C deploy test-e2e`; the mock is in `frontend/e2e/assessment-attempt-mock.ts`. `assessment-lockdown.spec.ts`: leaving fullscreen covers the task (its text is not in the page), sends a `fullscreen_exit` signal, and the continue button restores the task with the typed draft; leaving the tab covers the task and returning in fullscreen shows it; a browser without the fullscreen API shows the explanation and still takes the test from the keyboard; a refused fullscreen request continues without it; closing the notice without confirming leaves fullscreen and stores nothing. `assessment-task-protection.spec.ts`: the task text is not selectable, a select-all or scripted copy leaves no task text in the clipboard, the context menu and drag are cancelled on the task but not in a field, a field copies its own text, the text stays in the accessibility tree, and printing hides the task; an answer field refuses a paste, shows the notice, and the refused paste is sent as a `paste` signal with its size and without its text; the practice code editor accepts a paste and sends its size; an item is answered with the keyboard alone. The notice acknowledgement over the real backend is covered by the existing notice test in `assessment.spec.ts`, which now expects version 2. These specs show the page behavior in Chromium with a mocked server; they do not show behavior in other browsers, on a phone, with a real screen reader, or against a window manager that changes fullscreen on its own. The paste rule cannot see text that an on-screen keyboard inserts as typing.
Two browser specs run against a mocked API, so they need no backend data and also run against the Vite server (`E2E_BASE_URL=http://localhost:5173 pnpm exec playwright test e2e/assessment-lockdown.spec.ts e2e/assessment-task-protection.spec.ts --project=chromium`) as well as in `make -C deploy test-e2e`; the mock is in `frontend/e2e/assessment-attempt-mock.ts`. `assessment-lockdown.spec.ts`: leaving fullscreen covers the task (its text is not in the page), sends a `fullscreen_exit` signal, and the continue button restores the task with the typed draft; leaving the tab covers the task and returning in fullscreen shows it; a browser without the fullscreen API shows the explanation and still takes the test from the keyboard; a refused fullscreen request continues without it; closing the notice without confirming leaves fullscreen and stores nothing. `assessment-task-protection.spec.ts`: the task text is not selectable, a select-all or scripted copy leaves no task text in the clipboard, the context menu and drag are cancelled on the task but not in a field, a field copies its own text, the text stays in the accessibility tree, and printing hides the task; an answer field refuses a paste, shows the notice, and the refused paste is sent as a `paste` signal with its size and without its text; the practice code editor accepts a paste and sends its size; an item is answered with the keyboard alone. The notice acknowledgement over the real backend is covered by the existing notice test in `assessment.spec.ts`, which now expects version 3. These specs show the page behavior in Chromium with a mocked server; they do not show behavior in other browsers, on a phone, with a real screen reader, or against a window manager that changes fullscreen on its own. The paste rule cannot see text that an on-screen keyboard inserts as typing.
## Assessment watermark tests
`backend/internal/domain/assessment_watermark_test.go` covers the mark: two attempts that were served one real generated variant get different marked statements whose canonical text and reference answer are equal; marking is deterministic and idempotent; the invisible run decodes to the visible code, survives a copy of two sentences, and a cut, padded, or mis-checked run is ignored; the accessible text holds the words only; the alignment of a stored statement with a leak reads only the phrases that it finds there (words around the statement, such as a quotation or a message, are ignored), the wording agreement of the attempt that wrote the text holds for every phrase group, other seeds disagree, a fragment yields the phrases of the fragment, an unrelated text aligns nothing, and another variant of the same family aligns for fewer characters than the leaked one; the pieces between the phrases are the same in every copy of a statement; the number guard keeps `at most` at the end of a sentence; codes parse the way an operator or OCR reads them. `usecase/assessment/watermark_test.go` checks that only root and corrective attempts are marked, that the stored snapshot is not changed, that the visible code equals the invisible one, and that a missing `Watermarker` leaves snapshots alone; `adapter/primary/http/v1/assessment_test.go` checks that every attempt response goes through the presenter and that a presenter failure is an error. `TestAssessmentWatermarkOverHTTP` (PostgreSQL) checks over HTTP that a real attempt shows the code derived on the server and a marked prompt on creation, on a read, and on a replay, that a training run shows neither, that the response holds only the code, and that the stored statement has no mark. In the frontend, `features/assessment-watermark` has Vitest tests of the text split, of the accessible text of the rendered markup (everything in `aria-hidden` removed leaves exactly the words), and of the tile (code and UTC time, no `@`, hidden from assistive technology). `e2e/assessment-watermark.spec.ts` runs against the mocked API (also on the Vite server, `E2E_BASE_URL=http://localhost:5173 pnpm exec playwright test e2e/assessment-watermark.spec.ts --project=chromium`): the tile is on the task screen with the code and the time and without the account e-mail, is faint and takes no click, an attempt without a code shows no tile, and the accessibility tree of the marked prompt holds the words and no format character while the document keeps them. These tests do not run a real screen reader, a braille display, or another browser, so they do not show how a reader speaks the text; they do not show how many attempts a leak can be told from either, because the wording channel gives about one bit per phrase group.
## Internal notification tests
+13
View File
@@ -697,6 +697,19 @@ contact_grant относится к паре кандидат-компания
- Когда и как. Проверка никогда не считается в транзакции кандидата. Первый принятый ответ планирует задание `assessment.signal_review` с ключом `<попытка>:deadline`, срок - через минуту после дедлайна попытки (чтобы ответ, зафиксированный прямо на дедлайне, попал в факты), а завершение планирует `<попытка>:ended`, срок - сразу; оба - вставки в `scheduled_jobs` в транзакции ответа или завершения, повтор ничего не делает. Задание дедлайна покрывает и попытку, которая истекает или брошена, как и когда бы ни менялось ее состояние. Проверка - оценка на момент: она описывает факты, зафиксированные к запуску ее задания, а задание на дедлайне для завершенной попытки запускает ее снова и подхватывает поздние совпадения. Задание считает проверку своей попытки и обновляет проверку каждой другой завершившейся (терминальное состояние или срок прошел) попытки с общими ответами на уровне «внимание» и выше, не более 50 за задание; кольцо больше 50 попыток с общими ответами покрыто тем, что каждый участник запускает свое задание дедлайна и видит остальных. Еще идущую попытку помечает ее собственное задание, когда она закончится и увидит остальные факты. Писатели упорядочены транзакционной advisory-блокировкой на каждую проверку: задание берет блокировки проверок всех попыток, которые будет писать, по возрастанию идентификатора, до чтения любого факта, поэтому более позднее из двух заданий по одной попытке ждет и затем читает то, что зафиксировало раннее (нет потерянного обновления и нет цикла блокировок). Время проверки берется из часов базы внутри upsert, а время обновления не отстает от сохраненного. Больше ничего не блокируется: факты только добавляются, а задание планируется после фиксации его фактов. Сбой повторяется исполнителем с задержкой и никогда не блокирует и не меняет результат; без worker (`JOBS_ENABLED=false`) проверки ждут вместе со своими заданиями. В транзакции кандидата из запросов проверки только вставка задания (и два обновления счетчиков ответа). Задание пишет в журнал одну строку с числом записанных проверок и длительностью, без ответов, адресов и кандидатов. Граница применимости: доля читается из счетчиков за постоянное время, но сравнение соединяет ответы попытки с ответами, у которых те же значения, поэтому цена растет с числом держателей популярных значений, не более 23 заданий на число держателей каждого; для фоновых заданий это нормально на совокупностях до порядка 100 000 ответов на семейство, выше нужна выборка или предел.
- Ограничения. Браузерные сигналы можно подделать или подавить, поэтому это только подсказка. Клиентские меры страницы попытки (полноэкранный режим, скрытие задания, запрет копирования, выделения, печати и вставки) останавливают только простой путь: текст задания находится в браузере кандидата, поэтому снимок экрана, второе устройство или расширение его выносят, а сами по себе эти меры оценку не меняют. Помощь, например LLM на другом устройстве, не видна. Возможны ложные срабатывания: общая или меняющаяся сеть (мобильный интернет, NAT), перезагрузка страницы, две вкладки, копирование условия и случайные совпадения ответов из малого пространства. Срок хранения этих фактов, нужно ли для их сбора отдельное согласие сверх уведомления и кто калибрует пороги, не решено.
### Водяной знак текста задания
Реализовано для реальных попыток (root и corrective). У учебного запуска (`demo_express`) водяного знака нет. Знак связывает утекший текст условия, снимок экрана или фото экрана с попыткой, чтобы человек мог их проверить; он ничего из этого не предотвращает. Код: `backend/internal/domain/assessment_watermark.go` и `assessment_wording.go` (метка и таблица взаимозаменяемых оборотов), `backend/internal/usecase/assessment/watermark.go` (`Watermarker`), `Keyring.AssessmentWatermarkSeed` в `usecase/identity/keyring.go`, точка подключения `AssessmentHandler.WithPresenter` в HTTP-адаптере и `frontend/src/features/assessment-watermark/`.
- Где ставится метка. Только в ответе, но не в хранилище: сохраненный вариант, его эталонный ответ и сохраненные идемпотентные ответы остаются без метки, а оценка читает сохраненный вариант. Каждый ответ, в котором есть попытка (создание, чтение, начало сеанса, ответ, завершение), проходит через презентер, поэтому одна попытка показывает один и тот же код и один и тот же текст с меткой при каждом чтении и повторе. Если метку поставить не удалось, ответом будет 500, а не текст задания без метки.
- Ключ. Затравка попытки - это HMAC-SHA-256 от идентификатора попытки под ключом, выведенным из `IDENTITY_KEY_SECRET` с собственной меткой (`lincodex/assessment/watermark/v1`); нового секрета нет. Код, невидимая метка и выбор формулировок читаются из этой затравки на сервере, ни затравка, ни ключ не отправляются клиенту. Смена `IDENTITY_KEY_SECRET` меняет код и формулировки всех попыток, поэтому текст или снимок попытки, выданной до смены, проследить уже нельзя.
- Видимый канал. `AssessmentAttempt.watermark.code` - 10 символов base32 Крокфорда (50 бит затравки), показанные как `XXXXX-XXXXX`. Это псевдоним: в нем нет имени, контакта и идентификатора аккаунта, а без секрета его нельзя вычислить. Страница попытки рисует его вместе со временем (UTC, до минуты, по часам устройства) бледной плиткой поверх всего экрана задания: фиксированная, прозрачность 0,07, без событий указателя, скрыта от вспомогательных технологий. Плитка переживает снимок экрана и фото, а инструмент, который правит страницу, ее убирает.
- Невидимый канал. В тексте условия тот же код записан 25 четверичными цифрами и одной контрольной цифрой четырьмя символами нулевой ширины (U+200B, U+200C, U+200D, U+2060) и повторен после первого пробела и в начале каждого следующего предложения (не больше 8 копий), поэтому копия абзаца сохраняет целый запуск, а поврежденный запуск игнорируется. Метка переживает копирование текста страницы, сохраненную страницу и ответ API. Многие чаты, почтовые клиенты и средства распознавания убирают символы нулевой ширины, а в перепечатанном тексте их нет.
- Канал формулировок. `assessmentWordingGroups` перечисляет около 18 групп взаимозаменяемых оборотов простой связной речи (`at most` и `no more than` перед числом, `is not` и `isn't`, `non-decreasing` и `nondecreasing` и т. п., есть русские группы). Каждая попытка пишет каждую группу в форме, которую выбирает ее затравка. Таблица только дополняется, потому что перестановка меняет выбор уже выданных попыток; группа обходит термины, которые условие определяет и потом повторяет, а числовые группы действуют только перед цифрой. Канал переживает перепечатку и распознавание текста и слаб: в условии несколько групп, группа дает около одного бита, поэтому он различает только попытки, которым выдан один и тот же текст варианта.
- Смысл не меняется. Тесты сравнивают канонический текст двух попыток с одним вариантом (метка убрана, обороты приведены к одной форме) и находят их равными, проверяют, что эталонный ответ принадлежит варианту и разметка его не трогает, что повторная разметка дает тот же текст и что числа и данные условия остаются в доступном тексте.
- Доступность. Некоторые синтезаторы речи и брайлевские дисплеи могут озвучивать символы нулевой ширины или рвать слово на них; с настоящим экранным диктором это не проверялось. Поэтому страница кладет каждый запуск невидимых символов в элемент `aria-hidden`: дерево доступности содержит только слова (проверка Playwright читает дерево через `ariaSnapshot`, проверка Vitest вырезает скрытые элементы из разметки), а документ хранит символы, так что все, что из него скопировано, несет метку. Формулировки - обычные слова, варианты пробелов не используются, потому что неразрывный пробел не везде гарантированно беззвучен.
- Чего знак не делает. Снимок экрана, фото экрана или перепечатку в браузере предотвратить нельзя. Знак - доказательство для ручной проверки и апелляции, но не автоматическое решение; ни одна операция не показывает его работодателю, а кандидат видит только код своей попытки.
### Доказательства навыков
Реализовано как сохраняемая проекция неизменяемых результатов оценки с двумя чтениями: собственный список кандидата и разрешенная проекция сейчас видимой карточки. Проекцию для организации читает поиск (см. [Подбор и объяснение](#подбор-и-объяснение)); перцентиль ее пока не читает.
+6 -2
View File
@@ -540,11 +540,15 @@ Spec не проверяет запланированные переходы б
## Тесты ограничений во время попытки
Vitest работает в Node без DOM, поэтому ограничения проверяются по частям. `frontend/src/features/assessment-lockdown/model/fullscreen.test.ts` покрывает определение поддержки (в том числе браузер без полноэкранного режима элемента, например iPhone Safari), то, что запрос делается синхронно внутри вызова и остается внутри клика, и то, что отказ - это результат, а не исключение. `model/cover.test.ts` - таблица случаев, когда задание закрыто: выход из полноэкранного режима, скрытая вкладка, окно без фокуса, запрос в процессе и режим без полноэкранного режима. `ui/protected-region.test.tsx` рисует область с поддельным состоянием и проверяет, что закрытое задание не оставляет в разметке текста условия и вариантов, что у закрытия из-за ухода с вкладки нет кнопки полноэкранного режима, и объяснение для неподдерживаемого браузера; `features/answer-assessment/ui/answer-form.test.tsx` проверяет, что скрытая форма ничего не рисует. Версия 2 текста уведомления и перечень мер проверяются в `features/assessment-signals/ui/signal-notice.test.tsx`. В бэкенде `usecase/assessment/signal_notice_test.go` проверяет, что любая версия, кроме текущей, отклоняется, а `TestAssessmentSignalNoticeOverHTTP` по HTTP с PostgreSQL проверяет, что сохраненное подтверждение версии 1 не засчитывается для версии 2.
Vitest работает в Node без DOM, поэтому ограничения проверяются по частям. `frontend/src/features/assessment-lockdown/model/fullscreen.test.ts` покрывает определение поддержки (в том числе браузер без полноэкранного режима элемента, например iPhone Safari), то, что запрос делается синхронно внутри вызова и остается внутри клика, и то, что отказ - это результат, а не исключение. `model/cover.test.ts` - таблица случаев, когда задание закрыто: выход из полноэкранного режима, скрытая вкладка, окно без фокуса, запрос в процессе и режим без полноэкранного режима. `ui/protected-region.test.tsx` рисует область с поддельным состоянием и проверяет, что закрытое задание не оставляет в разметке текста условия и вариантов, что у закрытия из-за ухода с вкладки нет кнопки полноэкранного режима, и объяснение для неподдерживаемого браузера; `features/answer-assessment/ui/answer-form.test.tsx` проверяет, что скрытая форма ничего не рисует. Версия 3 текста уведомления и перечень мер проверяются в `features/assessment-signals/ui/signal-notice.test.tsx`. В бэкенде `usecase/assessment/signal_notice_test.go` проверяет, что любая версия, кроме текущей, отклоняется, а `TestAssessmentSignalNoticeOverHTTP` по HTTP с PostgreSQL проверяет, что сохраненное подтверждение версии 1 не засчитывается для текущей версии, а ее версии следуют за `CurrentSignalNoticeVersion`.
Модульные тесты защиты задания: `model/task-guard.test.ts` проверяет правила на небольших поддельных элементах и событиях: выделение, контекстное меню и перетаскивание отменяются на тексте задания и не трогаются в поле, сброс текста мышью никогда не заполняет поле, вставка отклоняется в полях ответа (и об этом сообщается, чтобы экран мог сказать) и разрешена в редакторе кода, пути `beforeinput` для вставки и сброса закрыты, а набор и композиция никогда не затрагиваются, копирование и вырезание отклоняются, когда цель или выделение доходят до задания, и не отклоняются внутри поля. `features/answer-assessment/ui/answer-form.test.tsx` проверяет, что исключение для вставки есть только у редактора кода.
Две браузерные спецификации работают с подставным API, поэтому им не нужны данные бэкенда, и их можно запускать и на сервере Vite (`E2E_BASE_URL=http://localhost:5173 pnpm exec playwright test e2e/assessment-lockdown.spec.ts e2e/assessment-task-protection.spec.ts --project=chromium`), и в `make -C deploy test-e2e`; подставной API лежит в `frontend/e2e/assessment-attempt-mock.ts`. `assessment-lockdown.spec.ts`: выход из полноэкранного режима закрывает задание (его текста нет в странице), отправляет сигнал `fullscreen_exit`, а кнопка продолжения возвращает задание вместе с набранным черновиком; уход с вкладки закрывает задание, а возврат в полноэкранном режиме показывает его; браузер без полноэкранного API показывает объяснение и проходит тест с клавиатуры; отказ в полноэкранном режиме не мешает продолжить; закрытие уведомления без подтверждения выходит из полноэкранного режима и ничего не сохраняет. `assessment-task-protection.spec.ts`: текст задания нельзя выделить, копирование после выделения всего или из скрипта не оставляет текста задания в буфере, контекстное меню и перетаскивание отменяются на задании, но не в поле, поле копирует собственный текст, текст остается в дереве доступности, печать скрывает задание; поле ответа отклоняет вставку и показывает сообщение, а отклоненная вставка уходит сигналом `paste` с размером и без текста; редактор кода принимает вставку и отправляет ее размер; задание отвечается только с клавиатуры. Подтверждение уведомления с настоящим бэкендом покрывает существующий тест уведомления в `assessment.spec.ts`, который теперь ожидает версию 2. Эти спецификации показывают поведение страницы в Chromium с подставным сервером; они не показывают поведение в других браузерах, на телефоне, с настоящим экранным диктором и в оконном менеджере, который сам меняет полноэкранный режим. Правило вставки не видит текст, который экранная клавиатура вставляет как набор.
Две браузерные спецификации работают с подставным API, поэтому им не нужны данные бэкенда, и их можно запускать и на сервере Vite (`E2E_BASE_URL=http://localhost:5173 pnpm exec playwright test e2e/assessment-lockdown.spec.ts e2e/assessment-task-protection.spec.ts --project=chromium`), и в `make -C deploy test-e2e`; подставной API лежит в `frontend/e2e/assessment-attempt-mock.ts`. `assessment-lockdown.spec.ts`: выход из полноэкранного режима закрывает задание (его текста нет в странице), отправляет сигнал `fullscreen_exit`, а кнопка продолжения возвращает задание вместе с набранным черновиком; уход с вкладки закрывает задание, а возврат в полноэкранном режиме показывает его; браузер без полноэкранного API показывает объяснение и проходит тест с клавиатуры; отказ в полноэкранном режиме не мешает продолжить; закрытие уведомления без подтверждения выходит из полноэкранного режима и ничего не сохраняет. `assessment-task-protection.spec.ts`: текст задания нельзя выделить, копирование после выделения всего или из скрипта не оставляет текста задания в буфере, контекстное меню и перетаскивание отменяются на задании, но не в поле, поле копирует собственный текст, текст остается в дереве доступности, печать скрывает задание; поле ответа отклоняет вставку и показывает сообщение, а отклоненная вставка уходит сигналом `paste` с размером и без текста; редактор кода принимает вставку и отправляет ее размер; задание отвечается только с клавиатуры. Подтверждение уведомления с настоящим бэкендом покрывает существующий тест уведомления в `assessment.spec.ts`, который теперь ожидает версию 3. Эти спецификации показывают поведение страницы в Chromium с подставным сервером; они не показывают поведение в других браузерах, на телефоне, с настоящим экранным диктором и в оконном менеджере, который сам меняет полноэкранный режим. Правило вставки не видит текст, который экранная клавиатура вставляет как набор.
## Тесты водяного знака оценки
`backend/internal/domain/assessment_watermark_test.go` покрывает метку: две попытки с одним настоящим сгенерированным вариантом получают разные тексты с меткой, у которых равны канонический текст и эталонный ответ; разметка детерминирована и идемпотентна; невидимый запуск декодируется в видимый код, переживает копию двух предложений, а обрезанный, удлиненный или с неверной контрольной цифрой запуск игнорируется; доступный текст содержит только слова; выравнивание сохраненного условия с утекшим текстом читает только найденные там обороты (слова вокруг условия, например цитата или сообщение, игнорируются), согласование формулировок попытки, которая написала текст, выполняется для каждой группы оборотов, другие затравки не согласуются, фрагмент дает обороты фрагмента, посторонний текст ничего не выравнивает, а другой вариант того же семейства выравнивается на меньшее число символов, чем утекший; части между оборотами одинаковы в каждой копии условия; числовая защита оставляет `at most` в конце предложения; коды разбираются так, как их читает оператор или распознавание. `usecase/assessment/watermark_test.go` проверяет, что размечаются только root и corrective, что сохраненный снимок не меняется, что видимый код равен невидимому и что отсутствие `Watermarker` оставляет снимки как есть; `adapter/primary/http/v1/assessment_test.go` проверяет, что каждый ответ с попыткой проходит через презентер и что отказ презентера - ошибка. `TestAssessmentWatermarkOverHTTP` (PostgreSQL) по HTTP проверяет, что реальная попытка при создании, чтении и повторе показывает код, выведенный на сервере, и текст с меткой, что учебный запуск не показывает ни того, ни другого, что в ответе только код и что в сохраненном условии метки нет. Во фронтенде у `features/assessment-watermark` есть тесты Vitest разбиения текста, доступного текста отрисованной разметки (без всего, что в `aria-hidden`, остаются ровно слова) и плитки (код и время UTC, без `@`, скрыта от вспомогательных технологий). `e2e/assessment-watermark.spec.ts` работает с подставным API (и на сервере Vite, `E2E_BASE_URL=http://localhost:5173 pnpm exec playwright test e2e/assessment-watermark.spec.ts --project=chromium`): плитка есть на экране задания с кодом и временем и без email аккаунта, бледная и не перехватывает клики, у попытки без кода плитки нет, а дерево доступности размеченного условия содержит слова и ни одного символа форматирования, хотя документ их хранит. Эти тесты не запускают настоящий экранный диктор, брайлевский дисплей или другой браузер, поэтому не показывают, как диктор читает текст; они не показывают и того, сколько попыток можно различить по утечке, потому что канал формулировок дает около одного бита на группу оборотов.
## Тесты внутренних уведомлений