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

+2 -1
View File
@@ -275,7 +275,7 @@ The `assessment` tag covers the assessment attempts of the current candidate (PR
Every operation also declares the `default` problem response.
The signal notice (`assessment-signal-notice`) lists the signals collected during a real attempt: browser events (focus loss, copy, paste and cut with a size, fullscreen exit; stored only while C3 is current) and server signals (response time, change of network address, parallel sessions, comparison of answer digests; only one-way keyed digests are stored, never addresses or session tokens). `GET` returns the notice version the server requires and whether the candidate acknowledged it; `PUT` stores the acknowledgement for the account and that version. The acknowledgement is a record that the candidate was informed, not a consent: it does not change C3, and the signal operation neither reads it nor refuses a batch without it. `PUT` needs no Idempotency-Key, because a repeat keeps the first time and answers 200; another version answers 409 `state_conflict`. The notice also lists the measures the page applies during a real attempt (fullscreen, covering the task, blocks on copying, selecting, and printing the task text, the paste rule, and a planned watermark); it is text version 2, and an acknowledgement of an earlier version never counts for the current one. The `demo_express` mode collects no signals and needs no acknowledgement.
The signal notice (`assessment-signal-notice`) lists the signals collected during a real attempt: browser events (focus loss, copy, paste and cut with a size, fullscreen exit; stored only while C3 is current) and server signals (response time, change of network address, parallel sessions, comparison of answer digests; only one-way keyed digests are stored, never addresses or session tokens). `GET` returns the notice version the server requires and whether the candidate acknowledged it; `PUT` stores the acknowledgement for the account and that version. The acknowledgement is a record that the candidate was informed, not a consent: it does not change C3, and the signal operation neither reads it nor refuses a batch without it. `PUT` needs no Idempotency-Key, because a repeat keeps the first time and answers 200; another version answers 409 `state_conflict`. The notice also lists the measures the page applies during a real attempt (fullscreen, covering the task, blocks on copying, selecting, and printing the task text, the paste rule, and the watermark of the task screen and text); it is text version 3, and an acknowledgement of an earlier version never counts for the current one. The `demo_express` mode collects no signals and needs no acknowledgement.
Access:
@@ -314,6 +314,7 @@ Attempt lifecycle, with the commands each state accepts:
Items and answers:
- An item has an `id` (the instance), `sequence`, a plain-text `prompt`, and `content` (`ItemContent`) in one of the formats `choice`, `number`, `string`, `order`, `find_error`, `configuration`, and `practice`. It never contains an answer key, a correct option, a score, a family or variant identifier, a seed, or a hidden check, and seed items look like scored ones. `multiple`, `max_selections`, and `max_length` are properties of the format or the task family and never derived from the key. The variant is fixed when first served, so a reload, a retry, or a resumed session returns the same instance.
- Watermark. A real attempt (`root` or `corrective`) carries `watermark.code`, a keyed pseudonym of the attempt such as `7K3QD-9XM2T`, which the client shows with the time as a faint tile over the task screen; a `demo_express` attempt omits the field. The `prompt` of a real attempt also carries an invisible mark and interchangeable wordings chosen by the same server secret; they change neither the meaning nor the reference answer, and a client keeps the invisible characters (zero width space, non-joiner, joiner, word joiner) out of the accessibility tree. Neither the code nor the mark names the candidate, and no operation gives either to an employer. See [Watermark of the task text](../docs/en/ARCHITECTURE.md#watermark-of-the-task-text).
- An answer (`AssessmentAnswer`) has the same seven formats and carries only the answer. Unknown fields such as `score`, `duration`, or `seed` answer 400. The server records the times and scores the answer with the key of the item instance; time never enters the grade decision. Responses never say whether an answer was correct.
- The practice solution runs asynchronously in the sandbox against three hidden check groups; the client polls the attempt while it is `pending`. The verdict shows only the score 0-3 and the pass state of each group. Every outcome caused by the solution (a compilation or runtime error, a time or memory limit) is `finished` with groups not passed. `failed` (`sandbox_busy` or `sandbox_error`) means only that the infrastructure could not run it; it consumes nothing. This keeps `failed` from acting as an oracle for hidden checks and from allowing endless retries. After `finished` no other solution is accepted.
- If the latest submission is still `failed` when the limit passes, the result is `not_determined` with the reason `sandbox_unavailable`. A practice never submitted gives `practice_incomplete`.
+2 -1
View File
@@ -275,7 +275,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro
Каждая операция также объявляет problem-ответ `default`.
Уведомление о сигналах (`assessment-signal-notice`) перечисляет сигналы, которые собираются во время реальной попытки: события браузера (потеря фокуса, копирование, вставка и вырезание с размером, выход из полноэкранного режима, сохраняются только при действующем C3) и серверные (время ответа, смена сетевого адреса, параллельные сессии, сравнение отпечатков ответов; хранятся только односторонние ключевые отпечатки, адреса и токены сессий не хранятся). `GET` возвращает версию уведомления, которую требует сервер, и признак, что кандидат ее подтвердил; `PUT` сохраняет подтверждение для аккаунта и этой версии. Подтверждение - запись о том, что кандидат ознакомлен, а не согласие: оно не меняет C3, и операция приема сигналов его не читает и не отклоняет пакет без него. `PUT` не требует Idempotency-Key: повтор сохраняет первое время и отвечает 200; другая версия отвечает 409 `state_conflict`. Уведомление также перечисляет меры, которые страница применяет во время реальной попытки (полноэкранный режим, скрытие задания, запрет копирования, выделения и печати текста задания, правило вставки и планируемый водяной знак); это версия 2 текста, и подтверждение более ранней версии для текущей никогда не засчитывается. Режим `demo_express` сигналы не собирает и подтверждения не требует.
Уведомление о сигналах (`assessment-signal-notice`) перечисляет сигналы, которые собираются во время реальной попытки: события браузера (потеря фокуса, копирование, вставка и вырезание с размером, выход из полноэкранного режима, сохраняются только при действующем C3) и серверные (время ответа, смена сетевого адреса, параллельные сессии, сравнение отпечатков ответов; хранятся только односторонние ключевые отпечатки, адреса и токены сессий не хранятся). `GET` возвращает версию уведомления, которую требует сервер, и признак, что кандидат ее подтвердил; `PUT` сохраняет подтверждение для аккаунта и этой версии. Подтверждение - запись о том, что кандидат ознакомлен, а не согласие: оно не меняет C3, и операция приема сигналов его не читает и не отклоняет пакет без него. `PUT` не требует Idempotency-Key: повтор сохраняет первое время и отвечает 200; другая версия отвечает 409 `state_conflict`. Уведомление также перечисляет меры, которые страница применяет во время реальной попытки (полноэкранный режим, скрытие задания, запрет копирования, выделения и печати текста задания, правило вставки и водяной знак экрана и текста задания); это версия 3 текста, и подтверждение более ранней версии для текущей никогда не засчитывается. Режим `demo_express` сигналы не собирает и подтверждения не требует.
Доступ:
@@ -314,6 +314,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro
Задания и ответы:
- У задания есть `id` (экземпляр), `sequence`, `prompt` простым текстом и `content` (`ItemContent`) в одном из форматов `choice`, `number`, `string`, `order`, `find_error`, `configuration` и `practice`. Оно никогда не содержит ключ ответа, правильный вариант, балл, идентификатор семейства или варианта, seed или скрытую проверку, а посевные задания выглядят так же, как оцениваемые. `multiple`, `max_selections` и `max_length` - свойства формата или семейства заданий и никогда не выводятся из ключа. Вариант фиксируется при первой выдаче, поэтому перезагрузка, повтор запроса и возобновление сессии возвращают тот же экземпляр.
- Водяной знак. Реальная попытка (`root` или `corrective`) несет `watermark.code` - ключевой псевдоним попытки вроде `7K3QD-9XM2T`, который клиент показывает вместе со временем бледной плиткой поверх экрана задания; у попытки `demo_express` поля нет. `prompt` реальной попытки также несет невидимую метку и взаимозаменяемые формулировки, выбранные тем же секретом сервера; они не меняют ни смысл, ни эталонный ответ, а клиент держит невидимые символы (пробел нулевой ширины, не-соединитель, соединитель, соединитель слов) вне дерева доступности. Ни код, ни метка не называют кандидата, и ни одна операция не отдает их работодателю. См. [Водяной знак текста задания](../docs/ru/ARCHITECTURE.md#водяной-знак-текста-задания).
- Ответ (`AssessmentAnswer`) имеет те же семь форматов и несет только ответ. Неизвестные поля вроде `score`, `duration` или `seed` дают 400. Сервер сам записывает время и оценивает ответ по ключу экземпляра задания; время не входит в решение о грейде. Ответы API никогда не сообщают, был ли ответ правильным.
- Решение практики исполняется в песочнице асинхронно на трех группах скрытых проверок; клиент опрашивает попытку, пока оно `pending`. Вердикт показывает только балл 0-3 и прохождение каждой группы. Любой исход, вызванный самим решением (ошибка компиляции или выполнения, лимит времени или памяти), - это `finished` с непройденными группами. `failed` (`sandbox_busy` или `sandbox_error`) означает только, что инфраструктура не смогла исполнить решение; он ничего не расходует. Так `failed` не становится оракулом для скрытых проверок и не дает бесконечных повторов. После `finished` другое решение не принимается.
- Если к истечению лимита последняя отправка все еще `failed`, результат - `not_determined` с причиной `sandbox_unavailable`. Неотправленная практика дает `practice_incomplete`.
+15
View File
@@ -734,6 +734,21 @@ AssessmentAttemptCommon:
description: Practices in the order assigned by the mode policy. The list exposes verdicts only after submission.
items:
$ref: '#/AssessmentPractice'
watermark:
$ref: '#/AssessmentWatermark'
AssessmentWatermark:
type: object
description: 'Visible mark of a real attempt. The client shows `code` with the current time as a faint tile over the task screen, so that a screenshot or a photo of the screen can be traced back to the attempt by an operator. The code is a keyed pseudonym derived on the server: it carries no name, contact, or identifier of the account, and it cannot be computed without the server secret. The task text of such an attempt also carries an invisible mark and interchangeable wordings chosen by the same secret; they change neither the meaning of a task nor its reference answer, and the client keeps the invisible characters out of the accessibility tree. Training runs (`demo_express`) carry no watermark. It is evidence for a manual review and an appeal, never an automatic decision.'
additionalProperties: false
required:
- code
properties:
code:
type: string
minLength: 10
maxLength: 11
pattern: ^[0-9A-HJKMNP-TV-Z]{5}-?[0-9A-HJKMNP-TV-Z]{5}$
description: Two groups of five symbols of Crockford base32, such as `7K3QD-9XM2T`.
AssessmentQualifiedAttempt:
allOf:
- $ref: '#/AssessmentAttemptCommon'
@@ -813,6 +813,32 @@ schemas:
exposes verdicts only after submission.
items:
$ref: "#/schemas/AssessmentPractice"
watermark:
$ref: "#/schemas/AssessmentWatermark"
AssessmentWatermark:
type: object
description: >-
Visible mark of a real attempt. The client shows `code` with the current
time as a faint tile over the task screen, so that a screenshot or a photo
of the screen can be traced back to the attempt by an operator. The code
is a keyed pseudonym derived on the server: it carries no name, contact,
or identifier of the account, and it cannot be computed without the server
secret. The task text of such an attempt also carries an invisible mark
and interchangeable wordings chosen by the same secret; they change
neither the meaning of a task nor its reference answer, and the client
keeps the invisible characters out of the accessibility tree. Training
runs (`demo_express`) carry no watermark. It is evidence for a manual
review and an appeal, never an automatic decision.
additionalProperties: false
required:
- code
properties:
code:
type: string
minLength: 10
maxLength: 11
pattern: "^[0-9A-HJKMNP-TV-Z]{5}-?[0-9A-HJKMNP-TV-Z]{5}$"
description: Two groups of five symbols of Crockford base32, such as `7K3QD-9XM2T`.
AssessmentQualifiedAttempt:
allOf:
- $ref: "#/schemas/AssessmentAttemptCommon"
+15
View File
@@ -10572,6 +10572,19 @@ components:
- root
- corrective
- demo_express
AssessmentWatermark:
type: object
description: 'Visible mark of a real attempt. The client shows `code` with the current time as a faint tile over the task screen, so that a screenshot or a photo of the screen can be traced back to the attempt by an operator. The code is a keyed pseudonym derived on the server: it carries no name, contact, or identifier of the account, and it cannot be computed without the server secret. The task text of such an attempt also carries an invisible mark and interchangeable wordings chosen by the same secret; they change neither the meaning of a task nor its reference answer, and the client keeps the invisible characters out of the accessibility tree. Training runs (`demo_express`) carry no watermark. It is evidence for a manual review and an appeal, never an automatic decision.'
additionalProperties: false
required:
- code
properties:
code:
type: string
minLength: 10
maxLength: 11
pattern: ^[0-9A-HJKMNP-TV-Z]{5}-?[0-9A-HJKMNP-TV-Z]{5}$
description: Two groups of five symbols of Crockford base32, such as `7K3QD-9XM2T`.
AssessmentAttemptCommon:
type: object
description: Common state of an assessment attempt. Real assessments have a specialization and target grade; demo_express has neither. The attempt shows its fixed versions, server deadlines, session limit, progress, current item, and practices. It never contains answer keys, answer correctness, item scores, family or variant identifiers, seeds, hidden checks, or anti-cheat signals.
@@ -10664,6 +10677,8 @@ components:
description: Practices in the order assigned by the mode policy. The list exposes verdicts only after submission.
items:
$ref: '#/components/schemas/AssessmentPractice'
watermark:
$ref: '#/components/schemas/AssessmentWatermark'
AssessmentQualifiedAttempt:
allOf:
- $ref: '#/components/schemas/AssessmentAttemptCommon'
+1 -1
View File
@@ -122,7 +122,7 @@ The candidate-only `POST /api/v1/me/assessment-attempts/{attempt_id}/signals` ac
The operation limits the body to 32 KiB, each batch to 50 events, new receipts to 30 per minute per attempt, and stored events to 10,000 per attempt. Capacity is checked for the whole batch. A saturated receipt accepts zero events; idempotent replay returns the original receipt without consuming the receipt budget. Client timestamps are untrusted metadata: a timestamp outside five minutes before the attempt's creation to five minutes after database time rejects the whole batch with 400, so the client moves its timestamps to server time using the `Date` header; rate windows use database time. Migration 28 cascades event, batch, and receipt deletion with the attempt. Existing consent retention constraints still prevent physical account deletion; this cascade does not implement account erasure. Interpretation of these signals is separate work.
The notice about the collected signals is stored separately. `GET` and `PUT /api/v1/me/assessment-signal-notice` read and write the candidate's acknowledgement of a text version (`usecase/assessment/signal_notice.go`, table `assessment_signal_notice_acknowledgements`, migration 34). The server sets the text version (`CurrentSignalNoticeVersion`, now 2: version 2 added the measures the page applies during an attempt to the signal list); an acknowledgement is stored per version, so one given for version 1 stays stored but never counts for version 2 and a new text needs no migration. A `PUT` with another version answers 409 and stores nothing, and a repeat keeps the time of the first acknowledgement. The acknowledgement is not a consent: the signal operation does not read it and still requires current C3, so the notice cannot be used to hide a consent. Attempt creation does not check the acknowledgement on the server; the candidate screen enforces the requirement. Rows are deleted by cascade with the user.
The notice about the collected signals is stored separately. `GET` and `PUT /api/v1/me/assessment-signal-notice` read and write the candidate's acknowledgement of a text version (`usecase/assessment/signal_notice.go`, table `assessment_signal_notice_acknowledgements`, migration 34). The server sets the text version (`CurrentSignalNoticeVersion`, now 3: version 2 added the measures the page applies during an attempt to the signal list, and version 3 describes the watermark of the task screen and text); an acknowledgement is stored per version, so one given for an earlier version stays stored but never counts for the current one and a new text needs no migration. A `PUT` with another version answers 409 and stores nothing, and a repeat keeps the time of the first acknowledgement. The acknowledgement is not a consent: the signal operation does not read it and still requires current C3, so the notice cannot be used to hide a consent. Attempt creation does not check the acknowledgement on the server; the candidate screen enforces the requirement. Rows are deleted by cascade with the user.
## Anonymous profile projection
+1 -1
View File
@@ -122,7 +122,7 @@
Операция ограничивает тело 32 КиБ, пакет 50 событиями, новые квитанции приема 30 в минуту на попытку, а хранение 10 000 событиями на попытку. Вместимость проверяется для всего пакета. При заполнении принимается ноль событий; идемпотентный повтор возвращает исходную квитанцию без расходования лимита. Клиентское время считается недоверенными метаданными: метка вне окна от создания попытки минус пять минут до времени БД плюс пять минут отклоняет весь пакет с 400, поэтому клиент приводит метки к серверному времени по заголовку `Date`; окна частоты используют время БД. Миграция 28 каскадно удаляет события, пакеты и квитанции вместе с попыткой. Действующие ограничения хранения согласий по-прежнему запрещают физическое удаление аккаунта; этот каскад не реализует удаление аккаунта. Интерпретация сигналов относится к отдельной работе.
Уведомление о собираемых сигналах хранится отдельно. `GET` и `PUT /api/v1/me/assessment-signal-notice` читают и записывают подтверждение ознакомления кандидата с версией текста (`usecase/assessment/signal_notice.go`, таблица `assessment_signal_notice_acknowledgements`, миграция 34). Версию текста задает сервер (`CurrentSignalNoticeVersion`, сейчас 2: версия 2 добавила к перечню сигналов меры, которые страница применяет во время попытки); подтверждение хранится для каждой версии отдельно, поэтому данное для версии 1 остается в таблице, но для версии 2 не засчитывается, а новый текст не требует миграции. `PUT` с другой версией отвечает 409 и ничего не сохраняет, а повтор сохраняет время первого подтверждения. Подтверждение не является согласием: операция приема сигналов его не читает и по-прежнему требует действующего C3, поэтому уведомление нельзя использовать, чтобы скрыть согласие. Создание попытки подтверждение на сервере не проверяет; требование задает экран кандидата. Строки удаляются каскадом вместе с пользователем.
Уведомление о собираемых сигналах хранится отдельно. `GET` и `PUT /api/v1/me/assessment-signal-notice` читают и записывают подтверждение ознакомления кандидата с версией текста (`usecase/assessment/signal_notice.go`, таблица `assessment_signal_notice_acknowledgements`, миграция 34). Версию текста задает сервер (`CurrentSignalNoticeVersion`, сейчас 3: версия 2 добавила к перечню сигналов меры, которые страница применяет во время попытки, а версия 3 описывает водяной знак экрана и текста задания); подтверждение хранится для каждой версии отдельно, поэтому данное для более ранней версии остается в таблице, но для текущей не засчитывается, а новый текст не требует миграции. `PUT` с другой версией отвечает 409 и ничего не сохраняет, а повтор сохраняет время первого подтверждения. Подтверждение не является согласием: операция приема сигналов его не читает и по-прежнему требует действующего C3, поэтому уведомление нельзя использовать, чтобы скрыть согласие. Создание попытки подтверждение на сервере не проверяет; требование задает экран кандидата. Строки удаляются каскадом вместе с пользователем.
## Анонимная проекция профиля
@@ -580,7 +580,11 @@ func newAssessmentAttemptHTTPHarnessWithMiddleware(
t.Fatalf("NewSignalObserver() error = %v", err)
}
attemptService.WithSignalObserver(signalObserver)
attemptHandler := v1.NewAssessmentHandler(attemptService)
watermarker, err := assessment.NewWatermarker(keyring)
if err != nil {
t.Fatalf("NewWatermarker() error = %v", err)
}
attemptHandler := v1.NewAssessmentHandler(attemptService).WithPresenter(watermarker)
signalService, err := assessment.NewSignalService(transactor, keyring, clock.Now)
if err != nil {
t.Fatalf("NewSignalService() error = %v", err)
@@ -5,10 +5,13 @@ package integration_test
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"time"
"lincodex/backend/internal/usecase/assessment"
)
const assessmentSignalNoticePath = "/api/v1/me/assessment-signal-notice"
@@ -19,6 +22,11 @@ type signalNoticeProjection struct {
AcknowledgedAt *string `json:"acknowledged_at"`
}
// noticeBody is the request body that acknowledges the given notice version.
func noticeBody(version int) string {
return fmt.Sprintf(`{"notice_version":%d}`, version)
}
func decodeSignalNotice(t *testing.T, response *httptest.ResponseRecorder) signalNoticeProjection {
t.Helper()
if response.Code != http.StatusOK {
@@ -45,6 +53,9 @@ func TestAssessmentSignalNoticeOverHTTP(t *testing.T) {
harness := newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv)
t.Cleanup(harness.pool.Close)
// The tests follow the version the server requires, so a new text version
// needs no edit here.
current := int(assessment.CurrentSignalNoticeVersion)
passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass)
if err != nil {
t.Fatalf("HashNewPassword() error = %v", err)
@@ -63,7 +74,7 @@ func TestAssessmentSignalNoticeOverHTTP(t *testing.T) {
requireSessionProblem(t, anonymous, http.StatusUnauthorized, "unauthenticated")
before := decodeSignalNotice(t, request(http.MethodGet, "", "", cookie.Value, ""))
if before.NoticeVersion != 2 || before.Acknowledged || before.AcknowledgedAt != nil {
if before.NoticeVersion != current || before.Acknowledged || before.AcknowledgedAt != nil {
t.Fatalf("notice before acknowledgement = %+v", before)
}
@@ -77,21 +88,21 @@ func TestAssessmentSignalNoticeOverHTTP(t *testing.T) {
if rejected := request(http.MethodPut, `{"notice_version":1,"accepted":true}`, sessionHTTPTestOrigin, cookie.Value, csrf); rejected.Code != http.StatusBadRequest {
t.Fatalf("unknown field = %d %s, want 400", rejected.Code, rejected.Body.String())
}
requireSessionProblem(t, request(http.MethodPut, `{"notice_version":3}`, sessionHTTPTestOrigin, cookie.Value, csrf),
requireSessionProblem(t, request(http.MethodPut, noticeBody(current+1), sessionHTTPTestOrigin, cookie.Value, csrf),
http.StatusConflict, "state_conflict")
// The previous version is no longer the one the server requires.
requireSessionProblem(t, request(http.MethodPut, `{"notice_version":1}`, sessionHTTPTestOrigin, cookie.Value, csrf),
requireSessionProblem(t, request(http.MethodPut, noticeBody(current-1), sessionHTTPTestOrigin, cookie.Value, csrf),
http.StatusConflict, "state_conflict")
if untouched := decodeSignalNotice(t, request(http.MethodGet, "", "", cookie.Value, "")); untouched.Acknowledged {
t.Fatalf("a refused request stored an acknowledgement: %+v", untouched)
}
first := decodeSignalNotice(t, request(http.MethodPut, `{"notice_version":2}`, sessionHTTPTestOrigin, cookie.Value, csrf))
if !first.Acknowledged || first.AcknowledgedAt == nil || first.NoticeVersion != 2 {
first := decodeSignalNotice(t, request(http.MethodPut, noticeBody(current), sessionHTTPTestOrigin, cookie.Value, csrf))
if !first.Acknowledged || first.AcknowledgedAt == nil || first.NoticeVersion != current {
t.Fatalf("first acknowledgement = %+v", first)
}
time.Sleep(5 * time.Millisecond)
repeat := decodeSignalNotice(t, request(http.MethodPut, `{"notice_version":2}`, sessionHTTPTestOrigin, cookie.Value, csrf))
repeat := decodeSignalNotice(t, request(http.MethodPut, noticeBody(current), sessionHTTPTestOrigin, cookie.Value, csrf))
if repeat.AcknowledgedAt == nil || *repeat.AcknowledgedAt != *first.AcknowledgedAt {
t.Fatalf("a repeat changed the first acknowledgement time: first %+v, repeat %+v", first, repeat)
}
@@ -104,7 +115,7 @@ func TestAssessmentSignalNoticeOverHTTP(t *testing.T) {
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM assessment_signal_notice_acknowledgements WHERE user_id = $1", candidate.ID).Scan(&rows); err != nil || rows != 1 {
t.Fatalf("stored acknowledgement rows = %d, error %v, want exactly one", rows, err)
}
// An acknowledgement of version 1 stays stored but does not count for version 2.
// An acknowledgement of version 1 stays stored but does not count for the current version.
if _, err := harness.pool.Exec(ctx, "INSERT INTO assessment_signal_notice_acknowledgements (user_id, notice_version, acknowledged_at) VALUES ($1, 1, now())", other.ID); err != nil {
t.Fatalf("store a version 1 acknowledgement: %v", err)
}
@@ -113,7 +124,7 @@ func TestAssessmentSignalNoticeOverHTTP(t *testing.T) {
}
requireSessionProblem(t, request(http.MethodGet, "", "", employerCookie.Value, ""), http.StatusForbidden, "forbidden")
requireSessionProblem(t, request(http.MethodPut, `{"notice_version":2}`, sessionHTTPTestOrigin, employerCookie.Value, employerCSRF),
requireSessionProblem(t, request(http.MethodPut, noticeBody(current), sessionHTTPTestOrigin, employerCookie.Value, employerCSRF),
http.StatusForbidden, "forbidden")
// The acknowledgement is a record, not a consent: it creates no ledger row.
@@ -0,0 +1,148 @@
//go:build integration
package integration_test
import (
"context"
"encoding/json"
"net/http"
"strings"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
)
const assessmentWatermarkHTTPTimeout = 6 * time.Minute
// TestAssessmentWatermarkOverHTTP checks the mark on the path from the stored
// attempt to the response: a real attempt shows a code and a marked task text
// on every read, a training run shows neither, and the stored variant stays
// unmarked, so the reference answer and the grading never see the mark.
func TestAssessmentWatermarkOverHTTP(t *testing.T) {
env := bootstrap(t, postgresService, redisService)
ctx, cancel := context.WithTimeout(t.Context(), assessmentWatermarkHTTPTimeout)
defer cancel()
databaseURL := env.createIsolatedDatabase(ctx, t)
applyMigrations(ctx, t, databaseURL)
isolatedEnv := *env
isolatedEnv.Config.DatabaseURL = databaseURL
harness := newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv)
t.Cleanup(harness.pool.Close)
seedAssessmentAttemptHTTPBank(ctx, t, harness.pool)
passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass)
if err != nil {
t.Fatalf("HashNewPassword() error = %v", err)
}
candidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "watermark-owner@example.test", passwordHash, true)
if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step = 'candidate_questionnaire' WHERE id = $1", candidate.ID); err != nil {
t.Fatalf("set candidate onboarding step: %v", err)
}
cookie, csrf := loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "192.0.2.231:1234")
if response := assessmentAttemptQuestionnaireRequest(t, harness, cookie.Value, csrf, "192.0.2.232:1234"); response.Code != http.StatusOK {
t.Fatalf("save candidate questionnaire = %d %s", response.Code, response.Body.String())
}
training := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", `{"kind":"demo_express"}`,
sessionHTTPTestOrigin, cookie.Value, csrf, "watermark-training", "192.0.2.233:1234")
if training.Code != http.StatusCreated {
t.Fatalf("create training attempt = %d %s", training.Code, training.Body.String())
}
if watermark, prompt := decodeWatermarkedAttempt(t, training.Body.Bytes()); watermark != "" || hasZeroWidth(prompt) {
t.Fatalf("training attempt carries watermark %q or a marked prompt, want neither", watermark)
}
grantCurrentAttemptConsent(t, harness, cookie, csrf, "192.0.2.237:1234")
create := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts",
assessmentAttemptCreateBody(t, "backend"), sessionHTTPTestOrigin, cookie.Value, csrf, "watermark-root", "192.0.2.234:1234")
if create.Code != http.StatusCreated {
t.Fatalf("create real attempt = %d %s", create.Code, create.Body.String())
}
attemptID, _ := assessmentSignalAttemptItem(t, create.Body.Bytes())
code, prompt := decodeWatermarkedAttempt(t, create.Body.Bytes())
want := domainWatermark(t, harness, attemptID)
if code != want.Code().String() {
t.Fatalf("created attempt code = %q, want the code derived on the server %q", code, want.Code())
}
marks := domain.ExtractAssessmentWatermarkCodes(prompt)
if len(marks) == 0 || marks[0] != want.Code() {
t.Fatalf("invisible mark of the prompt = %v, want %s", marks, want.Code())
}
// A later read, and a replay of the creation, give the same code and text.
read := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, "/api/v1/me/assessment-attempts/"+attemptID.String(), "",
"", cookie.Value, "", "", "192.0.2.235:1234")
if read.Code != http.StatusOK {
t.Fatalf("read attempt = %d %s", read.Code, read.Body.String())
}
if readCode, readPrompt := decodeWatermarkedAttempt(t, read.Body.Bytes()); readCode != code || readPrompt != prompt {
t.Fatalf("read attempt code/prompt = %q/%q, want the created ones %q/%q", readCode, readPrompt, code, prompt)
}
replay := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts",
assessmentAttemptCreateBody(t, "backend"), sessionHTTPTestOrigin, cookie.Value, csrf, "watermark-root", "192.0.2.236:1234")
if replayCode, replayPrompt := decodeWatermarkedAttempt(t, replay.Body.Bytes()); replay.Code != http.StatusCreated || replayCode != code || replayPrompt != prompt {
t.Fatalf("replayed creation = %d with code/prompt %q/%q, want the original ones", replay.Code, replayCode, replayPrompt)
}
// The response carries nothing of the key or the seed.
for _, secret := range []string{"seed", "key"} {
var document map[string]any
if err := json.Unmarshal(read.Body.Bytes(), &document); err != nil {
t.Fatalf("decode attempt: %v", err)
}
if watermark, ok := document["watermark"].(map[string]any); !ok || len(watermark) != 1 {
t.Fatalf("watermark object = %+v, want only a code", document["watermark"])
}
if _, exposed := document[secret]; exposed {
t.Fatalf("attempt response exposes %q", secret)
}
}
// The stored variant is the unmarked statement; grading reads it.
var stored string
if err := harness.pool.QueryRow(ctx, `SELECT variant->>'Statement' FROM assessment_attempt_items WHERE attempt_id = $1 ORDER BY ordinal LIMIT 1`, attemptID).Scan(&stored); err != nil {
t.Fatalf("read the stored statement: %v", err)
}
if hasZeroWidth(stored) {
t.Fatal("the stored statement carries an invisible mark, want the mark only on the presented text")
}
if domain.CanonicalAssessmentText(prompt) != domain.CanonicalAssessmentText(stored) {
t.Fatalf("the presented prompt differs in meaning from the stored statement:\n%q\n%q", prompt, stored)
}
}
func decodeWatermarkedAttempt(t *testing.T, body []byte) (code, prompt string) {
t.Helper()
var attempt struct {
Watermark *struct {
Code string `json:"code"`
} `json:"watermark"`
CurrentItem *struct {
Prompt string `json:"prompt"`
} `json:"current_item"`
}
if err := json.Unmarshal(body, &attempt); err != nil || attempt.CurrentItem == nil {
t.Fatalf("decode attempt: %+v, error %v", attempt, err)
}
if attempt.Watermark != nil {
code = attempt.Watermark.Code
}
return code, attempt.CurrentItem.Prompt
}
func hasZeroWidth(text string) bool {
return strings.ContainsAny(text, "\u200b\u200c\u200d\u2060")
}
func domainWatermark(t *testing.T, harness *assessmentAttemptHTTPHarness, attemptID uuid.UUID) domain.AssessmentWatermark {
t.Helper()
watermark, err := domain.NewAssessmentWatermark(harness.keyring.AssessmentWatermarkSeed(attemptID))
if err != nil {
t.Fatalf("NewAssessmentWatermark() error = %v", err)
}
return watermark
}
@@ -17,26 +17,27 @@ import (
)
var regexMap = map[string]ogenregex.Regexp{
"\\S": ogenregex.MustCompile("\\S"),
"^(/([^~/]|~[01])*)*$": ogenregex.MustCompile("^(/([^~/]|~[01])*)*$"),
"^/[A-Za-z0-9/_-]{0,255}$": ogenregex.MustCompile("^/[A-Za-z0-9/_-]{0,255}$"),
"^@[A-Za-z0-9_]{5,32}$": ogenregex.MustCompile("^@[A-Za-z0-9_]{5,32}$"),
"^SC-[0-9]{4}-[0-9]{6,10}$": ogenregex.MustCompile("^SC-[0-9]{4}-[0-9]{6,10}$"),
"^[0-9]{4}-(0[1-9]|1[0-2])$": ogenregex.MustCompile("^[0-9]{4}-(0[1-9]|1[0-2])$"),
"^[0-9]{6}$": ogenregex.MustCompile("^[0-9]{6}$"),
"^[A-Za-z0-9._-]+$": ogenregex.MustCompile("^[A-Za-z0-9._-]+$"),
"^[A-Za-z0-9._:-]+$": ogenregex.MustCompile("^[A-Za-z0-9._:-]+$"),
"^[A-Za-z0-9_-]+$": ogenregex.MustCompile("^[A-Za-z0-9_-]+$"),
"^[a-z0-9][a-z0-9_.+#-]*$": ogenregex.MustCompile("^[a-z0-9][a-z0-9_.+#-]*$"),
"^[a-z0-9_+-]+$": ogenregex.MustCompile("^[a-z0-9_+-]+$"),
"^[a-z0-9_]+$": ogenregex.MustCompile("^[a-z0-9_]+$"),
"^[a-z][a-z0-9_]*$": ogenregex.MustCompile("^[a-z][a-z0-9_]*$"),
"^\\+[1-9][0-9]{6,14}$": ogenregex.MustCompile("^\\+[1-9][0-9]{6,14}$"),
"^\\S(?:.*\\S)?$": ogenregex.MustCompile("^\\S(?:.*\\S)?$"),
"^\\S(?:[^\\n\\r]*\\S)?$": ogenregex.MustCompile("^\\S(?:[^\\n\\r]*\\S)?$"),
"^__Host-lincodex_session=": ogenregex.MustCompile("^__Host-lincodex_session="),
"^cv1_[A-Za-z0-9_-]{43}$": ogenregex.MustCompile("^cv1_[A-Za-z0-9_-]{43}$"),
"^https://[^\\s/?#@]+(?:[/?#][^\\s]*)?$": ogenregex.MustCompile("^https://[^\\s/?#@]+(?:[/?#][^\\s]*)?$"),
"\\S": ogenregex.MustCompile("\\S"),
"^(/([^~/]|~[01])*)*$": ogenregex.MustCompile("^(/([^~/]|~[01])*)*$"),
"^/[A-Za-z0-9/_-]{0,255}$": ogenregex.MustCompile("^/[A-Za-z0-9/_-]{0,255}$"),
"^@[A-Za-z0-9_]{5,32}$": ogenregex.MustCompile("^@[A-Za-z0-9_]{5,32}$"),
"^SC-[0-9]{4}-[0-9]{6,10}$": ogenregex.MustCompile("^SC-[0-9]{4}-[0-9]{6,10}$"),
"^[0-9A-HJKMNP-TV-Z]{5}-?[0-9A-HJKMNP-TV-Z]{5}$": ogenregex.MustCompile("^[0-9A-HJKMNP-TV-Z]{5}-?[0-9A-HJKMNP-TV-Z]{5}$"),
"^[0-9]{4}-(0[1-9]|1[0-2])$": ogenregex.MustCompile("^[0-9]{4}-(0[1-9]|1[0-2])$"),
"^[0-9]{6}$": ogenregex.MustCompile("^[0-9]{6}$"),
"^[A-Za-z0-9._-]+$": ogenregex.MustCompile("^[A-Za-z0-9._-]+$"),
"^[A-Za-z0-9._:-]+$": ogenregex.MustCompile("^[A-Za-z0-9._:-]+$"),
"^[A-Za-z0-9_-]+$": ogenregex.MustCompile("^[A-Za-z0-9_-]+$"),
"^[a-z0-9][a-z0-9_.+#-]*$": ogenregex.MustCompile("^[a-z0-9][a-z0-9_.+#-]*$"),
"^[a-z0-9_+-]+$": ogenregex.MustCompile("^[a-z0-9_+-]+$"),
"^[a-z0-9_]+$": ogenregex.MustCompile("^[a-z0-9_]+$"),
"^[a-z][a-z0-9_]*$": ogenregex.MustCompile("^[a-z][a-z0-9_]*$"),
"^\\+[1-9][0-9]{6,14}$": ogenregex.MustCompile("^\\+[1-9][0-9]{6,14}$"),
"^\\S(?:.*\\S)?$": ogenregex.MustCompile("^\\S(?:.*\\S)?$"),
"^\\S(?:[^\\n\\r]*\\S)?$": ogenregex.MustCompile("^\\S(?:[^\\n\\r]*\\S)?$"),
"^__Host-lincodex_session=": ogenregex.MustCompile("^__Host-lincodex_session="),
"^cv1_[A-Za-z0-9_-]{43}$": ogenregex.MustCompile("^cv1_[A-Za-z0-9_-]{43}$"),
"^https://[^\\s/?#@]+(?:[/?#][^\\s]*)?$": ogenregex.MustCompile("^https://[^\\s/?#@]+(?:[/?#][^\\s]*)?$"),
"^https://github\\.com/[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})/[A-Za-z0-9._-]{1,100}/?$": ogenregex.MustCompile("^https://github\\.com/[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})/[A-Za-z0-9._-]{1,100}/?$"),
}
var (
@@ -1496,6 +1496,12 @@ func (s AssessmentAttempt) encodeFields(e *jx.Encoder) {
}
e.ArrEnd()
}
{
if s.Watermark.Set {
e.FieldStart("watermark")
s.Watermark.Encode(e)
}
}
}
case AssessmentCorrectiveAttemptAssessmentAttempt:
e.FieldStart("kind")
@@ -1574,6 +1580,12 @@ func (s AssessmentAttempt) encodeFields(e *jx.Encoder) {
}
e.ArrEnd()
}
{
if s.Watermark.Set {
e.FieldStart("watermark")
s.Watermark.Encode(e)
}
}
}
case AssessmentExpressAttemptAssessmentAttempt:
e.FieldStart("kind")
@@ -1652,6 +1664,12 @@ func (s AssessmentAttempt) encodeFields(e *jx.Encoder) {
}
e.ArrEnd()
}
{
if s.Watermark.Set {
e.FieldStart("watermark")
s.Watermark.Encode(e)
}
}
}
}
}
@@ -2712,9 +2730,15 @@ func (s *AssessmentCorrectiveAttempt) encodeFields(e *jx.Encoder) {
}
e.ArrEnd()
}
{
if s.Watermark.Set {
e.FieldStart("watermark")
s.Watermark.Encode(e)
}
}
}
var jsonFieldsNameOfAssessmentCorrectiveAttempt = [18]string{
var jsonFieldsNameOfAssessmentCorrectiveAttempt = [19]string{
0: "id",
1: "version",
2: "specialization",
@@ -2733,6 +2757,7 @@ var jsonFieldsNameOfAssessmentCorrectiveAttempt = [18]string{
15: "progress",
16: "current_item",
17: "practices",
18: "watermark",
}
// Decode decodes AssessmentCorrectiveAttempt from json.
@@ -2934,6 +2959,16 @@ func (s *AssessmentCorrectiveAttempt) Decode(d *jx.Decoder) error {
}(); err != nil {
return errors.Wrap(err, "decode field \"practices\"")
}
case "watermark":
if err := func() error {
s.Watermark.Reset()
if err := s.Watermark.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"watermark\"")
}
default:
return errors.Errorf("unexpected field %q", k)
}
@@ -4031,9 +4066,15 @@ func (s *AssessmentExpressAttempt) encodeFields(e *jx.Encoder) {
}
e.ArrEnd()
}
{
if s.Watermark.Set {
e.FieldStart("watermark")
s.Watermark.Encode(e)
}
}
}
var jsonFieldsNameOfAssessmentExpressAttempt = [18]string{
var jsonFieldsNameOfAssessmentExpressAttempt = [19]string{
0: "id",
1: "version",
2: "specialization",
@@ -4052,6 +4093,7 @@ var jsonFieldsNameOfAssessmentExpressAttempt = [18]string{
15: "progress",
16: "current_item",
17: "practices",
18: "watermark",
}
// Decode decodes AssessmentExpressAttempt from json.
@@ -4253,6 +4295,16 @@ func (s *AssessmentExpressAttempt) Decode(d *jx.Decoder) error {
}(); err != nil {
return errors.Wrap(err, "decode field \"practices\"")
}
case "watermark":
if err := func() error {
s.Watermark.Reset()
if err := s.Watermark.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"watermark\"")
}
default:
return errors.Errorf("unexpected field %q", k)
}
@@ -7488,9 +7540,15 @@ func (s *AssessmentQualifiedAttempt) encodeFields(e *jx.Encoder) {
}
e.ArrEnd()
}
{
if s.Watermark.Set {
e.FieldStart("watermark")
s.Watermark.Encode(e)
}
}
}
var jsonFieldsNameOfAssessmentQualifiedAttempt = [18]string{
var jsonFieldsNameOfAssessmentQualifiedAttempt = [19]string{
0: "id",
1: "version",
2: "specialization",
@@ -7509,6 +7567,7 @@ var jsonFieldsNameOfAssessmentQualifiedAttempt = [18]string{
15: "progress",
16: "current_item",
17: "practices",
18: "watermark",
}
// Decode decodes AssessmentQualifiedAttempt from json.
@@ -7710,6 +7769,16 @@ func (s *AssessmentQualifiedAttempt) Decode(d *jx.Decoder) error {
}(); err != nil {
return errors.Wrap(err, "decode field \"practices\"")
}
case "watermark":
if err := func() error {
s.Watermark.Reset()
if err := s.Watermark.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"watermark\"")
}
default:
return errors.Errorf("unexpected field %q", k)
}
@@ -10838,6 +10907,102 @@ func (s *AssessmentVersions) UnmarshalJSON(data []byte) error {
return s.Decode(d)
}
// Encode implements json.Marshaler.
func (s *AssessmentWatermark) Encode(e *jx.Encoder) {
e.ObjStart()
s.encodeFields(e)
e.ObjEnd()
}
// encodeFields encodes fields.
func (s *AssessmentWatermark) encodeFields(e *jx.Encoder) {
{
e.FieldStart("code")
e.Str(s.Code)
}
}
var jsonFieldsNameOfAssessmentWatermark = [1]string{
0: "code",
}
// Decode decodes AssessmentWatermark from json.
func (s *AssessmentWatermark) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode AssessmentWatermark to nil")
}
var requiredBitSet [1]uint8
if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error {
switch string(k) {
case "code":
requiredBitSet[0] |= 1 << 0
if err := func() error {
v, err := d.Str()
s.Code = string(v)
if err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"code\"")
}
default:
return errors.Errorf("unexpected field %q", k)
}
return nil
}); err != nil {
return errors.Wrap(err, "decode AssessmentWatermark")
}
// Validate required fields.
var failures []validate.FieldError
for i, mask := range [1]uint8{
0b00000001,
} {
if result := (requiredBitSet[i] & mask) ^ mask; result != 0 {
// Mask only required fields and check equality to mask using XOR.
//
// If XOR result is not zero, result is not equal to expected, so some fields are missed.
// Bits of fields which would be set are actually bits of missed fields.
missed := bits.OnesCount8(result)
for bitN := 0; bitN < missed; bitN++ {
bitIdx := bits.TrailingZeros8(result)
fieldIdx := i*8 + bitIdx
var name string
if fieldIdx < len(jsonFieldsNameOfAssessmentWatermark) {
name = jsonFieldsNameOfAssessmentWatermark[fieldIdx]
} else {
name = strconv.Itoa(fieldIdx)
}
failures = append(failures, validate.FieldError{
Name: name,
Error: validate.ErrFieldRequired,
})
// Reset bit.
result &^= 1 << bitIdx
}
}
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *AssessmentWatermark) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *AssessmentWatermark) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode implements json.Marshaler.
func (s *BasicScore) Encode(e *jx.Encoder) {
e.ObjStart()
@@ -43534,6 +43699,39 @@ func (s *OptAssessmentCategoryDecisionView) UnmarshalJSON(data []byte) error {
return s.Decode(d)
}
// Encode encodes AssessmentWatermark as json.
func (o OptAssessmentWatermark) Encode(e *jx.Encoder) {
if !o.Set {
return
}
o.Value.Encode(e)
}
// Decode decodes AssessmentWatermark from json.
func (o *OptAssessmentWatermark) Decode(d *jx.Decoder) error {
if o == nil {
return errors.New("invalid: unable to decode OptAssessmentWatermark to nil")
}
o.Set = true
if err := o.Value.Decode(d); err != nil {
return err
}
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s OptAssessmentWatermark) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *OptAssessmentWatermark) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes CandidateSalaryCompatibility as json.
func (o OptCandidateSalaryCompatibility) Encode(e *jx.Encoder) {
if !o.Set {
@@ -1387,7 +1387,8 @@ type AssessmentCorrectiveAttempt struct {
// otherwise.
CurrentItem NilAssessmentItem `json:"current_item"`
// Practices in the order assigned by the mode policy. The list exposes verdicts only after submission.
Practices []AssessmentPractice `json:"practices"`
Practices []AssessmentPractice `json:"practices"`
Watermark OptAssessmentWatermark `json:"watermark"`
}
// GetID returns the value of ID.
@@ -1480,6 +1481,11 @@ func (s *AssessmentCorrectiveAttempt) GetPractices() []AssessmentPractice {
return s.Practices
}
// GetWatermark returns the value of Watermark.
func (s *AssessmentCorrectiveAttempt) GetWatermark() OptAssessmentWatermark {
return s.Watermark
}
// SetID sets the value of ID.
func (s *AssessmentCorrectiveAttempt) SetID(val uuid.UUID) {
s.ID = val
@@ -1570,6 +1576,11 @@ func (s *AssessmentCorrectiveAttempt) SetPractices(val []AssessmentPractice) {
s.Practices = val
}
// SetWatermark sets the value of Watermark.
func (s *AssessmentCorrectiveAttempt) SetWatermark(val OptAssessmentWatermark) {
s.Watermark = val
}
// Start a corrective real assessment at a lower target grade in the chain rooted at root_attempt_id.
// The server validates that this grade is strictly below the preceding grade and that the chain
// remains within its existing deadline and quota. chain_deadline is derived from the root attempt and
@@ -2172,7 +2183,8 @@ type AssessmentExpressAttempt struct {
// otherwise.
CurrentItem NilAssessmentItem `json:"current_item"`
// Practices in the order assigned by the mode policy. The list exposes verdicts only after submission.
Practices []AssessmentPractice `json:"practices"`
Practices []AssessmentPractice `json:"practices"`
Watermark OptAssessmentWatermark `json:"watermark"`
}
// GetID returns the value of ID.
@@ -2265,6 +2277,11 @@ func (s *AssessmentExpressAttempt) GetPractices() []AssessmentPractice {
return s.Practices
}
// GetWatermark returns the value of Watermark.
func (s *AssessmentExpressAttempt) GetWatermark() OptAssessmentWatermark {
return s.Watermark
}
// SetID sets the value of ID.
func (s *AssessmentExpressAttempt) SetID(val uuid.UUID) {
s.ID = val
@@ -2355,6 +2372,11 @@ func (s *AssessmentExpressAttempt) SetPractices(val []AssessmentPractice) {
s.Practices = val
}
// SetWatermark sets the value of Watermark.
func (s *AssessmentExpressAttempt) SetWatermark(val OptAssessmentWatermark) {
s.Watermark = val
}
// Explicitly start the short training run. It has no specialization or target grade, uses its separate
// demo policy, and does not consume a real-assessment attempt.
// Ref: #/components/schemas/AssessmentExpressAttemptCreate
@@ -4003,7 +4025,8 @@ type AssessmentQualifiedAttempt struct {
// otherwise.
CurrentItem NilAssessmentItem `json:"current_item"`
// Practices in the order assigned by the mode policy. The list exposes verdicts only after submission.
Practices []AssessmentPractice `json:"practices"`
Practices []AssessmentPractice `json:"practices"`
Watermark OptAssessmentWatermark `json:"watermark"`
}
// GetID returns the value of ID.
@@ -4096,6 +4119,11 @@ func (s *AssessmentQualifiedAttempt) GetPractices() []AssessmentPractice {
return s.Practices
}
// GetWatermark returns the value of Watermark.
func (s *AssessmentQualifiedAttempt) GetWatermark() OptAssessmentWatermark {
return s.Watermark
}
// SetID sets the value of ID.
func (s *AssessmentQualifiedAttempt) SetID(val uuid.UUID) {
s.ID = val
@@ -4186,6 +4214,11 @@ func (s *AssessmentQualifiedAttempt) SetPractices(val []AssessmentPractice) {
s.Practices = val
}
// SetWatermark sets the value of Watermark.
func (s *AssessmentQualifiedAttempt) SetWatermark(val OptAssessmentWatermark) {
s.Watermark = val
}
// Start a real assessment for a specialization and target grade, with the task language. The candidate
// comes from the session. The server chooses demo_basic or adaptive and fixes the policy, bank, and
// algorithm versions. Unknown fields such as `mode`, `seed`, or `score` are rejected.
@@ -5611,6 +5644,30 @@ func (s *AssessmentVersions) SetAlgorithmVersion(val AssessmentVersionLabel) {
s.AlgorithmVersion = val
}
// Visible mark of a real attempt. The client shows `code` with the current time as a faint tile over
// the task screen, so that a screenshot or a photo of the screen can be traced back to the attempt by
// an operator. The code is a keyed pseudonym derived on the server: it carries no name, contact, or
// identifier of the account, and it cannot be computed without the server secret. The task text of
// such an attempt also carries an invisible mark and interchangeable wordings chosen by the same
// secret; they change neither the meaning of a task nor its reference answer, and the client keeps the
// invisible characters out of the accessibility tree. Training runs (`demo_express`) carry no
// watermark. It is evidence for a manual review and an appeal, never an automatic decision.
// Ref: #/components/schemas/AssessmentWatermark
type AssessmentWatermark struct {
// Two groups of five symbols of Crockford base32, such as `7K3QD-9XM2T`.
Code string `json:"code"`
}
// GetCode returns the value of Code.
func (s *AssessmentWatermark) GetCode() string {
return s.Code
}
// SetCode sets the value of Code.
func (s *AssessmentWatermark) SetCode(val string) {
s.Code = val
}
// Raw score of a demo_basic attempt and the pass mark of the recorded basic grading policy. The pass
// mark comes from that policy version and never from the handler.
// Ref: #/components/schemas/BasicScore
@@ -21811,6 +21868,52 @@ func (o OptAssessmentCategoryDecisionView) Or(d AssessmentCategoryDecisionView)
return d
}
// NewOptAssessmentWatermark returns new OptAssessmentWatermark with value set to v.
func NewOptAssessmentWatermark(v AssessmentWatermark) OptAssessmentWatermark {
return OptAssessmentWatermark{
Value: v,
Set: true,
}
}
// OptAssessmentWatermark is optional AssessmentWatermark.
type OptAssessmentWatermark struct {
Value AssessmentWatermark
Set bool
}
// IsSet returns true if OptAssessmentWatermark was set.
func (o OptAssessmentWatermark) IsSet() bool { return o.Set }
// Reset unsets value.
func (o *OptAssessmentWatermark) Reset() {
var v AssessmentWatermark
o.Value = v
o.Set = false
}
// SetTo sets value to v.
func (o *OptAssessmentWatermark) SetTo(v AssessmentWatermark) {
o.Set = true
o.Value = v
}
// Get returns value and boolean that denotes whether value was set.
func (o OptAssessmentWatermark) Get() (v AssessmentWatermark, ok bool) {
if !o.Set {
return v, false
}
return o.Value, true
}
// Or returns value if set, or given parameter if does not.
func (o OptAssessmentWatermark) Or(d AssessmentWatermark) AssessmentWatermark {
if v, ok := o.Get(); ok {
return v
}
return d
}
// NewOptCandidateSalaryCompatibility returns new OptCandidateSalaryCompatibility with value set to v.
func NewOptCandidateSalaryCompatibility(v CandidateSalaryCompatibility) OptCandidateSalaryCompatibility {
return OptCandidateSalaryCompatibility{
@@ -1186,6 +1186,24 @@ func (s *AssessmentCorrectiveAttempt) Validate() error {
Error: err,
})
}
if err := func() error {
if value, ok := s.Watermark.Get(); ok {
if err := func() error {
if err := value.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "watermark",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
@@ -1954,6 +1972,24 @@ func (s *AssessmentExpressAttempt) Validate() error {
Error: err,
})
}
if err := func() error {
if value, ok := s.Watermark.Get(); ok {
if err := func() error {
if err := value.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "watermark",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
@@ -3460,6 +3496,24 @@ func (s *AssessmentQualifiedAttempt) Validate() error {
Error: err,
})
}
if err := func() error {
if value, ok := s.Watermark.Get(); ok {
if err := func() error {
if err := value.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "watermark",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
@@ -4735,6 +4789,41 @@ func (s *AssessmentVersions) Validate() error {
return nil
}
func (s *AssessmentWatermark) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := (validate.String{
MinLength: 10,
MinLengthSet: true,
MaxLength: 11,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: regexMap["^[0-9A-HJKMNP-TV-Z]{5}-?[0-9A-HJKMNP-TV-Z]{5}$"],
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(s.Code)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "code",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s *BasicScore) Validate() error {
if s == nil {
return validate.ErrNilPointer
@@ -23,9 +23,16 @@ type AssessmentOperations interface {
StartSession(ctx context.Context, command assessmentusecase.StartAttemptSessionCommand) (outbound.AssessmentAttemptSessionResult, error)
}
// AssessmentPresenter turns a stored attempt projection into what the candidate
// receives. It is the one place that marks the task text of a real attempt.
type AssessmentPresenter interface {
Present(snapshot domain.AssessmentAttemptPublicSnapshot) (domain.AssessmentAttemptPublicSnapshot, error)
}
// AssessmentHandler serves the candidate's frozen assessment attempts.
type AssessmentHandler struct {
operations AssessmentOperations
presenter AssessmentPresenter
}
func NewAssessmentHandler(operations AssessmentOperations) *AssessmentHandler {
@@ -35,6 +42,26 @@ func NewAssessmentHandler(operations AssessmentOperations) *AssessmentHandler {
return &AssessmentHandler{operations: operations}
}
// WithPresenter sets the presenter that every attempt response passes through.
// Without one the responses carry the stored projection unchanged.
func (handler *AssessmentHandler) WithPresenter(presenter AssessmentPresenter) *AssessmentHandler {
handler.presenter = presenter
return handler
}
// attemptResponse presents the snapshot and maps it to the response. Every
// operation that returns an attempt goes through it.
func (handler *AssessmentHandler) attemptResponse(snapshot domain.AssessmentAttemptPublicSnapshot) (api.AssessmentAttempt, error) {
if handler.presenter != nil {
presented, err := handler.presenter.Present(snapshot)
if err != nil {
return api.AssessmentAttempt{}, fmt.Errorf("AssessmentHandler.attemptResponse - present attempt: %w", err)
}
snapshot = presented
}
return assessmentAttemptResponse(snapshot)
}
func (handler *Handler) CreateMyAssessmentAttempt(
ctx context.Context,
request api.AssessmentAttemptCreate,
@@ -131,7 +158,7 @@ func (handler *AssessmentHandler) CreateMyAssessmentAttempt(
if result.Outcome.StatusCode != 201 {
return nil, fmt.Errorf("AssessmentHandler.CreateMyAssessmentAttempt - unexpected stored status %d", result.Outcome.StatusCode)
}
response, err := assessmentAttemptResponse(result.Outcome.Response)
response, err := handler.attemptResponse(result.Outcome.Response)
if err != nil {
return nil, fmt.Errorf("AssessmentHandler.CreateMyAssessmentAttempt - map response: %w", err)
}
@@ -150,7 +177,7 @@ func (handler *AssessmentHandler) GetMyAssessmentAttempt(
if err != nil {
return assessmentAttemptReadFailure(ctx, err)
}
response, err := assessmentAttemptResponse(snapshot)
response, err := handler.attemptResponse(snapshot)
if err != nil {
return nil, fmt.Errorf("AssessmentHandler.GetMyAssessmentAttempt - map response: %w", err)
}
@@ -176,7 +203,7 @@ func (handler *AssessmentHandler) StartMyAssessmentAttemptSession(
if err != nil {
return assessmentSessionFailure(ctx, err)
}
response, err := assessmentAttemptResponse(result.Response)
response, err := handler.attemptResponse(result.Response)
if err != nil {
return nil, fmt.Errorf("AssessmentHandler.StartMyAssessmentAttemptSession - map response: %w", err)
}
@@ -216,7 +243,7 @@ func (handler *AssessmentHandler) SubmitMyAssessmentAnswer(
if result.Outcome.StatusCode != 200 {
return assessmentAnswerCommandProblem(ctx, result.Outcome)
}
response, err := assessmentAttemptResponse(result.Outcome.Response)
response, err := handler.attemptResponse(result.Outcome.Response)
if err != nil {
return nil, fmt.Errorf("AssessmentHandler.SubmitMyAssessmentAnswer - map response: %w", err)
}
@@ -251,7 +278,7 @@ func (handler *AssessmentHandler) FinalizeMyAssessmentAttempt(
if result.Outcome.StatusCode != 200 {
return assessmentFinalizeCommandProblem(ctx, result.Outcome)
}
response, err := assessmentAttemptResponse(result.Outcome.Response)
response, err := handler.attemptResponse(result.Outcome.Response)
if err != nil {
return nil, fmt.Errorf("AssessmentHandler.FinalizeMyAssessmentAttempt - map response: %w", err)
}
@@ -714,7 +741,7 @@ func assessmentAttemptResponse(snapshot domain.AssessmentAttemptPublicSnapshot)
Mode: api.AssessmentQualifiedAttemptMode(snapshot.Mode), State: api.AssessmentAttemptState(snapshot.State),
Versions: fields.versions, StartedAt: fields.startedAt, ExpiresAt: fields.expiresAt,
Sessions: fields.sessions, FinishedAt: fields.finishedAt, Progress: fields.progress,
CurrentItem: fields.currentItem, Practices: []api.AssessmentPractice{},
CurrentItem: fields.currentItem, Practices: []api.AssessmentPractice{}, Watermark: fields.watermark,
}), nil
case domain.AssessmentAttemptKindCorrective:
return api.NewAssessmentCorrectiveAttemptAssessmentAttempt(api.AssessmentCorrectiveAttempt{
@@ -724,7 +751,7 @@ func assessmentAttemptResponse(snapshot domain.AssessmentAttemptPublicSnapshot)
Mode: api.AssessmentCorrectiveAttemptMode(snapshot.Mode), State: api.AssessmentAttemptState(snapshot.State),
Versions: fields.versions, StartedAt: fields.startedAt, ExpiresAt: fields.expiresAt,
Sessions: fields.sessions, FinishedAt: fields.finishedAt, Progress: fields.progress,
CurrentItem: fields.currentItem, Practices: []api.AssessmentPractice{},
CurrentItem: fields.currentItem, Practices: []api.AssessmentPractice{}, Watermark: fields.watermark,
}), nil
case domain.AssessmentAttemptKindDemoExpress:
return api.NewAssessmentExpressAttemptAssessmentAttempt(api.AssessmentExpressAttempt{
@@ -734,7 +761,7 @@ func assessmentAttemptResponse(snapshot domain.AssessmentAttemptPublicSnapshot)
Mode: api.AssessmentExpressAttemptMode(snapshot.Mode), State: api.AssessmentAttemptState(snapshot.State),
Versions: fields.versions, StartedAt: fields.startedAt, ExpiresAt: fields.expiresAt,
Sessions: fields.sessions, FinishedAt: fields.finishedAt, Progress: fields.progress,
CurrentItem: fields.currentItem, Practices: []api.AssessmentPractice{},
CurrentItem: fields.currentItem, Practices: []api.AssessmentPractice{}, Watermark: fields.watermark,
}), nil
default:
return api.AssessmentAttempt{}, errors.New("unknown assessment attempt kind")
@@ -754,6 +781,7 @@ type assessmentAttemptResponseFields struct {
finishedAt api.NilTimestamp
progress api.AssessmentProgress
currentItem api.NilAssessmentItem
watermark api.OptAssessmentWatermark
}
func assessmentAttemptFields(snapshot domain.AssessmentAttemptPublicSnapshot, currentItem api.NilAssessmentItem) assessmentAttemptResponseFields {
@@ -766,6 +794,9 @@ func assessmentAttemptFields(snapshot domain.AssessmentAttemptPublicSnapshot, cu
progress: api.AssessmentProgress{AnsweredItems: snapshot.AnsweredItems, MaxItems: snapshot.MaxItems},
currentItem: currentItem,
}
if snapshot.Watermark != nil {
fields.watermark.SetTo(api.AssessmentWatermark{Code: snapshot.Watermark.Code})
}
setAttemptTrackFields(&fields, snapshot)
setAttemptSessionFields(&fields, snapshot)
setAttemptEndFields(&fields, snapshot)
@@ -235,3 +235,73 @@ func assessmentPublicSnapshot() domain.AssessmentAttemptPublicSnapshot {
func domainCodePointer[T ~string](value T) *T {
return &value
}
type presenterStub struct{ err error }
func (stub presenterStub) Present(snapshot domain.AssessmentAttemptPublicSnapshot) (domain.AssessmentAttemptPublicSnapshot, error) {
if stub.err != nil {
return domain.AssessmentAttemptPublicSnapshot{}, stub.err
}
snapshot.Watermark = &domain.AssessmentAttemptPublicWatermark{Code: "7K3QD-9XM2T"}
item := *snapshot.CurrentItem
item.Prompt += "\u200b"
snapshot.CurrentItem = &item
return snapshot, nil
}
func TestEveryAttemptResponsePassesThroughThePresenter(t *testing.T) {
snapshot := assessmentPublicSnapshot()
operations := &assessmentOperationsStub{read: snapshot, start: outbound.AssessmentAttemptSessionResult{Response: snapshot}}
handler := NewAssessmentHandler(operations).WithPresenter(presenterStub{})
ctx := principalForTest(uuid.New())
read, err := handler.GetMyAssessmentAttempt(ctx, api.GetMyAssessmentAttemptParams{AttemptID: snapshot.ID.UUID()})
if err != nil {
t.Fatalf("GetMyAssessmentAttempt() error = %v", err)
}
started, err := handler.StartMyAssessmentAttemptSession(ctx, &api.AssessmentAttemptSessionStart{ExpectedVersion: 7},
api.StartMyAssessmentAttemptSessionParams{AttemptID: snapshot.ID.UUID(), IdempotencyKey: "session-key"})
if err != nil {
t.Fatalf("StartMyAssessmentAttemptSession() error = %v", err)
}
for name, response := range map[string]any{"read": read, "start": started} {
headers, ok := response.(*api.AssessmentAttemptHeaders)
if !ok {
t.Fatalf("%s response = %T, want attempt headers", name, response)
}
qualified, ok := headers.Response.GetAssessmentQualifiedAttempt()
if !ok {
t.Fatalf("%s response is not a qualified attempt", name)
}
code, hasCode := qualified.Watermark.Get()
item, _ := qualified.CurrentItem.Get()
if !hasCode || code.Code != "7K3QD-9XM2T" || item.Prompt != "Choose the number\u200b" {
t.Fatalf("%s response watermark = %+v/%v and prompt %q, want the presented values", name, code, hasCode, item.Prompt)
}
}
}
func TestAnAttemptWithoutAPresenterCarriesNoWatermark(t *testing.T) {
snapshot := assessmentPublicSnapshot()
handler := NewAssessmentHandler(&assessmentOperationsStub{read: snapshot})
read, err := handler.GetMyAssessmentAttempt(principalForTest(uuid.New()), api.GetMyAssessmentAttemptParams{AttemptID: snapshot.ID.UUID()})
if err != nil {
t.Fatalf("GetMyAssessmentAttempt() error = %v", err)
}
headers, ok := read.(*api.AssessmentAttemptHeaders)
if !ok {
t.Fatalf("read response = %T, want attempt headers", read)
}
qualified, _ := headers.Response.GetAssessmentQualifiedAttempt()
if qualified.Watermark.IsSet() {
t.Fatal("an attempt served without a presenter carries a watermark")
}
}
func TestAPresenterFailureIsAServerErrorNotAnUnmarkedAttempt(t *testing.T) {
snapshot := assessmentPublicSnapshot()
handler := NewAssessmentHandler(&assessmentOperationsStub{read: snapshot}).WithPresenter(presenterStub{err: errors.New("seed unavailable")})
if _, err := handler.GetMyAssessmentAttempt(principalForTest(uuid.New()), api.GetMyAssessmentAttemptParams{AttemptID: snapshot.ID.UUID()}); err == nil {
t.Fatal("GetMyAssessmentAttempt() succeeded, want an error so that the task text is never served unmarked")
}
}
+8 -1
View File
@@ -56,5 +56,12 @@ func newAssessmentHandler(
return nil, nil, fmt.Errorf("bootstrap.newAssessmentHandler - create signal observer: %w", err)
}
service.WithSignalObserver(observer)
return v1.NewAssessmentHandler(service), pool.Close, nil
// The watermark is derived from the identity keyring like the signal
// digests: the same secret, a key of its own, and no new setting.
watermarker, err := assessment.NewWatermarker(keyring)
if err != nil {
pool.Close()
return nil, nil, fmt.Errorf("bootstrap.newAssessmentHandler - create watermarker: %w", err)
}
return v1.NewAssessmentHandler(service).WithPresenter(watermarker), pool.Close, nil
}
@@ -318,6 +318,16 @@ type AssessmentAttemptPublicSnapshot struct {
IdleTimeout int32 `json:"idle_timeout_seconds"`
CurrentItem *AssessmentAttemptPublicItem `json:"current_item"`
Practices []AssessmentAttemptPublicPractice `json:"practices"`
// Watermark is set when a response is presented, never when it is stored:
// the retained idempotent response stays free of it, and every presentation
// derives the same value from the attempt.
Watermark *AssessmentAttemptPublicWatermark `json:"watermark,omitempty"`
}
// AssessmentAttemptPublicWatermark is the visible pseudonymous code that the
// task screen shows next to the time. It reveals nothing about the candidate.
type AssessmentAttemptPublicWatermark struct {
Code string `json:"code"`
}
// AssessmentAttemptPublicPractice is the empty, explicit practice projection
@@ -0,0 +1,321 @@
package domain
import (
"encoding/binary"
"errors"
"fmt"
"strings"
"unicode"
"unicode/utf8"
)
// ErrInvalidAssessmentWatermark reports a malformed watermark seed or code.
var ErrInvalidAssessmentWatermark = errors.New("invalid assessment watermark")
// AssessmentWatermarkSeed is the secret stream of one attempt: a keyed digest
// of the attempt identifier under a server key. The visible code, the zero-width
// mark, and the choice of wordings are all read from it, so none of them can be
// forged or predicted without the server secret, and none carries the attempt
// identifier or any account data. The seed itself never leaves the server.
type AssessmentWatermarkSeed [32]byte
// IsZero reports an unset seed.
func (seed AssessmentWatermarkSeed) IsZero() bool { return seed == AssessmentWatermarkSeed{} }
const (
// watermarkAlphabet is Crockford base32: no I, L, O, or U, so a code read
// from a screenshot is not confused between 0 and O or 1 and I.
watermarkAlphabet = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
watermarkCodeLength = 10
watermarkCodeBits = 5 * watermarkCodeLength
// watermarkDigits is the number of base-4 digits that carry the code bits
// in the zero-width mark. One more digit is a check.
watermarkDigits = watermarkCodeBits / 2
watermarkRunLength = watermarkDigits + 1
// watermarkMaxCopies bounds how many times the mark is repeated in one text.
watermarkMaxCopies = 8
// watermarkWordingOffset is where the wording choices start in the seed,
// after the 7 bytes that the code reads.
watermarkWordingOffset = 8
)
// watermarkZeroWidth are the four characters of the invisible mark, the digits
// 0 to 3. They are the zero width space, non-joiner, joiner, and word joiner.
//
//nolint:gochecknoglobals // A fixed table that is read-only after initialization.
var watermarkZeroWidth = [4]rune{'\u200b', '\u200c', '\u200d', '\u2060'}
// AssessmentWatermarkCode is the pseudonymous code of an attempt: 10 symbols
// of Crockford base32 held in upper case without separators. It shows on the
// task screen next to the time. It contains no name, contact, or identifier.
type AssessmentWatermarkCode string
// String writes the code in two groups of five, the way it is shown.
func (code AssessmentWatermarkCode) String() string {
if len(code) != watermarkCodeLength {
return string(code)
}
return string(code[:5]) + "-" + string(code[5:])
}
// ParseAssessmentWatermarkCode reads a code as an operator or an OCR gives it:
// any case, with or without the separator, with O read as 0 and I or L as 1.
func ParseAssessmentWatermarkCode(value string) (AssessmentWatermarkCode, error) {
var builder strings.Builder
for _, r := range strings.ToUpper(value) {
switch {
case r == '-' || unicode.IsSpace(r):
continue
case r == 'O':
r = '0'
case r == 'I' || r == 'L':
r = '1'
case r == 'U':
r = 'V'
}
if !strings.ContainsRune(watermarkAlphabet, r) {
return "", fmt.Errorf("domain.ParseAssessmentWatermarkCode - the code has a character outside its alphabet: %w", ErrInvalidAssessmentWatermark)
}
builder.WriteRune(r)
}
if builder.Len() != watermarkCodeLength {
return "", fmt.Errorf("domain.ParseAssessmentWatermarkCode - the code must have %d symbols: %w", watermarkCodeLength, ErrInvalidAssessmentWatermark)
}
return AssessmentWatermarkCode(builder.String()), nil
}
// Distance counts the positions at which two codes differ.
func (code AssessmentWatermarkCode) Distance(other AssessmentWatermarkCode) int {
if len(code) != len(other) {
return max(len(code), len(other))
}
differing := 0
for index := range len(code) {
if code[index] != other[index] {
differing++
}
}
return differing
}
// value is the code as one integer of watermarkCodeBits bits.
func (code AssessmentWatermarkCode) value() uint64 {
var number uint64
for index := range len(code) {
number = number<<5 | uint64(strings.IndexByte(watermarkAlphabet, code[index])) //nolint:gosec // The index is 0 to 31 for a parsed code.
}
return number
}
// AssessmentWatermark marks the task text of one attempt.
type AssessmentWatermark struct {
seed AssessmentWatermarkSeed
}
// NewAssessmentWatermark rejects an unset seed, which would give every attempt
// the same mark.
func NewAssessmentWatermark(seed AssessmentWatermarkSeed) (AssessmentWatermark, error) {
if seed.IsZero() {
return AssessmentWatermark{}, fmt.Errorf("domain.NewAssessmentWatermark - the seed must be set: %w", ErrInvalidAssessmentWatermark)
}
return AssessmentWatermark{seed: seed}, nil
}
// Code returns the visible code of the attempt: the leading bits of the seed.
func (watermark AssessmentWatermark) Code() AssessmentWatermarkCode {
number := binary.BigEndian.Uint64(watermark.seed[:8]) >> (64 - watermarkCodeBits)
symbols := make([]byte, watermarkCodeLength)
for index := watermarkCodeLength - 1; index >= 0; index-- {
symbols[index] = watermarkAlphabet[number&31]
number >>= 5
}
return AssessmentWatermarkCode(symbols)
}
// Mark writes the statement for this attempt. It picks one form for each
// interchangeable phrase and then inserts the invisible mark at the start of
// the sentences. Neither step changes the meaning, the answer, or what a screen
// reader says: see VisibleAssessmentText.
func (watermark AssessmentWatermark) Mark(statement string) string {
reworded := rewriteWording(canonicalWording(VisibleAssessmentText(statement)), watermark.wordingForm)
return insertWatermarkRuns(reworded, watermark.zeroWidthRun())
}
// wordingForm is the index of the form that this attempt uses for a group.
func (watermark AssessmentWatermark) wordingForm(group int) int {
forms := len(assessmentWordingGroups[group].forms)
return int(watermark.seed[watermarkWordingOffset+group%(len(watermark.seed)-watermarkWordingOffset)]) % forms
}
// WordingAgreement compares the phrases of a leaked text with the choices of
// this attempt, reading only the phrases that the leak shows within the stored
// statement (see AssessmentLeakAlignment): words around the statement in the
// leak, such as a quotation or a message, are not read. Slots is the number of
// phrase groups that the leak shows and Agreeing how many of them stand in the
// form this attempt picked. A group counts once however often it occurs, and a
// group that stands in two forms in the leak does not agree. Each group is
// worth about one bit: another attempt agrees with a group by chance in one
// case of two.
func (watermark AssessmentWatermark) WordingAgreement(alignment LeakAlignment) (agreeing, slots int) {
forms := map[int]int{}
conflicting := map[int]bool{}
for _, phrase := range alignment.Phrases {
if previous, seen := forms[phrase.Group]; seen && previous != phrase.Form {
conflicting[phrase.Group] = true
}
forms[phrase.Group] = phrase.Form
}
for group, form := range forms {
if !conflicting[group] && form == watermark.wordingForm(group) {
agreeing++
}
}
return agreeing, len(forms)
}
// zeroWidthRun encodes the code bits as watermarkDigits base-4 digits in the
// invisible characters, followed by a check digit, so a run that was cut or
// mixed with other characters is recognized as damaged.
func (watermark AssessmentWatermark) zeroWidthRun() string {
number := watermark.Code().value()
digits := make([]rune, watermarkDigits+1)
sum := 0
for index := watermarkDigits - 1; index >= 0; index-- {
digit := int(number & 3)
digits[index] = watermarkZeroWidth[digit]
sum += digit
number >>= 2
}
digits[watermarkDigits] = watermarkZeroWidth[sum%4]
return string(digits)
}
// insertWatermarkRuns places the mark after the first space and at the start of
// each following sentence, so that any copy of a sentence or two keeps a whole
// run. Positions are byte offsets in the text.
func insertWatermarkRuns(text, run string) string {
positions := watermarkPositions(text)
if len(positions) == 0 {
return text + run
}
var builder strings.Builder
builder.Grow(len(text) + len(positions)*len(run))
copied := 0
for _, position := range positions {
builder.WriteString(text[copied:position])
builder.WriteString(run)
copied = position
}
builder.WriteString(text[copied:])
return builder.String()
}
func watermarkPositions(text string) []int {
var positions []int
if first := strings.IndexFunc(text, unicode.IsSpace); first >= 0 && first+1 < len(text) {
positions = append(positions, first+1)
}
previous := rune(0)
for offset, r := range text {
if len(positions) >= watermarkMaxCopies {
break
}
next := offset + utf8.RuneLen(r)
if unicode.IsSpace(r) && (previous == '.' || previous == '!' || previous == '?') && next < len(text) {
if len(positions) == 0 || positions[len(positions)-1] != next {
positions = append(positions, next)
}
}
previous = r
}
return positions
}
// ExtractAssessmentWatermarkCodes returns the codes read from the invisible
// marks in a text, in order, one per intact run. A run is a maximal stretch of
// the four mark characters of exactly the right length and a correct check
// digit; anything else is ignored.
func ExtractAssessmentWatermarkCodes(text string) []AssessmentWatermarkCode {
var codes []AssessmentWatermarkCode
var run []int
flush := func() {
if code, ok := decodeWatermarkRun(run); ok {
codes = append(codes, code)
}
run = run[:0]
}
for _, r := range text {
if digit := watermarkDigit(r); digit >= 0 {
run = append(run, digit)
continue
}
flush()
}
flush()
return codes
}
func watermarkDigit(r rune) int {
for digit, candidate := range watermarkZeroWidth {
if r == candidate {
return digit
}
}
return -1
}
func decodeWatermarkRun(digits []int) (AssessmentWatermarkCode, bool) {
if len(digits) != watermarkRunLength {
return "", false
}
var number uint64
sum := 0
for _, digit := range digits[:watermarkDigits] {
number = number<<2 | uint64(digit) //nolint:gosec // A digit is 0 to 3.
sum += digit
}
if sum%4 != digits[watermarkDigits] {
return "", false
}
symbols := make([]byte, watermarkCodeLength)
for index := watermarkCodeLength - 1; index >= 0; index-- {
symbols[index] = watermarkAlphabet[number&31]
number >>= 5
}
return AssessmentWatermarkCode(symbols), true
}
// VisibleAssessmentText removes everything a reader cannot see from a marked
// text: the four mark characters (all of them format characters of Unicode) and
// the other invisible format characters. It
// is the text that assistive technology must read, and the client uses the same
// rule to keep the marks out of the accessibility tree.
func VisibleAssessmentText(text string) string {
return strings.Map(func(r rune) rune {
if invisibleTextRune(r) {
return -1
}
return r
}, text)
}
func invisibleTextRune(r rune) bool {
return unicode.Is(unicode.Cf, r)
}
// NormalizedAssessmentText brings a leaked text to a form in which it can be
// read: the invisible characters are removed, the typographic apostrophe
// becomes a plain one, and runs of white space, non-breaking spaces among them,
// collapse into one space. The wording of the text is kept.
func NormalizedAssessmentText(text string) string {
cleaned := strings.NewReplacer("\u2019", "'", "\u02bc", "'").Replace(VisibleAssessmentText(text))
return strings.Join(strings.Fields(cleaned), " ")
}
// CanonicalAssessmentText is the normalized text with every interchangeable
// phrase written in its canonical form. Two copies of one statement that differ
// only by the watermark have the same canonical text, and so does a stored
// statement, which makes it the form in which a leak is compared.
func CanonicalAssessmentText(text string) string {
return canonicalWording(NormalizedAssessmentText(text))
}
@@ -0,0 +1,343 @@
package domain
import (
"strings"
"testing"
"unicode"
)
// rateLimitTemplate is the statement template of the rate limit family of the demo
// bank. It holds several interchangeable phrases, as real statements do.
const rateLimitTemplate = "A gateway protects an endpoint with a sliding-window limiter. A request arriving at second t is accepted only when fewer than {{.limit}} previously accepted requests have an arrival time in the half-open interval (t - {{.window}}, t]. A rejected request is not remembered and does not count against later requests. The gateway receives {{.requests}} requests at these arrival times, in seconds and in non-decreasing order: {{.timestamps}}. How many requests does the gateway reject?"
func watermarkSeed(first byte) AssessmentWatermarkSeed {
var seed AssessmentWatermarkSeed
for index := range seed {
seed[index] = first + byte(index*7)
}
return seed
}
func testWatermark(t *testing.T, first byte) AssessmentWatermark {
t.Helper()
watermark, err := NewAssessmentWatermark(watermarkSeed(first))
if err != nil {
t.Fatalf("NewAssessmentWatermark() error = %v", err)
}
return watermark
}
func rateLimitVariant(t *testing.T) AssessmentVariant {
t.Helper()
input := testAssessmentInput()
input.Generator = AssessmentSeedGenerator{
Algorithm: "rate_limit_window.v1",
Parameters: map[string]AssessmentParameterRange{
"requests": {Min: 8, Max: 12}, "window": {Min: 3, Max: 5}, "limit": {Min: 2, Max: 3}, "max_gap": {Min: 0, Max: 3},
},
StatementTemplate: rateLimitTemplate,
}
input.AnswerKey.AnswerFormat = assessmentAlgorithms["rate_limit_window.v1"].answerFormat
variant, err := restoreAssessment(t, input).NewVariant(4242)
if err != nil {
t.Fatalf("NewVariant() error = %v", err)
}
return variant
}
func hasInvisible(text string) bool {
return strings.IndexFunc(text, func(r rune) bool { return unicode.Is(unicode.Cf, r) }) >= 0
}
func TestTheSameVariantOfTwoAttemptsDiffersOnlyByTheWatermark(t *testing.T) {
variant := rateLimitVariant(t)
first, second := testWatermark(t, 1), testWatermark(t, 9)
markedFirst, markedSecond := first.Mark(variant.Statement), second.Mark(variant.Statement)
if markedFirst == markedSecond {
t.Fatal("two attempts got the same marked statement, want a mark of their own")
}
if !hasInvisible(markedFirst) || !hasInvisible(markedSecond) {
t.Fatal("a marked statement has no invisible mark")
}
// Whatever the attempt, the statement says the same: only the mark and the
// interchangeable phrases differ, and both disappear in the canonical text.
want := CanonicalAssessmentText(variant.Statement)
for name, marked := range map[string]string{"first": markedFirst, "second": markedSecond} {
if got := CanonicalAssessmentText(marked); got != want {
t.Fatalf("canonical text of the %s attempt =\n%q\nwant\n%q", name, got, want)
}
}
// The mark is outside the variant: the reference answer, the rubric, and the
// options that grading reads are the ones of the variant.
if variant.ReferenceAnswer == "" {
t.Fatal("the variant has no reference answer to compare")
}
if again := rateLimitVariant(t); again.ReferenceAnswer != variant.ReferenceAnswer || again.Statement != variant.Statement {
t.Fatal("marking changed the variant, want the unmarked statement and the same reference answer")
}
}
func TestMarkingIsDeterministicAndIdempotent(t *testing.T) {
statement := rateLimitVariant(t).Statement
watermark := testWatermark(t, 3)
marked := watermark.Mark(statement)
if again := watermark.Mark(statement); again != marked {
t.Fatal("marking the same statement twice gave two results")
}
if again := watermark.Mark(marked); again != marked {
t.Fatal("marking a marked statement changed it, want the same text")
}
if other := testWatermark(t, 3).Mark(statement); other != marked {
t.Fatal("equal seeds gave different marks")
}
}
func TestInvisibleMarkRoundTripsAndSurvivesCopiedSentences(t *testing.T) {
statement := rateLimitVariant(t).Statement
watermark := testWatermark(t, 5)
marked := watermark.Mark(statement)
codes := ExtractAssessmentWatermarkCodes(marked)
if len(codes) < 3 {
t.Fatalf("ExtractAssessmentWatermarkCodes() found %d copies, want one in each of several sentences", len(codes))
}
for _, code := range codes {
if code != watermark.Code() {
t.Fatalf("a copy decoded to %s, want %s", code, watermark.Code())
}
}
// A paragraph taken from the middle keeps a whole run.
sentences := strings.SplitAfter(marked, ". ")
if got := ExtractAssessmentWatermarkCodes(sentences[2] + sentences[3]); len(got) == 0 || got[0] != watermark.Code() {
t.Fatalf("two copied sentences decoded to %v, want %s", got, watermark.Code())
}
// Removing the invisible characters removes the mark and nothing else.
if codes := ExtractAssessmentWatermarkCodes(VisibleAssessmentText(marked)); len(codes) != 0 {
t.Fatalf("a text without invisible characters decoded to %v", codes)
}
}
func TestDamagedInvisibleMarkIsNotRead(t *testing.T) {
watermark := testWatermark(t, 5)
run := watermark.zeroWidthRun()
runes := []rune(run)
tests := map[string]string{
"a run cut short": "a " + string(runes[:len(runes)-1]) + " b",
"a run with an extra": "a " + run + string(watermarkZeroWidth[1]) + " b",
"a wrong check digit": "a " + string(runes[:len(runes)-1]) + string(watermarkZeroWidth[(watermarkDigit(runes[len(runes)-1])+1)%4]) + " b",
"two runs run together": "a " + run + run + " b",
}
for name, text := range tests {
t.Run(name, func(t *testing.T) {
if codes := ExtractAssessmentWatermarkCodes(text); len(codes) != 0 {
t.Fatalf("ExtractAssessmentWatermarkCodes() = %v, want nothing from a damaged mark", codes)
}
})
}
if codes := ExtractAssessmentWatermarkCodes("a " + run + " b"); len(codes) != 1 || codes[0] != watermark.Code() {
t.Fatalf("ExtractAssessmentWatermarkCodes(intact run) = %v, want one code", codes)
}
}
func TestAccessibleTextOfAMarkedStatementIsTheStatement(t *testing.T) {
variant := rateLimitVariant(t)
watermark := testWatermark(t, 7)
marked := watermark.Mark(variant.Statement)
visible := VisibleAssessmentText(marked)
if hasInvisible(visible) {
t.Fatal("the accessible text still holds an invisible character")
}
// What assistive technology reads is the statement with the phrases the
// attempt picked: the same words in the same order, nothing added.
if got, want := CanonicalAssessmentText(visible), CanonicalAssessmentText(variant.Statement); got != want {
t.Fatalf("accessible text differs in meaning:\n%q\nwant\n%q", got, want)
}
if len(visible) > len(variant.Statement)+32 {
t.Fatalf("accessible text grew from %d to %d bytes, want only a different choice of phrases", len(variant.Statement), len(visible))
}
// The numbers and data of the task are untouched.
for _, token := range strings.Fields(variant.Statement) {
if strings.ContainsAny(token, "0123456789") && !strings.Contains(visible, strings.Trim(token, ".,:;")) {
t.Fatalf("data token %q is missing from the accessible text", token)
}
}
}
func TestWordingAgreementReadsOnlyTheAlignedPhrasesOfTheStatement(t *testing.T) {
statement := rateLimitVariant(t).Statement
first := testWatermark(t, 1)
own := first.Mark(statement)
// The statement as the attempt showed it, alone and among other words that
// hold phrases of their own, agrees with every phrase of its attempt.
surrounded := "He wrote: it isn't hard, and we don't know. " + VisibleAssessmentText(own) + " Thanks, it isn't clear."
for name, leak := range map[string]string{"alone": VisibleAssessmentText(own), "with the marks": own, "surrounded": surrounded} {
agreeing, slots := first.WordingAgreement(AssessmentLeakAlignment(statement, leak))
if slots < 4 || agreeing != slots {
t.Fatalf("%s: WordingAgreement() = %d of %d, want every one of at least four phrase groups to agree", name, agreeing, slots)
}
}
// Some other attempt picked other phrases for at least one group, and it
// disagrees with the leak of the first one.
disagreeing := 0
for seed := byte(2); seed < 40; seed++ {
if agreeing, slots := testWatermark(t, seed).WordingAgreement(AssessmentLeakAlignment(statement, VisibleAssessmentText(own))); agreeing < slots {
disagreeing++
}
}
if disagreeing == 0 {
t.Fatal("no other seed disagrees with the phrases of the first attempt")
}
// A leak of a fragment yields the phrases of the fragment only.
piece := VisibleAssessmentText(own)
start := strings.Index(piece, "A rejected")
if start < 0 {
t.Fatal("the statement has no sentence that starts with A rejected")
}
fragment := piece[start:]
if agreeing, slots := first.WordingAgreement(AssessmentLeakAlignment(statement, fragment)); slots == 0 || slots >= 5 || agreeing != slots {
t.Fatalf("fragment: WordingAgreement() = %d of %d, want fewer groups than the whole statement, all agreeing", agreeing, slots)
}
// A text that is not the statement has nothing to align.
if agreeing, slots := first.WordingAgreement(AssessmentLeakAlignment(statement, "It is not what it is. It does not matter, as it isn't related.")); slots != 0 || agreeing != 0 {
t.Fatalf("unrelated text: WordingAgreement() = %d of %d, want nothing aligned", agreeing, slots)
}
// A group written in two forms is edited text and agrees with no group.
edited := strings.Replace(VisibleAssessmentText(own), "does not", "doesn't", 1) + " " + strings.Replace(VisibleAssessmentText(own), "doesn't", "does not", 1)
if agreeing, slots := first.WordingAgreement(AssessmentLeakAlignment(statement, edited)); agreeing > slots {
t.Fatalf("edited text: %d of %d", agreeing, slots)
}
}
func TestAlignmentIsLongestForTheVariantThatWasLeakedAndShorterForOtherVariants(t *testing.T) {
input := testAssessmentInput()
input.Generator = AssessmentSeedGenerator{
Algorithm: "rate_limit_window.v1",
Parameters: map[string]AssessmentParameterRange{
"requests": {Min: 8, Max: 12}, "window": {Min: 3, Max: 5}, "limit": {Min: 2, Max: 3}, "max_gap": {Min: 0, Max: 3},
},
StatementTemplate: rateLimitTemplate,
}
input.AnswerKey.AnswerFormat = assessmentAlgorithms["rate_limit_window.v1"].answerFormat
family := restoreAssessment(t, input)
leaked, err := family.NewVariant(4242)
if err != nil {
t.Fatalf("NewVariant(4242) error = %v", err)
}
other, err := family.NewVariant(99)
if err != nil || other.Statement == leaked.Statement {
t.Fatalf("NewVariant(99) = %v, %v, want another statement", other.Statement, err)
}
leak := "Someone asked: " + VisibleAssessmentText(testWatermark(t, 1).Mark(leaked.Statement)) + " thanks"
own, foreign := AssessmentLeakAlignment(leaked.Statement, leak), AssessmentLeakAlignment(other.Statement, leak)
if own.Runes <= foreign.Runes {
t.Fatalf("aligned %d characters for the leaked variant and %d for another variant of the family, want the leaked one longer", own.Runes, foreign.Runes)
}
// The leak is a copy of the leaked variant, and the other variant shares only
// the text of its family and then diverges, so it is not the source.
if !own.Complete || !own.Follows() || foreign.Follows() {
t.Fatalf("leaked variant: %+v, other variant: %+v, want the leaked one followed to its end and the other one diverged", own, foreign)
}
// A leak cut inside the statement ends there; a leak with other words in the
// middle of it has diverged.
cut := VisibleAssessmentText(testWatermark(t, 1).Mark(leaked.Statement))
cut = cut[:len(cut)*2/3]
if got := AssessmentLeakAlignment(leaked.Statement, cut); got.Complete || !got.Ended || !got.Follows() {
t.Fatalf("a cut leak aligned %+v, want it to end inside the statement", got)
}
if got := AssessmentLeakAlignment(leaked.Statement, cut+" and some other words that the statement does not have"); got.Follows() {
t.Fatalf("a leak with other words inside the statement aligned %+v, want it to have diverged", got)
}
total := 0
for _, piece := range AssessmentTextPiecesBetweenPhrases(NormalizedAssessmentText(leaked.Statement)) {
total += len([]rune(piece))
}
if own.Runes != total {
t.Fatalf("the leaked variant aligned %d characters, want all %d characters of its pieces", own.Runes, total)
}
if got := AssessmentLeakAlignment(leaked.Statement, "nothing in common with it at all"); got.Runes != 0 || len(got.Phrases) != 0 {
t.Fatalf("unrelated text aligned %+v, want nothing", got)
}
}
func TestSplittingATextAtItsPhrasesLeavesPiecesThatEveryCopyShares(t *testing.T) {
statement := rateLimitVariant(t).Statement
// Whatever phrases an attempt picked, the pieces between them are the same.
want := AssessmentTextPiecesBetweenPhrases(NormalizedAssessmentText(statement))
for seed := byte(1); seed < 20; seed++ {
got := AssessmentTextPiecesBetweenPhrases(NormalizedAssessmentText(testWatermark(t, seed).Mark(statement)))
if len(got) != len(want) {
t.Fatalf("seed %d: %d pieces, want %d", seed, len(got), len(want))
}
for index := range want {
if got[index] != want[index] {
t.Fatalf("seed %d: piece %d = %q, want %q", seed, index, got[index], want[index])
}
}
}
}
func TestInterchangeablePhrasesStayWithinTheirGuards(t *testing.T) {
watermark := testWatermark(t, 1)
// At the end of a sentence "at most" is not followed by a number, so the
// alternative form would not read the same and is not used.
tail := "How many requests per minute can it serve at most?"
if got := VisibleAssessmentText(watermark.Mark(tail)); got != tail {
t.Fatalf("Mark(%q) = %q, want the phrase before a question mark kept", tail, got)
}
// Inside a longer word nothing is replaced.
inside := "This is nothing, and scannotes stays."
if got := VisibleAssessmentText(watermark.Mark(inside)); !strings.Contains(got, "scannotes") || !strings.Contains(got, "This is nothing") {
t.Fatalf("Mark(%q) = %q, want words that contain a phrase left alone", inside, got)
}
// Both forms of a group map to the canonical one.
for want, texts := range map[string][]string{
"holds at most 5 entries": {"holds at most 5 entries", "holds no more than 5 entries"},
"хранит не более 5 записей": {"хранит не более 5 записей", "хранит не больше 5 записей"},
"it isn't empty": {"it isn't empty", "it is not empty", "it isn\u2019t empty"},
} {
for _, text := range texts {
if got := CanonicalAssessmentText(text); got != strings.ReplaceAll(want, "isn't", "is not") {
t.Fatalf("CanonicalAssessmentText(%q) = %q", text, got)
}
}
}
}
func TestWatermarkCodeIsStableReadableAndParsesWhatOCRReads(t *testing.T) {
watermark := testWatermark(t, 1)
code := watermark.Code()
if len(code) != watermarkCodeLength || len(code.String()) != watermarkCodeLength+1 || code.String()[5] != '-' {
t.Fatalf("Code() = %q, want ten symbols shown as XXXXX-XXXXX", code)
}
if testWatermark(t, 1).Code() != code || testWatermark(t, 2).Code() == code {
t.Fatal("the code must follow the seed")
}
for _, shown := range []string{code.String(), strings.ToLower(code.String()), strings.ReplaceAll(code.String(), "-", " ")} {
parsed, err := ParseAssessmentWatermarkCode(shown)
if err != nil || parsed != code {
t.Fatalf("ParseAssessmentWatermarkCode(%q) = %q, %v, want %q", shown, parsed, err, code)
}
}
// The letters that OCR confuses read as the digits and letters of the alphabet.
read, err := ParseAssessmentWatermarkCode("OIL0O-1U123")
if err != nil {
t.Fatalf("ParseAssessmentWatermarkCode(OCR errors) error = %v", err)
}
if got, want := read.String(), "01100-1V123"; got != want {
t.Fatalf("ParseAssessmentWatermarkCode(OCR errors) = %q, want %q", got, want)
}
for _, bad := range []string{"", "ABCDE", "ABCDE-FGHJK-M", "ABCD!-FGHJK", "ABCDE-FGHJ#"} {
if _, err := ParseAssessmentWatermarkCode(bad); err == nil {
t.Fatalf("ParseAssessmentWatermarkCode(%q) succeeded, want an error", bad)
}
}
if code.Distance(code) != 0 || code.Distance(testWatermark(t, 2).Code()) == 0 {
t.Fatal("Distance must be zero for equal codes only")
}
if _, err := NewAssessmentWatermark(AssessmentWatermarkSeed{}); err == nil {
t.Fatal("NewAssessmentWatermark(zero seed) succeeded, want an error")
}
}
@@ -0,0 +1,262 @@
package domain
import (
"strings"
"unicode"
"unicode/utf8"
)
// wordingGroup lists interchangeable ways to write one phrase of a statement.
// Every form means exactly the same, so choosing one never changes the task or
// its reference answer. forms[0] is the canonical form: the attempt marker
// replaces every form of a group in a statement by the form it picked for the
// attempt, and the leak trace maps every form back to forms[0] before it
// compares texts.
//
// The list is append-only. Reordering or removing a form, or inserting a group
// before another, changes the choice of every attempt already served, and the
// marks of those attempts could no longer be read back. A new group goes to the
// end.
type wordingGroup struct {
forms []string
// beforeNumber limits the group to places where the phrase is followed by a
// space and a digit ("at most 5"). The forms read the same only there: "at
// most" ends a sentence in "how many can it serve at most?", where "no more
// than" would not.
beforeNumber bool
}
// assessmentWordingGroups are phrases of plain connective prose in the
// statements: comparisons of counts, negations that can be contracted, and
// spelling variants. They avoid the terms a statement defines and then reuses
// ("processed", "dropped", "accepted"), because rewording one of several uses of
// a defined term would confuse the task.
//
//nolint:gochecknoglobals // A fixed, append-only table that is read-only after initialization.
var assessmentWordingGroups = []wordingGroup{
{forms: []string{"at most", "no more than"}, beforeNumber: true},
{forms: []string{"at least", "no fewer than"}, beforeNumber: true},
{forms: []string{"fewer than", "less than"}, beforeNumber: true},
{forms: []string{"is not", "isn't"}},
{forms: []string{"are not", "aren't"}},
{forms: []string{"does not", "doesn't"}},
{forms: []string{"do not", "don't"}},
{forms: []string{"cannot", "can't"}},
{forms: []string{"non-decreasing", "nondecreasing"}},
{forms: []string{"only when", "only if"}},
{forms: []string{"half-open interval", "half open interval"}},
{forms: []string{"one at a time", "one by one"}},
{forms: []string{"Among all", "Of all"}},
{forms: []string{"не более", "не больше"}, beforeNumber: true},
{forms: []string{"не менее", "не меньше"}, beforeNumber: true},
{forms: []string{"только если", "лишь если"}},
{forms: []string{"в порядке неубывания", "в неубывающем порядке"}},
{forms: []string{"Найдите", "Определите"}},
}
// wordingOccurrence is one phrase found in a text.
type wordingOccurrence struct {
group int
form int
start int
end int
}
// findWordingOccurrences scans the text left to right and returns the
// non-overlapping phrases of the table. Where several forms start at the same
// place the longest wins.
func findWordingOccurrences(text string) []wordingOccurrence {
var found []wordingOccurrence
for position := 0; position < len(text); {
best := wordingOccurrence{group: -1}
for groupIndex, group := range assessmentWordingGroups {
for formIndex, form := range group.forms {
if !wordingFormAt(text, position, form, group.beforeNumber) {
continue
}
if best.group < 0 || len(form) > best.end-best.start {
best = wordingOccurrence{group: groupIndex, form: formIndex, start: position, end: position + len(form)}
}
}
}
if best.group < 0 {
_, size := utf8.DecodeRuneInString(text[position:])
position += size
continue
}
found = append(found, best)
position = best.end
}
return found
}
// wordingFormAt reports whether the form stands at the position as whole
// words: not inside a longer word and, for a number group, before a number.
func wordingFormAt(text string, position int, form string, beforeNumber bool) bool {
if !strings.HasPrefix(text[position:], form) {
return false
}
if previous, _ := utf8.DecodeLastRuneInString(text[:position]); position > 0 && wordRune(previous) {
return false
}
end := position + len(form)
if next, _ := utf8.DecodeRuneInString(text[end:]); end < len(text) && wordRune(next) {
return false
}
if !beforeNumber {
return true
}
rest := text[end:]
if len(rest) < 2 || rest[0] != ' ' {
return false
}
return rest[1] >= '0' && rest[1] <= '9'
}
// wordRune reports whether the rune continues a word. The apostrophe and the
// hyphen join words in the forms of the table, so a form never starts or ends
// inside a hyphenated or contracted word.
func wordRune(r rune) bool {
return unicode.IsLetter(r) || unicode.IsDigit(r) || r == '\'' || r == '-'
}
// rewriteWording replaces every phrase of the table by the form that choose
// returns for its group.
func rewriteWording(text string, choose func(group int) int) string {
occurrences := findWordingOccurrences(text)
if len(occurrences) == 0 {
return text
}
var builder strings.Builder
builder.Grow(len(text) + 16)
copied := 0
for _, occurrence := range occurrences {
builder.WriteString(text[copied:occurrence.start])
builder.WriteString(assessmentWordingGroups[occurrence.group].forms[choose(occurrence.group)])
copied = occurrence.end
}
builder.WriteString(text[copied:])
return builder.String()
}
// canonicalWording writes every phrase of the table in its canonical form.
func canonicalWording(text string) string {
return rewriteWording(text, func(int) int { return 0 })
}
// AssessmentTextPiecesBetweenPhrases cuts a text at every interchangeable
// phrase and returns the pieces in between. The pieces read the same in every
// copy of a statement, whichever form each attempt wrote the phrases in, so a
// stored statement can be searched for a piece literally.
func AssessmentTextPiecesBetweenPhrases(text string) []string {
pieces := make([]string, 0, 8)
copied := 0
for _, occurrence := range findWordingOccurrences(text) {
pieces = append(pieces, text[copied:occurrence.start])
copied = occurrence.end
}
return append(pieces, text[copied:])
}
// minAlignedPieceRunes is the shortest piece of a statement that the alignment
// accepts as a landmark in a leak: a shorter one occurs anywhere.
const minAlignedPieceRunes = 8
// LeakPhrase is a phrase of a statement as a leak writes it: the group and the
// index of the form that the leak uses.
type LeakPhrase struct {
Group int
Form int
}
// LeakAlignment is how far a leaked text follows a stored statement: the
// phrases it shows, in the forms it writes them, and the number of characters
// of the statement that it repeats between its phrases.
type LeakAlignment struct {
Phrases []LeakPhrase
// Runes is the length of the pieces of the statement that the leak repeats
// in order. A leak of the whole statement repeats all of them, and the
// statement of another variant of the same family repeats only the text of
// the family up to the first number that differs.
Runes int
// Complete reports that the leak followed the statement to its end. Ended
// reports that the leak stopped inside the statement, exactly where the
// statement continues. A leak that has other words where the statement
// continues does neither: it diverged from the statement, so the statement is
// not its source, however long the text they share.
Complete bool
Ended bool
}
// Follows reports whether the leak is a copy of the statement, whole or cut:
// it either reached the end of the statement or ended inside it.
func (alignment LeakAlignment) Follows() bool { return alignment.Complete || alignment.Ended }
// AssessmentLeakAlignment aligns a leaked text with a stored statement. It finds
// a landmark of the statement in the leak (the first piece between phrases that
// is long enough) and then follows the statement: after each piece, the leak
// must continue with one form of the next phrase and then the next piece. It
// stops at the first place where the leak does not follow the statement, so a
// leak that holds only part of the statement, an edited one, or the statement of
// another variant yields only the part that was aligned.
func AssessmentLeakAlignment(statement, leak string) LeakAlignment {
normalized := NormalizedAssessmentText(statement)
occurrences := findWordingOccurrences(normalized)
pieces := AssessmentTextPiecesBetweenPhrases(normalized)
leak = NormalizedAssessmentText(leak)
start, position := firstLandmark(pieces, leak)
if start < 0 {
return LeakAlignment{}
}
alignment := LeakAlignment{Runes: utf8.RuneCountInString(pieces[start]), Complete: true}
for index := start; index < len(occurrences); index++ {
group := assessmentWordingGroups[occurrences[index].group]
next := pieces[index+1]
matched := false
for form, text := range group.forms {
if strings.HasPrefix(leak[position:], text+next) {
alignment.Phrases = append(alignment.Phrases, LeakPhrase{Group: occurrences[index].group, Form: form})
alignment.Runes += utf8.RuneCountInString(next)
position += len(text) + len(next)
matched = true
break
}
}
if !matched {
alignment.Complete = false
alignment.Ended = leakEndsInside(leak[position:], group.forms, next)
break
}
}
return alignment
}
// leakEndsInside reports whether the rest of the leak is the beginning of what
// the statement has next (a form of the phrase, then the next piece), which is
// how a leak that was cut ends. An empty rest, and a rest that holds only a cut
// phrase or a cut piece, end the leak; any other word does not.
func leakEndsInside(rest string, forms []string, next string) bool {
if rest == "" {
return true
}
for _, form := range forms {
if strings.HasPrefix(form+next, rest) {
return true
}
}
return false
}
// firstLandmark returns the index of the first piece that is long enough and
// occurs in the leak, and the position in the leak just after it.
func firstLandmark(pieces []string, leak string) (index, position int) {
for index, piece := range pieces {
if utf8.RuneCountInString(piece) < minAlignedPieceRunes {
continue
}
if at := strings.Index(leak, piece); at >= 0 {
return index, at + len(piece)
}
}
return -1, 0
}
@@ -18,8 +18,10 @@ import (
// every candidate acknowledges the new wording. Acknowledgements are stored per
// version, so one given for an earlier version never counts for this one.
//
// Version 2 added the attempt measures to the text; version 1 listed signals only.
const CurrentSignalNoticeVersion int32 = 2
// Version 3 describes the watermark of the task screen and text, which version
// 2 announced as planned; version 2 added the attempt measures to the text;
// version 1 listed signals only.
const CurrentSignalNoticeVersion int32 = 3
// ErrSignalNoticeVersionMismatch reports an acknowledgement for a notice
// version other than the one the server requires.
@@ -0,0 +1,68 @@
package assessment
import (
"errors"
"fmt"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
)
// WatermarkSeeds derives the secret stream that marks the task text of one
// attempt. The seed is computed on the server from the attempt identifier and a
// server key and never leaves it.
type WatermarkSeeds interface {
AssessmentWatermarkSeed(attemptID uuid.UUID) domain.AssessmentWatermarkSeed
}
// Watermarker puts the attempt watermark on the task text of a response. The
// visible code is returned next to the text and the invisible mark is written
// into it, both from the seed of the attempt. The stored attempt, the
// idempotent responses, the reference answer, and the grading are not touched:
// the mark exists only in what is presented.
type Watermarker struct {
seeds WatermarkSeeds
}
// NewWatermarker fails at startup when the seed source is missing.
func NewWatermarker(seeds WatermarkSeeds) (*Watermarker, error) {
if seeds == nil {
return nil, errors.New("assessment.NewWatermarker - seeds must be set")
}
return &Watermarker{seeds: seeds}, nil
}
// Watermark returns the code and the marked statement for one attempt.
func (watermarker *Watermarker) Watermark(attemptID domain.AssessmentAttemptID) (domain.AssessmentWatermark, error) {
const location = "Watermarker.Watermark"
watermark, err := domain.NewAssessmentWatermark(watermarker.seeds.AssessmentWatermarkSeed(attemptID.UUID()))
if err != nil {
return domain.AssessmentWatermark{}, fmt.Errorf("%s - build watermark: %w", location, err)
}
return watermark, nil
}
// Present returns the snapshot as the candidate receives it. A real attempt,
// root or corrective, gets the visible code and the marked statement of its
// current item; a training run is returned unchanged. A nil Watermarker leaves
// every snapshot unchanged, so a deployment without it still serves attempts.
func (watermarker *Watermarker) Present(
snapshot domain.AssessmentAttemptPublicSnapshot,
) (domain.AssessmentAttemptPublicSnapshot, error) {
const location = "Watermarker.Present"
if watermarker == nil || !isRealAttemptKind(snapshot.Kind) {
return snapshot, nil
}
watermark, err := watermarker.Watermark(snapshot.ID)
if err != nil {
return domain.AssessmentAttemptPublicSnapshot{}, fmt.Errorf("%s - watermark attempt: %w", location, err)
}
snapshot.Watermark = &domain.AssessmentAttemptPublicWatermark{Code: watermark.Code().String()}
if snapshot.CurrentItem != nil {
item := *snapshot.CurrentItem
item.Prompt = watermark.Mark(item.Prompt)
snapshot.CurrentItem = &item
}
return snapshot, nil
}
@@ -0,0 +1,95 @@
package assessment
import (
"crypto/sha256"
"strings"
"testing"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
)
// hashedSeeds stands in for the keyring: a seed that follows the attempt.
type hashedSeeds struct{}
func (hashedSeeds) AssessmentWatermarkSeed(attemptID uuid.UUID) domain.AssessmentWatermarkSeed {
return sha256.Sum256(append([]byte("test-watermark:"), attemptID[:]...))
}
const watermarkTestPrompt = "A cache holds at most 3 entries. A read of a missing key is not a hit. How many reads are hits?"
func presentedSnapshot(kind domain.AssessmentAttemptKind) domain.AssessmentAttemptPublicSnapshot {
return domain.AssessmentAttemptPublicSnapshot{
ID: domain.AssessmentAttemptID(uuid.New()), Kind: kind,
CurrentItem: &domain.AssessmentAttemptPublicItem{
ID: uuid.New(), Sequence: 1, Prompt: watermarkTestPrompt,
Content: domain.AssessmentAttemptPublicItemContent{Format: "number"},
},
}
}
func TestPresentMarksRealAttemptsOnlyAndLeavesTheStoredSnapshotAlone(t *testing.T) {
watermarker, err := NewWatermarker(hashedSeeds{})
if err != nil {
t.Fatalf("NewWatermarker() error = %v", err)
}
for _, kind := range []domain.AssessmentAttemptKind{domain.AssessmentAttemptKindRoot, domain.AssessmentAttemptKindCorrective} {
stored := presentedSnapshot(kind)
presented, err := watermarker.Present(stored)
if err != nil {
t.Fatalf("Present(%s) error = %v", kind, err)
}
if presented.Watermark == nil || len(presented.Watermark.Code) != 11 {
t.Fatalf("Present(%s) watermark = %+v, want the visible code", kind, presented.Watermark)
}
if presented.CurrentItem.Prompt == watermarkTestPrompt || domain.CanonicalAssessmentText(presented.CurrentItem.Prompt) != domain.CanonicalAssessmentText(watermarkTestPrompt) {
t.Fatalf("Present(%s) prompt = %q, want the same statement with a mark", kind, presented.CurrentItem.Prompt)
}
if stored.CurrentItem.Prompt != watermarkTestPrompt || stored.Watermark != nil {
t.Fatalf("Present(%s) changed the stored snapshot", kind)
}
if again, _ := watermarker.Present(stored); again.CurrentItem.Prompt != presented.CurrentItem.Prompt || again.Watermark.Code != presented.Watermark.Code {
t.Fatalf("Present(%s) is not repeatable", kind)
}
}
training := presentedSnapshot(domain.AssessmentAttemptKindDemoExpress)
if got, err := watermarker.Present(training); err != nil || got.Watermark != nil || got.CurrentItem.Prompt != watermarkTestPrompt {
t.Fatalf("Present(training) = %+v, %v, want the unchanged snapshot", got, err)
}
}
func TestTwoAttemptsGetTheSameStatementWithTheirOwnMark(t *testing.T) {
watermarker, err := NewWatermarker(hashedSeeds{})
if err != nil {
t.Fatalf("NewWatermarker() error = %v", err)
}
first, _ := watermarker.Present(presentedSnapshot(domain.AssessmentAttemptKindRoot))
second, _ := watermarker.Present(presentedSnapshot(domain.AssessmentAttemptKindRoot))
if first.Watermark.Code == second.Watermark.Code || first.CurrentItem.Prompt == second.CurrentItem.Prompt {
t.Fatal("two attempts got the same code or the same marked statement")
}
if domain.CanonicalAssessmentText(first.CurrentItem.Prompt) != domain.CanonicalAssessmentText(second.CurrentItem.Prompt) {
t.Fatal("the statements of two attempts differ beyond the mark")
}
// The code on the screen is the code of the invisible mark.
codes := domain.ExtractAssessmentWatermarkCodes(first.CurrentItem.Prompt)
if len(codes) == 0 || codes[0].String() != first.Watermark.Code {
t.Fatalf("invisible mark = %v, want the visible code %s", codes, first.Watermark.Code)
}
if strings.ContainsAny(first.Watermark.Code, "@ ") {
t.Fatalf("visible code %q holds more than a code", first.Watermark.Code)
}
}
func TestAnUnsetWatermarkerLeavesSnapshotsAsTheyAre(t *testing.T) {
var watermarker *Watermarker
stored := presentedSnapshot(domain.AssessmentAttemptKindRoot)
got, err := watermarker.Present(stored)
if err != nil || got.Watermark != nil || got.CurrentItem.Prompt != watermarkTestPrompt {
t.Fatalf("Present() on a nil Watermarker = %+v, %v, want the unchanged snapshot", got, err)
}
if _, err := NewWatermarker(nil); err == nil {
t.Fatal("NewWatermarker(nil) succeeded, want an error")
}
}
@@ -33,6 +33,7 @@ const (
labelSignalSession = "lincodex/assessment/signal-session/v1"
labelSignalNetwork = "lincodex/assessment/signal-network/v1"
labelResultCursor = "lincodex/assessment/result-history-cursor/v1"
labelWatermark = "lincodex/assessment/watermark/v1"
)
// Keyring computes the keyed digests of the anonymous identity operations:
@@ -53,6 +54,7 @@ type Keyring struct {
signalSessionKey []byte
signalNetworkKey []byte
resultCursorKey []byte
watermarkKey []byte
}
// NewKeyring derives the purpose keys from secret.
@@ -73,6 +75,7 @@ func NewKeyring(secret []byte) (*Keyring, error) {
signalSessionKey: derive(secret, labelSignalSession),
signalNetworkKey: derive(secret, labelSignalNetwork),
resultCursorKey: derive(secret, labelResultCursor),
watermarkKey: derive(secret, labelWatermark),
}, nil
}
@@ -229,3 +232,13 @@ func (keyring *Keyring) AssessmentNetworkDigest(attemptID uuid.UUID, clientKey s
mac.Write([]byte(clientKey))
return domain.AssessmentDigest(mac.Sum(nil))
}
// AssessmentWatermarkSeed is the secret stream that marks the task text of one
// attempt. It is derived under a key of its own, so it cannot be computed from
// an idempotency scope or a digest, and it is never sent to a client: the
// visible code and the invisible mark are read from it on the server.
func (keyring *Keyring) AssessmentWatermarkSeed(attemptID uuid.UUID) domain.AssessmentWatermarkSeed {
mac := hmac.New(sha256.New, keyring.watermarkKey)
mac.Write(attemptID[:])
return domain.AssessmentWatermarkSeed(mac.Sum(nil))
}
@@ -125,6 +125,33 @@ func TestAssessmentSessionAndNetworkDigestsAreBoundToTheAttempt(t *testing.T) {
}
}
func TestAssessmentWatermarkSeedIsKeyedBoundToTheAttemptAndSeparateFromTheDigests(t *testing.T) {
keyring, err := NewKeyring(bytes.Repeat([]byte{1}, MinKeySecretBytes))
if err != nil {
t.Fatalf("NewKeyring() error = %v", err)
}
other, err := NewKeyring(bytes.Repeat([]byte{2}, MinKeySecretBytes))
if err != nil {
t.Fatalf("NewKeyring(other secret) error = %v", err)
}
attempt, otherAttempt := uuid.New(), uuid.New()
seed := keyring.AssessmentWatermarkSeed(attempt)
if seed.IsZero() || seed != keyring.AssessmentWatermarkSeed(attempt) {
t.Fatal("the watermark seed is empty or not deterministic")
}
if seed == keyring.AssessmentWatermarkSeed(otherAttempt) {
t.Fatal("two attempts have the same watermark seed")
}
if seed == other.AssessmentWatermarkSeed(attempt) {
t.Fatal("the watermark seed does not depend on the server secret, so it could be computed by anyone")
}
// The purpose key is its own: no other digest of the attempt equals the seed.
if seed == domain.AssessmentWatermarkSeed(keyring.AssessmentSessionDigest(attempt, attempt)) ||
seed == domain.AssessmentWatermarkSeed(keyring.AssessmentNetworkDigest(attempt, string(attempt[:]))) {
t.Fatal("the watermark seed shares a key with another assessment digest")
}
}
func TestResultHistoryCursorKeyIsSeparateFromIdempotencyAndBoundToTheCandidate(t *testing.T) {
keyring, err := NewKeyring([]byte(strings.Repeat("k", MinKeySecretBytes)))
if err != nil {
+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 аккаунта, бледная и не перехватывает клики, у попытки без кода плитки нет, а дерево доступности размеченного условия содержит слова и ни одного символа форматирования, хотя документ их хранит. Эти тесты не запускают настоящий экранный диктор, брайлевский дисплей или другой браузер, поэтому не показывают, как диктор читает текст; они не показывают и того, сколько попыток можно различить по утечке, потому что канал формулировок дает около одного бита на группу оборотов.
## Тесты внутренних уведомлений
+1 -1
View File
@@ -69,7 +69,7 @@ The attempt screen focuses on the item: a strip above it names the attempt and s
The `Idempotency-Key` of the express start is kept in the tab's sessionStorage per account until the run is finished or expired, and for 24 hours at most. When a new start gets 409 `state_conflict`, the page repeats the start with the key of the active run, and the server returns the stored 201 with that attempt: an unfinished demonstration continues after a reload. The key of a start with an unknown outcome (no response, 5xx) is kept and repeated as well. Without a key (another browser, a closed tab, blocked storage), the screen explains that the demonstration ends by itself within 5 minutes of its start.
Before a real attempt starts, the screen shows a dialog that lists the signals. The browser records tab or window switches, copy, paste and cut, and fullscreen exits; the server measures the answer time per item, a change of network address during the attempt, parallel sessions, and the match of answer digests with other candidates' answers. The dialog states that image, sound, and clipboard contents are not collected, that addresses and session tokens are not stored (only one-way keyed digests), and that browser events are stored only while the C3 consent is current. The attempt cannot start without confirmation: closing the dialog or pressing Escape starts nothing. The dialog also lists the measures the page applies during the attempt (fullscreen, covering the task when the candidate leaves, blocks on copying, selecting, and printing the task text, the paste rule, and a watermark that is announced as planned and not used yet). This is notice text version 2; an acknowledgement of version 1 does not count for it. The confirmation is stored on the server (`/me/assessment-signal-notice`) for the text version, so a reload or a new browser does not ask again; the same dialog opens when an older attempt that was created without the confirmation is resumed. It is a record of being informed, not a consent: C3 stays separate.
Before a real attempt starts, the screen shows a dialog that lists the signals. The browser records tab or window switches, copy, paste and cut, and fullscreen exits; the server measures the answer time per item, a change of network address during the attempt, parallel sessions, and the match of answer digests with other candidates' answers. The dialog states that image, sound, and clipboard contents are not collected, that addresses and session tokens are not stored (only one-way keyed digests), and that browser events are stored only while the C3 consent is current. The attempt cannot start without confirmation: closing the dialog or pressing Escape starts nothing. The dialog also lists the measures the page applies during the attempt (fullscreen, covering the task when the candidate leaves, blocks on copying, selecting, and printing the task text, the paste rule, and the watermark: a faint tile with the attempt code and the time and an invisible mark in the task text). This is notice text version 3; an acknowledgement of an earlier version does not count for it. The confirmation is stored on the server (`/me/assessment-signal-notice`) for the text version, so a reload or a new browser does not ask again; the same dialog opens when an older attempt that was created without the confirmation is resumed. It is a record of being informed, not a consent: C3 stays separate.
During a real attempt, `features/assessment-signals` collects the disclosed signals: focus loss with its duration, copy, paste and cut with a size only, and fullscreen exit. The collector's listeners are passive, block nothing, and show nothing (the measures of the next paragraph are a separate feature and do not depend on it). Events go in batches (every 10 seconds, when the tab is hidden, or at 20 queued events), and each batch keeps one `Idempotency-Key` across retries. When the page is closed (`pagehide`) or the collector unmounts, what remains is sent in one last request with `keepalive`, so closing the tab does not lose the last seconds of events; the result of that request is not awaited and not retried. A network failure never affects answer submission: a failed batch is sent again with the same key and body after a growing pause and is dropped after the attempt limit. A server refusal (no C3, finished attempt) stops collection. The demonstration run collects no signals.
+1 -1
View File
@@ -69,7 +69,7 @@ SPA на React и TypeScript со сборкой Vite и структурой FS
`Idempotency-Key` начала экспресс-запуска хранится в sessionStorage вкладки отдельно для каждого аккаунта, пока запуск не завершен или не истек, и не дольше 24 часов. Если новое начало получает 409 `state_conflict`, страница повторяет начало с ключом активного запуска, и сервер возвращает сохраненный ответ 201 с этой попыткой: незавершенная демонстрация продолжается после перезагрузки. Ключ начала с неизвестным исходом (нет ответа, 5xx) тоже сохраняется и повторяется. Если ключа нет (другой браузер, закрытая вкладка, заблокированное хранилище), экран объясняет, что демонстрация закончится сама не позже чем через 5 минут после начала.
Перед началом реальной попытки экран показывает окно с перечнем сигналов. Браузер фиксирует смену вкладки или окна, копирование, вставку и вырезание, выход из полноэкранного режима; сервер измеряет время ответа на задание, смену сетевого адреса во время попытки, параллельные сессии и совпадение отпечатков ответов с ответами других кандидатов. Окно прямо говорит, что изображение, звук и содержимое буфера обмена не собираются, что адреса и токены сессий не хранятся (только односторонние ключевые отпечатки) и что события браузера сохраняются, только пока действует согласие C3. Начало без подтверждения невозможно: закрытие окна или Escape ничего не запускает. Окно также перечисляет меры, которые страница применяет во время попытки (полноэкранный режим, скрытие задания при уходе, запрет копирования, выделения и печати текста задания, правило вставки и водяной знак, который объявлен как планируемый и пока не используется). Это версия 2 текста уведомления; подтверждение версии 1 для нее не засчитывается. Подтверждение сохраняется на сервере (`/me/assessment-signal-notice`) для версии текста, поэтому перезагрузка и новый браузер не спрашивают повторно; такое же окно открывается при продолжении старой попытки, начатой без подтверждения. Это запись об ознакомлении, а не согласие: C3 остается отдельным.
Перед началом реальной попытки экран показывает окно с перечнем сигналов. Браузер фиксирует смену вкладки или окна, копирование, вставку и вырезание, выход из полноэкранного режима; сервер измеряет время ответа на задание, смену сетевого адреса во время попытки, параллельные сессии и совпадение отпечатков ответов с ответами других кандидатов. Окно прямо говорит, что изображение, звук и содержимое буфера обмена не собираются, что адреса и токены сессий не хранятся (только односторонние ключевые отпечатки) и что события браузера сохраняются, только пока действует согласие C3. Начало без подтверждения невозможно: закрытие окна или Escape ничего не запускает. Окно также перечисляет меры, которые страница применяет во время попытки (полноэкранный режим, скрытие задания при уходе, запрет копирования, выделения и печати текста задания, правило вставки и водяной знак: бледная плитка с кодом попытки и временем и невидимая метка в тексте задания). Это версия 3 текста уведомления; подтверждение более ранней версии для нее не засчитывается. Подтверждение сохраняется на сервере (`/me/assessment-signal-notice`) для версии текста, поэтому перезагрузка и новый браузер не спрашивают повторно; такое же окно открывается при продолжении старой попытки, начатой без подтверждения. Это запись об ознакомлении, а не согласие: C3 остается отдельным.
Во время реальной попытки `features/assessment-signals` собирает отправляемые сигналы: потерю фокуса с длительностью, копирование, вставку и вырезание только с размером, выход из полноэкранного режима. Слушатели сборщика пассивные, ничего не блокируют и не показывают (меры из следующего абзаца - отдельная функция и от сборщика не зависят); события уходят пакетами (по таймеру в 10 секунд, при скрытии вкладки или накоплении 20 событий), у каждого пакета свой `Idempotency-Key`, который сохраняется при повторах. При закрытии страницы (`pagehide`) и при размонтировании оставшиеся события отправляются последним запросом с `keepalive`, поэтому закрытие вкладки не теряет накопленное за последние секунды; результат такого запроса не ожидается и не повторяется. Сбой сети никогда не мешает отправке ответа: неудачный пакет повторяется с тем же ключом и телом с нарастающей паузой, а после лимита попыток отбрасывается. Ответ сервера об отказе (нет C3, попытка завершена) останавливает сбор. Демонстрационный запуск сигналы не собирает.
+16 -6
View File
@@ -44,17 +44,26 @@ export type MockedAttempt = {
acknowledgements: unknown[];
};
export const watermarkCode = "7K3QD-9XM2T";
/** The notice text version the page knows; the mock server requires the same one. */
export const noticeVersion = 3;
type Options = {
content: MockItemContent;
/** The candidate already acknowledged the notice, so the start asks nothing. */
noticeAcknowledged?: boolean;
/** The task text the server sends, with its invisible mark when it has one. */
prompt?: string;
/** The visible code of the attempt, or null for an attempt without one. */
watermark?: string | null;
};
function isoSeconds(ms: number): string {
return `${new Date(ms).toISOString().slice(0, 19)}Z`;
}
function attemptBody(version: number, content: MockItemContent) {
function attemptBody(version: number, options: Options) {
const { content, prompt = taskPrompt, watermark = watermarkCode } = options;
return {
id: attemptId,
version,
@@ -76,8 +85,9 @@ function attemptBody(version: number, content: MockItemContent) {
sessions: { used: 1, max: 2, idle_timeout_seconds: 1800 },
finished_at: null,
progress: { answered_items: 0, max_items: 5 },
current_item: { id: itemId, sequence: 1, prompt: taskPrompt, content },
current_item: { id: itemId, sequence: 1, prompt, content },
practices: [],
...(watermark ? { watermark: { code: watermark } } : {}),
};
}
@@ -118,16 +128,16 @@ export async function mockAttemptApi(page: Page, options: Options): Promise<Mock
recorded.acknowledgements.push(JSON.parse(request.postData() ?? "{}"));
}
return reply({
notice_version: 2,
notice_version: noticeVersion,
acknowledged,
acknowledged_at: acknowledged ? "2026-10-10T10:00:00Z" : null,
});
}
if (path === base && method === "GET") return reply(attemptBody(1, options.content));
if (path === `${base}/sessions`) return reply(attemptBody(2, options.content));
if (path === base && method === "GET") return reply(attemptBody(1, options));
if (path === `${base}/sessions`) return reply(attemptBody(2, options));
if (path === `${base}/answers`) {
recorded.answers.push(JSON.parse(request.postData() ?? "{}"));
return reply(attemptBody(3, options.content));
return reply(attemptBody(3, options));
}
if (path === `${base}/signals`) {
const body = JSON.parse(request.postData() ?? "{}") as { events: SignalEvent[] };
+2 -1
View File
@@ -3,6 +3,7 @@ import {
attemptId,
isFullscreen,
mockAttemptApi,
noticeVersion,
numberContent,
setTabHidden,
startAttempt,
@@ -156,5 +157,5 @@ test("closing the notice without confirming leaves fullscreen and starts nothing
await page.getByRole("button", { name: "Подтверждаю ознакомление и начинаю" }).click();
await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible();
await expect.poll(() => isFullscreen(page)).toBe(true);
expect(recorded.acknowledgements).toEqual([{ notice_version: 2 }]);
expect(recorded.acknowledgements).toEqual([{ notice_version: noticeVersion }]);
});
+82
View File
@@ -0,0 +1,82 @@
import { expect, test } from "@playwright/test";
import {
mockAttemptApi,
numberContent,
startAttempt,
watermarkCode,
} from "./assessment-attempt-mock";
// The watermark of a real attempt: a faint visible tile with the attempt code and
// the time, and an invisible mark in the task text that assistive technology
// never meets. The API is mocked: these specs check what the page does with the
// mark the server sends, not how the server makes it.
const mark = "\u200b\u200c\u200d\u2060\u200b\u200c";
const markedPrompt = `SECRET-PROMPT: which HTTP status ${mark}code means that a resource ${mark}was created?`;
const readablePrompt = "SECRET-PROMPT: which HTTP status code means that a resource was created?";
test.use({ actionTimeout: 10_000, trace: "off", screenshot: "off", video: "off" });
test("the task screen shows a faint tile with the attempt code and the time, and nothing personal", async ({
page,
}) => {
await mockAttemptApi(page, { content: numberContent });
await startAttempt(page);
await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible();
const tile = page.getByTestId("watermark-tile");
await expect(tile).toHaveAttribute("data-code", watermarkCode);
await expect(tile).toHaveAttribute("aria-hidden", "true");
const text = (await tile.textContent()) ?? "";
expect(text).toMatch(new RegExp(`${watermarkCode} \\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}Z`));
// The tile carries no name or contact of the candidate: the mocked account has an e-mail.
expect(text).not.toContain("candidate@example.test");
expect(text).not.toContain("@");
// It is faint, it covers the screen, and it takes no click.
const style = await tile.evaluate((element) => {
const mark = element.firstElementChild as HTMLElement;
return {
opacity: Number(getComputedStyle(mark).opacity),
pointerEvents: getComputedStyle(element).pointerEvents,
position: getComputedStyle(element).position,
};
});
expect(style.opacity).toBeGreaterThan(0.02);
expect(style.opacity).toBeLessThan(0.15);
expect(style.pointerEvents).toBe("none");
expect(style.position).toBe("fixed");
await page.getByRole("textbox", { name: /^Числовой ответ/ }).fill("201");
await expect(page.getByRole("textbox", { name: /^Числовой ответ/ })).toHaveValue("201");
});
test("an attempt without a watermark shows no tile", async ({ page }) => {
await mockAttemptApi(page, { content: numberContent, watermark: null });
await startAttempt(page);
await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible();
await expect(page.getByTestId("watermark-tile")).toHaveCount(0);
});
test("the invisible mark stays in the page but out of the accessibility tree", async ({ page }) => {
await mockAttemptApi(page, { content: numberContent, prompt: markedPrompt });
await startAttempt(page);
await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible();
const prompt = page.locator("article p").first();
// The page keeps the mark, so that anything taken out of the page carries it.
expect(await prompt.evaluate((element) => element.textContent)).toBe(markedPrompt);
// Every run of invisible characters sits in an element hidden from assistive technology.
const hidden = await prompt.evaluate((element) => {
const runs = [...element.querySelectorAll("[data-watermark-mark]")];
return {
count: runs.length,
allHidden: runs.every((run) => run.getAttribute("aria-hidden") === "true"),
};
});
expect(hidden).toEqual({ count: 2, allHidden: true });
// The accessibility tree holds the words and no format character.
const snapshot = await prompt.ariaSnapshot();
expect(snapshot).toContain(readablePrompt);
expect(snapshot).not.toMatch(/[\u200b-\u200d\u2060]/u);
});
+1 -1
View File
@@ -806,7 +806,7 @@ test("closing the notice does not start the attempt and a confirmation is rememb
await page.getByRole("button", { name: "Закрыть без подтверждения" }).click();
await expect(dialog).toBeHidden();
expect(creates).toHaveLength(0);
expect(await readNotice(page)).toMatchObject({ acknowledged: false, notice_version: 2 });
expect(await readNotice(page)).toMatchObject({ acknowledged: false, notice_version: 3 });
await start.click();
await expect(dialog).toBeVisible();
@@ -3,7 +3,7 @@
* candidate acknowledged; change this number together with the text and with
* the version the server requires, so that everyone acknowledges the new text.
*/
export const knownSignalNoticeVersion = 2;
export const knownSignalNoticeVersion = 3;
export type DisclosedSignal = { code: string; title: string; detail: string };
@@ -57,7 +57,8 @@ export const attemptMeasures: readonly DisclosedSignal[] = [
{
code: "watermark",
title: "Водяной знак на странице задания",
detail: "Планируется. Пока не используется.",
detail:
"Бледная плитка с кодом попытки и временем поверх экрана задания и невидимая метка в тексте задания. В них нет имени и контактов. Они не мешают чтению с экрана и ничего не запрещают: по снимку экрана или скопированному тексту можно проверить, из какой попытки они взяты.",
},
];
@@ -4,8 +4,8 @@ import { knownSignalNoticeVersion } from "../model/notice-content";
import { SignalNoticeContent, SignalNoticeDialog, SignalNoticeSummary } from "./signal-notice";
describe("signal notice", () => {
it("is version 2, the text that added the attempt measures", () => {
expect(knownSignalNoticeVersion).toBe(2);
it("is version 3, the text that describes the watermark", () => {
expect(knownSignalNoticeVersion).toBe(3);
});
it("lists every measure the page applies during a real attempt", () => {
@@ -19,7 +19,9 @@ describe("signal notice", () => {
expect(markup).toContain("Вставка в поля ответа");
expect(markup).toContain("В редакторе кода вставка разрешена");
expect(markup).toContain("Водяной знак на странице задания");
expect(markup).toContain("Планируется");
expect(markup).toContain("Бледная плитка с кодом попытки и временем");
expect(markup).toContain("невидимая метка в тексте задания");
expect(markup).not.toContain("Планируется");
});
it("says that keyboard input and screen readers keep working", () => {
@@ -0,0 +1,4 @@
export { accessibleText, splitWatermarkedText } from "./model/watermark-text";
export { formatWatermarkTime } from "./model/watermark-time";
export { WatermarkedText } from "./ui/watermarked-text";
export { WatermarkTile } from "./ui/watermark-tile";
@@ -0,0 +1,17 @@
import { useEffect, useState } from "react";
import { formatWatermarkTime } from "./watermark-time";
const refreshMilliseconds = 15_000;
/** The tile time, refreshed so that it is never more than a minute behind. */
export function useWatermarkTime(): string {
const [time, setTime] = useState(() => formatWatermarkTime(new Date()));
useEffect(() => {
const timer = window.setInterval(() => {
// The same string keeps the state, so the tile re-renders once a minute.
setTime(formatWatermarkTime(new Date()));
}, refreshMilliseconds);
return () => window.clearInterval(timer);
}, []);
return time;
}
@@ -0,0 +1,43 @@
import { describe, expect, it } from "vitest";
import { accessibleText, splitWatermarkedText } from "./watermark-text";
const ZWSP = "\u200b";
const ZWNJ = "\u200c";
const ZWJ = "\u200d";
const WORD_JOINER = "\u2060";
const run = `${ZWSP}${ZWNJ}${ZWJ}${WORD_JOINER}${ZWSP}${ZWSP}`;
const statement = "A cache holds at most 3 entries. A read of a missing key is not a hit.";
const marked = `A cache ${run}holds at most 3 entries. ${run}A read of a missing key is not a hit.`;
describe("watermarked task text", () => {
it("separates the readable words from the invisible runs without losing either", () => {
const segments = splitWatermarkedText(marked);
expect(segments.filter((segment) => segment.kind === "mark")).toHaveLength(2);
expect(segments.map((segment) => segment.value).join("")).toBe(marked);
for (const segment of segments) {
if (segment.kind === "mark") expect(segment.value).toBe(run);
}
});
it("reads exactly the words of the task for assistive technology", () => {
expect(accessibleText(marked)).toBe(statement);
// No format character is left for a screen reader to announce.
expect(accessibleText(marked)).not.toMatch(/\p{Cf}/u);
});
it("handles runs at the edges and a text without a mark", () => {
expect(accessibleText(`${run}text${run}`)).toBe("text");
expect(splitWatermarkedText(`${run}text${run}`).map((segment) => segment.kind)).toEqual([
"mark",
"text",
"mark",
]);
expect(splitWatermarkedText("plain")).toEqual([{ kind: "text", value: "plain" }]);
expect(splitWatermarkedText("")).toEqual([]);
});
it("keeps Cyrillic text and ordinary punctuation as they are", () => {
const text = `Сколько запросов отклонено? ${run}Ответ: число.`;
expect(accessibleText(text)).toBe("Сколько запросов отклонено? Ответ: число.");
});
});
@@ -0,0 +1,41 @@
/**
* The server marks the task text of a real attempt with invisible characters
* (the zero width space, the non-joiner, the joiner, the word joiner) and picks
* interchangeable wordings. The wordings read like any other text. The
* invisible characters are format characters of Unicode; the client keeps them
* out of the accessibility tree, so a screen reader or a braille display never
* meets them, and leaves them in the text so that a copy of the page keeps the
* mark.
*/
export type TextSegment = { kind: "text" | "mark"; value: string };
/** The mark characters. The client treats every Unicode format character alike. */
const markRun = /[\p{Cf}]+/gu;
/** Splits a text into the readable stretches and the runs of invisible characters. */
export function splitWatermarkedText(text: string): TextSegment[] {
const segments: TextSegment[] = [];
let position = 0;
for (const match of text.matchAll(markRun)) {
if (match.index > position) {
segments.push({ kind: "text", value: text.slice(position, match.index) });
}
segments.push({ kind: "mark", value: match[0] });
position = match.index + match[0].length;
}
if (position < text.length) segments.push({ kind: "text", value: text.slice(position) });
return segments;
}
/**
* The text that assistive technology reads: the segments that are not marks.
* The page renders marks in elements hidden from the accessibility tree, so
* this is the accessible name content of the task text.
*/
export function accessibleText(text: string): string {
return splitWatermarkedText(text)
.filter((segment) => segment.kind === "text")
.map((segment) => segment.value)
.join("");
}
@@ -0,0 +1,9 @@
/**
* The time on the tile, to the minute and in UTC with an explicit `Z`, so that
* a screenshot taken in any time zone reads the same way against the server
* clock. It is the clock of the device: an operator treats it as a hint next to
* the code, never as proof.
*/
export function formatWatermarkTime(moment: Date): string {
return `${moment.toISOString().slice(0, 16).replace("T", " ")}Z`;
}
@@ -0,0 +1,24 @@
/* The tile covers the viewport and lets every click through. Its marks are
* faint enough not to disturb reading and dark enough to survive a screenshot. */
.tile {
position: fixed;
z-index: 25;
inset: 0;
overflow: hidden;
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-auto-rows: 1fr;
place-items: center;
transform: rotate(-18deg) scale(1.4);
pointer-events: none;
user-select: none;
}
.mark {
color: var(--color-text-strong);
font-family: var(--font-mono);
font-size: var(--font-size-s);
letter-spacing: 0.04em;
white-space: nowrap;
opacity: 0.07;
}
@@ -0,0 +1,24 @@
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vitest";
import { formatWatermarkTime } from "../model/watermark-time";
import { WatermarkTile } from "./watermark-tile";
describe("watermark tile", () => {
it("shows the pseudonymous code with the time and nothing about the candidate", () => {
const markup = renderToStaticMarkup(<WatermarkTile code="7K3QD-9XM2T" />);
expect(markup).toContain("7K3QD-9XM2T");
expect(markup).toMatch(/7K3QD-9XM2T \d{4}-\d{2}-\d{2} \d{2}:\d{2}Z/);
expect(markup).not.toMatch(/@|\+\d{6,}|candidate|email/i);
});
it("is hidden from assistive technology and marked for the page checks", () => {
const markup = renderToStaticMarkup(<WatermarkTile code="7K3QD-9XM2T" />);
expect(markup).toContain('aria-hidden="true"');
expect(markup).toContain('data-testid="watermark-tile"');
expect(markup).toContain('data-code="7K3QD-9XM2T"');
});
it("writes the time to the minute in UTC", () => {
expect(formatWatermarkTime(new Date("2026-10-11T07:42:59.900Z"))).toBe("2026-10-11 07:42Z");
});
});
@@ -0,0 +1,30 @@
import { useWatermarkTime } from "../model/use-watermark-time";
import styles from "./watermark-tile.module.css";
type WatermarkTileProps = {
/** The pseudonymous attempt code from the server. */
code: string;
};
const rows = 8;
const columns = 3;
/**
* A faint tile over the task screen: the attempt code and the time, repeated.
* A screenshot or a photo of the screen carries it, and an operator can trace
* the image to the attempt. It holds no name, e-mail, or other contact, it is
* hidden from assistive technology, and it never takes a click.
*/
export function WatermarkTile({ code }: WatermarkTileProps) {
const time = useWatermarkTime();
const label = `${code} ${time}`;
return (
<div className={styles.tile} aria-hidden="true" data-testid="watermark-tile" data-code={code}>
{Array.from({ length: rows * columns }, (_, index) => (
<span key={index} className={styles.mark}>
{label}
</span>
))}
</div>
);
}
@@ -0,0 +1,43 @@
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vitest";
import { accessibleText } from "../model/watermark-text";
import { WatermarkedText } from "./watermarked-text";
const run = "\u200b\u200c\u200d\u2060";
const marked = `The gateway ${run}rejects requests. ${run}How many?`;
/**
* The accessible text of the markup: what is left after the elements hidden
* from the accessibility tree and the tags themselves are removed, which is
* what a screen reader would read from this fragment.
*/
function readByAssistiveTechnology(markup: string): string {
return markup.replace(/<span aria-hidden="true"[^>]*>[^<]*<\/span>/g, "").replace(/<[^>]+>/g, "");
}
describe("watermarked text", () => {
it("puts every invisible run in an element hidden from assistive technology", () => {
const markup = renderToStaticMarkup(
<p>
<WatermarkedText text={marked} />
</p>,
);
expect(markup.match(/aria-hidden="true"/g)).toHaveLength(2);
expect(markup).toContain(run);
});
it("leaves a screen reader exactly the words of the task", () => {
const markup = renderToStaticMarkup(
<p>
<WatermarkedText text={marked} />
</p>,
);
expect(readByAssistiveTechnology(markup)).toBe("The gateway rejects requests. How many?");
expect(readByAssistiveTechnology(markup)).toBe(accessibleText(marked));
expect(readByAssistiveTechnology(markup)).not.toMatch(/\p{Cf}/u);
});
it("renders a text without a mark as it is", () => {
expect(renderToStaticMarkup(<WatermarkedText text="No mark here." />)).toBe("No mark here.");
});
});
@@ -0,0 +1,28 @@
import { splitWatermarkedText } from "../model/watermark-text";
type WatermarkedTextProps = {
/** The task text as the server sent it, with the invisible mark in it. */
text: string;
};
/**
* Shows the task text. The runs of invisible characters go into elements that
* are hidden from assistive technology, so the accessible text is exactly the
* words of the task. The characters stay in the document, which keeps the mark
* in anything copied from the page.
*/
export function WatermarkedText({ text }: WatermarkedTextProps) {
return (
<>
{splitWatermarkedText(text).map((segment, index) =>
segment.kind === "mark" ? (
<span key={index} aria-hidden="true" data-watermark-mark="">
{segment.value}
</span>
) : (
segment.value
),
)}
</>
);
}
@@ -64,6 +64,7 @@ import {
useAssessmentSignals,
useSignalNoticeGate,
} from "../../../features/assessment-signals";
import { WatermarkedText, WatermarkTile } from "../../../features/assessment-watermark";
import { forgetExpressStart } from "../model/express-start";
import { AttemptFocusBar, type AnswerSaveState } from "./attempt-focus-bar";
import attemptStyles from "./assessment-attempt-page.module.css";
@@ -704,7 +705,9 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
{`${currentItem.sequence} из ${attempt.progress.max_items}`}
</VisuallyHidden>
</div>
<p className={attemptStyles.prompt}>{currentItem.prompt}</p>
<p className={attemptStyles.prompt}>
<WatermarkedText text={currentItem.prompt} />
</p>
</>
}
>
@@ -794,6 +797,9 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
</ButtonLink>
</div>
</div>
{attempt.watermark && workReady && !terminal ? (
<WatermarkTile code={attempt.watermark.code} />
) : null}
<SignalNoticeDialog {...signalNotice.dialog} />
</Page>
);
@@ -84,11 +84,11 @@ export const getCreateMyAssessmentAttemptResponseAssessmentItemMock = (overrideR
export const getCreateMyAssessmentAttemptResponsePracticeVerdictMock = (overrideResponse: Partial<PracticeVerdict> = {}): PracticeVerdict => ({...{score: faker.number.int({min: 0, max: 3}), max_score: faker.number.int({min: 3, max: 3}), groups: Array.from({ length: faker.number.int({min: 3, max: 3}) }, (_, i) => i + 1).map(() => ({group: faker.number.int({min: 1, max: 3}), passed: faker.datatype.boolean()}))}, ...overrideResponse});
export const getCreateMyAssessmentAttemptResponseAssessmentQualifiedAttemptMock = (overrideResponse: Partial<AssessmentQualifiedAttempt> = {}): AssessmentQualifiedAttempt => ({...{...{...{id: faker.string.uuid(), version: faker.number.int({min: 1}), specialization: faker.helpers.arrayElement([faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const),null,]), target_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(['python','go'] as const),null,]), kind: faker.helpers.arrayElement(['root','corrective','demo_express'] as const), root_attempt_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), chain_deadline: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), mode: faker.helpers.arrayElement(['demo_basic','demo_express','adaptive'] as const), state: faker.helpers.arrayElement(['in_progress','practice_pending','additional_practice_pending','ready_to_finalize','completed','expired','insufficient_bank'] as const), versions: {policy_version: faker.number.int({min: 1}), bank_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), algorithm_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64})}, started_at: faker.date.past().toISOString().slice(0, 19) + 'Z', expires_at: faker.date.past().toISOString().slice(0, 19) + 'Z', sessions: faker.helpers.arrayElement([{...getCreateMyAssessmentAttemptResponseAssessmentSessionsMock()},null,]), finished_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), progress: {answered_items: faker.number.int({min: 0, max: 100}), max_items: faker.number.int({min: 1, max: 100})}, current_item: faker.helpers.arrayElement([{...getCreateMyAssessmentAttemptResponseAssessmentItemMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(['main','additional'] as const), item_id: faker.string.uuid(), status: faker.helpers.arrayElement(['not_started','pending','finished','failed'] as const), submitted_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), verdict: faker.helpers.arrayElement([{...getCreateMyAssessmentAttemptResponsePracticeVerdictMock()},null,]), failure_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['sandbox_busy','sandbox_error'] as const),null,])}))},...{kind: faker.helpers.arrayElement(['root'] as const), mode: faker.helpers.arrayElement(['demo_basic','adaptive'] as const), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), target_grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), root_attempt_id: null, chain_deadline: null},}, kind: faker.helpers.arrayElement(['root'] as const)}, ...overrideResponse});
export const getCreateMyAssessmentAttemptResponseAssessmentQualifiedAttemptMock = (overrideResponse: Partial<AssessmentQualifiedAttempt> = {}): AssessmentQualifiedAttempt => ({...{...{...{id: faker.string.uuid(), version: faker.number.int({min: 1}), specialization: faker.helpers.arrayElement([faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const),null,]), target_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(['python','go'] as const),null,]), kind: faker.helpers.arrayElement(['root','corrective','demo_express'] as const), root_attempt_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), chain_deadline: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), mode: faker.helpers.arrayElement(['demo_basic','demo_express','adaptive'] as const), state: faker.helpers.arrayElement(['in_progress','practice_pending','additional_practice_pending','ready_to_finalize','completed','expired','insufficient_bank'] as const), versions: {policy_version: faker.number.int({min: 1}), bank_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), algorithm_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64})}, started_at: faker.date.past().toISOString().slice(0, 19) + 'Z', expires_at: faker.date.past().toISOString().slice(0, 19) + 'Z', sessions: faker.helpers.arrayElement([{...getCreateMyAssessmentAttemptResponseAssessmentSessionsMock()},null,]), finished_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), progress: {answered_items: faker.number.int({min: 0, max: 100}), max_items: faker.number.int({min: 1, max: 100})}, current_item: faker.helpers.arrayElement([{...getCreateMyAssessmentAttemptResponseAssessmentItemMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(['main','additional'] as const), item_id: faker.string.uuid(), status: faker.helpers.arrayElement(['not_started','pending','finished','failed'] as const), submitted_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), verdict: faker.helpers.arrayElement([{...getCreateMyAssessmentAttemptResponsePracticeVerdictMock()},null,]), failure_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['sandbox_busy','sandbox_error'] as const),null,])})), ...(faker.datatype.boolean() ? {watermark: {code: fakeFromPattern("^[0-9A-HJKMNP-TV-Z]{5}-?[0-9A-HJKMNP-TV-Z]{5}$", {minLength: 10, maxLength: 11})}} : {})},...{kind: faker.helpers.arrayElement(['root'] as const), mode: faker.helpers.arrayElement(['demo_basic','adaptive'] as const), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), target_grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), root_attempt_id: null, chain_deadline: null},}, kind: faker.helpers.arrayElement(['root'] as const)}, ...overrideResponse});
export const getCreateMyAssessmentAttemptResponseAssessmentCorrectiveAttemptMock = (overrideResponse: Partial<AssessmentCorrectiveAttempt> = {}): AssessmentCorrectiveAttempt => ({...{...{...{id: faker.string.uuid(), version: faker.number.int({min: 1}), specialization: faker.helpers.arrayElement([faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const),null,]), target_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(['python','go'] as const),null,]), kind: faker.helpers.arrayElement(['root','corrective','demo_express'] as const), root_attempt_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), chain_deadline: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), mode: faker.helpers.arrayElement(['demo_basic','demo_express','adaptive'] as const), state: faker.helpers.arrayElement(['in_progress','practice_pending','additional_practice_pending','ready_to_finalize','completed','expired','insufficient_bank'] as const), versions: {policy_version: faker.number.int({min: 1}), bank_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), algorithm_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64})}, started_at: faker.date.past().toISOString().slice(0, 19) + 'Z', expires_at: faker.date.past().toISOString().slice(0, 19) + 'Z', sessions: faker.helpers.arrayElement([{...getCreateMyAssessmentAttemptResponseAssessmentSessionsMock()},null,]), finished_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), progress: {answered_items: faker.number.int({min: 0, max: 100}), max_items: faker.number.int({min: 1, max: 100})}, current_item: faker.helpers.arrayElement([{...getCreateMyAssessmentAttemptResponseAssessmentItemMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(['main','additional'] as const), item_id: faker.string.uuid(), status: faker.helpers.arrayElement(['not_started','pending','finished','failed'] as const), submitted_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), verdict: faker.helpers.arrayElement([{...getCreateMyAssessmentAttemptResponsePracticeVerdictMock()},null,]), failure_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['sandbox_busy','sandbox_error'] as const),null,])}))},...{kind: faker.helpers.arrayElement(['corrective'] as const), mode: faker.helpers.arrayElement(['demo_basic','adaptive'] as const), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), target_grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), root_attempt_id: faker.string.uuid(), chain_deadline: faker.date.past().toISOString().slice(0, 19) + 'Z'},}, kind: faker.helpers.arrayElement(['corrective'] as const)}, ...overrideResponse});
export const getCreateMyAssessmentAttemptResponseAssessmentCorrectiveAttemptMock = (overrideResponse: Partial<AssessmentCorrectiveAttempt> = {}): AssessmentCorrectiveAttempt => ({...{...{...{id: faker.string.uuid(), version: faker.number.int({min: 1}), specialization: faker.helpers.arrayElement([faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const),null,]), target_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(['python','go'] as const),null,]), kind: faker.helpers.arrayElement(['root','corrective','demo_express'] as const), root_attempt_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), chain_deadline: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), mode: faker.helpers.arrayElement(['demo_basic','demo_express','adaptive'] as const), state: faker.helpers.arrayElement(['in_progress','practice_pending','additional_practice_pending','ready_to_finalize','completed','expired','insufficient_bank'] as const), versions: {policy_version: faker.number.int({min: 1}), bank_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), algorithm_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64})}, started_at: faker.date.past().toISOString().slice(0, 19) + 'Z', expires_at: faker.date.past().toISOString().slice(0, 19) + 'Z', sessions: faker.helpers.arrayElement([{...getCreateMyAssessmentAttemptResponseAssessmentSessionsMock()},null,]), finished_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), progress: {answered_items: faker.number.int({min: 0, max: 100}), max_items: faker.number.int({min: 1, max: 100})}, current_item: faker.helpers.arrayElement([{...getCreateMyAssessmentAttemptResponseAssessmentItemMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(['main','additional'] as const), item_id: faker.string.uuid(), status: faker.helpers.arrayElement(['not_started','pending','finished','failed'] as const), submitted_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), verdict: faker.helpers.arrayElement([{...getCreateMyAssessmentAttemptResponsePracticeVerdictMock()},null,]), failure_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['sandbox_busy','sandbox_error'] as const),null,])})), ...(faker.datatype.boolean() ? {watermark: {code: fakeFromPattern("^[0-9A-HJKMNP-TV-Z]{5}-?[0-9A-HJKMNP-TV-Z]{5}$", {minLength: 10, maxLength: 11})}} : {})},...{kind: faker.helpers.arrayElement(['corrective'] as const), mode: faker.helpers.arrayElement(['demo_basic','adaptive'] as const), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), target_grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), root_attempt_id: faker.string.uuid(), chain_deadline: faker.date.past().toISOString().slice(0, 19) + 'Z'},}, kind: faker.helpers.arrayElement(['corrective'] as const)}, ...overrideResponse});
export const getCreateMyAssessmentAttemptResponseAssessmentExpressAttemptMock = (overrideResponse: Partial<AssessmentExpressAttempt> = {}): AssessmentExpressAttempt => ({...{...{...{id: faker.string.uuid(), version: faker.number.int({min: 1}), specialization: faker.helpers.arrayElement([faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const),null,]), target_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(['python','go'] as const),null,]), kind: faker.helpers.arrayElement(['root','corrective','demo_express'] as const), root_attempt_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), chain_deadline: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), mode: faker.helpers.arrayElement(['demo_basic','demo_express','adaptive'] as const), state: faker.helpers.arrayElement(['in_progress','practice_pending','additional_practice_pending','ready_to_finalize','completed','expired','insufficient_bank'] as const), versions: {policy_version: faker.number.int({min: 1}), bank_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), algorithm_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64})}, started_at: faker.date.past().toISOString().slice(0, 19) + 'Z', expires_at: faker.date.past().toISOString().slice(0, 19) + 'Z', sessions: faker.helpers.arrayElement([{...getCreateMyAssessmentAttemptResponseAssessmentSessionsMock()},null,]), finished_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), progress: {answered_items: faker.number.int({min: 0, max: 100}), max_items: faker.number.int({min: 1, max: 100})}, current_item: faker.helpers.arrayElement([{...getCreateMyAssessmentAttemptResponseAssessmentItemMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(['main','additional'] as const), item_id: faker.string.uuid(), status: faker.helpers.arrayElement(['not_started','pending','finished','failed'] as const), submitted_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), verdict: faker.helpers.arrayElement([{...getCreateMyAssessmentAttemptResponsePracticeVerdictMock()},null,]), failure_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['sandbox_busy','sandbox_error'] as const),null,])}))},...{kind: faker.helpers.arrayElement(['demo_express'] as const), mode: faker.helpers.arrayElement(['demo_express'] as const), specialization: null, target_grade: null, task_language: null, root_attempt_id: null, chain_deadline: null},}, kind: faker.helpers.arrayElement(['demo_express'] as const)}, ...overrideResponse});
export const getCreateMyAssessmentAttemptResponseAssessmentExpressAttemptMock = (overrideResponse: Partial<AssessmentExpressAttempt> = {}): AssessmentExpressAttempt => ({...{...{...{id: faker.string.uuid(), version: faker.number.int({min: 1}), specialization: faker.helpers.arrayElement([faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const),null,]), target_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(['python','go'] as const),null,]), kind: faker.helpers.arrayElement(['root','corrective','demo_express'] as const), root_attempt_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), chain_deadline: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), mode: faker.helpers.arrayElement(['demo_basic','demo_express','adaptive'] as const), state: faker.helpers.arrayElement(['in_progress','practice_pending','additional_practice_pending','ready_to_finalize','completed','expired','insufficient_bank'] as const), versions: {policy_version: faker.number.int({min: 1}), bank_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), algorithm_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64})}, started_at: faker.date.past().toISOString().slice(0, 19) + 'Z', expires_at: faker.date.past().toISOString().slice(0, 19) + 'Z', sessions: faker.helpers.arrayElement([{...getCreateMyAssessmentAttemptResponseAssessmentSessionsMock()},null,]), finished_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), progress: {answered_items: faker.number.int({min: 0, max: 100}), max_items: faker.number.int({min: 1, max: 100})}, current_item: faker.helpers.arrayElement([{...getCreateMyAssessmentAttemptResponseAssessmentItemMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(['main','additional'] as const), item_id: faker.string.uuid(), status: faker.helpers.arrayElement(['not_started','pending','finished','failed'] as const), submitted_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), verdict: faker.helpers.arrayElement([{...getCreateMyAssessmentAttemptResponsePracticeVerdictMock()},null,]), failure_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['sandbox_busy','sandbox_error'] as const),null,])})), ...(faker.datatype.boolean() ? {watermark: {code: fakeFromPattern("^[0-9A-HJKMNP-TV-Z]{5}-?[0-9A-HJKMNP-TV-Z]{5}$", {minLength: 10, maxLength: 11})}} : {})},...{kind: faker.helpers.arrayElement(['demo_express'] as const), mode: faker.helpers.arrayElement(['demo_express'] as const), specialization: null, target_grade: null, task_language: null, root_attempt_id: null, chain_deadline: null},}, kind: faker.helpers.arrayElement(['demo_express'] as const)}, ...overrideResponse});
export const getCreateMyAssessmentAttemptResponseMock = (): AssessmentAttempt => (faker.helpers.arrayElement([{...getCreateMyAssessmentAttemptResponseAssessmentQualifiedAttemptMock()},{...getCreateMyAssessmentAttemptResponseAssessmentCorrectiveAttemptMock()},{...getCreateMyAssessmentAttemptResponseAssessmentExpressAttemptMock()},]))
@@ -112,11 +112,11 @@ export const getGetMyAssessmentAttemptResponseAssessmentItemMock = (overrideResp
export const getGetMyAssessmentAttemptResponsePracticeVerdictMock = (overrideResponse: Partial<PracticeVerdict> = {}): PracticeVerdict => ({...{score: faker.number.int({min: 0, max: 3}), max_score: faker.number.int({min: 3, max: 3}), groups: Array.from({ length: faker.number.int({min: 3, max: 3}) }, (_, i) => i + 1).map(() => ({group: faker.number.int({min: 1, max: 3}), passed: faker.datatype.boolean()}))}, ...overrideResponse});
export const getGetMyAssessmentAttemptResponseAssessmentQualifiedAttemptMock = (overrideResponse: Partial<AssessmentQualifiedAttempt> = {}): AssessmentQualifiedAttempt => ({...{...{...{id: faker.string.uuid(), version: faker.number.int({min: 1}), specialization: faker.helpers.arrayElement([faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const),null,]), target_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(['python','go'] as const),null,]), kind: faker.helpers.arrayElement(['root','corrective','demo_express'] as const), root_attempt_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), chain_deadline: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), mode: faker.helpers.arrayElement(['demo_basic','demo_express','adaptive'] as const), state: faker.helpers.arrayElement(['in_progress','practice_pending','additional_practice_pending','ready_to_finalize','completed','expired','insufficient_bank'] as const), versions: {policy_version: faker.number.int({min: 1}), bank_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), algorithm_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64})}, started_at: faker.date.past().toISOString().slice(0, 19) + 'Z', expires_at: faker.date.past().toISOString().slice(0, 19) + 'Z', sessions: faker.helpers.arrayElement([{...getGetMyAssessmentAttemptResponseAssessmentSessionsMock()},null,]), finished_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), progress: {answered_items: faker.number.int({min: 0, max: 100}), max_items: faker.number.int({min: 1, max: 100})}, current_item: faker.helpers.arrayElement([{...getGetMyAssessmentAttemptResponseAssessmentItemMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(['main','additional'] as const), item_id: faker.string.uuid(), status: faker.helpers.arrayElement(['not_started','pending','finished','failed'] as const), submitted_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), verdict: faker.helpers.arrayElement([{...getGetMyAssessmentAttemptResponsePracticeVerdictMock()},null,]), failure_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['sandbox_busy','sandbox_error'] as const),null,])}))},...{kind: faker.helpers.arrayElement(['root'] as const), mode: faker.helpers.arrayElement(['demo_basic','adaptive'] as const), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), target_grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), root_attempt_id: null, chain_deadline: null},}, kind: faker.helpers.arrayElement(['root'] as const)}, ...overrideResponse});
export const getGetMyAssessmentAttemptResponseAssessmentQualifiedAttemptMock = (overrideResponse: Partial<AssessmentQualifiedAttempt> = {}): AssessmentQualifiedAttempt => ({...{...{...{id: faker.string.uuid(), version: faker.number.int({min: 1}), specialization: faker.helpers.arrayElement([faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const),null,]), target_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(['python','go'] as const),null,]), kind: faker.helpers.arrayElement(['root','corrective','demo_express'] as const), root_attempt_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), chain_deadline: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), mode: faker.helpers.arrayElement(['demo_basic','demo_express','adaptive'] as const), state: faker.helpers.arrayElement(['in_progress','practice_pending','additional_practice_pending','ready_to_finalize','completed','expired','insufficient_bank'] as const), versions: {policy_version: faker.number.int({min: 1}), bank_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), algorithm_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64})}, started_at: faker.date.past().toISOString().slice(0, 19) + 'Z', expires_at: faker.date.past().toISOString().slice(0, 19) + 'Z', sessions: faker.helpers.arrayElement([{...getGetMyAssessmentAttemptResponseAssessmentSessionsMock()},null,]), finished_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), progress: {answered_items: faker.number.int({min: 0, max: 100}), max_items: faker.number.int({min: 1, max: 100})}, current_item: faker.helpers.arrayElement([{...getGetMyAssessmentAttemptResponseAssessmentItemMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(['main','additional'] as const), item_id: faker.string.uuid(), status: faker.helpers.arrayElement(['not_started','pending','finished','failed'] as const), submitted_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), verdict: faker.helpers.arrayElement([{...getGetMyAssessmentAttemptResponsePracticeVerdictMock()},null,]), failure_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['sandbox_busy','sandbox_error'] as const),null,])})), ...(faker.datatype.boolean() ? {watermark: {code: fakeFromPattern("^[0-9A-HJKMNP-TV-Z]{5}-?[0-9A-HJKMNP-TV-Z]{5}$", {minLength: 10, maxLength: 11})}} : {})},...{kind: faker.helpers.arrayElement(['root'] as const), mode: faker.helpers.arrayElement(['demo_basic','adaptive'] as const), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), target_grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), root_attempt_id: null, chain_deadline: null},}, kind: faker.helpers.arrayElement(['root'] as const)}, ...overrideResponse});
export const getGetMyAssessmentAttemptResponseAssessmentCorrectiveAttemptMock = (overrideResponse: Partial<AssessmentCorrectiveAttempt> = {}): AssessmentCorrectiveAttempt => ({...{...{...{id: faker.string.uuid(), version: faker.number.int({min: 1}), specialization: faker.helpers.arrayElement([faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const),null,]), target_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(['python','go'] as const),null,]), kind: faker.helpers.arrayElement(['root','corrective','demo_express'] as const), root_attempt_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), chain_deadline: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), mode: faker.helpers.arrayElement(['demo_basic','demo_express','adaptive'] as const), state: faker.helpers.arrayElement(['in_progress','practice_pending','additional_practice_pending','ready_to_finalize','completed','expired','insufficient_bank'] as const), versions: {policy_version: faker.number.int({min: 1}), bank_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), algorithm_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64})}, started_at: faker.date.past().toISOString().slice(0, 19) + 'Z', expires_at: faker.date.past().toISOString().slice(0, 19) + 'Z', sessions: faker.helpers.arrayElement([{...getGetMyAssessmentAttemptResponseAssessmentSessionsMock()},null,]), finished_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), progress: {answered_items: faker.number.int({min: 0, max: 100}), max_items: faker.number.int({min: 1, max: 100})}, current_item: faker.helpers.arrayElement([{...getGetMyAssessmentAttemptResponseAssessmentItemMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(['main','additional'] as const), item_id: faker.string.uuid(), status: faker.helpers.arrayElement(['not_started','pending','finished','failed'] as const), submitted_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), verdict: faker.helpers.arrayElement([{...getGetMyAssessmentAttemptResponsePracticeVerdictMock()},null,]), failure_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['sandbox_busy','sandbox_error'] as const),null,])}))},...{kind: faker.helpers.arrayElement(['corrective'] as const), mode: faker.helpers.arrayElement(['demo_basic','adaptive'] as const), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), target_grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), root_attempt_id: faker.string.uuid(), chain_deadline: faker.date.past().toISOString().slice(0, 19) + 'Z'},}, kind: faker.helpers.arrayElement(['corrective'] as const)}, ...overrideResponse});
export const getGetMyAssessmentAttemptResponseAssessmentCorrectiveAttemptMock = (overrideResponse: Partial<AssessmentCorrectiveAttempt> = {}): AssessmentCorrectiveAttempt => ({...{...{...{id: faker.string.uuid(), version: faker.number.int({min: 1}), specialization: faker.helpers.arrayElement([faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const),null,]), target_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(['python','go'] as const),null,]), kind: faker.helpers.arrayElement(['root','corrective','demo_express'] as const), root_attempt_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), chain_deadline: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), mode: faker.helpers.arrayElement(['demo_basic','demo_express','adaptive'] as const), state: faker.helpers.arrayElement(['in_progress','practice_pending','additional_practice_pending','ready_to_finalize','completed','expired','insufficient_bank'] as const), versions: {policy_version: faker.number.int({min: 1}), bank_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), algorithm_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64})}, started_at: faker.date.past().toISOString().slice(0, 19) + 'Z', expires_at: faker.date.past().toISOString().slice(0, 19) + 'Z', sessions: faker.helpers.arrayElement([{...getGetMyAssessmentAttemptResponseAssessmentSessionsMock()},null,]), finished_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), progress: {answered_items: faker.number.int({min: 0, max: 100}), max_items: faker.number.int({min: 1, max: 100})}, current_item: faker.helpers.arrayElement([{...getGetMyAssessmentAttemptResponseAssessmentItemMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(['main','additional'] as const), item_id: faker.string.uuid(), status: faker.helpers.arrayElement(['not_started','pending','finished','failed'] as const), submitted_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), verdict: faker.helpers.arrayElement([{...getGetMyAssessmentAttemptResponsePracticeVerdictMock()},null,]), failure_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['sandbox_busy','sandbox_error'] as const),null,])})), ...(faker.datatype.boolean() ? {watermark: {code: fakeFromPattern("^[0-9A-HJKMNP-TV-Z]{5}-?[0-9A-HJKMNP-TV-Z]{5}$", {minLength: 10, maxLength: 11})}} : {})},...{kind: faker.helpers.arrayElement(['corrective'] as const), mode: faker.helpers.arrayElement(['demo_basic','adaptive'] as const), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), target_grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), root_attempt_id: faker.string.uuid(), chain_deadline: faker.date.past().toISOString().slice(0, 19) + 'Z'},}, kind: faker.helpers.arrayElement(['corrective'] as const)}, ...overrideResponse});
export const getGetMyAssessmentAttemptResponseAssessmentExpressAttemptMock = (overrideResponse: Partial<AssessmentExpressAttempt> = {}): AssessmentExpressAttempt => ({...{...{...{id: faker.string.uuid(), version: faker.number.int({min: 1}), specialization: faker.helpers.arrayElement([faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const),null,]), target_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(['python','go'] as const),null,]), kind: faker.helpers.arrayElement(['root','corrective','demo_express'] as const), root_attempt_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), chain_deadline: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), mode: faker.helpers.arrayElement(['demo_basic','demo_express','adaptive'] as const), state: faker.helpers.arrayElement(['in_progress','practice_pending','additional_practice_pending','ready_to_finalize','completed','expired','insufficient_bank'] as const), versions: {policy_version: faker.number.int({min: 1}), bank_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), algorithm_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64})}, started_at: faker.date.past().toISOString().slice(0, 19) + 'Z', expires_at: faker.date.past().toISOString().slice(0, 19) + 'Z', sessions: faker.helpers.arrayElement([{...getGetMyAssessmentAttemptResponseAssessmentSessionsMock()},null,]), finished_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), progress: {answered_items: faker.number.int({min: 0, max: 100}), max_items: faker.number.int({min: 1, max: 100})}, current_item: faker.helpers.arrayElement([{...getGetMyAssessmentAttemptResponseAssessmentItemMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(['main','additional'] as const), item_id: faker.string.uuid(), status: faker.helpers.arrayElement(['not_started','pending','finished','failed'] as const), submitted_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), verdict: faker.helpers.arrayElement([{...getGetMyAssessmentAttemptResponsePracticeVerdictMock()},null,]), failure_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['sandbox_busy','sandbox_error'] as const),null,])}))},...{kind: faker.helpers.arrayElement(['demo_express'] as const), mode: faker.helpers.arrayElement(['demo_express'] as const), specialization: null, target_grade: null, task_language: null, root_attempt_id: null, chain_deadline: null},}, kind: faker.helpers.arrayElement(['demo_express'] as const)}, ...overrideResponse});
export const getGetMyAssessmentAttemptResponseAssessmentExpressAttemptMock = (overrideResponse: Partial<AssessmentExpressAttempt> = {}): AssessmentExpressAttempt => ({...{...{...{id: faker.string.uuid(), version: faker.number.int({min: 1}), specialization: faker.helpers.arrayElement([faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const),null,]), target_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(['python','go'] as const),null,]), kind: faker.helpers.arrayElement(['root','corrective','demo_express'] as const), root_attempt_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), chain_deadline: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), mode: faker.helpers.arrayElement(['demo_basic','demo_express','adaptive'] as const), state: faker.helpers.arrayElement(['in_progress','practice_pending','additional_practice_pending','ready_to_finalize','completed','expired','insufficient_bank'] as const), versions: {policy_version: faker.number.int({min: 1}), bank_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), algorithm_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64})}, started_at: faker.date.past().toISOString().slice(0, 19) + 'Z', expires_at: faker.date.past().toISOString().slice(0, 19) + 'Z', sessions: faker.helpers.arrayElement([{...getGetMyAssessmentAttemptResponseAssessmentSessionsMock()},null,]), finished_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), progress: {answered_items: faker.number.int({min: 0, max: 100}), max_items: faker.number.int({min: 1, max: 100})}, current_item: faker.helpers.arrayElement([{...getGetMyAssessmentAttemptResponseAssessmentItemMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(['main','additional'] as const), item_id: faker.string.uuid(), status: faker.helpers.arrayElement(['not_started','pending','finished','failed'] as const), submitted_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), verdict: faker.helpers.arrayElement([{...getGetMyAssessmentAttemptResponsePracticeVerdictMock()},null,]), failure_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['sandbox_busy','sandbox_error'] as const),null,])})), ...(faker.datatype.boolean() ? {watermark: {code: fakeFromPattern("^[0-9A-HJKMNP-TV-Z]{5}-?[0-9A-HJKMNP-TV-Z]{5}$", {minLength: 10, maxLength: 11})}} : {})},...{kind: faker.helpers.arrayElement(['demo_express'] as const), mode: faker.helpers.arrayElement(['demo_express'] as const), specialization: null, target_grade: null, task_language: null, root_attempt_id: null, chain_deadline: null},}, kind: faker.helpers.arrayElement(['demo_express'] as const)}, ...overrideResponse});
export const getGetMyAssessmentAttemptResponseMock = (): AssessmentAttempt => (faker.helpers.arrayElement([{...getGetMyAssessmentAttemptResponseAssessmentQualifiedAttemptMock()},{...getGetMyAssessmentAttemptResponseAssessmentCorrectiveAttemptMock()},{...getGetMyAssessmentAttemptResponseAssessmentExpressAttemptMock()},]))
@@ -140,11 +140,11 @@ export const getStartMyAssessmentAttemptSessionResponseAssessmentItemMock = (ove
export const getStartMyAssessmentAttemptSessionResponsePracticeVerdictMock = (overrideResponse: Partial<PracticeVerdict> = {}): PracticeVerdict => ({...{score: faker.number.int({min: 0, max: 3}), max_score: faker.number.int({min: 3, max: 3}), groups: Array.from({ length: faker.number.int({min: 3, max: 3}) }, (_, i) => i + 1).map(() => ({group: faker.number.int({min: 1, max: 3}), passed: faker.datatype.boolean()}))}, ...overrideResponse});
export const getStartMyAssessmentAttemptSessionResponseAssessmentQualifiedAttemptMock = (overrideResponse: Partial<AssessmentQualifiedAttempt> = {}): AssessmentQualifiedAttempt => ({...{...{...{id: faker.string.uuid(), version: faker.number.int({min: 1}), specialization: faker.helpers.arrayElement([faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const),null,]), target_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(['python','go'] as const),null,]), kind: faker.helpers.arrayElement(['root','corrective','demo_express'] as const), root_attempt_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), chain_deadline: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), mode: faker.helpers.arrayElement(['demo_basic','demo_express','adaptive'] as const), state: faker.helpers.arrayElement(['in_progress','practice_pending','additional_practice_pending','ready_to_finalize','completed','expired','insufficient_bank'] as const), versions: {policy_version: faker.number.int({min: 1}), bank_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), algorithm_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64})}, started_at: faker.date.past().toISOString().slice(0, 19) + 'Z', expires_at: faker.date.past().toISOString().slice(0, 19) + 'Z', sessions: faker.helpers.arrayElement([{...getStartMyAssessmentAttemptSessionResponseAssessmentSessionsMock()},null,]), finished_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), progress: {answered_items: faker.number.int({min: 0, max: 100}), max_items: faker.number.int({min: 1, max: 100})}, current_item: faker.helpers.arrayElement([{...getStartMyAssessmentAttemptSessionResponseAssessmentItemMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(['main','additional'] as const), item_id: faker.string.uuid(), status: faker.helpers.arrayElement(['not_started','pending','finished','failed'] as const), submitted_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), verdict: faker.helpers.arrayElement([{...getStartMyAssessmentAttemptSessionResponsePracticeVerdictMock()},null,]), failure_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['sandbox_busy','sandbox_error'] as const),null,])}))},...{kind: faker.helpers.arrayElement(['root'] as const), mode: faker.helpers.arrayElement(['demo_basic','adaptive'] as const), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), target_grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), root_attempt_id: null, chain_deadline: null},}, kind: faker.helpers.arrayElement(['root'] as const)}, ...overrideResponse});
export const getStartMyAssessmentAttemptSessionResponseAssessmentQualifiedAttemptMock = (overrideResponse: Partial<AssessmentQualifiedAttempt> = {}): AssessmentQualifiedAttempt => ({...{...{...{id: faker.string.uuid(), version: faker.number.int({min: 1}), specialization: faker.helpers.arrayElement([faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const),null,]), target_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(['python','go'] as const),null,]), kind: faker.helpers.arrayElement(['root','corrective','demo_express'] as const), root_attempt_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), chain_deadline: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), mode: faker.helpers.arrayElement(['demo_basic','demo_express','adaptive'] as const), state: faker.helpers.arrayElement(['in_progress','practice_pending','additional_practice_pending','ready_to_finalize','completed','expired','insufficient_bank'] as const), versions: {policy_version: faker.number.int({min: 1}), bank_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), algorithm_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64})}, started_at: faker.date.past().toISOString().slice(0, 19) + 'Z', expires_at: faker.date.past().toISOString().slice(0, 19) + 'Z', sessions: faker.helpers.arrayElement([{...getStartMyAssessmentAttemptSessionResponseAssessmentSessionsMock()},null,]), finished_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), progress: {answered_items: faker.number.int({min: 0, max: 100}), max_items: faker.number.int({min: 1, max: 100})}, current_item: faker.helpers.arrayElement([{...getStartMyAssessmentAttemptSessionResponseAssessmentItemMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(['main','additional'] as const), item_id: faker.string.uuid(), status: faker.helpers.arrayElement(['not_started','pending','finished','failed'] as const), submitted_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), verdict: faker.helpers.arrayElement([{...getStartMyAssessmentAttemptSessionResponsePracticeVerdictMock()},null,]), failure_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['sandbox_busy','sandbox_error'] as const),null,])})), ...(faker.datatype.boolean() ? {watermark: {code: fakeFromPattern("^[0-9A-HJKMNP-TV-Z]{5}-?[0-9A-HJKMNP-TV-Z]{5}$", {minLength: 10, maxLength: 11})}} : {})},...{kind: faker.helpers.arrayElement(['root'] as const), mode: faker.helpers.arrayElement(['demo_basic','adaptive'] as const), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), target_grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), root_attempt_id: null, chain_deadline: null},}, kind: faker.helpers.arrayElement(['root'] as const)}, ...overrideResponse});
export const getStartMyAssessmentAttemptSessionResponseAssessmentCorrectiveAttemptMock = (overrideResponse: Partial<AssessmentCorrectiveAttempt> = {}): AssessmentCorrectiveAttempt => ({...{...{...{id: faker.string.uuid(), version: faker.number.int({min: 1}), specialization: faker.helpers.arrayElement([faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const),null,]), target_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(['python','go'] as const),null,]), kind: faker.helpers.arrayElement(['root','corrective','demo_express'] as const), root_attempt_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), chain_deadline: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), mode: faker.helpers.arrayElement(['demo_basic','demo_express','adaptive'] as const), state: faker.helpers.arrayElement(['in_progress','practice_pending','additional_practice_pending','ready_to_finalize','completed','expired','insufficient_bank'] as const), versions: {policy_version: faker.number.int({min: 1}), bank_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), algorithm_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64})}, started_at: faker.date.past().toISOString().slice(0, 19) + 'Z', expires_at: faker.date.past().toISOString().slice(0, 19) + 'Z', sessions: faker.helpers.arrayElement([{...getStartMyAssessmentAttemptSessionResponseAssessmentSessionsMock()},null,]), finished_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), progress: {answered_items: faker.number.int({min: 0, max: 100}), max_items: faker.number.int({min: 1, max: 100})}, current_item: faker.helpers.arrayElement([{...getStartMyAssessmentAttemptSessionResponseAssessmentItemMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(['main','additional'] as const), item_id: faker.string.uuid(), status: faker.helpers.arrayElement(['not_started','pending','finished','failed'] as const), submitted_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), verdict: faker.helpers.arrayElement([{...getStartMyAssessmentAttemptSessionResponsePracticeVerdictMock()},null,]), failure_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['sandbox_busy','sandbox_error'] as const),null,])}))},...{kind: faker.helpers.arrayElement(['corrective'] as const), mode: faker.helpers.arrayElement(['demo_basic','adaptive'] as const), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), target_grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), root_attempt_id: faker.string.uuid(), chain_deadline: faker.date.past().toISOString().slice(0, 19) + 'Z'},}, kind: faker.helpers.arrayElement(['corrective'] as const)}, ...overrideResponse});
export const getStartMyAssessmentAttemptSessionResponseAssessmentCorrectiveAttemptMock = (overrideResponse: Partial<AssessmentCorrectiveAttempt> = {}): AssessmentCorrectiveAttempt => ({...{...{...{id: faker.string.uuid(), version: faker.number.int({min: 1}), specialization: faker.helpers.arrayElement([faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const),null,]), target_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(['python','go'] as const),null,]), kind: faker.helpers.arrayElement(['root','corrective','demo_express'] as const), root_attempt_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), chain_deadline: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), mode: faker.helpers.arrayElement(['demo_basic','demo_express','adaptive'] as const), state: faker.helpers.arrayElement(['in_progress','practice_pending','additional_practice_pending','ready_to_finalize','completed','expired','insufficient_bank'] as const), versions: {policy_version: faker.number.int({min: 1}), bank_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), algorithm_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64})}, started_at: faker.date.past().toISOString().slice(0, 19) + 'Z', expires_at: faker.date.past().toISOString().slice(0, 19) + 'Z', sessions: faker.helpers.arrayElement([{...getStartMyAssessmentAttemptSessionResponseAssessmentSessionsMock()},null,]), finished_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), progress: {answered_items: faker.number.int({min: 0, max: 100}), max_items: faker.number.int({min: 1, max: 100})}, current_item: faker.helpers.arrayElement([{...getStartMyAssessmentAttemptSessionResponseAssessmentItemMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(['main','additional'] as const), item_id: faker.string.uuid(), status: faker.helpers.arrayElement(['not_started','pending','finished','failed'] as const), submitted_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), verdict: faker.helpers.arrayElement([{...getStartMyAssessmentAttemptSessionResponsePracticeVerdictMock()},null,]), failure_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['sandbox_busy','sandbox_error'] as const),null,])})), ...(faker.datatype.boolean() ? {watermark: {code: fakeFromPattern("^[0-9A-HJKMNP-TV-Z]{5}-?[0-9A-HJKMNP-TV-Z]{5}$", {minLength: 10, maxLength: 11})}} : {})},...{kind: faker.helpers.arrayElement(['corrective'] as const), mode: faker.helpers.arrayElement(['demo_basic','adaptive'] as const), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), target_grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), root_attempt_id: faker.string.uuid(), chain_deadline: faker.date.past().toISOString().slice(0, 19) + 'Z'},}, kind: faker.helpers.arrayElement(['corrective'] as const)}, ...overrideResponse});
export const getStartMyAssessmentAttemptSessionResponseAssessmentExpressAttemptMock = (overrideResponse: Partial<AssessmentExpressAttempt> = {}): AssessmentExpressAttempt => ({...{...{...{id: faker.string.uuid(), version: faker.number.int({min: 1}), specialization: faker.helpers.arrayElement([faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const),null,]), target_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(['python','go'] as const),null,]), kind: faker.helpers.arrayElement(['root','corrective','demo_express'] as const), root_attempt_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), chain_deadline: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), mode: faker.helpers.arrayElement(['demo_basic','demo_express','adaptive'] as const), state: faker.helpers.arrayElement(['in_progress','practice_pending','additional_practice_pending','ready_to_finalize','completed','expired','insufficient_bank'] as const), versions: {policy_version: faker.number.int({min: 1}), bank_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), algorithm_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64})}, started_at: faker.date.past().toISOString().slice(0, 19) + 'Z', expires_at: faker.date.past().toISOString().slice(0, 19) + 'Z', sessions: faker.helpers.arrayElement([{...getStartMyAssessmentAttemptSessionResponseAssessmentSessionsMock()},null,]), finished_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), progress: {answered_items: faker.number.int({min: 0, max: 100}), max_items: faker.number.int({min: 1, max: 100})}, current_item: faker.helpers.arrayElement([{...getStartMyAssessmentAttemptSessionResponseAssessmentItemMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(['main','additional'] as const), item_id: faker.string.uuid(), status: faker.helpers.arrayElement(['not_started','pending','finished','failed'] as const), submitted_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), verdict: faker.helpers.arrayElement([{...getStartMyAssessmentAttemptSessionResponsePracticeVerdictMock()},null,]), failure_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['sandbox_busy','sandbox_error'] as const),null,])}))},...{kind: faker.helpers.arrayElement(['demo_express'] as const), mode: faker.helpers.arrayElement(['demo_express'] as const), specialization: null, target_grade: null, task_language: null, root_attempt_id: null, chain_deadline: null},}, kind: faker.helpers.arrayElement(['demo_express'] as const)}, ...overrideResponse});
export const getStartMyAssessmentAttemptSessionResponseAssessmentExpressAttemptMock = (overrideResponse: Partial<AssessmentExpressAttempt> = {}): AssessmentExpressAttempt => ({...{...{...{id: faker.string.uuid(), version: faker.number.int({min: 1}), specialization: faker.helpers.arrayElement([faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const),null,]), target_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(['python','go'] as const),null,]), kind: faker.helpers.arrayElement(['root','corrective','demo_express'] as const), root_attempt_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), chain_deadline: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), mode: faker.helpers.arrayElement(['demo_basic','demo_express','adaptive'] as const), state: faker.helpers.arrayElement(['in_progress','practice_pending','additional_practice_pending','ready_to_finalize','completed','expired','insufficient_bank'] as const), versions: {policy_version: faker.number.int({min: 1}), bank_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), algorithm_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64})}, started_at: faker.date.past().toISOString().slice(0, 19) + 'Z', expires_at: faker.date.past().toISOString().slice(0, 19) + 'Z', sessions: faker.helpers.arrayElement([{...getStartMyAssessmentAttemptSessionResponseAssessmentSessionsMock()},null,]), finished_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), progress: {answered_items: faker.number.int({min: 0, max: 100}), max_items: faker.number.int({min: 1, max: 100})}, current_item: faker.helpers.arrayElement([{...getStartMyAssessmentAttemptSessionResponseAssessmentItemMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(['main','additional'] as const), item_id: faker.string.uuid(), status: faker.helpers.arrayElement(['not_started','pending','finished','failed'] as const), submitted_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), verdict: faker.helpers.arrayElement([{...getStartMyAssessmentAttemptSessionResponsePracticeVerdictMock()},null,]), failure_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['sandbox_busy','sandbox_error'] as const),null,])})), ...(faker.datatype.boolean() ? {watermark: {code: fakeFromPattern("^[0-9A-HJKMNP-TV-Z]{5}-?[0-9A-HJKMNP-TV-Z]{5}$", {minLength: 10, maxLength: 11})}} : {})},...{kind: faker.helpers.arrayElement(['demo_express'] as const), mode: faker.helpers.arrayElement(['demo_express'] as const), specialization: null, target_grade: null, task_language: null, root_attempt_id: null, chain_deadline: null},}, kind: faker.helpers.arrayElement(['demo_express'] as const)}, ...overrideResponse});
export const getStartMyAssessmentAttemptSessionResponseMock = (): AssessmentAttempt => (faker.helpers.arrayElement([{...getStartMyAssessmentAttemptSessionResponseAssessmentQualifiedAttemptMock()},{...getStartMyAssessmentAttemptSessionResponseAssessmentCorrectiveAttemptMock()},{...getStartMyAssessmentAttemptSessionResponseAssessmentExpressAttemptMock()},]))
@@ -170,11 +170,11 @@ export const getSubmitMyAssessmentAnswerResponseAssessmentItemMock = (overrideRe
export const getSubmitMyAssessmentAnswerResponsePracticeVerdictMock = (overrideResponse: Partial<PracticeVerdict> = {}): PracticeVerdict => ({...{score: faker.number.int({min: 0, max: 3}), max_score: faker.number.int({min: 3, max: 3}), groups: Array.from({ length: faker.number.int({min: 3, max: 3}) }, (_, i) => i + 1).map(() => ({group: faker.number.int({min: 1, max: 3}), passed: faker.datatype.boolean()}))}, ...overrideResponse});
export const getSubmitMyAssessmentAnswerResponseAssessmentQualifiedAttemptMock = (overrideResponse: Partial<AssessmentQualifiedAttempt> = {}): AssessmentQualifiedAttempt => ({...{...{...{id: faker.string.uuid(), version: faker.number.int({min: 1}), specialization: faker.helpers.arrayElement([faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const),null,]), target_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(['python','go'] as const),null,]), kind: faker.helpers.arrayElement(['root','corrective','demo_express'] as const), root_attempt_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), chain_deadline: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), mode: faker.helpers.arrayElement(['demo_basic','demo_express','adaptive'] as const), state: faker.helpers.arrayElement(['in_progress','practice_pending','additional_practice_pending','ready_to_finalize','completed','expired','insufficient_bank'] as const), versions: {policy_version: faker.number.int({min: 1}), bank_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), algorithm_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64})}, started_at: faker.date.past().toISOString().slice(0, 19) + 'Z', expires_at: faker.date.past().toISOString().slice(0, 19) + 'Z', sessions: faker.helpers.arrayElement([{...getSubmitMyAssessmentAnswerResponseAssessmentSessionsMock()},null,]), finished_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), progress: {answered_items: faker.number.int({min: 0, max: 100}), max_items: faker.number.int({min: 1, max: 100})}, current_item: faker.helpers.arrayElement([{...getSubmitMyAssessmentAnswerResponseAssessmentItemMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(['main','additional'] as const), item_id: faker.string.uuid(), status: faker.helpers.arrayElement(['not_started','pending','finished','failed'] as const), submitted_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), verdict: faker.helpers.arrayElement([{...getSubmitMyAssessmentAnswerResponsePracticeVerdictMock()},null,]), failure_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['sandbox_busy','sandbox_error'] as const),null,])}))},...{kind: faker.helpers.arrayElement(['root'] as const), mode: faker.helpers.arrayElement(['demo_basic','adaptive'] as const), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), target_grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), root_attempt_id: null, chain_deadline: null},}, kind: faker.helpers.arrayElement(['root'] as const)}, ...overrideResponse});
export const getSubmitMyAssessmentAnswerResponseAssessmentQualifiedAttemptMock = (overrideResponse: Partial<AssessmentQualifiedAttempt> = {}): AssessmentQualifiedAttempt => ({...{...{...{id: faker.string.uuid(), version: faker.number.int({min: 1}), specialization: faker.helpers.arrayElement([faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const),null,]), target_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(['python','go'] as const),null,]), kind: faker.helpers.arrayElement(['root','corrective','demo_express'] as const), root_attempt_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), chain_deadline: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), mode: faker.helpers.arrayElement(['demo_basic','demo_express','adaptive'] as const), state: faker.helpers.arrayElement(['in_progress','practice_pending','additional_practice_pending','ready_to_finalize','completed','expired','insufficient_bank'] as const), versions: {policy_version: faker.number.int({min: 1}), bank_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), algorithm_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64})}, started_at: faker.date.past().toISOString().slice(0, 19) + 'Z', expires_at: faker.date.past().toISOString().slice(0, 19) + 'Z', sessions: faker.helpers.arrayElement([{...getSubmitMyAssessmentAnswerResponseAssessmentSessionsMock()},null,]), finished_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), progress: {answered_items: faker.number.int({min: 0, max: 100}), max_items: faker.number.int({min: 1, max: 100})}, current_item: faker.helpers.arrayElement([{...getSubmitMyAssessmentAnswerResponseAssessmentItemMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(['main','additional'] as const), item_id: faker.string.uuid(), status: faker.helpers.arrayElement(['not_started','pending','finished','failed'] as const), submitted_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), verdict: faker.helpers.arrayElement([{...getSubmitMyAssessmentAnswerResponsePracticeVerdictMock()},null,]), failure_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['sandbox_busy','sandbox_error'] as const),null,])})), ...(faker.datatype.boolean() ? {watermark: {code: fakeFromPattern("^[0-9A-HJKMNP-TV-Z]{5}-?[0-9A-HJKMNP-TV-Z]{5}$", {minLength: 10, maxLength: 11})}} : {})},...{kind: faker.helpers.arrayElement(['root'] as const), mode: faker.helpers.arrayElement(['demo_basic','adaptive'] as const), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), target_grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), root_attempt_id: null, chain_deadline: null},}, kind: faker.helpers.arrayElement(['root'] as const)}, ...overrideResponse});
export const getSubmitMyAssessmentAnswerResponseAssessmentCorrectiveAttemptMock = (overrideResponse: Partial<AssessmentCorrectiveAttempt> = {}): AssessmentCorrectiveAttempt => ({...{...{...{id: faker.string.uuid(), version: faker.number.int({min: 1}), specialization: faker.helpers.arrayElement([faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const),null,]), target_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(['python','go'] as const),null,]), kind: faker.helpers.arrayElement(['root','corrective','demo_express'] as const), root_attempt_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), chain_deadline: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), mode: faker.helpers.arrayElement(['demo_basic','demo_express','adaptive'] as const), state: faker.helpers.arrayElement(['in_progress','practice_pending','additional_practice_pending','ready_to_finalize','completed','expired','insufficient_bank'] as const), versions: {policy_version: faker.number.int({min: 1}), bank_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), algorithm_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64})}, started_at: faker.date.past().toISOString().slice(0, 19) + 'Z', expires_at: faker.date.past().toISOString().slice(0, 19) + 'Z', sessions: faker.helpers.arrayElement([{...getSubmitMyAssessmentAnswerResponseAssessmentSessionsMock()},null,]), finished_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), progress: {answered_items: faker.number.int({min: 0, max: 100}), max_items: faker.number.int({min: 1, max: 100})}, current_item: faker.helpers.arrayElement([{...getSubmitMyAssessmentAnswerResponseAssessmentItemMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(['main','additional'] as const), item_id: faker.string.uuid(), status: faker.helpers.arrayElement(['not_started','pending','finished','failed'] as const), submitted_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), verdict: faker.helpers.arrayElement([{...getSubmitMyAssessmentAnswerResponsePracticeVerdictMock()},null,]), failure_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['sandbox_busy','sandbox_error'] as const),null,])}))},...{kind: faker.helpers.arrayElement(['corrective'] as const), mode: faker.helpers.arrayElement(['demo_basic','adaptive'] as const), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), target_grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), root_attempt_id: faker.string.uuid(), chain_deadline: faker.date.past().toISOString().slice(0, 19) + 'Z'},}, kind: faker.helpers.arrayElement(['corrective'] as const)}, ...overrideResponse});
export const getSubmitMyAssessmentAnswerResponseAssessmentCorrectiveAttemptMock = (overrideResponse: Partial<AssessmentCorrectiveAttempt> = {}): AssessmentCorrectiveAttempt => ({...{...{...{id: faker.string.uuid(), version: faker.number.int({min: 1}), specialization: faker.helpers.arrayElement([faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const),null,]), target_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(['python','go'] as const),null,]), kind: faker.helpers.arrayElement(['root','corrective','demo_express'] as const), root_attempt_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), chain_deadline: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), mode: faker.helpers.arrayElement(['demo_basic','demo_express','adaptive'] as const), state: faker.helpers.arrayElement(['in_progress','practice_pending','additional_practice_pending','ready_to_finalize','completed','expired','insufficient_bank'] as const), versions: {policy_version: faker.number.int({min: 1}), bank_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), algorithm_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64})}, started_at: faker.date.past().toISOString().slice(0, 19) + 'Z', expires_at: faker.date.past().toISOString().slice(0, 19) + 'Z', sessions: faker.helpers.arrayElement([{...getSubmitMyAssessmentAnswerResponseAssessmentSessionsMock()},null,]), finished_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), progress: {answered_items: faker.number.int({min: 0, max: 100}), max_items: faker.number.int({min: 1, max: 100})}, current_item: faker.helpers.arrayElement([{...getSubmitMyAssessmentAnswerResponseAssessmentItemMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(['main','additional'] as const), item_id: faker.string.uuid(), status: faker.helpers.arrayElement(['not_started','pending','finished','failed'] as const), submitted_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), verdict: faker.helpers.arrayElement([{...getSubmitMyAssessmentAnswerResponsePracticeVerdictMock()},null,]), failure_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['sandbox_busy','sandbox_error'] as const),null,])})), ...(faker.datatype.boolean() ? {watermark: {code: fakeFromPattern("^[0-9A-HJKMNP-TV-Z]{5}-?[0-9A-HJKMNP-TV-Z]{5}$", {minLength: 10, maxLength: 11})}} : {})},...{kind: faker.helpers.arrayElement(['corrective'] as const), mode: faker.helpers.arrayElement(['demo_basic','adaptive'] as const), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), target_grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), root_attempt_id: faker.string.uuid(), chain_deadline: faker.date.past().toISOString().slice(0, 19) + 'Z'},}, kind: faker.helpers.arrayElement(['corrective'] as const)}, ...overrideResponse});
export const getSubmitMyAssessmentAnswerResponseAssessmentExpressAttemptMock = (overrideResponse: Partial<AssessmentExpressAttempt> = {}): AssessmentExpressAttempt => ({...{...{...{id: faker.string.uuid(), version: faker.number.int({min: 1}), specialization: faker.helpers.arrayElement([faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const),null,]), target_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(['python','go'] as const),null,]), kind: faker.helpers.arrayElement(['root','corrective','demo_express'] as const), root_attempt_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), chain_deadline: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), mode: faker.helpers.arrayElement(['demo_basic','demo_express','adaptive'] as const), state: faker.helpers.arrayElement(['in_progress','practice_pending','additional_practice_pending','ready_to_finalize','completed','expired','insufficient_bank'] as const), versions: {policy_version: faker.number.int({min: 1}), bank_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), algorithm_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64})}, started_at: faker.date.past().toISOString().slice(0, 19) + 'Z', expires_at: faker.date.past().toISOString().slice(0, 19) + 'Z', sessions: faker.helpers.arrayElement([{...getSubmitMyAssessmentAnswerResponseAssessmentSessionsMock()},null,]), finished_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), progress: {answered_items: faker.number.int({min: 0, max: 100}), max_items: faker.number.int({min: 1, max: 100})}, current_item: faker.helpers.arrayElement([{...getSubmitMyAssessmentAnswerResponseAssessmentItemMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(['main','additional'] as const), item_id: faker.string.uuid(), status: faker.helpers.arrayElement(['not_started','pending','finished','failed'] as const), submitted_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), verdict: faker.helpers.arrayElement([{...getSubmitMyAssessmentAnswerResponsePracticeVerdictMock()},null,]), failure_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['sandbox_busy','sandbox_error'] as const),null,])}))},...{kind: faker.helpers.arrayElement(['demo_express'] as const), mode: faker.helpers.arrayElement(['demo_express'] as const), specialization: null, target_grade: null, task_language: null, root_attempt_id: null, chain_deadline: null},}, kind: faker.helpers.arrayElement(['demo_express'] as const)}, ...overrideResponse});
export const getSubmitMyAssessmentAnswerResponseAssessmentExpressAttemptMock = (overrideResponse: Partial<AssessmentExpressAttempt> = {}): AssessmentExpressAttempt => ({...{...{...{id: faker.string.uuid(), version: faker.number.int({min: 1}), specialization: faker.helpers.arrayElement([faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const),null,]), target_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(['python','go'] as const),null,]), kind: faker.helpers.arrayElement(['root','corrective','demo_express'] as const), root_attempt_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), chain_deadline: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), mode: faker.helpers.arrayElement(['demo_basic','demo_express','adaptive'] as const), state: faker.helpers.arrayElement(['in_progress','practice_pending','additional_practice_pending','ready_to_finalize','completed','expired','insufficient_bank'] as const), versions: {policy_version: faker.number.int({min: 1}), bank_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), algorithm_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64})}, started_at: faker.date.past().toISOString().slice(0, 19) + 'Z', expires_at: faker.date.past().toISOString().slice(0, 19) + 'Z', sessions: faker.helpers.arrayElement([{...getSubmitMyAssessmentAnswerResponseAssessmentSessionsMock()},null,]), finished_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), progress: {answered_items: faker.number.int({min: 0, max: 100}), max_items: faker.number.int({min: 1, max: 100})}, current_item: faker.helpers.arrayElement([{...getSubmitMyAssessmentAnswerResponseAssessmentItemMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(['main','additional'] as const), item_id: faker.string.uuid(), status: faker.helpers.arrayElement(['not_started','pending','finished','failed'] as const), submitted_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), verdict: faker.helpers.arrayElement([{...getSubmitMyAssessmentAnswerResponsePracticeVerdictMock()},null,]), failure_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['sandbox_busy','sandbox_error'] as const),null,])})), ...(faker.datatype.boolean() ? {watermark: {code: fakeFromPattern("^[0-9A-HJKMNP-TV-Z]{5}-?[0-9A-HJKMNP-TV-Z]{5}$", {minLength: 10, maxLength: 11})}} : {})},...{kind: faker.helpers.arrayElement(['demo_express'] as const), mode: faker.helpers.arrayElement(['demo_express'] as const), specialization: null, target_grade: null, task_language: null, root_attempt_id: null, chain_deadline: null},}, kind: faker.helpers.arrayElement(['demo_express'] as const)}, ...overrideResponse});
export const getSubmitMyAssessmentAnswerResponseMock = (): AssessmentAttempt => (faker.helpers.arrayElement([{...getSubmitMyAssessmentAnswerResponseAssessmentQualifiedAttemptMock()},{...getSubmitMyAssessmentAnswerResponseAssessmentCorrectiveAttemptMock()},{...getSubmitMyAssessmentAnswerResponseAssessmentExpressAttemptMock()},]))
@@ -198,11 +198,11 @@ export const getFinalizeMyAssessmentAttemptResponseAssessmentItemMock = (overrid
export const getFinalizeMyAssessmentAttemptResponsePracticeVerdictMock = (overrideResponse: Partial<PracticeVerdict> = {}): PracticeVerdict => ({...{score: faker.number.int({min: 0, max: 3}), max_score: faker.number.int({min: 3, max: 3}), groups: Array.from({ length: faker.number.int({min: 3, max: 3}) }, (_, i) => i + 1).map(() => ({group: faker.number.int({min: 1, max: 3}), passed: faker.datatype.boolean()}))}, ...overrideResponse});
export const getFinalizeMyAssessmentAttemptResponseAssessmentQualifiedAttemptMock = (overrideResponse: Partial<AssessmentQualifiedAttempt> = {}): AssessmentQualifiedAttempt => ({...{...{...{id: faker.string.uuid(), version: faker.number.int({min: 1}), specialization: faker.helpers.arrayElement([faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const),null,]), target_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(['python','go'] as const),null,]), kind: faker.helpers.arrayElement(['root','corrective','demo_express'] as const), root_attempt_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), chain_deadline: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), mode: faker.helpers.arrayElement(['demo_basic','demo_express','adaptive'] as const), state: faker.helpers.arrayElement(['in_progress','practice_pending','additional_practice_pending','ready_to_finalize','completed','expired','insufficient_bank'] as const), versions: {policy_version: faker.number.int({min: 1}), bank_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), algorithm_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64})}, started_at: faker.date.past().toISOString().slice(0, 19) + 'Z', expires_at: faker.date.past().toISOString().slice(0, 19) + 'Z', sessions: faker.helpers.arrayElement([{...getFinalizeMyAssessmentAttemptResponseAssessmentSessionsMock()},null,]), finished_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), progress: {answered_items: faker.number.int({min: 0, max: 100}), max_items: faker.number.int({min: 1, max: 100})}, current_item: faker.helpers.arrayElement([{...getFinalizeMyAssessmentAttemptResponseAssessmentItemMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(['main','additional'] as const), item_id: faker.string.uuid(), status: faker.helpers.arrayElement(['not_started','pending','finished','failed'] as const), submitted_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), verdict: faker.helpers.arrayElement([{...getFinalizeMyAssessmentAttemptResponsePracticeVerdictMock()},null,]), failure_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['sandbox_busy','sandbox_error'] as const),null,])}))},...{kind: faker.helpers.arrayElement(['root'] as const), mode: faker.helpers.arrayElement(['demo_basic','adaptive'] as const), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), target_grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), root_attempt_id: null, chain_deadline: null},}, kind: faker.helpers.arrayElement(['root'] as const)}, ...overrideResponse});
export const getFinalizeMyAssessmentAttemptResponseAssessmentQualifiedAttemptMock = (overrideResponse: Partial<AssessmentQualifiedAttempt> = {}): AssessmentQualifiedAttempt => ({...{...{...{id: faker.string.uuid(), version: faker.number.int({min: 1}), specialization: faker.helpers.arrayElement([faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const),null,]), target_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(['python','go'] as const),null,]), kind: faker.helpers.arrayElement(['root','corrective','demo_express'] as const), root_attempt_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), chain_deadline: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), mode: faker.helpers.arrayElement(['demo_basic','demo_express','adaptive'] as const), state: faker.helpers.arrayElement(['in_progress','practice_pending','additional_practice_pending','ready_to_finalize','completed','expired','insufficient_bank'] as const), versions: {policy_version: faker.number.int({min: 1}), bank_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), algorithm_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64})}, started_at: faker.date.past().toISOString().slice(0, 19) + 'Z', expires_at: faker.date.past().toISOString().slice(0, 19) + 'Z', sessions: faker.helpers.arrayElement([{...getFinalizeMyAssessmentAttemptResponseAssessmentSessionsMock()},null,]), finished_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), progress: {answered_items: faker.number.int({min: 0, max: 100}), max_items: faker.number.int({min: 1, max: 100})}, current_item: faker.helpers.arrayElement([{...getFinalizeMyAssessmentAttemptResponseAssessmentItemMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(['main','additional'] as const), item_id: faker.string.uuid(), status: faker.helpers.arrayElement(['not_started','pending','finished','failed'] as const), submitted_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), verdict: faker.helpers.arrayElement([{...getFinalizeMyAssessmentAttemptResponsePracticeVerdictMock()},null,]), failure_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['sandbox_busy','sandbox_error'] as const),null,])})), ...(faker.datatype.boolean() ? {watermark: {code: fakeFromPattern("^[0-9A-HJKMNP-TV-Z]{5}-?[0-9A-HJKMNP-TV-Z]{5}$", {minLength: 10, maxLength: 11})}} : {})},...{kind: faker.helpers.arrayElement(['root'] as const), mode: faker.helpers.arrayElement(['demo_basic','adaptive'] as const), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), target_grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), root_attempt_id: null, chain_deadline: null},}, kind: faker.helpers.arrayElement(['root'] as const)}, ...overrideResponse});
export const getFinalizeMyAssessmentAttemptResponseAssessmentCorrectiveAttemptMock = (overrideResponse: Partial<AssessmentCorrectiveAttempt> = {}): AssessmentCorrectiveAttempt => ({...{...{...{id: faker.string.uuid(), version: faker.number.int({min: 1}), specialization: faker.helpers.arrayElement([faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const),null,]), target_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(['python','go'] as const),null,]), kind: faker.helpers.arrayElement(['root','corrective','demo_express'] as const), root_attempt_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), chain_deadline: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), mode: faker.helpers.arrayElement(['demo_basic','demo_express','adaptive'] as const), state: faker.helpers.arrayElement(['in_progress','practice_pending','additional_practice_pending','ready_to_finalize','completed','expired','insufficient_bank'] as const), versions: {policy_version: faker.number.int({min: 1}), bank_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), algorithm_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64})}, started_at: faker.date.past().toISOString().slice(0, 19) + 'Z', expires_at: faker.date.past().toISOString().slice(0, 19) + 'Z', sessions: faker.helpers.arrayElement([{...getFinalizeMyAssessmentAttemptResponseAssessmentSessionsMock()},null,]), finished_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), progress: {answered_items: faker.number.int({min: 0, max: 100}), max_items: faker.number.int({min: 1, max: 100})}, current_item: faker.helpers.arrayElement([{...getFinalizeMyAssessmentAttemptResponseAssessmentItemMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(['main','additional'] as const), item_id: faker.string.uuid(), status: faker.helpers.arrayElement(['not_started','pending','finished','failed'] as const), submitted_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), verdict: faker.helpers.arrayElement([{...getFinalizeMyAssessmentAttemptResponsePracticeVerdictMock()},null,]), failure_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['sandbox_busy','sandbox_error'] as const),null,])}))},...{kind: faker.helpers.arrayElement(['corrective'] as const), mode: faker.helpers.arrayElement(['demo_basic','adaptive'] as const), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), target_grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), root_attempt_id: faker.string.uuid(), chain_deadline: faker.date.past().toISOString().slice(0, 19) + 'Z'},}, kind: faker.helpers.arrayElement(['corrective'] as const)}, ...overrideResponse});
export const getFinalizeMyAssessmentAttemptResponseAssessmentCorrectiveAttemptMock = (overrideResponse: Partial<AssessmentCorrectiveAttempt> = {}): AssessmentCorrectiveAttempt => ({...{...{...{id: faker.string.uuid(), version: faker.number.int({min: 1}), specialization: faker.helpers.arrayElement([faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const),null,]), target_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(['python','go'] as const),null,]), kind: faker.helpers.arrayElement(['root','corrective','demo_express'] as const), root_attempt_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), chain_deadline: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), mode: faker.helpers.arrayElement(['demo_basic','demo_express','adaptive'] as const), state: faker.helpers.arrayElement(['in_progress','practice_pending','additional_practice_pending','ready_to_finalize','completed','expired','insufficient_bank'] as const), versions: {policy_version: faker.number.int({min: 1}), bank_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), algorithm_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64})}, started_at: faker.date.past().toISOString().slice(0, 19) + 'Z', expires_at: faker.date.past().toISOString().slice(0, 19) + 'Z', sessions: faker.helpers.arrayElement([{...getFinalizeMyAssessmentAttemptResponseAssessmentSessionsMock()},null,]), finished_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), progress: {answered_items: faker.number.int({min: 0, max: 100}), max_items: faker.number.int({min: 1, max: 100})}, current_item: faker.helpers.arrayElement([{...getFinalizeMyAssessmentAttemptResponseAssessmentItemMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(['main','additional'] as const), item_id: faker.string.uuid(), status: faker.helpers.arrayElement(['not_started','pending','finished','failed'] as const), submitted_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), verdict: faker.helpers.arrayElement([{...getFinalizeMyAssessmentAttemptResponsePracticeVerdictMock()},null,]), failure_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['sandbox_busy','sandbox_error'] as const),null,])})), ...(faker.datatype.boolean() ? {watermark: {code: fakeFromPattern("^[0-9A-HJKMNP-TV-Z]{5}-?[0-9A-HJKMNP-TV-Z]{5}$", {minLength: 10, maxLength: 11})}} : {})},...{kind: faker.helpers.arrayElement(['corrective'] as const), mode: faker.helpers.arrayElement(['demo_basic','adaptive'] as const), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), target_grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), root_attempt_id: faker.string.uuid(), chain_deadline: faker.date.past().toISOString().slice(0, 19) + 'Z'},}, kind: faker.helpers.arrayElement(['corrective'] as const)}, ...overrideResponse});
export const getFinalizeMyAssessmentAttemptResponseAssessmentExpressAttemptMock = (overrideResponse: Partial<AssessmentExpressAttempt> = {}): AssessmentExpressAttempt => ({...{...{...{id: faker.string.uuid(), version: faker.number.int({min: 1}), specialization: faker.helpers.arrayElement([faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const),null,]), target_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(['python','go'] as const),null,]), kind: faker.helpers.arrayElement(['root','corrective','demo_express'] as const), root_attempt_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), chain_deadline: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), mode: faker.helpers.arrayElement(['demo_basic','demo_express','adaptive'] as const), state: faker.helpers.arrayElement(['in_progress','practice_pending','additional_practice_pending','ready_to_finalize','completed','expired','insufficient_bank'] as const), versions: {policy_version: faker.number.int({min: 1}), bank_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), algorithm_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64})}, started_at: faker.date.past().toISOString().slice(0, 19) + 'Z', expires_at: faker.date.past().toISOString().slice(0, 19) + 'Z', sessions: faker.helpers.arrayElement([{...getFinalizeMyAssessmentAttemptResponseAssessmentSessionsMock()},null,]), finished_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), progress: {answered_items: faker.number.int({min: 0, max: 100}), max_items: faker.number.int({min: 1, max: 100})}, current_item: faker.helpers.arrayElement([{...getFinalizeMyAssessmentAttemptResponseAssessmentItemMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(['main','additional'] as const), item_id: faker.string.uuid(), status: faker.helpers.arrayElement(['not_started','pending','finished','failed'] as const), submitted_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), verdict: faker.helpers.arrayElement([{...getFinalizeMyAssessmentAttemptResponsePracticeVerdictMock()},null,]), failure_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['sandbox_busy','sandbox_error'] as const),null,])}))},...{kind: faker.helpers.arrayElement(['demo_express'] as const), mode: faker.helpers.arrayElement(['demo_express'] as const), specialization: null, target_grade: null, task_language: null, root_attempt_id: null, chain_deadline: null},}, kind: faker.helpers.arrayElement(['demo_express'] as const)}, ...overrideResponse});
export const getFinalizeMyAssessmentAttemptResponseAssessmentExpressAttemptMock = (overrideResponse: Partial<AssessmentExpressAttempt> = {}): AssessmentExpressAttempt => ({...{...{...{id: faker.string.uuid(), version: faker.number.int({min: 1}), specialization: faker.helpers.arrayElement([faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const),null,]), target_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(['python','go'] as const),null,]), kind: faker.helpers.arrayElement(['root','corrective','demo_express'] as const), root_attempt_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), chain_deadline: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), mode: faker.helpers.arrayElement(['demo_basic','demo_express','adaptive'] as const), state: faker.helpers.arrayElement(['in_progress','practice_pending','additional_practice_pending','ready_to_finalize','completed','expired','insufficient_bank'] as const), versions: {policy_version: faker.number.int({min: 1}), bank_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), algorithm_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64})}, started_at: faker.date.past().toISOString().slice(0, 19) + 'Z', expires_at: faker.date.past().toISOString().slice(0, 19) + 'Z', sessions: faker.helpers.arrayElement([{...getFinalizeMyAssessmentAttemptResponseAssessmentSessionsMock()},null,]), finished_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), progress: {answered_items: faker.number.int({min: 0, max: 100}), max_items: faker.number.int({min: 1, max: 100})}, current_item: faker.helpers.arrayElement([{...getFinalizeMyAssessmentAttemptResponseAssessmentItemMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(['main','additional'] as const), item_id: faker.string.uuid(), status: faker.helpers.arrayElement(['not_started','pending','finished','failed'] as const), submitted_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), verdict: faker.helpers.arrayElement([{...getFinalizeMyAssessmentAttemptResponsePracticeVerdictMock()},null,]), failure_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['sandbox_busy','sandbox_error'] as const),null,])})), ...(faker.datatype.boolean() ? {watermark: {code: fakeFromPattern("^[0-9A-HJKMNP-TV-Z]{5}-?[0-9A-HJKMNP-TV-Z]{5}$", {minLength: 10, maxLength: 11})}} : {})},...{kind: faker.helpers.arrayElement(['demo_express'] as const), mode: faker.helpers.arrayElement(['demo_express'] as const), specialization: null, target_grade: null, task_language: null, root_attempt_id: null, chain_deadline: null},}, kind: faker.helpers.arrayElement(['demo_express'] as const)}, ...overrideResponse});
export const getFinalizeMyAssessmentAttemptResponseMock = (): AssessmentAttempt => (faker.helpers.arrayElement([{...getFinalizeMyAssessmentAttemptResponseAssessmentQualifiedAttemptMock()},{...getFinalizeMyAssessmentAttemptResponseAssessmentCorrectiveAttemptMock()},{...getFinalizeMyAssessmentAttemptResponseAssessmentExpressAttemptMock()},]))
@@ -97,6 +97,11 @@ export const assessmentAttemptOneOnePracticesItemVerdictOneGroupsMax = 3;
export const assessmentAttemptOneOnePracticesMax = 5;
export const assessmentAttemptOneOneWatermarkCodeMin = 10;
export const assessmentAttemptOneOneWatermarkCodeMax = 11;
export const assessmentAttemptOneOneWatermarkCodeRegExp = new RegExp('^[0-9A-HJKMNP-TV-Z]{5}-?[0-9A-HJKMNP-TV-Z]{5}$');
export const assessmentAttemptTwoOneVersionsBankVersionMax = 64;
@@ -188,6 +193,11 @@ export const assessmentAttemptTwoOnePracticesItemVerdictOneGroupsMax = 3;
export const assessmentAttemptTwoOnePracticesMax = 5;
export const assessmentAttemptTwoOneWatermarkCodeMin = 10;
export const assessmentAttemptTwoOneWatermarkCodeMax = 11;
export const assessmentAttemptTwoOneWatermarkCodeRegExp = new RegExp('^[0-9A-HJKMNP-TV-Z]{5}-?[0-9A-HJKMNP-TV-Z]{5}$');
export const assessmentAttemptThreeOneVersionsBankVersionMax = 64;
@@ -279,6 +289,11 @@ export const assessmentAttemptThreeOnePracticesItemVerdictOneGroupsMax = 3;
export const assessmentAttemptThreeOnePracticesMax = 5;
export const assessmentAttemptThreeOneWatermarkCodeMin = 10;
export const assessmentAttemptThreeOneWatermarkCodeMax = 11;
export const assessmentAttemptThreeOneWatermarkCodeRegExp = new RegExp('^[0-9A-HJKMNP-TV-Z]{5}-?[0-9A-HJKMNP-TV-Z]{5}$');
export const AssessmentAttempt = zod.union([zod.object({
"id": zod.uuid().describe('Attempt identifier.'),
@@ -368,7 +383,10 @@ export const AssessmentAttempt = zod.union([zod.object({
}).describe('Outcome of one hidden check group. It never contains the checks themselves.')).min(assessmentAttemptOneOnePracticesItemVerdictOneGroupsMin).max(assessmentAttemptOneOnePracticesItemVerdictOneGroupsMax)
}).describe('Verdict of a practice solution on the hidden checks: the score 0-3, one point for each passed group. The hidden checks, their inputs and outputs, error output, and seeds are never returned.'),zod.null()]).describe('The verdict when `status` is `finished`, otherwise null.'),
"failure_reason": zod.union([zod.enum(['sandbox_busy', 'sandbox_error']).describe('Why the sandbox infrastructure returned no verdict: `sandbox_busy` when its queue was full, `sandbox_error` for an infrastructure failure such as a broken executor. Neither depends on the solution; a solution that fails to compile, crashes, or exceeds a limit gets a `finished` verdict instead, so a failure never acts as an oracle for hidden checks.'),zod.null()]).describe('The reason when `status` is `failed`, otherwise null.')
}).describe('Practice of the attempt. Its verdict is shown only after the submission; the solution time is kept as a separate label and never enters the ability estimate or the grade decision.')).max(assessmentAttemptOneOnePracticesMax).describe('Practices in the order assigned by the mode policy. The list exposes verdicts only after submission.')
}).describe('Practice of the attempt. Its verdict is shown only after the submission; the solution time is kept as a separate label and never enters the ability estimate or the grade decision.')).max(assessmentAttemptOneOnePracticesMax).describe('Practices in the order assigned by the mode policy. The list exposes verdicts only after submission.'),
"watermark": zod.object({
"code": zod.string().min(assessmentAttemptOneOneWatermarkCodeMin).max(assessmentAttemptOneOneWatermarkCodeMax).regex(assessmentAttemptOneOneWatermarkCodeRegExp).describe('Two groups of five symbols of Crockford base32, such as `7K3QD-9XM2T`.')
}).exactOptional().describe('Visible mark of a real attempt. The client shows `code` with the current time as a faint tile over the task screen, so that a screenshot or a photo of the screen can be traced back to the attempt by an operator. The code is a keyed pseudonym derived on the server: it carries no name, contact, or identifier of the account, and it cannot be computed without the server secret. The task text of such an attempt also carries an invisible mark and interchangeable wordings chosen by the same secret; they change neither the meaning of a task nor its reference answer, and the client keeps the invisible characters out of the accessibility tree. Training runs (`demo_express`) carry no watermark. It is evidence for a manual review and an appeal, never an automatic decision.')
}).describe('Common state of an assessment attempt. Real assessments have a specialization and target grade; demo_express has neither. The attempt shows its fixed versions, server deadlines, session limit, progress, current item, and practices. It never contains answer keys, answer correctness, item scores, family or variant identifiers, seeds, hidden checks, or anti-cheat signals.').and(zod.object({
"kind": zod.enum(['root']),
"mode": zod.enum(['demo_basic', 'adaptive']),
@@ -466,7 +484,10 @@ export const AssessmentAttempt = zod.union([zod.object({
}).describe('Outcome of one hidden check group. It never contains the checks themselves.')).min(assessmentAttemptTwoOnePracticesItemVerdictOneGroupsMin).max(assessmentAttemptTwoOnePracticesItemVerdictOneGroupsMax)
}).describe('Verdict of a practice solution on the hidden checks: the score 0-3, one point for each passed group. The hidden checks, their inputs and outputs, error output, and seeds are never returned.'),zod.null()]).describe('The verdict when `status` is `finished`, otherwise null.'),
"failure_reason": zod.union([zod.enum(['sandbox_busy', 'sandbox_error']).describe('Why the sandbox infrastructure returned no verdict: `sandbox_busy` when its queue was full, `sandbox_error` for an infrastructure failure such as a broken executor. Neither depends on the solution; a solution that fails to compile, crashes, or exceeds a limit gets a `finished` verdict instead, so a failure never acts as an oracle for hidden checks.'),zod.null()]).describe('The reason when `status` is `failed`, otherwise null.')
}).describe('Practice of the attempt. Its verdict is shown only after the submission; the solution time is kept as a separate label and never enters the ability estimate or the grade decision.')).max(assessmentAttemptTwoOnePracticesMax).describe('Practices in the order assigned by the mode policy. The list exposes verdicts only after submission.')
}).describe('Practice of the attempt. Its verdict is shown only after the submission; the solution time is kept as a separate label and never enters the ability estimate or the grade decision.')).max(assessmentAttemptTwoOnePracticesMax).describe('Practices in the order assigned by the mode policy. The list exposes verdicts only after submission.'),
"watermark": zod.object({
"code": zod.string().min(assessmentAttemptTwoOneWatermarkCodeMin).max(assessmentAttemptTwoOneWatermarkCodeMax).regex(assessmentAttemptTwoOneWatermarkCodeRegExp).describe('Two groups of five symbols of Crockford base32, such as `7K3QD-9XM2T`.')
}).exactOptional().describe('Visible mark of a real attempt. The client shows `code` with the current time as a faint tile over the task screen, so that a screenshot or a photo of the screen can be traced back to the attempt by an operator. The code is a keyed pseudonym derived on the server: it carries no name, contact, or identifier of the account, and it cannot be computed without the server secret. The task text of such an attempt also carries an invisible mark and interchangeable wordings chosen by the same secret; they change neither the meaning of a task nor its reference answer, and the client keeps the invisible characters out of the accessibility tree. Training runs (`demo_express`) carry no watermark. It is evidence for a manual review and an appeal, never an automatic decision.')
}).describe('Common state of an assessment attempt. Real assessments have a specialization and target grade; demo_express has neither. The attempt shows its fixed versions, server deadlines, session limit, progress, current item, and practices. It never contains answer keys, answer correctness, item scores, family or variant identifiers, seeds, hidden checks, or anti-cheat signals.').and(zod.object({
"kind": zod.enum(['corrective']),
"mode": zod.enum(['demo_basic', 'adaptive']),
@@ -564,7 +585,10 @@ export const AssessmentAttempt = zod.union([zod.object({
}).describe('Outcome of one hidden check group. It never contains the checks themselves.')).min(assessmentAttemptThreeOnePracticesItemVerdictOneGroupsMin).max(assessmentAttemptThreeOnePracticesItemVerdictOneGroupsMax)
}).describe('Verdict of a practice solution on the hidden checks: the score 0-3, one point for each passed group. The hidden checks, their inputs and outputs, error output, and seeds are never returned.'),zod.null()]).describe('The verdict when `status` is `finished`, otherwise null.'),
"failure_reason": zod.union([zod.enum(['sandbox_busy', 'sandbox_error']).describe('Why the sandbox infrastructure returned no verdict: `sandbox_busy` when its queue was full, `sandbox_error` for an infrastructure failure such as a broken executor. Neither depends on the solution; a solution that fails to compile, crashes, or exceeds a limit gets a `finished` verdict instead, so a failure never acts as an oracle for hidden checks.'),zod.null()]).describe('The reason when `status` is `failed`, otherwise null.')
}).describe('Practice of the attempt. Its verdict is shown only after the submission; the solution time is kept as a separate label and never enters the ability estimate or the grade decision.')).max(assessmentAttemptThreeOnePracticesMax).describe('Practices in the order assigned by the mode policy. The list exposes verdicts only after submission.')
}).describe('Practice of the attempt. Its verdict is shown only after the submission; the solution time is kept as a separate label and never enters the ability estimate or the grade decision.')).max(assessmentAttemptThreeOnePracticesMax).describe('Practices in the order assigned by the mode policy. The list exposes verdicts only after submission.'),
"watermark": zod.object({
"code": zod.string().min(assessmentAttemptThreeOneWatermarkCodeMin).max(assessmentAttemptThreeOneWatermarkCodeMax).regex(assessmentAttemptThreeOneWatermarkCodeRegExp).describe('Two groups of five symbols of Crockford base32, such as `7K3QD-9XM2T`.')
}).exactOptional().describe('Visible mark of a real attempt. The client shows `code` with the current time as a faint tile over the task screen, so that a screenshot or a photo of the screen can be traced back to the attempt by an operator. The code is a keyed pseudonym derived on the server: it carries no name, contact, or identifier of the account, and it cannot be computed without the server secret. The task text of such an attempt also carries an invisible mark and interchangeable wordings chosen by the same secret; they change neither the meaning of a task nor its reference answer, and the client keeps the invisible characters out of the accessibility tree. Training runs (`demo_express`) carry no watermark. It is evidence for a manual review and an appeal, never an automatic decision.')
}).describe('Common state of an assessment attempt. Real assessments have a specialization and target grade; demo_express has neither. The attempt shows its fixed versions, server deadlines, session limit, progress, current item, and practices. It never contains answer keys, answer correctness, item scores, family or variant identifiers, seeds, hidden checks, or anti-cheat signals.').and(zod.object({
"kind": zod.enum(['demo_express']),
"mode": zod.enum(['demo_express']),
@@ -97,6 +97,11 @@ export const assessmentAttemptCommonPracticesItemVerdictOneGroupsMax = 3;
export const assessmentAttemptCommonPracticesMax = 5;
export const assessmentAttemptCommonWatermarkCodeMin = 10;
export const assessmentAttemptCommonWatermarkCodeMax = 11;
export const assessmentAttemptCommonWatermarkCodeRegExp = new RegExp('^[0-9A-HJKMNP-TV-Z]{5}-?[0-9A-HJKMNP-TV-Z]{5}$');
export const AssessmentAttemptCommon = zod.object({
"id": zod.uuid().describe('Attempt identifier.'),
@@ -186,7 +191,10 @@ export const AssessmentAttemptCommon = zod.object({
}).describe('Outcome of one hidden check group. It never contains the checks themselves.')).min(assessmentAttemptCommonPracticesItemVerdictOneGroupsMin).max(assessmentAttemptCommonPracticesItemVerdictOneGroupsMax)
}).describe('Verdict of a practice solution on the hidden checks: the score 0-3, one point for each passed group. The hidden checks, their inputs and outputs, error output, and seeds are never returned.'),zod.null()]).describe('The verdict when `status` is `finished`, otherwise null.'),
"failure_reason": zod.union([zod.enum(['sandbox_busy', 'sandbox_error']).describe('Why the sandbox infrastructure returned no verdict: `sandbox_busy` when its queue was full, `sandbox_error` for an infrastructure failure such as a broken executor. Neither depends on the solution; a solution that fails to compile, crashes, or exceeds a limit gets a `finished` verdict instead, so a failure never acts as an oracle for hidden checks.'),zod.null()]).describe('The reason when `status` is `failed`, otherwise null.')
}).describe('Practice of the attempt. Its verdict is shown only after the submission; the solution time is kept as a separate label and never enters the ability estimate or the grade decision.')).max(assessmentAttemptCommonPracticesMax).describe('Practices in the order assigned by the mode policy. The list exposes verdicts only after submission.')
}).describe('Practice of the attempt. Its verdict is shown only after the submission; the solution time is kept as a separate label and never enters the ability estimate or the grade decision.')).max(assessmentAttemptCommonPracticesMax).describe('Practices in the order assigned by the mode policy. The list exposes verdicts only after submission.'),
"watermark": zod.object({
"code": zod.string().min(assessmentAttemptCommonWatermarkCodeMin).max(assessmentAttemptCommonWatermarkCodeMax).regex(assessmentAttemptCommonWatermarkCodeRegExp).describe('Two groups of five symbols of Crockford base32, such as `7K3QD-9XM2T`.')
}).exactOptional().describe('Visible mark of a real attempt. The client shows `code` with the current time as a faint tile over the task screen, so that a screenshot or a photo of the screen can be traced back to the attempt by an operator. The code is a keyed pseudonym derived on the server: it carries no name, contact, or identifier of the account, and it cannot be computed without the server secret. The task text of such an attempt also carries an invisible mark and interchangeable wordings chosen by the same secret; they change neither the meaning of a task nor its reference answer, and the client keeps the invisible characters out of the accessibility tree. Training runs (`demo_express`) carry no watermark. It is evidence for a manual review and an appeal, never an automatic decision.')
}).describe('Common state of an assessment attempt. Real assessments have a specialization and target grade; demo_express has neither. The attempt shows its fixed versions, server deadlines, session limit, progress, current item, and practices. It never contains answer keys, answer correctness, item scores, family or variant identifiers, seeds, hidden checks, or anti-cheat signals.')
export type AssessmentAttemptCommon = zod.input<typeof AssessmentAttemptCommon>;
@@ -97,6 +97,11 @@ export const assessmentCorrectiveAttemptOnePracticesItemVerdictOneGroupsMax = 3;
export const assessmentCorrectiveAttemptOnePracticesMax = 5;
export const assessmentCorrectiveAttemptOneWatermarkCodeMin = 10;
export const assessmentCorrectiveAttemptOneWatermarkCodeMax = 11;
export const assessmentCorrectiveAttemptOneWatermarkCodeRegExp = new RegExp('^[0-9A-HJKMNP-TV-Z]{5}-?[0-9A-HJKMNP-TV-Z]{5}$');
export const AssessmentCorrectiveAttempt = zod.object({
"id": zod.uuid().describe('Attempt identifier.'),
@@ -186,7 +191,10 @@ export const AssessmentCorrectiveAttempt = zod.object({
}).describe('Outcome of one hidden check group. It never contains the checks themselves.')).min(assessmentCorrectiveAttemptOnePracticesItemVerdictOneGroupsMin).max(assessmentCorrectiveAttemptOnePracticesItemVerdictOneGroupsMax)
}).describe('Verdict of a practice solution on the hidden checks: the score 0-3, one point for each passed group. The hidden checks, their inputs and outputs, error output, and seeds are never returned.'),zod.null()]).describe('The verdict when `status` is `finished`, otherwise null.'),
"failure_reason": zod.union([zod.enum(['sandbox_busy', 'sandbox_error']).describe('Why the sandbox infrastructure returned no verdict: `sandbox_busy` when its queue was full, `sandbox_error` for an infrastructure failure such as a broken executor. Neither depends on the solution; a solution that fails to compile, crashes, or exceeds a limit gets a `finished` verdict instead, so a failure never acts as an oracle for hidden checks.'),zod.null()]).describe('The reason when `status` is `failed`, otherwise null.')
}).describe('Practice of the attempt. Its verdict is shown only after the submission; the solution time is kept as a separate label and never enters the ability estimate or the grade decision.')).max(assessmentCorrectiveAttemptOnePracticesMax).describe('Practices in the order assigned by the mode policy. The list exposes verdicts only after submission.')
}).describe('Practice of the attempt. Its verdict is shown only after the submission; the solution time is kept as a separate label and never enters the ability estimate or the grade decision.')).max(assessmentCorrectiveAttemptOnePracticesMax).describe('Practices in the order assigned by the mode policy. The list exposes verdicts only after submission.'),
"watermark": zod.object({
"code": zod.string().min(assessmentCorrectiveAttemptOneWatermarkCodeMin).max(assessmentCorrectiveAttemptOneWatermarkCodeMax).regex(assessmentCorrectiveAttemptOneWatermarkCodeRegExp).describe('Two groups of five symbols of Crockford base32, such as `7K3QD-9XM2T`.')
}).exactOptional().describe('Visible mark of a real attempt. The client shows `code` with the current time as a faint tile over the task screen, so that a screenshot or a photo of the screen can be traced back to the attempt by an operator. The code is a keyed pseudonym derived on the server: it carries no name, contact, or identifier of the account, and it cannot be computed without the server secret. The task text of such an attempt also carries an invisible mark and interchangeable wordings chosen by the same secret; they change neither the meaning of a task nor its reference answer, and the client keeps the invisible characters out of the accessibility tree. Training runs (`demo_express`) carry no watermark. It is evidence for a manual review and an appeal, never an automatic decision.')
}).describe('Common state of an assessment attempt. Real assessments have a specialization and target grade; demo_express has neither. The attempt shows its fixed versions, server deadlines, session limit, progress, current item, and practices. It never contains answer keys, answer correctness, item scores, family or variant identifiers, seeds, hidden checks, or anti-cheat signals.').and(zod.object({
"kind": zod.enum(['corrective']),
"mode": zod.enum(['demo_basic', 'adaptive']),
@@ -97,6 +97,11 @@ export const assessmentExpressAttemptOnePracticesItemVerdictOneGroupsMax = 3;
export const assessmentExpressAttemptOnePracticesMax = 5;
export const assessmentExpressAttemptOneWatermarkCodeMin = 10;
export const assessmentExpressAttemptOneWatermarkCodeMax = 11;
export const assessmentExpressAttemptOneWatermarkCodeRegExp = new RegExp('^[0-9A-HJKMNP-TV-Z]{5}-?[0-9A-HJKMNP-TV-Z]{5}$');
export const AssessmentExpressAttempt = zod.object({
"id": zod.uuid().describe('Attempt identifier.'),
@@ -186,7 +191,10 @@ export const AssessmentExpressAttempt = zod.object({
}).describe('Outcome of one hidden check group. It never contains the checks themselves.')).min(assessmentExpressAttemptOnePracticesItemVerdictOneGroupsMin).max(assessmentExpressAttemptOnePracticesItemVerdictOneGroupsMax)
}).describe('Verdict of a practice solution on the hidden checks: the score 0-3, one point for each passed group. The hidden checks, their inputs and outputs, error output, and seeds are never returned.'),zod.null()]).describe('The verdict when `status` is `finished`, otherwise null.'),
"failure_reason": zod.union([zod.enum(['sandbox_busy', 'sandbox_error']).describe('Why the sandbox infrastructure returned no verdict: `sandbox_busy` when its queue was full, `sandbox_error` for an infrastructure failure such as a broken executor. Neither depends on the solution; a solution that fails to compile, crashes, or exceeds a limit gets a `finished` verdict instead, so a failure never acts as an oracle for hidden checks.'),zod.null()]).describe('The reason when `status` is `failed`, otherwise null.')
}).describe('Practice of the attempt. Its verdict is shown only after the submission; the solution time is kept as a separate label and never enters the ability estimate or the grade decision.')).max(assessmentExpressAttemptOnePracticesMax).describe('Practices in the order assigned by the mode policy. The list exposes verdicts only after submission.')
}).describe('Practice of the attempt. Its verdict is shown only after the submission; the solution time is kept as a separate label and never enters the ability estimate or the grade decision.')).max(assessmentExpressAttemptOnePracticesMax).describe('Practices in the order assigned by the mode policy. The list exposes verdicts only after submission.'),
"watermark": zod.object({
"code": zod.string().min(assessmentExpressAttemptOneWatermarkCodeMin).max(assessmentExpressAttemptOneWatermarkCodeMax).regex(assessmentExpressAttemptOneWatermarkCodeRegExp).describe('Two groups of five symbols of Crockford base32, such as `7K3QD-9XM2T`.')
}).exactOptional().describe('Visible mark of a real attempt. The client shows `code` with the current time as a faint tile over the task screen, so that a screenshot or a photo of the screen can be traced back to the attempt by an operator. The code is a keyed pseudonym derived on the server: it carries no name, contact, or identifier of the account, and it cannot be computed without the server secret. The task text of such an attempt also carries an invisible mark and interchangeable wordings chosen by the same secret; they change neither the meaning of a task nor its reference answer, and the client keeps the invisible characters out of the accessibility tree. Training runs (`demo_express`) carry no watermark. It is evidence for a manual review and an appeal, never an automatic decision.')
}).describe('Common state of an assessment attempt. Real assessments have a specialization and target grade; demo_express has neither. The attempt shows its fixed versions, server deadlines, session limit, progress, current item, and practices. It never contains answer keys, answer correctness, item scores, family or variant identifiers, seeds, hidden checks, or anti-cheat signals.').and(zod.object({
"kind": zod.enum(['demo_express']),
"mode": zod.enum(['demo_express']),
@@ -97,6 +97,11 @@ export const assessmentQualifiedAttemptOnePracticesItemVerdictOneGroupsMax = 3;
export const assessmentQualifiedAttemptOnePracticesMax = 5;
export const assessmentQualifiedAttemptOneWatermarkCodeMin = 10;
export const assessmentQualifiedAttemptOneWatermarkCodeMax = 11;
export const assessmentQualifiedAttemptOneWatermarkCodeRegExp = new RegExp('^[0-9A-HJKMNP-TV-Z]{5}-?[0-9A-HJKMNP-TV-Z]{5}$');
export const AssessmentQualifiedAttempt = zod.object({
"id": zod.uuid().describe('Attempt identifier.'),
@@ -186,7 +191,10 @@ export const AssessmentQualifiedAttempt = zod.object({
}).describe('Outcome of one hidden check group. It never contains the checks themselves.')).min(assessmentQualifiedAttemptOnePracticesItemVerdictOneGroupsMin).max(assessmentQualifiedAttemptOnePracticesItemVerdictOneGroupsMax)
}).describe('Verdict of a practice solution on the hidden checks: the score 0-3, one point for each passed group. The hidden checks, their inputs and outputs, error output, and seeds are never returned.'),zod.null()]).describe('The verdict when `status` is `finished`, otherwise null.'),
"failure_reason": zod.union([zod.enum(['sandbox_busy', 'sandbox_error']).describe('Why the sandbox infrastructure returned no verdict: `sandbox_busy` when its queue was full, `sandbox_error` for an infrastructure failure such as a broken executor. Neither depends on the solution; a solution that fails to compile, crashes, or exceeds a limit gets a `finished` verdict instead, so a failure never acts as an oracle for hidden checks.'),zod.null()]).describe('The reason when `status` is `failed`, otherwise null.')
}).describe('Practice of the attempt. Its verdict is shown only after the submission; the solution time is kept as a separate label and never enters the ability estimate or the grade decision.')).max(assessmentQualifiedAttemptOnePracticesMax).describe('Practices in the order assigned by the mode policy. The list exposes verdicts only after submission.')
}).describe('Practice of the attempt. Its verdict is shown only after the submission; the solution time is kept as a separate label and never enters the ability estimate or the grade decision.')).max(assessmentQualifiedAttemptOnePracticesMax).describe('Practices in the order assigned by the mode policy. The list exposes verdicts only after submission.'),
"watermark": zod.object({
"code": zod.string().min(assessmentQualifiedAttemptOneWatermarkCodeMin).max(assessmentQualifiedAttemptOneWatermarkCodeMax).regex(assessmentQualifiedAttemptOneWatermarkCodeRegExp).describe('Two groups of five symbols of Crockford base32, such as `7K3QD-9XM2T`.')
}).exactOptional().describe('Visible mark of a real attempt. The client shows `code` with the current time as a faint tile over the task screen, so that a screenshot or a photo of the screen can be traced back to the attempt by an operator. The code is a keyed pseudonym derived on the server: it carries no name, contact, or identifier of the account, and it cannot be computed without the server secret. The task text of such an attempt also carries an invisible mark and interchangeable wordings chosen by the same secret; they change neither the meaning of a task nor its reference answer, and the client keeps the invisible characters out of the accessibility tree. Training runs (`demo_express`) carry no watermark. It is evidence for a manual review and an appeal, never an automatic decision.')
}).describe('Common state of an assessment attempt. Real assessments have a specialization and target grade; demo_express has neither. The attempt shows its fixed versions, server deadlines, session limit, progress, current item, and practices. It never contains answer keys, answer correctness, item scores, family or variant identifiers, seeds, hidden checks, or anti-cheat signals.').and(zod.object({
"kind": zod.enum(['root']),
"mode": zod.enum(['demo_basic', 'adaptive']),
@@ -0,0 +1,20 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const assessmentWatermarkCodeMin = 10;
export const assessmentWatermarkCodeMax = 11;
export const assessmentWatermarkCodeRegExp = new RegExp('^[0-9A-HJKMNP-TV-Z]{5}-?[0-9A-HJKMNP-TV-Z]{5}$');
export const AssessmentWatermark = zod.object({
"code": zod.string().min(assessmentWatermarkCodeMin).max(assessmentWatermarkCodeMax).regex(assessmentWatermarkCodeRegExp).describe('Two groups of five symbols of Crockford base32, such as `7K3QD-9XM2T`.')
}).describe('Visible mark of a real attempt. The client shows `code` with the current time as a faint tile over the task screen, so that a screenshot or a photo of the screen can be traced back to the attempt by an operator. The code is a keyed pseudonym derived on the server: it carries no name, contact, or identifier of the account, and it cannot be computed without the server secret. The task text of such an attempt also carries an invisible mark and interchangeable wordings chosen by the same secret; they change neither the meaning of a task nor its reference answer, and the client keeps the invisible characters out of the accessibility tree. Training runs (`demo_express`) carry no watermark. It is evidence for a manual review and an appeal, never an automatic decision.')
export type AssessmentWatermark = zod.input<typeof AssessmentWatermark>;
export type AssessmentWatermarkOutput = zod.output<typeof AssessmentWatermark>;
@@ -66,6 +66,7 @@ export * from './assessmentStrength.zod';
export * from './assessmentUncertainty.zod';
export * from './assessmentVersionLabel.zod';
export * from './assessmentVersions.zod';
export * from './assessmentWatermark.zod';
export * from './basicScore.zod';
export * from './calibrationStatus.zod';
export * from './choiceAnswer.zod';