diff --git a/api/Makefile b/api/Makefile index 8f2be02..6bfbadd 100644 --- a/api/Makefile +++ b/api/Makefile @@ -31,6 +31,7 @@ lint: bundle ## Lint both bundled contracts check: lint ## Build and lint both contract bundles PYTHONDONTWRITEBYTECODE=1 "$(CODEGEN_PYTHON)" -m unittest discover -s "$(ROOT_DIR)/scripts" -p 'test_merge_schemas.py' PYTHONDONTWRITEBYTECODE=1 "$(CODEGEN_PYTHON)" -m unittest discover -s "$(ROOT_DIR)/scripts" -p 'test_contract_copies.py' + PYTHONDONTWRITEBYTECODE=1 "$(CODEGEN_PYTHON)" -m unittest discover -s "$(ROOT_DIR)/scripts" -p 'test_assessment_contract.py' .PHONY: check-compat check-compat: bundle ## Compare the public contract with API_BASE_REF diff --git a/api/README.en.md b/api/README.en.md index 9d9c3c0..9ea93f9 100644 --- a/api/README.en.md +++ b/api/README.en.md @@ -245,6 +245,7 @@ The `assessment` tag covers the assessment attempts of the current candidate (PR | `GET /api/v1/me/assessment-availability` | `GetMyAssessmentAvailability` | session | 200 `AssessmentAvailability`, `Cache-Control: no-store` | 401 `unauthenticated`, 403 `forbidden` | | `POST /api/v1/me/assessment-attempts` | `CreateMyAssessmentAttempt` | session and CSRF, Idempotency-Key | 201 `AssessmentAttempt`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `csrf_check_failed` or `forbidden`, 409 `state_conflict` or `idempotency_in_progress`, 422 `idempotency_key_reused`, 429 | | `GET /api/v1/me/assessment-attempts/{attempt_id}` | `GetMyAssessmentAttempt` | session | 200 `AssessmentAttempt`, `Cache-Control: no-store` | 401, 403 `forbidden`, 404 `not_found` | +| `POST /api/v1/me/assessment-attempts/{attempt_id}/sessions` | `StartMyAssessmentAttemptSession` | session and CSRF, Idempotency-Key | 200 `AssessmentAttempt`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict` or `idempotency_in_progress`, 412 `version_conflict`, 422, 429 | | `POST /api/v1/me/assessment-attempts/{attempt_id}/answers` | `SubmitMyAssessmentAnswer` | session and CSRF, Idempotency-Key | 200 `AssessmentAttempt`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict` or `idempotency_in_progress`, 412 `version_conflict`, 422, 429 | | `POST /api/v1/me/assessment-attempts/{attempt_id}/finalize` | `FinalizeMyAssessmentAttempt` | session and CSRF, Idempotency-Key | 200 `AssessmentAttempt`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict` or `idempotency_in_progress`, 412 `version_conflict`, 422 | | `GET /api/v1/me/assessment-attempts/{attempt_id}/result` | `GetMyAssessmentResult` | session | 200 `AssessmentResult`, `Cache-Control: no-store` | 401, 403 `forbidden`, 404 `not_found`, 409 `state_conflict` | @@ -254,13 +255,14 @@ Every operation also declares the `default` problem response. Access: - The candidate comes only from the session; no operation takes a candidate identifier. An employer account answers 403 `forbidden`. An attempt of another candidate answers 404 `not_found`, the same as an unknown identifier, so attempt identifiers cannot be probed. -- No operation offers an employer the answers, the attempt history, or anti-cheat signals. Employers will see only the current category through a separate projection. +- No operation offers an employer answers, qualification evidence, attempt history, or anti-cheat signals. Employers will see only the current category through a separate projection. Modes and versions: -- `mode` is `demo_basic` or `adaptive`. The server picks it from the published bank of the category; the client never sends it. `demo_basic` scores a fixed form of reviewed demo items by their keys against the pass mark of the versioned basic grading policy, computes no ability estimate, and decides in one step: it never offers an additional practice. `adaptive` is the adaptive test of FR04. +- `kind` is required on creation: `root`, `corrective`, or `demo_express`. A real attempt uses `demo_basic` or `adaptive`; the server picks the mode from the published bank and the client never sends it. `demo_basic` scores a fixed form of reviewed demo items by their keys against the pass mark of the versioned basic grading policy, computes no ability estimate, and decides in one step: it never offers an additional practice. `adaptive` is the adaptive test of FR04. A candidate may explicitly request `demo_express`, a separate interactive 3 to 5 minute training run with no category, target grade, percentile, real-assessment quota, or qualification evidence. +- A corrective real attempt includes `root_attempt_id`. The server allows only a strictly lower target grade not already tried in that chain. Creating the root reserves one slot in the three-root-attempts-per-180-days quota; corrections share that slot and the root's immutable `chain_deadline` (72 hours from the root start under the current policy), while keeping their own item, practice, and session limits. A correction spends no additional root slot, cannot extend the deadline, and does not reset the 30/90-day timers. A root preflight refusal creates no attempt and reserves no slot. An expired or incomplete attempt does not create a free new chain, and an insufficient bank does not grant another root slot. `demo_express` is outside correction chains and real-assessment availability. - Creation fixes `versions`: `policy_version` (the number of the `product` policy version), `bank_version`, and `algorithm_version`. The attempt and its result keep them, so a result is reproduced from the stored answers and these versions, and a later version never rewrites it. -- The attempt `version` advances by exactly one with each committed change, including server-side transitions such as a verdict, a session start, expiry, or automatic finalization; a transition applied when the attempt is read is committed first and also advances it. +- The attempt `version` advances by exactly one with each committed change, including a verdict, an explicit session start, expiry, or automatic finalization. GET operations are projections only: they never change the state, consume session quota, or advance the version. A command or background transition commits due outcomes. Attempt lifecycle, with the commands each state accepts: @@ -276,12 +278,12 @@ Attempt lifecycle, with the commands each state accepts: - Additional practice (PRD FR04): with 0.50 <= P_G < 0.80 in the demo policy, the first finalize of an adaptive attempt completes nothing. It appends a practice of kind `additional` to `practices`, moves the attempt to `additional_practice_pending`, and returns the attempt. The practice continues the same attempt, keeps its time and session limits, and spends no new attempt. The next finalize after its verdict decides; P_G still below 0.80 gives `not_confirmed`. Finalizing without submitting it declines the offer with the same outcome. `practices` is a list with a `kind` rather than one more nullable field, so later practice kinds stay additive. - Finalize therefore always answers with `AssessmentAttempt`, never with a result or a `oneOf` of both. When the state is `completed`, the client reads `GetMyAssessmentResult`. One response type keeps generated clients unambiguous and leaves room for non-terminal decisions without a breaking change. -- Limits: `expires_at` and `sessions` (`used`, `max`, `idle_timeout_seconds`, null when the policy defines no session limit) come from the policy version; PRD FR04 allows two sessions within 72 hours. Creation starts session 1. A read or command on the active attempt after `idle_timeout_seconds` without one starts the next session; one beyond `max` starts none, and the attempt becomes `expired`. Reading a terminal attempt or a result never starts a session. -- At the limits: a practice already `pending` is graded first. Then `ready_to_finalize` is finalized by the server and becomes `completed`, an unsubmitted additional practice is declined (`completed`, `not_confirmed`), and `in_progress` and `practice_pending` become `expired`. A finalize after that answers 200 with the `completed` attempt; any other command answers 409 `state_conflict`. -- Insufficient bank is a distinct state in two places. Before the start, `GetMyAssessmentAvailability` shows `insufficient_bank` for a grade without a published bank or without enough families that this candidate has not seen, and `CreateMyAssessmentAttempt` answers 409 `state_conflict` without creating anything. During an attempt, the terminal state `insufficient_bank` ends it without a confirmed grade instead of repeating families. +- Limits: `expires_at` and `sessions` (`used`, `max`, `idle_timeout_seconds`, null when the policy defines no session limit) come from the policy version; PRD FR04 allows two sessions within 72 hours. Creation starts session 1. After an idle timeout the candidate explicitly calls `StartMyAssessmentAttemptSession` with the latest `expected_version`; it starts the next session only if quota and deadline allow. Calling it during an active session is a no-op. Session start does not extend `expires_at` or `chain_deadline`. +- At the limits: a practice already `pending` is graded first. A command or background transition then finalizes `ready_to_finalize` as `completed`, declines an unsubmitted additional practice (`completed`, `not_confirmed`), or moves `in_progress` and `practice_pending` to `expired`. GET never commits these transitions. `GetMyAssessmentResult` answers 409 while a due transition has not yet been stored. +- Insufficient bank is a distinct state in two places. Before a root attempt starts, `GetMyAssessmentAvailability` shows `insufficient_bank` for a grade without a published bank or enough unseen families, and `CreateMyAssessmentAttempt` answers 409 `state_conflict` without creating an attempt or reserving a root slot. A correction with an expired chain deadline or insufficient safe bank is also refused; it does not create a new chain. During an existing attempt, the terminal state `insufficient_bank` ends it without a confirmed grade instead of repeating families. - No new problem code is added, so attempt creation gets 409 `state_conflict` plus the availability status instead of a `bank_unavailable` code. The `ProblemCode` enum is copied byte-for-byte into the ML contract (`test_contract_copies.py`), so a new code would also change the ML contract and its generated models. The availability read also tells the client why an attempt cannot start and, for `cooldown`, from when, which a fixed problem detail cannot carry. - Availability shows the limits of each grade before the start: `time_limit_seconds`, `max_sessions`, `max_items`, and `practice_required`, null when unknown. -- Counting against the retry rules (3 attempts per 180 days, the 30-day same-grade interval): an attempt that ends `not_determined` with the reason `expired` or `practice_incomplete` is the candidate's attempt and counts. `insufficient_bank` and `sandbox_unavailable` are platform faults: they never count and start no interval. After a failure, including the first test, a lower grade can be tested at once. +- Root-attempt quota and retry timers are separate. Only root creation reserves one of the three root slots per 180 days; corrections in that chain do not reserve another. `insufficient_bank` or an unavailable sandbox does not create a new attempt or open a free chain. After a failure, including the first test, a strictly lower grade can be tested through the same chain; lower-grade corrections do not reset the 30-day same-grade or 90-day promotion timers. Items and answers: @@ -293,17 +295,18 @@ Items and answers: Commands, retries, and versions: -- Create, answer, and finalize require Idempotency-Key with the 24-hour replay described above, so a repeated command returns the same outcome. Answers and finalize also carry `expected_version`, the attempt `version` the client read. Creation has no version to compare and relies on the key; the single active attempt per specialization is enforced by the state. +- Create, start/resume session, answer, and finalize require Idempotency-Key with the 24-hour replay described above, so a repeated command returns the same outcome. Session start, answers, and finalize carry `expected_version`, the attempt `version` the client read. Creation has no version to compare and relies on the key; the single active real attempt per specialization is enforced by the state. - Each item accepts one answer. Sending the stored answer again, even with a new key or an older `expected_version`, stores nothing, keeps the version, and answers 200 with the current attempt. Equality is defined per format: sets for `option_ids` and `line_numbers`, the exact sequence for `element_ids`, numeric equality for `number`, identical text without normalization for `text` and `config`, and the same language with identical source for a practice. A different answer for an answered item answers 409 `state_conflict` with the current version; with a stale version the version check comes first and answers 412. - Exception: a practice whose latest verdict is `failed` is outside the repeat rule. A submission with the same or a different solution and the current version queues it again and advances the version. - Finalizing a `completed` attempt answers 200 with that attempt, so the result is computed once. A retry of the finalize that offered an additional practice, sent with a new key, carries the old version and answers 412, so it never declines the offer by accident. -- A stale `expected_version` answers 412 `version_conflict`, not 409. It keeps the repository rule above and the questionnaire precedent: `version_conflict` is 412 for If-Match and for a body `expected_version` alike, because the client action is the same, to read the resource again. 409 `state_conflict` is kept for a command that the attempt state does not allow at the current version: the item is not current or has another answer, the attempt is terminal or past its limits, a practice verdict is pending, or the attempt is not ready to finalize. The two codes therefore lead to different client actions. +- A stale `expected_version` answers 412 `version_conflict`, not 409. This keeps the repository rule and questionnaire precedent: `version_conflict` is 412 for If-Match and for a body `expected_version` alike, because the client action is to read the resource again. 409 `state_conflict` is kept for a command that the attempt state does not allow at the current version: the work session ended, the item is not current or has another answer, the attempt is terminal or past its limits, a practice verdict is pending, or the attempt is not ready to finalize. The two codes lead to different client actions. - A premature finalize answers 409 `state_conflict` without listing the unfinished items, because `Problem` allows no extension fields. The client reads them from the attempt: `state`, `progress`, `current_item`, and `practices`. -- Order of checks for a command: session (401), CSRF and Origin (403), request validation (400), account scenario (403 `forbidden`), the Idempotency-Key (422, 409 `idempotency_in_progress`, replay), the attempt (404, after any due transition), the repeat of a stored answer or of finalize on a completed attempt (200), the version (412), the state (409 `state_conflict`), then domain rules (400 with pointers such as `/answer/option_ids/0`). Following the Idempotency-Key convention, 404 and 409 `state_conflict` are stored under the key and replayed, while 400, including domain rules, 412, 429, and 5xx are not. Create and answers are rate-limited (429 with `Retry-After`), which also limits sandbox load. `TestAssessmentSchemaValidationPrecedesImplementation` checks the schema rejections through the generated server. +- Order of checks for a command: session (401), CSRF and Origin (403), request validation (400), account scenario (403 `forbidden`), the Idempotency-Key (422, 409 `idempotency_in_progress`, replay), attempt ownership (404), the attempt version (412 when supplied), due time or session transitions, then the command state (409 `state_conflict`) and domain rules (400 with pointers such as `/answer/option_ids/0`). An explicit session-start command returns the updated attempt when it commits a due terminal transition. Following the Idempotency-Key convention, stored 404 and 409 responses replay under the key; 400, 412, 429, and 5xx are not stored. Create and answers are rate-limited (429 with `Retry-After`), which also limits sandbox load. `TestAssessmentSchemaValidationPrecedesImplementation` checks the schema rejections through the generated server. Result: - `GetMyAssessmentResult` answers for a terminal attempt and 409 `state_conflict` for an active one, including `additional_practice_pending`. `outcome` is `confirmed`, `not_confirmed`, or `not_determined` with `not_determined_reason` (`expired`, `practice_incomplete`, `insufficient_bank`, `sandbox_unavailable`). A result never lowers a confirmed grade: `previous_confirmed_grade` stays in force when the attempt confirmed nothing. +- Attempt and result responses carry the `kind` discriminator: `root`, `corrective`, or `demo_express`. Real results always include the correction-chain field pair: both are null for a root attempt, and both are populated for a corrective result. A `demo_express` result is a separate educational shape with a short summary and `demonstration_only`; it has null category, target grade, confirmed grade, strength, uncertainty, and score, and empty practices, gaps, and next steps. It cannot be used as qualification evidence and is never visible to employers. - `calibration_status` and `limitations` describe the method. Fields that the method does not compute are null, never zero: `demo_basic` has null `uncertainty` and `strength`, and `adaptive` has null `basic_score`. `uncertainty` holds `theta`, `standard_error`, `interval_95`, and `p_grade`. `practices` lists the verdicts by kind. `durations` is a separate label and never enters the decision. - `next_steps` come from the server: `retake_same_grade`, `take_lower_grade`, `accept_lower_grade` (the command is planned), and `take_higher_grade`. A first confirmation is not a promotion, so `take_higher_grade` after it has a null `available_at`; after a promotion the next one waits for the 90-day promotion interval. - The result never contains answers, per-item correctness, keys, seeds, hidden checks, or anti-cheat signals. diff --git a/api/README.md b/api/README.md index e829a5c..4cac0ba 100644 --- a/api/README.md +++ b/api/README.md @@ -245,6 +245,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro | `GET /api/v1/me/assessment-availability` | `GetMyAssessmentAvailability` | сессия | 200 `AssessmentAvailability`, `Cache-Control: no-store` | 401 `unauthenticated`, 403 `forbidden` | | `POST /api/v1/me/assessment-attempts` | `CreateMyAssessmentAttempt` | сессия и CSRF, Idempotency-Key | 201 `AssessmentAttempt`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `csrf_check_failed` или `forbidden`, 409 `state_conflict` или `idempotency_in_progress`, 422 `idempotency_key_reused`, 429 | | `GET /api/v1/me/assessment-attempts/{attempt_id}` | `GetMyAssessmentAttempt` | сессия | 200 `AssessmentAttempt`, `Cache-Control: no-store` | 401, 403 `forbidden`, 404 `not_found` | +| `POST /api/v1/me/assessment-attempts/{attempt_id}/sessions` | `StartMyAssessmentAttemptSession` | сессия и CSRF, Idempotency-Key | 200 `AssessmentAttempt`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict` или `idempotency_in_progress`, 412 `version_conflict`, 422, 429 | | `POST /api/v1/me/assessment-attempts/{attempt_id}/answers` | `SubmitMyAssessmentAnswer` | сессия и CSRF, Idempotency-Key | 200 `AssessmentAttempt`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict` или `idempotency_in_progress`, 412 `version_conflict`, 422, 429 | | `POST /api/v1/me/assessment-attempts/{attempt_id}/finalize` | `FinalizeMyAssessmentAttempt` | сессия и CSRF, Idempotency-Key | 200 `AssessmentAttempt`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict` или `idempotency_in_progress`, 412 `version_conflict`, 422 | | `GET /api/v1/me/assessment-attempts/{attempt_id}/result` | `GetMyAssessmentResult` | сессия | 200 `AssessmentResult`, `Cache-Control: no-store` | 401, 403 `forbidden`, 404 `not_found`, 409 `state_conflict` | @@ -254,13 +255,14 @@ ML-сервис отвечает на ошибки той же схемой `Pro Доступ: - Кандидат берется только из сессии; ни одна операция не принимает идентификатор кандидата. Аккаунт работодателя получает 403 `forbidden`. Попытка другого кандидата дает 404 `not_found`, как и неизвестный идентификатор, поэтому идентификаторы попыток нельзя перебирать. -- Ни одна операция не дает работодателю ответы, историю попыток или античит-сигналы. Работодатель будет видеть только текущую категорию через отдельную проекцию. +- Ни одна операция не дает работодателю ответы, квалификационные данные, историю попыток или античит-сигналы. Работодатель будет видеть только текущую категорию через отдельную проекцию. Режимы и версии: -- `mode` - это `demo_basic` или `adaptive`. Сервер выбирает его по опубликованному банку категории; клиент режим не передает. `demo_basic` оценивает фиксированную форму проверенных демо-заданий по их ключам относительно проходного балла версионированной базовой политики, не вычисляет оценку способности и решает за один шаг: дополнительную практику он не предлагает. `adaptive` - адаптивный тест из FR04. +- При создании обязательно передается `kind`: `root`, `corrective` или `demo_express`. Реальная попытка использует `demo_basic` или `adaptive`; сервер выбирает режим по опубликованному банку, клиент его не передает. `demo_basic` оценивает фиксированную форму проверенных демо-заданий по их ключам относительно проходного балла версионированной базовой политики, не вычисляет оценку способности и решает за один шаг: дополнительную практику он не предлагает. `adaptive` - адаптивный тест из FR04. Кандидат может явно запросить `demo_express` - отдельный интерактивный учебный запуск на 3-5 минут без категории, целевого грейда, перцентиля, квоты реальных оценок или квалификационных данных. +- Корректирующая реальная попытка содержит `root_attempt_id`. Сервер разрешает только строго меньший целевой грейд, который еще не проверялся в этой цепочке. Создание корневой попытки резервирует один слот квоты из трех корневых попыток за 180 дней; корректировки используют этот же слот и неизменяемый `chain_deadline` корневой попытки (72 часа от ее старта по текущей политике), но имеют собственные лимиты заданий, практики и сессий. Корректировка не списывает еще один слот, не продлевает срок и не сбрасывает таймеры 30/90 дней. Предварительный отказ в запуске корневой попытки не создает попытку и не резервирует слот. Истечение или незавершенная практика не открывают бесплатную новую цепочку, а недостаточный банк не дает дополнительную корневую квоту. `demo_express` не входит в цепочки корректировок и доступность реальных оценок. - Создание фиксирует `versions`: `policy_version` (номер версии политики `product`), `bank_version` и `algorithm_version`. Попытка и ее результат хранят их, поэтому результат воспроизводится по сохраненным ответам и этим версиям, а более поздняя версия его не переписывает. -- `version` попытки растет ровно на единицу с каждым зафиксированным изменением, включая серверные переходы: вердикт, начало сессии, истечение, автоматическое завершение. Переход, примененный при чтении попытки, фиксируется до ответа и тоже увеличивает версию. +- `version` попытки растет ровно на единицу с каждым зафиксированным изменением: вердикт, явное начало сессии, истечение или автоматическое завершение. GET-операции возвращают только проекцию: они не меняют состояние, не расходуют квоту сессий и не увеличивают версию. Назревшие исходы фиксирует команда или фоновый переход. Жизненный цикл попытки и команды, которые принимает каждое состояние: @@ -276,12 +278,12 @@ ML-сервис отвечает на ошибки той же схемой `Pro - Дополнительная практика (FR04 в PRD): при 0.50 <= P_G < 0.80 в демо-политике первое завершение adaptive-попытки ничего не решает. Оно добавляет в `practices` практику вида `additional`, переводит попытку в `additional_practice_pending` и возвращает попытку. Практика продолжает ту же попытку, сохраняет ее лимиты времени и сессий и не расходует новую попытку. Следующее завершение после ее вердикта принимает решение; если P_G остается ниже 0.80, итог `not_confirmed`. Завершение без отправки практики отклоняет предложение с тем же итогом. `practices` - список с полем `kind`, а не еще одно nullable-поле, поэтому новые виды практики добавляются без ломающих изменений. - Поэтому завершение всегда отвечает `AssessmentAttempt`, а не результатом и не `oneOf` из двух схем. Когда состояние `completed`, клиент читает `GetMyAssessmentResult`. Один тип ответа делает сгенерированные клиенты однозначными и оставляет место для незавершающих решений без ломающих изменений. -- Лимиты: `expires_at` и `sessions` (`used`, `max`, `idle_timeout_seconds`; null, если политика не задает лимит сессий) берутся из версии политики; FR04 в PRD допускает две сессии в пределах 72 часов. Создание начинает сессию 1. Чтение или команда по активной попытке после `idle_timeout_seconds` без них начинает следующую сессию; сессия сверх `max` не начинается, и попытка становится `expired`. Чтение терминальной попытки или результата сессию не начинает. -- При достижении лимитов практика в статусе `pending` сначала оценивается. Затем сервер сам завершает `ready_to_finalize` и переводит в `completed`, неотправленная дополнительная практика считается отклоненной (`completed`, `not_confirmed`), а `in_progress` и `practice_pending` становятся `expired`. Завершение после этого дает 200 с попыткой в `completed`; любая другая команда дает 409 `state_conflict`. -- Недостаточный банк - отдельное состояние в двух местах. До старта `GetMyAssessmentAvailability` показывает `insufficient_bank` для грейда без опубликованного банка или без достаточного числа семейств, которых кандидат еще не видел, а `CreateMyAssessmentAttempt` отвечает 409 `state_conflict` и ничего не создает. Во время попытки терминальное состояние `insufficient_bank` завершает ее без подтвержденного грейда вместо повтора семейств. +- Лимиты: `expires_at` и `sessions` (`used`, `max`, `idle_timeout_seconds`; null, если политика не задает лимит сессий) берутся из версии политики; FR04 в PRD допускает две сессии в пределах 72 часов. Создание начинает сессию 1. После простоя кандидат явно вызывает `StartMyAssessmentAttemptSession` с последним `expected_version`; следующая сессия начинается только если позволяют квота и срок. Вызов во время активной сессии ничего не меняет. Начало сессии не продлевает `expires_at` или `chain_deadline`. +- При достижении лимитов практика, уже имеющая статус `pending`, сначала оценивается. Затем команда или фоновый переход завершает `ready_to_finalize` как `completed`, отклоняет неотправленную дополнительную практику (`completed`, `not_confirmed`) или переводит `in_progress` и `practice_pending` в `expired`. GET не фиксирует эти переходы. `GetMyAssessmentResult` отвечает 409, пока назревший переход не сохранен. +- Недостаточный банк - отдельное состояние в двух местах. До старта корневой попытки `GetMyAssessmentAvailability` показывает `insufficient_bank` для грейда без опубликованного банка или достаточного числа невиденных семейств, а `CreateMyAssessmentAttempt` отвечает 409 `state_conflict`, не создавая попытку и не резервируя корневой слот. Корректировка также отклоняется, если срок цепочки истек или безопасного банка недостаточно; новая цепочка не создается. Во время существующей попытки терминальное состояние `insufficient_bank` завершает ее без подтвержденного грейда вместо повтора семейств. - Новый код проблемы не добавлен, поэтому создание попытки получает 409 `state_conflict` и статус доступности вместо кода `bank_unavailable`. Перечисление `ProblemCode` побайтно скопировано в ML-контракт (`test_contract_copies.py`), поэтому новый код изменил бы и ML-контракт, и его сгенерированные модели. Чтение доступности к тому же объясняет клиенту, почему попытка не может начаться, и для `cooldown` - с какого момента; фиксированный detail проблемы этого передать не может. - Доступность показывает лимиты каждого грейда до старта: `time_limit_seconds`, `max_sessions`, `max_items` и `practice_required`; null, если значение неизвестно. -- Учет в правилах повтора (3 попытки за 180 дней, 30 дней до повтора того же грейда): попытка с итогом `not_determined` по причине `expired` или `practice_incomplete` - попытка кандидата и учитывается. `insufficient_bank` и `sandbox_unavailable` - сбои платформы: они не учитываются и не запускают интервал. После неудачи, включая первый тест, меньший грейд можно проверить сразу. +- Корневая квота и таймеры повторов разделены. Только запуск корневой попытки резервирует один из трех слотов на 180 дней; корректировки этой цепочки не резервируют дополнительные слоты. `insufficient_bank` или недоступность песочницы не создают новую попытку и не открывают бесплатную цепочку. После неудачи, включая первый тест, строго меньший грейд можно проверить в той же цепочке; корректировки не сбрасывают 30-дневный таймер повтора того же грейда или 90-дневный таймер повышения. Задания и ответы: @@ -293,17 +295,18 @@ ML-сервис отвечает на ошибки той же схемой `Pro Команды, повторы и версии: -- Создание, ответ и завершение требуют Idempotency-Key с 24-часовым повтором, описанным выше, поэтому повтор команды возвращает тот же исход. Ответ и завершение также передают `expected_version` - прочитанную клиентом `version` попытки. У создания нет версии для сравнения, оно опирается на ключ; единственную активную попытку по специализации обеспечивает состояние. +- Создание, начало или возобновление сессии, ответ и завершение требуют Idempotency-Key с 24-часовым повтором, описанным выше, поэтому повтор команды возвращает тот же исход. Начало сессии, ответ и завершение также передают `expected_version` - прочитанную клиентом `version` попытки. У создания нет версии для сравнения, оно опирается на ключ; единственную активную реальную попытку по специализации обеспечивает состояние. - Каждое задание принимает один ответ. Повторная отправка сохраненного ответа, даже с новым ключом или старым `expected_version`, ничего не сохраняет, не меняет версию и дает 200 с текущей попыткой. Равенство определено для каждого формата: множества для `option_ids` и `line_numbers`, точная последовательность для `element_ids`, числовое равенство для `number`, совпадение текста без нормализации для `text` и `config`, тот же язык и совпадающий исходный код для практики. Другой ответ на уже отвеченное задание дает 409 `state_conflict` при текущей версии; при устаревшей версии ее проверка идет раньше и дает 412. - Исключение: практика, последний вердикт которой `failed`, не подпадает под правило повтора. Отправка того же или другого решения с текущей версией снова ставит его в очередь и увеличивает версию. - Завершение попытки в `completed` дает 200 с этой попыткой, поэтому результат вычисляется один раз. Повтор завершения, которое предложило дополнительную практику, с новым ключом несет старую версию и получает 412, поэтому он не может случайно отклонить предложение. -- Устаревший `expected_version` дает 412 `version_conflict`, а не 409. Так сохраняется правило репозитория выше и прецедент анкеты: `version_conflict` - это 412 и для If-Match, и для `expected_version` в теле, потому что действие клиента одно - прочитать ресурс снова. 409 `state_conflict` оставлен для команды, которую состояние попытки не допускает при текущей версии: задание не текущее или уже имеет другой ответ, попытка терминальная или вышла за лимиты, вердикт практики еще не готов или попытка не готова к завершению. Поэтому два кода ведут к разным действиям клиента. +- Устаревший `expected_version` дает 412 `version_conflict`, а не 409. Так сохраняется правило репозитория и прецедент анкеты: `version_conflict` - это 412 и для If-Match, и для `expected_version` в теле, потому что действие клиента - прочитать ресурс снова. 409 `state_conflict` оставлен для команды, которую состояние попытки не допускает при текущей версии: рабочая сессия закончилась, задание не текущее или уже имеет другой ответ, попытка терминальная или вышла за лимиты, вердикт практики еще не готов или попытка не готова к завершению. Коды ведут к разным действиям клиента. - Преждевременное завершение дает 409 `state_conflict` без перечня незавершенных заданий, потому что `Problem` не допускает дополнительных полей. Клиент берет их из попытки: `state`, `progress`, `current_item` и `practices`. -- Порядок проверок команды: сессия (401), CSRF и Origin (403), валидация запроса (400), сценарий аккаунта (403 `forbidden`), Idempotency-Key (422, 409 `idempotency_in_progress`, повтор), попытка (404, после всех назревших переходов), повтор сохраненного ответа или завершения завершенной попытки (200), версия (412), состояние (409 `state_conflict`), затем доменные правила (400 с pointer вроде `/answer/option_ids/0`). По соглашению об Idempotency-Key 404 и 409 `state_conflict` сохраняются под ключом и повторяются, а 400 (включая доменные правила), 412, 429 и 5xx - нет. Создание и ответы ограничены по частоте (429 с `Retry-After`), что ограничивает и нагрузку на песочницу. `TestAssessmentSchemaValidationPrecedesImplementation` проверяет отказы схемы через сгенерированный сервер. +- Порядок проверок команды: сессия (401), CSRF и Origin (403), валидация запроса (400), сценарий аккаунта (403 `forbidden`), Idempotency-Key (422, 409 `idempotency_in_progress`, повтор), принадлежность попытки (404), версия попытки (412, если передана), переходы по сроку или лимиту сессий, затем состояние команды (409 `state_conflict`) и доменные правила (400 с pointer вроде `/answer/option_ids/0`). Команда начала сессии возвращает обновленную попытку, если она зафиксировала наступивший терминальный переход. По соглашению об Idempotency-Key сохраненные 404 и 409 повторяются под ключом; 400, 412, 429 и 5xx не сохраняются. Создание и ответы ограничены по частоте (429 с `Retry-After`), что ограничивает и нагрузку на песочницу. `TestAssessmentSchemaValidationPrecedesImplementation` проверяет отказы схемы через сгенерированный сервер. Результат: - `GetMyAssessmentResult` отвечает для терминальной попытки и дает 409 `state_conflict` для активной, включая `additional_practice_pending`. `outcome` - это `confirmed`, `not_confirmed` или `not_determined` с `not_determined_reason` (`expired`, `practice_incomplete`, `insufficient_bank`, `sandbox_unavailable`). Результат никогда не понижает подтвержденный грейд: если попытка ничего не подтвердила, действует `previous_confirmed_grade`. +- В ответах попытки и результата есть дискриминатор `kind`: `root`, `corrective` или `demo_express`. Реальный результат всегда содержит пару полей цепочки корректировок: у корневой попытки оба поля null, у корректирующей оба заполнены. Для `demo_express` используется отдельная учебная схема с кратким резюме и `demonstration_only`: категория, целевой и подтвержденный грейды, сила, неопределенность и балл равны null, списки практик, пробелов и следующих шагов пусты. Этот режим не создает квалификационных данных и не виден работодателю. - `calibration_status` и `limitations` описывают метод. Поля, которые метод не вычисляет, равны null, а не нулю: у `demo_basic` null в `uncertainty` и `strength`, у `adaptive` - null в `basic_score`. `uncertainty` содержит `theta`, `standard_error`, `interval_95` и `p_grade`. `practices` перечисляет вердикты по видам. `durations` - отдельная метка, которая не входит в решение. - `next_steps` приходят с сервера: `retake_same_grade`, `take_lower_grade`, `accept_lower_grade` (команда запланирована) и `take_higher_grade`. Первое подтверждение - не повышение, поэтому `take_higher_grade` после него имеет null в `available_at`; после повышения следующее ждет 90-дневный интервал повышения. - Результат никогда не содержит ответы, правильность отдельных заданий, ключи, seed, скрытые проверки или античит-сигналы. diff --git a/api/core/components/examples.yml b/api/core/components/examples.yml index 2195b60..e44c6f7 100644 --- a/api/core/components/examples.yml +++ b/api/core/components/examples.yml @@ -509,6 +509,7 @@ AssessmentAvailability: AssessmentAttemptCreateBackendJunior: summary: Start Backend junior with Go tasks value: + kind: root specialization: backend target_grade: junior task_language: go @@ -524,9 +525,12 @@ AssessmentAttemptCreated: value: id: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b version: 1 + kind: root specialization: backend target_grade: junior task_language: go + root_attempt_id: null + chain_deadline: null mode: demo_basic state: in_progress versions: @@ -560,6 +564,86 @@ AssessmentAttemptCreated: - id: c4 text: "500" practices: [] +AssessmentCorrectiveAttemptCreated: + summary: Corrective attempt shares the root chain deadline + value: + id: 01928f7e-8888-7a2b-8c3d-4e5f6a7b8c9d + version: 1 + kind: corrective + specialization: backend + target_grade: junior + task_language: go + root_attempt_id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d + chain_deadline: "2026-11-23T09:00:00Z" + mode: adaptive + state: in_progress + versions: + policy_version: 2 + bank_version: backend.2026-11.3 + algorithm_version: irt-1pl-eap.1 + started_at: "2026-11-22T10:00:00Z" + expires_at: "2026-11-23T09:00:00Z" + sessions: + used: 1 + max: 2 + idle_timeout_seconds: 1800 + finished_at: null + progress: + answered_items: 0 + max_items: 25 + current_item: + id: 01928f7e-9999-7a2b-8c3d-4e5f6a7b8c01 + sequence: 1 + prompt: "What does an HTTP 412 response indicate for expected_version?" + content: + format: choice + multiple: false + options: + - id: a1 + text: The version is stale. + - id: b2 + text: The request is malformed. + practices: [] +AssessmentExpressAttemptCreated: + summary: Short training attempt without a qualification category + value: + id: 01928f7f-9999-7a2b-8c3d-4e5f6a7b8c01 + version: 1 + kind: demo_express + specialization: null + target_grade: null + task_language: null + root_attempt_id: null + chain_deadline: null + mode: demo_express + state: in_progress + versions: + policy_version: 1 + bank_version: express-demo.2026-10.1 + algorithm_version: express-interactive.1 + started_at: "2026-10-08T10:00:00Z" + expires_at: "2026-10-08T10:05:00Z" + sessions: + used: 1 + max: 1 + idle_timeout_seconds: 300 + finished_at: null + progress: + answered_items: 0 + max_items: 5 + current_item: + id: 01928f7f-aaaa-7a2b-8c3d-4e5f6a7b8c01 + sequence: 1 + prompt: "Choose the status code that signals a version conflict." + content: + format: choice + multiple: false + options: + - id: c3 + text: "412" + - id: d4 + text: "200" + practices: [] AssessmentAnswerAccepted: summary: Answer to item 1 stored; item 2 follows description: >- @@ -572,9 +656,12 @@ AssessmentAnswerAccepted: value: id: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b version: 2 + kind: root specialization: backend target_grade: junior task_language: go + root_attempt_id: null + chain_deadline: null mode: demo_basic state: in_progress versions: @@ -612,9 +699,12 @@ AssessmentAttemptCompleted: value: id: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b version: 14 + kind: root specialization: backend target_grade: junior task_language: go + root_attempt_id: null + chain_deadline: null mode: demo_basic state: completed versions: @@ -643,9 +733,12 @@ AssessmentAttemptResumed: value: id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d version: 7 + kind: root specialization: backend target_grade: middle task_language: python + root_attempt_id: null + chain_deadline: null mode: adaptive state: in_progress versions: @@ -701,9 +794,12 @@ AssessmentAttemptPracticePending: value: id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d version: 16 + kind: root specialization: backend target_grade: middle task_language: python + root_attempt_id: null + chain_deadline: null mode: adaptive state: practice_pending versions: @@ -743,9 +839,12 @@ AssessmentAttemptPracticeVerdictPending: value: id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d version: 17 + kind: root specialization: backend target_grade: middle task_language: python + root_attempt_id: null + chain_deadline: null mode: adaptive state: practice_pending versions: @@ -779,9 +878,12 @@ AssessmentAttemptSandboxFailed: value: id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d version: 18 + kind: root specialization: backend target_grade: middle task_language: python + root_attempt_id: null + chain_deadline: null mode: adaptive state: practice_pending versions: @@ -821,9 +923,12 @@ AssessmentAttemptReadyToFinalize: value: id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d version: 20 + kind: root specialization: backend target_grade: middle task_language: python + root_attempt_id: null + chain_deadline: null mode: adaptive state: ready_to_finalize versions: @@ -870,9 +975,12 @@ AssessmentAttemptAdditionalPracticePending: value: id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d version: 21 + kind: root specialization: backend target_grade: middle task_language: python + root_attempt_id: null + chain_deadline: null mode: adaptive state: additional_practice_pending versions: @@ -932,9 +1040,12 @@ AssessmentAttemptInsufficientBank: value: id: 01928f7c-5555-7a2b-8c3d-4e5f6a7b8c9d version: 10 + kind: root specialization: network_engineer target_grade: middle task_language: null + root_attempt_id: null + chain_deadline: null mode: adaptive state: insufficient_bank versions: @@ -1048,6 +1159,9 @@ AssessmentDemoBasicResult: attempt_id: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b specialization: backend target_grade: junior + kind: root + root_attempt_id: null + chain_deadline: null task_language: go mode: demo_basic versions: @@ -1090,6 +1204,9 @@ AssessmentAdaptiveResult: attempt_id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d specialization: backend target_grade: middle + kind: root + root_attempt_id: null + chain_deadline: null task_language: python mode: adaptive versions: @@ -1157,6 +1274,9 @@ AssessmentNotConfirmedResult: attempt_id: 01928f7d-7777-7a2b-8c3d-4e5f6a7b8c9d specialization: backend target_grade: middle + kind: root + root_attempt_id: null + chain_deadline: null task_language: go mode: adaptive versions: @@ -1224,6 +1344,9 @@ AssessmentInsufficientBankResult: attempt_id: 01928f7c-5555-7a2b-8c3d-4e5f6a7b8c9d specialization: network_engineer target_grade: middle + kind: root + root_attempt_id: null + chain_deadline: null task_language: null mode: adaptive versions: @@ -1246,6 +1369,73 @@ AssessmentInsufficientBankResult: practice_seconds: null next_steps: [] decided_at: "2026-11-21T12:31:00Z" +AssessmentCorrectiveResult: + summary: Corrective result retains its root and fixed deadline + value: + attempt_id: 01928f7e-8888-7a2b-8c3d-4e5f6a7b8c9d + specialization: backend + target_grade: middle + kind: corrective + root_attempt_id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d + chain_deadline: "2026-11-23T09:00:00Z" + task_language: go + mode: adaptive + versions: + policy_version: 2 + bank_version: backend.2026-11.3 + algorithm_version: irt-1pl-eap.1 + outcome: not_confirmed + not_determined_reason: null + confirmed_grade: null + previous_confirmed_grade: junior + strength: null + calibration_status: uncalibrated + limitations: [uncalibrated_thresholds, unproctored] + uncertainty: + theta: 0.21 + standard_error: 0.25 + interval_95: + low: -0.28 + high: 0.70 + p_grade: 0.62 + basic_score: null + practices: [] + gaps: [] + durations: + items_seconds: 1500 + practice_seconds: 900 + next_steps: [] + decided_at: "2026-11-22T11:00:00Z" +AssessmentExpressResult: + summary: Short training result with no qualification evidence + value: + attempt_id: 01928f7f-9999-7a2b-8c3d-4e5f6a7b8c9d + specialization: null + target_grade: null + task_language: null + kind: demo_express + mode: demo_express + versions: + policy_version: 1 + bank_version: express-demo.2026-10.1 + algorithm_version: express-interactive.1 + outcome: demonstration + not_determined_reason: null + confirmed_grade: null + previous_confirmed_grade: null + strength: null + calibration_status: uncalibrated + limitations: [demonstration_only] + uncertainty: null + basic_score: null + practices: [] + gaps: [] + durations: + items_seconds: 260 + practice_seconds: null + next_steps: [] + summary: The run demonstrates the task flow and creates no qualification evidence. + decided_at: "2026-11-22T11:00:00Z" AssessmentSpecializationNotInQuestionnaire: summary: The specialization is not in the questionnaire value: diff --git a/api/core/components/schemas.yml b/api/core/components/schemas.yml index c9a3b17..d0d4a8b 100644 --- a/api/core/components/schemas.yml +++ b/api/core/components/schemas.yml @@ -33,23 +33,39 @@ CandidateHandle: - cand_7Qm2xVb9Lr4Kp0Zt AssessmentMode: type: string - description: 'Measurement method of an attempt. The server selects it from the published task bank of the category; the client never chooses it. + description: 'Method of an assessment attempt. For a real assessment, the server selects demo_basic or adaptive from the published bank. A candidate may explicitly request demo_express, which uses a separate training policy and creates no qualification evidence. - demo_basic: a fixed form of reviewed demo items scored by their keys against the pass mark of the versioned basic grading policy. It computes no ability estimate, standard error, or probability, so every uncertainty field of its result is null, its thresholds are uncalibrated, and its decision is binary: it never offers an additional practice. - adaptive: the adaptive test on task families with an ability estimate, its standard error, and the probability of reaching the grade threshold, as the versioned assessment policy defines them. A probability in the band below confirmation offers one additional practice in the same attempt. + - demo_express: an interactive 3 to 5 minute training run under a separate policy. It does not assign a category or percentile, count toward the real-assessment quota, or create qualification evidence. + Adding a value is a contract change.' enum: - demo_basic + - demo_express - adaptive +AssessmentRealMode: + type: string + description: Server-selected mode available to a real category assessment. + enum: + - demo_basic + - adaptive +AssessmentAttemptKind: + type: string + description: Assessment track that distinguishes root, corrective, and training attempts. + enum: + - root + - corrective + - demo_express AssessmentAttemptVersion: type: integer format: int64 minimum: 1 - description: 'Version of an assessment attempt. A new attempt has version 1, and each committed change advances it by exactly one: an accepted answer, a practice submission or resubmission, a verdict, a decision of finalize, a session start, and a server-side transition such as expiry or automatic finalization. A transition that the server applies when the attempt is read is committed before the response and also advances it. A rejected command and a repeat that stores nothing leave it unchanged. Commands send the version they read as `expected_version`.' + description: 'Version of an assessment attempt. A new attempt has version 1, and each committed change advances it by exactly one: an accepted answer, a practice submission or resubmission, a verdict, a decision of finalize, an explicit work-session start, and a server-side transition such as expiry or automatic finalization. Reads never change the attempt. A rejected command and a repeat that stores nothing leave it unchanged. Commands send the version they read as `expected_version`.' examples: - 4 AssessmentAttemptState: @@ -72,7 +88,7 @@ AssessmentAttemptState: - insufficient_bank: the published bank could not supply the items required for coverage within the limit, and the attempt ended without a confirmed grade instead of repeating families. The result is available. - When `expires_at` passes or the session limit is reached, a practice submitted before that and still `pending` is graded first. Then the server decides without another command: `ready_to_finalize` is finalized and becomes `completed`; `additional_practice_pending` with the additional practice not submitted is finalized as declined and becomes `completed` with `not_confirmed`; `in_progress` and `practice_pending` become `expired`, with the result reason `expired` or `practice_incomplete`; and when the latest submission of a practice ended `failed`, the attempt becomes `expired` with the reason `sandbox_unavailable`, which is not the candidate''s fault. `completed`, `expired`, and `insufficient_bank` are terminal and accept no command except the repeat of finalize described on FinalizeMyAssessmentAttempt. Adding a value is a contract change.' + When `expires_at` passes or the session limit is reached, a read returns the stored state without changing it. A command or background transition commits any due outcome and advances the version. A practice submitted before the limit and still `pending` is graded first. Then `ready_to_finalize` becomes `completed`; `additional_practice_pending` with the additional practice not submitted is finalized as declined and becomes `completed` with `not_confirmed`; `in_progress` and `practice_pending` become `expired`, with the result reason `expired` or `practice_incomplete`; and when the latest submission of a practice ended `failed`, the attempt becomes `expired` with the reason `sandbox_unavailable`, which is not the candidate''s fault. `completed`, `expired`, and `insufficient_bank` are terminal and accept no command except the repeat of finalize described on FinalizeMyAssessmentAttempt. Adding a value is a contract change.' enum: - in_progress - practice_pending @@ -110,7 +126,7 @@ AssessmentSessions: description: 'Work sessions of the attempt, as the policy version limits them, for example two sessions within the time limit. - A session starts with the creation of the attempt or, after the previous session ended, with the next GetMyAssessmentAttempt or command on the active attempt. It ends after `idle_timeout_seconds` without such a request. A request that would start a session beyond `max_sessions` starts none: the server moves the attempt to `expired` and answers with it (a read) or with 409 state_conflict (a command). Reading a terminal attempt or a result never starts a session.' + Session 1 starts with attempt creation. After it ends due to `idle_timeout_seconds` of inactivity, the candidate explicitly starts or resumes work with StartMyAssessmentAttemptSession. GetMyAssessmentAttempt and GetMyAssessmentResult are read-only and never start a session. The session command checks the attempt deadline and `max_sessions`; when either limit has passed, it records the due terminal transition and returns the resulting attempt. Reads of terminal attempts do not change them.' additionalProperties: false required: - used @@ -135,14 +151,32 @@ AssessmentSessions: maximum: 86400 description: Inactivity after which the current session ends. AssessmentAttemptCreate: + description: Start a real assessment, a corrective attempt in an existing chain, or an explicit training run. The required `kind` discriminator selects one of the three request shapes; `mode` remains server-selected for real assessments. + oneOf: + - $ref: '#/AssessmentQualifiedAttemptCreate' + - $ref: '#/AssessmentCorrectiveAttemptCreate' + - $ref: '#/AssessmentExpressAttemptCreate' + discriminator: + propertyName: kind + mapping: + root: '#/AssessmentQualifiedAttemptCreate' + corrective: '#/AssessmentCorrectiveAttemptCreate' + demo_express: '#/AssessmentExpressAttemptCreate' +AssessmentQualifiedAttemptCreate: type: object - description: 'Category to assess: a specialization and the target grade, with the task language. The candidate comes from the session. The mode and versions are chosen by the server; unknown fields such as `mode`, `seed`, or `score` are rejected.' + description: 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. additionalProperties: false required: + - kind - specialization - target_grade - task_language properties: + kind: + type: string + enum: + - root + description: Start a real-assessment chain and reserve one root quota slot. specialization: $ref: '#/SpecializationCode' target_grade: @@ -152,6 +186,56 @@ AssessmentAttemptCreate: oneOf: - $ref: '#/TaskLanguage' - type: 'null' +AssessmentCorrectiveAttemptCreate: + type: object + description: 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 is never supplied by the client. + additionalProperties: false + required: + - kind + - specialization + - target_grade + - task_language + - root_attempt_id + properties: + kind: + type: string + enum: + - corrective + description: Continue the existing real-assessment chain without reserving another root slot. + specialization: + $ref: '#/SpecializationCode' + target_grade: + $ref: '#/GradeCode' + task_language: + description: Task language of the attempt, or null when the bank offers no choice. + oneOf: + - $ref: '#/TaskLanguage' + - type: 'null' + root_attempt_id: + type: string + format: uuid + description: Root real-assessment attempt whose quota and deadline this attempt shares. +AssessmentExpressAttemptCreate: + type: object + description: 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. + additionalProperties: false + required: + - kind + properties: + kind: + type: string + enum: + - demo_express + description: Explicitly request the training run; real modes cannot be selected by the client. +AssessmentAttemptSessionStart: + type: object + description: Start or resume a work session using the attempt version last read by the candidate. + additionalProperties: false + required: + - expected_version + properties: + expected_version: + $ref: '#/AssessmentAttemptVersion' AssessmentItemId: type: string format: uuid @@ -547,8 +631,20 @@ AssessmentPractice: - $ref: '#/PracticeFailureReason' - type: 'null' AssessmentAttempt: + description: Candidate view of a real assessment, a corrective real assessment, or a demo_express training run. The variants keep training output separate from qualification attempts. + oneOf: + - $ref: '#/AssessmentQualifiedAttempt' + - $ref: '#/AssessmentCorrectiveAttempt' + - $ref: '#/AssessmentExpressAttempt' + discriminator: + propertyName: kind + mapping: + root: '#/AssessmentQualifiedAttempt' + corrective: '#/AssessmentCorrectiveAttempt' + demo_express: '#/AssessmentExpressAttempt' +AssessmentAttemptCommon: type: object - description: Assessment attempt of the current candidate for one category, a specialization and a target grade. It shows the state, the fixed versions, the server deadline `expires_at` from the policy version, which the client clock never extends, the session limit, the progress, the item to answer now, and the practices. It never contains answer keys, the correctness of submitted answers, scores of single items, family or variant identifiers, seeds, hidden checks, or anti-cheat signals. + 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. additionalProperties: false required: - id @@ -556,6 +652,7 @@ AssessmentAttempt: - specialization - target_grade - task_language + - kind - mode - state - versions @@ -574,14 +671,35 @@ AssessmentAttempt: version: $ref: '#/AssessmentAttemptVersion' specialization: - $ref: '#/SpecializationCode' + description: Null only for demo_express, which has no qualification category. + oneOf: + - $ref: '#/SpecializationCode' + - type: 'null' target_grade: - $ref: '#/GradeCode' + description: Null only for demo_express, which has no qualification category. + oneOf: + - $ref: '#/GradeCode' + - type: 'null' task_language: - description: Task language of the attempt, or null when the bank offers no choice. + description: Task language of the attempt, or null when none is selected. oneOf: - $ref: '#/TaskLanguage' - type: 'null' + kind: + $ref: '#/AssessmentAttemptKind' + root_attempt_id: + description: Present only for a corrective real assessment. It identifies the root attempt whose quota and chain deadline this attempt shares. + oneOf: + - type: string + format: uuid + - type: 'null' + readOnly: true + chain_deadline: + description: Present only for a corrective real assessment. It is the immutable deadline derived from the root attempt and is not extended by a lower target grade. + oneOf: + - $ref: '#/Timestamp' + - type: 'null' + readOnly: true mode: $ref: '#/AssessmentMode' state: @@ -591,9 +709,10 @@ AssessmentAttempt: started_at: $ref: '#/Timestamp' expires_at: + description: Server deadline. For demo_express it is 180 to 300 seconds after started_at; for a corrective assessment it does not exceed chain_deadline. $ref: '#/Timestamp' sessions: - description: Session limit of the attempt, or null when its policy version defines none. + description: Session limit of the attempt, or null when its policy defines none. oneOf: - $ref: '#/AssessmentSessions' - type: 'null' @@ -612,9 +731,103 @@ AssessmentAttempt: practices: type: array maxItems: 5 - description: 'Practices in the order they were assigned: the `main` practice first, then an `additional` practice once finalize offers it. Empty only for a demo_basic attempt while code practice is disabled until the sandbox isolation is verified; its result then lists the `practice_not_included` limitation. A list rather than one field leaves room for more practices without a breaking change.' + description: Practices in the order assigned by the mode policy. The list exposes verdicts only after submission. items: $ref: '#/AssessmentPractice' +AssessmentQualifiedAttempt: + allOf: + - $ref: '#/AssessmentAttemptCommon' + - type: object + properties: + kind: + type: string + enum: + - root + mode: + type: string + enum: + - demo_basic + - adaptive + specialization: + $ref: '#/SpecializationCode' + target_grade: + $ref: '#/GradeCode' + root_attempt_id: + type: 'null' + description: Root attempts have no parent attempt. + chain_deadline: + type: 'null' + description: A root attempt has no correction-chain deadline. + required: + - kind + - mode + - specialization + - target_grade + - root_attempt_id + - chain_deadline +AssessmentCorrectiveAttempt: + allOf: + - $ref: '#/AssessmentAttemptCommon' + - type: object + properties: + kind: + type: string + enum: + - corrective + mode: + type: string + enum: + - demo_basic + - adaptive + specialization: + $ref: '#/SpecializationCode' + target_grade: + $ref: '#/GradeCode' + root_attempt_id: + type: string + format: uuid + readOnly: true + chain_deadline: + $ref: '#/Timestamp' + readOnly: true + required: + - kind + - mode + - specialization + - target_grade + - root_attempt_id + - chain_deadline +AssessmentExpressAttempt: + allOf: + - $ref: '#/AssessmentAttemptCommon' + - type: object + properties: + kind: + type: string + enum: + - demo_express + mode: + type: string + enum: + - demo_express + specialization: + type: 'null' + target_grade: + type: 'null' + task_language: + type: 'null' + root_attempt_id: + type: 'null' + chain_deadline: + type: 'null' + required: + - kind + - mode + - specialization + - target_grade + - task_language + - root_attempt_id + - chain_deadline ChoiceAnswer: type: object description: 'Selected options of a choice item: exactly one unless the item allows several. Two answers are equal when they select the same set of options, in any order.' @@ -797,16 +1010,16 @@ AssessmentOutcome: - not_determined AssessmentNotDeterminedReason: type: string - description: 'Why an attempt gives no decision, and whether it counts against the retry rules. + description: 'Why an attempt gives no decision. One root quota slot is reserved when a real root attempt starts; corrective checks in its chain do not reserve another slot. - - expired: the time or session limit passed before the candidate finished the item part. It is the candidate''s attempt: it counts toward the attempt limit and starts the same-grade retry interval. + - expired: the time or session limit passed before the candidate finished the item part. Retry timing follows the recorded policy; a correction uses the existing root slot and does not reset the chain deadline or 30/90-day timers. - - practice_incomplete: the item part was done, but the candidate did not submit the main practice before the limit. It counts like `expired`. + - practice_incomplete: the item part was done, but the candidate did not submit the main practice before the limit. Retry timing follows the recorded policy; a correction uses the existing root slot and does not reset the chain deadline or 30/90-day timers. - - insufficient_bank: the bank could not supply the required coverage within the limit. It is a platform limitation: it never counts toward the attempt limit and starts no retry interval. + - insufficient_bank: the bank could not supply required coverage. A preflight refusal creates no attempt or root slot; a bank failure in an existing chain does not create a free new chain or another root slot. - - sandbox_unavailable: the latest submission of a required or additional practice ended `failed` because of the sandbox infrastructure, and the limit passed before a verdict. It is a platform fault: it never counts toward the attempt limit and starts no retry interval.' + - sandbox_unavailable: the latest submission of a required or additional practice ended `failed` because of the sandbox infrastructure, and the limit passed before a verdict. It is a platform fault and does not create a new root slot or a free chain.' enum: - expired - practice_incomplete @@ -826,7 +1039,7 @@ CalibrationStatus: - calibrated AssessmentLimitation: type: string - description: 'Known limitation of the method behind a result, shown with the result. + description: 'Known limitation of the method behind a real-assessment result, shown with the result. - uncalibrated_thresholds: the thresholds are not yet validated on a pilot. @@ -837,7 +1050,6 @@ AssessmentLimitation: - unproctored: the attempt was taken online without supervision. - Adding a value is a contract change.' enum: - uncalibrated_thresholds @@ -990,14 +1202,27 @@ AssessmentNextStep: - $ref: '#/Timestamp' - type: 'null' AssessmentResult: + description: Immutable result of a terminal assessment attempt. The result shape distinguishes real grade decisions from demo_express training output. + oneOf: + - $ref: '#/AssessmentQualifiedResult' + - $ref: '#/AssessmentCorrectiveResult' + - $ref: '#/AssessmentExpressResult' + discriminator: + propertyName: kind + mapping: + root: '#/AssessmentQualifiedResult' + corrective: '#/AssessmentCorrectiveResult' + demo_express: '#/AssessmentExpressResult' +AssessmentRealResultCommon: type: object - description: 'Immutable result of a terminal attempt, visible only to its candidate. It records the method, the versions, the decision, its uncertainty, and its limitations; a later policy, bank, or algorithm version never changes it. It never contains answers, per-item correctness, answer keys, seeds, hidden checks, or anti-cheat signals. Fields that the method does not compute are null, never zero: demo_basic has null `uncertainty` and `strength`, and adaptive has null `basic_score`.' + description: Immutable result of a real assessment, visible only to its candidate. It records the method, versions, decision, uncertainty, and limitations. A corrective result also carries root_attempt_id and chain_deadline from the same chain. Later policy, bank, or algorithm versions never change it. It never contains answers, per-item correctness, keys, seeds, hidden checks, or anti-cheat signals. Fields the method does not compute are null, never zero. additionalProperties: false required: - attempt_id - specialization - target_grade - task_language + - kind - mode - versions - outcome @@ -1022,12 +1247,33 @@ AssessmentResult: $ref: '#/SpecializationCode' target_grade: $ref: '#/GradeCode' + root_attempt_id: + description: Root attempt of a corrective check, or null when this is not a corrective result. The corrective attempt keeps this link. + oneOf: + - type: string + format: uuid + - type: 'null' + readOnly: true + chain_deadline: + description: Immutable deadline shared by a corrective chain, or null when this result is not from a corrective check. + oneOf: + - $ref: '#/Timestamp' + - type: 'null' + readOnly: true task_language: oneOf: - $ref: '#/TaskLanguage' - type: 'null' + kind: + type: string + enum: + - root + - corrective mode: - $ref: '#/AssessmentMode' + type: string + enum: + - demo_basic + - adaptive versions: $ref: '#/AssessmentVersions' outcome: @@ -1091,6 +1337,148 @@ AssessmentResult: $ref: '#/AssessmentNextStep' decided_at: $ref: '#/Timestamp' +AssessmentQualifiedResult: + description: Result of a real assessment that is not a corrective attempt. The correction-chain fields are explicitly null. + allOf: + - $ref: '#/AssessmentRealResultCommon' + - type: object + properties: + kind: + type: string + enum: + - root + root_attempt_id: + type: 'null' + chain_deadline: + type: 'null' + required: + - kind + - root_attempt_id + - chain_deadline +AssessmentCorrectiveResult: + description: Result of a corrective real assessment. Both chain fields are present and identify the same immutable correction chain. + allOf: + - $ref: '#/AssessmentRealResultCommon' + - type: object + properties: + kind: + type: string + enum: + - corrective + root_attempt_id: + type: string + format: uuid + readOnly: true + chain_deadline: + $ref: '#/Timestamp' + readOnly: true + required: + - kind + - root_attempt_id + - chain_deadline +AssessmentExpressResult: + type: object + description: Immutable educational result of a demo_express run. It includes a short summary but cannot report a category, percentile, uncertainty, grade, strength, or qualification evidence. The result belongs only to the training mode and does not consume a real-assessment quota. + additionalProperties: false + required: + - attempt_id + - specialization + - target_grade + - task_language + - kind + - mode + - versions + - outcome + - not_determined_reason + - confirmed_grade + - previous_confirmed_grade + - strength + - calibration_status + - limitations + - uncertainty + - basic_score + - practices + - gaps + - durations + - next_steps + - summary + - decided_at + properties: + attempt_id: + type: string + format: uuid + specialization: + type: 'null' + description: Express training does not assess a specialization. + target_grade: + type: 'null' + description: Express training does not assess a target grade. + task_language: + type: 'null' + kind: + type: string + enum: + - demo_express + mode: + type: string + enum: + - demo_express + versions: + $ref: '#/AssessmentVersions' + outcome: + type: string + enum: + - demonstration + not_determined_reason: + type: 'null' + confirmed_grade: + type: 'null' + description: Express training never confirms a grade. + previous_confirmed_grade: + type: 'null' + strength: + type: 'null' + calibration_status: + type: string + enum: + - uncalibrated + limitations: + type: array + minItems: 1 + maxItems: 1 + items: + type: string + enum: + - demonstration_only + uncertainty: + type: 'null' + description: Express training computes no ability estimate or percentile. + basic_score: + type: 'null' + practices: + type: array + maxItems: 0 + items: + $ref: '#/AssessmentPracticeResult' + gaps: + type: array + maxItems: 0 + items: + $ref: '#/AssessmentGap' + durations: + $ref: '#/AssessmentDurations' + next_steps: + type: array + maxItems: 0 + items: + $ref: '#/AssessmentNextStep' + summary: + type: string + minLength: 1 + maxLength: 2000 + description: Short educational feedback about this training run. + decided_at: + $ref: '#/Timestamp' AssessmentGradeAvailabilityStatus: type: string description: 'Whether an attempt for the grade can start now. @@ -1127,9 +1515,9 @@ AssessmentGradeAvailability: status: $ref: '#/AssessmentGradeAvailabilityStatus' mode: - description: Mode that an attempt would use, or null when the status is `insufficient_bank`. + description: Real-assessment mode that the server would use, or null when the status is `insufficient_bank`. `demo_express` is not a category assessment and is never returned here. oneOf: - - $ref: '#/AssessmentMode' + - $ref: '#/AssessmentRealMode' - type: 'null' available_at: description: When the status is `cooldown`, the first time the attempt can start; otherwise null. diff --git a/api/core/components/schemas/assessment_schemas.yml b/api/core/components/schemas/assessment_schemas.yml index ecfec44..d1d13e1 100644 --- a/api/core/components/schemas/assessment_schemas.yml +++ b/api/core/components/schemas/assessment_schemas.yml @@ -2,15 +2,30 @@ schemas: AssessmentMode: type: string description: |- - Measurement method of an attempt. The server selects it from the published task bank of the category; the client never chooses it. + Method of an assessment attempt. For a real assessment, the server selects demo_basic or adaptive from the published bank. A candidate may explicitly request demo_express, which uses a separate training policy and creates no qualification evidence. - demo_basic: a fixed form of reviewed demo items scored by their keys against the pass mark of the versioned basic grading policy. It computes no ability estimate, standard error, or probability, so every uncertainty field of its result is null, its thresholds are uncalibrated, and its decision is binary: it never offers an additional practice. - adaptive: the adaptive test on task families with an ability estimate, its standard error, and the probability of reaching the grade threshold, as the versioned assessment policy defines them. A probability in the band below confirmation offers one additional practice in the same attempt. + - demo_express: an interactive 3 to 5 minute training run under a separate policy. It does not assign a category or percentile, count toward the real-assessment quota, or create qualification evidence. Adding a value is a contract change. enum: - demo_basic + - demo_express - adaptive + AssessmentRealMode: + type: string + description: Server-selected mode available to a real category assessment. + enum: + - demo_basic + - adaptive + AssessmentAttemptKind: + type: string + description: Assessment track that distinguishes root, corrective, and training attempts. + enum: + - root + - corrective + - demo_express AssessmentAttemptVersion: type: integer format: int64 @@ -19,12 +34,10 @@ schemas: Version of an assessment attempt. A new attempt has version 1, and each committed change advances it by exactly one: an accepted answer, a practice submission or resubmission, a verdict, a decision of - finalize, a session start, and a server-side transition such as - expiry or automatic finalization. A transition that the server applies - when the attempt is read is committed before the response and also - advances it. A rejected command and a repeat that stores nothing leave - it unchanged. Commands send the version they read as - `expected_version`. + finalize, an explicit work-session start, and a server-side transition + such as expiry or automatic finalization. Reads never change the + attempt. A rejected command and a repeat that stores nothing leave it + unchanged. Commands send the version they read as `expected_version`. examples: - 4 AssessmentAttemptState: @@ -40,7 +53,7 @@ schemas: - expired: the time or session limit passed before the candidate finished the required parts. The result is available and confirms no grade. - insufficient_bank: the published bank could not supply the items required for coverage within the limit, and the attempt ended without a confirmed grade instead of repeating families. The result is available. - When `expires_at` passes or the session limit is reached, a practice submitted before that and still `pending` is graded first. Then the server decides without another command: `ready_to_finalize` is finalized and becomes `completed`; `additional_practice_pending` with the additional practice not submitted is finalized as declined and becomes `completed` with `not_confirmed`; `in_progress` and `practice_pending` become `expired`, with the result reason `expired` or `practice_incomplete`; and when the latest submission of a practice ended `failed`, the attempt becomes `expired` with the reason `sandbox_unavailable`, which is not the candidate's fault. `completed`, `expired`, and `insufficient_bank` are terminal and accept no command except the repeat of finalize described on FinalizeMyAssessmentAttempt. Adding a value is a contract change. + When `expires_at` passes or the session limit is reached, a read returns the stored state without changing it. A command or background transition commits any due outcome and advances the version. A practice submitted before the limit and still `pending` is graded first. Then `ready_to_finalize` becomes `completed`; `additional_practice_pending` with the additional practice not submitted is finalized as declined and becomes `completed` with `not_confirmed`; `in_progress` and `practice_pending` become `expired`, with the result reason `expired` or `practice_incomplete`; and when the latest submission of a practice ended `failed`, the attempt becomes `expired` with the reason `sandbox_unavailable`, which is not the candidate's fault. `completed`, `expired`, and `insufficient_bank` are terminal and accept no command except the repeat of finalize described on FinalizeMyAssessmentAttempt. Adding a value is a contract change. enum: - in_progress - practice_pending @@ -87,7 +100,7 @@ schemas: description: |- Work sessions of the attempt, as the policy version limits them, for example two sessions within the time limit. - A session starts with the creation of the attempt or, after the previous session ended, with the next GetMyAssessmentAttempt or command on the active attempt. It ends after `idle_timeout_seconds` without such a request. A request that would start a session beyond `max_sessions` starts none: the server moves the attempt to `expired` and answers with it (a read) or with 409 state_conflict (a command). Reading a terminal attempt or a result never starts a session. + Session 1 starts with attempt creation. After it ends due to `idle_timeout_seconds` of inactivity, the candidate explicitly starts or resumes work with StartMyAssessmentAttemptSession. GetMyAssessmentAttempt and GetMyAssessmentResult are read-only and never start a session. The session command checks the attempt deadline and `max_sessions`; when either limit has passed, it records the due terminal transition and returns the resulting attempt. Reads of terminal attempts do not change them. additionalProperties: false required: - used @@ -112,18 +125,41 @@ schemas: maximum: 86400 description: Inactivity after which the current session ends. AssessmentAttemptCreate: + description: >- + Start a real assessment, a corrective attempt in an existing chain, or + an explicit training run. The required `kind` discriminator selects + one of the three request shapes; `mode` remains server-selected for + real assessments. + oneOf: + - $ref: "#/schemas/AssessmentQualifiedAttemptCreate" + - $ref: "#/schemas/AssessmentCorrectiveAttemptCreate" + - $ref: "#/schemas/AssessmentExpressAttemptCreate" + discriminator: + propertyName: kind + mapping: + root: "#/schemas/AssessmentQualifiedAttemptCreate" + corrective: "#/schemas/AssessmentCorrectiveAttemptCreate" + demo_express: "#/schemas/AssessmentExpressAttemptCreate" + AssessmentQualifiedAttemptCreate: type: object description: >- - Category to assess: a specialization and the target grade, with the - task language. The candidate comes from the session. The mode and - versions are chosen by the server; unknown fields such as `mode`, - `seed`, or `score` are rejected. + 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. additionalProperties: false required: + - kind - specialization - target_grade - task_language properties: + kind: + type: string + enum: + - root + description: Start a real-assessment chain and reserve one root quota slot. specialization: $ref: "./catalog_schemas.yml#/schemas/SpecializationCode" target_grade: @@ -137,6 +173,64 @@ schemas: oneOf: - $ref: "./catalog_schemas.yml#/schemas/TaskLanguage" - type: "null" + AssessmentCorrectiveAttemptCreate: + type: object + description: >- + 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 is never supplied by the client. + additionalProperties: false + required: + - kind + - specialization + - target_grade + - task_language + - root_attempt_id + properties: + kind: + type: string + enum: + - corrective + description: Continue the existing real-assessment chain without reserving another root slot. + specialization: + $ref: "./catalog_schemas.yml#/schemas/SpecializationCode" + target_grade: + $ref: "./catalog_schemas.yml#/schemas/GradeCode" + task_language: + description: Task language of the attempt, or null when the bank offers no choice. + oneOf: + - $ref: "./catalog_schemas.yml#/schemas/TaskLanguage" + - type: "null" + root_attempt_id: + type: string + format: uuid + description: Root real-assessment attempt whose quota and deadline this attempt shares. + AssessmentExpressAttemptCreate: + type: object + description: >- + 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. + additionalProperties: false + required: + - kind + properties: + kind: + type: string + enum: + - demo_express + description: Explicitly request the training run; real modes cannot be selected by the client. + AssessmentAttemptSessionStart: + type: object + description: Start or resume a work session using the attempt version last read by the candidate. + additionalProperties: false + required: + - expected_version + properties: + expected_version: + $ref: "#/schemas/AssessmentAttemptVersion" AssessmentItemId: type: string format: uuid @@ -593,16 +687,29 @@ schemas: - $ref: "#/schemas/PracticeFailureReason" - type: "null" AssessmentAttempt: + description: >- + Candidate view of a real assessment, a corrective real assessment, or + a demo_express training run. The variants keep training output separate + from qualification attempts. + oneOf: + - $ref: "#/schemas/AssessmentQualifiedAttempt" + - $ref: "#/schemas/AssessmentCorrectiveAttempt" + - $ref: "#/schemas/AssessmentExpressAttempt" + discriminator: + propertyName: kind + mapping: + root: "#/schemas/AssessmentQualifiedAttempt" + corrective: "#/schemas/AssessmentCorrectiveAttempt" + demo_express: "#/schemas/AssessmentExpressAttempt" + AssessmentAttemptCommon: type: object description: >- - Assessment attempt of the current candidate for one category, a - specialization and a target grade. It shows the state, the fixed - versions, the server deadline `expires_at` from the policy version, - which the client clock never extends, the session limit, the - progress, the item - to answer now, and the practices. It never contains answer keys, the - correctness of submitted answers, scores of single items, family or - variant identifiers, seeds, hidden checks, or anti-cheat signals. + 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. additionalProperties: false required: - id @@ -610,6 +717,7 @@ schemas: - specialization - target_grade - task_language + - kind - mode - state - versions @@ -628,14 +736,40 @@ schemas: version: $ref: "#/schemas/AssessmentAttemptVersion" specialization: - $ref: "./catalog_schemas.yml#/schemas/SpecializationCode" + description: Null only for demo_express, which has no qualification category. + oneOf: + - $ref: "./catalog_schemas.yml#/schemas/SpecializationCode" + - type: "null" target_grade: - $ref: "./catalog_schemas.yml#/schemas/GradeCode" + description: Null only for demo_express, which has no qualification category. + oneOf: + - $ref: "./catalog_schemas.yml#/schemas/GradeCode" + - type: "null" task_language: - description: Task language of the attempt, or null when the bank offers no choice. + description: Task language of the attempt, or null when none is selected. oneOf: - $ref: "./catalog_schemas.yml#/schemas/TaskLanguage" - type: "null" + kind: + $ref: "#/schemas/AssessmentAttemptKind" + root_attempt_id: + description: >- + Present only for a corrective real assessment. It identifies the + root attempt whose quota and chain deadline this attempt shares. + oneOf: + - type: string + format: uuid + - type: "null" + readOnly: true + chain_deadline: + description: >- + Present only for a corrective real assessment. It is the immutable + deadline derived from the root attempt and is not extended by a + lower target grade. + oneOf: + - $ref: "./common_schemas.yml#/schemas/Timestamp" + - type: "null" + readOnly: true mode: $ref: "#/schemas/AssessmentMode" state: @@ -645,18 +779,18 @@ schemas: started_at: $ref: "./common_schemas.yml#/schemas/Timestamp" expires_at: + description: >- + Server deadline. For demo_express it is 180 to 300 seconds after + started_at; for a corrective assessment it does not exceed + chain_deadline. $ref: "./common_schemas.yml#/schemas/Timestamp" sessions: - description: >- - Session limit of the attempt, or null when its policy version - defines none. + description: Session limit of the attempt, or null when its policy defines none. oneOf: - $ref: "#/schemas/AssessmentSessions" - type: "null" finished_at: - description: >- - Time the attempt reached a terminal state, or null while it is - active. + description: Time the attempt reached a terminal state, or null while it is active. oneOf: - $ref: "./common_schemas.yml#/schemas/Timestamp" - type: "null" @@ -675,14 +809,104 @@ schemas: type: array maxItems: 5 description: >- - Practices in the order they were assigned: the `main` practice - first, then an `additional` practice once finalize offers it. Empty - only for a demo_basic attempt while code practice is disabled until - the sandbox isolation is verified; its result then lists the - `practice_not_included` limitation. A list rather than one field - leaves room for more practices without a breaking change. + Practices in the order assigned by the mode policy. The list + exposes verdicts only after submission. items: $ref: "#/schemas/AssessmentPractice" + AssessmentQualifiedAttempt: + allOf: + - $ref: "#/schemas/AssessmentAttemptCommon" + - type: object + properties: + kind: + type: string + enum: + - root + mode: + type: string + enum: + - demo_basic + - adaptive + specialization: + $ref: "./catalog_schemas.yml#/schemas/SpecializationCode" + target_grade: + $ref: "./catalog_schemas.yml#/schemas/GradeCode" + root_attempt_id: + type: "null" + description: Root attempts have no parent attempt. + chain_deadline: + type: "null" + description: A root attempt has no correction-chain deadline. + required: + - kind + - mode + - specialization + - target_grade + - root_attempt_id + - chain_deadline + AssessmentCorrectiveAttempt: + allOf: + - $ref: "#/schemas/AssessmentAttemptCommon" + - type: object + properties: + kind: + type: string + enum: + - corrective + mode: + type: string + enum: + - demo_basic + - adaptive + specialization: + $ref: "./catalog_schemas.yml#/schemas/SpecializationCode" + target_grade: + $ref: "./catalog_schemas.yml#/schemas/GradeCode" + root_attempt_id: + type: string + format: uuid + readOnly: true + chain_deadline: + $ref: "./common_schemas.yml#/schemas/Timestamp" + readOnly: true + required: + - kind + - mode + - specialization + - target_grade + - root_attempt_id + - chain_deadline + AssessmentExpressAttempt: + allOf: + - $ref: "#/schemas/AssessmentAttemptCommon" + - type: object + properties: + kind: + type: string + enum: + - demo_express + mode: + type: string + enum: + - demo_express + specialization: + type: "null" + target_grade: + type: "null" + task_language: + type: "null" + root_attempt_id: + type: "null" + chain_deadline: + type: "null" + required: + - kind + - mode + - specialization + - target_grade + - task_language + - root_attempt_id + - chain_deadline ChoiceAnswer: type: object description: >- @@ -894,12 +1118,12 @@ schemas: AssessmentNotDeterminedReason: type: string description: |- - Why an attempt gives no decision, and whether it counts against the retry rules. + Why an attempt gives no decision. One root quota slot is reserved when a real root attempt starts; corrective checks in its chain do not reserve another slot. - - expired: the time or session limit passed before the candidate finished the item part. It is the candidate's attempt: it counts toward the attempt limit and starts the same-grade retry interval. - - practice_incomplete: the item part was done, but the candidate did not submit the main practice before the limit. It counts like `expired`. - - insufficient_bank: the bank could not supply the required coverage within the limit. It is a platform limitation: it never counts toward the attempt limit and starts no retry interval. - - sandbox_unavailable: the latest submission of a required or additional practice ended `failed` because of the sandbox infrastructure, and the limit passed before a verdict. It is a platform fault: it never counts toward the attempt limit and starts no retry interval. + - expired: the time or session limit passed before the candidate finished the item part. Retry timing follows the recorded policy; a correction uses the existing root slot and does not reset the chain deadline or 30/90-day timers. + - practice_incomplete: the item part was done, but the candidate did not submit the main practice before the limit. Retry timing follows the recorded policy; a correction uses the existing root slot and does not reset the chain deadline or 30/90-day timers. + - insufficient_bank: the bank could not supply required coverage. A preflight refusal creates no attempt or root slot; a bank failure in an existing chain does not create a free new chain or another root slot. + - sandbox_unavailable: the latest submission of a required or additional practice ended `failed` because of the sandbox infrastructure, and the limit passed before a verdict. It is a platform fault and does not create a new root slot or a free chain. enum: - expired - practice_incomplete @@ -926,13 +1150,12 @@ schemas: AssessmentLimitation: type: string description: |- - Known limitation of the method behind a result, shown with the result. + Known limitation of the method behind a real-assessment result, shown with the result. - uncalibrated_thresholds: the thresholds are not yet validated on a pilot. - demo_bank: the result comes from the small reviewed demo bank. - practice_not_included: the attempt had no code practice because the sandbox was not enabled. - unproctored: the attempt was taken online without supervision. - Adding a value is a contract change. enum: - uncalibrated_thresholds @@ -1093,21 +1316,36 @@ schemas: - $ref: "./common_schemas.yml#/schemas/Timestamp" - type: "null" AssessmentResult: + description: >- + Immutable result of a terminal assessment attempt. The result shape + distinguishes real grade decisions from demo_express training output. + oneOf: + - $ref: "#/schemas/AssessmentQualifiedResult" + - $ref: "#/schemas/AssessmentCorrectiveResult" + - $ref: "#/schemas/AssessmentExpressResult" + discriminator: + propertyName: kind + mapping: + root: "#/schemas/AssessmentQualifiedResult" + corrective: "#/schemas/AssessmentCorrectiveResult" + demo_express: "#/schemas/AssessmentExpressResult" + AssessmentRealResultCommon: type: object description: >- - Immutable result of a terminal attempt, visible only to its candidate. - It records the method, the versions, the decision, its uncertainty, - and its limitations; a later policy, bank, or algorithm version never - changes it. It never contains answers, per-item correctness, answer - keys, seeds, hidden checks, or anti-cheat signals. Fields that the - method does not compute are null, never zero: demo_basic has null - `uncertainty` and `strength`, and adaptive has null `basic_score`. + Immutable result of a real assessment, visible only to its candidate. + It records the method, versions, decision, uncertainty, and + limitations. A corrective result also carries root_attempt_id and + chain_deadline from the same chain. Later policy, bank, or algorithm + versions never change it. It never contains answers, per-item + correctness, keys, seeds, hidden checks, or anti-cheat signals. + Fields the method does not compute are null, never zero. additionalProperties: false required: - attempt_id - specialization - target_grade - task_language + - kind - mode - versions - outcome @@ -1132,12 +1370,37 @@ schemas: $ref: "./catalog_schemas.yml#/schemas/SpecializationCode" target_grade: $ref: "./catalog_schemas.yml#/schemas/GradeCode" + root_attempt_id: + description: >- + Root attempt of a corrective check, or null when this is not a + corrective result. The corrective attempt keeps this link. + oneOf: + - type: string + format: uuid + - type: "null" + readOnly: true + chain_deadline: + description: >- + Immutable deadline shared by a corrective chain, or null when + this result is not from a corrective check. + oneOf: + - $ref: "./common_schemas.yml#/schemas/Timestamp" + - type: "null" + readOnly: true task_language: oneOf: - $ref: "./catalog_schemas.yml#/schemas/TaskLanguage" - type: "null" + kind: + type: string + enum: + - root + - corrective mode: - $ref: "#/schemas/AssessmentMode" + type: string + enum: + - demo_basic + - adaptive versions: $ref: "#/schemas/AssessmentVersions" outcome: @@ -1209,6 +1472,156 @@ schemas: $ref: "#/schemas/AssessmentNextStep" decided_at: $ref: "./common_schemas.yml#/schemas/Timestamp" + AssessmentQualifiedResult: + description: >- + Result of a real assessment that is not a corrective attempt. The + correction-chain fields are explicitly null. + allOf: + - $ref: "#/schemas/AssessmentRealResultCommon" + - type: object + properties: + kind: + type: string + enum: + - root + root_attempt_id: + type: "null" + chain_deadline: + type: "null" + required: + - kind + - root_attempt_id + - chain_deadline + AssessmentCorrectiveResult: + description: >- + Result of a corrective real assessment. Both chain fields are present + and identify the same immutable correction chain. + allOf: + - $ref: "#/schemas/AssessmentRealResultCommon" + - type: object + properties: + kind: + type: string + enum: + - corrective + root_attempt_id: + type: string + format: uuid + readOnly: true + chain_deadline: + $ref: "./common_schemas.yml#/schemas/Timestamp" + readOnly: true + required: + - kind + - root_attempt_id + - chain_deadline + AssessmentExpressResult: + type: object + description: >- + Immutable educational result of a demo_express run. It includes a + short summary but cannot report a category, percentile, uncertainty, + grade, strength, or qualification evidence. The result belongs only + to the training mode and does not consume a real-assessment quota. + additionalProperties: false + required: + - attempt_id + - specialization + - target_grade + - task_language + - kind + - mode + - versions + - outcome + - not_determined_reason + - confirmed_grade + - previous_confirmed_grade + - strength + - calibration_status + - limitations + - uncertainty + - basic_score + - practices + - gaps + - durations + - next_steps + - summary + - decided_at + properties: + attempt_id: + type: string + format: uuid + specialization: + type: "null" + description: Express training does not assess a specialization. + target_grade: + type: "null" + description: Express training does not assess a target grade. + task_language: + type: "null" + kind: + type: string + enum: + - demo_express + mode: + type: string + enum: + - demo_express + versions: + $ref: "#/schemas/AssessmentVersions" + outcome: + type: string + enum: + - demonstration + not_determined_reason: + type: "null" + confirmed_grade: + type: "null" + description: Express training never confirms a grade. + previous_confirmed_grade: + type: "null" + strength: + type: "null" + calibration_status: + type: string + enum: + - uncalibrated + limitations: + type: array + minItems: 1 + maxItems: 1 + items: + type: string + enum: + - demonstration_only + uncertainty: + type: "null" + description: Express training computes no ability estimate or percentile. + basic_score: + type: "null" + practices: + type: array + maxItems: 0 + items: + $ref: "#/schemas/AssessmentPracticeResult" + gaps: + type: array + maxItems: 0 + items: + $ref: "#/schemas/AssessmentGap" + durations: + $ref: "#/schemas/AssessmentDurations" + next_steps: + type: array + maxItems: 0 + items: + $ref: "#/schemas/AssessmentNextStep" + summary: + type: string + minLength: 1 + maxLength: 2000 + description: Short educational feedback about this training run. + decided_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" AssessmentGradeAvailabilityStatus: type: string description: |- @@ -1247,10 +1660,11 @@ schemas: $ref: "#/schemas/AssessmentGradeAvailabilityStatus" mode: description: >- - Mode that an attempt would use, or null when the status is - `insufficient_bank`. + Real-assessment mode that the server would use, or null when the + status is `insufficient_bank`. `demo_express` is not a category + assessment and is never returned here. oneOf: - - $ref: "#/schemas/AssessmentMode" + - $ref: "#/schemas/AssessmentRealMode" - type: "null" available_at: description: When the status is `cooldown`, the first time the attempt can start; otherwise null. diff --git a/api/core/openapi.bundle.yml b/api/core/openapi.bundle.yml index 9bd2b46..ec45354 100644 --- a/api/core/openapi.bundle.yml +++ b/api/core/openapi.bundle.yml @@ -636,13 +636,13 @@ paths: /api/v1/me/assessment-attempts: post: operationId: CreateMyAssessmentAttempt - summary: Start an assessment attempt for a category of the current candidate. + summary: Start a real, corrective, or training assessment attempt. description: |- - Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The body names the category, a specialization of the questionnaire and a target grade, and the task language. The server picks the mode from the published bank, `demo_basic` or `adaptive`, and fixes the policy, bank, and algorithm versions, the time and session limits, and the item variants in one transaction; the client never sends a mode, a seed, or a version. Creation starts session 1. The self-assessed grade only chooses where the test starts and adds no points. An adaptive retest starts from the previous ability estimate of the specialization, adjusted for the time passed, so a new attempt adds evidence instead of starting the measurement over. + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The request is one of three disjoint shapes. A real assessment names a specialization, target grade, and task language; the server picks `demo_basic` or `adaptive` and fixes the policy, bank, and algorithm versions, limits, and item variants. A corrective real assessment also names `root_attempt_id`; the server verifies the lower-grade chain and reuses its fixed quota and deadline. The client never sends a real mode, a seed, a version, or a chain deadline. Explicit `demo_express` starts a separate interactive training run that lasts 3 to 5 minutes, has no category or target grade, and creates no qualification evidence or percentile. Creation starts session 1. The self-assessed grade only chooses where a real test starts and adds no points. An adaptive retest starts from the previous ability estimate of the specialization, adjusted for the time passed, so a new attempt adds evidence instead of starting the measurement over. - A specialization has at most one active attempt. A new attempt cannot start while one is active, during a retry or promotion interval or past the attempt limit of the policy, or when the bank is insufficient; each answers 409 state_conflict and creates nothing, not even a placeholder attempt. GetMyAssessmentAvailability tells which case applies and when a blocked attempt opens. After a failure, including the first test, a lower grade can be tested at once. An attempt that ends as `expired` or with the reason `practice_incomplete` counts toward the attempt limit and starts the same-grade retry interval; one that ends as `insufficient_bank` or with the reason `sandbox_unavailable` counts toward neither. + A specialization has at most one active real attempt. A new root attempt cannot start while one is active, during a retry or promotion interval, past the root quota, or when the bank is insufficient; each such preflight refusal answers 409 state_conflict and creates nothing or consumes no root slot. Starting a root attempt reserves one slot in the root quota. A corrective attempt must reference its root, target a strictly lower grade not already attempted in that chain, and remain inside the root's fixed quota and deadline (72 hours from the root start in the current policy). It gets its own item, practice, and session limits, but spends no additional root slot and cannot reset the chain deadline or any 30/90-day timer. After a failure, including the first test, a lower grade can be tested at once. An expired or incomplete attempt does not create a free new chain; an insufficient bank or sandbox failure does not grant another root slot. `demo_express` is outside real-assessment availability, quotas, retry intervals, and qualification history. - The limits are server-side: `expires_at` and `sessions` come from the policy version, the client clock never extends them, and after them the attempt accepts no command. Within them the attempt is also bounded by the item limit of the policy. + The limits are server-side: `expires_at` and `sessions` come from the policy version, the client clock never extends them, and after them the attempt accepts no work command. For a corrective attempt, `expires_at` is no later than the root's immutable `chain_deadline`. Within these limits the attempt is also bounded by the item limit of its policy. Idempotency: a retry with the same key and body within 24 hours replays the stored 201 or 409 state_conflict response and creates nothing, so a lost response never creates a second attempt. A different body with the same key answers 422 idempotency_key_reused. 400 is never stored, so a corrected retry is evaluated again. @@ -663,6 +663,18 @@ paths: examples: backend_junior_go: $ref: '#/components/examples/AssessmentAttemptCreateBackendJunior' + corrective_backend_junior_go: + summary: Start a lower-grade assessment inside an existing correction chain + value: + kind: corrective + specialization: backend + target_grade: junior + task_language: go + root_attempt_id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d + demo_express: + summary: Start a short educational training run + value: + kind: demo_express responses: '201': description: The attempt was created, or a retry with the same Idempotency-Key replayed its creation. @@ -676,6 +688,10 @@ paths: examples: demo_basic_created: $ref: '#/components/examples/AssessmentAttemptCreated' + corrective_created: + $ref: '#/components/examples/AssessmentCorrectiveAttemptCreated' + demo_express_created: + $ref: '#/components/examples/AssessmentExpressAttemptCreated' '400': $ref: '#/components/responses/AssessmentAttemptCreateValidationFailed' '401': @@ -693,13 +709,13 @@ paths: /api/v1/me/assessment-attempts/{attempt_id}: get: operationId: GetMyAssessmentAttempt - summary: Read or resume an assessment attempt of the current candidate. + summary: Read an assessment attempt of the current candidate. description: |- - Requires the session cookie of a candidate account. Returns the attempt with its state, fixed versions, time and session limits, progress, the item to answer now, and the practices. A reload, a retried request, or a new session returns the same item instance with the same text and option order; a lost connection never creates a new attempt. The response never says whether an earlier answer was correct and never contains answer keys, item scores, family or variant identifiers, seeds, hidden checks, or anti-cheat signals. + Requires the session cookie of a candidate account. Returns the stored attempt projection with its state, fixed versions, time and session limits, progress, the item to answer now, and the practices. This GET is read-only: it never starts or resumes a work session, consumes session quota, advances the version, or commits expiry or finalization. A reload, a retried request, or a new session returns the same item instance with the same text and option order; a lost connection never creates a new attempt. After `idle_timeout_seconds`, the candidate explicitly starts or resumes work with StartMyAssessmentAttemptSession. The response never says whether an earlier answer was correct and never contains answer keys, item scores, family or variant identifiers, seeds, hidden checks, or anti-cheat signals. - Reading an active attempt counts as activity: after the previous session ended it starts the next session, and when that would exceed the session limit it starts none and the attempt becomes `expired`. Before it answers, the server commits any transition that is due, with a new version: past `expires_at`, `ready_to_finalize` becomes `completed`, an unsubmitted additional practice is declined and the attempt becomes `completed`, and the other active states become `expired`; a practice still `pending` is graded first. The client polls this operation while a practice is `pending`. Reading a terminal attempt changes nothing. + When the deadline passes, this read still returns the stored state and deadline. A command or background transition commits the due outcome; if the stored state is still active, GetMyAssessmentResult answers 409 until that transition is committed. The client polls this operation while a practice is `pending`, but polling alone never changes attempt state. - The attempt must belong to the candidate of the session: an attempt of another candidate answers 404 not_found, the same as an unknown identifier, so identifiers cannot be probed. An employer account answers 403 forbidden; no operation gives an employer the answers or the attempt history. + The attempt must belong to the candidate of the session: an attempt of another candidate answers 404 not_found, the same as an unknown identifier, so identifiers cannot be probed. An employer account answers 403 forbidden; no operation gives an employer the answers, qualification evidence, or attempt history. security: - sessionCookie: [] tags: @@ -741,6 +757,67 @@ paths: $ref: '#/components/responses/NotFound' default: $ref: '#/components/responses/Problem' + /api/v1/me/assessment-attempts/{attempt_id}/sessions: + post: + operationId: StartMyAssessmentAttemptSession + summary: Start or resume a work session for the current candidate's attempt. + description: |- + Requires a candidate session, its CSRF token in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The body carries the attempt version the candidate last read. The server checks ownership, idempotency, and `expected_version` atomically before starting a session; a stale version answers 412 and consumes no session. Repeating the same key and body within 24 hours replays the stored response. + + Creation starts session 1. After `idle_timeout_seconds` of inactivity, the candidate uses this command to start the next session. Calling it while a session is already active returns the current attempt without consuming another session or advancing its version. Starting a session advances the version once. The command cannot extend `expires_at` or `chain_deadline`. + + If the attempt deadline or session budget has passed, this command commits the due terminal transition and returns the resulting attempt. A pending practice submitted before the limit is graded first. `GetMyAssessmentAttempt` and `GetMyAssessmentResult` remain read-only: they never start a session or commit a due transition. A background transition may persist a due outcome independently; after that, this command returns the stored terminal attempt without changing it. + + The attempt must belong to the candidate of the session. An attempt of another candidate answers 404 not_found, the same as an unknown identifier. An employer account answers 403 forbidden; no operation gives an employer answers, qualification evidence, or attempt history. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - assessment + parameters: + - $ref: '#/components/parameters/AssessmentAttemptId' + - $ref: '#/components/parameters/IdempotencyKey' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/AssessmentAttemptSessionStart' + example: + expected_version: 7 + responses: + '200': + description: The current attempt after starting or resuming work, or after a due terminal transition was committed. A replay returns the stored body. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/AssessmentAttempt' + examples: + resumed: + $ref: '#/components/examples/AssessmentAttemptResumed' + terminal: + $ref: '#/components/examples/AssessmentAttemptCompleted' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '404': + $ref: '#/components/responses/NotFound' + '409': + $ref: '#/components/responses/AssessmentCommandConflict' + '412': + $ref: '#/components/responses/AssessmentVersionConflict' + '422': + $ref: '#/components/responses/UnprocessableContent' + '429': + $ref: '#/components/responses/TooManyRequests' + default: + $ref: '#/components/responses/Problem' /api/v1/me/assessment-attempts/{attempt_id}/answers: post: operationId: SubmitMyAssessmentAnswer @@ -750,6 +827,8 @@ paths: The response is the attempt with the next item to answer. It never says whether the answer was correct. Items are answered in order and each answer is final. + A work command requires an active session. After `idle_timeout_seconds` of inactivity, the candidate calls StartMyAssessmentAttemptSession to explicitly start or resume a session; this answer command never starts one or consumes session quota. Reading the attempt or result is always read-only. A command that finds a due deadline transition may commit it before returning; a command that finds an expired idle session answers 409 until the candidate explicitly starts the next session. + Practice: an answer with format `practice` submits the solution of the main or the additional practice. It is stored, and the sandbox runs it asynchronously against the hidden check groups; the response shows the practice `pending`, and the client polls GetMyAssessmentAttempt for the verdict. Only the score 0-3 and the pass state of each group are shown, never the checks, error output, or seeds. Every outcome caused by the solution, such as a compilation error, a crash, or a time or memory limit, is a `finished` verdict. A `failed` verdict means only that the sandbox infrastructure could not run it; it consumes nothing. After `finished` the practice accepts no other solution, so hidden group results cannot be used to tune it. Debug runs of the candidate's own tests and the public examples are unlimited apart from the sandbox rate limit and never show hidden group results; they are planned as a separate operation. Repeats and conflicts, per item: @@ -760,7 +839,7 @@ paths: Optimistic concurrency: `expected_version` must equal the current attempt version, otherwise the server answers 412 version_conflict and stores nothing; the client reads the attempt again. 412 is the repository status for a stale version, also used by SaveMyQuestionnaire; 409 state_conflict is kept for commands that the attempt state does not allow at the current version. - Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the attempt (404 not_found for an unknown attempt or one of another candidate; the server first commits any due transition such as expiry, and the request counts as activity for the session limit), the repeat of the stored answer (200, skipped for a practice whose latest verdict is `failed`), the version (412), the state (409 state_conflict: the attempt is terminal, the item is not current, the item has a different answer, or the practice verdict is pending or finished), then the answer against the item (400 with a pointer such as `/answer/format` or `/answer/option_ids/0`). Following the Idempotency-Key convention, 404 and 409 state_conflict are stored under the key and replayed; 400, 412, 429, and 5xx are not. The rate limit can answer 429 with Retry-After before any check. + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the attempt (404 not_found for an unknown attempt or one of another candidate; a due deadline transition may be committed, but this request never starts a work session), the repeat of the stored answer (200, skipped for a practice whose latest verdict is `failed`), the version (412), the state (409 state_conflict: the attempt is terminal, the work session ended, the item is not current, the item has a different answer, or the practice verdict is pending or finished), then the answer against the item (400 with a pointer such as `/answer/format` or `/answer/option_ids/0`). Following the Idempotency-Key convention, 404 and 409 state_conflict are stored under the key and replayed; 400, 412, 429, and 5xx are not. The rate limit can answer 429 with Retry-After before any check. security: - sessionCookie: [] sessionCsrf: [] @@ -830,16 +909,18 @@ paths: description: |- Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. Finalize always answers with the attempt, never with the result: the decision may continue the attempt, and one response type keeps that unambiguous for every generated client. When the returned state is `completed`, the client reads the result with GetMyAssessmentResult. + Finalize is a work command and requires an active session. After `idle_timeout_seconds` of inactivity, the candidate first calls StartMyAssessmentAttemptSession with the latest `expected_version`; finalize never starts a session. GET attempt and result operations do not change state. A command or background transition may commit a due deadline outcome. + Allowed in `ready_to_finalize`, where every required part is done, and in `additional_practice_pending` while the additional practice is `not_started` or `failed`. The server decides from the stored answers with the policy, bank, and algorithm versions fixed at creation: - `demo_basic` compares the raw score with the pass mark of the recorded basic grading policy and completes the attempt. It never offers an additional practice. - `adaptive` applies the probability bands of the recorded policy. Confirmation or rejection completes the attempt. A probability in the band below confirmation (0.50 to below 0.80 in the demo policy) on the first finalize, while time and sessions remain, completes nothing: the server appends an `additional` practice, moves the attempt to `additional_practice_pending`, and answers 200 with it. The additional practice continues the same attempt, keeps its limits, and spends no new attempt. The next finalize, after its verdict, decides with the added evidence; a probability still below confirmation gives `not_confirmed`. An attempt offers at most one additional practice. - Finalize in `additional_practice_pending` declines the offer and gives `not_confirmed` with the current evidence. A retry of the first finalize with a new key cannot decline by accident: it carries the version from before the offer and answers 412. - A failed attempt never lowers a confirmed grade. Repeats return the same outcome: a retry with the same Idempotency-Key replays the stored response, and a finalize of a `completed` attempt answers 200 with that attempt even with a new key or an older `expected_version`; the result is computed once. When `expires_at` passes or the session limit is reached, the server finalizes `ready_to_finalize` itself, without offering an additional practice, so a finalize after that also answers 200 with the `completed` attempt. + A failed attempt never lowers a confirmed grade. Repeats return the same outcome: a retry with the same Idempotency-Key replays the stored response, and a finalize of a `completed` attempt answers 200 with that attempt even with a new key or an older `expected_version`; the result is computed once. When `expires_at` passes or the session limit is reached, a command or background transition finalizes `ready_to_finalize` without offering an additional practice. A finalize after this transition answers 200 with the stored `completed` attempt; a GET never commits it. An attempt in `in_progress` or `practice_pending`, one with a practice verdict `pending`, or one that ended as `expired` or `insufficient_bank` answers 409 state_conflict. The problem does not list what is unfinished; the attempt shows it in `state`, `progress`, `current_item`, and `practices`. A stale `expected_version` answers 412 version_conflict, the repository status for a stale version. - Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the attempt (404 not_found, after any due transition), the repeat on a `completed` attempt (200), the version (412), then the state (409 state_conflict). 404 and 409 state_conflict are stored under the key; 400 and 412 are not. + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the attempt (404 not_found; a due deadline transition may be committed, but this request never starts a work session), the repeat on a `completed` attempt (200), the version (412), then the state (409 state_conflict, including an ended idle session). 404 and 409 state_conflict are stored under the key; 400 and 412 are not. security: - sessionCookie: [] sessionCsrf: [] @@ -893,11 +974,11 @@ paths: operationId: GetMyAssessmentResult summary: Read the result of an assessment attempt of the current candidate. description: |- - Requires the session cookie of a candidate account. Returns the immutable result of a terminal attempt: `completed`, `expired`, or `insufficient_bank`. It records the mode, the policy, bank, and algorithm versions, the decision, the previously confirmed grade, the calibration status and limitations of the method, the uncertainty where the method computes it, the practice verdicts, the weak domains, the working time as a separate label, and the next steps that the server allows. A later policy, bank, or algorithm version never changes it. + Requires the session cookie of a candidate account. Returns the immutable result of a terminal attempt: `completed`, `expired`, or `insufficient_bank`. A real result records the mode, policy, bank, and algorithm versions, decision, previously confirmed grade, calibration status and limitations, uncertainty where the method computes it, practice verdicts, weak domains, working time as a separate label, and allowed next steps. A corrective result also carries the root attempt and its immutable chain deadline. A `demo_express` result is a short educational summary only: it has no category, percentile, confirmed grade, score, uncertainty, or qualification evidence. A later policy, bank, or algorithm version never changes a result. Fields that the method does not compute are null and never zero: a `demo_basic` result has null `uncertainty` and `strength`. The result never contains answers, per-item correctness, answer keys, seeds, hidden checks, or anti-cheat signals. - An active attempt answers 409 state_conflict; an attempt in `additional_practice_pending` is active and has no result yet. The server first commits any due transition, so an attempt past its limits is read as terminal. An attempt of another candidate answers 404 not_found, the same as an unknown identifier. An employer account answers 403 forbidden; employers see only the current category through a separate projection, never this result or the attempt history. + An active attempt answers 409 state_conflict; an attempt in `additional_practice_pending` is active and has no result yet. This GET is read-only and never commits a due transition. If a deadline has passed but the due transition is not yet stored by a command or background worker, the attempt remains active for this read and answers 409; wait for the transition and retry. An attempt of another candidate answers 404 not_found, the same as an unknown identifier. An employer account answers 403 forbidden; employers see only the current category through a separate projection, never this result or the attempt history. security: - sessionCookie: [] tags: @@ -923,6 +1004,10 @@ paths: $ref: '#/components/examples/AssessmentNotConfirmedResult' insufficient_bank: $ref: '#/components/examples/AssessmentInsufficientBankResult' + corrective: + $ref: '#/components/examples/AssessmentCorrectiveResult' + demo_express: + $ref: '#/components/examples/AssessmentExpressResult' '401': $ref: '#/components/responses/Unauthenticated' '403': @@ -4115,20 +4200,22 @@ components: AssessmentMode: type: string description: |- - Measurement method of an attempt. The server selects it from the published task bank of the category; the client never chooses it. + Method of an assessment attempt. For a real assessment, the server selects demo_basic or adaptive from the published bank. A candidate may explicitly request demo_express, which uses a separate training policy and creates no qualification evidence. - demo_basic: a fixed form of reviewed demo items scored by their keys against the pass mark of the versioned basic grading policy. It computes no ability estimate, standard error, or probability, so every uncertainty field of its result is null, its thresholds are uncalibrated, and its decision is binary: it never offers an additional practice. - adaptive: the adaptive test on task families with an ability estimate, its standard error, and the probability of reaching the grade threshold, as the versioned assessment policy defines them. A probability in the band below confirmation offers one additional practice in the same attempt. + - demo_express: an interactive 3 to 5 minute training run under a separate policy. It does not assign a category or percentile, count toward the real-assessment quota, or create qualification evidence. Adding a value is a contract change. enum: - demo_basic + - demo_express - adaptive AssessmentAttemptVersion: type: integer format: int64 minimum: 1 - description: 'Version of an assessment attempt. A new attempt has version 1, and each committed change advances it by exactly one: an accepted answer, a practice submission or resubmission, a verdict, a decision of finalize, a session start, and a server-side transition such as expiry or automatic finalization. A transition that the server applies when the attempt is read is committed before the response and also advances it. A rejected command and a repeat that stores nothing leave it unchanged. Commands send the version they read as `expected_version`.' + description: 'Version of an assessment attempt. A new attempt has version 1, and each committed change advances it by exactly one: an accepted answer, a practice submission or resubmission, a verdict, a decision of finalize, an explicit work-session start, and a server-side transition such as expiry or automatic finalization. Reads never change the attempt. A rejected command and a repeat that stores nothing leave it unchanged. Commands send the version they read as `expected_version`.' examples: - 4 AssessmentAttemptState: @@ -4144,7 +4231,7 @@ components: - expired: the time or session limit passed before the candidate finished the required parts. The result is available and confirms no grade. - insufficient_bank: the published bank could not supply the items required for coverage within the limit, and the attempt ended without a confirmed grade instead of repeating families. The result is available. - When `expires_at` passes or the session limit is reached, a practice submitted before that and still `pending` is graded first. Then the server decides without another command: `ready_to_finalize` is finalized and becomes `completed`; `additional_practice_pending` with the additional practice not submitted is finalized as declined and becomes `completed` with `not_confirmed`; `in_progress` and `practice_pending` become `expired`, with the result reason `expired` or `practice_incomplete`; and when the latest submission of a practice ended `failed`, the attempt becomes `expired` with the reason `sandbox_unavailable`, which is not the candidate's fault. `completed`, `expired`, and `insufficient_bank` are terminal and accept no command except the repeat of finalize described on FinalizeMyAssessmentAttempt. Adding a value is a contract change. + When `expires_at` passes or the session limit is reached, a read returns the stored state without changing it. A command or background transition commits any due outcome and advances the version. A practice submitted before the limit and still `pending` is graded first. Then `ready_to_finalize` becomes `completed`; `additional_practice_pending` with the additional practice not submitted is finalized as declined and becomes `completed` with `not_confirmed`; `in_progress` and `practice_pending` become `expired`, with the result reason `expired` or `practice_incomplete`; and when the latest submission of a practice ended `failed`, the attempt becomes `expired` with the reason `sandbox_unavailable`, which is not the candidate's fault. `completed`, `expired`, and `insufficient_bank` are terminal and accept no command except the repeat of finalize described on FinalizeMyAssessmentAttempt. Adding a value is a contract change. enum: - in_progress - practice_pending @@ -4182,7 +4269,7 @@ components: description: |- Work sessions of the attempt, as the policy version limits them, for example two sessions within the time limit. - A session starts with the creation of the attempt or, after the previous session ended, with the next GetMyAssessmentAttempt or command on the active attempt. It ends after `idle_timeout_seconds` without such a request. A request that would start a session beyond `max_sessions` starts none: the server moves the attempt to `expired` and answers with it (a read) or with 409 state_conflict (a command). Reading a terminal attempt or a result never starts a session. + Session 1 starts with attempt creation. After it ends due to `idle_timeout_seconds` of inactivity, the candidate explicitly starts or resumes work with StartMyAssessmentAttemptSession. GetMyAssessmentAttempt and GetMyAssessmentResult are read-only and never start a session. The session command checks the attempt deadline and `max_sessions`; when either limit has passed, it records the due terminal transition and returns the resulting attempt. Reads of terminal attempts do not change them. additionalProperties: false required: - used @@ -4207,23 +4294,26 @@ components: maximum: 86400 description: Inactivity after which the current session ends. AssessmentAttemptCreate: + description: Start a real assessment, a corrective attempt in an existing chain, or an explicit training run. The required `kind` discriminator selects one of the three request shapes; `mode` remains server-selected for real assessments. + oneOf: + - $ref: '#/components/schemas/AssessmentQualifiedAttemptCreate' + - $ref: '#/components/schemas/AssessmentCorrectiveAttemptCreate' + - $ref: '#/components/schemas/AssessmentExpressAttemptCreate' + discriminator: + propertyName: kind + mapping: + root: '#/components/schemas/AssessmentQualifiedAttemptCreate' + corrective: '#/components/schemas/AssessmentCorrectiveAttemptCreate' + demo_express: '#/components/schemas/AssessmentExpressAttemptCreate' + AssessmentAttemptSessionStart: type: object - description: 'Category to assess: a specialization and the target grade, with the task language. The candidate comes from the session. The mode and versions are chosen by the server; unknown fields such as `mode`, `seed`, or `score` are rejected.' + description: Start or resume a work session using the attempt version last read by the candidate. additionalProperties: false required: - - specialization - - target_grade - - task_language + - expected_version properties: - specialization: - $ref: '#/components/schemas/SpecializationCode' - target_grade: - $ref: '#/components/schemas/GradeCode' - task_language: - description: Task language of the attempt, one of the `task_languages` of the published bank, or null when the bank offers no choice of language. The questionnaire choice is the value the client offers first. - oneOf: - - $ref: '#/components/schemas/TaskLanguage' - - type: 'null' + expected_version: + $ref: '#/components/schemas/AssessmentAttemptVersion' AssessmentItemId: type: string format: uuid @@ -4614,74 +4704,17 @@ components: - $ref: '#/components/schemas/PracticeFailureReason' - type: 'null' AssessmentAttempt: - type: object - description: Assessment attempt of the current candidate for one category, a specialization and a target grade. It shows the state, the fixed versions, the server deadline `expires_at` from the policy version, which the client clock never extends, the session limit, the progress, the item to answer now, and the practices. It never contains answer keys, the correctness of submitted answers, scores of single items, family or variant identifiers, seeds, hidden checks, or anti-cheat signals. - additionalProperties: false - required: - - id - - version - - specialization - - target_grade - - task_language - - mode - - state - - versions - - started_at - - expires_at - - sessions - - finished_at - - progress - - current_item - - practices - properties: - id: - type: string - format: uuid - description: Attempt identifier. - version: - $ref: '#/components/schemas/AssessmentAttemptVersion' - specialization: - $ref: '#/components/schemas/SpecializationCode' - target_grade: - $ref: '#/components/schemas/GradeCode' - task_language: - description: Task language of the attempt, or null when the bank offers no choice. - oneOf: - - $ref: '#/components/schemas/TaskLanguage' - - type: 'null' - mode: - $ref: '#/components/schemas/AssessmentMode' - state: - $ref: '#/components/schemas/AssessmentAttemptState' - versions: - $ref: '#/components/schemas/AssessmentVersions' - started_at: - $ref: '#/components/schemas/Timestamp' - expires_at: - $ref: '#/components/schemas/Timestamp' - sessions: - description: Session limit of the attempt, or null when its policy version defines none. - oneOf: - - $ref: '#/components/schemas/AssessmentSessions' - - type: 'null' - finished_at: - description: Time the attempt reached a terminal state, or null while it is active. - oneOf: - - $ref: '#/components/schemas/Timestamp' - - type: 'null' - progress: - $ref: '#/components/schemas/AssessmentProgress' - current_item: - description: 'Item to answer now: a test item in `in_progress`, the practice item to submit in `practice_pending` or `additional_practice_pending` while that practice is `not_started` or `failed`, and null otherwise.' - oneOf: - - $ref: '#/components/schemas/AssessmentItem' - - type: 'null' - practices: - type: array - maxItems: 5 - description: 'Practices in the order they were assigned: the `main` practice first, then an `additional` practice once finalize offers it. Empty only for a demo_basic attempt while code practice is disabled until the sandbox isolation is verified; its result then lists the `practice_not_included` limitation. A list rather than one field leaves room for more practices without a breaking change.' - items: - $ref: '#/components/schemas/AssessmentPractice' + description: Candidate view of a real assessment, a corrective real assessment, or a demo_express training run. The variants keep training output separate from qualification attempts. + oneOf: + - $ref: '#/components/schemas/AssessmentQualifiedAttempt' + - $ref: '#/components/schemas/AssessmentCorrectiveAttempt' + - $ref: '#/components/schemas/AssessmentExpressAttempt' + discriminator: + propertyName: kind + mapping: + root: '#/components/schemas/AssessmentQualifiedAttempt' + corrective: '#/components/schemas/AssessmentCorrectiveAttempt' + demo_express: '#/components/schemas/AssessmentExpressAttempt' ChoiceAnswer: type: object description: 'Selected options of a choice item: exactly one unless the item allows several. Two answers are equal when they select the same set of options, in any order.' @@ -4862,12 +4895,12 @@ components: AssessmentNotDeterminedReason: type: string description: |- - Why an attempt gives no decision, and whether it counts against the retry rules. + Why an attempt gives no decision. One root quota slot is reserved when a real root attempt starts; corrective checks in its chain do not reserve another slot. - - expired: the time or session limit passed before the candidate finished the item part. It is the candidate's attempt: it counts toward the attempt limit and starts the same-grade retry interval. - - practice_incomplete: the item part was done, but the candidate did not submit the main practice before the limit. It counts like `expired`. - - insufficient_bank: the bank could not supply the required coverage within the limit. It is a platform limitation: it never counts toward the attempt limit and starts no retry interval. - - sandbox_unavailable: the latest submission of a required or additional practice ended `failed` because of the sandbox infrastructure, and the limit passed before a verdict. It is a platform fault: it never counts toward the attempt limit and starts no retry interval. + - expired: the time or session limit passed before the candidate finished the item part. Retry timing follows the recorded policy; a correction uses the existing root slot and does not reset the chain deadline or 30/90-day timers. + - practice_incomplete: the item part was done, but the candidate did not submit the main practice before the limit. Retry timing follows the recorded policy; a correction uses the existing root slot and does not reset the chain deadline or 30/90-day timers. + - insufficient_bank: the bank could not supply required coverage. A preflight refusal creates no attempt or root slot; a bank failure in an existing chain does not create a free new chain or another root slot. + - sandbox_unavailable: the latest submission of a required or additional practice ended `failed` because of the sandbox infrastructure, and the limit passed before a verdict. It is a platform fault and does not create a new root slot or a free chain. enum: - expired - practice_incomplete @@ -4888,13 +4921,12 @@ components: AssessmentLimitation: type: string description: |- - Known limitation of the method behind a result, shown with the result. + Known limitation of the method behind a real-assessment result, shown with the result. - uncalibrated_thresholds: the thresholds are not yet validated on a pilot. - demo_bank: the result comes from the small reviewed demo bank. - practice_not_included: the attempt had no code practice because the sandbox was not enabled. - unproctored: the attempt was taken online without supervision. - Adding a value is a contract change. enum: - uncalibrated_thresholds @@ -5044,107 +5076,17 @@ components: - $ref: '#/components/schemas/Timestamp' - type: 'null' AssessmentResult: - type: object - description: 'Immutable result of a terminal attempt, visible only to its candidate. It records the method, the versions, the decision, its uncertainty, and its limitations; a later policy, bank, or algorithm version never changes it. It never contains answers, per-item correctness, answer keys, seeds, hidden checks, or anti-cheat signals. Fields that the method does not compute are null, never zero: demo_basic has null `uncertainty` and `strength`, and adaptive has null `basic_score`.' - additionalProperties: false - required: - - attempt_id - - specialization - - target_grade - - task_language - - mode - - versions - - outcome - - not_determined_reason - - confirmed_grade - - previous_confirmed_grade - - strength - - calibration_status - - limitations - - uncertainty - - basic_score - - practices - - gaps - - durations - - next_steps - - decided_at - properties: - attempt_id: - type: string - format: uuid - specialization: - $ref: '#/components/schemas/SpecializationCode' - target_grade: - $ref: '#/components/schemas/GradeCode' - task_language: - oneOf: - - $ref: '#/components/schemas/TaskLanguage' - - type: 'null' - mode: - $ref: '#/components/schemas/AssessmentMode' - versions: - $ref: '#/components/schemas/AssessmentVersions' - outcome: - $ref: '#/components/schemas/AssessmentOutcome' - not_determined_reason: - description: The reason when `outcome` is `not_determined`, otherwise null. - oneOf: - - $ref: '#/components/schemas/AssessmentNotDeterminedReason' - - type: 'null' - confirmed_grade: - description: Grade that this attempt confirmed, the target grade, or null when it confirmed none. Together with the specialization it forms the category. - oneOf: - - $ref: '#/components/schemas/GradeCode' - - type: 'null' - previous_confirmed_grade: - description: Confirmed grade of the specialization before this attempt, or null. When the attempt confirmed nothing, this grade stays in force. - oneOf: - - $ref: '#/components/schemas/GradeCode' - - type: 'null' - strength: - description: Strength of an adaptive confirmation, otherwise null. - oneOf: - - $ref: '#/components/schemas/AssessmentStrength' - - type: 'null' - calibration_status: - $ref: '#/components/schemas/CalibrationStatus' - limitations: - type: array - maxItems: 10 - uniqueItems: true - items: - $ref: '#/components/schemas/AssessmentLimitation' - uncertainty: - description: Ability estimate and uncertainty of an adaptive attempt with a decision; null for demo_basic, which computes none, and for an attempt without a decision. - oneOf: - - $ref: '#/components/schemas/AssessmentUncertainty' - - type: 'null' - basic_score: - description: Raw score of a demo_basic attempt with a decision, otherwise null. - oneOf: - - $ref: '#/components/schemas/BasicScore' - - type: 'null' - practices: - type: array - maxItems: 5 - description: Verdicts of the practices that have one, main first. - items: - $ref: '#/components/schemas/AssessmentPracticeResult' - gaps: - type: array - maxItems: 20 - description: Domains with weak evidence; empty when none were found or the method finds none. - items: - $ref: '#/components/schemas/AssessmentGap' - durations: - $ref: '#/components/schemas/AssessmentDurations' - next_steps: - type: array - maxItems: 5 - items: - $ref: '#/components/schemas/AssessmentNextStep' - decided_at: - $ref: '#/components/schemas/Timestamp' + description: Immutable result of a terminal assessment attempt. The result shape distinguishes real grade decisions from demo_express training output. + oneOf: + - $ref: '#/components/schemas/AssessmentQualifiedResult' + - $ref: '#/components/schemas/AssessmentCorrectiveResult' + - $ref: '#/components/schemas/AssessmentExpressResult' + discriminator: + propertyName: kind + mapping: + root: '#/components/schemas/AssessmentQualifiedResult' + corrective: '#/components/schemas/AssessmentCorrectiveResult' + demo_express: '#/components/schemas/AssessmentExpressResult' AssessmentGradeAvailabilityStatus: type: string description: |- @@ -5178,9 +5120,9 @@ components: status: $ref: '#/components/schemas/AssessmentGradeAvailabilityStatus' mode: - description: Mode that an attempt would use, or null when the status is `insufficient_bank`. + description: Real-assessment mode that the server would use, or null when the status is `insufficient_bank`. `demo_express` is not a category assessment and is never returned here. oneOf: - - $ref: '#/components/schemas/AssessmentMode' + - $ref: '#/components/schemas/AssessmentRealMode' - type: 'null' available_at: description: When the status is `cooldown`, the first time the attempt can start; otherwise null. @@ -8675,6 +8617,536 @@ components: type: string enum: - ok + AssessmentRealMode: + type: string + description: Server-selected mode available to a real category assessment. + enum: + - demo_basic + - adaptive + AssessmentQualifiedAttemptCreate: + type: object + description: 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. + additionalProperties: false + required: + - kind + - specialization + - target_grade + - task_language + properties: + kind: + type: string + enum: + - root + description: Start a real-assessment chain and reserve one root quota slot. + specialization: + $ref: '#/components/schemas/SpecializationCode' + target_grade: + $ref: '#/components/schemas/GradeCode' + task_language: + description: Task language of the attempt, one of the `task_languages` of the published bank, or null when the bank offers no choice of language. The questionnaire choice is the value the client offers first. + oneOf: + - $ref: '#/components/schemas/TaskLanguage' + - type: 'null' + AssessmentCorrectiveAttemptCreate: + type: object + description: 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 is never supplied by the client. + additionalProperties: false + required: + - kind + - specialization + - target_grade + - task_language + - root_attempt_id + properties: + kind: + type: string + enum: + - corrective + description: Continue the existing real-assessment chain without reserving another root slot. + specialization: + $ref: '#/components/schemas/SpecializationCode' + target_grade: + $ref: '#/components/schemas/GradeCode' + task_language: + description: Task language of the attempt, or null when the bank offers no choice. + oneOf: + - $ref: '#/components/schemas/TaskLanguage' + - type: 'null' + root_attempt_id: + type: string + format: uuid + description: Root real-assessment attempt whose quota and deadline this attempt shares. + AssessmentExpressAttemptCreate: + type: object + description: 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. + additionalProperties: false + required: + - kind + properties: + kind: + type: string + enum: + - demo_express + description: Explicitly request the training run; real modes cannot be selected by the client. + AssessmentAttemptKind: + type: string + description: Assessment track that distinguishes root, corrective, and training attempts. + enum: + - root + - corrective + - demo_express + 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. + additionalProperties: false + required: + - id + - version + - specialization + - target_grade + - task_language + - kind + - mode + - state + - versions + - started_at + - expires_at + - sessions + - finished_at + - progress + - current_item + - practices + properties: + id: + type: string + format: uuid + description: Attempt identifier. + version: + $ref: '#/components/schemas/AssessmentAttemptVersion' + specialization: + description: Null only for demo_express, which has no qualification category. + oneOf: + - $ref: '#/components/schemas/SpecializationCode' + - type: 'null' + target_grade: + description: Null only for demo_express, which has no qualification category. + oneOf: + - $ref: '#/components/schemas/GradeCode' + - type: 'null' + task_language: + description: Task language of the attempt, or null when none is selected. + oneOf: + - $ref: '#/components/schemas/TaskLanguage' + - type: 'null' + kind: + $ref: '#/components/schemas/AssessmentAttemptKind' + root_attempt_id: + description: Present only for a corrective real assessment. It identifies the root attempt whose quota and chain deadline this attempt shares. + oneOf: + - type: string + format: uuid + - type: 'null' + readOnly: true + chain_deadline: + description: Present only for a corrective real assessment. It is the immutable deadline derived from the root attempt and is not extended by a lower target grade. + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + readOnly: true + mode: + $ref: '#/components/schemas/AssessmentMode' + state: + $ref: '#/components/schemas/AssessmentAttemptState' + versions: + $ref: '#/components/schemas/AssessmentVersions' + started_at: + $ref: '#/components/schemas/Timestamp' + expires_at: + description: Server deadline. For demo_express it is 180 to 300 seconds after started_at; for a corrective assessment it does not exceed chain_deadline. + $ref: '#/components/schemas/Timestamp' + sessions: + description: Session limit of the attempt, or null when its policy defines none. + oneOf: + - $ref: '#/components/schemas/AssessmentSessions' + - type: 'null' + finished_at: + description: Time the attempt reached a terminal state, or null while it is active. + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + progress: + $ref: '#/components/schemas/AssessmentProgress' + current_item: + description: 'Item to answer now: a test item in `in_progress`, the practice item to submit in `practice_pending` or `additional_practice_pending` while that practice is `not_started` or `failed`, and null otherwise.' + oneOf: + - $ref: '#/components/schemas/AssessmentItem' + - type: 'null' + practices: + type: array + maxItems: 5 + description: Practices in the order assigned by the mode policy. The list exposes verdicts only after submission. + items: + $ref: '#/components/schemas/AssessmentPractice' + AssessmentQualifiedAttempt: + allOf: + - $ref: '#/components/schemas/AssessmentAttemptCommon' + - type: object + properties: + kind: + type: string + enum: + - root + mode: + type: string + enum: + - demo_basic + - adaptive + specialization: + $ref: '#/components/schemas/SpecializationCode' + target_grade: + $ref: '#/components/schemas/GradeCode' + root_attempt_id: + type: 'null' + description: Root attempts have no parent attempt. + chain_deadline: + type: 'null' + description: A root attempt has no correction-chain deadline. + required: + - kind + - mode + - specialization + - target_grade + - root_attempt_id + - chain_deadline + AssessmentCorrectiveAttempt: + allOf: + - $ref: '#/components/schemas/AssessmentAttemptCommon' + - type: object + properties: + kind: + type: string + enum: + - corrective + mode: + type: string + enum: + - demo_basic + - adaptive + specialization: + $ref: '#/components/schemas/SpecializationCode' + target_grade: + $ref: '#/components/schemas/GradeCode' + root_attempt_id: + type: string + format: uuid + readOnly: true + chain_deadline: + $ref: '#/components/schemas/Timestamp' + readOnly: true + required: + - kind + - mode + - specialization + - target_grade + - root_attempt_id + - chain_deadline + AssessmentExpressAttempt: + allOf: + - $ref: '#/components/schemas/AssessmentAttemptCommon' + - type: object + properties: + kind: + type: string + enum: + - demo_express + mode: + type: string + enum: + - demo_express + specialization: + type: 'null' + target_grade: + type: 'null' + task_language: + type: 'null' + root_attempt_id: + type: 'null' + chain_deadline: + type: 'null' + required: + - kind + - mode + - specialization + - target_grade + - task_language + - root_attempt_id + - chain_deadline + AssessmentRealResultCommon: + type: object + description: Immutable result of a real assessment, visible only to its candidate. It records the method, versions, decision, uncertainty, and limitations. A corrective result also carries root_attempt_id and chain_deadline from the same chain. Later policy, bank, or algorithm versions never change it. It never contains answers, per-item correctness, keys, seeds, hidden checks, or anti-cheat signals. Fields the method does not compute are null, never zero. + additionalProperties: false + required: + - attempt_id + - specialization + - target_grade + - task_language + - kind + - mode + - versions + - outcome + - not_determined_reason + - confirmed_grade + - previous_confirmed_grade + - strength + - calibration_status + - limitations + - uncertainty + - basic_score + - practices + - gaps + - durations + - next_steps + - decided_at + properties: + attempt_id: + type: string + format: uuid + specialization: + $ref: '#/components/schemas/SpecializationCode' + target_grade: + $ref: '#/components/schemas/GradeCode' + root_attempt_id: + description: Root attempt of a corrective check, or null when this is not a corrective result. The corrective attempt keeps this link. + oneOf: + - type: string + format: uuid + - type: 'null' + readOnly: true + chain_deadline: + description: Immutable deadline shared by a corrective chain, or null when this result is not from a corrective check. + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + readOnly: true + task_language: + oneOf: + - $ref: '#/components/schemas/TaskLanguage' + - type: 'null' + kind: + type: string + enum: + - root + - corrective + mode: + type: string + enum: + - demo_basic + - adaptive + versions: + $ref: '#/components/schemas/AssessmentVersions' + outcome: + $ref: '#/components/schemas/AssessmentOutcome' + not_determined_reason: + description: The reason when `outcome` is `not_determined`, otherwise null. + oneOf: + - $ref: '#/components/schemas/AssessmentNotDeterminedReason' + - type: 'null' + confirmed_grade: + description: Grade that this attempt confirmed, the target grade, or null when it confirmed none. Together with the specialization it forms the category. + oneOf: + - $ref: '#/components/schemas/GradeCode' + - type: 'null' + previous_confirmed_grade: + description: Confirmed grade of the specialization before this attempt, or null. When the attempt confirmed nothing, this grade stays in force. + oneOf: + - $ref: '#/components/schemas/GradeCode' + - type: 'null' + strength: + description: Strength of an adaptive confirmation, otherwise null. + oneOf: + - $ref: '#/components/schemas/AssessmentStrength' + - type: 'null' + calibration_status: + $ref: '#/components/schemas/CalibrationStatus' + limitations: + type: array + maxItems: 10 + uniqueItems: true + items: + $ref: '#/components/schemas/AssessmentLimitation' + uncertainty: + description: Ability estimate and uncertainty of an adaptive attempt with a decision; null for demo_basic, which computes none, and for an attempt without a decision. + oneOf: + - $ref: '#/components/schemas/AssessmentUncertainty' + - type: 'null' + basic_score: + description: Raw score of a demo_basic attempt with a decision, otherwise null. + oneOf: + - $ref: '#/components/schemas/BasicScore' + - type: 'null' + practices: + type: array + maxItems: 5 + description: Verdicts of the practices that have one, main first. + items: + $ref: '#/components/schemas/AssessmentPracticeResult' + gaps: + type: array + maxItems: 20 + description: Domains with weak evidence; empty when none were found or the method finds none. + items: + $ref: '#/components/schemas/AssessmentGap' + durations: + $ref: '#/components/schemas/AssessmentDurations' + next_steps: + type: array + maxItems: 5 + items: + $ref: '#/components/schemas/AssessmentNextStep' + decided_at: + $ref: '#/components/schemas/Timestamp' + AssessmentQualifiedResult: + description: Result of a real assessment that is not a corrective attempt. The correction-chain fields are explicitly null. + allOf: + - $ref: '#/components/schemas/AssessmentRealResultCommon' + - type: object + properties: + kind: + type: string + enum: + - root + root_attempt_id: + type: 'null' + chain_deadline: + type: 'null' + required: + - kind + - root_attempt_id + - chain_deadline + AssessmentCorrectiveResult: + description: Result of a corrective real assessment. Both chain fields are present and identify the same immutable correction chain. + allOf: + - $ref: '#/components/schemas/AssessmentRealResultCommon' + - type: object + properties: + kind: + type: string + enum: + - corrective + root_attempt_id: + type: string + format: uuid + readOnly: true + chain_deadline: + $ref: '#/components/schemas/Timestamp' + readOnly: true + required: + - kind + - root_attempt_id + - chain_deadline + AssessmentExpressResult: + type: object + description: Immutable educational result of a demo_express run. It includes a short summary but cannot report a category, percentile, uncertainty, grade, strength, or qualification evidence. The result belongs only to the training mode and does not consume a real-assessment quota. + additionalProperties: false + required: + - attempt_id + - specialization + - target_grade + - task_language + - kind + - mode + - versions + - outcome + - not_determined_reason + - confirmed_grade + - previous_confirmed_grade + - strength + - calibration_status + - limitations + - uncertainty + - basic_score + - practices + - gaps + - durations + - next_steps + - summary + - decided_at + properties: + attempt_id: + type: string + format: uuid + specialization: + type: 'null' + description: Express training does not assess a specialization. + target_grade: + type: 'null' + description: Express training does not assess a target grade. + task_language: + type: 'null' + kind: + type: string + enum: + - demo_express + mode: + type: string + enum: + - demo_express + versions: + $ref: '#/components/schemas/AssessmentVersions' + outcome: + type: string + enum: + - demonstration + not_determined_reason: + type: 'null' + confirmed_grade: + type: 'null' + description: Express training never confirms a grade. + previous_confirmed_grade: + type: 'null' + strength: + type: 'null' + calibration_status: + type: string + enum: + - uncalibrated + limitations: + type: array + minItems: 1 + maxItems: 1 + items: + type: string + enum: + - demonstration_only + uncertainty: + type: 'null' + description: Express training computes no ability estimate or percentile. + basic_score: + type: 'null' + practices: + type: array + maxItems: 0 + items: + $ref: '#/components/schemas/AssessmentPracticeResult' + gaps: + type: array + maxItems: 0 + items: + $ref: '#/components/schemas/AssessmentGap' + durations: + $ref: '#/components/schemas/AssessmentDurations' + next_steps: + type: array + maxItems: 0 + items: + $ref: '#/components/schemas/AssessmentNextStep' + summary: + type: string + minLength: 1 + maxLength: 2000 + description: Short educational feedback about this training run. + decided_at: + $ref: '#/components/schemas/Timestamp' parameters: IdempotencyKey: name: Idempotency-Key @@ -10095,6 +10567,7 @@ components: AssessmentAttemptCreateBackendJunior: summary: Start Backend junior with Go tasks value: + kind: root specialization: backend target_grade: junior task_language: go @@ -10104,9 +10577,12 @@ components: value: id: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b version: 1 + kind: root specialization: backend target_grade: junior task_language: go + root_attempt_id: null + chain_deadline: null mode: demo_basic state: in_progress versions: @@ -10140,6 +10616,86 @@ components: - id: c4 text: '500' practices: [] + AssessmentCorrectiveAttemptCreated: + summary: Corrective attempt shares the root chain deadline + value: + id: 01928f7e-8888-7a2b-8c3d-4e5f6a7b8c9d + version: 1 + kind: corrective + specialization: backend + target_grade: junior + task_language: go + root_attempt_id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d + chain_deadline: '2026-11-23T09:00:00Z' + mode: adaptive + state: in_progress + versions: + policy_version: 2 + bank_version: backend.2026-11.3 + algorithm_version: irt-1pl-eap.1 + started_at: '2026-11-22T10:00:00Z' + expires_at: '2026-11-23T09:00:00Z' + sessions: + used: 1 + max: 2 + idle_timeout_seconds: 1800 + finished_at: null + progress: + answered_items: 0 + max_items: 25 + current_item: + id: 01928f7e-9999-7a2b-8c3d-4e5f6a7b8c01 + sequence: 1 + prompt: What does an HTTP 412 response indicate for expected_version? + content: + format: choice + multiple: false + options: + - id: a1 + text: The version is stale. + - id: b2 + text: The request is malformed. + practices: [] + AssessmentExpressAttemptCreated: + summary: Short training attempt without a qualification category + value: + id: 01928f7f-9999-7a2b-8c3d-4e5f6a7b8c01 + version: 1 + kind: demo_express + specialization: null + target_grade: null + task_language: null + root_attempt_id: null + chain_deadline: null + mode: demo_express + state: in_progress + versions: + policy_version: 1 + bank_version: express-demo.2026-10.1 + algorithm_version: express-interactive.1 + started_at: '2026-10-08T10:00:00Z' + expires_at: '2026-10-08T10:05:00Z' + sessions: + used: 1 + max: 1 + idle_timeout_seconds: 300 + finished_at: null + progress: + answered_items: 0 + max_items: 5 + current_item: + id: 01928f7f-aaaa-7a2b-8c3d-4e5f6a7b8c01 + sequence: 1 + prompt: Choose the status code that signals a version conflict. + content: + format: choice + multiple: false + options: + - id: c3 + text: '412' + - id: d4 + text: '200' + practices: [] AssessmentSpecializationNotInQuestionnaire: summary: The specialization is not in the questionnaire value: @@ -10169,9 +10725,12 @@ components: value: id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d version: 7 + kind: root specialization: backend target_grade: middle task_language: python + root_attempt_id: null + chain_deadline: null mode: adaptive state: in_progress versions: @@ -10224,9 +10783,12 @@ components: value: id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d version: 16 + kind: root specialization: backend target_grade: middle task_language: python + root_attempt_id: null + chain_deadline: null mode: adaptive state: practice_pending versions: @@ -10267,9 +10829,12 @@ components: value: id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d version: 17 + kind: root specialization: backend target_grade: middle task_language: python + root_attempt_id: null + chain_deadline: null mode: adaptive state: practice_pending versions: @@ -10300,9 +10865,12 @@ components: value: id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d version: 18 + kind: root specialization: backend target_grade: middle task_language: python + root_attempt_id: null + chain_deadline: null mode: adaptive state: practice_pending versions: @@ -10343,9 +10911,12 @@ components: value: id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d version: 20 + kind: root specialization: backend target_grade: middle task_language: python + root_attempt_id: null + chain_deadline: null mode: adaptive state: ready_to_finalize versions: @@ -10385,9 +10956,12 @@ components: value: id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d version: 21 + kind: root specialization: backend target_grade: middle task_language: python + root_attempt_id: null + chain_deadline: null mode: adaptive state: additional_practice_pending versions: @@ -10443,9 +11017,12 @@ components: value: id: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b version: 14 + kind: root specialization: backend target_grade: junior task_language: go + root_attempt_id: null + chain_deadline: null mode: demo_basic state: completed versions: @@ -10470,9 +11047,12 @@ components: value: id: 01928f7c-5555-7a2b-8c3d-4e5f6a7b8c9d version: 10 + kind: root specialization: network_engineer target_grade: middle task_language: null + root_attempt_id: null + chain_deadline: null mode: adaptive state: insufficient_bank versions: @@ -10497,6 +11077,25 @@ components: submitted_at: null verdict: null failure_reason: null + AssessmentItemNotCurrent: + summary: The answered item is not the current item, or it already has another answer + value: + type: urn:lincodex:problem:state_conflict + title: Resource state conflict + status: 409 + code: state_conflict + detail: The resource is in a state that does not allow this operation. + trace_id: 2c3d4e5f-6a7b-4c8d-9e9f-0a1b2c3d4e5f + AssessmentStaleVersion: + summary: The command carried a stale expected_version + description: Another tab or device changed the attempt after the client read version 1. Nothing was stored; the client reads the attempt again and continues from its current item. The repository answers a stale version with 412, not 409. + value: + type: urn:lincodex:problem:version_conflict + title: Resource version conflict + status: 412 + code: version_conflict + detail: The resource changed after it was read. Read it again before retrying. + trace_id: 5f6a7b8c-9d0e-4f1a-8b2c-3d4e5f6a7b8c AssessmentChoiceAnswer: summary: Answer item 1 of version 1 value: @@ -10577,9 +11176,12 @@ components: value: id: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b version: 2 + kind: root specialization: backend target_grade: junior task_language: go + root_attempt_id: null + chain_deadline: null mode: demo_basic state: in_progress versions: @@ -10640,25 +11242,6 @@ components: pointer: '' code: invalid message: The value does not match the contract. - AssessmentItemNotCurrent: - summary: The answered item is not the current item, or it already has another answer - value: - type: urn:lincodex:problem:state_conflict - title: Resource state conflict - status: 409 - code: state_conflict - detail: The resource is in a state that does not allow this operation. - trace_id: 2c3d4e5f-6a7b-4c8d-9e9f-0a1b2c3d4e5f - AssessmentStaleVersion: - summary: The command carried a stale expected_version - description: Another tab or device changed the attempt after the client read version 1. Nothing was stored; the client reads the attempt again and continues from its current item. The repository answers a stale version with 412, not 409. - value: - type: urn:lincodex:problem:version_conflict - title: Resource version conflict - status: 412 - code: version_conflict - detail: The resource changed after it was read. Read it again before retrying. - trace_id: 5f6a7b8c-9d0e-4f1a-8b2c-3d4e5f6a7b8c AssessmentFinalization: summary: Finalize version 20 value: @@ -10680,6 +11263,9 @@ components: attempt_id: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b specialization: backend target_grade: junior + kind: root + root_attempt_id: null + chain_deadline: null task_language: go mode: demo_basic versions: @@ -10719,6 +11305,9 @@ components: attempt_id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d specialization: backend target_grade: middle + kind: root + root_attempt_id: null + chain_deadline: null task_language: python mode: adaptive versions: @@ -10783,6 +11372,9 @@ components: attempt_id: 01928f7d-7777-7a2b-8c3d-4e5f6a7b8c9d specialization: backend target_grade: middle + kind: root + root_attempt_id: null + chain_deadline: null task_language: go mode: adaptive versions: @@ -10852,6 +11444,9 @@ components: attempt_id: 01928f7c-5555-7a2b-8c3d-4e5f6a7b8c9d specialization: network_engineer target_grade: middle + kind: root + root_attempt_id: null + chain_deadline: null task_language: null mode: adaptive versions: @@ -10876,6 +11471,76 @@ components: practice_seconds: null next_steps: [] decided_at: '2026-11-21T12:31:00Z' + AssessmentCorrectiveResult: + summary: Corrective result retains its root and fixed deadline + value: + attempt_id: 01928f7e-8888-7a2b-8c3d-4e5f6a7b8c9d + specialization: backend + target_grade: middle + kind: corrective + root_attempt_id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d + chain_deadline: '2026-11-23T09:00:00Z' + task_language: go + mode: adaptive + versions: + policy_version: 2 + bank_version: backend.2026-11.3 + algorithm_version: irt-1pl-eap.1 + outcome: not_confirmed + not_determined_reason: null + confirmed_grade: null + previous_confirmed_grade: junior + strength: null + calibration_status: uncalibrated + limitations: + - uncalibrated_thresholds + - unproctored + uncertainty: + theta: 0.21 + standard_error: 0.25 + interval_95: + low: -0.28 + high: 0.7 + p_grade: 0.62 + basic_score: null + practices: [] + gaps: [] + durations: + items_seconds: 1500 + practice_seconds: 900 + next_steps: [] + decided_at: '2026-11-22T11:00:00Z' + AssessmentExpressResult: + summary: Short training result with no qualification evidence + value: + attempt_id: 01928f7f-9999-7a2b-8c3d-4e5f6a7b8c9d + specialization: null + target_grade: null + task_language: null + kind: demo_express + mode: demo_express + versions: + policy_version: 1 + bank_version: express-demo.2026-10.1 + algorithm_version: express-interactive.1 + outcome: demonstration + not_determined_reason: null + confirmed_grade: null + previous_confirmed_grade: null + strength: null + calibration_status: uncalibrated + limitations: + - demonstration_only + uncertainty: null + basic_score: null + practices: [] + gaps: [] + durations: + items_seconds: 260 + practice_seconds: null + next_steps: [] + summary: The run demonstrates the task flow and creates no qualification evidence. + decided_at: '2026-11-22T11:00:00Z' AssessmentResultNotReady: summary: The attempt has no result yet value: diff --git a/api/core/openapi.yml b/api/core/openapi.yml index 6b0bdfd..875a4fe 100644 --- a/api/core/openapi.yml +++ b/api/core/openapi.yml @@ -105,6 +105,8 @@ paths: $ref: ./routes/candidate_assessment_attempts.yml /api/v1/me/assessment-attempts/{attempt_id}: $ref: ./routes/candidate_assessment_attempt.yml + /api/v1/me/assessment-attempts/{attempt_id}/sessions: + $ref: ./routes/candidate_assessment_attempt_sessions.yml /api/v1/me/assessment-attempts/{attempt_id}/answers: $ref: ./routes/candidate_assessment_attempt_answers.yml /api/v1/me/assessment-attempts/{attempt_id}/finalize: @@ -353,6 +355,8 @@ components: $ref: ./components/schemas.yml#/AssessmentSessions AssessmentAttemptCreate: $ref: ./components/schemas.yml#/AssessmentAttemptCreate + AssessmentAttemptSessionStart: + $ref: ./components/schemas.yml#/AssessmentAttemptSessionStart AssessmentItemId: $ref: ./components/schemas.yml#/AssessmentItemId AssessmentOptionId: diff --git a/api/core/routes/candidate_assessment_attempt.yml b/api/core/routes/candidate_assessment_attempt.yml index 77c2e6d..93c184f 100644 --- a/api/core/routes/candidate_assessment_attempt.yml +++ b/api/core/routes/candidate_assessment_attempt.yml @@ -1,12 +1,12 @@ get: operationId: GetMyAssessmentAttempt - summary: Read or resume an assessment attempt of the current candidate. + summary: Read an assessment attempt of the current candidate. description: |- - Requires the session cookie of a candidate account. Returns the attempt with its state, fixed versions, time and session limits, progress, the item to answer now, and the practices. A reload, a retried request, or a new session returns the same item instance with the same text and option order; a lost connection never creates a new attempt. The response never says whether an earlier answer was correct and never contains answer keys, item scores, family or variant identifiers, seeds, hidden checks, or anti-cheat signals. + Requires the session cookie of a candidate account. Returns the stored attempt projection with its state, fixed versions, time and session limits, progress, the item to answer now, and the practices. This GET is read-only: it never starts or resumes a work session, consumes session quota, advances the version, or commits expiry or finalization. A reload, a retried request, or a new session returns the same item instance with the same text and option order; a lost connection never creates a new attempt. After `idle_timeout_seconds`, the candidate explicitly starts or resumes work with StartMyAssessmentAttemptSession. The response never says whether an earlier answer was correct and never contains answer keys, item scores, family or variant identifiers, seeds, hidden checks, or anti-cheat signals. - Reading an active attempt counts as activity: after the previous session ended it starts the next session, and when that would exceed the session limit it starts none and the attempt becomes `expired`. Before it answers, the server commits any transition that is due, with a new version: past `expires_at`, `ready_to_finalize` becomes `completed`, an unsubmitted additional practice is declined and the attempt becomes `completed`, and the other active states become `expired`; a practice still `pending` is graded first. The client polls this operation while a practice is `pending`. Reading a terminal attempt changes nothing. + When the deadline passes, this read still returns the stored state and deadline. A command or background transition commits the due outcome; if the stored state is still active, GetMyAssessmentResult answers 409 until that transition is committed. The client polls this operation while a practice is `pending`, but polling alone never changes attempt state. - The attempt must belong to the candidate of the session: an attempt of another candidate answers 404 not_found, the same as an unknown identifier, so identifiers cannot be probed. An employer account answers 403 forbidden; no operation gives an employer the answers or the attempt history. + The attempt must belong to the candidate of the session: an attempt of another candidate answers 404 not_found, the same as an unknown identifier, so identifiers cannot be probed. An employer account answers 403 forbidden; no operation gives an employer the answers, qualification evidence, or attempt history. security: - sessionCookie: [] tags: diff --git a/api/core/routes/candidate_assessment_attempt_answers.yml b/api/core/routes/candidate_assessment_attempt_answers.yml index 9e27268..db12398 100644 --- a/api/core/routes/candidate_assessment_attempt_answers.yml +++ b/api/core/routes/candidate_assessment_attempt_answers.yml @@ -6,6 +6,8 @@ post: The response is the attempt with the next item to answer. It never says whether the answer was correct. Items are answered in order and each answer is final. + A work command requires an active session. After `idle_timeout_seconds` of inactivity, the candidate calls StartMyAssessmentAttemptSession to explicitly start or resume a session; this answer command never starts one or consumes session quota. Reading the attempt or result is always read-only. A command that finds a due deadline transition may commit it before returning; a command that finds an expired idle session answers 409 until the candidate explicitly starts the next session. + Practice: an answer with format `practice` submits the solution of the main or the additional practice. It is stored, and the sandbox runs it asynchronously against the hidden check groups; the response shows the practice `pending`, and the client polls GetMyAssessmentAttempt for the verdict. Only the score 0-3 and the pass state of each group are shown, never the checks, error output, or seeds. Every outcome caused by the solution, such as a compilation error, a crash, or a time or memory limit, is a `finished` verdict. A `failed` verdict means only that the sandbox infrastructure could not run it; it consumes nothing. After `finished` the practice accepts no other solution, so hidden group results cannot be used to tune it. Debug runs of the candidate's own tests and the public examples are unlimited apart from the sandbox rate limit and never show hidden group results; they are planned as a separate operation. Repeats and conflicts, per item: @@ -16,7 +18,7 @@ post: Optimistic concurrency: `expected_version` must equal the current attempt version, otherwise the server answers 412 version_conflict and stores nothing; the client reads the attempt again. 412 is the repository status for a stale version, also used by SaveMyQuestionnaire; 409 state_conflict is kept for commands that the attempt state does not allow at the current version. - Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the attempt (404 not_found for an unknown attempt or one of another candidate; the server first commits any due transition such as expiry, and the request counts as activity for the session limit), the repeat of the stored answer (200, skipped for a practice whose latest verdict is `failed`), the version (412), the state (409 state_conflict: the attempt is terminal, the item is not current, the item has a different answer, or the practice verdict is pending or finished), then the answer against the item (400 with a pointer such as `/answer/format` or `/answer/option_ids/0`). Following the Idempotency-Key convention, 404 and 409 state_conflict are stored under the key and replayed; 400, 412, 429, and 5xx are not. The rate limit can answer 429 with Retry-After before any check. + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the attempt (404 not_found for an unknown attempt or one of another candidate; a due deadline transition may be committed, but this request never starts a work session), the repeat of the stored answer (200, skipped for a practice whose latest verdict is `failed`), the version (412), the state (409 state_conflict: the attempt is terminal, the work session ended, the item is not current, the item has a different answer, or the practice verdict is pending or finished), then the answer against the item (400 with a pointer such as `/answer/format` or `/answer/option_ids/0`). Following the Idempotency-Key convention, 404 and 409 state_conflict are stored under the key and replayed; 400, 412, 429, and 5xx are not. The rate limit can answer 429 with Retry-After before any check. security: - sessionCookie: [] sessionCsrf: [] diff --git a/api/core/routes/candidate_assessment_attempt_finalize.yml b/api/core/routes/candidate_assessment_attempt_finalize.yml index b4cad86..6d8eb51 100644 --- a/api/core/routes/candidate_assessment_attempt_finalize.yml +++ b/api/core/routes/candidate_assessment_attempt_finalize.yml @@ -4,16 +4,18 @@ post: description: |- Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. Finalize always answers with the attempt, never with the result: the decision may continue the attempt, and one response type keeps that unambiguous for every generated client. When the returned state is `completed`, the client reads the result with GetMyAssessmentResult. + Finalize is a work command and requires an active session. After `idle_timeout_seconds` of inactivity, the candidate first calls StartMyAssessmentAttemptSession with the latest `expected_version`; finalize never starts a session. GET attempt and result operations do not change state. A command or background transition may commit a due deadline outcome. + Allowed in `ready_to_finalize`, where every required part is done, and in `additional_practice_pending` while the additional practice is `not_started` or `failed`. The server decides from the stored answers with the policy, bank, and algorithm versions fixed at creation: - `demo_basic` compares the raw score with the pass mark of the recorded basic grading policy and completes the attempt. It never offers an additional practice. - `adaptive` applies the probability bands of the recorded policy. Confirmation or rejection completes the attempt. A probability in the band below confirmation (0.50 to below 0.80 in the demo policy) on the first finalize, while time and sessions remain, completes nothing: the server appends an `additional` practice, moves the attempt to `additional_practice_pending`, and answers 200 with it. The additional practice continues the same attempt, keeps its limits, and spends no new attempt. The next finalize, after its verdict, decides with the added evidence; a probability still below confirmation gives `not_confirmed`. An attempt offers at most one additional practice. - Finalize in `additional_practice_pending` declines the offer and gives `not_confirmed` with the current evidence. A retry of the first finalize with a new key cannot decline by accident: it carries the version from before the offer and answers 412. - A failed attempt never lowers a confirmed grade. Repeats return the same outcome: a retry with the same Idempotency-Key replays the stored response, and a finalize of a `completed` attempt answers 200 with that attempt even with a new key or an older `expected_version`; the result is computed once. When `expires_at` passes or the session limit is reached, the server finalizes `ready_to_finalize` itself, without offering an additional practice, so a finalize after that also answers 200 with the `completed` attempt. + A failed attempt never lowers a confirmed grade. Repeats return the same outcome: a retry with the same Idempotency-Key replays the stored response, and a finalize of a `completed` attempt answers 200 with that attempt even with a new key or an older `expected_version`; the result is computed once. When `expires_at` passes or the session limit is reached, a command or background transition finalizes `ready_to_finalize` without offering an additional practice. A finalize after this transition answers 200 with the stored `completed` attempt; a GET never commits it. An attempt in `in_progress` or `practice_pending`, one with a practice verdict `pending`, or one that ended as `expired` or `insufficient_bank` answers 409 state_conflict. The problem does not list what is unfinished; the attempt shows it in `state`, `progress`, `current_item`, and `practices`. A stale `expected_version` answers 412 version_conflict, the repository status for a stale version. - Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the attempt (404 not_found, after any due transition), the repeat on a `completed` attempt (200), the version (412), then the state (409 state_conflict). 404 and 409 state_conflict are stored under the key; 400 and 412 are not. + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the attempt (404 not_found; a due deadline transition may be committed, but this request never starts a work session), the repeat on a `completed` attempt (200), the version (412), then the state (409 state_conflict, including an ended idle session). 404 and 409 state_conflict are stored under the key; 400 and 412 are not. security: - sessionCookie: [] sessionCsrf: [] diff --git a/api/core/routes/candidate_assessment_attempt_result.yml b/api/core/routes/candidate_assessment_attempt_result.yml index e42f3c3..f3be564 100644 --- a/api/core/routes/candidate_assessment_attempt_result.yml +++ b/api/core/routes/candidate_assessment_attempt_result.yml @@ -2,11 +2,11 @@ get: operationId: GetMyAssessmentResult summary: Read the result of an assessment attempt of the current candidate. description: |- - Requires the session cookie of a candidate account. Returns the immutable result of a terminal attempt: `completed`, `expired`, or `insufficient_bank`. It records the mode, the policy, bank, and algorithm versions, the decision, the previously confirmed grade, the calibration status and limitations of the method, the uncertainty where the method computes it, the practice verdicts, the weak domains, the working time as a separate label, and the next steps that the server allows. A later policy, bank, or algorithm version never changes it. + Requires the session cookie of a candidate account. Returns the immutable result of a terminal attempt: `completed`, `expired`, or `insufficient_bank`. A real result records the mode, policy, bank, and algorithm versions, decision, previously confirmed grade, calibration status and limitations, uncertainty where the method computes it, practice verdicts, weak domains, working time as a separate label, and allowed next steps. A corrective result also carries the root attempt and its immutable chain deadline. A `demo_express` result is a short educational summary only: it has no category, percentile, confirmed grade, score, uncertainty, or qualification evidence. A later policy, bank, or algorithm version never changes a result. Fields that the method does not compute are null and never zero: a `demo_basic` result has null `uncertainty` and `strength`. The result never contains answers, per-item correctness, answer keys, seeds, hidden checks, or anti-cheat signals. - An active attempt answers 409 state_conflict; an attempt in `additional_practice_pending` is active and has no result yet. The server first commits any due transition, so an attempt past its limits is read as terminal. An attempt of another candidate answers 404 not_found, the same as an unknown identifier. An employer account answers 403 forbidden; employers see only the current category through a separate projection, never this result or the attempt history. + An active attempt answers 409 state_conflict; an attempt in `additional_practice_pending` is active and has no result yet. This GET is read-only and never commits a due transition. If a deadline has passed but the due transition is not yet stored by a command or background worker, the attempt remains active for this read and answers 409; wait for the transition and retry. An attempt of another candidate answers 404 not_found, the same as an unknown identifier. An employer account answers 403 forbidden; employers see only the current category through a separate projection, never this result or the attempt history. security: - sessionCookie: [] tags: @@ -32,6 +32,10 @@ get: $ref: ../components/examples.yml#/AssessmentNotConfirmedResult insufficient_bank: $ref: ../components/examples.yml#/AssessmentInsufficientBankResult + corrective: + $ref: ../components/examples.yml#/AssessmentCorrectiveResult + demo_express: + $ref: ../components/examples.yml#/AssessmentExpressResult "401": $ref: ../components/responses.yml#/Unauthenticated "403": diff --git a/api/core/routes/candidate_assessment_attempt_sessions.yml b/api/core/routes/candidate_assessment_attempt_sessions.yml new file mode 100644 index 0000000..49d1f5e --- /dev/null +++ b/api/core/routes/candidate_assessment_attempt_sessions.yml @@ -0,0 +1,62 @@ +post: + operationId: StartMyAssessmentAttemptSession + summary: Start or resume a work session for the current candidate's attempt. + description: |- + Requires a candidate session, its CSRF token in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The body carries the attempt version the candidate last read. The server checks ownership, idempotency, and `expected_version` atomically before starting a session; a stale version answers 412 and consumes no session. Repeating the same key and body within 24 hours replays the stored response. + + Creation starts session 1. After `idle_timeout_seconds` of inactivity, the candidate uses this command to start the next session. Calling it while a session is already active returns the current attempt without consuming another session or advancing its version. Starting a session advances the version once. The command cannot extend `expires_at` or `chain_deadline`. + + If the attempt deadline or session budget has passed, this command commits the due terminal transition and returns the resulting attempt. A pending practice submitted before the limit is graded first. `GetMyAssessmentAttempt` and `GetMyAssessmentResult` remain read-only: they never start a session or commit a due transition. A background transition may persist a due outcome independently; after that, this command returns the stored terminal attempt without changing it. + + The attempt must belong to the candidate of the session. An attempt of another candidate answers 404 not_found, the same as an unknown identifier. An employer account answers 403 forbidden; no operation gives an employer answers, qualification evidence, or attempt history. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - assessment + parameters: + - $ref: ../components/parameters.yml#/AssessmentAttemptId + - $ref: ../components/parameters.yml#/IdempotencyKey + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/AssessmentAttemptSessionStart + example: + expected_version: 7 + responses: + "200": + description: >- + The current attempt after starting or resuming work, or after a due + terminal transition was committed. A replay returns the stored body. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/AssessmentAttempt + examples: + resumed: + $ref: ../components/examples.yml#/AssessmentAttemptResumed + terminal: + $ref: ../components/examples.yml#/AssessmentAttemptCompleted + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden + "404": + $ref: ../components/responses.yml#/NotFound + "409": + $ref: ../components/responses.yml#/AssessmentCommandConflict + "412": + $ref: ../components/responses.yml#/AssessmentVersionConflict + "422": + $ref: ../components/responses.yml#/UnprocessableContent + "429": + $ref: ../components/responses.yml#/TooManyRequests + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_assessment_attempts.yml b/api/core/routes/candidate_assessment_attempts.yml index 426670d..c41a624 100644 --- a/api/core/routes/candidate_assessment_attempts.yml +++ b/api/core/routes/candidate_assessment_attempts.yml @@ -1,12 +1,12 @@ post: operationId: CreateMyAssessmentAttempt - summary: Start an assessment attempt for a category of the current candidate. + summary: Start a real, corrective, or training assessment attempt. description: |- - Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The body names the category, a specialization of the questionnaire and a target grade, and the task language. The server picks the mode from the published bank, `demo_basic` or `adaptive`, and fixes the policy, bank, and algorithm versions, the time and session limits, and the item variants in one transaction; the client never sends a mode, a seed, or a version. Creation starts session 1. The self-assessed grade only chooses where the test starts and adds no points. An adaptive retest starts from the previous ability estimate of the specialization, adjusted for the time passed, so a new attempt adds evidence instead of starting the measurement over. + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The request is one of three disjoint shapes. A real assessment names a specialization, target grade, and task language; the server picks `demo_basic` or `adaptive` and fixes the policy, bank, and algorithm versions, limits, and item variants. A corrective real assessment also names `root_attempt_id`; the server verifies the lower-grade chain and reuses its fixed quota and deadline. The client never sends a real mode, a seed, a version, or a chain deadline. Explicit `demo_express` starts a separate interactive training run that lasts 3 to 5 minutes, has no category or target grade, and creates no qualification evidence or percentile. Creation starts session 1. The self-assessed grade only chooses where a real test starts and adds no points. An adaptive retest starts from the previous ability estimate of the specialization, adjusted for the time passed, so a new attempt adds evidence instead of starting the measurement over. - A specialization has at most one active attempt. A new attempt cannot start while one is active, during a retry or promotion interval or past the attempt limit of the policy, or when the bank is insufficient; each answers 409 state_conflict and creates nothing, not even a placeholder attempt. GetMyAssessmentAvailability tells which case applies and when a blocked attempt opens. After a failure, including the first test, a lower grade can be tested at once. An attempt that ends as `expired` or with the reason `practice_incomplete` counts toward the attempt limit and starts the same-grade retry interval; one that ends as `insufficient_bank` or with the reason `sandbox_unavailable` counts toward neither. + A specialization has at most one active real attempt. A new root attempt cannot start while one is active, during a retry or promotion interval, past the root quota, or when the bank is insufficient; each such preflight refusal answers 409 state_conflict and creates nothing or consumes no root slot. Starting a root attempt reserves one slot in the root quota. A corrective attempt must reference its root, target a strictly lower grade not already attempted in that chain, and remain inside the root's fixed quota and deadline (72 hours from the root start in the current policy). It gets its own item, practice, and session limits, but spends no additional root slot and cannot reset the chain deadline or any 30/90-day timer. After a failure, including the first test, a lower grade can be tested at once. An expired or incomplete attempt does not create a free new chain; an insufficient bank or sandbox failure does not grant another root slot. `demo_express` is outside real-assessment availability, quotas, retry intervals, and qualification history. - The limits are server-side: `expires_at` and `sessions` come from the policy version, the client clock never extends them, and after them the attempt accepts no command. Within them the attempt is also bounded by the item limit of the policy. + The limits are server-side: `expires_at` and `sessions` come from the policy version, the client clock never extends them, and after them the attempt accepts no work command. For a corrective attempt, `expires_at` is no later than the root's immutable `chain_deadline`. Within these limits the attempt is also bounded by the item limit of its policy. Idempotency: a retry with the same key and body within 24 hours replays the stored 201 or 409 state_conflict response and creates nothing, so a lost response never creates a second attempt. A different body with the same key answers 422 idempotency_key_reused. 400 is never stored, so a corrected retry is evaluated again. @@ -27,6 +27,18 @@ post: examples: backend_junior_go: $ref: ../components/examples.yml#/AssessmentAttemptCreateBackendJunior + corrective_backend_junior_go: + summary: Start a lower-grade assessment inside an existing correction chain + value: + kind: corrective + specialization: backend + target_grade: junior + task_language: go + root_attempt_id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d + demo_express: + summary: Start a short educational training run + value: + kind: demo_express responses: "201": description: >- @@ -42,6 +54,10 @@ post: examples: demo_basic_created: $ref: ../components/examples.yml#/AssessmentAttemptCreated + corrective_created: + $ref: ../components/examples.yml#/AssessmentCorrectiveAttemptCreated + demo_express_created: + $ref: ../components/examples.yml#/AssessmentExpressAttemptCreated "400": $ref: ../components/responses.yml#/AssessmentAttemptCreateValidationFailed "401": diff --git a/api/redocly.yaml b/api/redocly.yaml index 485cbb6..0fac86f 100644 --- a/api/redocly.yaml +++ b/api/redocly.yaml @@ -3,3 +3,4 @@ extends: rules: info-license: off operation-4xx-response: off + no-invalid-media-type-examples: error diff --git a/backend/internal/adapter/primary/http/api/oas_handlers_gen.go b/backend/internal/adapter/primary/http/api/oas_handlers_gen.go index 1c2bf74..256dba0 100644 --- a/backend/internal/adapter/primary/http/api/oas_handlers_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_handlers_gen.go @@ -785,27 +785,33 @@ func (s *Server) handleConfirmEmailRequest(args [0]string, argsEscaped bool, w h // handleCreateMyAssessmentAttemptRequest handles CreateMyAssessmentAttempt operation. // // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, -// an allowed Origin, and an Idempotency-Key. The body names the category, a specialization of the -// questionnaire and a target grade, and the task language. The server picks the mode from the -// published bank, `demo_basic` or `adaptive`, and fixes the policy, bank, and algorithm versions, the -// time and session limits, and the item variants in one transaction; the client never sends a mode, a -// seed, or a version. Creation starts session 1. The self-assessed grade only chooses where the test -// starts and adds no points. An adaptive retest starts from the previous ability estimate of the -// specialization, adjusted for the time passed, so a new attempt adds evidence instead of starting the -// measurement over. +// an allowed Origin, and an Idempotency-Key. The request is one of three disjoint shapes. A real +// assessment names a specialization, target grade, and task language; the server picks `demo_basic` or +// `adaptive` and fixes the policy, bank, and algorithm versions, limits, and item variants. A +// corrective real assessment also names `root_attempt_id`; the server verifies the lower-grade chain +// and reuses its fixed quota and deadline. The client never sends a real mode, a seed, a version, or a +// chain deadline. Explicit `demo_express` starts a separate interactive training run that lasts 3 to 5 +// minutes, has no category or target grade, and creates no qualification evidence or percentile. +// Creation starts session 1. The self-assessed grade only chooses where a real test starts and adds no +// points. An adaptive retest starts from the previous ability estimate of the specialization, adjusted +// for the time passed, so a new attempt adds evidence instead of starting the measurement over. // -// A specialization has at most one active attempt. A new attempt cannot start while one is active, -// during a retry or promotion interval or past the attempt limit of the policy, or when the bank is -// insufficient; each answers 409 state_conflict and creates nothing, not even a placeholder attempt. -// GetMyAssessmentAvailability tells which case applies and when a blocked attempt opens. After a -// failure, including the first test, a lower grade can be tested at once. An attempt that ends as -// `expired` or with the reason `practice_incomplete` counts toward the attempt limit and starts the -// same-grade retry interval; one that ends as `insufficient_bank` or with the reason -// `sandbox_unavailable` counts toward neither. +// A specialization has at most one active real attempt. A new root attempt cannot start while one is +// active, during a retry or promotion interval, past the root quota, or when the bank is insufficient; +// each such preflight refusal answers 409 state_conflict and creates nothing or consumes no root slot. +// Starting a root attempt reserves one slot in the root quota. A corrective attempt must reference its +// root, target a strictly lower grade not already attempted in that chain, and remain inside the +// root's fixed quota and deadline (72 hours from the root start in the current policy). It gets its +// own item, practice, and session limits, but spends no additional root slot and cannot reset the +// chain deadline or any 30/90-day timer. After a failure, including the first test, a lower grade can +// be tested at once. An expired or incomplete attempt does not create a free new chain; an +// insufficient bank or sandbox failure does not grant another root slot. `demo_express` is outside +// real-assessment availability, quotas, retry intervals, and qualification history. // // The limits are server-side: `expires_at` and `sessions` come from the policy version, the client -// clock never extends them, and after them the attempt accepts no command. Within them the attempt is -// also bounded by the item limit of the policy. +// clock never extends them, and after them the attempt accepts no work command. For a corrective +// attempt, `expires_at` is no later than the root's immutable `chain_deadline`. Within these limits +// the attempt is also bounded by the item limit of its policy. // // Idempotency: a retry with the same key and body within 24 hours replays the stored 201 or 409 // state_conflict response and creates nothing, so a lost response never creates a second attempt. A @@ -988,7 +994,7 @@ func (s *Server) handleCreateMyAssessmentAttemptRequest(args [0]string, argsEsca mreq := middleware.Request{ Context: ctx, OperationName: CreateMyAssessmentAttemptOperation, - OperationSummary: "Start an assessment attempt for a category of the current candidate.", + OperationSummary: "Start a real, corrective, or training assessment attempt.", OperationID: "CreateMyAssessmentAttempt", Body: request, RawBody: rawBody, @@ -1002,7 +1008,7 @@ func (s *Server) handleCreateMyAssessmentAttemptRequest(args [0]string, argsEsca } type ( - Request = *AssessmentAttemptCreate + Request = AssessmentAttemptCreate Params = CreateMyAssessmentAttemptParams Response = CreateMyAssessmentAttemptRes ) @@ -2466,6 +2472,11 @@ func (s *Server) handleDeclineMyInvitationRequest(args [1]string, argsEscaped bo // every generated client. When the returned state is `completed`, the client reads the result with // GetMyAssessmentResult. // +// Finalize is a work command and requires an active session. After `idle_timeout_seconds` of +// inactivity, the candidate first calls StartMyAssessmentAttemptSession with the latest +// `expected_version`; finalize never starts a session. GET attempt and result operations do not change +// state. A command or background transition may commit a due deadline outcome. +// // Allowed in `ready_to_finalize`, where every required part is done, and in // `additional_practice_pending` while the additional practice is `not_started` or `failed`. The server // decides from the stored answers with the policy, bank, and algorithm versions fixed at creation: @@ -2487,9 +2498,9 @@ func (s *Server) handleDeclineMyInvitationRequest(args [1]string, argsEscaped bo // A failed attempt never lowers a confirmed grade. Repeats return the same outcome: a retry with the // same Idempotency-Key replays the stored response, and a finalize of a `completed` attempt answers // 200 with that attempt even with a new key or an older `expected_version`; the result is computed -// once. When `expires_at` passes or the session limit is reached, the server finalizes -// `ready_to_finalize` itself, without offering an additional practice, so a finalize after that also -// answers 200 with the `completed` attempt. +// once. When `expires_at` passes or the session limit is reached, a command or background transition +// finalizes `ready_to_finalize` without offering an additional practice. A finalize after this +// transition answers 200 with the stored `completed` attempt; a GET never commits it. // // An attempt in `in_progress` or `practice_pending`, one with a practice verdict `pending`, or one // that ended as `expired` or `insufficient_bank` answers 409 state_conflict. The problem does not list @@ -2498,8 +2509,9 @@ func (s *Server) handleDeclineMyInvitationRequest(args [1]string, argsEscaped bo // // Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), // account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), -// the attempt (404 not_found, after any due transition), the repeat on a `completed` attempt (200), -// the version (412), then the state (409 state_conflict). 404 and 409 state_conflict are stored under +// the attempt (404 not_found; a due deadline transition may be committed, but this request never +// starts a work session), the repeat on a `completed` attempt (200), the version (412), then the state +// (409 state_conflict, including an ended idle session). 404 and 409 state_conflict are stored under // the key; 400 and 412 are not. // // POST /api/v1/me/assessment-attempts/{attempt_id}/finalize @@ -3408,24 +3420,25 @@ func (s *Server) handleGetHealthzRequest(args [0]string, argsEscaped bool, w htt // handleGetMyAssessmentAttemptRequest handles GetMyAssessmentAttempt operation. // -// Requires the session cookie of a candidate account. Returns the attempt with its state, fixed -// versions, time and session limits, progress, the item to answer now, and the practices. A reload, a -// retried request, or a new session returns the same item instance with the same text and option -// order; a lost connection never creates a new attempt. The response never says whether an earlier -// answer was correct and never contains answer keys, item scores, family or variant identifiers, -// seeds, hidden checks, or anti-cheat signals. +// Requires the session cookie of a candidate account. Returns the stored attempt projection with its +// state, fixed versions, time and session limits, progress, the item to answer now, and the practices. +// This GET is read-only: it never starts or resumes a work session, consumes session quota, advances +// the version, or commits expiry or finalization. A reload, a retried request, or a new session +// returns the same item instance with the same text and option order; a lost connection never creates +// a new attempt. After `idle_timeout_seconds`, the candidate explicitly starts or resumes work with +// StartMyAssessmentAttemptSession. The response never says whether an earlier answer was correct and +// never contains answer keys, item scores, family or variant identifiers, seeds, hidden checks, or +// anti-cheat signals. // -// Reading an active attempt counts as activity: after the previous session ended it starts the next -// session, and when that would exceed the session limit it starts none and the attempt becomes -// `expired`. Before it answers, the server commits any transition that is due, with a new version: -// past `expires_at`, `ready_to_finalize` becomes `completed`, an unsubmitted additional practice is -// declined and the attempt becomes `completed`, and the other active states become `expired`; a -// practice still `pending` is graded first. The client polls this operation while a practice is -// `pending`. Reading a terminal attempt changes nothing. +// When the deadline passes, this read still returns the stored state and deadline. A command or +// background transition commits the due outcome; if the stored state is still active, +// GetMyAssessmentResult answers 409 until that transition is committed. The client polls this +// operation while a practice is `pending`, but polling alone never changes attempt state. // // The attempt must belong to the candidate of the session: an attempt of another candidate answers 404 // not_found, the same as an unknown identifier, so identifiers cannot be probed. An employer account -// answers 403 forbidden; no operation gives an employer the answers or the attempt history. +// answers 403 forbidden; no operation gives an employer the answers, qualification evidence, or +// attempt history. // // GET /api/v1/me/assessment-attempts/{attempt_id} func (s *Server) handleGetMyAssessmentAttemptRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { @@ -3563,7 +3576,7 @@ func (s *Server) handleGetMyAssessmentAttemptRequest(args [1]string, argsEscaped mreq := middleware.Request{ Context: ctx, OperationName: GetMyAssessmentAttemptOperation, - OperationSummary: "Read or resume an assessment attempt of the current candidate.", + OperationSummary: "Read an assessment attempt of the current candidate.", OperationID: "GetMyAssessmentAttempt", Body: nil, RawBody: rawBody, @@ -3826,21 +3839,25 @@ func (s *Server) handleGetMyAssessmentAvailabilityRequest(args [0]string, argsEs // handleGetMyAssessmentResultRequest handles GetMyAssessmentResult operation. // // Requires the session cookie of a candidate account. Returns the immutable result of a terminal -// attempt: `completed`, `expired`, or `insufficient_bank`. It records the mode, the policy, bank, and -// algorithm versions, the decision, the previously confirmed grade, the calibration status and -// limitations of the method, the uncertainty where the method computes it, the practice verdicts, the -// weak domains, the working time as a separate label, and the next steps that the server allows. A -// later policy, bank, or algorithm version never changes it. +// attempt: `completed`, `expired`, or `insufficient_bank`. A real result records the mode, policy, +// bank, and algorithm versions, decision, previously confirmed grade, calibration status and +// limitations, uncertainty where the method computes it, practice verdicts, weak domains, working time +// as a separate label, and allowed next steps. A corrective result also carries the root attempt and +// its immutable chain deadline. A `demo_express` result is a short educational summary only: it has no +// category, percentile, confirmed grade, score, uncertainty, or qualification evidence. A later +// policy, bank, or algorithm version never changes a result. // // Fields that the method does not compute are null and never zero: a `demo_basic` result has null // `uncertainty` and `strength`. The result never contains answers, per-item correctness, answer keys, // seeds, hidden checks, or anti-cheat signals. // // An active attempt answers 409 state_conflict; an attempt in `additional_practice_pending` is active -// and has no result yet. The server first commits any due transition, so an attempt past its limits is -// read as terminal. An attempt of another candidate answers 404 not_found, the same as an unknown -// identifier. An employer account answers 403 forbidden; employers see only the current category -// through a separate projection, never this result or the attempt history. +// and has no result yet. This GET is read-only and never commits a due transition. If a deadline has +// passed but the due transition is not yet stored by a command or background worker, the attempt +// remains active for this read and answers 409; wait for the transition and retry. An attempt of +// another candidate answers 404 not_found, the same as an unknown identifier. An employer account +// answers 403 forbidden; employers see only the current category through a separate projection, never +// this result or the attempt history. // // GET /api/v1/me/assessment-attempts/{attempt_id}/result func (s *Server) handleGetMyAssessmentResultRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { @@ -10876,6 +10893,262 @@ func (s *Server) handleSetMySearchStatusRequest(args [0]string, argsEscaped bool } } +// handleStartMyAssessmentAttemptSessionRequest handles StartMyAssessmentAttemptSession operation. +// +// Requires a candidate session, its CSRF token in X-CSRF-Token, an allowed Origin, and an +// Idempotency-Key. The body carries the attempt version the candidate last read. The server checks +// ownership, idempotency, and `expected_version` atomically before starting a session; a stale version +// answers 412 and consumes no session. Repeating the same key and body within 24 hours replays the +// stored response. +// +// Creation starts session 1. After `idle_timeout_seconds` of inactivity, the candidate uses this +// command to start the next session. Calling it while a session is already active returns the current +// attempt without consuming another session or advancing its version. Starting a session advances the +// version once. The command cannot extend `expires_at` or `chain_deadline`. +// +// If the attempt deadline or session budget has passed, this command commits the due terminal +// transition and returns the resulting attempt. A pending practice submitted before the limit is +// graded first. `GetMyAssessmentAttempt` and `GetMyAssessmentResult` remain read-only: they never +// start a session or commit a due transition. A background transition may persist a due outcome +// independently; after that, this command returns the stored terminal attempt without changing it. +// +// The attempt must belong to the candidate of the session. An attempt of another candidate answers 404 +// not_found, the same as an unknown identifier. An employer account answers 403 forbidden; no +// operation gives an employer answers, qualification evidence, or attempt history. +// +// POST /api/v1/me/assessment-attempts/{attempt_id}/sessions +func (s *Server) handleStartMyAssessmentAttemptSessionRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("StartMyAssessmentAttemptSession"), + semconv.HTTPRequestMethodKey.String("POST"), + semconv.HTTPRouteKey.String("/api/v1/me/assessment-attempts/{attempt_id}/sessions"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), StartMyAssessmentAttemptSessionOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(attrs...) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + opErrContext = ogenerrors.OperationContext{ + Name: StartMyAssessmentAttemptSessionOperation, + ID: "StartMyAssessmentAttemptSession", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, StartMyAssessmentAttemptSessionOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCookie", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCookie", err) + } + return + } + if ok { + satisfied[0] |= 1 << 0 + ctx = sctx + } + } + { + sctx, ok, err := s.securitySessionCsrf(ctx, StartMyAssessmentAttemptSessionOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCsrf", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCsrf", err) + } + return + } + if ok { + satisfied[0] |= 1 << 1 + ctx = sctx + } + } + + if ok := func() bool { + nextRequirement: + for _, requirement := range []bitset{ + {0b00000011}, + } { + for i, mask := range requirement { + if satisfied[i]&mask != mask { + continue nextRequirement + } + } + return true + } + return false + }(); !ok { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security", err) + } + return + } + } + params, err := decodeStartMyAssessmentAttemptSessionParams(args, argsEscaped, r) + if err != nil { + err = &ogenerrors.DecodeParamsError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeParams", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + + var rawBody []byte + request, rawBody, close, err := s.decodeStartMyAssessmentAttemptSessionRequest(r) + if err != nil { + err = &ogenerrors.DecodeRequestError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeRequest", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + defer func() { + if err := close(); err != nil { + recordError("CloseRequest", err) + } + }() + + var response StartMyAssessmentAttemptSessionRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: StartMyAssessmentAttemptSessionOperation, + OperationSummary: "Start or resume a work session for the current candidate's attempt.", + OperationID: "StartMyAssessmentAttemptSession", + Body: request, + RawBody: rawBody, + Params: middleware.Parameters{ + { + Name: "attempt_id", + In: "path", + }: params.AttemptID, + { + Name: "Idempotency-Key", + In: "header", + }: params.IdempotencyKey, + }, + Raw: r, + } + + type ( + Request = *AssessmentAttemptSessionStart + Params = StartMyAssessmentAttemptSessionParams + Response = StartMyAssessmentAttemptSessionRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackStartMyAssessmentAttemptSessionParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.StartMyAssessmentAttemptSession(ctx, request, params) + return response, err + }, + ) + } else { + response, err = s.h.StartMyAssessmentAttemptSession(ctx, request, params) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeStartMyAssessmentAttemptSessionResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + // handleSubmitMyAssessmentAnswerRequest handles SubmitMyAssessmentAnswer operation. // // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, @@ -10888,6 +11161,12 @@ func (s *Server) handleSetMySearchStatusRequest(args [0]string, argsEscaped bool // The response is the attempt with the next item to answer. It never says whether the answer was // correct. Items are answered in order and each answer is final. // +// A work command requires an active session. After `idle_timeout_seconds` of inactivity, the candidate +// calls StartMyAssessmentAttemptSession to explicitly start or resume a session; this answer command +// never starts one or consumes session quota. Reading the attempt or result is always read-only. A +// command that finds a due deadline transition may commit it before returning; a command that finds an +// expired idle session answers 409 until the candidate explicitly starts the next session. +// // Practice: an answer with format `practice` submits the solution of the main or the additional // practice. It is stored, and the sandbox runs it asynchronously against the hidden check groups; the // response shows the practice `pending`, and the client polls GetMyAssessmentAttempt for the verdict. @@ -10921,15 +11200,14 @@ func (s *Server) handleSetMySearchStatusRequest(args [0]string, argsEscaped bool // // Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), // account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), -// the attempt (404 not_found for an unknown attempt or one of another candidate; the server first -// commits any due transition such as expiry, and the request counts as activity for the session -// limit), the repeat of the stored answer (200, skipped for a practice whose latest verdict is -// `failed`), the version (412), the state (409 state_conflict: the attempt is terminal, the item is -// not current, the item has a different answer, or the practice verdict is pending or finished), then -// the answer against the item (400 with a pointer such as `/answer/format` or `/answer/option_ids/0`). -// Following the Idempotency-Key convention, 404 and 409 state_conflict are stored under the key and -// replayed; 400, 412, 429, and 5xx are not. The rate limit can answer 429 with Retry-After before any -// check. +// the attempt (404 not_found for an unknown attempt or one of another candidate; a due deadline +// transition may be committed, but this request never starts a work session), the repeat of the stored +// answer (200, skipped for a practice whose latest verdict is `failed`), the version (412), the state +// (409 state_conflict: the attempt is terminal, the work session ended, the item is not current, the +// item has a different answer, or the practice verdict is pending or finished), then the answer +// against the item (400 with a pointer such as `/answer/format` or `/answer/option_ids/0`). Following +// the Idempotency-Key convention, 404 and 409 state_conflict are stored under the key and replayed; +// 400, 412, 429, and 5xx are not. The rate limit can answer 429 with Retry-After before any check. // // POST /api/v1/me/assessment-attempts/{attempt_id}/answers func (s *Server) handleSubmitMyAssessmentAnswerRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { diff --git a/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go b/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go index be3faf7..01abde0 100644 --- a/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go @@ -185,6 +185,10 @@ type SetMySearchStatusRes interface { setMySearchStatusRes() } +type StartMyAssessmentAttemptSessionRes interface { + startMyAssessmentAttemptSessionRes() +} + type SubmitMyAssessmentAnswerRes interface { submitMyAssessmentAnswerRes() } diff --git a/backend/internal/adapter/primary/http/api/oas_json_gen.go b/backend/internal/adapter/primary/http/api/oas_json_gen.go index a063e14..36bafc8 100644 --- a/backend/internal/adapter/primary/http/api/oas_json_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_json_gen.go @@ -1142,314 +1142,318 @@ func (s *AssessmentAnswerSubmission) UnmarshalJSON(data []byte) error { return s.Decode(d) } -// Encode implements json.Marshaler. -func (s *AssessmentAttempt) Encode(e *jx.Encoder) { +// Encode encodes AssessmentAttempt as json. +func (s AssessmentAttempt) Encode(e *jx.Encoder) { e.ObjStart() s.encodeFields(e) e.ObjEnd() } -// encodeFields encodes fields. -func (s *AssessmentAttempt) encodeFields(e *jx.Encoder) { - { - e.FieldStart("id") - json.EncodeUUID(e, s.ID) - } - { - e.FieldStart("version") - s.Version.Encode(e) - } - { - e.FieldStart("specialization") - s.Specialization.Encode(e) - } - { - e.FieldStart("target_grade") - s.TargetGrade.Encode(e) - } - { - e.FieldStart("task_language") - s.TaskLanguage.Encode(e) - } - { - e.FieldStart("mode") - s.Mode.Encode(e) - } - { - e.FieldStart("state") - s.State.Encode(e) - } - { - e.FieldStart("versions") - s.Versions.Encode(e) - } - { - e.FieldStart("started_at") - s.StartedAt.Encode(e) - } - { - e.FieldStart("expires_at") - s.ExpiresAt.Encode(e) - } - { - e.FieldStart("sessions") - s.Sessions.Encode(e) - } - { - e.FieldStart("finished_at") - s.FinishedAt.Encode(e) - } - { - e.FieldStart("progress") - s.Progress.Encode(e) - } - { - e.FieldStart("current_item") - s.CurrentItem.Encode(e) - } - { - e.FieldStart("practices") - e.ArrStart() - for _, elem := range s.Practices { - elem.Encode(e) +func (s AssessmentAttempt) encodeFields(e *jx.Encoder) { + switch s.Type { + case AssessmentQualifiedAttemptAssessmentAttempt: + e.FieldStart("kind") + e.Str("root") + { + s := s.AssessmentQualifiedAttempt + { + e.FieldStart("id") + json.EncodeUUID(e, s.ID) + } + { + e.FieldStart("version") + s.Version.Encode(e) + } + { + e.FieldStart("specialization") + s.Specialization.Encode(e) + } + { + e.FieldStart("target_grade") + s.TargetGrade.Encode(e) + } + { + e.FieldStart("task_language") + s.TaskLanguage.Encode(e) + } + { + e.FieldStart("root_attempt_id") + s.RootAttemptID.Encode(e) + } + { + e.FieldStart("chain_deadline") + s.ChainDeadline.Encode(e) + } + { + e.FieldStart("mode") + s.Mode.Encode(e) + } + { + e.FieldStart("state") + s.State.Encode(e) + } + { + e.FieldStart("versions") + s.Versions.Encode(e) + } + { + e.FieldStart("started_at") + s.StartedAt.Encode(e) + } + { + e.FieldStart("expires_at") + s.ExpiresAt.Encode(e) + } + { + e.FieldStart("sessions") + s.Sessions.Encode(e) + } + { + e.FieldStart("finished_at") + s.FinishedAt.Encode(e) + } + { + e.FieldStart("progress") + s.Progress.Encode(e) + } + { + e.FieldStart("current_item") + s.CurrentItem.Encode(e) + } + { + e.FieldStart("practices") + e.ArrStart() + for _, elem := range s.Practices { + elem.Encode(e) + } + e.ArrEnd() + } + } + case AssessmentCorrectiveAttemptAssessmentAttempt: + e.FieldStart("kind") + e.Str("corrective") + { + s := s.AssessmentCorrectiveAttempt + { + e.FieldStart("id") + json.EncodeUUID(e, s.ID) + } + { + e.FieldStart("version") + s.Version.Encode(e) + } + { + e.FieldStart("specialization") + s.Specialization.Encode(e) + } + { + e.FieldStart("target_grade") + s.TargetGrade.Encode(e) + } + { + e.FieldStart("task_language") + s.TaskLanguage.Encode(e) + } + { + e.FieldStart("root_attempt_id") + s.RootAttemptID.Encode(e) + } + { + e.FieldStart("chain_deadline") + s.ChainDeadline.Encode(e) + } + { + e.FieldStart("mode") + s.Mode.Encode(e) + } + { + e.FieldStart("state") + s.State.Encode(e) + } + { + e.FieldStart("versions") + s.Versions.Encode(e) + } + { + e.FieldStart("started_at") + s.StartedAt.Encode(e) + } + { + e.FieldStart("expires_at") + s.ExpiresAt.Encode(e) + } + { + e.FieldStart("sessions") + s.Sessions.Encode(e) + } + { + e.FieldStart("finished_at") + s.FinishedAt.Encode(e) + } + { + e.FieldStart("progress") + s.Progress.Encode(e) + } + { + e.FieldStart("current_item") + s.CurrentItem.Encode(e) + } + { + e.FieldStart("practices") + e.ArrStart() + for _, elem := range s.Practices { + elem.Encode(e) + } + e.ArrEnd() + } + } + case AssessmentExpressAttemptAssessmentAttempt: + e.FieldStart("kind") + e.Str("demo_express") + { + s := s.AssessmentExpressAttempt + { + e.FieldStart("id") + json.EncodeUUID(e, s.ID) + } + { + e.FieldStart("version") + s.Version.Encode(e) + } + { + e.FieldStart("specialization") + s.Specialization.Encode(e) + } + { + e.FieldStart("target_grade") + s.TargetGrade.Encode(e) + } + { + e.FieldStart("task_language") + s.TaskLanguage.Encode(e) + } + { + e.FieldStart("root_attempt_id") + s.RootAttemptID.Encode(e) + } + { + e.FieldStart("chain_deadline") + s.ChainDeadline.Encode(e) + } + { + e.FieldStart("mode") + s.Mode.Encode(e) + } + { + e.FieldStart("state") + s.State.Encode(e) + } + { + e.FieldStart("versions") + s.Versions.Encode(e) + } + { + e.FieldStart("started_at") + s.StartedAt.Encode(e) + } + { + e.FieldStart("expires_at") + s.ExpiresAt.Encode(e) + } + { + e.FieldStart("sessions") + s.Sessions.Encode(e) + } + { + e.FieldStart("finished_at") + s.FinishedAt.Encode(e) + } + { + e.FieldStart("progress") + s.Progress.Encode(e) + } + { + e.FieldStart("current_item") + s.CurrentItem.Encode(e) + } + { + e.FieldStart("practices") + e.ArrStart() + for _, elem := range s.Practices { + elem.Encode(e) + } + e.ArrEnd() + } } - e.ArrEnd() } } -var jsonFieldsNameOfAssessmentAttempt = [15]string{ - 0: "id", - 1: "version", - 2: "specialization", - 3: "target_grade", - 4: "task_language", - 5: "mode", - 6: "state", - 7: "versions", - 8: "started_at", - 9: "expires_at", - 10: "sessions", - 11: "finished_at", - 12: "progress", - 13: "current_item", - 14: "practices", -} - // Decode decodes AssessmentAttempt from json. func (s *AssessmentAttempt) Decode(d *jx.Decoder) error { if s == nil { return errors.New("invalid: unable to decode AssessmentAttempt to nil") } - var requiredBitSet [2]uint8 + // Sum type discriminator. + if typ := d.Next(); typ != jx.Object { + return errors.Errorf("unexpected json type %q", typ) + } - if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { - switch string(k) { - case "id": - requiredBitSet[0] |= 1 << 0 - if err := func() error { - v, err := json.DecodeUUID(d) - s.ID = v + var found bool + if err := d.Capture(func(d *jx.Decoder) error { + return d.ObjBytes(func(d *jx.Decoder, key []byte) error { + if found { + return d.Skip() + } + switch string(key) { + case "kind": + typ, err := d.Str() if err != nil { return err } - return nil - }(); err != nil { - return errors.Wrap(err, "decode field \"id\"") - } - case "version": - requiredBitSet[0] |= 1 << 1 - if err := func() error { - if err := s.Version.Decode(d); err != nil { - return err + switch typ { + case "root": + s.Type = AssessmentQualifiedAttemptAssessmentAttempt + found = true + case "corrective": + s.Type = AssessmentCorrectiveAttemptAssessmentAttempt + found = true + case "demo_express": + s.Type = AssessmentExpressAttemptAssessmentAttempt + found = true + default: + return errors.Errorf("unknown type %s", typ) } return nil - }(); err != nil { - return errors.Wrap(err, "decode field \"version\"") } - case "specialization": - requiredBitSet[0] |= 1 << 2 - if err := func() error { - if err := s.Specialization.Decode(d); err != nil { - return err - } - return nil - }(); err != nil { - return errors.Wrap(err, "decode field \"specialization\"") - } - case "target_grade": - requiredBitSet[0] |= 1 << 3 - if err := func() error { - if err := s.TargetGrade.Decode(d); err != nil { - return err - } - return nil - }(); err != nil { - return errors.Wrap(err, "decode field \"target_grade\"") - } - case "task_language": - requiredBitSet[0] |= 1 << 4 - if err := func() error { - if err := s.TaskLanguage.Decode(d); err != nil { - return err - } - return nil - }(); err != nil { - return errors.Wrap(err, "decode field \"task_language\"") - } - case "mode": - requiredBitSet[0] |= 1 << 5 - if err := func() error { - if err := s.Mode.Decode(d); err != nil { - return err - } - return nil - }(); err != nil { - return errors.Wrap(err, "decode field \"mode\"") - } - case "state": - requiredBitSet[0] |= 1 << 6 - if err := func() error { - if err := s.State.Decode(d); err != nil { - return err - } - return nil - }(); err != nil { - return errors.Wrap(err, "decode field \"state\"") - } - case "versions": - requiredBitSet[0] |= 1 << 7 - if err := func() error { - if err := s.Versions.Decode(d); err != nil { - return err - } - return nil - }(); err != nil { - return errors.Wrap(err, "decode field \"versions\"") - } - case "started_at": - requiredBitSet[1] |= 1 << 0 - if err := func() error { - if err := s.StartedAt.Decode(d); err != nil { - return err - } - return nil - }(); err != nil { - return errors.Wrap(err, "decode field \"started_at\"") - } - case "expires_at": - requiredBitSet[1] |= 1 << 1 - if err := func() error { - if err := s.ExpiresAt.Decode(d); err != nil { - return err - } - return nil - }(); err != nil { - return errors.Wrap(err, "decode field \"expires_at\"") - } - case "sessions": - requiredBitSet[1] |= 1 << 2 - if err := func() error { - if err := s.Sessions.Decode(d); err != nil { - return err - } - return nil - }(); err != nil { - return errors.Wrap(err, "decode field \"sessions\"") - } - case "finished_at": - requiredBitSet[1] |= 1 << 3 - if err := func() error { - if err := s.FinishedAt.Decode(d); err != nil { - return err - } - return nil - }(); err != nil { - return errors.Wrap(err, "decode field \"finished_at\"") - } - case "progress": - requiredBitSet[1] |= 1 << 4 - if err := func() error { - if err := s.Progress.Decode(d); err != nil { - return err - } - return nil - }(); err != nil { - return errors.Wrap(err, "decode field \"progress\"") - } - case "current_item": - requiredBitSet[1] |= 1 << 5 - if err := func() error { - if err := s.CurrentItem.Decode(d); err != nil { - return err - } - return nil - }(); err != nil { - return errors.Wrap(err, "decode field \"current_item\"") - } - case "practices": - requiredBitSet[1] |= 1 << 6 - if err := func() error { - s.Practices = make([]AssessmentPractice, 0) - if err := d.Arr(func(d *jx.Decoder) error { - var elem AssessmentPractice - if err := elem.Decode(d); err != nil { - return err - } - s.Practices = append(s.Practices, elem) - return nil - }); err != nil { - return err - } - return nil - }(); err != nil { - return errors.Wrap(err, "decode field \"practices\"") - } - default: - return errors.Errorf("unexpected field %q", k) - } - return nil + return d.Skip() + }) }); err != nil { - return errors.Wrap(err, "decode AssessmentAttempt") + return errors.Wrap(err, "capture") } - // Validate required fields. - var failures []validate.FieldError - for i, mask := range [2]uint8{ - 0b11111111, - 0b01111111, - } { - 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(jsonFieldsNameOfAssessmentAttempt) { - name = jsonFieldsNameOfAssessmentAttempt[fieldIdx] - } else { - name = strconv.Itoa(fieldIdx) - } - failures = append(failures, validate.FieldError{ - Name: name, - Error: validate.ErrFieldRequired, - }) - // Reset bit. - result &^= 1 << bitIdx - } + if !found { + return errors.New("unable to detect sum type variant") + } + switch s.Type { + case AssessmentQualifiedAttemptAssessmentAttempt: + if err := s.AssessmentQualifiedAttempt.Decode(d); err != nil { + return err } + case AssessmentCorrectiveAttemptAssessmentAttempt: + if err := s.AssessmentCorrectiveAttempt.Decode(d); err != nil { + return err + } + case AssessmentExpressAttemptAssessmentAttempt: + if err := s.AssessmentExpressAttempt.Decode(d); err != nil { + return err + } + default: + return errors.Errorf("inferred invalid type: %s", s.Type) } - if len(failures) > 0 { - return &validate.Error{Fields: failures} - } - return nil } // MarshalJSON implements stdjson.Marshaler. -func (s *AssessmentAttempt) MarshalJSON() ([]byte, error) { +func (s AssessmentAttempt) MarshalJSON() ([]byte, error) { e := jx.Encoder{} s.Encode(&e) return e.Bytes(), nil @@ -1461,33 +1465,59 @@ func (s *AssessmentAttempt) UnmarshalJSON(data []byte) error { return s.Decode(d) } -// Encode implements json.Marshaler. -func (s *AssessmentAttemptCreate) Encode(e *jx.Encoder) { +// Encode encodes AssessmentAttemptCreate as json. +func (s AssessmentAttemptCreate) Encode(e *jx.Encoder) { e.ObjStart() s.encodeFields(e) e.ObjEnd() } -// encodeFields encodes fields. -func (s *AssessmentAttemptCreate) encodeFields(e *jx.Encoder) { - { - e.FieldStart("specialization") - s.Specialization.Encode(e) +func (s AssessmentAttemptCreate) encodeFields(e *jx.Encoder) { + switch s.Type { + case AssessmentQualifiedAttemptCreateAssessmentAttemptCreate: + e.FieldStart("kind") + e.Str("root") + { + s := s.AssessmentQualifiedAttemptCreate + { + e.FieldStart("specialization") + s.Specialization.Encode(e) + } + { + e.FieldStart("target_grade") + s.TargetGrade.Encode(e) + } + { + e.FieldStart("task_language") + s.TaskLanguage.Encode(e) + } + } + case AssessmentCorrectiveAttemptCreateAssessmentAttemptCreate: + e.FieldStart("kind") + e.Str("corrective") + { + s := s.AssessmentCorrectiveAttemptCreate + { + e.FieldStart("specialization") + s.Specialization.Encode(e) + } + { + e.FieldStart("target_grade") + s.TargetGrade.Encode(e) + } + { + e.FieldStart("task_language") + s.TaskLanguage.Encode(e) + } + { + e.FieldStart("root_attempt_id") + json.EncodeUUID(e, s.RootAttemptID) + } + } + case AssessmentExpressAttemptCreateAssessmentAttemptCreate: + e.FieldStart("kind") + e.Str("demo_express") } - { - e.FieldStart("target_grade") - s.TargetGrade.Encode(e) - } - { - e.FieldStart("task_language") - s.TaskLanguage.Encode(e) - } -} - -var jsonFieldsNameOfAssessmentAttemptCreate = [3]string{ - 0: "specialization", - 1: "target_grade", - 2: "task_language", } // Decode decodes AssessmentAttemptCreate from json. @@ -1495,51 +1525,127 @@ func (s *AssessmentAttemptCreate) Decode(d *jx.Decoder) error { if s == nil { return errors.New("invalid: unable to decode AssessmentAttemptCreate to nil") } + // Sum type discriminator. + if typ := d.Next(); typ != jx.Object { + return errors.Errorf("unexpected json type %q", typ) + } + + var found bool + if err := d.Capture(func(d *jx.Decoder) error { + return d.ObjBytes(func(d *jx.Decoder, key []byte) error { + if found { + return d.Skip() + } + switch string(key) { + case "kind": + typ, err := d.Str() + if err != nil { + return err + } + switch typ { + case "root": + s.Type = AssessmentQualifiedAttemptCreateAssessmentAttemptCreate + found = true + case "corrective": + s.Type = AssessmentCorrectiveAttemptCreateAssessmentAttemptCreate + found = true + case "demo_express": + s.Type = AssessmentExpressAttemptCreateAssessmentAttemptCreate + found = true + default: + return errors.Errorf("unknown type %s", typ) + } + return nil + } + return d.Skip() + }) + }); err != nil { + return errors.Wrap(err, "capture") + } + if !found { + return errors.New("unable to detect sum type variant") + } + switch s.Type { + case AssessmentQualifiedAttemptCreateAssessmentAttemptCreate: + if err := s.AssessmentQualifiedAttemptCreate.Decode(d); err != nil { + return err + } + case AssessmentCorrectiveAttemptCreateAssessmentAttemptCreate: + if err := s.AssessmentCorrectiveAttemptCreate.Decode(d); err != nil { + return err + } + case AssessmentExpressAttemptCreateAssessmentAttemptCreate: + if err := s.AssessmentExpressAttemptCreate.Decode(d); err != nil { + return err + } + default: + return errors.Errorf("inferred invalid type: %s", s.Type) + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AssessmentAttemptCreate) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentAttemptCreate) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *AssessmentAttemptSessionStart) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *AssessmentAttemptSessionStart) encodeFields(e *jx.Encoder) { + { + e.FieldStart("expected_version") + s.ExpectedVersion.Encode(e) + } +} + +var jsonFieldsNameOfAssessmentAttemptSessionStart = [1]string{ + 0: "expected_version", +} + +// Decode decodes AssessmentAttemptSessionStart from json. +func (s *AssessmentAttemptSessionStart) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentAttemptSessionStart to nil") + } var requiredBitSet [1]uint8 if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { switch string(k) { - case "specialization": + case "expected_version": requiredBitSet[0] |= 1 << 0 if err := func() error { - if err := s.Specialization.Decode(d); err != nil { + if err := s.ExpectedVersion.Decode(d); err != nil { return err } return nil }(); err != nil { - return errors.Wrap(err, "decode field \"specialization\"") - } - case "target_grade": - requiredBitSet[0] |= 1 << 1 - if err := func() error { - if err := s.TargetGrade.Decode(d); err != nil { - return err - } - return nil - }(); err != nil { - return errors.Wrap(err, "decode field \"target_grade\"") - } - case "task_language": - requiredBitSet[0] |= 1 << 2 - if err := func() error { - if err := s.TaskLanguage.Decode(d); err != nil { - return err - } - return nil - }(); err != nil { - return errors.Wrap(err, "decode field \"task_language\"") + return errors.Wrap(err, "decode field \"expected_version\"") } default: return errors.Errorf("unexpected field %q", k) } return nil }); err != nil { - return errors.Wrap(err, "decode AssessmentAttemptCreate") + return errors.Wrap(err, "decode AssessmentAttemptSessionStart") } // Validate required fields. var failures []validate.FieldError for i, mask := range [1]uint8{ - 0b00000111, + 0b00000001, } { if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { // Mask only required fields and check equality to mask using XOR. @@ -1551,8 +1657,8 @@ func (s *AssessmentAttemptCreate) Decode(d *jx.Decoder) error { bitIdx := bits.TrailingZeros8(result) fieldIdx := i*8 + bitIdx var name string - if fieldIdx < len(jsonFieldsNameOfAssessmentAttemptCreate) { - name = jsonFieldsNameOfAssessmentAttemptCreate[fieldIdx] + if fieldIdx < len(jsonFieldsNameOfAssessmentAttemptSessionStart) { + name = jsonFieldsNameOfAssessmentAttemptSessionStart[fieldIdx] } else { name = strconv.Itoa(fieldIdx) } @@ -1573,14 +1679,14 @@ func (s *AssessmentAttemptCreate) Decode(d *jx.Decoder) error { } // MarshalJSON implements stdjson.Marshaler. -func (s *AssessmentAttemptCreate) MarshalJSON() ([]byte, error) { +func (s *AssessmentAttemptSessionStart) MarshalJSON() ([]byte, error) { e := jx.Encoder{} s.Encode(&e) return e.Bytes(), nil } // UnmarshalJSON implements stdjson.Unmarshaler. -func (s *AssessmentAttemptCreate) UnmarshalJSON(data []byte) error { +func (s *AssessmentAttemptSessionStart) UnmarshalJSON(data []byte) error { d := jx.DecodeBytes(data) return s.Decode(d) } @@ -1781,6 +1887,1197 @@ func (s *AssessmentAvailability) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode implements json.Marshaler. +func (s *AssessmentCorrectiveAttempt) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *AssessmentCorrectiveAttempt) encodeFields(e *jx.Encoder) { + { + e.FieldStart("id") + json.EncodeUUID(e, s.ID) + } + { + e.FieldStart("version") + s.Version.Encode(e) + } + { + e.FieldStart("specialization") + s.Specialization.Encode(e) + } + { + e.FieldStart("target_grade") + s.TargetGrade.Encode(e) + } + { + e.FieldStart("task_language") + s.TaskLanguage.Encode(e) + } + { + e.FieldStart("kind") + s.Kind.Encode(e) + } + { + e.FieldStart("root_attempt_id") + s.RootAttemptID.Encode(e) + } + { + e.FieldStart("chain_deadline") + s.ChainDeadline.Encode(e) + } + { + e.FieldStart("mode") + s.Mode.Encode(e) + } + { + e.FieldStart("state") + s.State.Encode(e) + } + { + e.FieldStart("versions") + s.Versions.Encode(e) + } + { + e.FieldStart("started_at") + s.StartedAt.Encode(e) + } + { + e.FieldStart("expires_at") + s.ExpiresAt.Encode(e) + } + { + e.FieldStart("sessions") + s.Sessions.Encode(e) + } + { + e.FieldStart("finished_at") + s.FinishedAt.Encode(e) + } + { + e.FieldStart("progress") + s.Progress.Encode(e) + } + { + e.FieldStart("current_item") + s.CurrentItem.Encode(e) + } + { + e.FieldStart("practices") + e.ArrStart() + for _, elem := range s.Practices { + elem.Encode(e) + } + e.ArrEnd() + } +} + +var jsonFieldsNameOfAssessmentCorrectiveAttempt = [18]string{ + 0: "id", + 1: "version", + 2: "specialization", + 3: "target_grade", + 4: "task_language", + 5: "kind", + 6: "root_attempt_id", + 7: "chain_deadline", + 8: "mode", + 9: "state", + 10: "versions", + 11: "started_at", + 12: "expires_at", + 13: "sessions", + 14: "finished_at", + 15: "progress", + 16: "current_item", + 17: "practices", +} + +// Decode decodes AssessmentCorrectiveAttempt from json. +func (s *AssessmentCorrectiveAttempt) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentCorrectiveAttempt to nil") + } + var requiredBitSet [3]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "id": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := json.DecodeUUID(d) + s.ID = v + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"id\"") + } + case "version": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Version.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"version\"") + } + case "specialization": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.Specialization.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"specialization\"") + } + case "target_grade": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + if err := s.TargetGrade.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"target_grade\"") + } + case "task_language": + requiredBitSet[0] |= 1 << 4 + if err := func() error { + if err := s.TaskLanguage.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"task_language\"") + } + case "kind": + requiredBitSet[0] |= 1 << 5 + if err := func() error { + if err := s.Kind.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"kind\"") + } + case "root_attempt_id": + requiredBitSet[0] |= 1 << 6 + if err := func() error { + if err := s.RootAttemptID.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"root_attempt_id\"") + } + case "chain_deadline": + requiredBitSet[0] |= 1 << 7 + if err := func() error { + if err := s.ChainDeadline.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"chain_deadline\"") + } + case "mode": + requiredBitSet[1] |= 1 << 0 + if err := func() error { + if err := s.Mode.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"mode\"") + } + case "state": + requiredBitSet[1] |= 1 << 1 + if err := func() error { + if err := s.State.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"state\"") + } + case "versions": + requiredBitSet[1] |= 1 << 2 + if err := func() error { + if err := s.Versions.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"versions\"") + } + case "started_at": + requiredBitSet[1] |= 1 << 3 + if err := func() error { + if err := s.StartedAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"started_at\"") + } + case "expires_at": + requiredBitSet[1] |= 1 << 4 + if err := func() error { + if err := s.ExpiresAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"expires_at\"") + } + case "sessions": + requiredBitSet[1] |= 1 << 5 + if err := func() error { + if err := s.Sessions.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"sessions\"") + } + case "finished_at": + requiredBitSet[1] |= 1 << 6 + if err := func() error { + if err := s.FinishedAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"finished_at\"") + } + case "progress": + requiredBitSet[1] |= 1 << 7 + if err := func() error { + if err := s.Progress.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"progress\"") + } + case "current_item": + requiredBitSet[2] |= 1 << 0 + if err := func() error { + if err := s.CurrentItem.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"current_item\"") + } + case "practices": + requiredBitSet[2] |= 1 << 1 + if err := func() error { + s.Practices = make([]AssessmentPractice, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem AssessmentPractice + if err := elem.Decode(d); err != nil { + return err + } + s.Practices = append(s.Practices, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"practices\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode AssessmentCorrectiveAttempt") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [3]uint8{ + 0b11111111, + 0b11111111, + 0b00000011, + } { + 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(jsonFieldsNameOfAssessmentCorrectiveAttempt) { + name = jsonFieldsNameOfAssessmentCorrectiveAttempt[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 *AssessmentCorrectiveAttempt) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentCorrectiveAttempt) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *AssessmentCorrectiveAttemptCreate) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *AssessmentCorrectiveAttemptCreate) encodeFields(e *jx.Encoder) { + { + e.FieldStart("kind") + s.Kind.Encode(e) + } + { + e.FieldStart("specialization") + s.Specialization.Encode(e) + } + { + e.FieldStart("target_grade") + s.TargetGrade.Encode(e) + } + { + e.FieldStart("task_language") + s.TaskLanguage.Encode(e) + } + { + e.FieldStart("root_attempt_id") + json.EncodeUUID(e, s.RootAttemptID) + } +} + +var jsonFieldsNameOfAssessmentCorrectiveAttemptCreate = [5]string{ + 0: "kind", + 1: "specialization", + 2: "target_grade", + 3: "task_language", + 4: "root_attempt_id", +} + +// Decode decodes AssessmentCorrectiveAttemptCreate from json. +func (s *AssessmentCorrectiveAttemptCreate) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentCorrectiveAttemptCreate to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "kind": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Kind.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"kind\"") + } + case "specialization": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Specialization.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"specialization\"") + } + case "target_grade": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.TargetGrade.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"target_grade\"") + } + case "task_language": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + if err := s.TaskLanguage.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"task_language\"") + } + case "root_attempt_id": + requiredBitSet[0] |= 1 << 4 + if err := func() error { + v, err := json.DecodeUUID(d) + s.RootAttemptID = v + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"root_attempt_id\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode AssessmentCorrectiveAttemptCreate") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00011111, + } { + 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(jsonFieldsNameOfAssessmentCorrectiveAttemptCreate) { + name = jsonFieldsNameOfAssessmentCorrectiveAttemptCreate[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 *AssessmentCorrectiveAttemptCreate) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentCorrectiveAttemptCreate) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentCorrectiveAttemptCreateKind as json. +func (s AssessmentCorrectiveAttemptCreateKind) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes AssessmentCorrectiveAttemptCreateKind from json. +func (s *AssessmentCorrectiveAttemptCreateKind) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentCorrectiveAttemptCreateKind to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch AssessmentCorrectiveAttemptCreateKind(v) { + case AssessmentCorrectiveAttemptCreateKindCorrective: + *s = AssessmentCorrectiveAttemptCreateKindCorrective + default: + *s = AssessmentCorrectiveAttemptCreateKind(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AssessmentCorrectiveAttemptCreateKind) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentCorrectiveAttemptCreateKind) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentCorrectiveAttemptKind as json. +func (s AssessmentCorrectiveAttemptKind) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes AssessmentCorrectiveAttemptKind from json. +func (s *AssessmentCorrectiveAttemptKind) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentCorrectiveAttemptKind to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch AssessmentCorrectiveAttemptKind(v) { + case AssessmentCorrectiveAttemptKindCorrective: + *s = AssessmentCorrectiveAttemptKindCorrective + default: + *s = AssessmentCorrectiveAttemptKind(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AssessmentCorrectiveAttemptKind) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentCorrectiveAttemptKind) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentCorrectiveAttemptMode as json. +func (s AssessmentCorrectiveAttemptMode) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes AssessmentCorrectiveAttemptMode from json. +func (s *AssessmentCorrectiveAttemptMode) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentCorrectiveAttemptMode to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch AssessmentCorrectiveAttemptMode(v) { + case AssessmentCorrectiveAttemptModeDemoBasic: + *s = AssessmentCorrectiveAttemptModeDemoBasic + case AssessmentCorrectiveAttemptModeAdaptive: + *s = AssessmentCorrectiveAttemptModeAdaptive + default: + *s = AssessmentCorrectiveAttemptMode(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AssessmentCorrectiveAttemptMode) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentCorrectiveAttemptMode) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *AssessmentCorrectiveResult) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *AssessmentCorrectiveResult) encodeFields(e *jx.Encoder) { + { + e.FieldStart("attempt_id") + json.EncodeUUID(e, s.AttemptID) + } + { + e.FieldStart("specialization") + s.Specialization.Encode(e) + } + { + e.FieldStart("target_grade") + s.TargetGrade.Encode(e) + } + { + e.FieldStart("root_attempt_id") + s.RootAttemptID.Encode(e) + } + { + e.FieldStart("chain_deadline") + s.ChainDeadline.Encode(e) + } + { + e.FieldStart("task_language") + s.TaskLanguage.Encode(e) + } + { + e.FieldStart("kind") + s.Kind.Encode(e) + } + { + e.FieldStart("mode") + s.Mode.Encode(e) + } + { + e.FieldStart("versions") + s.Versions.Encode(e) + } + { + e.FieldStart("outcome") + s.Outcome.Encode(e) + } + { + e.FieldStart("not_determined_reason") + s.NotDeterminedReason.Encode(e) + } + { + e.FieldStart("confirmed_grade") + s.ConfirmedGrade.Encode(e) + } + { + e.FieldStart("previous_confirmed_grade") + s.PreviousConfirmedGrade.Encode(e) + } + { + e.FieldStart("strength") + s.Strength.Encode(e) + } + { + e.FieldStart("calibration_status") + s.CalibrationStatus.Encode(e) + } + { + e.FieldStart("limitations") + e.ArrStart() + for _, elem := range s.Limitations { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("uncertainty") + s.Uncertainty.Encode(e) + } + { + e.FieldStart("basic_score") + s.BasicScore.Encode(e) + } + { + e.FieldStart("practices") + e.ArrStart() + for _, elem := range s.Practices { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("gaps") + e.ArrStart() + for _, elem := range s.Gaps { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("durations") + s.Durations.Encode(e) + } + { + e.FieldStart("next_steps") + e.ArrStart() + for _, elem := range s.NextSteps { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("decided_at") + s.DecidedAt.Encode(e) + } +} + +var jsonFieldsNameOfAssessmentCorrectiveResult = [23]string{ + 0: "attempt_id", + 1: "specialization", + 2: "target_grade", + 3: "root_attempt_id", + 4: "chain_deadline", + 5: "task_language", + 6: "kind", + 7: "mode", + 8: "versions", + 9: "outcome", + 10: "not_determined_reason", + 11: "confirmed_grade", + 12: "previous_confirmed_grade", + 13: "strength", + 14: "calibration_status", + 15: "limitations", + 16: "uncertainty", + 17: "basic_score", + 18: "practices", + 19: "gaps", + 20: "durations", + 21: "next_steps", + 22: "decided_at", +} + +// Decode decodes AssessmentCorrectiveResult from json. +func (s *AssessmentCorrectiveResult) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentCorrectiveResult to nil") + } + var requiredBitSet [3]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "attempt_id": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := json.DecodeUUID(d) + s.AttemptID = v + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"attempt_id\"") + } + case "specialization": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Specialization.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"specialization\"") + } + case "target_grade": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.TargetGrade.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"target_grade\"") + } + case "root_attempt_id": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + if err := s.RootAttemptID.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"root_attempt_id\"") + } + case "chain_deadline": + requiredBitSet[0] |= 1 << 4 + if err := func() error { + if err := s.ChainDeadline.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"chain_deadline\"") + } + case "task_language": + requiredBitSet[0] |= 1 << 5 + if err := func() error { + if err := s.TaskLanguage.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"task_language\"") + } + case "kind": + requiredBitSet[0] |= 1 << 6 + if err := func() error { + if err := s.Kind.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"kind\"") + } + case "mode": + requiredBitSet[0] |= 1 << 7 + if err := func() error { + if err := s.Mode.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"mode\"") + } + case "versions": + requiredBitSet[1] |= 1 << 0 + if err := func() error { + if err := s.Versions.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"versions\"") + } + case "outcome": + requiredBitSet[1] |= 1 << 1 + if err := func() error { + if err := s.Outcome.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"outcome\"") + } + case "not_determined_reason": + requiredBitSet[1] |= 1 << 2 + if err := func() error { + if err := s.NotDeterminedReason.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"not_determined_reason\"") + } + case "confirmed_grade": + requiredBitSet[1] |= 1 << 3 + if err := func() error { + if err := s.ConfirmedGrade.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"confirmed_grade\"") + } + case "previous_confirmed_grade": + requiredBitSet[1] |= 1 << 4 + if err := func() error { + if err := s.PreviousConfirmedGrade.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"previous_confirmed_grade\"") + } + case "strength": + requiredBitSet[1] |= 1 << 5 + if err := func() error { + if err := s.Strength.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"strength\"") + } + case "calibration_status": + requiredBitSet[1] |= 1 << 6 + if err := func() error { + if err := s.CalibrationStatus.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"calibration_status\"") + } + case "limitations": + requiredBitSet[1] |= 1 << 7 + if err := func() error { + s.Limitations = make([]AssessmentLimitation, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem AssessmentLimitation + if err := elem.Decode(d); err != nil { + return err + } + s.Limitations = append(s.Limitations, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"limitations\"") + } + case "uncertainty": + requiredBitSet[2] |= 1 << 0 + if err := func() error { + if err := s.Uncertainty.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"uncertainty\"") + } + case "basic_score": + requiredBitSet[2] |= 1 << 1 + if err := func() error { + if err := s.BasicScore.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"basic_score\"") + } + case "practices": + requiredBitSet[2] |= 1 << 2 + if err := func() error { + s.Practices = make([]AssessmentPracticeResult, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem AssessmentPracticeResult + if err := elem.Decode(d); err != nil { + return err + } + s.Practices = append(s.Practices, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"practices\"") + } + case "gaps": + requiredBitSet[2] |= 1 << 3 + if err := func() error { + s.Gaps = make([]AssessmentGap, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem AssessmentGap + if err := elem.Decode(d); err != nil { + return err + } + s.Gaps = append(s.Gaps, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"gaps\"") + } + case "durations": + requiredBitSet[2] |= 1 << 4 + if err := func() error { + if err := s.Durations.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"durations\"") + } + case "next_steps": + requiredBitSet[2] |= 1 << 5 + if err := func() error { + s.NextSteps = make([]AssessmentNextStep, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem AssessmentNextStep + if err := elem.Decode(d); err != nil { + return err + } + s.NextSteps = append(s.NextSteps, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"next_steps\"") + } + case "decided_at": + requiredBitSet[2] |= 1 << 6 + if err := func() error { + if err := s.DecidedAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"decided_at\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode AssessmentCorrectiveResult") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [3]uint8{ + 0b11111111, + 0b11111111, + 0b01111111, + } { + 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(jsonFieldsNameOfAssessmentCorrectiveResult) { + name = jsonFieldsNameOfAssessmentCorrectiveResult[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 *AssessmentCorrectiveResult) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentCorrectiveResult) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentCorrectiveResultKind as json. +func (s AssessmentCorrectiveResultKind) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes AssessmentCorrectiveResultKind from json. +func (s *AssessmentCorrectiveResultKind) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentCorrectiveResultKind to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch AssessmentCorrectiveResultKind(v) { + case AssessmentCorrectiveResultKindCorrective: + *s = AssessmentCorrectiveResultKindCorrective + default: + *s = AssessmentCorrectiveResultKind(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AssessmentCorrectiveResultKind) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentCorrectiveResultKind) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentCorrectiveResultMode as json. +func (s AssessmentCorrectiveResultMode) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes AssessmentCorrectiveResultMode from json. +func (s *AssessmentCorrectiveResultMode) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentCorrectiveResultMode to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch AssessmentCorrectiveResultMode(v) { + case AssessmentCorrectiveResultModeDemoBasic: + *s = AssessmentCorrectiveResultModeDemoBasic + case AssessmentCorrectiveResultModeAdaptive: + *s = AssessmentCorrectiveResultModeAdaptive + default: + *s = AssessmentCorrectiveResultMode(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AssessmentCorrectiveResultMode) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentCorrectiveResultMode) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode implements json.Marshaler. func (s *AssessmentDurations) Encode(e *jx.Encoder) { e.ObjStart() @@ -1892,6 +3189,1241 @@ func (s *AssessmentDurations) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode implements json.Marshaler. +func (s *AssessmentExpressAttempt) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *AssessmentExpressAttempt) encodeFields(e *jx.Encoder) { + { + e.FieldStart("id") + json.EncodeUUID(e, s.ID) + } + { + e.FieldStart("version") + s.Version.Encode(e) + } + { + e.FieldStart("specialization") + s.Specialization.Encode(e) + } + { + e.FieldStart("target_grade") + s.TargetGrade.Encode(e) + } + { + e.FieldStart("task_language") + s.TaskLanguage.Encode(e) + } + { + e.FieldStart("kind") + s.Kind.Encode(e) + } + { + e.FieldStart("root_attempt_id") + s.RootAttemptID.Encode(e) + } + { + e.FieldStart("chain_deadline") + s.ChainDeadline.Encode(e) + } + { + e.FieldStart("mode") + s.Mode.Encode(e) + } + { + e.FieldStart("state") + s.State.Encode(e) + } + { + e.FieldStart("versions") + s.Versions.Encode(e) + } + { + e.FieldStart("started_at") + s.StartedAt.Encode(e) + } + { + e.FieldStart("expires_at") + s.ExpiresAt.Encode(e) + } + { + e.FieldStart("sessions") + s.Sessions.Encode(e) + } + { + e.FieldStart("finished_at") + s.FinishedAt.Encode(e) + } + { + e.FieldStart("progress") + s.Progress.Encode(e) + } + { + e.FieldStart("current_item") + s.CurrentItem.Encode(e) + } + { + e.FieldStart("practices") + e.ArrStart() + for _, elem := range s.Practices { + elem.Encode(e) + } + e.ArrEnd() + } +} + +var jsonFieldsNameOfAssessmentExpressAttempt = [18]string{ + 0: "id", + 1: "version", + 2: "specialization", + 3: "target_grade", + 4: "task_language", + 5: "kind", + 6: "root_attempt_id", + 7: "chain_deadline", + 8: "mode", + 9: "state", + 10: "versions", + 11: "started_at", + 12: "expires_at", + 13: "sessions", + 14: "finished_at", + 15: "progress", + 16: "current_item", + 17: "practices", +} + +// Decode decodes AssessmentExpressAttempt from json. +func (s *AssessmentExpressAttempt) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentExpressAttempt to nil") + } + var requiredBitSet [3]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "id": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := json.DecodeUUID(d) + s.ID = v + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"id\"") + } + case "version": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Version.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"version\"") + } + case "specialization": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.Specialization.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"specialization\"") + } + case "target_grade": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + if err := s.TargetGrade.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"target_grade\"") + } + case "task_language": + requiredBitSet[0] |= 1 << 4 + if err := func() error { + if err := s.TaskLanguage.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"task_language\"") + } + case "kind": + requiredBitSet[0] |= 1 << 5 + if err := func() error { + if err := s.Kind.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"kind\"") + } + case "root_attempt_id": + requiredBitSet[0] |= 1 << 6 + if err := func() error { + if err := s.RootAttemptID.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"root_attempt_id\"") + } + case "chain_deadline": + requiredBitSet[0] |= 1 << 7 + if err := func() error { + if err := s.ChainDeadline.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"chain_deadline\"") + } + case "mode": + requiredBitSet[1] |= 1 << 0 + if err := func() error { + if err := s.Mode.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"mode\"") + } + case "state": + requiredBitSet[1] |= 1 << 1 + if err := func() error { + if err := s.State.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"state\"") + } + case "versions": + requiredBitSet[1] |= 1 << 2 + if err := func() error { + if err := s.Versions.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"versions\"") + } + case "started_at": + requiredBitSet[1] |= 1 << 3 + if err := func() error { + if err := s.StartedAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"started_at\"") + } + case "expires_at": + requiredBitSet[1] |= 1 << 4 + if err := func() error { + if err := s.ExpiresAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"expires_at\"") + } + case "sessions": + requiredBitSet[1] |= 1 << 5 + if err := func() error { + if err := s.Sessions.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"sessions\"") + } + case "finished_at": + requiredBitSet[1] |= 1 << 6 + if err := func() error { + if err := s.FinishedAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"finished_at\"") + } + case "progress": + requiredBitSet[1] |= 1 << 7 + if err := func() error { + if err := s.Progress.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"progress\"") + } + case "current_item": + requiredBitSet[2] |= 1 << 0 + if err := func() error { + if err := s.CurrentItem.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"current_item\"") + } + case "practices": + requiredBitSet[2] |= 1 << 1 + if err := func() error { + s.Practices = make([]AssessmentPractice, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem AssessmentPractice + if err := elem.Decode(d); err != nil { + return err + } + s.Practices = append(s.Practices, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"practices\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode AssessmentExpressAttempt") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [3]uint8{ + 0b11111111, + 0b11111111, + 0b00000011, + } { + 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(jsonFieldsNameOfAssessmentExpressAttempt) { + name = jsonFieldsNameOfAssessmentExpressAttempt[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 *AssessmentExpressAttempt) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentExpressAttempt) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *AssessmentExpressAttemptCreate) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *AssessmentExpressAttemptCreate) encodeFields(e *jx.Encoder) { + { + e.FieldStart("kind") + s.Kind.Encode(e) + } +} + +var jsonFieldsNameOfAssessmentExpressAttemptCreate = [1]string{ + 0: "kind", +} + +// Decode decodes AssessmentExpressAttemptCreate from json. +func (s *AssessmentExpressAttemptCreate) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentExpressAttemptCreate to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "kind": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Kind.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"kind\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode AssessmentExpressAttemptCreate") + } + // 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(jsonFieldsNameOfAssessmentExpressAttemptCreate) { + name = jsonFieldsNameOfAssessmentExpressAttemptCreate[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 *AssessmentExpressAttemptCreate) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentExpressAttemptCreate) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentExpressAttemptCreateKind as json. +func (s AssessmentExpressAttemptCreateKind) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes AssessmentExpressAttemptCreateKind from json. +func (s *AssessmentExpressAttemptCreateKind) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentExpressAttemptCreateKind to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch AssessmentExpressAttemptCreateKind(v) { + case AssessmentExpressAttemptCreateKindDemoExpress: + *s = AssessmentExpressAttemptCreateKindDemoExpress + default: + *s = AssessmentExpressAttemptCreateKind(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AssessmentExpressAttemptCreateKind) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentExpressAttemptCreateKind) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentExpressAttemptKind as json. +func (s AssessmentExpressAttemptKind) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes AssessmentExpressAttemptKind from json. +func (s *AssessmentExpressAttemptKind) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentExpressAttemptKind to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch AssessmentExpressAttemptKind(v) { + case AssessmentExpressAttemptKindDemoExpress: + *s = AssessmentExpressAttemptKindDemoExpress + default: + *s = AssessmentExpressAttemptKind(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AssessmentExpressAttemptKind) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentExpressAttemptKind) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentExpressAttemptMode as json. +func (s AssessmentExpressAttemptMode) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes AssessmentExpressAttemptMode from json. +func (s *AssessmentExpressAttemptMode) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentExpressAttemptMode to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch AssessmentExpressAttemptMode(v) { + case AssessmentExpressAttemptModeDemoExpress: + *s = AssessmentExpressAttemptModeDemoExpress + default: + *s = AssessmentExpressAttemptMode(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AssessmentExpressAttemptMode) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentExpressAttemptMode) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *AssessmentExpressResult) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *AssessmentExpressResult) encodeFields(e *jx.Encoder) { + { + e.FieldStart("attempt_id") + json.EncodeUUID(e, s.AttemptID) + } + { + _ = s.Specialization + e.FieldStart("specialization") + e.Null() + } + { + _ = s.TargetGrade + e.FieldStart("target_grade") + e.Null() + } + { + _ = s.TaskLanguage + e.FieldStart("task_language") + e.Null() + } + { + e.FieldStart("kind") + s.Kind.Encode(e) + } + { + e.FieldStart("mode") + s.Mode.Encode(e) + } + { + e.FieldStart("versions") + s.Versions.Encode(e) + } + { + e.FieldStart("outcome") + s.Outcome.Encode(e) + } + { + _ = s.NotDeterminedReason + e.FieldStart("not_determined_reason") + e.Null() + } + { + _ = s.ConfirmedGrade + e.FieldStart("confirmed_grade") + e.Null() + } + { + _ = s.PreviousConfirmedGrade + e.FieldStart("previous_confirmed_grade") + e.Null() + } + { + _ = s.Strength + e.FieldStart("strength") + e.Null() + } + { + e.FieldStart("calibration_status") + s.CalibrationStatus.Encode(e) + } + { + e.FieldStart("limitations") + e.ArrStart() + for _, elem := range s.Limitations { + elem.Encode(e) + } + e.ArrEnd() + } + { + _ = s.Uncertainty + e.FieldStart("uncertainty") + e.Null() + } + { + _ = s.BasicScore + e.FieldStart("basic_score") + e.Null() + } + { + e.FieldStart("practices") + e.ArrStart() + for _, elem := range s.Practices { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("gaps") + e.ArrStart() + for _, elem := range s.Gaps { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("durations") + s.Durations.Encode(e) + } + { + e.FieldStart("next_steps") + e.ArrStart() + for _, elem := range s.NextSteps { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("summary") + e.Str(s.Summary) + } + { + e.FieldStart("decided_at") + s.DecidedAt.Encode(e) + } +} + +var jsonFieldsNameOfAssessmentExpressResult = [22]string{ + 0: "attempt_id", + 1: "specialization", + 2: "target_grade", + 3: "task_language", + 4: "kind", + 5: "mode", + 6: "versions", + 7: "outcome", + 8: "not_determined_reason", + 9: "confirmed_grade", + 10: "previous_confirmed_grade", + 11: "strength", + 12: "calibration_status", + 13: "limitations", + 14: "uncertainty", + 15: "basic_score", + 16: "practices", + 17: "gaps", + 18: "durations", + 19: "next_steps", + 20: "summary", + 21: "decided_at", +} + +// Decode decodes AssessmentExpressResult from json. +func (s *AssessmentExpressResult) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentExpressResult to nil") + } + var requiredBitSet [3]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "attempt_id": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := json.DecodeUUID(d) + s.AttemptID = v + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"attempt_id\"") + } + case "specialization": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := d.Null(); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"specialization\"") + } + case "target_grade": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := d.Null(); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"target_grade\"") + } + case "task_language": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + if err := d.Null(); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"task_language\"") + } + case "kind": + requiredBitSet[0] |= 1 << 4 + if err := func() error { + if err := s.Kind.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"kind\"") + } + case "mode": + requiredBitSet[0] |= 1 << 5 + if err := func() error { + if err := s.Mode.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"mode\"") + } + case "versions": + requiredBitSet[0] |= 1 << 6 + if err := func() error { + if err := s.Versions.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"versions\"") + } + case "outcome": + requiredBitSet[0] |= 1 << 7 + if err := func() error { + if err := s.Outcome.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"outcome\"") + } + case "not_determined_reason": + requiredBitSet[1] |= 1 << 0 + if err := func() error { + if err := d.Null(); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"not_determined_reason\"") + } + case "confirmed_grade": + requiredBitSet[1] |= 1 << 1 + if err := func() error { + if err := d.Null(); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"confirmed_grade\"") + } + case "previous_confirmed_grade": + requiredBitSet[1] |= 1 << 2 + if err := func() error { + if err := d.Null(); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"previous_confirmed_grade\"") + } + case "strength": + requiredBitSet[1] |= 1 << 3 + if err := func() error { + if err := d.Null(); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"strength\"") + } + case "calibration_status": + requiredBitSet[1] |= 1 << 4 + if err := func() error { + if err := s.CalibrationStatus.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"calibration_status\"") + } + case "limitations": + requiredBitSet[1] |= 1 << 5 + if err := func() error { + s.Limitations = make([]AssessmentExpressResultLimitationsItem, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem AssessmentExpressResultLimitationsItem + if err := elem.Decode(d); err != nil { + return err + } + s.Limitations = append(s.Limitations, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"limitations\"") + } + case "uncertainty": + requiredBitSet[1] |= 1 << 6 + if err := func() error { + if err := d.Null(); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"uncertainty\"") + } + case "basic_score": + requiredBitSet[1] |= 1 << 7 + if err := func() error { + if err := d.Null(); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"basic_score\"") + } + case "practices": + requiredBitSet[2] |= 1 << 0 + if err := func() error { + s.Practices = make([]AssessmentPracticeResult, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem AssessmentPracticeResult + if err := elem.Decode(d); err != nil { + return err + } + s.Practices = append(s.Practices, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"practices\"") + } + case "gaps": + requiredBitSet[2] |= 1 << 1 + if err := func() error { + s.Gaps = make([]AssessmentGap, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem AssessmentGap + if err := elem.Decode(d); err != nil { + return err + } + s.Gaps = append(s.Gaps, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"gaps\"") + } + case "durations": + requiredBitSet[2] |= 1 << 2 + if err := func() error { + if err := s.Durations.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"durations\"") + } + case "next_steps": + requiredBitSet[2] |= 1 << 3 + if err := func() error { + s.NextSteps = make([]AssessmentNextStep, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem AssessmentNextStep + if err := elem.Decode(d); err != nil { + return err + } + s.NextSteps = append(s.NextSteps, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"next_steps\"") + } + case "summary": + requiredBitSet[2] |= 1 << 4 + if err := func() error { + v, err := d.Str() + s.Summary = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"summary\"") + } + case "decided_at": + requiredBitSet[2] |= 1 << 5 + if err := func() error { + if err := s.DecidedAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"decided_at\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode AssessmentExpressResult") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [3]uint8{ + 0b11111111, + 0b11111111, + 0b00111111, + } { + 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(jsonFieldsNameOfAssessmentExpressResult) { + name = jsonFieldsNameOfAssessmentExpressResult[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 *AssessmentExpressResult) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentExpressResult) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentExpressResultCalibrationStatus as json. +func (s AssessmentExpressResultCalibrationStatus) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes AssessmentExpressResultCalibrationStatus from json. +func (s *AssessmentExpressResultCalibrationStatus) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentExpressResultCalibrationStatus to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch AssessmentExpressResultCalibrationStatus(v) { + case AssessmentExpressResultCalibrationStatusUncalibrated: + *s = AssessmentExpressResultCalibrationStatusUncalibrated + default: + *s = AssessmentExpressResultCalibrationStatus(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AssessmentExpressResultCalibrationStatus) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentExpressResultCalibrationStatus) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentExpressResultKind as json. +func (s AssessmentExpressResultKind) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes AssessmentExpressResultKind from json. +func (s *AssessmentExpressResultKind) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentExpressResultKind to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch AssessmentExpressResultKind(v) { + case AssessmentExpressResultKindDemoExpress: + *s = AssessmentExpressResultKindDemoExpress + default: + *s = AssessmentExpressResultKind(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AssessmentExpressResultKind) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentExpressResultKind) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentExpressResultLimitationsItem as json. +func (s AssessmentExpressResultLimitationsItem) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes AssessmentExpressResultLimitationsItem from json. +func (s *AssessmentExpressResultLimitationsItem) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentExpressResultLimitationsItem to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch AssessmentExpressResultLimitationsItem(v) { + case AssessmentExpressResultLimitationsItemDemonstrationOnly: + *s = AssessmentExpressResultLimitationsItemDemonstrationOnly + default: + *s = AssessmentExpressResultLimitationsItem(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AssessmentExpressResultLimitationsItem) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentExpressResultLimitationsItem) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentExpressResultMode as json. +func (s AssessmentExpressResultMode) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes AssessmentExpressResultMode from json. +func (s *AssessmentExpressResultMode) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentExpressResultMode to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch AssessmentExpressResultMode(v) { + case AssessmentExpressResultModeDemoExpress: + *s = AssessmentExpressResultModeDemoExpress + default: + *s = AssessmentExpressResultMode(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AssessmentExpressResultMode) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentExpressResultMode) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentExpressResultOutcome as json. +func (s AssessmentExpressResultOutcome) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes AssessmentExpressResultOutcome from json. +func (s *AssessmentExpressResultOutcome) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentExpressResultOutcome to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch AssessmentExpressResultOutcome(v) { + case AssessmentExpressResultOutcomeDemonstration: + *s = AssessmentExpressResultOutcomeDemonstration + default: + *s = AssessmentExpressResultOutcome(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AssessmentExpressResultOutcome) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentExpressResultOutcome) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode implements json.Marshaler. func (s *AssessmentFinalization) Encode(e *jx.Encoder) { e.ObjStart() @@ -2682,46 +5214,6 @@ func (s *AssessmentLimitation) UnmarshalJSON(data []byte) error { return s.Decode(d) } -// Encode encodes AssessmentMode as json. -func (s AssessmentMode) Encode(e *jx.Encoder) { - e.Str(string(s)) -} - -// Decode decodes AssessmentMode from json. -func (s *AssessmentMode) Decode(d *jx.Decoder) error { - if s == nil { - return errors.New("invalid: unable to decode AssessmentMode to nil") - } - v, err := d.StrBytes() - if err != nil { - return err - } - // Try to use constant string. - switch AssessmentMode(v) { - case AssessmentModeDemoBasic: - *s = AssessmentModeDemoBasic - case AssessmentModeAdaptive: - *s = AssessmentModeAdaptive - default: - *s = AssessmentMode(v) - } - - return nil -} - -// MarshalJSON implements stdjson.Marshaler. -func (s AssessmentMode) MarshalJSON() ([]byte, error) { - e := jx.Encoder{} - s.Encode(&e) - return e.Bytes(), nil -} - -// UnmarshalJSON implements stdjson.Unmarshaler. -func (s *AssessmentMode) UnmarshalJSON(data []byte) error { - d := jx.DecodeBytes(data) - return s.Decode(d) -} - // Encode encodes AssessmentNextAction as json. func (s AssessmentNextAction) Encode(e *jx.Encoder) { e.Str(string(s)) @@ -3519,14 +6011,634 @@ func (s *AssessmentProgress) UnmarshalJSON(data []byte) error { } // Encode implements json.Marshaler. -func (s *AssessmentResult) Encode(e *jx.Encoder) { +func (s *AssessmentQualifiedAttempt) Encode(e *jx.Encoder) { e.ObjStart() s.encodeFields(e) e.ObjEnd() } // encodeFields encodes fields. -func (s *AssessmentResult) encodeFields(e *jx.Encoder) { +func (s *AssessmentQualifiedAttempt) encodeFields(e *jx.Encoder) { + { + e.FieldStart("id") + json.EncodeUUID(e, s.ID) + } + { + e.FieldStart("version") + s.Version.Encode(e) + } + { + e.FieldStart("specialization") + s.Specialization.Encode(e) + } + { + e.FieldStart("target_grade") + s.TargetGrade.Encode(e) + } + { + e.FieldStart("task_language") + s.TaskLanguage.Encode(e) + } + { + e.FieldStart("kind") + s.Kind.Encode(e) + } + { + e.FieldStart("root_attempt_id") + s.RootAttemptID.Encode(e) + } + { + e.FieldStart("chain_deadline") + s.ChainDeadline.Encode(e) + } + { + e.FieldStart("mode") + s.Mode.Encode(e) + } + { + e.FieldStart("state") + s.State.Encode(e) + } + { + e.FieldStart("versions") + s.Versions.Encode(e) + } + { + e.FieldStart("started_at") + s.StartedAt.Encode(e) + } + { + e.FieldStart("expires_at") + s.ExpiresAt.Encode(e) + } + { + e.FieldStart("sessions") + s.Sessions.Encode(e) + } + { + e.FieldStart("finished_at") + s.FinishedAt.Encode(e) + } + { + e.FieldStart("progress") + s.Progress.Encode(e) + } + { + e.FieldStart("current_item") + s.CurrentItem.Encode(e) + } + { + e.FieldStart("practices") + e.ArrStart() + for _, elem := range s.Practices { + elem.Encode(e) + } + e.ArrEnd() + } +} + +var jsonFieldsNameOfAssessmentQualifiedAttempt = [18]string{ + 0: "id", + 1: "version", + 2: "specialization", + 3: "target_grade", + 4: "task_language", + 5: "kind", + 6: "root_attempt_id", + 7: "chain_deadline", + 8: "mode", + 9: "state", + 10: "versions", + 11: "started_at", + 12: "expires_at", + 13: "sessions", + 14: "finished_at", + 15: "progress", + 16: "current_item", + 17: "practices", +} + +// Decode decodes AssessmentQualifiedAttempt from json. +func (s *AssessmentQualifiedAttempt) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentQualifiedAttempt to nil") + } + var requiredBitSet [3]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "id": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := json.DecodeUUID(d) + s.ID = v + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"id\"") + } + case "version": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Version.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"version\"") + } + case "specialization": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.Specialization.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"specialization\"") + } + case "target_grade": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + if err := s.TargetGrade.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"target_grade\"") + } + case "task_language": + requiredBitSet[0] |= 1 << 4 + if err := func() error { + if err := s.TaskLanguage.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"task_language\"") + } + case "kind": + requiredBitSet[0] |= 1 << 5 + if err := func() error { + if err := s.Kind.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"kind\"") + } + case "root_attempt_id": + requiredBitSet[0] |= 1 << 6 + if err := func() error { + if err := s.RootAttemptID.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"root_attempt_id\"") + } + case "chain_deadline": + requiredBitSet[0] |= 1 << 7 + if err := func() error { + if err := s.ChainDeadline.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"chain_deadline\"") + } + case "mode": + requiredBitSet[1] |= 1 << 0 + if err := func() error { + if err := s.Mode.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"mode\"") + } + case "state": + requiredBitSet[1] |= 1 << 1 + if err := func() error { + if err := s.State.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"state\"") + } + case "versions": + requiredBitSet[1] |= 1 << 2 + if err := func() error { + if err := s.Versions.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"versions\"") + } + case "started_at": + requiredBitSet[1] |= 1 << 3 + if err := func() error { + if err := s.StartedAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"started_at\"") + } + case "expires_at": + requiredBitSet[1] |= 1 << 4 + if err := func() error { + if err := s.ExpiresAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"expires_at\"") + } + case "sessions": + requiredBitSet[1] |= 1 << 5 + if err := func() error { + if err := s.Sessions.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"sessions\"") + } + case "finished_at": + requiredBitSet[1] |= 1 << 6 + if err := func() error { + if err := s.FinishedAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"finished_at\"") + } + case "progress": + requiredBitSet[1] |= 1 << 7 + if err := func() error { + if err := s.Progress.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"progress\"") + } + case "current_item": + requiredBitSet[2] |= 1 << 0 + if err := func() error { + if err := s.CurrentItem.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"current_item\"") + } + case "practices": + requiredBitSet[2] |= 1 << 1 + if err := func() error { + s.Practices = make([]AssessmentPractice, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem AssessmentPractice + if err := elem.Decode(d); err != nil { + return err + } + s.Practices = append(s.Practices, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"practices\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode AssessmentQualifiedAttempt") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [3]uint8{ + 0b11111111, + 0b11111111, + 0b00000011, + } { + 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(jsonFieldsNameOfAssessmentQualifiedAttempt) { + name = jsonFieldsNameOfAssessmentQualifiedAttempt[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 *AssessmentQualifiedAttempt) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentQualifiedAttempt) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *AssessmentQualifiedAttemptCreate) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *AssessmentQualifiedAttemptCreate) encodeFields(e *jx.Encoder) { + { + e.FieldStart("kind") + s.Kind.Encode(e) + } + { + e.FieldStart("specialization") + s.Specialization.Encode(e) + } + { + e.FieldStart("target_grade") + s.TargetGrade.Encode(e) + } + { + e.FieldStart("task_language") + s.TaskLanguage.Encode(e) + } +} + +var jsonFieldsNameOfAssessmentQualifiedAttemptCreate = [4]string{ + 0: "kind", + 1: "specialization", + 2: "target_grade", + 3: "task_language", +} + +// Decode decodes AssessmentQualifiedAttemptCreate from json. +func (s *AssessmentQualifiedAttemptCreate) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentQualifiedAttemptCreate to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "kind": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Kind.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"kind\"") + } + case "specialization": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Specialization.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"specialization\"") + } + case "target_grade": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.TargetGrade.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"target_grade\"") + } + case "task_language": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + if err := s.TaskLanguage.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"task_language\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode AssessmentQualifiedAttemptCreate") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00001111, + } { + 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(jsonFieldsNameOfAssessmentQualifiedAttemptCreate) { + name = jsonFieldsNameOfAssessmentQualifiedAttemptCreate[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 *AssessmentQualifiedAttemptCreate) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentQualifiedAttemptCreate) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentQualifiedAttemptCreateKind as json. +func (s AssessmentQualifiedAttemptCreateKind) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes AssessmentQualifiedAttemptCreateKind from json. +func (s *AssessmentQualifiedAttemptCreateKind) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentQualifiedAttemptCreateKind to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch AssessmentQualifiedAttemptCreateKind(v) { + case AssessmentQualifiedAttemptCreateKindRoot: + *s = AssessmentQualifiedAttemptCreateKindRoot + default: + *s = AssessmentQualifiedAttemptCreateKind(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AssessmentQualifiedAttemptCreateKind) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentQualifiedAttemptCreateKind) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentQualifiedAttemptKind as json. +func (s AssessmentQualifiedAttemptKind) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes AssessmentQualifiedAttemptKind from json. +func (s *AssessmentQualifiedAttemptKind) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentQualifiedAttemptKind to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch AssessmentQualifiedAttemptKind(v) { + case AssessmentQualifiedAttemptKindRoot: + *s = AssessmentQualifiedAttemptKindRoot + default: + *s = AssessmentQualifiedAttemptKind(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AssessmentQualifiedAttemptKind) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentQualifiedAttemptKind) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentQualifiedAttemptMode as json. +func (s AssessmentQualifiedAttemptMode) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes AssessmentQualifiedAttemptMode from json. +func (s *AssessmentQualifiedAttemptMode) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentQualifiedAttemptMode to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch AssessmentQualifiedAttemptMode(v) { + case AssessmentQualifiedAttemptModeDemoBasic: + *s = AssessmentQualifiedAttemptModeDemoBasic + case AssessmentQualifiedAttemptModeAdaptive: + *s = AssessmentQualifiedAttemptModeAdaptive + default: + *s = AssessmentQualifiedAttemptMode(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AssessmentQualifiedAttemptMode) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentQualifiedAttemptMode) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *AssessmentQualifiedResult) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *AssessmentQualifiedResult) encodeFields(e *jx.Encoder) { { e.FieldStart("attempt_id") json.EncodeUUID(e, s.AttemptID) @@ -3539,10 +6651,22 @@ func (s *AssessmentResult) encodeFields(e *jx.Encoder) { e.FieldStart("target_grade") s.TargetGrade.Encode(e) } + { + e.FieldStart("root_attempt_id") + s.RootAttemptID.Encode(e) + } + { + e.FieldStart("chain_deadline") + s.ChainDeadline.Encode(e) + } { e.FieldStart("task_language") s.TaskLanguage.Encode(e) } + { + e.FieldStart("kind") + s.Kind.Encode(e) + } { e.FieldStart("mode") s.Mode.Encode(e) @@ -3625,33 +6749,36 @@ func (s *AssessmentResult) encodeFields(e *jx.Encoder) { } } -var jsonFieldsNameOfAssessmentResult = [20]string{ +var jsonFieldsNameOfAssessmentQualifiedResult = [23]string{ 0: "attempt_id", 1: "specialization", 2: "target_grade", - 3: "task_language", - 4: "mode", - 5: "versions", - 6: "outcome", - 7: "not_determined_reason", - 8: "confirmed_grade", - 9: "previous_confirmed_grade", - 10: "strength", - 11: "calibration_status", - 12: "limitations", - 13: "uncertainty", - 14: "basic_score", - 15: "practices", - 16: "gaps", - 17: "durations", - 18: "next_steps", - 19: "decided_at", + 3: "root_attempt_id", + 4: "chain_deadline", + 5: "task_language", + 6: "kind", + 7: "mode", + 8: "versions", + 9: "outcome", + 10: "not_determined_reason", + 11: "confirmed_grade", + 12: "previous_confirmed_grade", + 13: "strength", + 14: "calibration_status", + 15: "limitations", + 16: "uncertainty", + 17: "basic_score", + 18: "practices", + 19: "gaps", + 20: "durations", + 21: "next_steps", + 22: "decided_at", } -// Decode decodes AssessmentResult from json. -func (s *AssessmentResult) Decode(d *jx.Decoder) error { +// Decode decodes AssessmentQualifiedResult from json. +func (s *AssessmentQualifiedResult) Decode(d *jx.Decoder) error { if s == nil { - return errors.New("invalid: unable to decode AssessmentResult to nil") + return errors.New("invalid: unable to decode AssessmentQualifiedResult to nil") } var requiredBitSet [3]uint8 @@ -3689,8 +6816,28 @@ func (s *AssessmentResult) Decode(d *jx.Decoder) error { }(); err != nil { return errors.Wrap(err, "decode field \"target_grade\"") } - case "task_language": + case "root_attempt_id": requiredBitSet[0] |= 1 << 3 + if err := func() error { + if err := s.RootAttemptID.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"root_attempt_id\"") + } + case "chain_deadline": + requiredBitSet[0] |= 1 << 4 + if err := func() error { + if err := s.ChainDeadline.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"chain_deadline\"") + } + case "task_language": + requiredBitSet[0] |= 1 << 5 if err := func() error { if err := s.TaskLanguage.Decode(d); err != nil { return err @@ -3699,8 +6846,18 @@ func (s *AssessmentResult) Decode(d *jx.Decoder) error { }(); err != nil { return errors.Wrap(err, "decode field \"task_language\"") } + case "kind": + requiredBitSet[0] |= 1 << 6 + if err := func() error { + if err := s.Kind.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"kind\"") + } case "mode": - requiredBitSet[0] |= 1 << 4 + requiredBitSet[0] |= 1 << 7 if err := func() error { if err := s.Mode.Decode(d); err != nil { return err @@ -3710,7 +6867,7 @@ func (s *AssessmentResult) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"mode\"") } case "versions": - requiredBitSet[0] |= 1 << 5 + requiredBitSet[1] |= 1 << 0 if err := func() error { if err := s.Versions.Decode(d); err != nil { return err @@ -3720,7 +6877,7 @@ func (s *AssessmentResult) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"versions\"") } case "outcome": - requiredBitSet[0] |= 1 << 6 + requiredBitSet[1] |= 1 << 1 if err := func() error { if err := s.Outcome.Decode(d); err != nil { return err @@ -3730,7 +6887,7 @@ func (s *AssessmentResult) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"outcome\"") } case "not_determined_reason": - requiredBitSet[0] |= 1 << 7 + requiredBitSet[1] |= 1 << 2 if err := func() error { if err := s.NotDeterminedReason.Decode(d); err != nil { return err @@ -3740,7 +6897,7 @@ func (s *AssessmentResult) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"not_determined_reason\"") } case "confirmed_grade": - requiredBitSet[1] |= 1 << 0 + requiredBitSet[1] |= 1 << 3 if err := func() error { if err := s.ConfirmedGrade.Decode(d); err != nil { return err @@ -3750,7 +6907,7 @@ func (s *AssessmentResult) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"confirmed_grade\"") } case "previous_confirmed_grade": - requiredBitSet[1] |= 1 << 1 + requiredBitSet[1] |= 1 << 4 if err := func() error { if err := s.PreviousConfirmedGrade.Decode(d); err != nil { return err @@ -3760,7 +6917,7 @@ func (s *AssessmentResult) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"previous_confirmed_grade\"") } case "strength": - requiredBitSet[1] |= 1 << 2 + requiredBitSet[1] |= 1 << 5 if err := func() error { if err := s.Strength.Decode(d); err != nil { return err @@ -3770,7 +6927,7 @@ func (s *AssessmentResult) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"strength\"") } case "calibration_status": - requiredBitSet[1] |= 1 << 3 + requiredBitSet[1] |= 1 << 6 if err := func() error { if err := s.CalibrationStatus.Decode(d); err != nil { return err @@ -3780,7 +6937,7 @@ func (s *AssessmentResult) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"calibration_status\"") } case "limitations": - requiredBitSet[1] |= 1 << 4 + requiredBitSet[1] |= 1 << 7 if err := func() error { s.Limitations = make([]AssessmentLimitation, 0) if err := d.Arr(func(d *jx.Decoder) error { @@ -3798,7 +6955,7 @@ func (s *AssessmentResult) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"limitations\"") } case "uncertainty": - requiredBitSet[1] |= 1 << 5 + requiredBitSet[2] |= 1 << 0 if err := func() error { if err := s.Uncertainty.Decode(d); err != nil { return err @@ -3808,7 +6965,7 @@ func (s *AssessmentResult) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"uncertainty\"") } case "basic_score": - requiredBitSet[1] |= 1 << 6 + requiredBitSet[2] |= 1 << 1 if err := func() error { if err := s.BasicScore.Decode(d); err != nil { return err @@ -3818,7 +6975,7 @@ func (s *AssessmentResult) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"basic_score\"") } case "practices": - requiredBitSet[1] |= 1 << 7 + requiredBitSet[2] |= 1 << 2 if err := func() error { s.Practices = make([]AssessmentPracticeResult, 0) if err := d.Arr(func(d *jx.Decoder) error { @@ -3836,7 +6993,7 @@ func (s *AssessmentResult) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"practices\"") } case "gaps": - requiredBitSet[2] |= 1 << 0 + requiredBitSet[2] |= 1 << 3 if err := func() error { s.Gaps = make([]AssessmentGap, 0) if err := d.Arr(func(d *jx.Decoder) error { @@ -3854,7 +7011,7 @@ func (s *AssessmentResult) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"gaps\"") } case "durations": - requiredBitSet[2] |= 1 << 1 + requiredBitSet[2] |= 1 << 4 if err := func() error { if err := s.Durations.Decode(d); err != nil { return err @@ -3864,7 +7021,7 @@ func (s *AssessmentResult) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"durations\"") } case "next_steps": - requiredBitSet[2] |= 1 << 2 + requiredBitSet[2] |= 1 << 5 if err := func() error { s.NextSteps = make([]AssessmentNextStep, 0) if err := d.Arr(func(d *jx.Decoder) error { @@ -3882,7 +7039,7 @@ func (s *AssessmentResult) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"next_steps\"") } case "decided_at": - requiredBitSet[2] |= 1 << 3 + requiredBitSet[2] |= 1 << 6 if err := func() error { if err := s.DecidedAt.Decode(d); err != nil { return err @@ -3896,14 +7053,14 @@ func (s *AssessmentResult) Decode(d *jx.Decoder) error { } return nil }); err != nil { - return errors.Wrap(err, "decode AssessmentResult") + return errors.Wrap(err, "decode AssessmentQualifiedResult") } // Validate required fields. var failures []validate.FieldError for i, mask := range [3]uint8{ 0b11111111, 0b11111111, - 0b00001111, + 0b01111111, } { if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { // Mask only required fields and check equality to mask using XOR. @@ -3915,8 +7072,8 @@ func (s *AssessmentResult) Decode(d *jx.Decoder) error { bitIdx := bits.TrailingZeros8(result) fieldIdx := i*8 + bitIdx var name string - if fieldIdx < len(jsonFieldsNameOfAssessmentResult) { - name = jsonFieldsNameOfAssessmentResult[fieldIdx] + if fieldIdx < len(jsonFieldsNameOfAssessmentQualifiedResult) { + name = jsonFieldsNameOfAssessmentQualifiedResult[fieldIdx] } else { name = strconv.Itoa(fieldIdx) } @@ -3937,7 +7094,549 @@ func (s *AssessmentResult) Decode(d *jx.Decoder) error { } // MarshalJSON implements stdjson.Marshaler. -func (s *AssessmentResult) MarshalJSON() ([]byte, error) { +func (s *AssessmentQualifiedResult) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentQualifiedResult) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentQualifiedResultKind as json. +func (s AssessmentQualifiedResultKind) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes AssessmentQualifiedResultKind from json. +func (s *AssessmentQualifiedResultKind) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentQualifiedResultKind to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch AssessmentQualifiedResultKind(v) { + case AssessmentQualifiedResultKindRoot: + *s = AssessmentQualifiedResultKindRoot + default: + *s = AssessmentQualifiedResultKind(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AssessmentQualifiedResultKind) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentQualifiedResultKind) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentQualifiedResultMode as json. +func (s AssessmentQualifiedResultMode) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes AssessmentQualifiedResultMode from json. +func (s *AssessmentQualifiedResultMode) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentQualifiedResultMode to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch AssessmentQualifiedResultMode(v) { + case AssessmentQualifiedResultModeDemoBasic: + *s = AssessmentQualifiedResultModeDemoBasic + case AssessmentQualifiedResultModeAdaptive: + *s = AssessmentQualifiedResultModeAdaptive + default: + *s = AssessmentQualifiedResultMode(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AssessmentQualifiedResultMode) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentQualifiedResultMode) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentRealMode as json. +func (s AssessmentRealMode) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes AssessmentRealMode from json. +func (s *AssessmentRealMode) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentRealMode to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch AssessmentRealMode(v) { + case AssessmentRealModeDemoBasic: + *s = AssessmentRealModeDemoBasic + case AssessmentRealModeAdaptive: + *s = AssessmentRealModeAdaptive + default: + *s = AssessmentRealMode(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AssessmentRealMode) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentRealMode) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentResult as json. +func (s AssessmentResult) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +func (s AssessmentResult) encodeFields(e *jx.Encoder) { + switch s.Type { + case AssessmentQualifiedResultAssessmentResult: + e.FieldStart("kind") + e.Str("root") + { + s := s.AssessmentQualifiedResult + { + e.FieldStart("attempt_id") + json.EncodeUUID(e, s.AttemptID) + } + { + e.FieldStart("specialization") + s.Specialization.Encode(e) + } + { + e.FieldStart("target_grade") + s.TargetGrade.Encode(e) + } + { + e.FieldStart("root_attempt_id") + s.RootAttemptID.Encode(e) + } + { + e.FieldStart("chain_deadline") + s.ChainDeadline.Encode(e) + } + { + e.FieldStart("task_language") + s.TaskLanguage.Encode(e) + } + { + e.FieldStart("mode") + s.Mode.Encode(e) + } + { + e.FieldStart("versions") + s.Versions.Encode(e) + } + { + e.FieldStart("outcome") + s.Outcome.Encode(e) + } + { + e.FieldStart("not_determined_reason") + s.NotDeterminedReason.Encode(e) + } + { + e.FieldStart("confirmed_grade") + s.ConfirmedGrade.Encode(e) + } + { + e.FieldStart("previous_confirmed_grade") + s.PreviousConfirmedGrade.Encode(e) + } + { + e.FieldStart("strength") + s.Strength.Encode(e) + } + { + e.FieldStart("calibration_status") + s.CalibrationStatus.Encode(e) + } + { + e.FieldStart("limitations") + e.ArrStart() + for _, elem := range s.Limitations { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("uncertainty") + s.Uncertainty.Encode(e) + } + { + e.FieldStart("basic_score") + s.BasicScore.Encode(e) + } + { + e.FieldStart("practices") + e.ArrStart() + for _, elem := range s.Practices { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("gaps") + e.ArrStart() + for _, elem := range s.Gaps { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("durations") + s.Durations.Encode(e) + } + { + e.FieldStart("next_steps") + e.ArrStart() + for _, elem := range s.NextSteps { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("decided_at") + s.DecidedAt.Encode(e) + } + } + case AssessmentCorrectiveResultAssessmentResult: + e.FieldStart("kind") + e.Str("corrective") + { + s := s.AssessmentCorrectiveResult + { + e.FieldStart("attempt_id") + json.EncodeUUID(e, s.AttemptID) + } + { + e.FieldStart("specialization") + s.Specialization.Encode(e) + } + { + e.FieldStart("target_grade") + s.TargetGrade.Encode(e) + } + { + e.FieldStart("root_attempt_id") + s.RootAttemptID.Encode(e) + } + { + e.FieldStart("chain_deadline") + s.ChainDeadline.Encode(e) + } + { + e.FieldStart("task_language") + s.TaskLanguage.Encode(e) + } + { + e.FieldStart("mode") + s.Mode.Encode(e) + } + { + e.FieldStart("versions") + s.Versions.Encode(e) + } + { + e.FieldStart("outcome") + s.Outcome.Encode(e) + } + { + e.FieldStart("not_determined_reason") + s.NotDeterminedReason.Encode(e) + } + { + e.FieldStart("confirmed_grade") + s.ConfirmedGrade.Encode(e) + } + { + e.FieldStart("previous_confirmed_grade") + s.PreviousConfirmedGrade.Encode(e) + } + { + e.FieldStart("strength") + s.Strength.Encode(e) + } + { + e.FieldStart("calibration_status") + s.CalibrationStatus.Encode(e) + } + { + e.FieldStart("limitations") + e.ArrStart() + for _, elem := range s.Limitations { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("uncertainty") + s.Uncertainty.Encode(e) + } + { + e.FieldStart("basic_score") + s.BasicScore.Encode(e) + } + { + e.FieldStart("practices") + e.ArrStart() + for _, elem := range s.Practices { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("gaps") + e.ArrStart() + for _, elem := range s.Gaps { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("durations") + s.Durations.Encode(e) + } + { + e.FieldStart("next_steps") + e.ArrStart() + for _, elem := range s.NextSteps { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("decided_at") + s.DecidedAt.Encode(e) + } + } + case AssessmentExpressResultAssessmentResult: + e.FieldStart("kind") + e.Str("demo_express") + { + s := s.AssessmentExpressResult + { + e.FieldStart("attempt_id") + json.EncodeUUID(e, s.AttemptID) + } + { + _ = s.Specialization + e.FieldStart("specialization") + e.Null() + } + { + _ = s.TargetGrade + e.FieldStart("target_grade") + e.Null() + } + { + _ = s.TaskLanguage + e.FieldStart("task_language") + e.Null() + } + { + e.FieldStart("mode") + s.Mode.Encode(e) + } + { + e.FieldStart("versions") + s.Versions.Encode(e) + } + { + e.FieldStart("outcome") + s.Outcome.Encode(e) + } + { + _ = s.NotDeterminedReason + e.FieldStart("not_determined_reason") + e.Null() + } + { + _ = s.ConfirmedGrade + e.FieldStart("confirmed_grade") + e.Null() + } + { + _ = s.PreviousConfirmedGrade + e.FieldStart("previous_confirmed_grade") + e.Null() + } + { + _ = s.Strength + e.FieldStart("strength") + e.Null() + } + { + e.FieldStart("calibration_status") + s.CalibrationStatus.Encode(e) + } + { + e.FieldStart("limitations") + e.ArrStart() + for _, elem := range s.Limitations { + elem.Encode(e) + } + e.ArrEnd() + } + { + _ = s.Uncertainty + e.FieldStart("uncertainty") + e.Null() + } + { + _ = s.BasicScore + e.FieldStart("basic_score") + e.Null() + } + { + e.FieldStart("practices") + e.ArrStart() + for _, elem := range s.Practices { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("gaps") + e.ArrStart() + for _, elem := range s.Gaps { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("durations") + s.Durations.Encode(e) + } + { + e.FieldStart("next_steps") + e.ArrStart() + for _, elem := range s.NextSteps { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("summary") + e.Str(s.Summary) + } + { + e.FieldStart("decided_at") + s.DecidedAt.Encode(e) + } + } + } +} + +// Decode decodes AssessmentResult from json. +func (s *AssessmentResult) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentResult to nil") + } + // Sum type discriminator. + if typ := d.Next(); typ != jx.Object { + return errors.Errorf("unexpected json type %q", typ) + } + + var found bool + if err := d.Capture(func(d *jx.Decoder) error { + return d.ObjBytes(func(d *jx.Decoder, key []byte) error { + if found { + return d.Skip() + } + switch string(key) { + case "kind": + typ, err := d.Str() + if err != nil { + return err + } + switch typ { + case "root": + s.Type = AssessmentQualifiedResultAssessmentResult + found = true + case "corrective": + s.Type = AssessmentCorrectiveResultAssessmentResult + found = true + case "demo_express": + s.Type = AssessmentExpressResultAssessmentResult + found = true + default: + return errors.Errorf("unknown type %s", typ) + } + return nil + } + return d.Skip() + }) + }); err != nil { + return errors.Wrap(err, "capture") + } + if !found { + return errors.New("unable to detect sum type variant") + } + switch s.Type { + case AssessmentQualifiedResultAssessmentResult: + if err := s.AssessmentQualifiedResult.Decode(d); err != nil { + return err + } + case AssessmentCorrectiveResultAssessmentResult: + if err := s.AssessmentCorrectiveResult.Decode(d); err != nil { + return err + } + case AssessmentExpressResultAssessmentResult: + if err := s.AssessmentExpressResult.Decode(d); err != nil { + return err + } + default: + return errors.Errorf("inferred invalid type: %s", s.Type) + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AssessmentResult) MarshalJSON() ([]byte, error) { e := jx.Encoder{} s.Encode(&e) return e.Bytes(), nil @@ -25188,50 +28887,6 @@ func (s *NilAssessmentItem) UnmarshalJSON(data []byte) error { return s.Decode(d) } -// Encode encodes AssessmentMode as json. -func (o NilAssessmentMode) Encode(e *jx.Encoder) { - if o.Null { - e.Null() - return - } - e.Str(string(o.Value)) -} - -// Decode decodes AssessmentMode from json. -func (o *NilAssessmentMode) Decode(d *jx.Decoder) error { - if o == nil { - return errors.New("invalid: unable to decode NilAssessmentMode to nil") - } - if d.Next() == jx.Null { - if err := d.Null(); err != nil { - return err - } - - var v AssessmentMode - o.Value = v - o.Null = true - return nil - } - o.Null = false - if err := o.Value.Decode(d); err != nil { - return err - } - return nil -} - -// MarshalJSON implements stdjson.Marshaler. -func (s NilAssessmentMode) MarshalJSON() ([]byte, error) { - e := jx.Encoder{} - s.Encode(&e) - return e.Bytes(), nil -} - -// UnmarshalJSON implements stdjson.Unmarshaler. -func (s *NilAssessmentMode) UnmarshalJSON(data []byte) error { - d := jx.DecodeBytes(data) - return s.Decode(d) -} - // Encode encodes AssessmentNotDeterminedReason as json. func (o NilAssessmentNotDeterminedReason) Encode(e *jx.Encoder) { if o.Null { @@ -25276,6 +28931,50 @@ func (s *NilAssessmentNotDeterminedReason) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes AssessmentRealMode as json. +func (o NilAssessmentRealMode) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + e.Str(string(o.Value)) +} + +// Decode decodes AssessmentRealMode from json. +func (o *NilAssessmentRealMode) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilAssessmentRealMode to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v AssessmentRealMode + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilAssessmentRealMode) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilAssessmentRealMode) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes AssessmentSessions as json. func (o NilAssessmentSessions) Encode(e *jx.Encoder) { if o.Null { @@ -42086,6 +45785,272 @@ func (s *StackTag) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes StartMyAssessmentAttemptSessionBadRequest as json. +func (s *StartMyAssessmentAttemptSessionBadRequest) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes StartMyAssessmentAttemptSessionBadRequest from json. +func (s *StartMyAssessmentAttemptSessionBadRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode StartMyAssessmentAttemptSessionBadRequest to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = StartMyAssessmentAttemptSessionBadRequest(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *StartMyAssessmentAttemptSessionBadRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *StartMyAssessmentAttemptSessionBadRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes StartMyAssessmentAttemptSessionConflict as json. +func (s *StartMyAssessmentAttemptSessionConflict) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes StartMyAssessmentAttemptSessionConflict from json. +func (s *StartMyAssessmentAttemptSessionConflict) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode StartMyAssessmentAttemptSessionConflict to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = StartMyAssessmentAttemptSessionConflict(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *StartMyAssessmentAttemptSessionConflict) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *StartMyAssessmentAttemptSessionConflict) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes StartMyAssessmentAttemptSessionForbidden as json. +func (s *StartMyAssessmentAttemptSessionForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes StartMyAssessmentAttemptSessionForbidden from json. +func (s *StartMyAssessmentAttemptSessionForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode StartMyAssessmentAttemptSessionForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = StartMyAssessmentAttemptSessionForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *StartMyAssessmentAttemptSessionForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *StartMyAssessmentAttemptSessionForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes StartMyAssessmentAttemptSessionNotFound as json. +func (s *StartMyAssessmentAttemptSessionNotFound) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes StartMyAssessmentAttemptSessionNotFound from json. +func (s *StartMyAssessmentAttemptSessionNotFound) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode StartMyAssessmentAttemptSessionNotFound to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = StartMyAssessmentAttemptSessionNotFound(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *StartMyAssessmentAttemptSessionNotFound) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *StartMyAssessmentAttemptSessionNotFound) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes StartMyAssessmentAttemptSessionPreconditionFailed as json. +func (s *StartMyAssessmentAttemptSessionPreconditionFailed) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes StartMyAssessmentAttemptSessionPreconditionFailed from json. +func (s *StartMyAssessmentAttemptSessionPreconditionFailed) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode StartMyAssessmentAttemptSessionPreconditionFailed to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = StartMyAssessmentAttemptSessionPreconditionFailed(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *StartMyAssessmentAttemptSessionPreconditionFailed) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *StartMyAssessmentAttemptSessionPreconditionFailed) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes StartMyAssessmentAttemptSessionUnauthorized as json. +func (s *StartMyAssessmentAttemptSessionUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes StartMyAssessmentAttemptSessionUnauthorized from json. +func (s *StartMyAssessmentAttemptSessionUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode StartMyAssessmentAttemptSessionUnauthorized to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = StartMyAssessmentAttemptSessionUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *StartMyAssessmentAttemptSessionUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *StartMyAssessmentAttemptSessionUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes StartMyAssessmentAttemptSessionUnprocessableEntity as json. +func (s *StartMyAssessmentAttemptSessionUnprocessableEntity) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes StartMyAssessmentAttemptSessionUnprocessableEntity from json. +func (s *StartMyAssessmentAttemptSessionUnprocessableEntity) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode StartMyAssessmentAttemptSessionUnprocessableEntity to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = StartMyAssessmentAttemptSessionUnprocessableEntity(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *StartMyAssessmentAttemptSessionUnprocessableEntity) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *StartMyAssessmentAttemptSessionUnprocessableEntity) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode implements json.Marshaler. func (s *StringAnswer) Encode(e *jx.Encoder) { e.ObjStart() diff --git a/backend/internal/adapter/primary/http/api/oas_operations_gen.go b/backend/internal/adapter/primary/http/api/oas_operations_gen.go index 18ed2e8..f7e07dc 100644 --- a/backend/internal/adapter/primary/http/api/oas_operations_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_operations_gen.go @@ -54,6 +54,7 @@ const ( SendOrganizationInvitationOperation OperationName = "SendOrganizationInvitation" SetMyPublicationOperation OperationName = "SetMyPublication" SetMySearchStatusOperation OperationName = "SetMySearchStatus" + StartMyAssessmentAttemptSessionOperation OperationName = "StartMyAssessmentAttemptSession" SubmitMyAssessmentAnswerOperation OperationName = "SubmitMyAssessmentAnswer" UnhideOrganizationOperation OperationName = "UnhideOrganization" UpdateOrganizationOperation OperationName = "UpdateOrganization" diff --git a/backend/internal/adapter/primary/http/api/oas_parameters_gen.go b/backend/internal/adapter/primary/http/api/oas_parameters_gen.go index ebd09f4..7e352fe 100644 --- a/backend/internal/adapter/primary/http/api/oas_parameters_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_parameters_gen.go @@ -4415,6 +4415,155 @@ func decodeSendOrganizationInvitationParams(args [2]string, argsEscaped bool, r return params, nil } +// StartMyAssessmentAttemptSessionParams is parameters of StartMyAssessmentAttemptSession operation. +type StartMyAssessmentAttemptSessionParams struct { + // Identifier of an assessment attempt of the current candidate. An attempt of another candidate and an + // unknown identifier both answer 404 not_found, so identifiers cannot be enumerated. + AttemptID uuid.UUID + // Client-generated key that makes a retried mutating command safe; a UUID v4 is recommended. The value + // is sent without quotes. The server scopes the key by caller and operation and fingerprints the + // request by method, path, and body. + // + // Stored for 24 hours after the first request and replayed with the same status, headers, and body: + // the final 2xx outcome and final deterministic 4xx business outcomes of the command, such as 404 + // not_found or 409 state_conflict. A replay does not repeat the side effect. + // + // Not stored, so a retry with the same key is evaluated again: 400 validation_failed, 413, and 415 for + // the request itself, 401 and 403, 409 idempotency_in_progress, 412 version_conflict and 428 + // precondition_required (nothing changed; read the resource again and retry), 422 + // idempotency_key_reused, 429, and every 5xx. + // + // Order of checks: authentication (401), request validation (400, 413, 415), authorization (403), then + // the key. A stored or running request with a different fingerprint returns 422 idempotency_key_reused + // before any other key check; a running request with the same fingerprint returns 409 + // idempotency_in_progress; a stored outcome with the same fingerprint is replayed. Only after that + // does the server check If-Match, so a retry of a completed change replays its outcome instead of + // failing on the version it has just changed. After 24 hours the key may be accepted as new. + IdempotencyKey string +} + +func unpackStartMyAssessmentAttemptSessionParams(packed middleware.Parameters) (params StartMyAssessmentAttemptSessionParams) { + { + key := middleware.ParameterKey{ + Name: "attempt_id", + In: "path", + } + params.AttemptID = packed[key].(uuid.UUID) + } + { + key := middleware.ParameterKey{ + Name: "Idempotency-Key", + In: "header", + } + params.IdempotencyKey = packed[key].(string) + } + return params +} + +func decodeStartMyAssessmentAttemptSessionParams(args [1]string, argsEscaped bool, r *http.Request) (params StartMyAssessmentAttemptSessionParams, _ error) { + h := uri.NewHeaderDecoder(r.Header) + // Decode path: attempt_id. + if err := func() error { + param := args[0] + if argsEscaped { + unescaped, err := url.PathUnescape(args[0]) + if err != nil { + return errors.Wrap(err, "unescape path") + } + param = unescaped + } + if len(param) > 0 { + d := uri.NewPathDecoder(uri.PathDecoderConfig{ + Param: "attempt_id", + Value: param, + Style: uri.PathStyleSimple, + Explode: false, + }) + + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToUUID(val) + if err != nil { + return err + } + + params.AttemptID = c + return nil + }(); err != nil { + return err + } + } else { + return validate.ErrFieldRequired + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "attempt_id", + In: "path", + Err: err, + } + } + // Decode header: Idempotency-Key. + if err := func() error { + cfg := uri.HeaderParameterDecodingConfig{ + Name: "Idempotency-Key", + Explode: false, + } + if err := h.HasParam(cfg); err == nil { + if err := h.DecodeParam(cfg, func(d uri.Decoder) error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToString(val) + if err != nil { + return err + } + + params.IdempotencyKey = c + return nil + }); err != nil { + return err + } + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 255, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^[A-Za-z0-9._:-]+$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(params.IdempotencyKey)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + return err + } + } else { + return err + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "Idempotency-Key", + In: "header", + Err: err, + } + } + return params, nil +} + // SubmitMyAssessmentAnswerParams is parameters of SubmitMyAssessmentAnswer operation. type SubmitMyAssessmentAnswerParams struct { // Identifier of an assessment attempt of the current candidate. An attempt of another candidate and an diff --git a/backend/internal/adapter/primary/http/api/oas_request_decoders_gen.go b/backend/internal/adapter/primary/http/api/oas_request_decoders_gen.go index 276429a..4a2333d 100644 --- a/backend/internal/adapter/primary/http/api/oas_request_decoders_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_request_decoders_gen.go @@ -252,7 +252,7 @@ func (s *Server) decodeConfirmEmailRequest(r *http.Request) ( } func (s *Server) decodeCreateMyAssessmentAttemptRequest(r *http.Request) ( - req *AssessmentAttemptCreate, + req AssessmentAttemptCreate, rawBody []byte, close func() error, rerr error, @@ -324,7 +324,7 @@ func (s *Server) decodeCreateMyAssessmentAttemptRequest(r *http.Request) ( }(); err != nil { return req, rawBody, close, errors.Wrap(err, "validate") } - return &request, rawBody, close, nil + return request, rawBody, close, nil default: return req, rawBody, close, validate.InvalidContentType(ct) } @@ -1515,6 +1515,85 @@ func (s *Server) decodeSetMySearchStatusRequest(r *http.Request) ( } } +func (s *Server) decodeStartMyAssessmentAttemptSessionRequest(r *http.Request) ( + req *AssessmentAttemptSessionStart, + rawBody []byte, + close func() error, + rerr error, +) { + var closers []func() error + close = func() error { + var merr error + // Close in reverse order, to match defer behavior. + for i := len(closers) - 1; i >= 0; i-- { + c := closers[i] + merr = errors.Join(merr, c()) + } + return merr + } + defer func() { + if rerr != nil { + rerr = errors.Join(rerr, close()) + } + }() + ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) + if err != nil { + return req, rawBody, close, errors.Wrap(err, "parse media type") + } + switch { + case ct == "application/json": + if r.ContentLength == 0 { + return req, rawBody, close, validate.ErrBodyRequired + } + buf, err := io.ReadAll(r.Body) + defer func() { + _ = r.Body.Close() + }() + if err != nil { + return req, rawBody, close, err + } + + // Reset the body to allow for downstream reading. + r.Body = io.NopCloser(bytes.NewBuffer(buf)) + + if len(buf) == 0 { + return req, rawBody, close, validate.ErrBodyRequired + } + + rawBody = append(rawBody, buf...) + d := jx.DecodeBytes(buf) + + var request AssessmentAttemptSessionStart + if err := func() error { + if err := request.Decode(d); err != nil { + return err + } + if err := d.Skip(); err != io.EOF { + return errors.New("unexpected trailing data") + } + return nil + }(); err != nil { + err = &ogenerrors.DecodeBodyError{ + ContentType: ct, + Body: buf, + Err: err, + } + return req, rawBody, close, err + } + if err := func() error { + if err := request.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return req, rawBody, close, errors.Wrap(err, "validate") + } + return &request, rawBody, close, nil + default: + return req, rawBody, close, validate.InvalidContentType(ct) + } +} + func (s *Server) decodeSubmitMyAssessmentAnswerRequest(r *http.Request) ( req *AssessmentAnswerSubmission, rawBody []byte, diff --git a/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go b/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go index 1990573..752e042 100644 --- a/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go @@ -4190,6 +4190,157 @@ func encodeSetMySearchStatusResponse(response SetMySearchStatusRes, w http.Respo } } +func encodeStartMyAssessmentAttemptSessionResponse(response StartMyAssessmentAttemptSessionRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *AssessmentAttemptHeaders: + w.Header().Set("Content-Type", "application/json; charset=utf-8") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Cache-Control" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Cache-Control", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + return e.EncodeValue(conv.StringToString(string(response.CacheControl))) + }); err != nil { + return errors.Wrap(err, "encode Cache-Control header") + } + } + } + w.WriteHeader(200) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *StartMyAssessmentAttemptSessionBadRequest: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(400) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *StartMyAssessmentAttemptSessionUnauthorized: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(401) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *StartMyAssessmentAttemptSessionForbidden: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(403) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *StartMyAssessmentAttemptSessionNotFound: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(404) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *StartMyAssessmentAttemptSessionConflict: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(409) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *StartMyAssessmentAttemptSessionPreconditionFailed: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(412) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *StartMyAssessmentAttemptSessionUnprocessableEntity: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(422) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *TooManyRequestsHeaders: + w.Header().Set("Content-Type", "application/problem+json") + w.Header().Set("Access-Control-Expose-Headers", "Retry-After") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Retry-After" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Retry-After", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + if val, ok := response.RetryAfter.Get(); ok { + return e.EncodeValue(conv.Int32ToString(val)) + } + return nil + }); err != nil { + return errors.Wrap(err, "encode Retry-After header") + } + } + } + w.WriteHeader(429) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + default: + return errors.Errorf("unexpected response type: %T", response) + } +} + func encodeSubmitMyAssessmentAnswerResponse(response SubmitMyAssessmentAnswerRes, w http.ResponseWriter, span trace.Span) error { switch response := response.(type) { case *AssessmentAttemptHeaders: diff --git a/backend/internal/adapter/primary/http/api/oas_router_gen.go b/backend/internal/adapter/primary/http/api/oas_router_gen.go index d231d8e..16479f3 100644 --- a/backend/internal/adapter/primary/http/api/oas_router_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_router_gen.go @@ -29,12 +29,15 @@ var ( rn9AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn65AllowedHeaders = map[string]string{ + rn66AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } rn20AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } + rn65AllowedHeaders = map[string]string{ + "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", + } rn3AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } @@ -44,7 +47,7 @@ var ( rn17AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn66AllowedHeaders = map[string]string{ + rn67AllowedHeaders = map[string]string{ "POST": "X-Csrf-Token", } rn46AllowedHeaders = map[string]string{ @@ -84,7 +87,7 @@ var ( rn61AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn67AllowedHeaders = map[string]string{ + rn68AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } rn16AllowedHeaders = map[string]string{ @@ -501,7 +504,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn65AllowedHeaders, + allowedHeaders: rn66AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -564,6 +567,33 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { return } + case 's': // Prefix: "sessions" + + if l := len("sessions"); len(elem) >= l && elem[0:l] == "sessions" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "POST": + s.handleStartMyAssessmentAttemptSessionRequest([1]string{ + args[0], + }, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "POST", + allowedHeaders: rn65AllowedHeaders, + acceptPost: "application/json", + acceptPatch: "", + }) + } + + return + } + } } @@ -792,7 +822,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn66AllowedHeaders, + allowedHeaders: rn67AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -1500,7 +1530,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn67AllowedHeaders, + allowedHeaders: rn68AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -2003,7 +2033,7 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) { switch method { case "POST": r.name = CreateMyAssessmentAttemptOperation - r.summary = "Start an assessment attempt for a category of the current candidate." + r.summary = "Start a real, corrective, or training assessment attempt." r.operationID = "CreateMyAssessmentAttempt" r.operationGroup = "" r.pathPattern = "/api/v1/me/assessment-attempts" @@ -2036,7 +2066,7 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) { switch method { case "GET": r.name = GetMyAssessmentAttemptOperation - r.summary = "Read or resume an assessment attempt of the current candidate." + r.summary = "Read an assessment attempt of the current candidate." r.operationID = "GetMyAssessmentAttempt" r.operationGroup = "" r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}" @@ -2135,6 +2165,31 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) { } } + case 's': // Prefix: "sessions" + + if l := len("sessions"); len(elem) >= l && elem[0:l] == "sessions" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch method { + case "POST": + r.name = StartMyAssessmentAttemptSessionOperation + r.summary = "Start or resume a work session for the current candidate's attempt." + r.operationID = "StartMyAssessmentAttemptSession" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}/sessions" + r.args = args + r.count = 1 + return r, true + default: + return + } + } + } } diff --git a/backend/internal/adapter/primary/http/api/oas_schemas_gen.go b/backend/internal/adapter/primary/http/api/oas_schemas_gen.go index edac15a..33aaee0 100644 --- a/backend/internal/adapter/primary/http/api/oas_schemas_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_schemas_gen.go @@ -520,231 +520,205 @@ func (s *AssessmentAnswerSubmission) SetAnswer(val AssessmentAnswer) { s.Answer = val } -// Assessment attempt of the current candidate for one category, a specialization and a target grade. -// It shows the state, the fixed versions, the server deadline `expires_at` from the policy version, -// which the client clock never extends, the session limit, the progress, the item to answer now, and -// the practices. It never contains answer keys, the correctness of submitted answers, scores of single -// items, family or variant identifiers, seeds, hidden checks, or anti-cheat signals. +// Candidate view of a real assessment, a corrective real assessment, or a demo_express training run. +// The variants keep training output separate from qualification attempts. // Ref: #/components/schemas/AssessmentAttempt +// AssessmentAttempt represents sum type. type AssessmentAttempt struct { - // Attempt identifier. - ID uuid.UUID `json:"id"` - Version AssessmentAttemptVersion `json:"version"` - Specialization SpecializationCode `json:"specialization"` - TargetGrade GradeCode `json:"target_grade"` - // Task language of the attempt, or null when the bank offers no choice. - TaskLanguage NilTaskLanguage `json:"task_language"` - Mode AssessmentMode `json:"mode"` - State AssessmentAttemptState `json:"state"` - Versions AssessmentVersions `json:"versions"` - StartedAt Timestamp `json:"started_at"` - ExpiresAt Timestamp `json:"expires_at"` - // Session limit of the attempt, or null when its policy version defines none. - Sessions NilAssessmentSessions `json:"sessions"` - // Time the attempt reached a terminal state, or null while it is active. - FinishedAt NilTimestamp `json:"finished_at"` - Progress AssessmentProgress `json:"progress"` - // Item to answer now: a test item in `in_progress`, the practice item to submit in `practice_pending` - // or `additional_practice_pending` while that practice is `not_started` or `failed`, and null - // otherwise. - CurrentItem NilAssessmentItem `json:"current_item"` - // Practices in the order they were assigned: the `main` practice first, then an `additional` practice - // once finalize offers it. Empty only for a demo_basic attempt while code practice is disabled until - // the sandbox isolation is verified; its result then lists the `practice_not_included` limitation. A - // list rather than one field leaves room for more practices without a breaking change. - Practices []AssessmentPractice `json:"practices"` + // Type selects the active sum variant, switch on this field. + Type AssessmentAttemptType + AssessmentQualifiedAttempt AssessmentQualifiedAttempt + AssessmentCorrectiveAttempt AssessmentCorrectiveAttempt + AssessmentExpressAttempt AssessmentExpressAttempt } -// GetID returns the value of ID. -func (s *AssessmentAttempt) GetID() uuid.UUID { - return s.ID +// AssessmentAttemptType is oneOf type of AssessmentAttempt. +type AssessmentAttemptType string + +// Possible values for AssessmentAttemptType. +const ( + AssessmentQualifiedAttemptAssessmentAttempt AssessmentAttemptType = "root" + AssessmentCorrectiveAttemptAssessmentAttempt AssessmentAttemptType = "corrective" + AssessmentExpressAttemptAssessmentAttempt AssessmentAttemptType = "demo_express" +) + +// IsAssessmentQualifiedAttempt reports whether AssessmentAttempt is AssessmentQualifiedAttempt. +func (s AssessmentAttempt) IsAssessmentQualifiedAttempt() bool { + return s.Type == AssessmentQualifiedAttemptAssessmentAttempt } -// GetVersion returns the value of Version. -func (s *AssessmentAttempt) GetVersion() AssessmentAttemptVersion { - return s.Version +// IsAssessmentCorrectiveAttempt reports whether AssessmentAttempt is AssessmentCorrectiveAttempt. +func (s AssessmentAttempt) IsAssessmentCorrectiveAttempt() bool { + return s.Type == AssessmentCorrectiveAttemptAssessmentAttempt } -// GetSpecialization returns the value of Specialization. -func (s *AssessmentAttempt) GetSpecialization() SpecializationCode { - return s.Specialization +// IsAssessmentExpressAttempt reports whether AssessmentAttempt is AssessmentExpressAttempt. +func (s AssessmentAttempt) IsAssessmentExpressAttempt() bool { + return s.Type == AssessmentExpressAttemptAssessmentAttempt } -// GetTargetGrade returns the value of TargetGrade. -func (s *AssessmentAttempt) GetTargetGrade() GradeCode { - return s.TargetGrade +// SetAssessmentQualifiedAttempt sets AssessmentAttempt to AssessmentQualifiedAttempt. +func (s *AssessmentAttempt) SetAssessmentQualifiedAttempt(v AssessmentQualifiedAttempt) { + s.Type = AssessmentQualifiedAttemptAssessmentAttempt + s.AssessmentQualifiedAttempt = v } -// GetTaskLanguage returns the value of TaskLanguage. -func (s *AssessmentAttempt) GetTaskLanguage() NilTaskLanguage { - return s.TaskLanguage +// GetAssessmentQualifiedAttempt returns AssessmentQualifiedAttempt and true boolean if AssessmentAttempt is AssessmentQualifiedAttempt. +func (s AssessmentAttempt) GetAssessmentQualifiedAttempt() (v AssessmentQualifiedAttempt, ok bool) { + if !s.IsAssessmentQualifiedAttempt() { + return v, false + } + return s.AssessmentQualifiedAttempt, true } -// GetMode returns the value of Mode. -func (s *AssessmentAttempt) GetMode() AssessmentMode { - return s.Mode +// NewAssessmentQualifiedAttemptAssessmentAttempt returns new AssessmentAttempt from AssessmentQualifiedAttempt. +func NewAssessmentQualifiedAttemptAssessmentAttempt(v AssessmentQualifiedAttempt) AssessmentAttempt { + var s AssessmentAttempt + s.SetAssessmentQualifiedAttempt(v) + return s } -// GetState returns the value of State. -func (s *AssessmentAttempt) GetState() AssessmentAttemptState { - return s.State +// SetAssessmentCorrectiveAttempt sets AssessmentAttempt to AssessmentCorrectiveAttempt. +func (s *AssessmentAttempt) SetAssessmentCorrectiveAttempt(v AssessmentCorrectiveAttempt) { + s.Type = AssessmentCorrectiveAttemptAssessmentAttempt + s.AssessmentCorrectiveAttempt = v } -// GetVersions returns the value of Versions. -func (s *AssessmentAttempt) GetVersions() AssessmentVersions { - return s.Versions +// GetAssessmentCorrectiveAttempt returns AssessmentCorrectiveAttempt and true boolean if AssessmentAttempt is AssessmentCorrectiveAttempt. +func (s AssessmentAttempt) GetAssessmentCorrectiveAttempt() (v AssessmentCorrectiveAttempt, ok bool) { + if !s.IsAssessmentCorrectiveAttempt() { + return v, false + } + return s.AssessmentCorrectiveAttempt, true } -// GetStartedAt returns the value of StartedAt. -func (s *AssessmentAttempt) GetStartedAt() Timestamp { - return s.StartedAt +// NewAssessmentCorrectiveAttemptAssessmentAttempt returns new AssessmentAttempt from AssessmentCorrectiveAttempt. +func NewAssessmentCorrectiveAttemptAssessmentAttempt(v AssessmentCorrectiveAttempt) AssessmentAttempt { + var s AssessmentAttempt + s.SetAssessmentCorrectiveAttempt(v) + return s } -// GetExpiresAt returns the value of ExpiresAt. -func (s *AssessmentAttempt) GetExpiresAt() Timestamp { - return s.ExpiresAt +// SetAssessmentExpressAttempt sets AssessmentAttempt to AssessmentExpressAttempt. +func (s *AssessmentAttempt) SetAssessmentExpressAttempt(v AssessmentExpressAttempt) { + s.Type = AssessmentExpressAttemptAssessmentAttempt + s.AssessmentExpressAttempt = v } -// GetSessions returns the value of Sessions. -func (s *AssessmentAttempt) GetSessions() NilAssessmentSessions { - return s.Sessions +// GetAssessmentExpressAttempt returns AssessmentExpressAttempt and true boolean if AssessmentAttempt is AssessmentExpressAttempt. +func (s AssessmentAttempt) GetAssessmentExpressAttempt() (v AssessmentExpressAttempt, ok bool) { + if !s.IsAssessmentExpressAttempt() { + return v, false + } + return s.AssessmentExpressAttempt, true } -// GetFinishedAt returns the value of FinishedAt. -func (s *AssessmentAttempt) GetFinishedAt() NilTimestamp { - return s.FinishedAt +// NewAssessmentExpressAttemptAssessmentAttempt returns new AssessmentAttempt from AssessmentExpressAttempt. +func NewAssessmentExpressAttemptAssessmentAttempt(v AssessmentExpressAttempt) AssessmentAttempt { + var s AssessmentAttempt + s.SetAssessmentExpressAttempt(v) + return s } -// GetProgress returns the value of Progress. -func (s *AssessmentAttempt) GetProgress() AssessmentProgress { - return s.Progress -} - -// GetCurrentItem returns the value of CurrentItem. -func (s *AssessmentAttempt) GetCurrentItem() NilAssessmentItem { - return s.CurrentItem -} - -// GetPractices returns the value of Practices. -func (s *AssessmentAttempt) GetPractices() []AssessmentPractice { - return s.Practices -} - -// SetID sets the value of ID. -func (s *AssessmentAttempt) SetID(val uuid.UUID) { - s.ID = val -} - -// SetVersion sets the value of Version. -func (s *AssessmentAttempt) SetVersion(val AssessmentAttemptVersion) { - s.Version = val -} - -// SetSpecialization sets the value of Specialization. -func (s *AssessmentAttempt) SetSpecialization(val SpecializationCode) { - s.Specialization = val -} - -// SetTargetGrade sets the value of TargetGrade. -func (s *AssessmentAttempt) SetTargetGrade(val GradeCode) { - s.TargetGrade = val -} - -// SetTaskLanguage sets the value of TaskLanguage. -func (s *AssessmentAttempt) SetTaskLanguage(val NilTaskLanguage) { - s.TaskLanguage = val -} - -// SetMode sets the value of Mode. -func (s *AssessmentAttempt) SetMode(val AssessmentMode) { - s.Mode = val -} - -// SetState sets the value of State. -func (s *AssessmentAttempt) SetState(val AssessmentAttemptState) { - s.State = val -} - -// SetVersions sets the value of Versions. -func (s *AssessmentAttempt) SetVersions(val AssessmentVersions) { - s.Versions = val -} - -// SetStartedAt sets the value of StartedAt. -func (s *AssessmentAttempt) SetStartedAt(val Timestamp) { - s.StartedAt = val -} - -// SetExpiresAt sets the value of ExpiresAt. -func (s *AssessmentAttempt) SetExpiresAt(val Timestamp) { - s.ExpiresAt = val -} - -// SetSessions sets the value of Sessions. -func (s *AssessmentAttempt) SetSessions(val NilAssessmentSessions) { - s.Sessions = val -} - -// SetFinishedAt sets the value of FinishedAt. -func (s *AssessmentAttempt) SetFinishedAt(val NilTimestamp) { - s.FinishedAt = val -} - -// SetProgress sets the value of Progress. -func (s *AssessmentAttempt) SetProgress(val AssessmentProgress) { - s.Progress = val -} - -// SetCurrentItem sets the value of CurrentItem. -func (s *AssessmentAttempt) SetCurrentItem(val NilAssessmentItem) { - s.CurrentItem = val -} - -// SetPractices sets the value of Practices. -func (s *AssessmentAttempt) SetPractices(val []AssessmentPractice) { - s.Practices = val -} - -// Category to assess: a specialization and the target grade, with the task language. The candidate -// comes from the session. The mode and versions are chosen by the server; unknown fields such as -// `mode`, `seed`, or `score` are rejected. +// Start a real assessment, a corrective attempt in an existing chain, or an explicit training run. The +// required `kind` discriminator selects one of the three request shapes; `mode` remains +// server-selected for real assessments. // Ref: #/components/schemas/AssessmentAttemptCreate +// AssessmentAttemptCreate represents sum type. type AssessmentAttemptCreate struct { - Specialization SpecializationCode `json:"specialization"` - TargetGrade GradeCode `json:"target_grade"` - // Task language of the attempt, one of the `task_languages` of the published bank, or null when the - // bank offers no choice of language. The questionnaire choice is the value the client offers first. - TaskLanguage NilTaskLanguage `json:"task_language"` + // Type selects the active sum variant, switch on this field. + Type AssessmentAttemptCreateType + AssessmentQualifiedAttemptCreate AssessmentQualifiedAttemptCreate + AssessmentCorrectiveAttemptCreate AssessmentCorrectiveAttemptCreate + AssessmentExpressAttemptCreate AssessmentExpressAttemptCreate } -// GetSpecialization returns the value of Specialization. -func (s *AssessmentAttemptCreate) GetSpecialization() SpecializationCode { - return s.Specialization +// AssessmentAttemptCreateType is oneOf type of AssessmentAttemptCreate. +type AssessmentAttemptCreateType string + +// Possible values for AssessmentAttemptCreateType. +const ( + AssessmentQualifiedAttemptCreateAssessmentAttemptCreate AssessmentAttemptCreateType = "root" + AssessmentCorrectiveAttemptCreateAssessmentAttemptCreate AssessmentAttemptCreateType = "corrective" + AssessmentExpressAttemptCreateAssessmentAttemptCreate AssessmentAttemptCreateType = "demo_express" +) + +// IsAssessmentQualifiedAttemptCreate reports whether AssessmentAttemptCreate is AssessmentQualifiedAttemptCreate. +func (s AssessmentAttemptCreate) IsAssessmentQualifiedAttemptCreate() bool { + return s.Type == AssessmentQualifiedAttemptCreateAssessmentAttemptCreate } -// GetTargetGrade returns the value of TargetGrade. -func (s *AssessmentAttemptCreate) GetTargetGrade() GradeCode { - return s.TargetGrade +// IsAssessmentCorrectiveAttemptCreate reports whether AssessmentAttemptCreate is AssessmentCorrectiveAttemptCreate. +func (s AssessmentAttemptCreate) IsAssessmentCorrectiveAttemptCreate() bool { + return s.Type == AssessmentCorrectiveAttemptCreateAssessmentAttemptCreate } -// GetTaskLanguage returns the value of TaskLanguage. -func (s *AssessmentAttemptCreate) GetTaskLanguage() NilTaskLanguage { - return s.TaskLanguage +// IsAssessmentExpressAttemptCreate reports whether AssessmentAttemptCreate is AssessmentExpressAttemptCreate. +func (s AssessmentAttemptCreate) IsAssessmentExpressAttemptCreate() bool { + return s.Type == AssessmentExpressAttemptCreateAssessmentAttemptCreate } -// SetSpecialization sets the value of Specialization. -func (s *AssessmentAttemptCreate) SetSpecialization(val SpecializationCode) { - s.Specialization = val +// SetAssessmentQualifiedAttemptCreate sets AssessmentAttemptCreate to AssessmentQualifiedAttemptCreate. +func (s *AssessmentAttemptCreate) SetAssessmentQualifiedAttemptCreate(v AssessmentQualifiedAttemptCreate) { + s.Type = AssessmentQualifiedAttemptCreateAssessmentAttemptCreate + s.AssessmentQualifiedAttemptCreate = v } -// SetTargetGrade sets the value of TargetGrade. -func (s *AssessmentAttemptCreate) SetTargetGrade(val GradeCode) { - s.TargetGrade = val +// GetAssessmentQualifiedAttemptCreate returns AssessmentQualifiedAttemptCreate and true boolean if AssessmentAttemptCreate is AssessmentQualifiedAttemptCreate. +func (s AssessmentAttemptCreate) GetAssessmentQualifiedAttemptCreate() (v AssessmentQualifiedAttemptCreate, ok bool) { + if !s.IsAssessmentQualifiedAttemptCreate() { + return v, false + } + return s.AssessmentQualifiedAttemptCreate, true } -// SetTaskLanguage sets the value of TaskLanguage. -func (s *AssessmentAttemptCreate) SetTaskLanguage(val NilTaskLanguage) { - s.TaskLanguage = val +// NewAssessmentQualifiedAttemptCreateAssessmentAttemptCreate returns new AssessmentAttemptCreate from AssessmentQualifiedAttemptCreate. +func NewAssessmentQualifiedAttemptCreateAssessmentAttemptCreate(v AssessmentQualifiedAttemptCreate) AssessmentAttemptCreate { + var s AssessmentAttemptCreate + s.SetAssessmentQualifiedAttemptCreate(v) + return s +} + +// SetAssessmentCorrectiveAttemptCreate sets AssessmentAttemptCreate to AssessmentCorrectiveAttemptCreate. +func (s *AssessmentAttemptCreate) SetAssessmentCorrectiveAttemptCreate(v AssessmentCorrectiveAttemptCreate) { + s.Type = AssessmentCorrectiveAttemptCreateAssessmentAttemptCreate + s.AssessmentCorrectiveAttemptCreate = v +} + +// GetAssessmentCorrectiveAttemptCreate returns AssessmentCorrectiveAttemptCreate and true boolean if AssessmentAttemptCreate is AssessmentCorrectiveAttemptCreate. +func (s AssessmentAttemptCreate) GetAssessmentCorrectiveAttemptCreate() (v AssessmentCorrectiveAttemptCreate, ok bool) { + if !s.IsAssessmentCorrectiveAttemptCreate() { + return v, false + } + return s.AssessmentCorrectiveAttemptCreate, true +} + +// NewAssessmentCorrectiveAttemptCreateAssessmentAttemptCreate returns new AssessmentAttemptCreate from AssessmentCorrectiveAttemptCreate. +func NewAssessmentCorrectiveAttemptCreateAssessmentAttemptCreate(v AssessmentCorrectiveAttemptCreate) AssessmentAttemptCreate { + var s AssessmentAttemptCreate + s.SetAssessmentCorrectiveAttemptCreate(v) + return s +} + +// SetAssessmentExpressAttemptCreate sets AssessmentAttemptCreate to AssessmentExpressAttemptCreate. +func (s *AssessmentAttemptCreate) SetAssessmentExpressAttemptCreate(v AssessmentExpressAttemptCreate) { + s.Type = AssessmentExpressAttemptCreateAssessmentAttemptCreate + s.AssessmentExpressAttemptCreate = v +} + +// GetAssessmentExpressAttemptCreate returns AssessmentExpressAttemptCreate and true boolean if AssessmentAttemptCreate is AssessmentExpressAttemptCreate. +func (s AssessmentAttemptCreate) GetAssessmentExpressAttemptCreate() (v AssessmentExpressAttemptCreate, ok bool) { + if !s.IsAssessmentExpressAttemptCreate() { + return v, false + } + return s.AssessmentExpressAttemptCreate, true +} + +// NewAssessmentExpressAttemptCreateAssessmentAttemptCreate returns new AssessmentAttemptCreate from AssessmentExpressAttemptCreate. +func NewAssessmentExpressAttemptCreateAssessmentAttemptCreate(v AssessmentExpressAttemptCreate) AssessmentAttemptCreate { + var s AssessmentAttemptCreate + s.SetAssessmentExpressAttemptCreate(v) + return s } // AssessmentAttemptHeaders wraps AssessmentAttempt with response headers. @@ -773,10 +747,27 @@ func (s *AssessmentAttemptHeaders) SetResponse(val AssessmentAttempt) { s.Response = val } -func (*AssessmentAttemptHeaders) createMyAssessmentAttemptRes() {} -func (*AssessmentAttemptHeaders) finalizeMyAssessmentAttemptRes() {} -func (*AssessmentAttemptHeaders) getMyAssessmentAttemptRes() {} -func (*AssessmentAttemptHeaders) submitMyAssessmentAnswerRes() {} +func (*AssessmentAttemptHeaders) createMyAssessmentAttemptRes() {} +func (*AssessmentAttemptHeaders) finalizeMyAssessmentAttemptRes() {} +func (*AssessmentAttemptHeaders) getMyAssessmentAttemptRes() {} +func (*AssessmentAttemptHeaders) startMyAssessmentAttemptSessionRes() {} +func (*AssessmentAttemptHeaders) submitMyAssessmentAnswerRes() {} + +// Start or resume a work session using the attempt version last read by the candidate. +// Ref: #/components/schemas/AssessmentAttemptSessionStart +type AssessmentAttemptSessionStart struct { + ExpectedVersion AssessmentAttemptVersion `json:"expected_version"` +} + +// GetExpectedVersion returns the value of ExpectedVersion. +func (s *AssessmentAttemptSessionStart) GetExpectedVersion() AssessmentAttemptVersion { + return s.ExpectedVersion +} + +// SetExpectedVersion sets the value of ExpectedVersion. +func (s *AssessmentAttemptSessionStart) SetExpectedVersion(val AssessmentAttemptVersion) { + s.ExpectedVersion = val +} // Lifecycle state of an attempt and the commands it accepts. // @@ -802,10 +793,11 @@ func (*AssessmentAttemptHeaders) submitMyAssessmentAnswerRes() {} // limit, and the attempt ended without a confirmed grade instead of repeating families. The result // is available. // -// When `expires_at` passes or the session limit is reached, a practice submitted before that and still -// `pending` is graded first. Then the server decides without another command: `ready_to_finalize` is -// finalized and becomes `completed`; `additional_practice_pending` with the additional practice not -// submitted is finalized as declined and becomes `completed` with `not_confirmed`; `in_progress` and +// When `expires_at` passes or the session limit is reached, a read returns the stored state without +// changing it. A command or background transition commits any due outcome and advances the version. A +// practice submitted before the limit and still `pending` is graded first. Then `ready_to_finalize` +// becomes `completed`; `additional_practice_pending` with the additional practice not submitted is +// finalized as declined and becomes `completed` with `not_confirmed`; `in_progress` and // `practice_pending` become `expired`, with the result reason `expired` or `practice_incomplete`; and // when the latest submission of a practice ended `failed`, the attempt becomes `expired` with the // reason `sandbox_unavailable`, which is not the candidate's fault. `completed`, `expired`, and @@ -936,6 +928,751 @@ func (s *AssessmentAvailabilityHeaders) SetResponse(val AssessmentAvailability) func (*AssessmentAvailabilityHeaders) getMyAssessmentAvailabilityRes() {} +// Merged schema. +// Ref: #/components/schemas/AssessmentCorrectiveAttempt +type AssessmentCorrectiveAttempt struct { + // Attempt identifier. + ID uuid.UUID `json:"id"` + Version AssessmentAttemptVersion `json:"version"` + // Merged property. + Specialization NilSpecializationCode `json:"specialization"` + // Merged property. + TargetGrade NilGradeCode `json:"target_grade"` + // Task language of the attempt, or null when none is selected. + TaskLanguage NilTaskLanguage `json:"task_language"` + // Merged property. + Kind AssessmentCorrectiveAttemptKind `json:"kind"` + // Merged property. + RootAttemptID NilUUID `json:"root_attempt_id"` + // Merged property. + ChainDeadline NilTimestamp `json:"chain_deadline"` + // Merged property. + Mode AssessmentCorrectiveAttemptMode `json:"mode"` + State AssessmentAttemptState `json:"state"` + Versions AssessmentVersions `json:"versions"` + StartedAt Timestamp `json:"started_at"` + // Server deadline. For demo_express it is 180 to 300 seconds after started_at; for a corrective + // assessment it does not exceed chain_deadline. + ExpiresAt Timestamp `json:"expires_at"` + // Session limit of the attempt, or null when its policy defines none. + Sessions NilAssessmentSessions `json:"sessions"` + // Time the attempt reached a terminal state, or null while it is active. + FinishedAt NilTimestamp `json:"finished_at"` + Progress AssessmentProgress `json:"progress"` + // Item to answer now: a test item in `in_progress`, the practice item to submit in `practice_pending` + // or `additional_practice_pending` while that practice is `not_started` or `failed`, and null + // 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"` +} + +// GetID returns the value of ID. +func (s *AssessmentCorrectiveAttempt) GetID() uuid.UUID { + return s.ID +} + +// GetVersion returns the value of Version. +func (s *AssessmentCorrectiveAttempt) GetVersion() AssessmentAttemptVersion { + return s.Version +} + +// GetSpecialization returns the value of Specialization. +func (s *AssessmentCorrectiveAttempt) GetSpecialization() NilSpecializationCode { + return s.Specialization +} + +// GetTargetGrade returns the value of TargetGrade. +func (s *AssessmentCorrectiveAttempt) GetTargetGrade() NilGradeCode { + return s.TargetGrade +} + +// GetTaskLanguage returns the value of TaskLanguage. +func (s *AssessmentCorrectiveAttempt) GetTaskLanguage() NilTaskLanguage { + return s.TaskLanguage +} + +// GetKind returns the value of Kind. +func (s *AssessmentCorrectiveAttempt) GetKind() AssessmentCorrectiveAttemptKind { + return s.Kind +} + +// GetRootAttemptID returns the value of RootAttemptID. +func (s *AssessmentCorrectiveAttempt) GetRootAttemptID() NilUUID { + return s.RootAttemptID +} + +// GetChainDeadline returns the value of ChainDeadline. +func (s *AssessmentCorrectiveAttempt) GetChainDeadline() NilTimestamp { + return s.ChainDeadline +} + +// GetMode returns the value of Mode. +func (s *AssessmentCorrectiveAttempt) GetMode() AssessmentCorrectiveAttemptMode { + return s.Mode +} + +// GetState returns the value of State. +func (s *AssessmentCorrectiveAttempt) GetState() AssessmentAttemptState { + return s.State +} + +// GetVersions returns the value of Versions. +func (s *AssessmentCorrectiveAttempt) GetVersions() AssessmentVersions { + return s.Versions +} + +// GetStartedAt returns the value of StartedAt. +func (s *AssessmentCorrectiveAttempt) GetStartedAt() Timestamp { + return s.StartedAt +} + +// GetExpiresAt returns the value of ExpiresAt. +func (s *AssessmentCorrectiveAttempt) GetExpiresAt() Timestamp { + return s.ExpiresAt +} + +// GetSessions returns the value of Sessions. +func (s *AssessmentCorrectiveAttempt) GetSessions() NilAssessmentSessions { + return s.Sessions +} + +// GetFinishedAt returns the value of FinishedAt. +func (s *AssessmentCorrectiveAttempt) GetFinishedAt() NilTimestamp { + return s.FinishedAt +} + +// GetProgress returns the value of Progress. +func (s *AssessmentCorrectiveAttempt) GetProgress() AssessmentProgress { + return s.Progress +} + +// GetCurrentItem returns the value of CurrentItem. +func (s *AssessmentCorrectiveAttempt) GetCurrentItem() NilAssessmentItem { + return s.CurrentItem +} + +// GetPractices returns the value of Practices. +func (s *AssessmentCorrectiveAttempt) GetPractices() []AssessmentPractice { + return s.Practices +} + +// SetID sets the value of ID. +func (s *AssessmentCorrectiveAttempt) SetID(val uuid.UUID) { + s.ID = val +} + +// SetVersion sets the value of Version. +func (s *AssessmentCorrectiveAttempt) SetVersion(val AssessmentAttemptVersion) { + s.Version = val +} + +// SetSpecialization sets the value of Specialization. +func (s *AssessmentCorrectiveAttempt) SetSpecialization(val NilSpecializationCode) { + s.Specialization = val +} + +// SetTargetGrade sets the value of TargetGrade. +func (s *AssessmentCorrectiveAttempt) SetTargetGrade(val NilGradeCode) { + s.TargetGrade = val +} + +// SetTaskLanguage sets the value of TaskLanguage. +func (s *AssessmentCorrectiveAttempt) SetTaskLanguage(val NilTaskLanguage) { + s.TaskLanguage = val +} + +// SetKind sets the value of Kind. +func (s *AssessmentCorrectiveAttempt) SetKind(val AssessmentCorrectiveAttemptKind) { + s.Kind = val +} + +// SetRootAttemptID sets the value of RootAttemptID. +func (s *AssessmentCorrectiveAttempt) SetRootAttemptID(val NilUUID) { + s.RootAttemptID = val +} + +// SetChainDeadline sets the value of ChainDeadline. +func (s *AssessmentCorrectiveAttempt) SetChainDeadline(val NilTimestamp) { + s.ChainDeadline = val +} + +// SetMode sets the value of Mode. +func (s *AssessmentCorrectiveAttempt) SetMode(val AssessmentCorrectiveAttemptMode) { + s.Mode = val +} + +// SetState sets the value of State. +func (s *AssessmentCorrectiveAttempt) SetState(val AssessmentAttemptState) { + s.State = val +} + +// SetVersions sets the value of Versions. +func (s *AssessmentCorrectiveAttempt) SetVersions(val AssessmentVersions) { + s.Versions = val +} + +// SetStartedAt sets the value of StartedAt. +func (s *AssessmentCorrectiveAttempt) SetStartedAt(val Timestamp) { + s.StartedAt = val +} + +// SetExpiresAt sets the value of ExpiresAt. +func (s *AssessmentCorrectiveAttempt) SetExpiresAt(val Timestamp) { + s.ExpiresAt = val +} + +// SetSessions sets the value of Sessions. +func (s *AssessmentCorrectiveAttempt) SetSessions(val NilAssessmentSessions) { + s.Sessions = val +} + +// SetFinishedAt sets the value of FinishedAt. +func (s *AssessmentCorrectiveAttempt) SetFinishedAt(val NilTimestamp) { + s.FinishedAt = val +} + +// SetProgress sets the value of Progress. +func (s *AssessmentCorrectiveAttempt) SetProgress(val AssessmentProgress) { + s.Progress = val +} + +// SetCurrentItem sets the value of CurrentItem. +func (s *AssessmentCorrectiveAttempt) SetCurrentItem(val NilAssessmentItem) { + s.CurrentItem = val +} + +// SetPractices sets the value of Practices. +func (s *AssessmentCorrectiveAttempt) SetPractices(val []AssessmentPractice) { + s.Practices = 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 +// is never supplied by the client. +// Ref: #/components/schemas/AssessmentCorrectiveAttemptCreate +type AssessmentCorrectiveAttemptCreate struct { + // Continue the existing real-assessment chain without reserving another root slot. + Kind AssessmentCorrectiveAttemptCreateKind `json:"kind"` + Specialization SpecializationCode `json:"specialization"` + TargetGrade GradeCode `json:"target_grade"` + // Task language of the attempt, or null when the bank offers no choice. + TaskLanguage NilTaskLanguage `json:"task_language"` + // Root real-assessment attempt whose quota and deadline this attempt shares. + RootAttemptID uuid.UUID `json:"root_attempt_id"` +} + +// GetKind returns the value of Kind. +func (s *AssessmentCorrectiveAttemptCreate) GetKind() AssessmentCorrectiveAttemptCreateKind { + return s.Kind +} + +// GetSpecialization returns the value of Specialization. +func (s *AssessmentCorrectiveAttemptCreate) GetSpecialization() SpecializationCode { + return s.Specialization +} + +// GetTargetGrade returns the value of TargetGrade. +func (s *AssessmentCorrectiveAttemptCreate) GetTargetGrade() GradeCode { + return s.TargetGrade +} + +// GetTaskLanguage returns the value of TaskLanguage. +func (s *AssessmentCorrectiveAttemptCreate) GetTaskLanguage() NilTaskLanguage { + return s.TaskLanguage +} + +// GetRootAttemptID returns the value of RootAttemptID. +func (s *AssessmentCorrectiveAttemptCreate) GetRootAttemptID() uuid.UUID { + return s.RootAttemptID +} + +// SetKind sets the value of Kind. +func (s *AssessmentCorrectiveAttemptCreate) SetKind(val AssessmentCorrectiveAttemptCreateKind) { + s.Kind = val +} + +// SetSpecialization sets the value of Specialization. +func (s *AssessmentCorrectiveAttemptCreate) SetSpecialization(val SpecializationCode) { + s.Specialization = val +} + +// SetTargetGrade sets the value of TargetGrade. +func (s *AssessmentCorrectiveAttemptCreate) SetTargetGrade(val GradeCode) { + s.TargetGrade = val +} + +// SetTaskLanguage sets the value of TaskLanguage. +func (s *AssessmentCorrectiveAttemptCreate) SetTaskLanguage(val NilTaskLanguage) { + s.TaskLanguage = val +} + +// SetRootAttemptID sets the value of RootAttemptID. +func (s *AssessmentCorrectiveAttemptCreate) SetRootAttemptID(val uuid.UUID) { + s.RootAttemptID = val +} + +// Continue the existing real-assessment chain without reserving another root slot. +type AssessmentCorrectiveAttemptCreateKind string + +const ( + AssessmentCorrectiveAttemptCreateKindCorrective AssessmentCorrectiveAttemptCreateKind = "corrective" +) + +// AllValues returns all AssessmentCorrectiveAttemptCreateKind values. +func (AssessmentCorrectiveAttemptCreateKind) AllValues() []AssessmentCorrectiveAttemptCreateKind { + return []AssessmentCorrectiveAttemptCreateKind{ + AssessmentCorrectiveAttemptCreateKindCorrective, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s AssessmentCorrectiveAttemptCreateKind) MarshalText() ([]byte, error) { + switch s { + case AssessmentCorrectiveAttemptCreateKindCorrective: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *AssessmentCorrectiveAttemptCreateKind) UnmarshalText(data []byte) error { + switch AssessmentCorrectiveAttemptCreateKind(data) { + case AssessmentCorrectiveAttemptCreateKindCorrective: + *s = AssessmentCorrectiveAttemptCreateKindCorrective + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Merged schema. +type AssessmentCorrectiveAttemptKind string + +const ( + AssessmentCorrectiveAttemptKindCorrective AssessmentCorrectiveAttemptKind = "corrective" +) + +// AllValues returns all AssessmentCorrectiveAttemptKind values. +func (AssessmentCorrectiveAttemptKind) AllValues() []AssessmentCorrectiveAttemptKind { + return []AssessmentCorrectiveAttemptKind{ + AssessmentCorrectiveAttemptKindCorrective, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s AssessmentCorrectiveAttemptKind) MarshalText() ([]byte, error) { + switch s { + case AssessmentCorrectiveAttemptKindCorrective: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *AssessmentCorrectiveAttemptKind) UnmarshalText(data []byte) error { + switch AssessmentCorrectiveAttemptKind(data) { + case AssessmentCorrectiveAttemptKindCorrective: + *s = AssessmentCorrectiveAttemptKindCorrective + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Merged schema. +type AssessmentCorrectiveAttemptMode string + +const ( + AssessmentCorrectiveAttemptModeDemoBasic AssessmentCorrectiveAttemptMode = "demo_basic" + AssessmentCorrectiveAttemptModeAdaptive AssessmentCorrectiveAttemptMode = "adaptive" +) + +// AllValues returns all AssessmentCorrectiveAttemptMode values. +func (AssessmentCorrectiveAttemptMode) AllValues() []AssessmentCorrectiveAttemptMode { + return []AssessmentCorrectiveAttemptMode{ + AssessmentCorrectiveAttemptModeDemoBasic, + AssessmentCorrectiveAttemptModeAdaptive, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s AssessmentCorrectiveAttemptMode) MarshalText() ([]byte, error) { + switch s { + case AssessmentCorrectiveAttemptModeDemoBasic: + return []byte(s), nil + case AssessmentCorrectiveAttemptModeAdaptive: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *AssessmentCorrectiveAttemptMode) UnmarshalText(data []byte) error { + switch AssessmentCorrectiveAttemptMode(data) { + case AssessmentCorrectiveAttemptModeDemoBasic: + *s = AssessmentCorrectiveAttemptModeDemoBasic + return nil + case AssessmentCorrectiveAttemptModeAdaptive: + *s = AssessmentCorrectiveAttemptModeAdaptive + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Merged schema. +// Ref: #/components/schemas/AssessmentCorrectiveResult +type AssessmentCorrectiveResult struct { + AttemptID uuid.UUID `json:"attempt_id"` + Specialization SpecializationCode `json:"specialization"` + TargetGrade GradeCode `json:"target_grade"` + // Merged property. + RootAttemptID NilUUID `json:"root_attempt_id"` + // Merged property. + ChainDeadline NilTimestamp `json:"chain_deadline"` + TaskLanguage NilTaskLanguage `json:"task_language"` + // Merged property. + Kind AssessmentCorrectiveResultKind `json:"kind"` + Mode AssessmentCorrectiveResultMode `json:"mode"` + Versions AssessmentVersions `json:"versions"` + Outcome AssessmentOutcome `json:"outcome"` + // The reason when `outcome` is `not_determined`, otherwise null. + NotDeterminedReason NilAssessmentNotDeterminedReason `json:"not_determined_reason"` + // Grade that this attempt confirmed, the target grade, or null when it confirmed none. Together with + // the specialization it forms the category. + ConfirmedGrade NilGradeCode `json:"confirmed_grade"` + // Confirmed grade of the specialization before this attempt, or null. When the attempt confirmed + // nothing, this grade stays in force. + PreviousConfirmedGrade NilGradeCode `json:"previous_confirmed_grade"` + // Strength of an adaptive confirmation, otherwise null. + Strength NilAssessmentStrength `json:"strength"` + CalibrationStatus CalibrationStatus `json:"calibration_status"` + Limitations []AssessmentLimitation `json:"limitations"` + // Ability estimate and uncertainty of an adaptive attempt with a decision; null for demo_basic, which + // computes none, and for an attempt without a decision. + Uncertainty NilAssessmentUncertainty `json:"uncertainty"` + // Raw score of a demo_basic attempt with a decision, otherwise null. + BasicScore NilBasicScore `json:"basic_score"` + // Verdicts of the practices that have one, main first. + Practices []AssessmentPracticeResult `json:"practices"` + // Domains with weak evidence; empty when none were found or the method finds none. + Gaps []AssessmentGap `json:"gaps"` + Durations AssessmentDurations `json:"durations"` + NextSteps []AssessmentNextStep `json:"next_steps"` + DecidedAt Timestamp `json:"decided_at"` +} + +// GetAttemptID returns the value of AttemptID. +func (s *AssessmentCorrectiveResult) GetAttemptID() uuid.UUID { + return s.AttemptID +} + +// GetSpecialization returns the value of Specialization. +func (s *AssessmentCorrectiveResult) GetSpecialization() SpecializationCode { + return s.Specialization +} + +// GetTargetGrade returns the value of TargetGrade. +func (s *AssessmentCorrectiveResult) GetTargetGrade() GradeCode { + return s.TargetGrade +} + +// GetRootAttemptID returns the value of RootAttemptID. +func (s *AssessmentCorrectiveResult) GetRootAttemptID() NilUUID { + return s.RootAttemptID +} + +// GetChainDeadline returns the value of ChainDeadline. +func (s *AssessmentCorrectiveResult) GetChainDeadline() NilTimestamp { + return s.ChainDeadline +} + +// GetTaskLanguage returns the value of TaskLanguage. +func (s *AssessmentCorrectiveResult) GetTaskLanguage() NilTaskLanguage { + return s.TaskLanguage +} + +// GetKind returns the value of Kind. +func (s *AssessmentCorrectiveResult) GetKind() AssessmentCorrectiveResultKind { + return s.Kind +} + +// GetMode returns the value of Mode. +func (s *AssessmentCorrectiveResult) GetMode() AssessmentCorrectiveResultMode { + return s.Mode +} + +// GetVersions returns the value of Versions. +func (s *AssessmentCorrectiveResult) GetVersions() AssessmentVersions { + return s.Versions +} + +// GetOutcome returns the value of Outcome. +func (s *AssessmentCorrectiveResult) GetOutcome() AssessmentOutcome { + return s.Outcome +} + +// GetNotDeterminedReason returns the value of NotDeterminedReason. +func (s *AssessmentCorrectiveResult) GetNotDeterminedReason() NilAssessmentNotDeterminedReason { + return s.NotDeterminedReason +} + +// GetConfirmedGrade returns the value of ConfirmedGrade. +func (s *AssessmentCorrectiveResult) GetConfirmedGrade() NilGradeCode { + return s.ConfirmedGrade +} + +// GetPreviousConfirmedGrade returns the value of PreviousConfirmedGrade. +func (s *AssessmentCorrectiveResult) GetPreviousConfirmedGrade() NilGradeCode { + return s.PreviousConfirmedGrade +} + +// GetStrength returns the value of Strength. +func (s *AssessmentCorrectiveResult) GetStrength() NilAssessmentStrength { + return s.Strength +} + +// GetCalibrationStatus returns the value of CalibrationStatus. +func (s *AssessmentCorrectiveResult) GetCalibrationStatus() CalibrationStatus { + return s.CalibrationStatus +} + +// GetLimitations returns the value of Limitations. +func (s *AssessmentCorrectiveResult) GetLimitations() []AssessmentLimitation { + return s.Limitations +} + +// GetUncertainty returns the value of Uncertainty. +func (s *AssessmentCorrectiveResult) GetUncertainty() NilAssessmentUncertainty { + return s.Uncertainty +} + +// GetBasicScore returns the value of BasicScore. +func (s *AssessmentCorrectiveResult) GetBasicScore() NilBasicScore { + return s.BasicScore +} + +// GetPractices returns the value of Practices. +func (s *AssessmentCorrectiveResult) GetPractices() []AssessmentPracticeResult { + return s.Practices +} + +// GetGaps returns the value of Gaps. +func (s *AssessmentCorrectiveResult) GetGaps() []AssessmentGap { + return s.Gaps +} + +// GetDurations returns the value of Durations. +func (s *AssessmentCorrectiveResult) GetDurations() AssessmentDurations { + return s.Durations +} + +// GetNextSteps returns the value of NextSteps. +func (s *AssessmentCorrectiveResult) GetNextSteps() []AssessmentNextStep { + return s.NextSteps +} + +// GetDecidedAt returns the value of DecidedAt. +func (s *AssessmentCorrectiveResult) GetDecidedAt() Timestamp { + return s.DecidedAt +} + +// SetAttemptID sets the value of AttemptID. +func (s *AssessmentCorrectiveResult) SetAttemptID(val uuid.UUID) { + s.AttemptID = val +} + +// SetSpecialization sets the value of Specialization. +func (s *AssessmentCorrectiveResult) SetSpecialization(val SpecializationCode) { + s.Specialization = val +} + +// SetTargetGrade sets the value of TargetGrade. +func (s *AssessmentCorrectiveResult) SetTargetGrade(val GradeCode) { + s.TargetGrade = val +} + +// SetRootAttemptID sets the value of RootAttemptID. +func (s *AssessmentCorrectiveResult) SetRootAttemptID(val NilUUID) { + s.RootAttemptID = val +} + +// SetChainDeadline sets the value of ChainDeadline. +func (s *AssessmentCorrectiveResult) SetChainDeadline(val NilTimestamp) { + s.ChainDeadline = val +} + +// SetTaskLanguage sets the value of TaskLanguage. +func (s *AssessmentCorrectiveResult) SetTaskLanguage(val NilTaskLanguage) { + s.TaskLanguage = val +} + +// SetKind sets the value of Kind. +func (s *AssessmentCorrectiveResult) SetKind(val AssessmentCorrectiveResultKind) { + s.Kind = val +} + +// SetMode sets the value of Mode. +func (s *AssessmentCorrectiveResult) SetMode(val AssessmentCorrectiveResultMode) { + s.Mode = val +} + +// SetVersions sets the value of Versions. +func (s *AssessmentCorrectiveResult) SetVersions(val AssessmentVersions) { + s.Versions = val +} + +// SetOutcome sets the value of Outcome. +func (s *AssessmentCorrectiveResult) SetOutcome(val AssessmentOutcome) { + s.Outcome = val +} + +// SetNotDeterminedReason sets the value of NotDeterminedReason. +func (s *AssessmentCorrectiveResult) SetNotDeterminedReason(val NilAssessmentNotDeterminedReason) { + s.NotDeterminedReason = val +} + +// SetConfirmedGrade sets the value of ConfirmedGrade. +func (s *AssessmentCorrectiveResult) SetConfirmedGrade(val NilGradeCode) { + s.ConfirmedGrade = val +} + +// SetPreviousConfirmedGrade sets the value of PreviousConfirmedGrade. +func (s *AssessmentCorrectiveResult) SetPreviousConfirmedGrade(val NilGradeCode) { + s.PreviousConfirmedGrade = val +} + +// SetStrength sets the value of Strength. +func (s *AssessmentCorrectiveResult) SetStrength(val NilAssessmentStrength) { + s.Strength = val +} + +// SetCalibrationStatus sets the value of CalibrationStatus. +func (s *AssessmentCorrectiveResult) SetCalibrationStatus(val CalibrationStatus) { + s.CalibrationStatus = val +} + +// SetLimitations sets the value of Limitations. +func (s *AssessmentCorrectiveResult) SetLimitations(val []AssessmentLimitation) { + s.Limitations = val +} + +// SetUncertainty sets the value of Uncertainty. +func (s *AssessmentCorrectiveResult) SetUncertainty(val NilAssessmentUncertainty) { + s.Uncertainty = val +} + +// SetBasicScore sets the value of BasicScore. +func (s *AssessmentCorrectiveResult) SetBasicScore(val NilBasicScore) { + s.BasicScore = val +} + +// SetPractices sets the value of Practices. +func (s *AssessmentCorrectiveResult) SetPractices(val []AssessmentPracticeResult) { + s.Practices = val +} + +// SetGaps sets the value of Gaps. +func (s *AssessmentCorrectiveResult) SetGaps(val []AssessmentGap) { + s.Gaps = val +} + +// SetDurations sets the value of Durations. +func (s *AssessmentCorrectiveResult) SetDurations(val AssessmentDurations) { + s.Durations = val +} + +// SetNextSteps sets the value of NextSteps. +func (s *AssessmentCorrectiveResult) SetNextSteps(val []AssessmentNextStep) { + s.NextSteps = val +} + +// SetDecidedAt sets the value of DecidedAt. +func (s *AssessmentCorrectiveResult) SetDecidedAt(val Timestamp) { + s.DecidedAt = val +} + +// Merged schema. +type AssessmentCorrectiveResultKind string + +const ( + AssessmentCorrectiveResultKindCorrective AssessmentCorrectiveResultKind = "corrective" +) + +// AllValues returns all AssessmentCorrectiveResultKind values. +func (AssessmentCorrectiveResultKind) AllValues() []AssessmentCorrectiveResultKind { + return []AssessmentCorrectiveResultKind{ + AssessmentCorrectiveResultKindCorrective, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s AssessmentCorrectiveResultKind) MarshalText() ([]byte, error) { + switch s { + case AssessmentCorrectiveResultKindCorrective: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *AssessmentCorrectiveResultKind) UnmarshalText(data []byte) error { + switch AssessmentCorrectiveResultKind(data) { + case AssessmentCorrectiveResultKindCorrective: + *s = AssessmentCorrectiveResultKindCorrective + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +type AssessmentCorrectiveResultMode string + +const ( + AssessmentCorrectiveResultModeDemoBasic AssessmentCorrectiveResultMode = "demo_basic" + AssessmentCorrectiveResultModeAdaptive AssessmentCorrectiveResultMode = "adaptive" +) + +// AllValues returns all AssessmentCorrectiveResultMode values. +func (AssessmentCorrectiveResultMode) AllValues() []AssessmentCorrectiveResultMode { + return []AssessmentCorrectiveResultMode{ + AssessmentCorrectiveResultModeDemoBasic, + AssessmentCorrectiveResultModeAdaptive, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s AssessmentCorrectiveResultMode) MarshalText() ([]byte, error) { + switch s { + case AssessmentCorrectiveResultModeDemoBasic: + return []byte(s), nil + case AssessmentCorrectiveResultModeAdaptive: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *AssessmentCorrectiveResultMode) UnmarshalText(data []byte) error { + switch AssessmentCorrectiveResultMode(data) { + case AssessmentCorrectiveResultModeDemoBasic: + *s = AssessmentCorrectiveResultModeDemoBasic + return nil + case AssessmentCorrectiveResultModeAdaptive: + *s = AssessmentCorrectiveResultModeAdaptive + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + // Working time recorded by the server. It is a separate label: it never enters the ability estimate or // the grade decision. // Ref: #/components/schemas/AssessmentDurations @@ -965,6 +1702,772 @@ func (s *AssessmentDurations) SetPracticeSeconds(val NilInt32) { s.PracticeSeconds = val } +// Merged schema. +// Ref: #/components/schemas/AssessmentExpressAttempt +type AssessmentExpressAttempt struct { + // Attempt identifier. + ID uuid.UUID `json:"id"` + Version AssessmentAttemptVersion `json:"version"` + // Merged property. + Specialization NilSpecializationCode `json:"specialization"` + // Merged property. + TargetGrade NilGradeCode `json:"target_grade"` + // Merged property. + TaskLanguage NilTaskLanguage `json:"task_language"` + // Merged property. + Kind AssessmentExpressAttemptKind `json:"kind"` + // Merged property. + RootAttemptID NilUUID `json:"root_attempt_id"` + // Merged property. + ChainDeadline NilTimestamp `json:"chain_deadline"` + // Merged property. + Mode AssessmentExpressAttemptMode `json:"mode"` + State AssessmentAttemptState `json:"state"` + Versions AssessmentVersions `json:"versions"` + StartedAt Timestamp `json:"started_at"` + // Server deadline. For demo_express it is 180 to 300 seconds after started_at; for a corrective + // assessment it does not exceed chain_deadline. + ExpiresAt Timestamp `json:"expires_at"` + // Session limit of the attempt, or null when its policy defines none. + Sessions NilAssessmentSessions `json:"sessions"` + // Time the attempt reached a terminal state, or null while it is active. + FinishedAt NilTimestamp `json:"finished_at"` + Progress AssessmentProgress `json:"progress"` + // Item to answer now: a test item in `in_progress`, the practice item to submit in `practice_pending` + // or `additional_practice_pending` while that practice is `not_started` or `failed`, and null + // 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"` +} + +// GetID returns the value of ID. +func (s *AssessmentExpressAttempt) GetID() uuid.UUID { + return s.ID +} + +// GetVersion returns the value of Version. +func (s *AssessmentExpressAttempt) GetVersion() AssessmentAttemptVersion { + return s.Version +} + +// GetSpecialization returns the value of Specialization. +func (s *AssessmentExpressAttempt) GetSpecialization() NilSpecializationCode { + return s.Specialization +} + +// GetTargetGrade returns the value of TargetGrade. +func (s *AssessmentExpressAttempt) GetTargetGrade() NilGradeCode { + return s.TargetGrade +} + +// GetTaskLanguage returns the value of TaskLanguage. +func (s *AssessmentExpressAttempt) GetTaskLanguage() NilTaskLanguage { + return s.TaskLanguage +} + +// GetKind returns the value of Kind. +func (s *AssessmentExpressAttempt) GetKind() AssessmentExpressAttemptKind { + return s.Kind +} + +// GetRootAttemptID returns the value of RootAttemptID. +func (s *AssessmentExpressAttempt) GetRootAttemptID() NilUUID { + return s.RootAttemptID +} + +// GetChainDeadline returns the value of ChainDeadline. +func (s *AssessmentExpressAttempt) GetChainDeadline() NilTimestamp { + return s.ChainDeadline +} + +// GetMode returns the value of Mode. +func (s *AssessmentExpressAttempt) GetMode() AssessmentExpressAttemptMode { + return s.Mode +} + +// GetState returns the value of State. +func (s *AssessmentExpressAttempt) GetState() AssessmentAttemptState { + return s.State +} + +// GetVersions returns the value of Versions. +func (s *AssessmentExpressAttempt) GetVersions() AssessmentVersions { + return s.Versions +} + +// GetStartedAt returns the value of StartedAt. +func (s *AssessmentExpressAttempt) GetStartedAt() Timestamp { + return s.StartedAt +} + +// GetExpiresAt returns the value of ExpiresAt. +func (s *AssessmentExpressAttempt) GetExpiresAt() Timestamp { + return s.ExpiresAt +} + +// GetSessions returns the value of Sessions. +func (s *AssessmentExpressAttempt) GetSessions() NilAssessmentSessions { + return s.Sessions +} + +// GetFinishedAt returns the value of FinishedAt. +func (s *AssessmentExpressAttempt) GetFinishedAt() NilTimestamp { + return s.FinishedAt +} + +// GetProgress returns the value of Progress. +func (s *AssessmentExpressAttempt) GetProgress() AssessmentProgress { + return s.Progress +} + +// GetCurrentItem returns the value of CurrentItem. +func (s *AssessmentExpressAttempt) GetCurrentItem() NilAssessmentItem { + return s.CurrentItem +} + +// GetPractices returns the value of Practices. +func (s *AssessmentExpressAttempt) GetPractices() []AssessmentPractice { + return s.Practices +} + +// SetID sets the value of ID. +func (s *AssessmentExpressAttempt) SetID(val uuid.UUID) { + s.ID = val +} + +// SetVersion sets the value of Version. +func (s *AssessmentExpressAttempt) SetVersion(val AssessmentAttemptVersion) { + s.Version = val +} + +// SetSpecialization sets the value of Specialization. +func (s *AssessmentExpressAttempt) SetSpecialization(val NilSpecializationCode) { + s.Specialization = val +} + +// SetTargetGrade sets the value of TargetGrade. +func (s *AssessmentExpressAttempt) SetTargetGrade(val NilGradeCode) { + s.TargetGrade = val +} + +// SetTaskLanguage sets the value of TaskLanguage. +func (s *AssessmentExpressAttempt) SetTaskLanguage(val NilTaskLanguage) { + s.TaskLanguage = val +} + +// SetKind sets the value of Kind. +func (s *AssessmentExpressAttempt) SetKind(val AssessmentExpressAttemptKind) { + s.Kind = val +} + +// SetRootAttemptID sets the value of RootAttemptID. +func (s *AssessmentExpressAttempt) SetRootAttemptID(val NilUUID) { + s.RootAttemptID = val +} + +// SetChainDeadline sets the value of ChainDeadline. +func (s *AssessmentExpressAttempt) SetChainDeadline(val NilTimestamp) { + s.ChainDeadline = val +} + +// SetMode sets the value of Mode. +func (s *AssessmentExpressAttempt) SetMode(val AssessmentExpressAttemptMode) { + s.Mode = val +} + +// SetState sets the value of State. +func (s *AssessmentExpressAttempt) SetState(val AssessmentAttemptState) { + s.State = val +} + +// SetVersions sets the value of Versions. +func (s *AssessmentExpressAttempt) SetVersions(val AssessmentVersions) { + s.Versions = val +} + +// SetStartedAt sets the value of StartedAt. +func (s *AssessmentExpressAttempt) SetStartedAt(val Timestamp) { + s.StartedAt = val +} + +// SetExpiresAt sets the value of ExpiresAt. +func (s *AssessmentExpressAttempt) SetExpiresAt(val Timestamp) { + s.ExpiresAt = val +} + +// SetSessions sets the value of Sessions. +func (s *AssessmentExpressAttempt) SetSessions(val NilAssessmentSessions) { + s.Sessions = val +} + +// SetFinishedAt sets the value of FinishedAt. +func (s *AssessmentExpressAttempt) SetFinishedAt(val NilTimestamp) { + s.FinishedAt = val +} + +// SetProgress sets the value of Progress. +func (s *AssessmentExpressAttempt) SetProgress(val AssessmentProgress) { + s.Progress = val +} + +// SetCurrentItem sets the value of CurrentItem. +func (s *AssessmentExpressAttempt) SetCurrentItem(val NilAssessmentItem) { + s.CurrentItem = val +} + +// SetPractices sets the value of Practices. +func (s *AssessmentExpressAttempt) SetPractices(val []AssessmentPractice) { + s.Practices = 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 +type AssessmentExpressAttemptCreate struct { + // Explicitly request the training run; real modes cannot be selected by the client. + Kind AssessmentExpressAttemptCreateKind `json:"kind"` +} + +// GetKind returns the value of Kind. +func (s *AssessmentExpressAttemptCreate) GetKind() AssessmentExpressAttemptCreateKind { + return s.Kind +} + +// SetKind sets the value of Kind. +func (s *AssessmentExpressAttemptCreate) SetKind(val AssessmentExpressAttemptCreateKind) { + s.Kind = val +} + +// Explicitly request the training run; real modes cannot be selected by the client. +type AssessmentExpressAttemptCreateKind string + +const ( + AssessmentExpressAttemptCreateKindDemoExpress AssessmentExpressAttemptCreateKind = "demo_express" +) + +// AllValues returns all AssessmentExpressAttemptCreateKind values. +func (AssessmentExpressAttemptCreateKind) AllValues() []AssessmentExpressAttemptCreateKind { + return []AssessmentExpressAttemptCreateKind{ + AssessmentExpressAttemptCreateKindDemoExpress, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s AssessmentExpressAttemptCreateKind) MarshalText() ([]byte, error) { + switch s { + case AssessmentExpressAttemptCreateKindDemoExpress: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *AssessmentExpressAttemptCreateKind) UnmarshalText(data []byte) error { + switch AssessmentExpressAttemptCreateKind(data) { + case AssessmentExpressAttemptCreateKindDemoExpress: + *s = AssessmentExpressAttemptCreateKindDemoExpress + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Merged schema. +type AssessmentExpressAttemptKind string + +const ( + AssessmentExpressAttemptKindDemoExpress AssessmentExpressAttemptKind = "demo_express" +) + +// AllValues returns all AssessmentExpressAttemptKind values. +func (AssessmentExpressAttemptKind) AllValues() []AssessmentExpressAttemptKind { + return []AssessmentExpressAttemptKind{ + AssessmentExpressAttemptKindDemoExpress, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s AssessmentExpressAttemptKind) MarshalText() ([]byte, error) { + switch s { + case AssessmentExpressAttemptKindDemoExpress: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *AssessmentExpressAttemptKind) UnmarshalText(data []byte) error { + switch AssessmentExpressAttemptKind(data) { + case AssessmentExpressAttemptKindDemoExpress: + *s = AssessmentExpressAttemptKindDemoExpress + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Merged schema. +type AssessmentExpressAttemptMode string + +const ( + AssessmentExpressAttemptModeDemoExpress AssessmentExpressAttemptMode = "demo_express" +) + +// AllValues returns all AssessmentExpressAttemptMode values. +func (AssessmentExpressAttemptMode) AllValues() []AssessmentExpressAttemptMode { + return []AssessmentExpressAttemptMode{ + AssessmentExpressAttemptModeDemoExpress, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s AssessmentExpressAttemptMode) MarshalText() ([]byte, error) { + switch s { + case AssessmentExpressAttemptModeDemoExpress: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *AssessmentExpressAttemptMode) UnmarshalText(data []byte) error { + switch AssessmentExpressAttemptMode(data) { + case AssessmentExpressAttemptModeDemoExpress: + *s = AssessmentExpressAttemptModeDemoExpress + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Immutable educational result of a demo_express run. It includes a short summary but cannot report a +// category, percentile, uncertainty, grade, strength, or qualification evidence. The result belongs +// only to the training mode and does not consume a real-assessment quota. +// Ref: #/components/schemas/AssessmentExpressResult +type AssessmentExpressResult struct { + AttemptID uuid.UUID `json:"attempt_id"` + // Express training does not assess a specialization. + Specialization struct{} `json:"specialization"` + // Express training does not assess a target grade. + TargetGrade struct{} `json:"target_grade"` + TaskLanguage struct{} `json:"task_language"` + Kind AssessmentExpressResultKind `json:"kind"` + Mode AssessmentExpressResultMode `json:"mode"` + Versions AssessmentVersions `json:"versions"` + Outcome AssessmentExpressResultOutcome `json:"outcome"` + NotDeterminedReason struct{} `json:"not_determined_reason"` + // Express training never confirms a grade. + ConfirmedGrade struct{} `json:"confirmed_grade"` + PreviousConfirmedGrade struct{} `json:"previous_confirmed_grade"` + Strength struct{} `json:"strength"` + CalibrationStatus AssessmentExpressResultCalibrationStatus `json:"calibration_status"` + Limitations []AssessmentExpressResultLimitationsItem `json:"limitations"` + // Express training computes no ability estimate or percentile. + Uncertainty struct{} `json:"uncertainty"` + BasicScore struct{} `json:"basic_score"` + Practices []AssessmentPracticeResult `json:"practices"` + Gaps []AssessmentGap `json:"gaps"` + Durations AssessmentDurations `json:"durations"` + NextSteps []AssessmentNextStep `json:"next_steps"` + // Short educational feedback about this training run. + Summary string `json:"summary"` + DecidedAt Timestamp `json:"decided_at"` +} + +// GetAttemptID returns the value of AttemptID. +func (s *AssessmentExpressResult) GetAttemptID() uuid.UUID { + return s.AttemptID +} + +// GetSpecialization returns the value of Specialization. +func (s *AssessmentExpressResult) GetSpecialization() struct{} { + return s.Specialization +} + +// GetTargetGrade returns the value of TargetGrade. +func (s *AssessmentExpressResult) GetTargetGrade() struct{} { + return s.TargetGrade +} + +// GetTaskLanguage returns the value of TaskLanguage. +func (s *AssessmentExpressResult) GetTaskLanguage() struct{} { + return s.TaskLanguage +} + +// GetKind returns the value of Kind. +func (s *AssessmentExpressResult) GetKind() AssessmentExpressResultKind { + return s.Kind +} + +// GetMode returns the value of Mode. +func (s *AssessmentExpressResult) GetMode() AssessmentExpressResultMode { + return s.Mode +} + +// GetVersions returns the value of Versions. +func (s *AssessmentExpressResult) GetVersions() AssessmentVersions { + return s.Versions +} + +// GetOutcome returns the value of Outcome. +func (s *AssessmentExpressResult) GetOutcome() AssessmentExpressResultOutcome { + return s.Outcome +} + +// GetNotDeterminedReason returns the value of NotDeterminedReason. +func (s *AssessmentExpressResult) GetNotDeterminedReason() struct{} { + return s.NotDeterminedReason +} + +// GetConfirmedGrade returns the value of ConfirmedGrade. +func (s *AssessmentExpressResult) GetConfirmedGrade() struct{} { + return s.ConfirmedGrade +} + +// GetPreviousConfirmedGrade returns the value of PreviousConfirmedGrade. +func (s *AssessmentExpressResult) GetPreviousConfirmedGrade() struct{} { + return s.PreviousConfirmedGrade +} + +// GetStrength returns the value of Strength. +func (s *AssessmentExpressResult) GetStrength() struct{} { + return s.Strength +} + +// GetCalibrationStatus returns the value of CalibrationStatus. +func (s *AssessmentExpressResult) GetCalibrationStatus() AssessmentExpressResultCalibrationStatus { + return s.CalibrationStatus +} + +// GetLimitations returns the value of Limitations. +func (s *AssessmentExpressResult) GetLimitations() []AssessmentExpressResultLimitationsItem { + return s.Limitations +} + +// GetUncertainty returns the value of Uncertainty. +func (s *AssessmentExpressResult) GetUncertainty() struct{} { + return s.Uncertainty +} + +// GetBasicScore returns the value of BasicScore. +func (s *AssessmentExpressResult) GetBasicScore() struct{} { + return s.BasicScore +} + +// GetPractices returns the value of Practices. +func (s *AssessmentExpressResult) GetPractices() []AssessmentPracticeResult { + return s.Practices +} + +// GetGaps returns the value of Gaps. +func (s *AssessmentExpressResult) GetGaps() []AssessmentGap { + return s.Gaps +} + +// GetDurations returns the value of Durations. +func (s *AssessmentExpressResult) GetDurations() AssessmentDurations { + return s.Durations +} + +// GetNextSteps returns the value of NextSteps. +func (s *AssessmentExpressResult) GetNextSteps() []AssessmentNextStep { + return s.NextSteps +} + +// GetSummary returns the value of Summary. +func (s *AssessmentExpressResult) GetSummary() string { + return s.Summary +} + +// GetDecidedAt returns the value of DecidedAt. +func (s *AssessmentExpressResult) GetDecidedAt() Timestamp { + return s.DecidedAt +} + +// SetAttemptID sets the value of AttemptID. +func (s *AssessmentExpressResult) SetAttemptID(val uuid.UUID) { + s.AttemptID = val +} + +// SetSpecialization sets the value of Specialization. +func (s *AssessmentExpressResult) SetSpecialization(val struct{}) { + s.Specialization = val +} + +// SetTargetGrade sets the value of TargetGrade. +func (s *AssessmentExpressResult) SetTargetGrade(val struct{}) { + s.TargetGrade = val +} + +// SetTaskLanguage sets the value of TaskLanguage. +func (s *AssessmentExpressResult) SetTaskLanguage(val struct{}) { + s.TaskLanguage = val +} + +// SetKind sets the value of Kind. +func (s *AssessmentExpressResult) SetKind(val AssessmentExpressResultKind) { + s.Kind = val +} + +// SetMode sets the value of Mode. +func (s *AssessmentExpressResult) SetMode(val AssessmentExpressResultMode) { + s.Mode = val +} + +// SetVersions sets the value of Versions. +func (s *AssessmentExpressResult) SetVersions(val AssessmentVersions) { + s.Versions = val +} + +// SetOutcome sets the value of Outcome. +func (s *AssessmentExpressResult) SetOutcome(val AssessmentExpressResultOutcome) { + s.Outcome = val +} + +// SetNotDeterminedReason sets the value of NotDeterminedReason. +func (s *AssessmentExpressResult) SetNotDeterminedReason(val struct{}) { + s.NotDeterminedReason = val +} + +// SetConfirmedGrade sets the value of ConfirmedGrade. +func (s *AssessmentExpressResult) SetConfirmedGrade(val struct{}) { + s.ConfirmedGrade = val +} + +// SetPreviousConfirmedGrade sets the value of PreviousConfirmedGrade. +func (s *AssessmentExpressResult) SetPreviousConfirmedGrade(val struct{}) { + s.PreviousConfirmedGrade = val +} + +// SetStrength sets the value of Strength. +func (s *AssessmentExpressResult) SetStrength(val struct{}) { + s.Strength = val +} + +// SetCalibrationStatus sets the value of CalibrationStatus. +func (s *AssessmentExpressResult) SetCalibrationStatus(val AssessmentExpressResultCalibrationStatus) { + s.CalibrationStatus = val +} + +// SetLimitations sets the value of Limitations. +func (s *AssessmentExpressResult) SetLimitations(val []AssessmentExpressResultLimitationsItem) { + s.Limitations = val +} + +// SetUncertainty sets the value of Uncertainty. +func (s *AssessmentExpressResult) SetUncertainty(val struct{}) { + s.Uncertainty = val +} + +// SetBasicScore sets the value of BasicScore. +func (s *AssessmentExpressResult) SetBasicScore(val struct{}) { + s.BasicScore = val +} + +// SetPractices sets the value of Practices. +func (s *AssessmentExpressResult) SetPractices(val []AssessmentPracticeResult) { + s.Practices = val +} + +// SetGaps sets the value of Gaps. +func (s *AssessmentExpressResult) SetGaps(val []AssessmentGap) { + s.Gaps = val +} + +// SetDurations sets the value of Durations. +func (s *AssessmentExpressResult) SetDurations(val AssessmentDurations) { + s.Durations = val +} + +// SetNextSteps sets the value of NextSteps. +func (s *AssessmentExpressResult) SetNextSteps(val []AssessmentNextStep) { + s.NextSteps = val +} + +// SetSummary sets the value of Summary. +func (s *AssessmentExpressResult) SetSummary(val string) { + s.Summary = val +} + +// SetDecidedAt sets the value of DecidedAt. +func (s *AssessmentExpressResult) SetDecidedAt(val Timestamp) { + s.DecidedAt = val +} + +type AssessmentExpressResultCalibrationStatus string + +const ( + AssessmentExpressResultCalibrationStatusUncalibrated AssessmentExpressResultCalibrationStatus = "uncalibrated" +) + +// AllValues returns all AssessmentExpressResultCalibrationStatus values. +func (AssessmentExpressResultCalibrationStatus) AllValues() []AssessmentExpressResultCalibrationStatus { + return []AssessmentExpressResultCalibrationStatus{ + AssessmentExpressResultCalibrationStatusUncalibrated, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s AssessmentExpressResultCalibrationStatus) MarshalText() ([]byte, error) { + switch s { + case AssessmentExpressResultCalibrationStatusUncalibrated: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *AssessmentExpressResultCalibrationStatus) UnmarshalText(data []byte) error { + switch AssessmentExpressResultCalibrationStatus(data) { + case AssessmentExpressResultCalibrationStatusUncalibrated: + *s = AssessmentExpressResultCalibrationStatusUncalibrated + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +type AssessmentExpressResultKind string + +const ( + AssessmentExpressResultKindDemoExpress AssessmentExpressResultKind = "demo_express" +) + +// AllValues returns all AssessmentExpressResultKind values. +func (AssessmentExpressResultKind) AllValues() []AssessmentExpressResultKind { + return []AssessmentExpressResultKind{ + AssessmentExpressResultKindDemoExpress, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s AssessmentExpressResultKind) MarshalText() ([]byte, error) { + switch s { + case AssessmentExpressResultKindDemoExpress: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *AssessmentExpressResultKind) UnmarshalText(data []byte) error { + switch AssessmentExpressResultKind(data) { + case AssessmentExpressResultKindDemoExpress: + *s = AssessmentExpressResultKindDemoExpress + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +type AssessmentExpressResultLimitationsItem string + +const ( + AssessmentExpressResultLimitationsItemDemonstrationOnly AssessmentExpressResultLimitationsItem = "demonstration_only" +) + +// AllValues returns all AssessmentExpressResultLimitationsItem values. +func (AssessmentExpressResultLimitationsItem) AllValues() []AssessmentExpressResultLimitationsItem { + return []AssessmentExpressResultLimitationsItem{ + AssessmentExpressResultLimitationsItemDemonstrationOnly, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s AssessmentExpressResultLimitationsItem) MarshalText() ([]byte, error) { + switch s { + case AssessmentExpressResultLimitationsItemDemonstrationOnly: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *AssessmentExpressResultLimitationsItem) UnmarshalText(data []byte) error { + switch AssessmentExpressResultLimitationsItem(data) { + case AssessmentExpressResultLimitationsItemDemonstrationOnly: + *s = AssessmentExpressResultLimitationsItemDemonstrationOnly + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +type AssessmentExpressResultMode string + +const ( + AssessmentExpressResultModeDemoExpress AssessmentExpressResultMode = "demo_express" +) + +// AllValues returns all AssessmentExpressResultMode values. +func (AssessmentExpressResultMode) AllValues() []AssessmentExpressResultMode { + return []AssessmentExpressResultMode{ + AssessmentExpressResultModeDemoExpress, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s AssessmentExpressResultMode) MarshalText() ([]byte, error) { + switch s { + case AssessmentExpressResultModeDemoExpress: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *AssessmentExpressResultMode) UnmarshalText(data []byte) error { + switch AssessmentExpressResultMode(data) { + case AssessmentExpressResultModeDemoExpress: + *s = AssessmentExpressResultModeDemoExpress + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +type AssessmentExpressResultOutcome string + +const ( + AssessmentExpressResultOutcomeDemonstration AssessmentExpressResultOutcome = "demonstration" +) + +// AllValues returns all AssessmentExpressResultOutcome values. +func (AssessmentExpressResultOutcome) AllValues() []AssessmentExpressResultOutcome { + return []AssessmentExpressResultOutcome{ + AssessmentExpressResultOutcomeDemonstration, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s AssessmentExpressResultOutcome) MarshalText() ([]byte, error) { + switch s { + case AssessmentExpressResultOutcomeDemonstration: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *AssessmentExpressResultOutcome) UnmarshalText(data []byte) error { + switch AssessmentExpressResultOutcome(data) { + case AssessmentExpressResultOutcomeDemonstration: + *s = AssessmentExpressResultOutcomeDemonstration + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + // Command to finalize the attempt. // Ref: #/components/schemas/AssessmentFinalization type AssessmentFinalization struct { @@ -1017,8 +2520,9 @@ func (s *AssessmentGap) SetTitle(val string) { type AssessmentGradeAvailability struct { Grade GradeCode `json:"grade"` Status AssessmentGradeAvailabilityStatus `json:"status"` - // Mode that an attempt would use, or null when the status is `insufficient_bank`. - Mode NilAssessmentMode `json:"mode"` + // Real-assessment mode that the server would use, or null when the status is `insufficient_bank`. + // `demo_express` is not a category assessment and is never returned here. + Mode NilAssessmentRealMode `json:"mode"` // When the status is `cooldown`, the first time the attempt can start; otherwise null. AvailableAt NilTimestamp `json:"available_at"` // Time from the start to `expires_at`. @@ -1042,7 +2546,7 @@ func (s *AssessmentGradeAvailability) GetStatus() AssessmentGradeAvailabilitySta } // GetMode returns the value of Mode. -func (s *AssessmentGradeAvailability) GetMode() NilAssessmentMode { +func (s *AssessmentGradeAvailability) GetMode() NilAssessmentRealMode { return s.Mode } @@ -1082,7 +2586,7 @@ func (s *AssessmentGradeAvailability) SetStatus(val AssessmentGradeAvailabilityS } // SetMode sets the value of Mode. -func (s *AssessmentGradeAvailability) SetMode(val NilAssessmentMode) { +func (s *AssessmentGradeAvailability) SetMode(val NilAssessmentRealMode) { s.Mode = val } @@ -1260,14 +2764,14 @@ func (s *AssessmentItem) SetContent(val ItemContent) { type AssessmentItemId uuid.UUID -// Known limitation of the method behind a result, shown with the result. +// Known limitation of the method behind a real-assessment result, shown with the result. // // - uncalibrated_thresholds: the thresholds are not yet validated on a pilot. // - demo_bank: the result comes from the small reviewed demo bank. // - practice_not_included: the attempt had no code practice because the sandbox was not enabled. -// - unproctored: the attempt was taken online without supervision. +// - unproctored: the attempt was taken online without supervision. Adding a value is a contract +// change. // -// Adding a value is a contract change. // Ref: #/components/schemas/AssessmentLimitation type AssessmentLimitation string @@ -1324,60 +2828,6 @@ func (s *AssessmentLimitation) UnmarshalText(data []byte) error { } } -// Measurement method of an attempt. The server selects it from the published task bank of the -// category; the client never chooses it. -// -// - demo_basic: a fixed form of reviewed demo items scored by their keys against the pass mark of the -// versioned basic grading policy. It computes no ability estimate, standard error, or probability, -// so every uncertainty field of its result is null, its thresholds are uncalibrated, and its -// decision is binary: it never offers an additional practice. -// - adaptive: the adaptive test on task families with an ability estimate, its standard error, and -// the probability of reaching the grade threshold, as the versioned assessment policy defines them. -// A probability in the band below confirmation offers one additional practice in the same attempt. -// -// Adding a value is a contract change. -// Ref: #/components/schemas/AssessmentMode -type AssessmentMode string - -const ( - AssessmentModeDemoBasic AssessmentMode = "demo_basic" - AssessmentModeAdaptive AssessmentMode = "adaptive" -) - -// AllValues returns all AssessmentMode values. -func (AssessmentMode) AllValues() []AssessmentMode { - return []AssessmentMode{ - AssessmentModeDemoBasic, - AssessmentModeAdaptive, - } -} - -// MarshalText implements encoding.TextMarshaler. -func (s AssessmentMode) MarshalText() ([]byte, error) { - switch s { - case AssessmentModeDemoBasic: - return []byte(s), nil - case AssessmentModeAdaptive: - return []byte(s), nil - default: - return nil, errors.Errorf("invalid value: %q", s) - } -} - -// UnmarshalText implements encoding.TextUnmarshaler. -func (s *AssessmentMode) UnmarshalText(data []byte) error { - switch AssessmentMode(data) { - case AssessmentModeDemoBasic: - *s = AssessmentModeDemoBasic - return nil - case AssessmentModeAdaptive: - *s = AssessmentModeAdaptive - return nil - default: - return errors.Errorf("invalid value: %q", data) - } -} - // Step that the candidate may take next. // // - retake_same_grade: test the same grade again from `available_at`. @@ -1484,17 +2934,21 @@ func (s *AssessmentNextStep) SetAvailableAt(val NilTimestamp) { s.AvailableAt = val } -// Why an attempt gives no decision, and whether it counts against the retry rules. +// Why an attempt gives no decision. One root quota slot is reserved when a real root attempt starts; +// corrective checks in its chain do not reserve another slot. // -// - expired: the time or session limit passed before the candidate finished the item part. It is the -// candidate's attempt: it counts toward the attempt limit and starts the same-grade retry interval. +// - expired: the time or session limit passed before the candidate finished the item part. Retry +// timing follows the recorded policy; a correction uses the existing root slot and does not reset +// the chain deadline or 30/90-day timers. // - practice_incomplete: the item part was done, but the candidate did not submit the main practice -// before the limit. It counts like `expired`. -// - insufficient_bank: the bank could not supply the required coverage within the limit. It is a -// platform limitation: it never counts toward the attempt limit and starts no retry interval. +// before the limit. Retry timing follows the recorded policy; a correction uses the existing root +// slot and does not reset the chain deadline or 30/90-day timers. +// - insufficient_bank: the bank could not supply required coverage. A preflight refusal creates no +// attempt or root slot; a bank failure in an existing chain does not create a free new chain or +// another root slot. // - sandbox_unavailable: the latest submission of a required or additional practice ended `failed` // because of the sandbox infrastructure, and the limit passed before a verdict. It is a platform -// fault: it never counts toward the attempt limit and starts no retry interval. +// fault and does not create a new root slot or a free chain. // // Ref: #/components/schemas/AssessmentNotDeterminedReason type AssessmentNotDeterminedReason string @@ -1775,20 +3229,407 @@ func (s *AssessmentProgress) SetMaxItems(val int32) { s.MaxItems = val } -// Immutable result of a terminal attempt, visible only to its candidate. It records the method, the -// versions, the decision, its uncertainty, and its limitations; a later policy, bank, or algorithm -// version never changes it. It never contains answers, per-item correctness, answer keys, seeds, -// hidden checks, or anti-cheat signals. Fields that the method does not compute are null, never zero: -// demo_basic has null `uncertainty` and `strength`, and adaptive has null `basic_score`. -// Ref: #/components/schemas/AssessmentResult -type AssessmentResult struct { +// Merged schema. +// Ref: #/components/schemas/AssessmentQualifiedAttempt +type AssessmentQualifiedAttempt struct { + // Attempt identifier. + ID uuid.UUID `json:"id"` + Version AssessmentAttemptVersion `json:"version"` + // Merged property. + Specialization NilSpecializationCode `json:"specialization"` + // Merged property. + TargetGrade NilGradeCode `json:"target_grade"` + // Task language of the attempt, or null when none is selected. + TaskLanguage NilTaskLanguage `json:"task_language"` + // Merged property. + Kind AssessmentQualifiedAttemptKind `json:"kind"` + // Merged property. + RootAttemptID NilUUID `json:"root_attempt_id"` + // Merged property. + ChainDeadline NilTimestamp `json:"chain_deadline"` + // Merged property. + Mode AssessmentQualifiedAttemptMode `json:"mode"` + State AssessmentAttemptState `json:"state"` + Versions AssessmentVersions `json:"versions"` + StartedAt Timestamp `json:"started_at"` + // Server deadline. For demo_express it is 180 to 300 seconds after started_at; for a corrective + // assessment it does not exceed chain_deadline. + ExpiresAt Timestamp `json:"expires_at"` + // Session limit of the attempt, or null when its policy defines none. + Sessions NilAssessmentSessions `json:"sessions"` + // Time the attempt reached a terminal state, or null while it is active. + FinishedAt NilTimestamp `json:"finished_at"` + Progress AssessmentProgress `json:"progress"` + // Item to answer now: a test item in `in_progress`, the practice item to submit in `practice_pending` + // or `additional_practice_pending` while that practice is `not_started` or `failed`, and null + // 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"` +} + +// GetID returns the value of ID. +func (s *AssessmentQualifiedAttempt) GetID() uuid.UUID { + return s.ID +} + +// GetVersion returns the value of Version. +func (s *AssessmentQualifiedAttempt) GetVersion() AssessmentAttemptVersion { + return s.Version +} + +// GetSpecialization returns the value of Specialization. +func (s *AssessmentQualifiedAttempt) GetSpecialization() NilSpecializationCode { + return s.Specialization +} + +// GetTargetGrade returns the value of TargetGrade. +func (s *AssessmentQualifiedAttempt) GetTargetGrade() NilGradeCode { + return s.TargetGrade +} + +// GetTaskLanguage returns the value of TaskLanguage. +func (s *AssessmentQualifiedAttempt) GetTaskLanguage() NilTaskLanguage { + return s.TaskLanguage +} + +// GetKind returns the value of Kind. +func (s *AssessmentQualifiedAttempt) GetKind() AssessmentQualifiedAttemptKind { + return s.Kind +} + +// GetRootAttemptID returns the value of RootAttemptID. +func (s *AssessmentQualifiedAttempt) GetRootAttemptID() NilUUID { + return s.RootAttemptID +} + +// GetChainDeadline returns the value of ChainDeadline. +func (s *AssessmentQualifiedAttempt) GetChainDeadline() NilTimestamp { + return s.ChainDeadline +} + +// GetMode returns the value of Mode. +func (s *AssessmentQualifiedAttempt) GetMode() AssessmentQualifiedAttemptMode { + return s.Mode +} + +// GetState returns the value of State. +func (s *AssessmentQualifiedAttempt) GetState() AssessmentAttemptState { + return s.State +} + +// GetVersions returns the value of Versions. +func (s *AssessmentQualifiedAttempt) GetVersions() AssessmentVersions { + return s.Versions +} + +// GetStartedAt returns the value of StartedAt. +func (s *AssessmentQualifiedAttempt) GetStartedAt() Timestamp { + return s.StartedAt +} + +// GetExpiresAt returns the value of ExpiresAt. +func (s *AssessmentQualifiedAttempt) GetExpiresAt() Timestamp { + return s.ExpiresAt +} + +// GetSessions returns the value of Sessions. +func (s *AssessmentQualifiedAttempt) GetSessions() NilAssessmentSessions { + return s.Sessions +} + +// GetFinishedAt returns the value of FinishedAt. +func (s *AssessmentQualifiedAttempt) GetFinishedAt() NilTimestamp { + return s.FinishedAt +} + +// GetProgress returns the value of Progress. +func (s *AssessmentQualifiedAttempt) GetProgress() AssessmentProgress { + return s.Progress +} + +// GetCurrentItem returns the value of CurrentItem. +func (s *AssessmentQualifiedAttempt) GetCurrentItem() NilAssessmentItem { + return s.CurrentItem +} + +// GetPractices returns the value of Practices. +func (s *AssessmentQualifiedAttempt) GetPractices() []AssessmentPractice { + return s.Practices +} + +// SetID sets the value of ID. +func (s *AssessmentQualifiedAttempt) SetID(val uuid.UUID) { + s.ID = val +} + +// SetVersion sets the value of Version. +func (s *AssessmentQualifiedAttempt) SetVersion(val AssessmentAttemptVersion) { + s.Version = val +} + +// SetSpecialization sets the value of Specialization. +func (s *AssessmentQualifiedAttempt) SetSpecialization(val NilSpecializationCode) { + s.Specialization = val +} + +// SetTargetGrade sets the value of TargetGrade. +func (s *AssessmentQualifiedAttempt) SetTargetGrade(val NilGradeCode) { + s.TargetGrade = val +} + +// SetTaskLanguage sets the value of TaskLanguage. +func (s *AssessmentQualifiedAttempt) SetTaskLanguage(val NilTaskLanguage) { + s.TaskLanguage = val +} + +// SetKind sets the value of Kind. +func (s *AssessmentQualifiedAttempt) SetKind(val AssessmentQualifiedAttemptKind) { + s.Kind = val +} + +// SetRootAttemptID sets the value of RootAttemptID. +func (s *AssessmentQualifiedAttempt) SetRootAttemptID(val NilUUID) { + s.RootAttemptID = val +} + +// SetChainDeadline sets the value of ChainDeadline. +func (s *AssessmentQualifiedAttempt) SetChainDeadline(val NilTimestamp) { + s.ChainDeadline = val +} + +// SetMode sets the value of Mode. +func (s *AssessmentQualifiedAttempt) SetMode(val AssessmentQualifiedAttemptMode) { + s.Mode = val +} + +// SetState sets the value of State. +func (s *AssessmentQualifiedAttempt) SetState(val AssessmentAttemptState) { + s.State = val +} + +// SetVersions sets the value of Versions. +func (s *AssessmentQualifiedAttempt) SetVersions(val AssessmentVersions) { + s.Versions = val +} + +// SetStartedAt sets the value of StartedAt. +func (s *AssessmentQualifiedAttempt) SetStartedAt(val Timestamp) { + s.StartedAt = val +} + +// SetExpiresAt sets the value of ExpiresAt. +func (s *AssessmentQualifiedAttempt) SetExpiresAt(val Timestamp) { + s.ExpiresAt = val +} + +// SetSessions sets the value of Sessions. +func (s *AssessmentQualifiedAttempt) SetSessions(val NilAssessmentSessions) { + s.Sessions = val +} + +// SetFinishedAt sets the value of FinishedAt. +func (s *AssessmentQualifiedAttempt) SetFinishedAt(val NilTimestamp) { + s.FinishedAt = val +} + +// SetProgress sets the value of Progress. +func (s *AssessmentQualifiedAttempt) SetProgress(val AssessmentProgress) { + s.Progress = val +} + +// SetCurrentItem sets the value of CurrentItem. +func (s *AssessmentQualifiedAttempt) SetCurrentItem(val NilAssessmentItem) { + s.CurrentItem = val +} + +// SetPractices sets the value of Practices. +func (s *AssessmentQualifiedAttempt) SetPractices(val []AssessmentPractice) { + s.Practices = 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. +// Ref: #/components/schemas/AssessmentQualifiedAttemptCreate +type AssessmentQualifiedAttemptCreate struct { + // Start a real-assessment chain and reserve one root quota slot. + Kind AssessmentQualifiedAttemptCreateKind `json:"kind"` + Specialization SpecializationCode `json:"specialization"` + TargetGrade GradeCode `json:"target_grade"` + // Task language of the attempt, one of the `task_languages` of the published bank, or null when the + // bank offers no choice of language. The questionnaire choice is the value the client offers first. + TaskLanguage NilTaskLanguage `json:"task_language"` +} + +// GetKind returns the value of Kind. +func (s *AssessmentQualifiedAttemptCreate) GetKind() AssessmentQualifiedAttemptCreateKind { + return s.Kind +} + +// GetSpecialization returns the value of Specialization. +func (s *AssessmentQualifiedAttemptCreate) GetSpecialization() SpecializationCode { + return s.Specialization +} + +// GetTargetGrade returns the value of TargetGrade. +func (s *AssessmentQualifiedAttemptCreate) GetTargetGrade() GradeCode { + return s.TargetGrade +} + +// GetTaskLanguage returns the value of TaskLanguage. +func (s *AssessmentQualifiedAttemptCreate) GetTaskLanguage() NilTaskLanguage { + return s.TaskLanguage +} + +// SetKind sets the value of Kind. +func (s *AssessmentQualifiedAttemptCreate) SetKind(val AssessmentQualifiedAttemptCreateKind) { + s.Kind = val +} + +// SetSpecialization sets the value of Specialization. +func (s *AssessmentQualifiedAttemptCreate) SetSpecialization(val SpecializationCode) { + s.Specialization = val +} + +// SetTargetGrade sets the value of TargetGrade. +func (s *AssessmentQualifiedAttemptCreate) SetTargetGrade(val GradeCode) { + s.TargetGrade = val +} + +// SetTaskLanguage sets the value of TaskLanguage. +func (s *AssessmentQualifiedAttemptCreate) SetTaskLanguage(val NilTaskLanguage) { + s.TaskLanguage = val +} + +// Start a real-assessment chain and reserve one root quota slot. +type AssessmentQualifiedAttemptCreateKind string + +const ( + AssessmentQualifiedAttemptCreateKindRoot AssessmentQualifiedAttemptCreateKind = "root" +) + +// AllValues returns all AssessmentQualifiedAttemptCreateKind values. +func (AssessmentQualifiedAttemptCreateKind) AllValues() []AssessmentQualifiedAttemptCreateKind { + return []AssessmentQualifiedAttemptCreateKind{ + AssessmentQualifiedAttemptCreateKindRoot, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s AssessmentQualifiedAttemptCreateKind) MarshalText() ([]byte, error) { + switch s { + case AssessmentQualifiedAttemptCreateKindRoot: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *AssessmentQualifiedAttemptCreateKind) UnmarshalText(data []byte) error { + switch AssessmentQualifiedAttemptCreateKind(data) { + case AssessmentQualifiedAttemptCreateKindRoot: + *s = AssessmentQualifiedAttemptCreateKindRoot + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Merged schema. +type AssessmentQualifiedAttemptKind string + +const ( + AssessmentQualifiedAttemptKindRoot AssessmentQualifiedAttemptKind = "root" +) + +// AllValues returns all AssessmentQualifiedAttemptKind values. +func (AssessmentQualifiedAttemptKind) AllValues() []AssessmentQualifiedAttemptKind { + return []AssessmentQualifiedAttemptKind{ + AssessmentQualifiedAttemptKindRoot, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s AssessmentQualifiedAttemptKind) MarshalText() ([]byte, error) { + switch s { + case AssessmentQualifiedAttemptKindRoot: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *AssessmentQualifiedAttemptKind) UnmarshalText(data []byte) error { + switch AssessmentQualifiedAttemptKind(data) { + case AssessmentQualifiedAttemptKindRoot: + *s = AssessmentQualifiedAttemptKindRoot + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Merged schema. +type AssessmentQualifiedAttemptMode string + +const ( + AssessmentQualifiedAttemptModeDemoBasic AssessmentQualifiedAttemptMode = "demo_basic" + AssessmentQualifiedAttemptModeAdaptive AssessmentQualifiedAttemptMode = "adaptive" +) + +// AllValues returns all AssessmentQualifiedAttemptMode values. +func (AssessmentQualifiedAttemptMode) AllValues() []AssessmentQualifiedAttemptMode { + return []AssessmentQualifiedAttemptMode{ + AssessmentQualifiedAttemptModeDemoBasic, + AssessmentQualifiedAttemptModeAdaptive, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s AssessmentQualifiedAttemptMode) MarshalText() ([]byte, error) { + switch s { + case AssessmentQualifiedAttemptModeDemoBasic: + return []byte(s), nil + case AssessmentQualifiedAttemptModeAdaptive: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *AssessmentQualifiedAttemptMode) UnmarshalText(data []byte) error { + switch AssessmentQualifiedAttemptMode(data) { + case AssessmentQualifiedAttemptModeDemoBasic: + *s = AssessmentQualifiedAttemptModeDemoBasic + return nil + case AssessmentQualifiedAttemptModeAdaptive: + *s = AssessmentQualifiedAttemptModeAdaptive + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Merged schema. +// Ref: #/components/schemas/AssessmentQualifiedResult +type AssessmentQualifiedResult struct { AttemptID uuid.UUID `json:"attempt_id"` Specialization SpecializationCode `json:"specialization"` TargetGrade GradeCode `json:"target_grade"` - TaskLanguage NilTaskLanguage `json:"task_language"` - Mode AssessmentMode `json:"mode"` - Versions AssessmentVersions `json:"versions"` - Outcome AssessmentOutcome `json:"outcome"` + // Merged property. + RootAttemptID NilUUID `json:"root_attempt_id"` + // Merged property. + ChainDeadline NilTimestamp `json:"chain_deadline"` + TaskLanguage NilTaskLanguage `json:"task_language"` + // Merged property. + Kind AssessmentQualifiedResultKind `json:"kind"` + Mode AssessmentQualifiedResultMode `json:"mode"` + Versions AssessmentVersions `json:"versions"` + Outcome AssessmentOutcome `json:"outcome"` // The reason when `outcome` is `not_determined`, otherwise null. NotDeterminedReason NilAssessmentNotDeterminedReason `json:"not_determined_reason"` // Grade that this attempt confirmed, the target grade, or null when it confirmed none. Together with @@ -1816,205 +3657,454 @@ type AssessmentResult struct { } // GetAttemptID returns the value of AttemptID. -func (s *AssessmentResult) GetAttemptID() uuid.UUID { +func (s *AssessmentQualifiedResult) GetAttemptID() uuid.UUID { return s.AttemptID } // GetSpecialization returns the value of Specialization. -func (s *AssessmentResult) GetSpecialization() SpecializationCode { +func (s *AssessmentQualifiedResult) GetSpecialization() SpecializationCode { return s.Specialization } // GetTargetGrade returns the value of TargetGrade. -func (s *AssessmentResult) GetTargetGrade() GradeCode { +func (s *AssessmentQualifiedResult) GetTargetGrade() GradeCode { return s.TargetGrade } +// GetRootAttemptID returns the value of RootAttemptID. +func (s *AssessmentQualifiedResult) GetRootAttemptID() NilUUID { + return s.RootAttemptID +} + +// GetChainDeadline returns the value of ChainDeadline. +func (s *AssessmentQualifiedResult) GetChainDeadline() NilTimestamp { + return s.ChainDeadline +} + // GetTaskLanguage returns the value of TaskLanguage. -func (s *AssessmentResult) GetTaskLanguage() NilTaskLanguage { +func (s *AssessmentQualifiedResult) GetTaskLanguage() NilTaskLanguage { return s.TaskLanguage } +// GetKind returns the value of Kind. +func (s *AssessmentQualifiedResult) GetKind() AssessmentQualifiedResultKind { + return s.Kind +} + // GetMode returns the value of Mode. -func (s *AssessmentResult) GetMode() AssessmentMode { +func (s *AssessmentQualifiedResult) GetMode() AssessmentQualifiedResultMode { return s.Mode } // GetVersions returns the value of Versions. -func (s *AssessmentResult) GetVersions() AssessmentVersions { +func (s *AssessmentQualifiedResult) GetVersions() AssessmentVersions { return s.Versions } // GetOutcome returns the value of Outcome. -func (s *AssessmentResult) GetOutcome() AssessmentOutcome { +func (s *AssessmentQualifiedResult) GetOutcome() AssessmentOutcome { return s.Outcome } // GetNotDeterminedReason returns the value of NotDeterminedReason. -func (s *AssessmentResult) GetNotDeterminedReason() NilAssessmentNotDeterminedReason { +func (s *AssessmentQualifiedResult) GetNotDeterminedReason() NilAssessmentNotDeterminedReason { return s.NotDeterminedReason } // GetConfirmedGrade returns the value of ConfirmedGrade. -func (s *AssessmentResult) GetConfirmedGrade() NilGradeCode { +func (s *AssessmentQualifiedResult) GetConfirmedGrade() NilGradeCode { return s.ConfirmedGrade } // GetPreviousConfirmedGrade returns the value of PreviousConfirmedGrade. -func (s *AssessmentResult) GetPreviousConfirmedGrade() NilGradeCode { +func (s *AssessmentQualifiedResult) GetPreviousConfirmedGrade() NilGradeCode { return s.PreviousConfirmedGrade } // GetStrength returns the value of Strength. -func (s *AssessmentResult) GetStrength() NilAssessmentStrength { +func (s *AssessmentQualifiedResult) GetStrength() NilAssessmentStrength { return s.Strength } // GetCalibrationStatus returns the value of CalibrationStatus. -func (s *AssessmentResult) GetCalibrationStatus() CalibrationStatus { +func (s *AssessmentQualifiedResult) GetCalibrationStatus() CalibrationStatus { return s.CalibrationStatus } // GetLimitations returns the value of Limitations. -func (s *AssessmentResult) GetLimitations() []AssessmentLimitation { +func (s *AssessmentQualifiedResult) GetLimitations() []AssessmentLimitation { return s.Limitations } // GetUncertainty returns the value of Uncertainty. -func (s *AssessmentResult) GetUncertainty() NilAssessmentUncertainty { +func (s *AssessmentQualifiedResult) GetUncertainty() NilAssessmentUncertainty { return s.Uncertainty } // GetBasicScore returns the value of BasicScore. -func (s *AssessmentResult) GetBasicScore() NilBasicScore { +func (s *AssessmentQualifiedResult) GetBasicScore() NilBasicScore { return s.BasicScore } // GetPractices returns the value of Practices. -func (s *AssessmentResult) GetPractices() []AssessmentPracticeResult { +func (s *AssessmentQualifiedResult) GetPractices() []AssessmentPracticeResult { return s.Practices } // GetGaps returns the value of Gaps. -func (s *AssessmentResult) GetGaps() []AssessmentGap { +func (s *AssessmentQualifiedResult) GetGaps() []AssessmentGap { return s.Gaps } // GetDurations returns the value of Durations. -func (s *AssessmentResult) GetDurations() AssessmentDurations { +func (s *AssessmentQualifiedResult) GetDurations() AssessmentDurations { return s.Durations } // GetNextSteps returns the value of NextSteps. -func (s *AssessmentResult) GetNextSteps() []AssessmentNextStep { +func (s *AssessmentQualifiedResult) GetNextSteps() []AssessmentNextStep { return s.NextSteps } // GetDecidedAt returns the value of DecidedAt. -func (s *AssessmentResult) GetDecidedAt() Timestamp { +func (s *AssessmentQualifiedResult) GetDecidedAt() Timestamp { return s.DecidedAt } // SetAttemptID sets the value of AttemptID. -func (s *AssessmentResult) SetAttemptID(val uuid.UUID) { +func (s *AssessmentQualifiedResult) SetAttemptID(val uuid.UUID) { s.AttemptID = val } // SetSpecialization sets the value of Specialization. -func (s *AssessmentResult) SetSpecialization(val SpecializationCode) { +func (s *AssessmentQualifiedResult) SetSpecialization(val SpecializationCode) { s.Specialization = val } // SetTargetGrade sets the value of TargetGrade. -func (s *AssessmentResult) SetTargetGrade(val GradeCode) { +func (s *AssessmentQualifiedResult) SetTargetGrade(val GradeCode) { s.TargetGrade = val } +// SetRootAttemptID sets the value of RootAttemptID. +func (s *AssessmentQualifiedResult) SetRootAttemptID(val NilUUID) { + s.RootAttemptID = val +} + +// SetChainDeadline sets the value of ChainDeadline. +func (s *AssessmentQualifiedResult) SetChainDeadline(val NilTimestamp) { + s.ChainDeadline = val +} + // SetTaskLanguage sets the value of TaskLanguage. -func (s *AssessmentResult) SetTaskLanguage(val NilTaskLanguage) { +func (s *AssessmentQualifiedResult) SetTaskLanguage(val NilTaskLanguage) { s.TaskLanguage = val } +// SetKind sets the value of Kind. +func (s *AssessmentQualifiedResult) SetKind(val AssessmentQualifiedResultKind) { + s.Kind = val +} + // SetMode sets the value of Mode. -func (s *AssessmentResult) SetMode(val AssessmentMode) { +func (s *AssessmentQualifiedResult) SetMode(val AssessmentQualifiedResultMode) { s.Mode = val } // SetVersions sets the value of Versions. -func (s *AssessmentResult) SetVersions(val AssessmentVersions) { +func (s *AssessmentQualifiedResult) SetVersions(val AssessmentVersions) { s.Versions = val } // SetOutcome sets the value of Outcome. -func (s *AssessmentResult) SetOutcome(val AssessmentOutcome) { +func (s *AssessmentQualifiedResult) SetOutcome(val AssessmentOutcome) { s.Outcome = val } // SetNotDeterminedReason sets the value of NotDeterminedReason. -func (s *AssessmentResult) SetNotDeterminedReason(val NilAssessmentNotDeterminedReason) { +func (s *AssessmentQualifiedResult) SetNotDeterminedReason(val NilAssessmentNotDeterminedReason) { s.NotDeterminedReason = val } // SetConfirmedGrade sets the value of ConfirmedGrade. -func (s *AssessmentResult) SetConfirmedGrade(val NilGradeCode) { +func (s *AssessmentQualifiedResult) SetConfirmedGrade(val NilGradeCode) { s.ConfirmedGrade = val } // SetPreviousConfirmedGrade sets the value of PreviousConfirmedGrade. -func (s *AssessmentResult) SetPreviousConfirmedGrade(val NilGradeCode) { +func (s *AssessmentQualifiedResult) SetPreviousConfirmedGrade(val NilGradeCode) { s.PreviousConfirmedGrade = val } // SetStrength sets the value of Strength. -func (s *AssessmentResult) SetStrength(val NilAssessmentStrength) { +func (s *AssessmentQualifiedResult) SetStrength(val NilAssessmentStrength) { s.Strength = val } // SetCalibrationStatus sets the value of CalibrationStatus. -func (s *AssessmentResult) SetCalibrationStatus(val CalibrationStatus) { +func (s *AssessmentQualifiedResult) SetCalibrationStatus(val CalibrationStatus) { s.CalibrationStatus = val } // SetLimitations sets the value of Limitations. -func (s *AssessmentResult) SetLimitations(val []AssessmentLimitation) { +func (s *AssessmentQualifiedResult) SetLimitations(val []AssessmentLimitation) { s.Limitations = val } // SetUncertainty sets the value of Uncertainty. -func (s *AssessmentResult) SetUncertainty(val NilAssessmentUncertainty) { +func (s *AssessmentQualifiedResult) SetUncertainty(val NilAssessmentUncertainty) { s.Uncertainty = val } // SetBasicScore sets the value of BasicScore. -func (s *AssessmentResult) SetBasicScore(val NilBasicScore) { +func (s *AssessmentQualifiedResult) SetBasicScore(val NilBasicScore) { s.BasicScore = val } // SetPractices sets the value of Practices. -func (s *AssessmentResult) SetPractices(val []AssessmentPracticeResult) { +func (s *AssessmentQualifiedResult) SetPractices(val []AssessmentPracticeResult) { s.Practices = val } // SetGaps sets the value of Gaps. -func (s *AssessmentResult) SetGaps(val []AssessmentGap) { +func (s *AssessmentQualifiedResult) SetGaps(val []AssessmentGap) { s.Gaps = val } // SetDurations sets the value of Durations. -func (s *AssessmentResult) SetDurations(val AssessmentDurations) { +func (s *AssessmentQualifiedResult) SetDurations(val AssessmentDurations) { s.Durations = val } // SetNextSteps sets the value of NextSteps. -func (s *AssessmentResult) SetNextSteps(val []AssessmentNextStep) { +func (s *AssessmentQualifiedResult) SetNextSteps(val []AssessmentNextStep) { s.NextSteps = val } // SetDecidedAt sets the value of DecidedAt. -func (s *AssessmentResult) SetDecidedAt(val Timestamp) { +func (s *AssessmentQualifiedResult) SetDecidedAt(val Timestamp) { s.DecidedAt = val } +// Merged schema. +type AssessmentQualifiedResultKind string + +const ( + AssessmentQualifiedResultKindRoot AssessmentQualifiedResultKind = "root" +) + +// AllValues returns all AssessmentQualifiedResultKind values. +func (AssessmentQualifiedResultKind) AllValues() []AssessmentQualifiedResultKind { + return []AssessmentQualifiedResultKind{ + AssessmentQualifiedResultKindRoot, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s AssessmentQualifiedResultKind) MarshalText() ([]byte, error) { + switch s { + case AssessmentQualifiedResultKindRoot: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *AssessmentQualifiedResultKind) UnmarshalText(data []byte) error { + switch AssessmentQualifiedResultKind(data) { + case AssessmentQualifiedResultKindRoot: + *s = AssessmentQualifiedResultKindRoot + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +type AssessmentQualifiedResultMode string + +const ( + AssessmentQualifiedResultModeDemoBasic AssessmentQualifiedResultMode = "demo_basic" + AssessmentQualifiedResultModeAdaptive AssessmentQualifiedResultMode = "adaptive" +) + +// AllValues returns all AssessmentQualifiedResultMode values. +func (AssessmentQualifiedResultMode) AllValues() []AssessmentQualifiedResultMode { + return []AssessmentQualifiedResultMode{ + AssessmentQualifiedResultModeDemoBasic, + AssessmentQualifiedResultModeAdaptive, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s AssessmentQualifiedResultMode) MarshalText() ([]byte, error) { + switch s { + case AssessmentQualifiedResultModeDemoBasic: + return []byte(s), nil + case AssessmentQualifiedResultModeAdaptive: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *AssessmentQualifiedResultMode) UnmarshalText(data []byte) error { + switch AssessmentQualifiedResultMode(data) { + case AssessmentQualifiedResultModeDemoBasic: + *s = AssessmentQualifiedResultModeDemoBasic + return nil + case AssessmentQualifiedResultModeAdaptive: + *s = AssessmentQualifiedResultModeAdaptive + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Server-selected mode available to a real category assessment. +// Ref: #/components/schemas/AssessmentRealMode +type AssessmentRealMode string + +const ( + AssessmentRealModeDemoBasic AssessmentRealMode = "demo_basic" + AssessmentRealModeAdaptive AssessmentRealMode = "adaptive" +) + +// AllValues returns all AssessmentRealMode values. +func (AssessmentRealMode) AllValues() []AssessmentRealMode { + return []AssessmentRealMode{ + AssessmentRealModeDemoBasic, + AssessmentRealModeAdaptive, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s AssessmentRealMode) MarshalText() ([]byte, error) { + switch s { + case AssessmentRealModeDemoBasic: + return []byte(s), nil + case AssessmentRealModeAdaptive: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *AssessmentRealMode) UnmarshalText(data []byte) error { + switch AssessmentRealMode(data) { + case AssessmentRealModeDemoBasic: + *s = AssessmentRealModeDemoBasic + return nil + case AssessmentRealModeAdaptive: + *s = AssessmentRealModeAdaptive + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Immutable result of a terminal assessment attempt. The result shape distinguishes real grade +// decisions from demo_express training output. +// Ref: #/components/schemas/AssessmentResult +// AssessmentResult represents sum type. +type AssessmentResult struct { + // Type selects the active sum variant, switch on this field. + Type AssessmentResultType + AssessmentQualifiedResult AssessmentQualifiedResult + AssessmentCorrectiveResult AssessmentCorrectiveResult + AssessmentExpressResult AssessmentExpressResult +} + +// AssessmentResultType is oneOf type of AssessmentResult. +type AssessmentResultType string + +// Possible values for AssessmentResultType. +const ( + AssessmentQualifiedResultAssessmentResult AssessmentResultType = "root" + AssessmentCorrectiveResultAssessmentResult AssessmentResultType = "corrective" + AssessmentExpressResultAssessmentResult AssessmentResultType = "demo_express" +) + +// IsAssessmentQualifiedResult reports whether AssessmentResult is AssessmentQualifiedResult. +func (s AssessmentResult) IsAssessmentQualifiedResult() bool { + return s.Type == AssessmentQualifiedResultAssessmentResult +} + +// IsAssessmentCorrectiveResult reports whether AssessmentResult is AssessmentCorrectiveResult. +func (s AssessmentResult) IsAssessmentCorrectiveResult() bool { + return s.Type == AssessmentCorrectiveResultAssessmentResult +} + +// IsAssessmentExpressResult reports whether AssessmentResult is AssessmentExpressResult. +func (s AssessmentResult) IsAssessmentExpressResult() bool { + return s.Type == AssessmentExpressResultAssessmentResult +} + +// SetAssessmentQualifiedResult sets AssessmentResult to AssessmentQualifiedResult. +func (s *AssessmentResult) SetAssessmentQualifiedResult(v AssessmentQualifiedResult) { + s.Type = AssessmentQualifiedResultAssessmentResult + s.AssessmentQualifiedResult = v +} + +// GetAssessmentQualifiedResult returns AssessmentQualifiedResult and true boolean if AssessmentResult is AssessmentQualifiedResult. +func (s AssessmentResult) GetAssessmentQualifiedResult() (v AssessmentQualifiedResult, ok bool) { + if !s.IsAssessmentQualifiedResult() { + return v, false + } + return s.AssessmentQualifiedResult, true +} + +// NewAssessmentQualifiedResultAssessmentResult returns new AssessmentResult from AssessmentQualifiedResult. +func NewAssessmentQualifiedResultAssessmentResult(v AssessmentQualifiedResult) AssessmentResult { + var s AssessmentResult + s.SetAssessmentQualifiedResult(v) + return s +} + +// SetAssessmentCorrectiveResult sets AssessmentResult to AssessmentCorrectiveResult. +func (s *AssessmentResult) SetAssessmentCorrectiveResult(v AssessmentCorrectiveResult) { + s.Type = AssessmentCorrectiveResultAssessmentResult + s.AssessmentCorrectiveResult = v +} + +// GetAssessmentCorrectiveResult returns AssessmentCorrectiveResult and true boolean if AssessmentResult is AssessmentCorrectiveResult. +func (s AssessmentResult) GetAssessmentCorrectiveResult() (v AssessmentCorrectiveResult, ok bool) { + if !s.IsAssessmentCorrectiveResult() { + return v, false + } + return s.AssessmentCorrectiveResult, true +} + +// NewAssessmentCorrectiveResultAssessmentResult returns new AssessmentResult from AssessmentCorrectiveResult. +func NewAssessmentCorrectiveResultAssessmentResult(v AssessmentCorrectiveResult) AssessmentResult { + var s AssessmentResult + s.SetAssessmentCorrectiveResult(v) + return s +} + +// SetAssessmentExpressResult sets AssessmentResult to AssessmentExpressResult. +func (s *AssessmentResult) SetAssessmentExpressResult(v AssessmentExpressResult) { + s.Type = AssessmentExpressResultAssessmentResult + s.AssessmentExpressResult = v +} + +// GetAssessmentExpressResult returns AssessmentExpressResult and true boolean if AssessmentResult is AssessmentExpressResult. +func (s AssessmentResult) GetAssessmentExpressResult() (v AssessmentExpressResult, ok bool) { + if !s.IsAssessmentExpressResult() { + return v, false + } + return s.AssessmentExpressResult, true +} + +// NewAssessmentExpressResultAssessmentResult returns new AssessmentResult from AssessmentExpressResult. +func NewAssessmentExpressResultAssessmentResult(v AssessmentExpressResult) AssessmentResult { + var s AssessmentResult + s.SetAssessmentExpressResult(v) + return s +} + // AssessmentResultHeaders wraps AssessmentResult with response headers. type AssessmentResultHeaders struct { CacheControl CacheControlNoStore @@ -2046,11 +4136,12 @@ func (*AssessmentResultHeaders) getMyAssessmentResultRes() {} // Work sessions of the attempt, as the policy version limits them, for example two sessions within the // time limit. // -// A session starts with the creation of the attempt or, after the previous session ended, with the -// next GetMyAssessmentAttempt or command on the active attempt. It ends after `idle_timeout_seconds` -// without such a request. A request that would start a session beyond `max_sessions` starts none: the -// server moves the attempt to `expired` and answers with it (a read) or with 409 state_conflict (a -// command). Reading a terminal attempt or a result never starts a session. +// Session 1 starts with attempt creation. After it ends due to `idle_timeout_seconds` of inactivity, +// the candidate explicitly starts or resumes work with StartMyAssessmentAttemptSession. +// GetMyAssessmentAttempt and GetMyAssessmentResult are read-only and never start a session. The +// session command checks the attempt deadline and `max_sessions`; when either limit has passed, it +// records the due terminal transition and returns the resulting attempt. Reads of terminal attempts do +// not change them. // Ref: #/components/schemas/AssessmentSessions type AssessmentSessions struct { // Sessions started so far, including the current one. @@ -10508,51 +12599,6 @@ func (o NilAssessmentItem) Or(d AssessmentItem) AssessmentItem { return d } -// NewNilAssessmentMode returns new NilAssessmentMode with value set to v. -func NewNilAssessmentMode(v AssessmentMode) NilAssessmentMode { - return NilAssessmentMode{ - Value: v, - } -} - -// NilAssessmentMode is nullable AssessmentMode. -type NilAssessmentMode struct { - Value AssessmentMode - Null bool -} - -// SetTo sets value to v. -func (o *NilAssessmentMode) SetTo(v AssessmentMode) { - o.Null = false - o.Value = v -} - -// IsNull returns true if value is Null. -func (o NilAssessmentMode) IsNull() bool { return o.Null } - -// SetToNull sets value to null. -func (o *NilAssessmentMode) SetToNull() { - o.Null = true - var v AssessmentMode - o.Value = v -} - -// Get returns value and boolean that denotes whether value was set. -func (o NilAssessmentMode) Get() (v AssessmentMode, ok bool) { - if o.Null { - return v, false - } - return o.Value, true -} - -// Or returns value if set, or given parameter if does not. -func (o NilAssessmentMode) Or(d AssessmentMode) AssessmentMode { - if v, ok := o.Get(); ok { - return v - } - return d -} - // NewNilAssessmentNotDeterminedReason returns new NilAssessmentNotDeterminedReason with value set to v. func NewNilAssessmentNotDeterminedReason(v AssessmentNotDeterminedReason) NilAssessmentNotDeterminedReason { return NilAssessmentNotDeterminedReason{ @@ -10598,6 +12644,51 @@ func (o NilAssessmentNotDeterminedReason) Or(d AssessmentNotDeterminedReason) As return d } +// NewNilAssessmentRealMode returns new NilAssessmentRealMode with value set to v. +func NewNilAssessmentRealMode(v AssessmentRealMode) NilAssessmentRealMode { + return NilAssessmentRealMode{ + Value: v, + } +} + +// NilAssessmentRealMode is nullable AssessmentRealMode. +type NilAssessmentRealMode struct { + Value AssessmentRealMode + Null bool +} + +// SetTo sets value to v. +func (o *NilAssessmentRealMode) SetTo(v AssessmentRealMode) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilAssessmentRealMode) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilAssessmentRealMode) SetToNull() { + o.Null = true + var v AssessmentRealMode + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilAssessmentRealMode) Get() (v AssessmentRealMode, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilAssessmentRealMode) Or(d AssessmentRealMode) AssessmentRealMode { + if v, ok := o.Get(); ok { + return v + } + return d +} + // NewNilAssessmentSessions returns new NilAssessmentSessions with value set to v. func NewNilAssessmentSessions(v AssessmentSessions) NilAssessmentSessions { return NilAssessmentSessions{ @@ -20598,6 +22689,34 @@ func (s *SpecializationCode) UnmarshalText(data []byte) error { type StackTag string +type StartMyAssessmentAttemptSessionBadRequest Problem + +func (*StartMyAssessmentAttemptSessionBadRequest) startMyAssessmentAttemptSessionRes() {} + +type StartMyAssessmentAttemptSessionConflict Problem + +func (*StartMyAssessmentAttemptSessionConflict) startMyAssessmentAttemptSessionRes() {} + +type StartMyAssessmentAttemptSessionForbidden Problem + +func (*StartMyAssessmentAttemptSessionForbidden) startMyAssessmentAttemptSessionRes() {} + +type StartMyAssessmentAttemptSessionNotFound Problem + +func (*StartMyAssessmentAttemptSessionNotFound) startMyAssessmentAttemptSessionRes() {} + +type StartMyAssessmentAttemptSessionPreconditionFailed Problem + +func (*StartMyAssessmentAttemptSessionPreconditionFailed) startMyAssessmentAttemptSessionRes() {} + +type StartMyAssessmentAttemptSessionUnauthorized Problem + +func (*StartMyAssessmentAttemptSessionUnauthorized) startMyAssessmentAttemptSessionRes() {} + +type StartMyAssessmentAttemptSessionUnprocessableEntity Problem + +func (*StartMyAssessmentAttemptSessionUnprocessableEntity) startMyAssessmentAttemptSessionRes() {} + // String answer, at most the `max_length` of the item. Two answers are equal only when their texts are // identical; no trimming, case folding, or Unicode normalization applies to that comparison. // Ref: #/components/schemas/StringAnswer @@ -22886,6 +25005,7 @@ func (*TooManyRequestsHeaders) raiseOrganizationInvitationSalaryRes() {} func (*TooManyRequestsHeaders) registerAccountRes() {} func (*TooManyRequestsHeaders) resendEmailVerificationRes() {} func (*TooManyRequestsHeaders) sendOrganizationInvitationRes() {} +func (*TooManyRequestsHeaders) startMyAssessmentAttemptSessionRes() {} func (*TooManyRequestsHeaders) submitMyAssessmentAnswerRes() {} func (*TooManyRequestsHeaders) updateOrganizationInvitationRes() {} func (*TooManyRequestsHeaders) updateOrganizationNeedRes() {} diff --git a/backend/internal/adapter/primary/http/api/oas_security_gen.go b/backend/internal/adapter/primary/http/api/oas_security_gen.go index 8a010e6..22b6792 100644 --- a/backend/internal/adapter/primary/http/api/oas_security_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_security_gen.go @@ -97,6 +97,7 @@ var operationRolesSessionCookie = map[string][]string{ SendOrganizationInvitationOperation: []string{}, SetMyPublicationOperation: []string{}, SetMySearchStatusOperation: []string{}, + StartMyAssessmentAttemptSessionOperation: []string{}, SubmitMyAssessmentAnswerOperation: []string{}, UnhideOrganizationOperation: []string{}, UpdateOrganizationOperation: []string{}, @@ -146,6 +147,7 @@ var operationRolesSessionCsrf = map[string][]string{ SendOrganizationInvitationOperation: []string{}, SetMyPublicationOperation: []string{}, SetMySearchStatusOperation: []string{}, + StartMyAssessmentAttemptSessionOperation: []string{}, SubmitMyAssessmentAnswerOperation: []string{}, UnhideOrganizationOperation: []string{}, UpdateOrganizationOperation: []string{}, diff --git a/backend/internal/adapter/primary/http/api/oas_server_gen.go b/backend/internal/adapter/primary/http/api/oas_server_gen.go index f51200b..7ce742c 100644 --- a/backend/internal/adapter/primary/http/api/oas_server_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_server_gen.go @@ -135,27 +135,33 @@ type Handler interface { // CreateMyAssessmentAttempt implements CreateMyAssessmentAttempt operation. // // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, - // an allowed Origin, and an Idempotency-Key. The body names the category, a specialization of the - // questionnaire and a target grade, and the task language. The server picks the mode from the - // published bank, `demo_basic` or `adaptive`, and fixes the policy, bank, and algorithm versions, the - // time and session limits, and the item variants in one transaction; the client never sends a mode, a - // seed, or a version. Creation starts session 1. The self-assessed grade only chooses where the test - // starts and adds no points. An adaptive retest starts from the previous ability estimate of the - // specialization, adjusted for the time passed, so a new attempt adds evidence instead of starting the - // measurement over. + // an allowed Origin, and an Idempotency-Key. The request is one of three disjoint shapes. A real + // assessment names a specialization, target grade, and task language; the server picks `demo_basic` or + // `adaptive` and fixes the policy, bank, and algorithm versions, limits, and item variants. A + // corrective real assessment also names `root_attempt_id`; the server verifies the lower-grade chain + // and reuses its fixed quota and deadline. The client never sends a real mode, a seed, a version, or a + // chain deadline. Explicit `demo_express` starts a separate interactive training run that lasts 3 to 5 + // minutes, has no category or target grade, and creates no qualification evidence or percentile. + // Creation starts session 1. The self-assessed grade only chooses where a real test starts and adds no + // points. An adaptive retest starts from the previous ability estimate of the specialization, adjusted + // for the time passed, so a new attempt adds evidence instead of starting the measurement over. // - // A specialization has at most one active attempt. A new attempt cannot start while one is active, - // during a retry or promotion interval or past the attempt limit of the policy, or when the bank is - // insufficient; each answers 409 state_conflict and creates nothing, not even a placeholder attempt. - // GetMyAssessmentAvailability tells which case applies and when a blocked attempt opens. After a - // failure, including the first test, a lower grade can be tested at once. An attempt that ends as - // `expired` or with the reason `practice_incomplete` counts toward the attempt limit and starts the - // same-grade retry interval; one that ends as `insufficient_bank` or with the reason - // `sandbox_unavailable` counts toward neither. + // A specialization has at most one active real attempt. A new root attempt cannot start while one is + // active, during a retry or promotion interval, past the root quota, or when the bank is insufficient; + // each such preflight refusal answers 409 state_conflict and creates nothing or consumes no root slot. + // Starting a root attempt reserves one slot in the root quota. A corrective attempt must reference its + // root, target a strictly lower grade not already attempted in that chain, and remain inside the + // root's fixed quota and deadline (72 hours from the root start in the current policy). It gets its + // own item, practice, and session limits, but spends no additional root slot and cannot reset the + // chain deadline or any 30/90-day timer. After a failure, including the first test, a lower grade can + // be tested at once. An expired or incomplete attempt does not create a free new chain; an + // insufficient bank or sandbox failure does not grant another root slot. `demo_express` is outside + // real-assessment availability, quotas, retry intervals, and qualification history. // // The limits are server-side: `expires_at` and `sessions` come from the policy version, the client - // clock never extends them, and after them the attempt accepts no command. Within them the attempt is - // also bounded by the item limit of the policy. + // clock never extends them, and after them the attempt accepts no work command. For a corrective + // attempt, `expires_at` is no later than the root's immutable `chain_deadline`. Within these limits + // the attempt is also bounded by the item limit of its policy. // // Idempotency: a retry with the same key and body within 24 hours replays the stored 201 or 409 // state_conflict response and creates nothing, so a lost response never creates a second attempt. A @@ -170,7 +176,7 @@ type Handler interface { // Retry-After before any of them; it is not stored. // // POST /api/v1/me/assessment-attempts - CreateMyAssessmentAttempt(ctx context.Context, req *AssessmentAttemptCreate, params CreateMyAssessmentAttemptParams) (CreateMyAssessmentAttemptRes, error) + CreateMyAssessmentAttempt(ctx context.Context, req AssessmentAttemptCreate, params CreateMyAssessmentAttemptParams) (CreateMyAssessmentAttemptRes, error) // CreateMySupportCase implements CreateMySupportCase operation. // // Requires the session cookie, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and @@ -442,6 +448,11 @@ type Handler interface { // every generated client. When the returned state is `completed`, the client reads the result with // GetMyAssessmentResult. // + // Finalize is a work command and requires an active session. After `idle_timeout_seconds` of + // inactivity, the candidate first calls StartMyAssessmentAttemptSession with the latest + // `expected_version`; finalize never starts a session. GET attempt and result operations do not change + // state. A command or background transition may commit a due deadline outcome. + // // Allowed in `ready_to_finalize`, where every required part is done, and in // `additional_practice_pending` while the additional practice is `not_started` or `failed`. The server // decides from the stored answers with the policy, bank, and algorithm versions fixed at creation: @@ -463,9 +474,9 @@ type Handler interface { // A failed attempt never lowers a confirmed grade. Repeats return the same outcome: a retry with the // same Idempotency-Key replays the stored response, and a finalize of a `completed` attempt answers // 200 with that attempt even with a new key or an older `expected_version`; the result is computed - // once. When `expires_at` passes or the session limit is reached, the server finalizes - // `ready_to_finalize` itself, without offering an additional practice, so a finalize after that also - // answers 200 with the `completed` attempt. + // once. When `expires_at` passes or the session limit is reached, a command or background transition + // finalizes `ready_to_finalize` without offering an additional practice. A finalize after this + // transition answers 200 with the stored `completed` attempt; a GET never commits it. // // An attempt in `in_progress` or `practice_pending`, one with a practice verdict `pending`, or one // that ended as `expired` or `insufficient_bank` answers 409 state_conflict. The problem does not list @@ -474,8 +485,9 @@ type Handler interface { // // Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), // account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), - // the attempt (404 not_found, after any due transition), the repeat on a `completed` attempt (200), - // the version (412), then the state (409 state_conflict). 404 and 409 state_conflict are stored under + // the attempt (404 not_found; a due deadline transition may be committed, but this request never + // starts a work session), the repeat on a `completed` attempt (200), the version (412), then the state + // (409 state_conflict, including an ended idle session). 404 and 409 state_conflict are stored under // the key; 400 and 412 are not. // // POST /api/v1/me/assessment-attempts/{attempt_id}/finalize @@ -518,24 +530,25 @@ type Handler interface { GetHealthz(ctx context.Context) (*HealthResponse, error) // GetMyAssessmentAttempt implements GetMyAssessmentAttempt operation. // - // Requires the session cookie of a candidate account. Returns the attempt with its state, fixed - // versions, time and session limits, progress, the item to answer now, and the practices. A reload, a - // retried request, or a new session returns the same item instance with the same text and option - // order; a lost connection never creates a new attempt. The response never says whether an earlier - // answer was correct and never contains answer keys, item scores, family or variant identifiers, - // seeds, hidden checks, or anti-cheat signals. + // Requires the session cookie of a candidate account. Returns the stored attempt projection with its + // state, fixed versions, time and session limits, progress, the item to answer now, and the practices. + // This GET is read-only: it never starts or resumes a work session, consumes session quota, advances + // the version, or commits expiry or finalization. A reload, a retried request, or a new session + // returns the same item instance with the same text and option order; a lost connection never creates + // a new attempt. After `idle_timeout_seconds`, the candidate explicitly starts or resumes work with + // StartMyAssessmentAttemptSession. The response never says whether an earlier answer was correct and + // never contains answer keys, item scores, family or variant identifiers, seeds, hidden checks, or + // anti-cheat signals. // - // Reading an active attempt counts as activity: after the previous session ended it starts the next - // session, and when that would exceed the session limit it starts none and the attempt becomes - // `expired`. Before it answers, the server commits any transition that is due, with a new version: - // past `expires_at`, `ready_to_finalize` becomes `completed`, an unsubmitted additional practice is - // declined and the attempt becomes `completed`, and the other active states become `expired`; a - // practice still `pending` is graded first. The client polls this operation while a practice is - // `pending`. Reading a terminal attempt changes nothing. + // When the deadline passes, this read still returns the stored state and deadline. A command or + // background transition commits the due outcome; if the stored state is still active, + // GetMyAssessmentResult answers 409 until that transition is committed. The client polls this + // operation while a practice is `pending`, but polling alone never changes attempt state. // // The attempt must belong to the candidate of the session: an attempt of another candidate answers 404 // not_found, the same as an unknown identifier, so identifiers cannot be probed. An employer account - // answers 403 forbidden; no operation gives an employer the answers or the attempt history. + // answers 403 forbidden; no operation gives an employer the answers, qualification evidence, or + // attempt history. // // GET /api/v1/me/assessment-attempts/{attempt_id} GetMyAssessmentAttempt(ctx context.Context, params GetMyAssessmentAttemptParams) (GetMyAssessmentAttemptRes, error) @@ -563,21 +576,25 @@ type Handler interface { // GetMyAssessmentResult implements GetMyAssessmentResult operation. // // Requires the session cookie of a candidate account. Returns the immutable result of a terminal - // attempt: `completed`, `expired`, or `insufficient_bank`. It records the mode, the policy, bank, and - // algorithm versions, the decision, the previously confirmed grade, the calibration status and - // limitations of the method, the uncertainty where the method computes it, the practice verdicts, the - // weak domains, the working time as a separate label, and the next steps that the server allows. A - // later policy, bank, or algorithm version never changes it. + // attempt: `completed`, `expired`, or `insufficient_bank`. A real result records the mode, policy, + // bank, and algorithm versions, decision, previously confirmed grade, calibration status and + // limitations, uncertainty where the method computes it, practice verdicts, weak domains, working time + // as a separate label, and allowed next steps. A corrective result also carries the root attempt and + // its immutable chain deadline. A `demo_express` result is a short educational summary only: it has no + // category, percentile, confirmed grade, score, uncertainty, or qualification evidence. A later + // policy, bank, or algorithm version never changes a result. // // Fields that the method does not compute are null and never zero: a `demo_basic` result has null // `uncertainty` and `strength`. The result never contains answers, per-item correctness, answer keys, // seeds, hidden checks, or anti-cheat signals. // // An active attempt answers 409 state_conflict; an attempt in `additional_practice_pending` is active - // and has no result yet. The server first commits any due transition, so an attempt past its limits is - // read as terminal. An attempt of another candidate answers 404 not_found, the same as an unknown - // identifier. An employer account answers 403 forbidden; employers see only the current category - // through a separate projection, never this result or the attempt history. + // and has no result yet. This GET is read-only and never commits a due transition. If a deadline has + // passed but the due transition is not yet stored by a command or background worker, the attempt + // remains active for this read and answers 409; wait for the transition and retry. An attempt of + // another candidate answers 404 not_found, the same as an unknown identifier. An employer account + // answers 403 forbidden; employers see only the current category through a separate projection, never + // this result or the attempt history. // // GET /api/v1/me/assessment-attempts/{attempt_id}/result GetMyAssessmentResult(ctx context.Context, params GetMyAssessmentResultParams) (GetMyAssessmentResultRes, error) @@ -1418,6 +1435,31 @@ type Handler interface { // // PUT /api/v1/me/privacy/search-status SetMySearchStatus(ctx context.Context, req *SearchStatusUpdate) (SetMySearchStatusRes, error) + // StartMyAssessmentAttemptSession implements StartMyAssessmentAttemptSession operation. + // + // Requires a candidate session, its CSRF token in X-CSRF-Token, an allowed Origin, and an + // Idempotency-Key. The body carries the attempt version the candidate last read. The server checks + // ownership, idempotency, and `expected_version` atomically before starting a session; a stale version + // answers 412 and consumes no session. Repeating the same key and body within 24 hours replays the + // stored response. + // + // Creation starts session 1. After `idle_timeout_seconds` of inactivity, the candidate uses this + // command to start the next session. Calling it while a session is already active returns the current + // attempt without consuming another session or advancing its version. Starting a session advances the + // version once. The command cannot extend `expires_at` or `chain_deadline`. + // + // If the attempt deadline or session budget has passed, this command commits the due terminal + // transition and returns the resulting attempt. A pending practice submitted before the limit is + // graded first. `GetMyAssessmentAttempt` and `GetMyAssessmentResult` remain read-only: they never + // start a session or commit a due transition. A background transition may persist a due outcome + // independently; after that, this command returns the stored terminal attempt without changing it. + // + // The attempt must belong to the candidate of the session. An attempt of another candidate answers 404 + // not_found, the same as an unknown identifier. An employer account answers 403 forbidden; no + // operation gives an employer answers, qualification evidence, or attempt history. + // + // POST /api/v1/me/assessment-attempts/{attempt_id}/sessions + StartMyAssessmentAttemptSession(ctx context.Context, req *AssessmentAttemptSessionStart, params StartMyAssessmentAttemptSessionParams) (StartMyAssessmentAttemptSessionRes, error) // SubmitMyAssessmentAnswer implements SubmitMyAssessmentAnswer operation. // // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, @@ -1430,6 +1472,12 @@ type Handler interface { // The response is the attempt with the next item to answer. It never says whether the answer was // correct. Items are answered in order and each answer is final. // + // A work command requires an active session. After `idle_timeout_seconds` of inactivity, the candidate + // calls StartMyAssessmentAttemptSession to explicitly start or resume a session; this answer command + // never starts one or consumes session quota. Reading the attempt or result is always read-only. A + // command that finds a due deadline transition may commit it before returning; a command that finds an + // expired idle session answers 409 until the candidate explicitly starts the next session. + // // Practice: an answer with format `practice` submits the solution of the main or the additional // practice. It is stored, and the sandbox runs it asynchronously against the hidden check groups; the // response shows the practice `pending`, and the client polls GetMyAssessmentAttempt for the verdict. @@ -1463,15 +1511,14 @@ type Handler interface { // // Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), // account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), - // the attempt (404 not_found for an unknown attempt or one of another candidate; the server first - // commits any due transition such as expiry, and the request counts as activity for the session - // limit), the repeat of the stored answer (200, skipped for a practice whose latest verdict is - // `failed`), the version (412), the state (409 state_conflict: the attempt is terminal, the item is - // not current, the item has a different answer, or the practice verdict is pending or finished), then - // the answer against the item (400 with a pointer such as `/answer/format` or `/answer/option_ids/0`). - // Following the Idempotency-Key convention, 404 and 409 state_conflict are stored under the key and - // replayed; 400, 412, 429, and 5xx are not. The rate limit can answer 429 with Retry-After before any - // check. + // the attempt (404 not_found for an unknown attempt or one of another candidate; a due deadline + // transition may be committed, but this request never starts a work session), the repeat of the stored + // answer (200, skipped for a practice whose latest verdict is `failed`), the version (412), the state + // (409 state_conflict: the attempt is terminal, the work session ended, the item is not current, the + // item has a different answer, or the practice verdict is pending or finished), then the answer + // against the item (400 with a pointer such as `/answer/format` or `/answer/option_ids/0`). Following + // the Idempotency-Key convention, 404 and 409 state_conflict are stored under the key and replayed; + // 400, 412, 429, and 5xx are not. The rate limit can answer 429 with Retry-After before any check. // // POST /api/v1/me/assessment-attempts/{attempt_id}/answers SubmitMyAssessmentAnswer(ctx context.Context, req *AssessmentAnswerSubmission, params SubmitMyAssessmentAnswerParams) (SubmitMyAssessmentAnswerRes, error) diff --git a/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go b/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go index 819c1f6..edb74e4 100644 --- a/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go @@ -149,27 +149,33 @@ func (UnimplementedHandler) ConfirmEmail(ctx context.Context, req *EmailVerifica // CreateMyAssessmentAttempt implements CreateMyAssessmentAttempt operation. // // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, -// an allowed Origin, and an Idempotency-Key. The body names the category, a specialization of the -// questionnaire and a target grade, and the task language. The server picks the mode from the -// published bank, `demo_basic` or `adaptive`, and fixes the policy, bank, and algorithm versions, the -// time and session limits, and the item variants in one transaction; the client never sends a mode, a -// seed, or a version. Creation starts session 1. The self-assessed grade only chooses where the test -// starts and adds no points. An adaptive retest starts from the previous ability estimate of the -// specialization, adjusted for the time passed, so a new attempt adds evidence instead of starting the -// measurement over. +// an allowed Origin, and an Idempotency-Key. The request is one of three disjoint shapes. A real +// assessment names a specialization, target grade, and task language; the server picks `demo_basic` or +// `adaptive` and fixes the policy, bank, and algorithm versions, limits, and item variants. A +// corrective real assessment also names `root_attempt_id`; the server verifies the lower-grade chain +// and reuses its fixed quota and deadline. The client never sends a real mode, a seed, a version, or a +// chain deadline. Explicit `demo_express` starts a separate interactive training run that lasts 3 to 5 +// minutes, has no category or target grade, and creates no qualification evidence or percentile. +// Creation starts session 1. The self-assessed grade only chooses where a real test starts and adds no +// points. An adaptive retest starts from the previous ability estimate of the specialization, adjusted +// for the time passed, so a new attempt adds evidence instead of starting the measurement over. // -// A specialization has at most one active attempt. A new attempt cannot start while one is active, -// during a retry or promotion interval or past the attempt limit of the policy, or when the bank is -// insufficient; each answers 409 state_conflict and creates nothing, not even a placeholder attempt. -// GetMyAssessmentAvailability tells which case applies and when a blocked attempt opens. After a -// failure, including the first test, a lower grade can be tested at once. An attempt that ends as -// `expired` or with the reason `practice_incomplete` counts toward the attempt limit and starts the -// same-grade retry interval; one that ends as `insufficient_bank` or with the reason -// `sandbox_unavailable` counts toward neither. +// A specialization has at most one active real attempt. A new root attempt cannot start while one is +// active, during a retry or promotion interval, past the root quota, or when the bank is insufficient; +// each such preflight refusal answers 409 state_conflict and creates nothing or consumes no root slot. +// Starting a root attempt reserves one slot in the root quota. A corrective attempt must reference its +// root, target a strictly lower grade not already attempted in that chain, and remain inside the +// root's fixed quota and deadline (72 hours from the root start in the current policy). It gets its +// own item, practice, and session limits, but spends no additional root slot and cannot reset the +// chain deadline or any 30/90-day timer. After a failure, including the first test, a lower grade can +// be tested at once. An expired or incomplete attempt does not create a free new chain; an +// insufficient bank or sandbox failure does not grant another root slot. `demo_express` is outside +// real-assessment availability, quotas, retry intervals, and qualification history. // // The limits are server-side: `expires_at` and `sessions` come from the policy version, the client -// clock never extends them, and after them the attempt accepts no command. Within them the attempt is -// also bounded by the item limit of the policy. +// clock never extends them, and after them the attempt accepts no work command. For a corrective +// attempt, `expires_at` is no later than the root's immutable `chain_deadline`. Within these limits +// the attempt is also bounded by the item limit of its policy. // // Idempotency: a retry with the same key and body within 24 hours replays the stored 201 or 409 // state_conflict response and creates nothing, so a lost response never creates a second attempt. A @@ -184,7 +190,7 @@ func (UnimplementedHandler) ConfirmEmail(ctx context.Context, req *EmailVerifica // Retry-After before any of them; it is not stored. // // POST /api/v1/me/assessment-attempts -func (UnimplementedHandler) CreateMyAssessmentAttempt(ctx context.Context, req *AssessmentAttemptCreate, params CreateMyAssessmentAttemptParams) (r CreateMyAssessmentAttemptRes, _ error) { +func (UnimplementedHandler) CreateMyAssessmentAttempt(ctx context.Context, req AssessmentAttemptCreate, params CreateMyAssessmentAttemptParams) (r CreateMyAssessmentAttemptRes, _ error) { return r, ht.ErrNotImplemented } @@ -474,6 +480,11 @@ func (UnimplementedHandler) DeclineMyInvitation(ctx context.Context, req *Invita // every generated client. When the returned state is `completed`, the client reads the result with // GetMyAssessmentResult. // +// Finalize is a work command and requires an active session. After `idle_timeout_seconds` of +// inactivity, the candidate first calls StartMyAssessmentAttemptSession with the latest +// `expected_version`; finalize never starts a session. GET attempt and result operations do not change +// state. A command or background transition may commit a due deadline outcome. +// // Allowed in `ready_to_finalize`, where every required part is done, and in // `additional_practice_pending` while the additional practice is `not_started` or `failed`. The server // decides from the stored answers with the policy, bank, and algorithm versions fixed at creation: @@ -495,9 +506,9 @@ func (UnimplementedHandler) DeclineMyInvitation(ctx context.Context, req *Invita // A failed attempt never lowers a confirmed grade. Repeats return the same outcome: a retry with the // same Idempotency-Key replays the stored response, and a finalize of a `completed` attempt answers // 200 with that attempt even with a new key or an older `expected_version`; the result is computed -// once. When `expires_at` passes or the session limit is reached, the server finalizes -// `ready_to_finalize` itself, without offering an additional practice, so a finalize after that also -// answers 200 with the `completed` attempt. +// once. When `expires_at` passes or the session limit is reached, a command or background transition +// finalizes `ready_to_finalize` without offering an additional practice. A finalize after this +// transition answers 200 with the stored `completed` attempt; a GET never commits it. // // An attempt in `in_progress` or `practice_pending`, one with a practice verdict `pending`, or one // that ended as `expired` or `insufficient_bank` answers 409 state_conflict. The problem does not list @@ -506,8 +517,9 @@ func (UnimplementedHandler) DeclineMyInvitation(ctx context.Context, req *Invita // // Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), // account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), -// the attempt (404 not_found, after any due transition), the repeat on a `completed` attempt (200), -// the version (412), then the state (409 state_conflict). 404 and 409 state_conflict are stored under +// the attempt (404 not_found; a due deadline transition may be committed, but this request never +// starts a work session), the repeat on a `completed` attempt (200), the version (412), then the state +// (409 state_conflict, including an ended idle session). 404 and 409 state_conflict are stored under // the key; 400 and 412 are not. // // POST /api/v1/me/assessment-attempts/{attempt_id}/finalize @@ -565,24 +577,25 @@ func (UnimplementedHandler) GetHealthz(ctx context.Context) (r *HealthResponse, // GetMyAssessmentAttempt implements GetMyAssessmentAttempt operation. // -// Requires the session cookie of a candidate account. Returns the attempt with its state, fixed -// versions, time and session limits, progress, the item to answer now, and the practices. A reload, a -// retried request, or a new session returns the same item instance with the same text and option -// order; a lost connection never creates a new attempt. The response never says whether an earlier -// answer was correct and never contains answer keys, item scores, family or variant identifiers, -// seeds, hidden checks, or anti-cheat signals. +// Requires the session cookie of a candidate account. Returns the stored attempt projection with its +// state, fixed versions, time and session limits, progress, the item to answer now, and the practices. +// This GET is read-only: it never starts or resumes a work session, consumes session quota, advances +// the version, or commits expiry or finalization. A reload, a retried request, or a new session +// returns the same item instance with the same text and option order; a lost connection never creates +// a new attempt. After `idle_timeout_seconds`, the candidate explicitly starts or resumes work with +// StartMyAssessmentAttemptSession. The response never says whether an earlier answer was correct and +// never contains answer keys, item scores, family or variant identifiers, seeds, hidden checks, or +// anti-cheat signals. // -// Reading an active attempt counts as activity: after the previous session ended it starts the next -// session, and when that would exceed the session limit it starts none and the attempt becomes -// `expired`. Before it answers, the server commits any transition that is due, with a new version: -// past `expires_at`, `ready_to_finalize` becomes `completed`, an unsubmitted additional practice is -// declined and the attempt becomes `completed`, and the other active states become `expired`; a -// practice still `pending` is graded first. The client polls this operation while a practice is -// `pending`. Reading a terminal attempt changes nothing. +// When the deadline passes, this read still returns the stored state and deadline. A command or +// background transition commits the due outcome; if the stored state is still active, +// GetMyAssessmentResult answers 409 until that transition is committed. The client polls this +// operation while a practice is `pending`, but polling alone never changes attempt state. // // The attempt must belong to the candidate of the session: an attempt of another candidate answers 404 // not_found, the same as an unknown identifier, so identifiers cannot be probed. An employer account -// answers 403 forbidden; no operation gives an employer the answers or the attempt history. +// answers 403 forbidden; no operation gives an employer the answers, qualification evidence, or +// attempt history. // // GET /api/v1/me/assessment-attempts/{attempt_id} func (UnimplementedHandler) GetMyAssessmentAttempt(ctx context.Context, params GetMyAssessmentAttemptParams) (r GetMyAssessmentAttemptRes, _ error) { @@ -616,21 +629,25 @@ func (UnimplementedHandler) GetMyAssessmentAvailability(ctx context.Context) (r // GetMyAssessmentResult implements GetMyAssessmentResult operation. // // Requires the session cookie of a candidate account. Returns the immutable result of a terminal -// attempt: `completed`, `expired`, or `insufficient_bank`. It records the mode, the policy, bank, and -// algorithm versions, the decision, the previously confirmed grade, the calibration status and -// limitations of the method, the uncertainty where the method computes it, the practice verdicts, the -// weak domains, the working time as a separate label, and the next steps that the server allows. A -// later policy, bank, or algorithm version never changes it. +// attempt: `completed`, `expired`, or `insufficient_bank`. A real result records the mode, policy, +// bank, and algorithm versions, decision, previously confirmed grade, calibration status and +// limitations, uncertainty where the method computes it, practice verdicts, weak domains, working time +// as a separate label, and allowed next steps. A corrective result also carries the root attempt and +// its immutable chain deadline. A `demo_express` result is a short educational summary only: it has no +// category, percentile, confirmed grade, score, uncertainty, or qualification evidence. A later +// policy, bank, or algorithm version never changes a result. // // Fields that the method does not compute are null and never zero: a `demo_basic` result has null // `uncertainty` and `strength`. The result never contains answers, per-item correctness, answer keys, // seeds, hidden checks, or anti-cheat signals. // // An active attempt answers 409 state_conflict; an attempt in `additional_practice_pending` is active -// and has no result yet. The server first commits any due transition, so an attempt past its limits is -// read as terminal. An attempt of another candidate answers 404 not_found, the same as an unknown -// identifier. An employer account answers 403 forbidden; employers see only the current category -// through a separate projection, never this result or the attempt history. +// and has no result yet. This GET is read-only and never commits a due transition. If a deadline has +// passed but the due transition is not yet stored by a command or background worker, the attempt +// remains active for this read and answers 409; wait for the transition and retry. An attempt of +// another candidate answers 404 not_found, the same as an unknown identifier. An employer account +// answers 403 forbidden; employers see only the current category through a separate projection, never +// this result or the attempt history. // // GET /api/v1/me/assessment-attempts/{attempt_id}/result func (UnimplementedHandler) GetMyAssessmentResult(ctx context.Context, params GetMyAssessmentResultParams) (r GetMyAssessmentResultRes, _ error) { @@ -1567,6 +1584,34 @@ func (UnimplementedHandler) SetMySearchStatus(ctx context.Context, req *SearchSt return r, ht.ErrNotImplemented } +// StartMyAssessmentAttemptSession implements StartMyAssessmentAttemptSession operation. +// +// Requires a candidate session, its CSRF token in X-CSRF-Token, an allowed Origin, and an +// Idempotency-Key. The body carries the attempt version the candidate last read. The server checks +// ownership, idempotency, and `expected_version` atomically before starting a session; a stale version +// answers 412 and consumes no session. Repeating the same key and body within 24 hours replays the +// stored response. +// +// Creation starts session 1. After `idle_timeout_seconds` of inactivity, the candidate uses this +// command to start the next session. Calling it while a session is already active returns the current +// attempt without consuming another session or advancing its version. Starting a session advances the +// version once. The command cannot extend `expires_at` or `chain_deadline`. +// +// If the attempt deadline or session budget has passed, this command commits the due terminal +// transition and returns the resulting attempt. A pending practice submitted before the limit is +// graded first. `GetMyAssessmentAttempt` and `GetMyAssessmentResult` remain read-only: they never +// start a session or commit a due transition. A background transition may persist a due outcome +// independently; after that, this command returns the stored terminal attempt without changing it. +// +// The attempt must belong to the candidate of the session. An attempt of another candidate answers 404 +// not_found, the same as an unknown identifier. An employer account answers 403 forbidden; no +// operation gives an employer answers, qualification evidence, or attempt history. +// +// POST /api/v1/me/assessment-attempts/{attempt_id}/sessions +func (UnimplementedHandler) StartMyAssessmentAttemptSession(ctx context.Context, req *AssessmentAttemptSessionStart, params StartMyAssessmentAttemptSessionParams) (r StartMyAssessmentAttemptSessionRes, _ error) { + return r, ht.ErrNotImplemented +} + // SubmitMyAssessmentAnswer implements SubmitMyAssessmentAnswer operation. // // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, @@ -1579,6 +1624,12 @@ func (UnimplementedHandler) SetMySearchStatus(ctx context.Context, req *SearchSt // The response is the attempt with the next item to answer. It never says whether the answer was // correct. Items are answered in order and each answer is final. // +// A work command requires an active session. After `idle_timeout_seconds` of inactivity, the candidate +// calls StartMyAssessmentAttemptSession to explicitly start or resume a session; this answer command +// never starts one or consumes session quota. Reading the attempt or result is always read-only. A +// command that finds a due deadline transition may commit it before returning; a command that finds an +// expired idle session answers 409 until the candidate explicitly starts the next session. +// // Practice: an answer with format `practice` submits the solution of the main or the additional // practice. It is stored, and the sandbox runs it asynchronously against the hidden check groups; the // response shows the practice `pending`, and the client polls GetMyAssessmentAttempt for the verdict. @@ -1612,15 +1663,14 @@ func (UnimplementedHandler) SetMySearchStatus(ctx context.Context, req *SearchSt // // Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), // account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), -// the attempt (404 not_found for an unknown attempt or one of another candidate; the server first -// commits any due transition such as expiry, and the request counts as activity for the session -// limit), the repeat of the stored answer (200, skipped for a practice whose latest verdict is -// `failed`), the version (412), the state (409 state_conflict: the attempt is terminal, the item is -// not current, the item has a different answer, or the practice verdict is pending or finished), then -// the answer against the item (400 with a pointer such as `/answer/format` or `/answer/option_ids/0`). -// Following the Idempotency-Key convention, 404 and 409 state_conflict are stored under the key and -// replayed; 400, 412, 429, and 5xx are not. The rate limit can answer 429 with Retry-After before any -// check. +// the attempt (404 not_found for an unknown attempt or one of another candidate; a due deadline +// transition may be committed, but this request never starts a work session), the repeat of the stored +// answer (200, skipped for a practice whose latest verdict is `failed`), the version (412), the state +// (409 state_conflict: the attempt is terminal, the work session ended, the item is not current, the +// item has a different answer, or the practice verdict is pending or finished), then the answer +// against the item (400 with a pointer such as `/answer/format` or `/answer/option_ids/0`). Following +// the Idempotency-Key convention, 404 and 409 state_conflict are stored under the key and replayed; +// 400, 412, 429, and 5xx are not. The rate limit can answer 429 with Retry-After before any check. // // POST /api/v1/me/assessment-attempts/{attempt_id}/answers func (UnimplementedHandler) SubmitMyAssessmentAnswer(ctx context.Context, req *AssessmentAnswerSubmission, params SubmitMyAssessmentAnswerParams) (r SubmitMyAssessmentAnswerRes, _ error) { diff --git a/backend/internal/adapter/primary/http/api/oas_validators_gen.go b/backend/internal/adapter/primary/http/api/oas_validators_gen.go index 22526ba..af643e0 100644 --- a/backend/internal/adapter/primary/http/api/oas_validators_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_validators_gen.go @@ -421,235 +421,48 @@ func (s *AssessmentAnswerSubmission) Validate() error { return nil } -func (s *AssessmentAttempt) Validate() error { - if s == nil { - return validate.ErrNilPointer - } - - var failures []validate.FieldError - if err := func() error { - if err := s.Version.Validate(); err != nil { +func (s AssessmentAttempt) Validate() error { + switch s.Type { + case AssessmentQualifiedAttemptAssessmentAttempt: + if err := s.AssessmentQualifiedAttempt.Validate(); err != nil { return err } return nil - }(); err != nil { - failures = append(failures, validate.FieldError{ - Name: "version", - Error: err, - }) - } - if err := func() error { - if err := s.Specialization.Validate(); err != nil { + case AssessmentCorrectiveAttemptAssessmentAttempt: + if err := s.AssessmentCorrectiveAttempt.Validate(); err != nil { return err } return nil - }(); err != nil { - failures = append(failures, validate.FieldError{ - Name: "specialization", - Error: err, - }) - } - if err := func() error { - if err := s.TargetGrade.Validate(); err != nil { + case AssessmentExpressAttemptAssessmentAttempt: + if err := s.AssessmentExpressAttempt.Validate(); err != nil { return err } return nil - }(); err != nil { - failures = append(failures, validate.FieldError{ - Name: "target_grade", - Error: err, - }) + default: + return errors.Errorf("invalid type %q", s.Type) } - if err := func() error { - if value, ok := s.TaskLanguage.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: "task_language", - Error: err, - }) - } - if err := func() error { - if err := s.Mode.Validate(); err != nil { - return err - } - return nil - }(); err != nil { - failures = append(failures, validate.FieldError{ - Name: "mode", - Error: err, - }) - } - if err := func() error { - if err := s.State.Validate(); err != nil { - return err - } - return nil - }(); err != nil { - failures = append(failures, validate.FieldError{ - Name: "state", - Error: err, - }) - } - if err := func() error { - if err := s.Versions.Validate(); err != nil { - return err - } - return nil - }(); err != nil { - failures = append(failures, validate.FieldError{ - Name: "versions", - Error: err, - }) - } - if err := func() error { - if value, ok := s.Sessions.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: "sessions", - Error: err, - }) - } - if err := func() error { - if err := s.Progress.Validate(); err != nil { - return err - } - return nil - }(); err != nil { - failures = append(failures, validate.FieldError{ - Name: "progress", - Error: err, - }) - } - if err := func() error { - if value, ok := s.CurrentItem.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: "current_item", - Error: err, - }) - } - if err := func() error { - if s.Practices == nil { - return errors.New("nil is invalid value") - } - if err := (validate.Array{ - MinLength: 0, - MinLengthSet: false, - MaxLength: 5, - MaxLengthSet: true, - }).ValidateLength(len(s.Practices)); err != nil { - return errors.Wrap(err, "array") - } - var failures []validate.FieldError - for i, elem := range s.Practices { - if err := func() error { - if err := elem.Validate(); err != nil { - return err - } - return nil - }(); err != nil { - failures = append(failures, validate.FieldError{ - Name: fmt.Sprintf("[%d]", i), - Error: err, - }) - } - } - if len(failures) > 0 { - return &validate.Error{Fields: failures} - } - return nil - }(); err != nil { - failures = append(failures, validate.FieldError{ - Name: "practices", - Error: err, - }) - } - if len(failures) > 0 { - return &validate.Error{Fields: failures} - } - return nil } -func (s *AssessmentAttemptCreate) Validate() error { - if s == nil { - return validate.ErrNilPointer - } - - var failures []validate.FieldError - if err := func() error { - if err := s.Specialization.Validate(); err != nil { +func (s AssessmentAttemptCreate) Validate() error { + switch s.Type { + case AssessmentQualifiedAttemptCreateAssessmentAttemptCreate: + if err := s.AssessmentQualifiedAttemptCreate.Validate(); err != nil { return err } return nil - }(); err != nil { - failures = append(failures, validate.FieldError{ - Name: "specialization", - Error: err, - }) - } - if err := func() error { - if err := s.TargetGrade.Validate(); err != nil { + case AssessmentCorrectiveAttemptCreateAssessmentAttemptCreate: + if err := s.AssessmentCorrectiveAttemptCreate.Validate(); err != nil { return err } return nil - }(); err != nil { - failures = append(failures, validate.FieldError{ - Name: "target_grade", - Error: err, - }) - } - if err := func() error { - if value, ok := s.TaskLanguage.Get(); ok { - if err := func() error { - if err := value.Validate(); err != nil { - return err - } - return nil - }(); err != nil { - return err - } + case AssessmentExpressAttemptCreateAssessmentAttemptCreate: + if err := s.AssessmentExpressAttemptCreate.Validate(); err != nil { + return err } return nil - }(); err != nil { - failures = append(failures, validate.FieldError{ - Name: "task_language", - Error: err, - }) + default: + return errors.Errorf("invalid type %q", s.Type) } - if len(failures) > 0 { - return &validate.Error{Fields: failures} - } - return nil } func (s *AssessmentAttemptHeaders) Validate() error { @@ -686,6 +499,29 @@ func (s *AssessmentAttemptHeaders) Validate() error { return nil } +func (s *AssessmentAttemptSessionStart) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.ExpectedVersion.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "expected_version", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + func (s AssessmentAttemptState) Validate() error { switch s { case "in_progress": @@ -807,6 +643,695 @@ func (s *AssessmentAvailabilityHeaders) Validate() error { return nil } +func (s *AssessmentCorrectiveAttempt) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Version.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "version", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Specialization.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: "specialization", + Error: err, + }) + } + if err := func() error { + if value, ok := s.TargetGrade.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: "target_grade", + Error: err, + }) + } + if err := func() error { + if value, ok := s.TaskLanguage.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: "task_language", + Error: err, + }) + } + if err := func() error { + if err := s.Kind.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "kind", + Error: err, + }) + } + if err := func() error { + if err := s.Mode.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "mode", + Error: err, + }) + } + if err := func() error { + if err := s.State.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "state", + Error: err, + }) + } + if err := func() error { + if err := s.Versions.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "versions", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Sessions.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: "sessions", + Error: err, + }) + } + if err := func() error { + if err := s.Progress.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "progress", + Error: err, + }) + } + if err := func() error { + if value, ok := s.CurrentItem.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: "current_item", + Error: err, + }) + } + if err := func() error { + if s.Practices == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 5, + MaxLengthSet: true, + }).ValidateLength(len(s.Practices)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Practices { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "practices", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *AssessmentCorrectiveAttemptCreate) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Kind.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "kind", + Error: err, + }) + } + if err := func() error { + if err := s.Specialization.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "specialization", + Error: err, + }) + } + if err := func() error { + if err := s.TargetGrade.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "target_grade", + Error: err, + }) + } + if err := func() error { + if value, ok := s.TaskLanguage.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: "task_language", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s AssessmentCorrectiveAttemptCreateKind) Validate() error { + switch s { + case "corrective": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s AssessmentCorrectiveAttemptKind) Validate() error { + switch s { + case "corrective": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s AssessmentCorrectiveAttemptMode) Validate() error { + switch s { + case "demo_basic": + return nil + case "adaptive": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *AssessmentCorrectiveResult) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Specialization.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "specialization", + Error: err, + }) + } + if err := func() error { + if err := s.TargetGrade.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "target_grade", + Error: err, + }) + } + if err := func() error { + if value, ok := s.TaskLanguage.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: "task_language", + Error: err, + }) + } + if err := func() error { + if err := s.Kind.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "kind", + Error: err, + }) + } + if err := func() error { + if err := s.Mode.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "mode", + Error: err, + }) + } + if err := func() error { + if err := s.Versions.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "versions", + Error: err, + }) + } + if err := func() error { + if err := s.Outcome.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "outcome", + Error: err, + }) + } + if err := func() error { + if value, ok := s.NotDeterminedReason.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: "not_determined_reason", + Error: err, + }) + } + if err := func() error { + if value, ok := s.ConfirmedGrade.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: "confirmed_grade", + Error: err, + }) + } + if err := func() error { + if value, ok := s.PreviousConfirmedGrade.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: "previous_confirmed_grade", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Strength.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: "strength", + Error: err, + }) + } + if err := func() error { + if err := s.CalibrationStatus.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "calibration_status", + Error: err, + }) + } + if err := func() error { + if s.Limitations == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 10, + MaxLengthSet: true, + }).ValidateLength(len(s.Limitations)); err != nil { + return errors.Wrap(err, "array") + } + if err := validate.UniqueItems(s.Limitations); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Limitations { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "limitations", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Uncertainty.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: "uncertainty", + Error: err, + }) + } + if err := func() error { + if value, ok := s.BasicScore.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: "basic_score", + Error: err, + }) + } + if err := func() error { + if s.Practices == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 5, + MaxLengthSet: true, + }).ValidateLength(len(s.Practices)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Practices { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "practices", + Error: err, + }) + } + if err := func() error { + if s.Gaps == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 20, + MaxLengthSet: true, + }).ValidateLength(len(s.Gaps)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Gaps { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "gaps", + Error: err, + }) + } + if err := func() error { + if err := s.Durations.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "durations", + Error: err, + }) + } + if err := func() error { + if s.NextSteps == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 5, + MaxLengthSet: true, + }).ValidateLength(len(s.NextSteps)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.NextSteps { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "next_steps", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s AssessmentCorrectiveResultKind) Validate() error { + switch s { + case "corrective": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s AssessmentCorrectiveResultMode) Validate() error { + switch s { + case "demo_basic": + return nil + case "adaptive": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + func (s *AssessmentDurations) Validate() error { if s == nil { return validate.ErrNilPointer @@ -868,6 +1393,550 @@ func (s *AssessmentDurations) Validate() error { return nil } +func (s *AssessmentExpressAttempt) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Version.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "version", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Specialization.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: "specialization", + Error: err, + }) + } + if err := func() error { + if value, ok := s.TargetGrade.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: "target_grade", + Error: err, + }) + } + if err := func() error { + if value, ok := s.TaskLanguage.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: "task_language", + Error: err, + }) + } + if err := func() error { + if err := s.Kind.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "kind", + Error: err, + }) + } + if err := func() error { + if err := s.Mode.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "mode", + Error: err, + }) + } + if err := func() error { + if err := s.State.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "state", + Error: err, + }) + } + if err := func() error { + if err := s.Versions.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "versions", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Sessions.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: "sessions", + Error: err, + }) + } + if err := func() error { + if err := s.Progress.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "progress", + Error: err, + }) + } + if err := func() error { + if value, ok := s.CurrentItem.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: "current_item", + Error: err, + }) + } + if err := func() error { + if s.Practices == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 5, + MaxLengthSet: true, + }).ValidateLength(len(s.Practices)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Practices { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "practices", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *AssessmentExpressAttemptCreate) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Kind.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "kind", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s AssessmentExpressAttemptCreateKind) Validate() error { + switch s { + case "demo_express": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s AssessmentExpressAttemptKind) Validate() error { + switch s { + case "demo_express": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s AssessmentExpressAttemptMode) Validate() error { + switch s { + case "demo_express": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *AssessmentExpressResult) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Kind.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "kind", + Error: err, + }) + } + if err := func() error { + if err := s.Mode.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "mode", + Error: err, + }) + } + if err := func() error { + if err := s.Versions.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "versions", + Error: err, + }) + } + if err := func() error { + if err := s.Outcome.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "outcome", + Error: err, + }) + } + if err := func() error { + if err := s.CalibrationStatus.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "calibration_status", + Error: err, + }) + } + if err := func() error { + if s.Limitations == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 1, + MaxLengthSet: true, + }).ValidateLength(len(s.Limitations)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Limitations { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "limitations", + Error: err, + }) + } + if err := func() error { + if s.Practices == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 0, + MaxLengthSet: true, + }).ValidateLength(len(s.Practices)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Practices { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "practices", + Error: err, + }) + } + if err := func() error { + if s.Gaps == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 0, + MaxLengthSet: true, + }).ValidateLength(len(s.Gaps)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Gaps { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "gaps", + Error: err, + }) + } + if err := func() error { + if err := s.Durations.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "durations", + Error: err, + }) + } + if err := func() error { + if s.NextSteps == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 0, + MaxLengthSet: true, + }).ValidateLength(len(s.NextSteps)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.NextSteps { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "next_steps", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 2000, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Summary)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "summary", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s AssessmentExpressResultCalibrationStatus) Validate() error { + switch s { + case "uncalibrated": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s AssessmentExpressResultKind) Validate() error { + switch s { + case "demo_express": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s AssessmentExpressResultLimitationsItem) Validate() error { + switch s { + case "demonstration_only": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s AssessmentExpressResultMode) Validate() error { + switch s { + case "demo_express": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s AssessmentExpressResultOutcome) Validate() error { + switch s { + case "demonstration": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + func (s *AssessmentFinalization) Validate() error { if s == nil { return validate.ErrNilPointer @@ -1216,17 +2285,6 @@ func (s AssessmentLimitation) Validate() error { } } -func (s AssessmentMode) Validate() error { - switch s { - case "demo_basic": - return nil - case "adaptive": - return nil - default: - return errors.Errorf("invalid value: %v", s) - } -} - func (s AssessmentNextAction) Validate() error { switch s { case "retake_same_grade": @@ -1528,7 +2586,303 @@ func (s *AssessmentProgress) Validate() error { return nil } -func (s *AssessmentResult) Validate() error { +func (s *AssessmentQualifiedAttempt) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Version.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "version", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Specialization.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: "specialization", + Error: err, + }) + } + if err := func() error { + if value, ok := s.TargetGrade.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: "target_grade", + Error: err, + }) + } + if err := func() error { + if value, ok := s.TaskLanguage.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: "task_language", + Error: err, + }) + } + if err := func() error { + if err := s.Kind.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "kind", + Error: err, + }) + } + if err := func() error { + if err := s.Mode.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "mode", + Error: err, + }) + } + if err := func() error { + if err := s.State.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "state", + Error: err, + }) + } + if err := func() error { + if err := s.Versions.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "versions", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Sessions.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: "sessions", + Error: err, + }) + } + if err := func() error { + if err := s.Progress.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "progress", + Error: err, + }) + } + if err := func() error { + if value, ok := s.CurrentItem.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: "current_item", + Error: err, + }) + } + if err := func() error { + if s.Practices == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 5, + MaxLengthSet: true, + }).ValidateLength(len(s.Practices)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Practices { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "practices", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *AssessmentQualifiedAttemptCreate) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Kind.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "kind", + Error: err, + }) + } + if err := func() error { + if err := s.Specialization.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "specialization", + Error: err, + }) + } + if err := func() error { + if err := s.TargetGrade.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "target_grade", + Error: err, + }) + } + if err := func() error { + if value, ok := s.TaskLanguage.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: "task_language", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s AssessmentQualifiedAttemptCreateKind) Validate() error { + switch s { + case "root": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s AssessmentQualifiedAttemptKind) Validate() error { + switch s { + case "root": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s AssessmentQualifiedAttemptMode) Validate() error { + switch s { + case "demo_basic": + return nil + case "adaptive": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *AssessmentQualifiedResult) Validate() error { if s == nil { return validate.ErrNilPointer } @@ -1574,6 +2928,17 @@ func (s *AssessmentResult) Validate() error { Error: err, }) } + if err := func() error { + if err := s.Kind.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "kind", + Error: err, + }) + } if err := func() error { if err := s.Mode.Validate(); err != nil { return err @@ -1890,6 +3255,59 @@ func (s *AssessmentResult) Validate() error { return nil } +func (s AssessmentQualifiedResultKind) Validate() error { + switch s { + case "root": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s AssessmentQualifiedResultMode) Validate() error { + switch s { + case "demo_basic": + return nil + case "adaptive": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s AssessmentRealMode) Validate() error { + switch s { + case "demo_basic": + return nil + case "adaptive": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s AssessmentResult) Validate() error { + switch s.Type { + case AssessmentQualifiedResultAssessmentResult: + if err := s.AssessmentQualifiedResult.Validate(); err != nil { + return err + } + return nil + case AssessmentCorrectiveResultAssessmentResult: + if err := s.AssessmentCorrectiveResult.Validate(); err != nil { + return err + } + return nil + case AssessmentExpressResultAssessmentResult: + if err := s.AssessmentExpressResult.Validate(); err != nil { + return err + } + return nil + default: + return errors.Errorf("invalid type %q", s.Type) + } +} + func (s *AssessmentResultHeaders) Validate() error { if s == nil { return validate.ErrNilPointer @@ -16737,6 +18155,62 @@ func (s StackTag) Validate() error { return nil } +func (s *StartMyAssessmentAttemptSessionBadRequest) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *StartMyAssessmentAttemptSessionConflict) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *StartMyAssessmentAttemptSessionForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *StartMyAssessmentAttemptSessionNotFound) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *StartMyAssessmentAttemptSessionPreconditionFailed) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *StartMyAssessmentAttemptSessionUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *StartMyAssessmentAttemptSessionUnprocessableEntity) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + func (s *StringAnswer) Validate() error { if s == nil { return validate.ErrNilPointer diff --git a/backend/internal/adapter/primary/http/router_test.go b/backend/internal/adapter/primary/http/router_test.go index 99db77a..c61c5d0 100644 --- a/backend/internal/adapter/primary/http/router_test.go +++ b/backend/internal/adapter/primary/http/router_test.go @@ -573,7 +573,9 @@ const ( assessmentFinalizePath = assessmentAttemptPath + "/finalize" assessmentResultPath = assessmentAttemptPath + "/result" assessmentItemID = "01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d01" - validAttemptCreate = `{"specialization":"backend","target_grade":"junior","task_language":"go"}` + validAttemptCreate = `{"kind":"root","specialization":"backend","target_grade":"junior","task_language":"go"}` + validCorrectiveCreate = `{"kind":"corrective","specialization":"backend","target_grade":"middle","task_language":"go","root_attempt_id":"01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b"}` + validExpressCreate = `{"kind":"demo_express"}` ) // assessmentAnswerBody returns a SubmitMyAssessmentAnswer body for version 1 @@ -605,9 +607,27 @@ func TestAssessmentSchemaValidationPrecedesImplementation(t *testing.T) { name: "create", request: identityRequest{method: http.MethodPost, path: assessmentAttemptsPath, body: validAttemptCreate, headers: command}, }, + { + name: "create a corrective attempt in an existing chain", + request: identityRequest{method: http.MethodPost, path: assessmentAttemptsPath, body: validCorrectiveCreate, headers: command}, + }, + { + name: "create a demo express training attempt", + request: identityRequest{method: http.MethodPost, path: assessmentAttemptsPath, body: validExpressCreate, headers: command}, + }, + { + name: "create without a kind discriminator", + request: identityRequest{method: http.MethodPost, path: assessmentAttemptsPath, body: `{"specialization":"backend","target_grade":"junior","task_language":"go"}`, headers: command}, + location: api.ProblemFieldLocationBody, pointer: "", code: "invalid", + }, + { + name: "express create with a real-assessment grade", + request: identityRequest{method: http.MethodPost, path: assessmentAttemptsPath, body: `{"kind":"demo_express","target_grade":"junior"}`, headers: command}, + location: api.ProblemFieldLocationBody, pointer: "", code: "invalid", + }, { name: "create without a task language choice", - request: identityRequest{method: http.MethodPost, path: assessmentAttemptsPath, body: `{"specialization":"network_engineer","target_grade":"middle","task_language":null}`, headers: command}, + request: identityRequest{method: http.MethodPost, path: assessmentAttemptsPath, body: `{"kind":"root","specialization":"network_engineer","target_grade":"middle","task_language":null}`, headers: command}, }, { // The server picks the mode from the published bank. diff --git a/frontend/src/shared/api/assessment-contract.test.ts b/frontend/src/shared/api/assessment-contract.test.ts index 16ab4c2..40f3f50 100644 --- a/frontend/src/shared/api/assessment-contract.test.ts +++ b/frontend/src/shared/api/assessment-contract.test.ts @@ -1,6 +1,7 @@ import { describe, expect, expectTypeOf, it } from "vitest"; import { submitMyAssessmentAnswer } from "./endpoints/assessment/assessment"; import { + AssessmentAttemptCreate, AssessmentAnswerSubmission, AssessmentItem, ItemContent, @@ -28,6 +29,46 @@ const bodySchemas = [ ["SubmitMyAssessmentAnswerBody", SubmitMyAssessmentAnswerBody], ] as const; +describe("generated assessment creation variants", () => { + it("selects root, corrective, or training shape by kind", () => { + const root = AssessmentAttemptCreate.parse({ + kind: "root", + specialization: "backend", + target_grade: "junior", + task_language: "go", + }); + const corrective = AssessmentAttemptCreate.parse({ + kind: "corrective", + specialization: "backend", + target_grade: "junior", + task_language: "go", + root_attempt_id: "01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d", + }); + const express = AssessmentAttemptCreate.parse({ kind: "demo_express" }); + + expect(root.kind).toBe("root"); + expect(root).not.toHaveProperty("mode"); + expect(corrective.kind).toBe("corrective"); + expect(corrective).toHaveProperty("root_attempt_id"); + expect(express).toEqual({ kind: "demo_express" }); + expect(AssessmentAttemptCreate.safeParse({ mode: "demo_express" }).success).toBe(false); + expect( + AssessmentAttemptCreate.safeParse({ + kind: "corrective", + specialization: "backend", + target_grade: "junior", + task_language: "go", + }).success, + ).toBe(false); + }); + + it("keeps express creation free of qualification fields in its type", () => { + type ExpressCreate = Extract; + + expectTypeOf().toEqualTypeOf<"kind">(); + }); +}); + describe.each(bodySchemas)("generated %s", (_name, schema) => { it.each(Object.entries(answers))("accepts a %s answer", (format, answer) => { const parsed = schema.parse({ expected_version: 1, item_id: itemId, answer }); diff --git a/frontend/src/shared/api/assessment-response-contract.test.ts b/frontend/src/shared/api/assessment-response-contract.test.ts index cfd1fb7..571dc8f 100644 --- a/frontend/src/shared/api/assessment-response-contract.test.ts +++ b/frontend/src/shared/api/assessment-response-contract.test.ts @@ -12,6 +12,9 @@ const demoResult = { attempt_id: "01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b", specialization: "backend", target_grade: "junior", + kind: "root", + root_attempt_id: null, + chain_deadline: null, task_language: "go", mode: "demo_basic", versions: { @@ -35,12 +38,52 @@ const demoResult = { decided_at: "2026-10-08T10:24:00Z", }; +const correctiveResult = { + ...demoResult, + target_grade: "middle", + kind: "corrective", + root_attempt_id: "01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d", + chain_deadline: "2026-11-23T09:00:00Z", +}; + +const expressResult = { + attempt_id: "01928f7f-9999-7a2b-8c3d-4e5f6a7b8c9d", + specialization: null, + target_grade: null, + task_language: null, + kind: "demo_express", + mode: "demo_express", + versions: { + policy_version: 1, + bank_version: "express-demo.2026-10.1", + algorithm_version: "express-interactive.1", + }, + outcome: "demonstration", + not_determined_reason: null, + confirmed_grade: null, + previous_confirmed_grade: null, + strength: null, + calibration_status: "uncalibrated", + limitations: ["demonstration_only"], + uncertainty: null, + basic_score: null, + practices: [], + gaps: [], + durations: { items_seconds: 260, practice_seconds: null }, + next_steps: [], + summary: "This short run demonstrates the task flow.", + decided_at: "2026-10-08T10:05:00Z", +}; + const pendingPracticeAttempt = { id: "01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d", version: 7, + kind: "root", specialization: "backend", target_grade: "middle", task_language: "python", + root_attempt_id: null, + chain_deadline: null, mode: "adaptive", state: "practice_pending", versions: { @@ -66,6 +109,13 @@ const pendingPracticeAttempt = { ], }; +const correctivePracticeAttempt = { + ...pendingPracticeAttempt, + kind: "corrective", + root_attempt_id: "01928f7b-2222-7a2b-8c3d-4e5f6a7b8c9d", + chain_deadline: "2026-11-23T09:00:00Z", +}; + describe("generated AssessmentResult", () => { it("accepts a demo result without uncertainty or strength numbers", () => { const parsed = AssessmentResult.parse(demoResult); @@ -75,6 +125,55 @@ describe("generated AssessmentResult", () => { expect(parsed.strength).toBeNull(); }); + it("requires an explicit null pair for a root result", () => { + expect(AssessmentResult.parse(demoResult)).toMatchObject({ + kind: "root", + root_attempt_id: null, + chain_deadline: null, + }); + + const missingPair: Record = { ...demoResult }; + delete missingPair.chain_deadline; + + expect(AssessmentResult.safeParse(missingPair).success).toBe(false); + expect( + AssessmentResult.safeParse({ + ...demoResult, + root_attempt_id: "01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d", + }).success, + ).toBe(false); + }); + + it("requires both correction-chain values together", () => { + expect(AssessmentResult.parse(correctiveResult).kind).toBe("corrective"); + expect(AssessmentResult.safeParse({ ...correctiveResult, root_attempt_id: null }).success).toBe( + false, + ); + expect(AssessmentResult.safeParse({ ...correctiveResult, chain_deadline: null }).success).toBe( + false, + ); + }); + + it("keeps demo_express training results from confirming qualification", () => { + const parsed = AssessmentResult.parse(expressResult); + + expect(parsed).toMatchObject({ + kind: "demo_express", + outcome: "demonstration", + confirmed_grade: null, + specialization: null, + target_grade: null, + uncertainty: null, + basic_score: null, + }); + expect( + AssessmentResult.safeParse({ ...expressResult, confirmed_grade: "junior" }).success, + ).toBe(false); + expect(AssessmentResult.safeParse({ ...expressResult, outcome: "confirmed" }).success).toBe( + false, + ); + }); + it("rejects a result without calibration_status", () => { const result: Record = { ...demoResult }; delete result.calibration_status; @@ -82,18 +181,16 @@ describe("generated AssessmentResult", () => { const parsed = AssessmentResult.safeParse(result); expect(parsed.success).toBe(false); - expect(parsed.error?.issues).toEqual([ - expect.objectContaining({ path: ["calibration_status"] }), - ]); + expect(parsed.error?.issues[0]).toMatchObject({ code: "invalid_union" }); + expect(JSON.stringify(parsed.error?.issues)).toContain('"calibration_status"'); }); it("rejects an unknown calibration status", () => { const parsed = AssessmentResult.safeParse({ ...demoResult, calibration_status: "estimated" }); expect(parsed.success).toBe(false); - expect(parsed.error?.issues).toEqual([ - expect.objectContaining({ code: "invalid_value", path: ["calibration_status"] }), - ]); + expect(parsed.error?.issues[0]).toMatchObject({ code: "invalid_union" }); + expect(JSON.stringify(parsed.error?.issues)).toContain('"calibration_status"'); }); }); @@ -105,18 +202,28 @@ describe("generated AssessmentAttempt", () => { expect(parsed.practices[0]?.verdict).toBeNull(); }); + it("requires both correction-chain values together", () => { + expect(AssessmentAttempt.parse(correctivePracticeAttempt).kind).toBe("corrective"); + expect( + AssessmentAttempt.safeParse({ ...correctivePracticeAttempt, root_attempt_id: null }).success, + ).toBe(false); + expect( + AssessmentAttempt.safeParse({ ...correctivePracticeAttempt, chain_deadline: null }).success, + ).toBe(false); + }); + it("rejects an unknown attempt state", () => { const parsed = AssessmentAttempt.safeParse({ ...pendingPracticeAttempt, state: "paused" }); expect(parsed.success).toBe(false); - expect(parsed.error?.issues).toEqual([ - expect.objectContaining({ code: "invalid_value", path: ["state"] }), - ]); + expect(parsed.error?.issues[0]).toMatchObject({ code: "invalid_union" }); + expect(JSON.stringify(parsed.error?.issues)).toContain('"state"'); }); }); it("types allow null instead of fabricated numbers", () => { type Practice = AssessmentAttempt["practices"][number]; + type ExpressResult = Extract; expectTypeOf().toExtend(); expectTypeOf().toExtend(); @@ -124,4 +231,9 @@ it("types allow null instead of fabricated numbers", () => { expectTypeOf().toExtend(); expectTypeOf<"uncalibrated">().toExtend(); expectTypeOf<"pending">().toExtend(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf< + Extract + >().toEqualTypeOf(); }); diff --git a/frontend/src/shared/api/endpoints/assessment/assessment.msw.ts b/frontend/src/shared/api/endpoints/assessment/assessment.msw.ts index 3a72e12..58f75e1 100644 --- a/frontend/src/shared/api/endpoints/assessment/assessment.msw.ts +++ b/frontend/src/shared/api/endpoints/assessment/assessment.msw.ts @@ -23,7 +23,13 @@ import type { import type { AssessmentAttempt, AssessmentAvailability, + AssessmentCorrectiveAttempt, + AssessmentCorrectiveResult, + AssessmentExpressAttempt, + AssessmentExpressResult, AssessmentItem, + AssessmentQualifiedAttempt, + AssessmentQualifiedResult, AssessmentResult, AssessmentSessions, AssessmentUncertainty, @@ -61,7 +67,13 @@ export const getCreateMyAssessmentAttemptResponseAssessmentItemMock = (overrideR export const getCreateMyAssessmentAttemptResponsePracticeVerdictMock = (overrideResponse: Partial = {}): 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 getCreateMyAssessmentAttemptResponseMock = (overrideResponse: Partial> = {}): AssessmentAttempt => ({id: faker.string.uuid(), version: faker.number.int({min: 1}), 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), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(['python','go'] as const),null,]), mode: faker.helpers.arrayElement(['demo_basic','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,])})), ...overrideResponse}) +export const getCreateMyAssessmentAttemptResponseAssessmentQualifiedAttemptMock = (overrideResponse: Partial = {}): 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 getCreateMyAssessmentAttemptResponseAssessmentCorrectiveAttemptMock = (overrideResponse: Partial = {}): 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 getCreateMyAssessmentAttemptResponseAssessmentExpressAttemptMock = (overrideResponse: Partial = {}): 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 getCreateMyAssessmentAttemptResponseMock = (): AssessmentAttempt => (faker.helpers.arrayElement([{...getCreateMyAssessmentAttemptResponseAssessmentQualifiedAttemptMock()},{...getCreateMyAssessmentAttemptResponseAssessmentCorrectiveAttemptMock()},{...getCreateMyAssessmentAttemptResponseAssessmentExpressAttemptMock()},])) export const getGetMyAssessmentAttemptResponseAssessmentSessionsMock = (overrideResponse: Partial = {}): AssessmentSessions => ({...{used: faker.number.int({min: 1, max: 10}), max: faker.number.int({min: 1, max: 10}), idle_timeout_seconds: faker.number.int({min: 60, max: 86400})}, ...overrideResponse}); @@ -83,7 +95,41 @@ export const getGetMyAssessmentAttemptResponseAssessmentItemMock = (overrideResp export const getGetMyAssessmentAttemptResponsePracticeVerdictMock = (overrideResponse: Partial = {}): 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 getGetMyAssessmentAttemptResponseMock = (overrideResponse: Partial> = {}): AssessmentAttempt => ({id: faker.string.uuid(), version: faker.number.int({min: 1}), 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), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(['python','go'] as const),null,]), mode: faker.helpers.arrayElement(['demo_basic','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,])})), ...overrideResponse}) +export const getGetMyAssessmentAttemptResponseAssessmentQualifiedAttemptMock = (overrideResponse: Partial = {}): 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 getGetMyAssessmentAttemptResponseAssessmentCorrectiveAttemptMock = (overrideResponse: Partial = {}): 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 getGetMyAssessmentAttemptResponseAssessmentExpressAttemptMock = (overrideResponse: Partial = {}): 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 getGetMyAssessmentAttemptResponseMock = (): AssessmentAttempt => (faker.helpers.arrayElement([{...getGetMyAssessmentAttemptResponseAssessmentQualifiedAttemptMock()},{...getGetMyAssessmentAttemptResponseAssessmentCorrectiveAttemptMock()},{...getGetMyAssessmentAttemptResponseAssessmentExpressAttemptMock()},])) + +export const getStartMyAssessmentAttemptSessionResponseAssessmentSessionsMock = (overrideResponse: Partial = {}): AssessmentSessions => ({...{used: faker.number.int({min: 1, max: 10}), max: faker.number.int({min: 1, max: 10}), idle_timeout_seconds: faker.number.int({min: 60, max: 86400})}, ...overrideResponse}); + +export const getStartMyAssessmentAttemptSessionResponseChoiceItemContentMock = (overrideResponse: Partial = {}): ChoiceItemContent => ({...{format: faker.helpers.arrayElement(['choice'] as const), options: Array.from({ length: faker.number.int({min: 2, max: 10}) }, (_, i) => i + 1).map(() => ({id: fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 32}), text: faker.string.alpha({length: {min: 1, max: 2000}})})), multiple: faker.datatype.boolean()}, ...overrideResponse}); + +export const getStartMyAssessmentAttemptSessionResponseNumberItemContentMock = (overrideResponse: Partial = {}): NumberItemContent => ({...{format: faker.helpers.arrayElement(['number'] as const), unit: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 32}}), null])}, ...overrideResponse}); + +export const getStartMyAssessmentAttemptSessionResponseStringItemContentMock = (overrideResponse: Partial = {}): StringItemContent => ({...{format: faker.helpers.arrayElement(['string'] as const), max_length: faker.number.int({min: 1, max: 500})}, ...overrideResponse}); + +export const getStartMyAssessmentAttemptSessionResponseOrderItemContentMock = (overrideResponse: Partial = {}): OrderItemContent => ({...{format: faker.helpers.arrayElement(['order'] as const), elements: Array.from({ length: faker.number.int({min: 2, max: 20}) }, (_, i) => i + 1).map(() => ({id: fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 32}), text: faker.string.alpha({length: {min: 1, max: 2000}})}))}, ...overrideResponse}); + +export const getStartMyAssessmentAttemptSessionResponseFindErrorItemContentMock = (overrideResponse: Partial = {}): FindErrorItemContent => ({...{format: faker.helpers.arrayElement(['find_error'] as const), syntax: faker.helpers.arrayElement([fakeFromPattern("^[a-z0-9_+-]+$", {minLength: 1, maxLength: 32}), null]), lines: Array.from({ length: faker.number.int({min: 1, max: 500}) }, (_, i) => i + 1).map(() => ({number: faker.number.int({min: 1, max: 500}), text: faker.string.alpha({length: {min: 10, max: 1000}})})), max_selections: faker.number.int({min: 1, max: 10})}, ...overrideResponse}); + +export const getStartMyAssessmentAttemptSessionResponseConfigurationItemContentMock = (overrideResponse: Partial = {}): ConfigurationItemContent => ({...{format: faker.helpers.arrayElement(['configuration'] as const), syntax: fakeFromPattern("^[a-z0-9_+-]+$", {minLength: 1, maxLength: 32}), initial_config: faker.string.alpha({length: {min: 10, max: 20000}}), max_length: faker.number.int({min: 1, max: 20000})}, ...overrideResponse}); + +export const getStartMyAssessmentAttemptSessionResponsePracticeItemContentMock = (overrideResponse: Partial = {}): PracticeItemContent => ({...{format: faker.helpers.arrayElement(['practice'] as const), languages: faker.helpers.arrayElements(['python','go'] as const), public_examples: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({input: faker.string.alpha({length: {min: 10, max: 10000}}), expected_output: faker.string.alpha({length: {min: 10, max: 10000}})})), max_source_length: faker.number.int({min: 1, max: 65536})}, ...overrideResponse}); + +export const getStartMyAssessmentAttemptSessionResponseAssessmentItemMock = (overrideResponse: Partial = {}): AssessmentItem => ({...{id: faker.string.uuid(), sequence: faker.number.int({min: 1, max: 100}), prompt: faker.string.alpha({length: {min: 1, max: 20000}}), content: faker.helpers.arrayElement([{...getStartMyAssessmentAttemptSessionResponseChoiceItemContentMock()},{...getStartMyAssessmentAttemptSessionResponseNumberItemContentMock()},{...getStartMyAssessmentAttemptSessionResponseStringItemContentMock()},{...getStartMyAssessmentAttemptSessionResponseOrderItemContentMock()},{...getStartMyAssessmentAttemptSessionResponseFindErrorItemContentMock()},{...getStartMyAssessmentAttemptSessionResponseConfigurationItemContentMock()},{...getStartMyAssessmentAttemptSessionResponsePracticeItemContentMock()},])}, ...overrideResponse}); + +export const getStartMyAssessmentAttemptSessionResponsePracticeVerdictMock = (overrideResponse: Partial = {}): 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 => ({...{...{...{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 getStartMyAssessmentAttemptSessionResponseAssessmentCorrectiveAttemptMock = (overrideResponse: Partial = {}): 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 getStartMyAssessmentAttemptSessionResponseAssessmentExpressAttemptMock = (overrideResponse: Partial = {}): 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 getStartMyAssessmentAttemptSessionResponseMock = (): AssessmentAttempt => (faker.helpers.arrayElement([{...getStartMyAssessmentAttemptSessionResponseAssessmentQualifiedAttemptMock()},{...getStartMyAssessmentAttemptSessionResponseAssessmentCorrectiveAttemptMock()},{...getStartMyAssessmentAttemptSessionResponseAssessmentExpressAttemptMock()},])) export const getSubmitMyAssessmentAnswerResponseAssessmentSessionsMock = (overrideResponse: Partial = {}): AssessmentSessions => ({...{used: faker.number.int({min: 1, max: 10}), max: faker.number.int({min: 1, max: 10}), idle_timeout_seconds: faker.number.int({min: 60, max: 86400})}, ...overrideResponse}); @@ -105,7 +151,13 @@ export const getSubmitMyAssessmentAnswerResponseAssessmentItemMock = (overrideRe export const getSubmitMyAssessmentAnswerResponsePracticeVerdictMock = (overrideResponse: Partial = {}): 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 getSubmitMyAssessmentAnswerResponseMock = (overrideResponse: Partial> = {}): AssessmentAttempt => ({id: faker.string.uuid(), version: faker.number.int({min: 1}), 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), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(['python','go'] as const),null,]), mode: faker.helpers.arrayElement(['demo_basic','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,])})), ...overrideResponse}) +export const getSubmitMyAssessmentAnswerResponseAssessmentQualifiedAttemptMock = (overrideResponse: Partial = {}): 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 getSubmitMyAssessmentAnswerResponseAssessmentCorrectiveAttemptMock = (overrideResponse: Partial = {}): 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 getSubmitMyAssessmentAnswerResponseAssessmentExpressAttemptMock = (overrideResponse: Partial = {}): 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 getSubmitMyAssessmentAnswerResponseMock = (): AssessmentAttempt => (faker.helpers.arrayElement([{...getSubmitMyAssessmentAnswerResponseAssessmentQualifiedAttemptMock()},{...getSubmitMyAssessmentAnswerResponseAssessmentCorrectiveAttemptMock()},{...getSubmitMyAssessmentAnswerResponseAssessmentExpressAttemptMock()},])) export const getFinalizeMyAssessmentAttemptResponseAssessmentSessionsMock = (overrideResponse: Partial = {}): AssessmentSessions => ({...{used: faker.number.int({min: 1, max: 10}), max: faker.number.int({min: 1, max: 10}), idle_timeout_seconds: faker.number.int({min: 60, max: 86400})}, ...overrideResponse}); @@ -127,13 +179,25 @@ export const getFinalizeMyAssessmentAttemptResponseAssessmentItemMock = (overrid export const getFinalizeMyAssessmentAttemptResponsePracticeVerdictMock = (overrideResponse: Partial = {}): 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 getFinalizeMyAssessmentAttemptResponseMock = (overrideResponse: Partial> = {}): AssessmentAttempt => ({id: faker.string.uuid(), version: faker.number.int({min: 1}), 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), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(['python','go'] as const),null,]), mode: faker.helpers.arrayElement(['demo_basic','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,])})), ...overrideResponse}) +export const getFinalizeMyAssessmentAttemptResponseAssessmentQualifiedAttemptMock = (overrideResponse: Partial = {}): 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 getFinalizeMyAssessmentAttemptResponseAssessmentCorrectiveAttemptMock = (overrideResponse: Partial = {}): 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 getFinalizeMyAssessmentAttemptResponseAssessmentExpressAttemptMock = (overrideResponse: Partial = {}): 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 getFinalizeMyAssessmentAttemptResponseMock = (): AssessmentAttempt => (faker.helpers.arrayElement([{...getFinalizeMyAssessmentAttemptResponseAssessmentQualifiedAttemptMock()},{...getFinalizeMyAssessmentAttemptResponseAssessmentCorrectiveAttemptMock()},{...getFinalizeMyAssessmentAttemptResponseAssessmentExpressAttemptMock()},])) export const getGetMyAssessmentResultResponseAssessmentUncertaintyMock = (overrideResponse: Partial = {}): AssessmentUncertainty => ({...{theta: faker.number.float({fractionDigits: 2}), standard_error: faker.number.float({min: 0, fractionDigits: 2}), interval_95: {low: faker.number.float({fractionDigits: 2}), high: faker.number.float({fractionDigits: 2})}, p_grade: faker.number.float({min: 0, max: 1, fractionDigits: 2})}, ...overrideResponse}); export const getGetMyAssessmentResultResponseBasicScoreMock = (overrideResponse: Partial = {}): BasicScore => ({...{points: faker.number.int({min: 0}), max_points: faker.number.int({min: 1}), pass_points: faker.number.int({min: 1})}, ...overrideResponse}); -export const getGetMyAssessmentResultResponseMock = (overrideResponse: Partial> = {}): AssessmentResult => ({attempt_id: faker.string.uuid(), 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), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(['python','go'] as const),null,]), mode: faker.helpers.arrayElement(['demo_basic','adaptive'] 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})}, outcome: faker.helpers.arrayElement(['confirmed','not_confirmed','not_determined'] as const), not_determined_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['expired','practice_incomplete','insufficient_bank','sandbox_unavailable'] as const),null,]), confirmed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), previous_confirmed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), strength: faker.helpers.arrayElement([faker.helpers.arrayElement(['high','medium'] as const),null,]), calibration_status: faker.helpers.arrayElement(['uncalibrated','calibrated'] as const), limitations: faker.helpers.arrayElements(['uncalibrated_thresholds','demo_bank','practice_not_included','unproctored'] as const), uncertainty: faker.helpers.arrayElement([{...getGetMyAssessmentResultResponseAssessmentUncertaintyMock()},null,]), basic_score: faker.helpers.arrayElement([{...getGetMyAssessmentResultResponseBasicScoreMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(['main','additional'] as const), verdict: {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()}))}})), gaps: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => ({domain: fakeFromPattern("^[a-z0-9_]+$", {minLength: 1, maxLength: 64}), title: faker.string.alpha({length: {min: 1, max: 200}})})), durations: {items_seconds: faker.number.int({min: 0}), practice_seconds: faker.helpers.arrayElement([faker.number.int({min: 0}), null])}, next_steps: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({action: faker.helpers.arrayElement(['retake_same_grade','take_lower_grade','accept_lower_grade','take_higher_grade'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), available_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])})), decided_at: faker.date.past().toISOString().slice(0, 19) + 'Z', ...overrideResponse}) +export const getGetMyAssessmentResultResponseAssessmentQualifiedResultMock = (overrideResponse: Partial = {}): AssessmentQualifiedResult => ({...{...{...{attempt_id: faker.string.uuid(), 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.helpers.arrayElement([faker.string.uuid(),null,]), chain_deadline: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(['python','go'] as const),null,]), kind: faker.helpers.arrayElement(['root','corrective'] as const), mode: faker.helpers.arrayElement(['demo_basic','adaptive'] 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})}, outcome: faker.helpers.arrayElement(['confirmed','not_confirmed','not_determined'] as const), not_determined_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['expired','practice_incomplete','insufficient_bank','sandbox_unavailable'] as const),null,]), confirmed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), previous_confirmed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), strength: faker.helpers.arrayElement([faker.helpers.arrayElement(['high','medium'] as const),null,]), calibration_status: faker.helpers.arrayElement(['uncalibrated','calibrated'] as const), limitations: faker.helpers.arrayElements(['uncalibrated_thresholds','demo_bank','practice_not_included','unproctored'] as const), uncertainty: faker.helpers.arrayElement([{...getGetMyAssessmentResultResponseAssessmentUncertaintyMock()},null,]), basic_score: faker.helpers.arrayElement([{...getGetMyAssessmentResultResponseBasicScoreMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(['main','additional'] as const), verdict: {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()}))}})), gaps: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => ({domain: fakeFromPattern("^[a-z0-9_]+$", {minLength: 1, maxLength: 64}), title: faker.string.alpha({length: {min: 1, max: 200}})})), durations: {items_seconds: faker.number.int({min: 0}), practice_seconds: faker.helpers.arrayElement([faker.number.int({min: 0}), null])}, next_steps: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({action: faker.helpers.arrayElement(['retake_same_grade','take_lower_grade','accept_lower_grade','take_higher_grade'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), available_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])})), decided_at: faker.date.past().toISOString().slice(0, 19) + 'Z'},...{kind: faker.helpers.arrayElement(['root'] as const), root_attempt_id: null, chain_deadline: null},}, kind: faker.helpers.arrayElement(['root'] as const)}, ...overrideResponse}); + +export const getGetMyAssessmentResultResponseAssessmentCorrectiveResultMock = (overrideResponse: Partial = {}): AssessmentCorrectiveResult => ({...{...{...{attempt_id: faker.string.uuid(), 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.helpers.arrayElement([faker.string.uuid(),null,]), chain_deadline: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(['python','go'] as const),null,]), kind: faker.helpers.arrayElement(['root','corrective'] as const), mode: faker.helpers.arrayElement(['demo_basic','adaptive'] 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})}, outcome: faker.helpers.arrayElement(['confirmed','not_confirmed','not_determined'] as const), not_determined_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['expired','practice_incomplete','insufficient_bank','sandbox_unavailable'] as const),null,]), confirmed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), previous_confirmed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), strength: faker.helpers.arrayElement([faker.helpers.arrayElement(['high','medium'] as const),null,]), calibration_status: faker.helpers.arrayElement(['uncalibrated','calibrated'] as const), limitations: faker.helpers.arrayElements(['uncalibrated_thresholds','demo_bank','practice_not_included','unproctored'] as const), uncertainty: faker.helpers.arrayElement([{...getGetMyAssessmentResultResponseAssessmentUncertaintyMock()},null,]), basic_score: faker.helpers.arrayElement([{...getGetMyAssessmentResultResponseBasicScoreMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(['main','additional'] as const), verdict: {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()}))}})), gaps: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => ({domain: fakeFromPattern("^[a-z0-9_]+$", {minLength: 1, maxLength: 64}), title: faker.string.alpha({length: {min: 1, max: 200}})})), durations: {items_seconds: faker.number.int({min: 0}), practice_seconds: faker.helpers.arrayElement([faker.number.int({min: 0}), null])}, next_steps: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({action: faker.helpers.arrayElement(['retake_same_grade','take_lower_grade','accept_lower_grade','take_higher_grade'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), available_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])})), decided_at: faker.date.past().toISOString().slice(0, 19) + 'Z'},...{kind: faker.helpers.arrayElement(['corrective'] 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 getGetMyAssessmentResultResponseAssessmentExpressResultMock = (overrideResponse: Partial = {}): AssessmentExpressResult => ({...{attempt_id: faker.string.uuid(), specialization: null, target_grade: null, task_language: null, kind: faker.helpers.arrayElement(['demo_express'] as const), mode: faker.helpers.arrayElement(['demo_express'] 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})}, outcome: faker.helpers.arrayElement(['demonstration'] as const), not_determined_reason: null, confirmed_grade: null, previous_confirmed_grade: null, strength: null, calibration_status: faker.helpers.arrayElement(['uncalibrated'] as const), limitations: faker.helpers.arrayElements(['demonstration_only'] as const), uncertainty: null, basic_score: null, practices: Array.from({ length: faker.number.int({min: 0, max: 0}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(['main','additional'] as const), verdict: {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()}))}})), gaps: Array.from({ length: faker.number.int({min: 0, max: 0}) }, (_, i) => i + 1).map(() => ({domain: fakeFromPattern("^[a-z0-9_]+$", {minLength: 1, maxLength: 64}), title: faker.string.alpha({length: {min: 1, max: 200}})})), durations: {items_seconds: faker.number.int({min: 0}), practice_seconds: faker.helpers.arrayElement([faker.number.int({min: 0}), null])}, next_steps: Array.from({ length: faker.number.int({min: 0, max: 0}) }, (_, i) => i + 1).map(() => ({action: faker.helpers.arrayElement(['retake_same_grade','take_lower_grade','accept_lower_grade','take_higher_grade'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), available_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])})), summary: faker.string.alpha({length: {min: 1, max: 2000}}), decided_at: faker.date.past().toISOString().slice(0, 19) + 'Z'}, ...overrideResponse}); + +export const getGetMyAssessmentResultResponseMock = (): AssessmentResult => (faker.helpers.arrayElement([{...getGetMyAssessmentResultResponseAssessmentQualifiedResultMock()},{...getGetMyAssessmentResultResponseAssessmentCorrectiveResultMock()},{...getGetMyAssessmentResultResponseAssessmentExpressResultMock()},])) export const getGetMyAssessmentAvailabilityMockHandler = (overrideResponse?: AssessmentAvailability | ((info: Parameters[1]>[0]) => Promise | AssessmentAvailability), options?: RequestHandlerOptions) => { @@ -172,6 +236,18 @@ export const getGetMyAssessmentAttemptMockHandler = (overrideResponse?: Assessme }, options) } +export const getStartMyAssessmentAttemptSessionMockHandler = (overrideResponse?: AssessmentAttempt | ((info: Parameters[1]>[0]) => Promise | AssessmentAttempt), options?: RequestHandlerOptions) => { + return http.post('*/api/v1/me/assessment-attempts/:attemptId/sessions', async (info: Parameters[1]>[0]) => { + + + return HttpResponse.json(overrideResponse !== undefined + ? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse) + : getStartMyAssessmentAttemptSessionResponseMock(), + { status: 200 + }) + }, options) +} + export const getSubmitMyAssessmentAnswerMockHandler = (overrideResponse?: AssessmentAttempt | ((info: Parameters[1]>[0]) => Promise | AssessmentAttempt), options?: RequestHandlerOptions) => { return http.post('*/api/v1/me/assessment-attempts/:attemptId/answers', async (info: Parameters[1]>[0]) => { @@ -211,6 +287,7 @@ export const getAssessmentMock = () => [ getGetMyAssessmentAvailabilityMockHandler(), getCreateMyAssessmentAttemptMockHandler(), getGetMyAssessmentAttemptMockHandler(), + getStartMyAssessmentAttemptSessionMockHandler(), getSubmitMyAssessmentAnswerMockHandler(), getFinalizeMyAssessmentAttemptMockHandler(), getGetMyAssessmentResultMockHandler() diff --git a/frontend/src/shared/api/endpoints/assessment/assessment.ts b/frontend/src/shared/api/endpoints/assessment/assessment.ts index 4b66970..7365d04 100644 --- a/frontend/src/shared/api/endpoints/assessment/assessment.ts +++ b/frontend/src/shared/api/endpoints/assessment/assessment.ts @@ -27,12 +27,14 @@ import type { AssessmentAnswerSubmission, AssessmentAttempt, AssessmentAttemptCreate, + AssessmentAttemptSessionStart, AssessmentAvailability, AssessmentFinalization, AssessmentResult, CreateMyAssessmentAttemptHeaders, FinalizeMyAssessmentAttemptHeaders, Problem, + StartMyAssessmentAttemptSessionHeaders, SubmitMyAssessmentAnswerHeaders } from '../../schemas'; @@ -173,16 +175,16 @@ export const getCreateMyAssessmentAttemptUrl = () => { } /** - * Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The body names the category, a specialization of the questionnaire and a target grade, and the task language. The server picks the mode from the published bank, `demo_basic` or `adaptive`, and fixes the policy, bank, and algorithm versions, the time and session limits, and the item variants in one transaction; the client never sends a mode, a seed, or a version. Creation starts session 1. The self-assessed grade only chooses where the test starts and adds no points. An adaptive retest starts from the previous ability estimate of the specialization, adjusted for the time passed, so a new attempt adds evidence instead of starting the measurement over. + * Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The request is one of three disjoint shapes. A real assessment names a specialization, target grade, and task language; the server picks `demo_basic` or `adaptive` and fixes the policy, bank, and algorithm versions, limits, and item variants. A corrective real assessment also names `root_attempt_id`; the server verifies the lower-grade chain and reuses its fixed quota and deadline. The client never sends a real mode, a seed, a version, or a chain deadline. Explicit `demo_express` starts a separate interactive training run that lasts 3 to 5 minutes, has no category or target grade, and creates no qualification evidence or percentile. Creation starts session 1. The self-assessed grade only chooses where a real test starts and adds no points. An adaptive retest starts from the previous ability estimate of the specialization, adjusted for the time passed, so a new attempt adds evidence instead of starting the measurement over. * - * A specialization has at most one active attempt. A new attempt cannot start while one is active, during a retry or promotion interval or past the attempt limit of the policy, or when the bank is insufficient; each answers 409 state_conflict and creates nothing, not even a placeholder attempt. GetMyAssessmentAvailability tells which case applies and when a blocked attempt opens. After a failure, including the first test, a lower grade can be tested at once. An attempt that ends as `expired` or with the reason `practice_incomplete` counts toward the attempt limit and starts the same-grade retry interval; one that ends as `insufficient_bank` or with the reason `sandbox_unavailable` counts toward neither. + * A specialization has at most one active real attempt. A new root attempt cannot start while one is active, during a retry or promotion interval, past the root quota, or when the bank is insufficient; each such preflight refusal answers 409 state_conflict and creates nothing or consumes no root slot. Starting a root attempt reserves one slot in the root quota. A corrective attempt must reference its root, target a strictly lower grade not already attempted in that chain, and remain inside the root's fixed quota and deadline (72 hours from the root start in the current policy). It gets its own item, practice, and session limits, but spends no additional root slot and cannot reset the chain deadline or any 30/90-day timer. After a failure, including the first test, a lower grade can be tested at once. An expired or incomplete attempt does not create a free new chain; an insufficient bank or sandbox failure does not grant another root slot. `demo_express` is outside real-assessment availability, quotas, retry intervals, and qualification history. * - * The limits are server-side: `expires_at` and `sessions` come from the policy version, the client clock never extends them, and after them the attempt accepts no command. Within them the attempt is also bounded by the item limit of the policy. + * The limits are server-side: `expires_at` and `sessions` come from the policy version, the client clock never extends them, and after them the attempt accepts no work command. For a corrective attempt, `expires_at` is no later than the root's immutable `chain_deadline`. Within these limits the attempt is also bounded by the item limit of its policy. * * Idempotency: a retry with the same key and body within 24 hours replays the stored 201 or 409 state_conflict response and creates nothing, so a lost response never creates a second attempt. A different body with the same key answers 422 idempotency_key_reused. 400 is never stored, so a corrected retry is evaluated again. * * Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for an employer), the Idempotency-Key (422, 409 idempotency_in_progress, replay), domain rules (400 with a pointer, for example `/specialization` for a specialization that is not in the questionnaire or `/task_language` for a language that the bank does not offer), then availability (409 state_conflict). The rate limit can answer 429 with Retry-After before any of them; it is not stored. - * @summary Start an assessment attempt for a category of the current candidate. + * @summary Start a real, corrective, or training assessment attempt. */ export const createMyAssessmentAttempt = async (assessmentAttemptCreate: AssessmentAttemptCreate, headers: CreateMyAssessmentAttemptHeaders, options?: Parameters[1]): Promise => { @@ -249,7 +251,7 @@ const {mutation: mutationOptions, request: requestOptions} = options ? export type CreateMyAssessmentAttemptMutationVariables = {data: AssessmentAttemptCreate;headers: CreateMyAssessmentAttemptHeaders} /** - * @summary Start an assessment attempt for a category of the current candidate. + * @summary Start a real, corrective, or training assessment attempt. */ export const useCreateMyAssessmentAttempt = , TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,CreateMyAssessmentAttemptMutationVariables, TContext>, request?: SecondParameter} @@ -270,12 +272,12 @@ export const useCreateMyAssessmentAttempt = , } /** - * Requires the session cookie of a candidate account. Returns the attempt with its state, fixed versions, time and session limits, progress, the item to answer now, and the practices. A reload, a retried request, or a new session returns the same item instance with the same text and option order; a lost connection never creates a new attempt. The response never says whether an earlier answer was correct and never contains answer keys, item scores, family or variant identifiers, seeds, hidden checks, or anti-cheat signals. + * Requires the session cookie of a candidate account. Returns the stored attempt projection with its state, fixed versions, time and session limits, progress, the item to answer now, and the practices. This GET is read-only: it never starts or resumes a work session, consumes session quota, advances the version, or commits expiry or finalization. A reload, a retried request, or a new session returns the same item instance with the same text and option order; a lost connection never creates a new attempt. After `idle_timeout_seconds`, the candidate explicitly starts or resumes work with StartMyAssessmentAttemptSession. The response never says whether an earlier answer was correct and never contains answer keys, item scores, family or variant identifiers, seeds, hidden checks, or anti-cheat signals. * - * Reading an active attempt counts as activity: after the previous session ended it starts the next session, and when that would exceed the session limit it starts none and the attempt becomes `expired`. Before it answers, the server commits any transition that is due, with a new version: past `expires_at`, `ready_to_finalize` becomes `completed`, an unsubmitted additional practice is declined and the attempt becomes `completed`, and the other active states become `expired`; a practice still `pending` is graded first. The client polls this operation while a practice is `pending`. Reading a terminal attempt changes nothing. + * When the deadline passes, this read still returns the stored state and deadline. A command or background transition commits the due outcome; if the stored state is still active, GetMyAssessmentResult answers 409 until that transition is committed. The client polls this operation while a practice is `pending`, but polling alone never changes attempt state. * - * The attempt must belong to the candidate of the session: an attempt of another candidate answers 404 not_found, the same as an unknown identifier, so identifiers cannot be probed. An employer account answers 403 forbidden; no operation gives an employer the answers or the attempt history. - * @summary Read or resume an assessment attempt of the current candidate. + * The attempt must belong to the candidate of the session: an attempt of another candidate answers 404 not_found, the same as an unknown identifier, so identifiers cannot be probed. An employer account answers 403 forbidden; no operation gives an employer the answers, qualification evidence, or attempt history. + * @summary Read an assessment attempt of the current candidate. */ export const getMyAssessmentAttempt = async (attemptId: string, options?: Parameters[1]): Promise => { @@ -346,7 +348,7 @@ export function useGetMyAssessmentAttempt & { queryKey: DataTag } /** - * @summary Read or resume an assessment attempt of the current candidate. + * @summary Read an assessment attempt of the current candidate. */ export function useGetMyAssessmentAttempt>, TError = ErrorType>( @@ -366,7 +368,103 @@ export function useGetMyAssessmentAttempt { +export const getStartMyAssessmentAttemptSessionUrl = (attemptId: string,) => { + + + + + return `/api/v1/me/assessment-attempts/${attemptId}/sessions` +} + +/** + * Requires a candidate session, its CSRF token in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The body carries the attempt version the candidate last read. The server checks ownership, idempotency, and `expected_version` atomically before starting a session; a stale version answers 412 and consumes no session. Repeating the same key and body within 24 hours replays the stored response. + * + * Creation starts session 1. After `idle_timeout_seconds` of inactivity, the candidate uses this command to start the next session. Calling it while a session is already active returns the current attempt without consuming another session or advancing its version. Starting a session advances the version once. The command cannot extend `expires_at` or `chain_deadline`. + * + * If the attempt deadline or session budget has passed, this command commits the due terminal transition and returns the resulting attempt. A pending practice submitted before the limit is graded first. `GetMyAssessmentAttempt` and `GetMyAssessmentResult` remain read-only: they never start a session or commit a due transition. A background transition may persist a due outcome independently; after that, this command returns the stored terminal attempt without changing it. + * + * The attempt must belong to the candidate of the session. An attempt of another candidate answers 404 not_found, the same as an unknown identifier. An employer account answers 403 forbidden; no operation gives an employer answers, qualification evidence, or attempt history. + * @summary Start or resume a work session for the current candidate's attempt. + */ +export const startMyAssessmentAttemptSession = async (attemptId: string, + assessmentAttemptSessionStart: AssessmentAttemptSessionStart, + headers: StartMyAssessmentAttemptSessionHeaders, options?: Parameters[1]): Promise => { + + const getHeaders = (h?: NonNullable): Record => { + if (!h) return {}; + if (h instanceof Headers) return Object.fromEntries(h.entries()); + if (Symbol.iterator in h) { + return Object.fromEntries( + Array.from(h as Iterable>, (entry) => Array.from(entry) as [string, string]), + ); + } + const headers: Record = {}; + for (const [name, value] of Object.entries(h)) { + if (value !== undefined) headers[name] = value; + } + return headers; + }; +return apiRequest(getStartMyAssessmentAttemptSessionUrl(attemptId), + { + ...options, + method: 'POST', + headers: { 'Content-Type': 'application/json',...headers, ...getHeaders(options?.headers) }, + body: JSON.stringify(assessmentAttemptSessionStart) + } +);} + + + + + +export const getStartMyAssessmentAttemptSessionMutationKey = () => ['startMyAssessmentAttemptSession'] as const; + +export const getStartMyAssessmentAttemptSessionMutationOptions = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,StartMyAssessmentAttemptSessionMutationVariables, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,StartMyAssessmentAttemptSessionMutationVariables, TContext> => { + +const mutationKey = getStartMyAssessmentAttemptSessionMutationKey(); +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, StartMyAssessmentAttemptSessionMutationVariables> = (props) => { + const {attemptId,data,headers} = props ?? {}; + + return startMyAssessmentAttemptSession(attemptId,data,headers,requestOptions) + } + + + + + + + return { mutationFn, ...mutationOptions }} + + export type StartMyAssessmentAttemptSessionMutationResult = NonNullable>> + export type StartMyAssessmentAttemptSessionMutationBody = AssessmentAttemptSessionStart + export type StartMyAssessmentAttemptSessionMutationError = ErrorType + export type StartMyAssessmentAttemptSessionMutationVariables = {attemptId: string;data: AssessmentAttemptSessionStart;headers: StartMyAssessmentAttemptSessionHeaders} + + /** + * @summary Start or resume a work session for the current candidate's attempt. + */ +export const useStartMyAssessmentAttemptSession = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,StartMyAssessmentAttemptSessionMutationVariables, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + StartMyAssessmentAttemptSessionMutationVariables, + TContext + > => { + return useMutation(getStartMyAssessmentAttemptSessionMutationOptions(options), queryClient); + } + export const getSubmitMyAssessmentAnswerUrl = (attemptId: string,) => { @@ -379,6 +477,8 @@ export const getSubmitMyAssessmentAnswerUrl = (attemptId: string,) => { * * The response is the attempt with the next item to answer. It never says whether the answer was correct. Items are answered in order and each answer is final. * + * A work command requires an active session. After `idle_timeout_seconds` of inactivity, the candidate calls StartMyAssessmentAttemptSession to explicitly start or resume a session; this answer command never starts one or consumes session quota. Reading the attempt or result is always read-only. A command that finds a due deadline transition may commit it before returning; a command that finds an expired idle session answers 409 until the candidate explicitly starts the next session. + * * Practice: an answer with format `practice` submits the solution of the main or the additional practice. It is stored, and the sandbox runs it asynchronously against the hidden check groups; the response shows the practice `pending`, and the client polls GetMyAssessmentAttempt for the verdict. Only the score 0-3 and the pass state of each group are shown, never the checks, error output, or seeds. Every outcome caused by the solution, such as a compilation error, a crash, or a time or memory limit, is a `finished` verdict. A `failed` verdict means only that the sandbox infrastructure could not run it; it consumes nothing. After `finished` the practice accepts no other solution, so hidden group results cannot be used to tune it. Debug runs of the candidate's own tests and the public examples are unlimited apart from the sandbox rate limit and never show hidden group results; they are planned as a separate operation. * * Repeats and conflicts, per item: @@ -389,7 +489,7 @@ export const getSubmitMyAssessmentAnswerUrl = (attemptId: string,) => { * * Optimistic concurrency: `expected_version` must equal the current attempt version, otherwise the server answers 412 version_conflict and stores nothing; the client reads the attempt again. 412 is the repository status for a stale version, also used by SaveMyQuestionnaire; 409 state_conflict is kept for commands that the attempt state does not allow at the current version. * - * Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the attempt (404 not_found for an unknown attempt or one of another candidate; the server first commits any due transition such as expiry, and the request counts as activity for the session limit), the repeat of the stored answer (200, skipped for a practice whose latest verdict is `failed`), the version (412), the state (409 state_conflict: the attempt is terminal, the item is not current, the item has a different answer, or the practice verdict is pending or finished), then the answer against the item (400 with a pointer such as `/answer/format` or `/answer/option_ids/0`). Following the Idempotency-Key convention, 404 and 409 state_conflict are stored under the key and replayed; 400, 412, 429, and 5xx are not. The rate limit can answer 429 with Retry-After before any check. + * Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the attempt (404 not_found for an unknown attempt or one of another candidate; a due deadline transition may be committed, but this request never starts a work session), the repeat of the stored answer (200, skipped for a practice whose latest verdict is `failed`), the version (412), the state (409 state_conflict: the attempt is terminal, the work session ended, the item is not current, the item has a different answer, or the practice verdict is pending or finished), then the answer against the item (400 with a pointer such as `/answer/format` or `/answer/option_ids/0`). Following the Idempotency-Key convention, 404 and 409 state_conflict are stored under the key and replayed; 400, 412, 429, and 5xx are not. The rate limit can answer 429 with Retry-After before any check. * @summary Answer the current item or submit a practice of an assessment attempt. */ export const submitMyAssessmentAnswer = async (attemptId: string, @@ -481,16 +581,18 @@ export const useSubmitMyAssessmentAnswer = , /** * Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. Finalize always answers with the attempt, never with the result: the decision may continue the attempt, and one response type keeps that unambiguous for every generated client. When the returned state is `completed`, the client reads the result with GetMyAssessmentResult. * + * Finalize is a work command and requires an active session. After `idle_timeout_seconds` of inactivity, the candidate first calls StartMyAssessmentAttemptSession with the latest `expected_version`; finalize never starts a session. GET attempt and result operations do not change state. A command or background transition may commit a due deadline outcome. + * * Allowed in `ready_to_finalize`, where every required part is done, and in `additional_practice_pending` while the additional practice is `not_started` or `failed`. The server decides from the stored answers with the policy, bank, and algorithm versions fixed at creation: * - `demo_basic` compares the raw score with the pass mark of the recorded basic grading policy and completes the attempt. It never offers an additional practice. * - `adaptive` applies the probability bands of the recorded policy. Confirmation or rejection completes the attempt. A probability in the band below confirmation (0.50 to below 0.80 in the demo policy) on the first finalize, while time and sessions remain, completes nothing: the server appends an `additional` practice, moves the attempt to `additional_practice_pending`, and answers 200 with it. The additional practice continues the same attempt, keeps its limits, and spends no new attempt. The next finalize, after its verdict, decides with the added evidence; a probability still below confirmation gives `not_confirmed`. An attempt offers at most one additional practice. * - Finalize in `additional_practice_pending` declines the offer and gives `not_confirmed` with the current evidence. A retry of the first finalize with a new key cannot decline by accident: it carries the version from before the offer and answers 412. * - * A failed attempt never lowers a confirmed grade. Repeats return the same outcome: a retry with the same Idempotency-Key replays the stored response, and a finalize of a `completed` attempt answers 200 with that attempt even with a new key or an older `expected_version`; the result is computed once. When `expires_at` passes or the session limit is reached, the server finalizes `ready_to_finalize` itself, without offering an additional practice, so a finalize after that also answers 200 with the `completed` attempt. + * A failed attempt never lowers a confirmed grade. Repeats return the same outcome: a retry with the same Idempotency-Key replays the stored response, and a finalize of a `completed` attempt answers 200 with that attempt even with a new key or an older `expected_version`; the result is computed once. When `expires_at` passes or the session limit is reached, a command or background transition finalizes `ready_to_finalize` without offering an additional practice. A finalize after this transition answers 200 with the stored `completed` attempt; a GET never commits it. * * An attempt in `in_progress` or `practice_pending`, one with a practice verdict `pending`, or one that ended as `expired` or `insufficient_bank` answers 409 state_conflict. The problem does not list what is unfinished; the attempt shows it in `state`, `progress`, `current_item`, and `practices`. A stale `expected_version` answers 412 version_conflict, the repository status for a stale version. * - * Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the attempt (404 not_found, after any due transition), the repeat on a `completed` attempt (200), the version (412), then the state (409 state_conflict). 404 and 409 state_conflict are stored under the key; 400 and 412 are not. + * Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the attempt (404 not_found; a due deadline transition may be committed, but this request never starts a work session), the repeat on a `completed` attempt (200), the version (412), then the state (409 state_conflict, including an ended idle session). 404 and 409 state_conflict are stored under the key; 400 and 412 are not. * @summary Ask for the grade decision of an assessment attempt. */ export const finalizeMyAssessmentAttempt = async (attemptId: string, @@ -580,11 +682,11 @@ export const useFinalizeMyAssessmentAttempt = , } /** - * Requires the session cookie of a candidate account. Returns the immutable result of a terminal attempt: `completed`, `expired`, or `insufficient_bank`. It records the mode, the policy, bank, and algorithm versions, the decision, the previously confirmed grade, the calibration status and limitations of the method, the uncertainty where the method computes it, the practice verdicts, the weak domains, the working time as a separate label, and the next steps that the server allows. A later policy, bank, or algorithm version never changes it. + * Requires the session cookie of a candidate account. Returns the immutable result of a terminal attempt: `completed`, `expired`, or `insufficient_bank`. A real result records the mode, policy, bank, and algorithm versions, decision, previously confirmed grade, calibration status and limitations, uncertainty where the method computes it, practice verdicts, weak domains, working time as a separate label, and allowed next steps. A corrective result also carries the root attempt and its immutable chain deadline. A `demo_express` result is a short educational summary only: it has no category, percentile, confirmed grade, score, uncertainty, or qualification evidence. A later policy, bank, or algorithm version never changes a result. * * Fields that the method does not compute are null and never zero: a `demo_basic` result has null `uncertainty` and `strength`. The result never contains answers, per-item correctness, answer keys, seeds, hidden checks, or anti-cheat signals. * - * An active attempt answers 409 state_conflict; an attempt in `additional_practice_pending` is active and has no result yet. The server first commits any due transition, so an attempt past its limits is read as terminal. An attempt of another candidate answers 404 not_found, the same as an unknown identifier. An employer account answers 403 forbidden; employers see only the current category through a separate projection, never this result or the attempt history. + * An active attempt answers 409 state_conflict; an attempt in `additional_practice_pending` is active and has no result yet. This GET is read-only and never commits a due transition. If a deadline has passed but the due transition is not yet stored by a command or background worker, the attempt remains active for this read and answers 409; wait for the transition and retry. An attempt of another candidate answers 404 not_found, the same as an unknown identifier. An employer account answers 403 forbidden; employers see only the current category through a separate projection, never this result or the attempt history. * @summary Read the result of an assessment attempt of the current candidate. */ export const getMyAssessmentResult = async (attemptId: string, options?: Parameters[1]): Promise => { diff --git a/frontend/src/shared/api/mock-validity.test.ts b/frontend/src/shared/api/mock-validity.test.ts index c30ea39..e5a4b03 100644 --- a/frontend/src/shared/api/mock-validity.test.ts +++ b/frontend/src/shared/api/mock-validity.test.ts @@ -25,7 +25,7 @@ const mockSources = import.meta.glob("./endpoints/*/*.msw.ts", { // Orval declares each response factory with the response type as its return // type. The Zod schema with the same name is the generated response schema. const factoryDeclaration = - /export const (get\w+ResponseMock) = \(overrideResponse: [^=]*= \{\}\): (\w+) =>/g; + /export const (get\w+ResponseMock) = \((?:overrideResponse: [^=]*= \{\})?\): (\w+) =>/g; interface ResponseMockCase { readonly file: string; @@ -101,6 +101,16 @@ describe("generated MSW response mocks", () => { expect(Object.keys(mockModules).filter((file) => !covered.has(file))).toEqual([]); }); + it("discovers the no-argument union response factory", () => { + expect( + cases.some( + ({ factoryName, schemaName }) => + factoryName === "getCreateMyAssessmentAttemptResponseMock" && + schemaName === "AssessmentAttempt", + ), + ).toBe(true); + }); + it.each(cases)("$factoryName returns a valid $schemaName", ({ factory, schema }) => { const failures: string[] = []; for (const seed of seeds) { diff --git a/frontend/src/shared/api/schemas/assessment/assessmentAnswerSubmission.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentAnswerSubmission.zod.ts index 59210d1..35adbeb 100644 --- a/frontend/src/shared/api/schemas/assessment/assessmentAnswerSubmission.zod.ts +++ b/frontend/src/shared/api/schemas/assessment/assessmentAnswerSubmission.zod.ts @@ -32,7 +32,7 @@ export const assessmentAnswerSubmissionAnswerSevenSourceCodeMax = 65536; export const AssessmentAnswerSubmission = zod.object({ - "expected_version": zod.int().min(1).describe('Version of an assessment attempt. A new attempt has version 1, and each committed change advances it by exactly one: an accepted answer, a practice submission or resubmission, a verdict, a decision of finalize, a session start, and a server-side transition such as expiry or automatic finalization. A transition that the server applies when the attempt is read is committed before the response and also advances it. A rejected command and a repeat that stores nothing leave it unchanged. Commands send the version they read as `expected_version`.'), + "expected_version": zod.int().min(1).describe('Version of an assessment attempt. A new attempt has version 1, and each committed change advances it by exactly one: an accepted answer, a practice submission or resubmission, a verdict, a decision of finalize, an explicit work-session start, and a server-side transition such as expiry or automatic finalization. Reads never change the attempt. A rejected command and a repeat that stores nothing leave it unchanged. Commands send the version they read as `expected_version`.'), "item_id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'), "answer": zod.union([zod.object({ "format": zod.enum(['choice']), diff --git a/frontend/src/shared/api/schemas/assessment/assessmentAttempt.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentAttempt.zod.ts index 55dfd88..0257da5 100644 --- a/frontend/src/shared/api/schemas/assessment/assessmentAttempt.zod.ts +++ b/frontend/src/shared/api/schemas/assessment/assessmentAttempt.zod.ts @@ -8,165 +8,350 @@ import * as zod from 'zod'; -export const assessmentAttemptVersionsBankVersionMax = 64; +export const assessmentAttemptOneOneVersionsBankVersionMax = 64; -export const assessmentAttemptVersionsBankVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$'); -export const assessmentAttemptVersionsAlgorithmVersionMax = 64; +export const assessmentAttemptOneOneVersionsBankVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$'); +export const assessmentAttemptOneOneVersionsAlgorithmVersionMax = 64; -export const assessmentAttemptVersionsAlgorithmVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$'); -export const assessmentAttemptSessionsOneUsedMax = 10; +export const assessmentAttemptOneOneVersionsAlgorithmVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$'); +export const assessmentAttemptOneOneSessionsOneUsedMax = 10; -export const assessmentAttemptSessionsOneMaxMax = 10; +export const assessmentAttemptOneOneSessionsOneMaxMax = 10; -export const assessmentAttemptSessionsOneIdleTimeoutSecondsMin = 60; -export const assessmentAttemptSessionsOneIdleTimeoutSecondsMax = 86400; +export const assessmentAttemptOneOneSessionsOneIdleTimeoutSecondsMin = 60; +export const assessmentAttemptOneOneSessionsOneIdleTimeoutSecondsMax = 86400; -export const assessmentAttemptProgressAnsweredItemsMin = 0; -export const assessmentAttemptProgressAnsweredItemsMax = 100; +export const assessmentAttemptOneOneProgressAnsweredItemsMin = 0; +export const assessmentAttemptOneOneProgressAnsweredItemsMax = 100; -export const assessmentAttemptProgressMaxItemsMax = 100; +export const assessmentAttemptOneOneProgressMaxItemsMax = 100; -export const assessmentAttemptCurrentItemOneSequenceMax = 100; +export const assessmentAttemptOneOneCurrentItemOneSequenceMax = 100; -export const assessmentAttemptCurrentItemOnePromptMax = 20000; +export const assessmentAttemptOneOneCurrentItemOnePromptMax = 20000; -export const assessmentAttemptCurrentItemOneContentOneOptionsItemIdMax = 32; +export const assessmentAttemptOneOneCurrentItemOneContentOneOptionsItemIdMax = 32; -export const assessmentAttemptCurrentItemOneContentOneOptionsItemIdRegExp = new RegExp('^[A-Za-z0-9_-]+$'); -export const assessmentAttemptCurrentItemOneContentOneOptionsItemTextMax = 2000; +export const assessmentAttemptOneOneCurrentItemOneContentOneOptionsItemIdRegExp = new RegExp('^[A-Za-z0-9_-]+$'); +export const assessmentAttemptOneOneCurrentItemOneContentOneOptionsItemTextMax = 2000; -export const assessmentAttemptCurrentItemOneContentOneOptionsMin = 2; -export const assessmentAttemptCurrentItemOneContentOneOptionsMax = 10; +export const assessmentAttemptOneOneCurrentItemOneContentOneOptionsMin = 2; +export const assessmentAttemptOneOneCurrentItemOneContentOneOptionsMax = 10; -export const assessmentAttemptCurrentItemOneContentTwoUnitMax = 32; +export const assessmentAttemptOneOneCurrentItemOneContentTwoUnitMax = 32; -export const assessmentAttemptCurrentItemOneContentThreeMaxLengthMax = 500; +export const assessmentAttemptOneOneCurrentItemOneContentThreeMaxLengthMax = 500; -export const assessmentAttemptCurrentItemOneContentFourElementsItemIdMax = 32; +export const assessmentAttemptOneOneCurrentItemOneContentFourElementsItemIdMax = 32; -export const assessmentAttemptCurrentItemOneContentFourElementsItemIdRegExp = new RegExp('^[A-Za-z0-9_-]+$'); -export const assessmentAttemptCurrentItemOneContentFourElementsItemTextMax = 2000; +export const assessmentAttemptOneOneCurrentItemOneContentFourElementsItemIdRegExp = new RegExp('^[A-Za-z0-9_-]+$'); +export const assessmentAttemptOneOneCurrentItemOneContentFourElementsItemTextMax = 2000; -export const assessmentAttemptCurrentItemOneContentFourElementsMin = 2; -export const assessmentAttemptCurrentItemOneContentFourElementsMax = 20; +export const assessmentAttemptOneOneCurrentItemOneContentFourElementsMin = 2; +export const assessmentAttemptOneOneCurrentItemOneContentFourElementsMax = 20; -export const assessmentAttemptCurrentItemOneContentFiveSyntaxMax = 32; +export const assessmentAttemptOneOneCurrentItemOneContentFiveSyntaxMax = 32; -export const assessmentAttemptCurrentItemOneContentFiveSyntaxRegExp = new RegExp('^[a-z0-9_+-]+$'); -export const assessmentAttemptCurrentItemOneContentFiveLinesItemNumberMax = 500; +export const assessmentAttemptOneOneCurrentItemOneContentFiveSyntaxRegExp = new RegExp('^[a-z0-9_+-]+$'); +export const assessmentAttemptOneOneCurrentItemOneContentFiveLinesItemNumberMax = 500; -export const assessmentAttemptCurrentItemOneContentFiveLinesItemTextMax = 1000; +export const assessmentAttemptOneOneCurrentItemOneContentFiveLinesItemTextMax = 1000; -export const assessmentAttemptCurrentItemOneContentFiveLinesMax = 500; +export const assessmentAttemptOneOneCurrentItemOneContentFiveLinesMax = 500; -export const assessmentAttemptCurrentItemOneContentFiveMaxSelectionsMax = 10; +export const assessmentAttemptOneOneCurrentItemOneContentFiveMaxSelectionsMax = 10; -export const assessmentAttemptCurrentItemOneContentSixSyntaxMax = 32; +export const assessmentAttemptOneOneCurrentItemOneContentSixSyntaxMax = 32; -export const assessmentAttemptCurrentItemOneContentSixSyntaxRegExp = new RegExp('^[a-z0-9_+-]+$'); -export const assessmentAttemptCurrentItemOneContentSixInitialConfigMax = 20000; +export const assessmentAttemptOneOneCurrentItemOneContentSixSyntaxRegExp = new RegExp('^[a-z0-9_+-]+$'); +export const assessmentAttemptOneOneCurrentItemOneContentSixInitialConfigMax = 20000; -export const assessmentAttemptCurrentItemOneContentSixMaxLengthMax = 20000; +export const assessmentAttemptOneOneCurrentItemOneContentSixMaxLengthMax = 20000; -export const assessmentAttemptCurrentItemOneContentSevenLanguagesMax = 2; +export const assessmentAttemptOneOneCurrentItemOneContentSevenLanguagesMax = 2; -export const assessmentAttemptCurrentItemOneContentSevenPublicExamplesItemInputMax = 10000; +export const assessmentAttemptOneOneCurrentItemOneContentSevenPublicExamplesItemInputMax = 10000; -export const assessmentAttemptCurrentItemOneContentSevenPublicExamplesItemExpectedOutputMax = 10000; +export const assessmentAttemptOneOneCurrentItemOneContentSevenPublicExamplesItemExpectedOutputMax = 10000; -export const assessmentAttemptCurrentItemOneContentSevenPublicExamplesMax = 10; +export const assessmentAttemptOneOneCurrentItemOneContentSevenPublicExamplesMax = 10; -export const assessmentAttemptCurrentItemOneContentSevenMaxSourceLengthMax = 65536; +export const assessmentAttemptOneOneCurrentItemOneContentSevenMaxSourceLengthMax = 65536; -export const assessmentAttemptPracticesItemVerdictOneScoreMin = 0; -export const assessmentAttemptPracticesItemVerdictOneScoreMax = 3; +export const assessmentAttemptOneOnePracticesItemVerdictOneScoreMin = 0; +export const assessmentAttemptOneOnePracticesItemVerdictOneScoreMax = 3; -export const assessmentAttemptPracticesItemVerdictOneMaxScoreMin = 3; -export const assessmentAttemptPracticesItemVerdictOneMaxScoreMax = 3; +export const assessmentAttemptOneOnePracticesItemVerdictOneMaxScoreMin = 3; +export const assessmentAttemptOneOnePracticesItemVerdictOneMaxScoreMax = 3; -export const assessmentAttemptPracticesItemVerdictOneGroupsItemGroupMax = 3; +export const assessmentAttemptOneOnePracticesItemVerdictOneGroupsItemGroupMax = 3; -export const assessmentAttemptPracticesItemVerdictOneGroupsMin = 3; -export const assessmentAttemptPracticesItemVerdictOneGroupsMax = 3; +export const assessmentAttemptOneOnePracticesItemVerdictOneGroupsMin = 3; +export const assessmentAttemptOneOnePracticesItemVerdictOneGroupsMax = 3; -export const assessmentAttemptPracticesMax = 5; +export const assessmentAttemptOneOnePracticesMax = 5; -export const AssessmentAttempt = zod.object({ + +export const assessmentAttemptTwoOneVersionsBankVersionMax = 64; + + +export const assessmentAttemptTwoOneVersionsBankVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$'); +export const assessmentAttemptTwoOneVersionsAlgorithmVersionMax = 64; + + +export const assessmentAttemptTwoOneVersionsAlgorithmVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$'); +export const assessmentAttemptTwoOneSessionsOneUsedMax = 10; + +export const assessmentAttemptTwoOneSessionsOneMaxMax = 10; + +export const assessmentAttemptTwoOneSessionsOneIdleTimeoutSecondsMin = 60; +export const assessmentAttemptTwoOneSessionsOneIdleTimeoutSecondsMax = 86400; + +export const assessmentAttemptTwoOneProgressAnsweredItemsMin = 0; +export const assessmentAttemptTwoOneProgressAnsweredItemsMax = 100; + +export const assessmentAttemptTwoOneProgressMaxItemsMax = 100; + +export const assessmentAttemptTwoOneCurrentItemOneSequenceMax = 100; + +export const assessmentAttemptTwoOneCurrentItemOnePromptMax = 20000; + +export const assessmentAttemptTwoOneCurrentItemOneContentOneOptionsItemIdMax = 32; + + +export const assessmentAttemptTwoOneCurrentItemOneContentOneOptionsItemIdRegExp = new RegExp('^[A-Za-z0-9_-]+$'); +export const assessmentAttemptTwoOneCurrentItemOneContentOneOptionsItemTextMax = 2000; + +export const assessmentAttemptTwoOneCurrentItemOneContentOneOptionsMin = 2; +export const assessmentAttemptTwoOneCurrentItemOneContentOneOptionsMax = 10; + +export const assessmentAttemptTwoOneCurrentItemOneContentTwoUnitMax = 32; + +export const assessmentAttemptTwoOneCurrentItemOneContentThreeMaxLengthMax = 500; + +export const assessmentAttemptTwoOneCurrentItemOneContentFourElementsItemIdMax = 32; + + +export const assessmentAttemptTwoOneCurrentItemOneContentFourElementsItemIdRegExp = new RegExp('^[A-Za-z0-9_-]+$'); +export const assessmentAttemptTwoOneCurrentItemOneContentFourElementsItemTextMax = 2000; + +export const assessmentAttemptTwoOneCurrentItemOneContentFourElementsMin = 2; +export const assessmentAttemptTwoOneCurrentItemOneContentFourElementsMax = 20; + +export const assessmentAttemptTwoOneCurrentItemOneContentFiveSyntaxMax = 32; + + +export const assessmentAttemptTwoOneCurrentItemOneContentFiveSyntaxRegExp = new RegExp('^[a-z0-9_+-]+$'); +export const assessmentAttemptTwoOneCurrentItemOneContentFiveLinesItemNumberMax = 500; + +export const assessmentAttemptTwoOneCurrentItemOneContentFiveLinesItemTextMax = 1000; + +export const assessmentAttemptTwoOneCurrentItemOneContentFiveLinesMax = 500; + +export const assessmentAttemptTwoOneCurrentItemOneContentFiveMaxSelectionsMax = 10; + +export const assessmentAttemptTwoOneCurrentItemOneContentSixSyntaxMax = 32; + + +export const assessmentAttemptTwoOneCurrentItemOneContentSixSyntaxRegExp = new RegExp('^[a-z0-9_+-]+$'); +export const assessmentAttemptTwoOneCurrentItemOneContentSixInitialConfigMax = 20000; + +export const assessmentAttemptTwoOneCurrentItemOneContentSixMaxLengthMax = 20000; + +export const assessmentAttemptTwoOneCurrentItemOneContentSevenLanguagesMax = 2; + +export const assessmentAttemptTwoOneCurrentItemOneContentSevenPublicExamplesItemInputMax = 10000; + +export const assessmentAttemptTwoOneCurrentItemOneContentSevenPublicExamplesItemExpectedOutputMax = 10000; + +export const assessmentAttemptTwoOneCurrentItemOneContentSevenPublicExamplesMax = 10; + +export const assessmentAttemptTwoOneCurrentItemOneContentSevenMaxSourceLengthMax = 65536; + +export const assessmentAttemptTwoOnePracticesItemVerdictOneScoreMin = 0; +export const assessmentAttemptTwoOnePracticesItemVerdictOneScoreMax = 3; + +export const assessmentAttemptTwoOnePracticesItemVerdictOneMaxScoreMin = 3; +export const assessmentAttemptTwoOnePracticesItemVerdictOneMaxScoreMax = 3; + +export const assessmentAttemptTwoOnePracticesItemVerdictOneGroupsItemGroupMax = 3; + +export const assessmentAttemptTwoOnePracticesItemVerdictOneGroupsMin = 3; +export const assessmentAttemptTwoOnePracticesItemVerdictOneGroupsMax = 3; + +export const assessmentAttemptTwoOnePracticesMax = 5; + + + +export const assessmentAttemptThreeOneVersionsBankVersionMax = 64; + + +export const assessmentAttemptThreeOneVersionsBankVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$'); +export const assessmentAttemptThreeOneVersionsAlgorithmVersionMax = 64; + + +export const assessmentAttemptThreeOneVersionsAlgorithmVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$'); +export const assessmentAttemptThreeOneSessionsOneUsedMax = 10; + +export const assessmentAttemptThreeOneSessionsOneMaxMax = 10; + +export const assessmentAttemptThreeOneSessionsOneIdleTimeoutSecondsMin = 60; +export const assessmentAttemptThreeOneSessionsOneIdleTimeoutSecondsMax = 86400; + +export const assessmentAttemptThreeOneProgressAnsweredItemsMin = 0; +export const assessmentAttemptThreeOneProgressAnsweredItemsMax = 100; + +export const assessmentAttemptThreeOneProgressMaxItemsMax = 100; + +export const assessmentAttemptThreeOneCurrentItemOneSequenceMax = 100; + +export const assessmentAttemptThreeOneCurrentItemOnePromptMax = 20000; + +export const assessmentAttemptThreeOneCurrentItemOneContentOneOptionsItemIdMax = 32; + + +export const assessmentAttemptThreeOneCurrentItemOneContentOneOptionsItemIdRegExp = new RegExp('^[A-Za-z0-9_-]+$'); +export const assessmentAttemptThreeOneCurrentItemOneContentOneOptionsItemTextMax = 2000; + +export const assessmentAttemptThreeOneCurrentItemOneContentOneOptionsMin = 2; +export const assessmentAttemptThreeOneCurrentItemOneContentOneOptionsMax = 10; + +export const assessmentAttemptThreeOneCurrentItemOneContentTwoUnitMax = 32; + +export const assessmentAttemptThreeOneCurrentItemOneContentThreeMaxLengthMax = 500; + +export const assessmentAttemptThreeOneCurrentItemOneContentFourElementsItemIdMax = 32; + + +export const assessmentAttemptThreeOneCurrentItemOneContentFourElementsItemIdRegExp = new RegExp('^[A-Za-z0-9_-]+$'); +export const assessmentAttemptThreeOneCurrentItemOneContentFourElementsItemTextMax = 2000; + +export const assessmentAttemptThreeOneCurrentItemOneContentFourElementsMin = 2; +export const assessmentAttemptThreeOneCurrentItemOneContentFourElementsMax = 20; + +export const assessmentAttemptThreeOneCurrentItemOneContentFiveSyntaxMax = 32; + + +export const assessmentAttemptThreeOneCurrentItemOneContentFiveSyntaxRegExp = new RegExp('^[a-z0-9_+-]+$'); +export const assessmentAttemptThreeOneCurrentItemOneContentFiveLinesItemNumberMax = 500; + +export const assessmentAttemptThreeOneCurrentItemOneContentFiveLinesItemTextMax = 1000; + +export const assessmentAttemptThreeOneCurrentItemOneContentFiveLinesMax = 500; + +export const assessmentAttemptThreeOneCurrentItemOneContentFiveMaxSelectionsMax = 10; + +export const assessmentAttemptThreeOneCurrentItemOneContentSixSyntaxMax = 32; + + +export const assessmentAttemptThreeOneCurrentItemOneContentSixSyntaxRegExp = new RegExp('^[a-z0-9_+-]+$'); +export const assessmentAttemptThreeOneCurrentItemOneContentSixInitialConfigMax = 20000; + +export const assessmentAttemptThreeOneCurrentItemOneContentSixMaxLengthMax = 20000; + +export const assessmentAttemptThreeOneCurrentItemOneContentSevenLanguagesMax = 2; + +export const assessmentAttemptThreeOneCurrentItemOneContentSevenPublicExamplesItemInputMax = 10000; + +export const assessmentAttemptThreeOneCurrentItemOneContentSevenPublicExamplesItemExpectedOutputMax = 10000; + +export const assessmentAttemptThreeOneCurrentItemOneContentSevenPublicExamplesMax = 10; + +export const assessmentAttemptThreeOneCurrentItemOneContentSevenMaxSourceLengthMax = 65536; + +export const assessmentAttemptThreeOnePracticesItemVerdictOneScoreMin = 0; +export const assessmentAttemptThreeOnePracticesItemVerdictOneScoreMax = 3; + +export const assessmentAttemptThreeOnePracticesItemVerdictOneMaxScoreMin = 3; +export const assessmentAttemptThreeOnePracticesItemVerdictOneMaxScoreMax = 3; + +export const assessmentAttemptThreeOnePracticesItemVerdictOneGroupsItemGroupMax = 3; + +export const assessmentAttemptThreeOnePracticesItemVerdictOneGroupsMin = 3; +export const assessmentAttemptThreeOnePracticesItemVerdictOneGroupsMax = 3; + +export const assessmentAttemptThreeOnePracticesMax = 5; + + +export const AssessmentAttempt = zod.union([zod.object({ "id": zod.uuid().describe('Attempt identifier.'), - "version": zod.int().min(1).describe('Version of an assessment attempt. A new attempt has version 1, and each committed change advances it by exactly one: an accepted answer, a practice submission or resubmission, a verdict, a decision of finalize, a session start, and a server-side transition such as expiry or automatic finalization. A transition that the server applies when the attempt is read is committed before the response and also advances it. A rejected command and a repeat that stores nothing leave it unchanged. Commands send the version they read as `expected_version`.'), - "specialization": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'), - "target_grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'), - "task_language": zod.union([zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.'),zod.null()]).describe('Task language of the attempt, or null when the bank offers no choice.'), - "mode": zod.enum(['demo_basic', 'adaptive']).describe('Measurement method of an attempt. The server selects it from the published task bank of the category; the client never chooses it.\n\n- demo_basic: a fixed form of reviewed demo items scored by their keys against the pass mark of the versioned basic grading policy. It computes no ability estimate, standard error, or probability, so every uncertainty field of its result is null, its thresholds are uncalibrated, and its decision is binary: it never offers an additional practice.\n- adaptive: the adaptive test on task families with an ability estimate, its standard error, and the probability of reaching the grade threshold, as the versioned assessment policy defines them. A probability in the band below confirmation offers one additional practice in the same attempt.\n\nAdding a value is a contract change.'), - "state": zod.enum(['in_progress', 'practice_pending', 'additional_practice_pending', 'ready_to_finalize', 'completed', 'expired', 'insufficient_bank']).describe('Lifecycle state of an attempt and the commands it accepts.\n\n- in_progress: items are being answered; `current_item` is the item to answer. Accepts SubmitMyAssessmentAnswer for that item.\n- practice_pending: the item part is finished, and the main practice has no finished verdict yet: it is not submitted, its verdict is pending in the sandbox, or the sandbox failed and the practice can be submitted again. Accepts SubmitMyAssessmentAnswer with the practice item while its status is `not_started` or `failed`. No grade is confirmed while the practice is unfinished, even when the adaptive stop rule has already ended the item part.\n- additional_practice_pending: adaptive only. Finalize found the probability of reaching the grade in the band below confirmation, so the attempt offers one additional practice without spending a new attempt; it keeps the time and session limits of the attempt. Accepts SubmitMyAssessmentAnswer with the additional practice item while its status is `not_started` or `failed`, and FinalizeMyAssessmentAttempt in the same statuses, which declines the offer and decides `not_confirmed` with the current evidence.\n- ready_to_finalize: every required part is done, including a submitted additional practice with a finished verdict. Accepts FinalizeMyAssessmentAttempt.\n- completed: a decision was made; the result is available.\n- expired: the time or session limit passed before the candidate finished the required parts. The result is available and confirms no grade.\n- insufficient_bank: the published bank could not supply the items required for coverage within the limit, and the attempt ended without a confirmed grade instead of repeating families. The result is available.\n\nWhen `expires_at` passes or the session limit is reached, a practice submitted before that and still `pending` is graded first. Then the server decides without another command: `ready_to_finalize` is finalized and becomes `completed`; `additional_practice_pending` with the additional practice not submitted is finalized as declined and becomes `completed` with `not_confirmed`; `in_progress` and `practice_pending` become `expired`, with the result reason `expired` or `practice_incomplete`; and when the latest submission of a practice ended `failed`, the attempt becomes `expired` with the reason `sandbox_unavailable`, which is not the candidate\'s fault. `completed`, `expired`, and `insufficient_bank` are terminal and accept no command except the repeat of finalize described on FinalizeMyAssessmentAttempt. Adding a value is a contract change.'), + "version": zod.int().min(1).describe('Version of an assessment attempt. A new attempt has version 1, and each committed change advances it by exactly one: an accepted answer, a practice submission or resubmission, a verdict, a decision of finalize, an explicit work-session start, and a server-side transition such as expiry or automatic finalization. Reads never change the attempt. A rejected command and a repeat that stores nothing leave it unchanged. Commands send the version they read as `expected_version`.'), + "specialization": zod.union([zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'),zod.null()]).describe('Null only for demo_express, which has no qualification category.'), + "target_grade": zod.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Null only for demo_express, which has no qualification category.'), + "task_language": zod.union([zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.'),zod.null()]).describe('Task language of the attempt, or null when none is selected.'), + "kind": zod.enum(['root', 'corrective', 'demo_express']).describe('Assessment track that distinguishes root, corrective, and training attempts.'), + "root_attempt_id": zod.union([zod.uuid(),zod.null()]).describe('Present only for a corrective real assessment. It identifies the root attempt whose quota and chain deadline this attempt shares.'), + "chain_deadline": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('Present only for a corrective real assessment. It is the immutable deadline derived from the root attempt and is not extended by a lower target grade.'), + "mode": zod.enum(['demo_basic', 'demo_express', 'adaptive']).describe('Method of an assessment attempt. For a real assessment, the server selects demo_basic or adaptive from the published bank. A candidate may explicitly request demo_express, which uses a separate training policy and creates no qualification evidence.\n\n- demo_basic: a fixed form of reviewed demo items scored by their keys against the pass mark of the versioned basic grading policy. It computes no ability estimate, standard error, or probability, so every uncertainty field of its result is null, its thresholds are uncalibrated, and its decision is binary: it never offers an additional practice.\n- adaptive: the adaptive test on task families with an ability estimate, its standard error, and the probability of reaching the grade threshold, as the versioned assessment policy defines them. A probability in the band below confirmation offers one additional practice in the same attempt.\n- demo_express: an interactive 3 to 5 minute training run under a separate policy. It does not assign a category or percentile, count toward the real-assessment quota, or create qualification evidence.\n\nAdding a value is a contract change.'), + "state": zod.enum(['in_progress', 'practice_pending', 'additional_practice_pending', 'ready_to_finalize', 'completed', 'expired', 'insufficient_bank']).describe('Lifecycle state of an attempt and the commands it accepts.\n\n- in_progress: items are being answered; `current_item` is the item to answer. Accepts SubmitMyAssessmentAnswer for that item.\n- practice_pending: the item part is finished, and the main practice has no finished verdict yet: it is not submitted, its verdict is pending in the sandbox, or the sandbox failed and the practice can be submitted again. Accepts SubmitMyAssessmentAnswer with the practice item while its status is `not_started` or `failed`. No grade is confirmed while the practice is unfinished, even when the adaptive stop rule has already ended the item part.\n- additional_practice_pending: adaptive only. Finalize found the probability of reaching the grade in the band below confirmation, so the attempt offers one additional practice without spending a new attempt; it keeps the time and session limits of the attempt. Accepts SubmitMyAssessmentAnswer with the additional practice item while its status is `not_started` or `failed`, and FinalizeMyAssessmentAttempt in the same statuses, which declines the offer and decides `not_confirmed` with the current evidence.\n- ready_to_finalize: every required part is done, including a submitted additional practice with a finished verdict. Accepts FinalizeMyAssessmentAttempt.\n- completed: a decision was made; the result is available.\n- expired: the time or session limit passed before the candidate finished the required parts. The result is available and confirms no grade.\n- insufficient_bank: the published bank could not supply the items required for coverage within the limit, and the attempt ended without a confirmed grade instead of repeating families. The result is available.\n\nWhen `expires_at` passes or the session limit is reached, a read returns the stored state without changing it. A command or background transition commits any due outcome and advances the version. A practice submitted before the limit and still `pending` is graded first. Then `ready_to_finalize` becomes `completed`; `additional_practice_pending` with the additional practice not submitted is finalized as declined and becomes `completed` with `not_confirmed`; `in_progress` and `practice_pending` become `expired`, with the result reason `expired` or `practice_incomplete`; and when the latest submission of a practice ended `failed`, the attempt becomes `expired` with the reason `sandbox_unavailable`, which is not the candidate\'s fault. `completed`, `expired`, and `insufficient_bank` are terminal and accept no command except the repeat of finalize described on FinalizeMyAssessmentAttempt. Adding a value is a contract change.'), "versions": zod.object({ "policy_version": zod.int().min(1).describe('Number of the `product` policy version whose assessment rules apply: thresholds, stop rules, item limits, time and session limits, and retry intervals.'), - "bank_version": zod.string().min(1).max(assessmentAttemptVersionsBankVersionMax).regex(assessmentAttemptVersionsBankVersionRegExp).describe('Opaque identifier of a published version, for example `backend-demo.2026-10.1`. Clients show it as text and never parse it.'), - "algorithm_version": zod.string().min(1).max(assessmentAttemptVersionsAlgorithmVersionMax).regex(assessmentAttemptVersionsAlgorithmVersionRegExp).describe('Opaque identifier of a published version, for example `backend-demo.2026-10.1`. Clients show it as text and never parse it.') + "bank_version": zod.string().min(1).max(assessmentAttemptOneOneVersionsBankVersionMax).regex(assessmentAttemptOneOneVersionsBankVersionRegExp).describe('Opaque identifier of a published version, for example `backend-demo.2026-10.1`. Clients show it as text and never parse it.'), + "algorithm_version": zod.string().min(1).max(assessmentAttemptOneOneVersionsAlgorithmVersionMax).regex(assessmentAttemptOneOneVersionsAlgorithmVersionRegExp).describe('Opaque identifier of a published version, for example `backend-demo.2026-10.1`. Clients show it as text and never parse it.') }).describe('Versions fixed when the attempt was created. They never change during the attempt, and a result is always reproduced from the stored answers with these versions; a later policy, bank, or algorithm version does not rewrite it.'), "started_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'), - "expires_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'), + "expires_at": zod.iso.datetime({"offset":true}).describe('Server deadline. For demo_express it is 180 to 300 seconds after started_at; for a corrective assessment it does not exceed chain_deadline.'), "sessions": zod.union([zod.object({ - "used": zod.int().min(1).max(assessmentAttemptSessionsOneUsedMax).describe('Sessions started so far, including the current one.'), - "max": zod.int().min(1).max(assessmentAttemptSessionsOneMaxMax), - "idle_timeout_seconds": zod.int().min(assessmentAttemptSessionsOneIdleTimeoutSecondsMin).max(assessmentAttemptSessionsOneIdleTimeoutSecondsMax).describe('Inactivity after which the current session ends.') -}).describe('Work sessions of the attempt, as the policy version limits them, for example two sessions within the time limit.\n\nA session starts with the creation of the attempt or, after the previous session ended, with the next GetMyAssessmentAttempt or command on the active attempt. It ends after `idle_timeout_seconds` without such a request. A request that would start a session beyond `max_sessions` starts none: the server moves the attempt to `expired` and answers with it (a read) or with 409 state_conflict (a command). Reading a terminal attempt or a result never starts a session.'),zod.null()]).describe('Session limit of the attempt, or null when its policy version defines none.'), + "used": zod.int().min(1).max(assessmentAttemptOneOneSessionsOneUsedMax).describe('Sessions started so far, including the current one.'), + "max": zod.int().min(1).max(assessmentAttemptOneOneSessionsOneMaxMax), + "idle_timeout_seconds": zod.int().min(assessmentAttemptOneOneSessionsOneIdleTimeoutSecondsMin).max(assessmentAttemptOneOneSessionsOneIdleTimeoutSecondsMax).describe('Inactivity after which the current session ends.') +}).describe('Work sessions of the attempt, as the policy version limits them, for example two sessions within the time limit.\n\nSession 1 starts with attempt creation. After it ends due to `idle_timeout_seconds` of inactivity, the candidate explicitly starts or resumes work with StartMyAssessmentAttemptSession. GetMyAssessmentAttempt and GetMyAssessmentResult are read-only and never start a session. The session command checks the attempt deadline and `max_sessions`; when either limit has passed, it records the due terminal transition and returns the resulting attempt. Reads of terminal attempts do not change them.'),zod.null()]).describe('Session limit of the attempt, or null when its policy defines none.'), "finished_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('Time the attempt reached a terminal state, or null while it is active.'), "progress": zod.object({ - "answered_items": zod.int().min(assessmentAttemptProgressAnsweredItemsMin).max(assessmentAttemptProgressAnsweredItemsMax), - "max_items": zod.int().min(1).max(assessmentAttemptProgressMaxItemsMax).describe('Item limit of the attempt: the form size in demo_basic, or the policy limit of scored and seed items together in adaptive.') + "answered_items": zod.int().min(assessmentAttemptOneOneProgressAnsweredItemsMin).max(assessmentAttemptOneOneProgressAnsweredItemsMax), + "max_items": zod.int().min(1).max(assessmentAttemptOneOneProgressMaxItemsMax).describe('Item limit of the attempt: the form size in demo_basic, or the policy limit of scored and seed items together in adaptive.') }).describe('Progress of the item part. It counts seed items like scored ones, so it does not reveal which items are scored. An adaptive attempt may end its item part before `max_items` by its stop rule. A finalize refused as premature does not list the unfinished parts; the client reads them here, in `current_item`, and in `practices`.'), "current_item": zod.union([zod.object({ "id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'), - "sequence": zod.int().min(1).max(assessmentAttemptCurrentItemOneSequenceMax).describe('Position of the item in the attempt, from 1.'), - "prompt": zod.string().min(1).max(assessmentAttemptCurrentItemOnePromptMax).describe('Statement in Russian. Plain text with line breaks; the client shows it as text, never as HTML.'), + "sequence": zod.int().min(1).max(assessmentAttemptOneOneCurrentItemOneSequenceMax).describe('Position of the item in the attempt, from 1.'), + "prompt": zod.string().min(1).max(assessmentAttemptOneOneCurrentItemOnePromptMax).describe('Statement in Russian. Plain text with line breaks; the client shows it as text, never as HTML.'), "content": zod.union([zod.object({ "format": zod.enum(['choice']), "options": zod.array(zod.object({ - "id": zod.string().min(1).max(assessmentAttemptCurrentItemOneContentOneOptionsItemIdMax).regex(assessmentAttemptCurrentItemOneContentOneOptionsItemIdRegExp).describe('Opaque identifier of a choice option or an order element within one item instance. It is unrelated to the position or correctness of the option.'), - "text": zod.string().min(1).max(assessmentAttemptCurrentItemOneContentOneOptionsItemTextMax).describe('Text of the option; the client shows it as text, never as HTML.') -}).describe('Choice option or order element. Plain text.')).min(assessmentAttemptCurrentItemOneContentOneOptionsMin).max(assessmentAttemptCurrentItemOneContentOneOptionsMax).describe('Options in the order of this instance.'), + "id": zod.string().min(1).max(assessmentAttemptOneOneCurrentItemOneContentOneOptionsItemIdMax).regex(assessmentAttemptOneOneCurrentItemOneContentOneOptionsItemIdRegExp).describe('Opaque identifier of a choice option or an order element within one item instance. It is unrelated to the position or correctness of the option.'), + "text": zod.string().min(1).max(assessmentAttemptOneOneCurrentItemOneContentOneOptionsItemTextMax).describe('Text of the option; the client shows it as text, never as HTML.') +}).describe('Choice option or order element. Plain text.')).min(assessmentAttemptOneOneCurrentItemOneContentOneOptionsMin).max(assessmentAttemptOneOneCurrentItemOneContentOneOptionsMax).describe('Options in the order of this instance.'), "multiple": zod.boolean().describe('Whether more than one option may be selected. It is a property of the task family, fixed for every variant, and never derived from the key: a multiple-choice variant may have a single correct option.') }).describe('Choose one option, or several when `multiple` is true. The content never says which options are correct or how many are.'),zod.object({ "format": zod.enum(['number']), - "unit": zod.string().min(1).max(assessmentAttemptCurrentItemOneContentTwoUnitMax).nullable().describe('Unit of the expected value, for example `ms`, or null.') + "unit": zod.string().min(1).max(assessmentAttemptOneOneCurrentItemOneContentTwoUnitMax).nullable().describe('Unit of the expected value, for example `ms`, or null.') }).describe('Enter a number, optionally in the given unit.'),zod.object({ "format": zod.enum(['string']), - "max_length": zod.int().min(1).max(assessmentAttemptCurrentItemOneContentThreeMaxLengthMax).describe('Maximum length of the answer in characters. It is an input limit of the task family, never derived from the key, so it does not reveal the length of the correct answer.') + "max_length": zod.int().min(1).max(assessmentAttemptOneOneCurrentItemOneContentThreeMaxLengthMax).describe('Maximum length of the answer in characters. It is an input limit of the task family, never derived from the key, so it does not reveal the length of the correct answer.') }).describe('Enter a short string, such as a command, a header name, or an address.'),zod.object({ "format": zod.enum(['order']), "elements": zod.array(zod.object({ - "id": zod.string().min(1).max(assessmentAttemptCurrentItemOneContentFourElementsItemIdMax).regex(assessmentAttemptCurrentItemOneContentFourElementsItemIdRegExp).describe('Opaque identifier of a choice option or an order element within one item instance. It is unrelated to the position or correctness of the option.'), - "text": zod.string().min(1).max(assessmentAttemptCurrentItemOneContentFourElementsItemTextMax).describe('Text of the option; the client shows it as text, never as HTML.') -}).describe('Choice option or order element. Plain text.')).min(assessmentAttemptCurrentItemOneContentFourElementsMin).max(assessmentAttemptCurrentItemOneContentFourElementsMax) + "id": zod.string().min(1).max(assessmentAttemptOneOneCurrentItemOneContentFourElementsItemIdMax).regex(assessmentAttemptOneOneCurrentItemOneContentFourElementsItemIdRegExp).describe('Opaque identifier of a choice option or an order element within one item instance. It is unrelated to the position or correctness of the option.'), + "text": zod.string().min(1).max(assessmentAttemptOneOneCurrentItemOneContentFourElementsItemTextMax).describe('Text of the option; the client shows it as text, never as HTML.') +}).describe('Choice option or order element. Plain text.')).min(assessmentAttemptOneOneCurrentItemOneContentFourElementsMin).max(assessmentAttemptOneOneCurrentItemOneContentFourElementsMax) }).describe('Put every element into the right order. The elements arrive in the order of this instance, which is never the answer.'),zod.object({ "format": zod.enum(['find_error']), - "syntax": zod.string().min(1).max(assessmentAttemptCurrentItemOneContentFiveSyntaxMax).regex(assessmentAttemptCurrentItemOneContentFiveSyntaxRegExp).nullable().describe('Highlighting hint such as `go`, `python`, or `cisco_ios`, or null.'), + "syntax": zod.string().min(1).max(assessmentAttemptOneOneCurrentItemOneContentFiveSyntaxMax).regex(assessmentAttemptOneOneCurrentItemOneContentFiveSyntaxRegExp).nullable().describe('Highlighting hint such as `go`, `python`, or `cisco_ios`, or null.'), "lines": zod.array(zod.object({ - "number": zod.int().min(1).max(assessmentAttemptCurrentItemOneContentFiveLinesItemNumberMax), - "text": zod.string().max(assessmentAttemptCurrentItemOneContentFiveLinesItemTextMax) -}).describe('One numbered line of a code or configuration fragment. Plain text.')).min(1).max(assessmentAttemptCurrentItemOneContentFiveLinesMax).describe('Lines numbered from 1 in order.'), - "max_selections": zod.int().min(1).max(assessmentAttemptCurrentItemOneContentFiveMaxSelectionsMax).describe('Maximum number of lines the answer may select. It is a limit of the task family, fixed for every variant and never derived from the key; it is not the number of wrong lines.') + "number": zod.int().min(1).max(assessmentAttemptOneOneCurrentItemOneContentFiveLinesItemNumberMax), + "text": zod.string().max(assessmentAttemptOneOneCurrentItemOneContentFiveLinesItemTextMax) +}).describe('One numbered line of a code or configuration fragment. Plain text.')).min(1).max(assessmentAttemptOneOneCurrentItemOneContentFiveLinesMax).describe('Lines numbered from 1 in order.'), + "max_selections": zod.int().min(1).max(assessmentAttemptOneOneCurrentItemOneContentFiveMaxSelectionsMax).describe('Maximum number of lines the answer may select. It is a limit of the task family, fixed for every variant and never derived from the key; it is not the number of wrong lines.') }).describe('Find the lines with the error in a code or configuration fragment and select up to `max_selections` line numbers.'),zod.object({ "format": zod.enum(['configuration']), - "syntax": zod.string().min(1).max(assessmentAttemptCurrentItemOneContentSixSyntaxMax).regex(assessmentAttemptCurrentItemOneContentSixSyntaxRegExp).describe('Configuration syntax such as `cisco_ios`, `nginx`, or `yaml`.'), - "initial_config": zod.string().max(assessmentAttemptCurrentItemOneContentSixInitialConfigMax).describe('Starting text to edit; empty when the candidate writes it from scratch.'), - "max_length": zod.int().min(1).max(assessmentAttemptCurrentItemOneContentSixMaxLengthMax).describe('Maximum length of the submitted configuration in characters, an input limit of the task family that is never derived from the key.') + "syntax": zod.string().min(1).max(assessmentAttemptOneOneCurrentItemOneContentSixSyntaxMax).regex(assessmentAttemptOneOneCurrentItemOneContentSixSyntaxRegExp).describe('Configuration syntax such as `cisco_ios`, `nginx`, or `yaml`.'), + "initial_config": zod.string().max(assessmentAttemptOneOneCurrentItemOneContentSixInitialConfigMax).describe('Starting text to edit; empty when the candidate writes it from scratch.'), + "max_length": zod.int().min(1).max(assessmentAttemptOneOneCurrentItemOneContentSixMaxLengthMax).describe('Maximum length of the submitted configuration in characters, an input limit of the task family that is never derived from the key.') }).describe('Write or fix a configuration. The server checks the submitted text with the computed key or reference check of the task family; it never executes it as code.'),zod.object({ "format": zod.enum(['practice']), - "languages": zod.array(zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.')).max(assessmentAttemptCurrentItemOneContentSevenLanguagesMax).describe('Languages the solution may use. Empty when the task does not offer a choice; the submission then sends a null language.'), + "languages": zod.array(zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.')).max(assessmentAttemptOneOneCurrentItemOneContentSevenLanguagesMax).describe('Languages the solution may use. Empty when the task does not offer a choice; the submission then sends a null language.'), "public_examples": zod.array(zod.object({ - "input": zod.string().max(assessmentAttemptCurrentItemOneContentSevenPublicExamplesItemInputMax), - "expected_output": zod.string().max(assessmentAttemptCurrentItemOneContentSevenPublicExamplesItemExpectedOutputMax) -}).describe('Public example of the practice task: an input and its expected output. Hidden checks are never listed.')).max(assessmentAttemptCurrentItemOneContentSevenPublicExamplesMax), - "max_source_length": zod.int().min(1).max(assessmentAttemptCurrentItemOneContentSevenMaxSourceLengthMax).describe('Maximum length of the solution source in characters.') + "input": zod.string().max(assessmentAttemptOneOneCurrentItemOneContentSevenPublicExamplesItemInputMax), + "expected_output": zod.string().max(assessmentAttemptOneOneCurrentItemOneContentSevenPublicExamplesItemExpectedOutputMax) +}).describe('Public example of the practice task: an input and its expected output. Hidden checks are never listed.')).max(assessmentAttemptOneOneCurrentItemOneContentSevenPublicExamplesMax), + "max_source_length": zod.int().min(1).max(assessmentAttemptOneOneCurrentItemOneContentSevenMaxSourceLengthMax).describe('Maximum length of the solution source in characters.') }).describe('Code practice. The candidate submits one final solution, which runs in the isolated sandbox against three groups of hidden checks. The content lists only the statement, the allowed languages, and public examples; hidden checks, their inputs, and seeds never reach the client.')]).describe('Format-specific part of an item, selected by `format`. It holds only what the candidate needs to answer: never an answer key, a correct option, a score, a family or variant identifier, a seed, or a hidden check. Limits such as `multiple`, `max_selections`, and `max_length` belong to the format or the task family and never reveal the key.') }).describe('Item instance served to the candidate. The variant is fixed when it is first served: a reload, a retried request, or a resumed session returns the same instance with the same text and option order. The item never says whether an earlier answer was correct, and seed items, which are not scored, are indistinguishable from scored ones.'),zod.null()]).describe('Item to answer now: a test item in `in_progress`, the practice item to submit in `practice_pending` or `additional_practice_pending` while that practice is `not_started` or `failed`, and null otherwise.'), "practices": zod.array(zod.object({ @@ -175,16 +360,222 @@ export const AssessmentAttempt = zod.object({ "status": zod.enum(['not_started', 'pending', 'finished', 'failed']).describe('State of a practice.\n\n- not_started: no solution was submitted yet.\n- pending: the submitted solution is queued or running in the sandbox.\n- finished: the sandbox ran the solution and returned a verdict; `verdict` holds it. Every outcome caused by the solution itself, such as a compilation error, a runtime error, a time limit, or a memory limit, is `finished` with the affected groups not passed.\n- failed: the sandbox infrastructure could not run the solution, for example because its queue was full or an executor broke, independently of the solution. The failure is not the candidate\'s and consumes nothing; the practice can be submitted again.'), "submitted_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('Time of the latest submission, or null before the first one.'), "verdict": zod.union([zod.object({ - "score": zod.int().min(assessmentAttemptPracticesItemVerdictOneScoreMin).max(assessmentAttemptPracticesItemVerdictOneScoreMax), - "max_score": zod.int().min(assessmentAttemptPracticesItemVerdictOneMaxScoreMin).max(assessmentAttemptPracticesItemVerdictOneMaxScoreMax), + "score": zod.int().min(assessmentAttemptOneOnePracticesItemVerdictOneScoreMin).max(assessmentAttemptOneOnePracticesItemVerdictOneScoreMax), + "max_score": zod.int().min(assessmentAttemptOneOnePracticesItemVerdictOneMaxScoreMin).max(assessmentAttemptOneOnePracticesItemVerdictOneMaxScoreMax), "groups": zod.array(zod.object({ - "group": zod.int().min(1).max(assessmentAttemptPracticesItemVerdictOneGroupsItemGroupMax), + "group": zod.int().min(1).max(assessmentAttemptOneOnePracticesItemVerdictOneGroupsItemGroupMax), "passed": zod.boolean() -}).describe('Outcome of one hidden check group. It never contains the checks themselves.')).min(assessmentAttemptPracticesItemVerdictOneGroupsMin).max(assessmentAttemptPracticesItemVerdictOneGroupsMax) +}).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(assessmentAttemptPracticesMax).describe('Practices in the order they were assigned: the `main` practice first, then an `additional` practice once finalize offers it. Empty only for a demo_basic attempt while code practice is disabled until the sandbox isolation is verified; its result then lists the `practice_not_included` limitation. A list rather than one field leaves room for more practices without a breaking change.') -}).describe('Assessment attempt of the current candidate for one category, a specialization and a target grade. It shows the state, the fixed versions, the server deadline `expires_at` from the policy version, which the client clock never extends, the session limit, the progress, the item to answer now, and the practices. It never contains answer keys, the correctness of submitted answers, scores of single items, family or variant identifiers, seeds, hidden checks, or anti-cheat signals.') +}).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('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']), + "specialization": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'), + "target_grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'), + "root_attempt_id": zod.null().describe('Root attempts have no parent attempt.'), + "chain_deadline": zod.null().describe('A root attempt has no correction-chain deadline.') +})).and(zod.object({ + "kind": zod.enum(['root']) +})),zod.object({ + "id": zod.uuid().describe('Attempt identifier.'), + "version": zod.int().min(1).describe('Version of an assessment attempt. A new attempt has version 1, and each committed change advances it by exactly one: an accepted answer, a practice submission or resubmission, a verdict, a decision of finalize, an explicit work-session start, and a server-side transition such as expiry or automatic finalization. Reads never change the attempt. A rejected command and a repeat that stores nothing leave it unchanged. Commands send the version they read as `expected_version`.'), + "specialization": zod.union([zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'),zod.null()]).describe('Null only for demo_express, which has no qualification category.'), + "target_grade": zod.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Null only for demo_express, which has no qualification category.'), + "task_language": zod.union([zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.'),zod.null()]).describe('Task language of the attempt, or null when none is selected.'), + "kind": zod.enum(['root', 'corrective', 'demo_express']).describe('Assessment track that distinguishes root, corrective, and training attempts.'), + "root_attempt_id": zod.union([zod.uuid(),zod.null()]).describe('Present only for a corrective real assessment. It identifies the root attempt whose quota and chain deadline this attempt shares.'), + "chain_deadline": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('Present only for a corrective real assessment. It is the immutable deadline derived from the root attempt and is not extended by a lower target grade.'), + "mode": zod.enum(['demo_basic', 'demo_express', 'adaptive']).describe('Method of an assessment attempt. For a real assessment, the server selects demo_basic or adaptive from the published bank. A candidate may explicitly request demo_express, which uses a separate training policy and creates no qualification evidence.\n\n- demo_basic: a fixed form of reviewed demo items scored by their keys against the pass mark of the versioned basic grading policy. It computes no ability estimate, standard error, or probability, so every uncertainty field of its result is null, its thresholds are uncalibrated, and its decision is binary: it never offers an additional practice.\n- adaptive: the adaptive test on task families with an ability estimate, its standard error, and the probability of reaching the grade threshold, as the versioned assessment policy defines them. A probability in the band below confirmation offers one additional practice in the same attempt.\n- demo_express: an interactive 3 to 5 minute training run under a separate policy. It does not assign a category or percentile, count toward the real-assessment quota, or create qualification evidence.\n\nAdding a value is a contract change.'), + "state": zod.enum(['in_progress', 'practice_pending', 'additional_practice_pending', 'ready_to_finalize', 'completed', 'expired', 'insufficient_bank']).describe('Lifecycle state of an attempt and the commands it accepts.\n\n- in_progress: items are being answered; `current_item` is the item to answer. Accepts SubmitMyAssessmentAnswer for that item.\n- practice_pending: the item part is finished, and the main practice has no finished verdict yet: it is not submitted, its verdict is pending in the sandbox, or the sandbox failed and the practice can be submitted again. Accepts SubmitMyAssessmentAnswer with the practice item while its status is `not_started` or `failed`. No grade is confirmed while the practice is unfinished, even when the adaptive stop rule has already ended the item part.\n- additional_practice_pending: adaptive only. Finalize found the probability of reaching the grade in the band below confirmation, so the attempt offers one additional practice without spending a new attempt; it keeps the time and session limits of the attempt. Accepts SubmitMyAssessmentAnswer with the additional practice item while its status is `not_started` or `failed`, and FinalizeMyAssessmentAttempt in the same statuses, which declines the offer and decides `not_confirmed` with the current evidence.\n- ready_to_finalize: every required part is done, including a submitted additional practice with a finished verdict. Accepts FinalizeMyAssessmentAttempt.\n- completed: a decision was made; the result is available.\n- expired: the time or session limit passed before the candidate finished the required parts. The result is available and confirms no grade.\n- insufficient_bank: the published bank could not supply the items required for coverage within the limit, and the attempt ended without a confirmed grade instead of repeating families. The result is available.\n\nWhen `expires_at` passes or the session limit is reached, a read returns the stored state without changing it. A command or background transition commits any due outcome and advances the version. A practice submitted before the limit and still `pending` is graded first. Then `ready_to_finalize` becomes `completed`; `additional_practice_pending` with the additional practice not submitted is finalized as declined and becomes `completed` with `not_confirmed`; `in_progress` and `practice_pending` become `expired`, with the result reason `expired` or `practice_incomplete`; and when the latest submission of a practice ended `failed`, the attempt becomes `expired` with the reason `sandbox_unavailable`, which is not the candidate\'s fault. `completed`, `expired`, and `insufficient_bank` are terminal and accept no command except the repeat of finalize described on FinalizeMyAssessmentAttempt. Adding a value is a contract change.'), + "versions": zod.object({ + "policy_version": zod.int().min(1).describe('Number of the `product` policy version whose assessment rules apply: thresholds, stop rules, item limits, time and session limits, and retry intervals.'), + "bank_version": zod.string().min(1).max(assessmentAttemptTwoOneVersionsBankVersionMax).regex(assessmentAttemptTwoOneVersionsBankVersionRegExp).describe('Opaque identifier of a published version, for example `backend-demo.2026-10.1`. Clients show it as text and never parse it.'), + "algorithm_version": zod.string().min(1).max(assessmentAttemptTwoOneVersionsAlgorithmVersionMax).regex(assessmentAttemptTwoOneVersionsAlgorithmVersionRegExp).describe('Opaque identifier of a published version, for example `backend-demo.2026-10.1`. Clients show it as text and never parse it.') +}).describe('Versions fixed when the attempt was created. They never change during the attempt, and a result is always reproduced from the stored answers with these versions; a later policy, bank, or algorithm version does not rewrite it.'), + "started_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'), + "expires_at": zod.iso.datetime({"offset":true}).describe('Server deadline. For demo_express it is 180 to 300 seconds after started_at; for a corrective assessment it does not exceed chain_deadline.'), + "sessions": zod.union([zod.object({ + "used": zod.int().min(1).max(assessmentAttemptTwoOneSessionsOneUsedMax).describe('Sessions started so far, including the current one.'), + "max": zod.int().min(1).max(assessmentAttemptTwoOneSessionsOneMaxMax), + "idle_timeout_seconds": zod.int().min(assessmentAttemptTwoOneSessionsOneIdleTimeoutSecondsMin).max(assessmentAttemptTwoOneSessionsOneIdleTimeoutSecondsMax).describe('Inactivity after which the current session ends.') +}).describe('Work sessions of the attempt, as the policy version limits them, for example two sessions within the time limit.\n\nSession 1 starts with attempt creation. After it ends due to `idle_timeout_seconds` of inactivity, the candidate explicitly starts or resumes work with StartMyAssessmentAttemptSession. GetMyAssessmentAttempt and GetMyAssessmentResult are read-only and never start a session. The session command checks the attempt deadline and `max_sessions`; when either limit has passed, it records the due terminal transition and returns the resulting attempt. Reads of terminal attempts do not change them.'),zod.null()]).describe('Session limit of the attempt, or null when its policy defines none.'), + "finished_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('Time the attempt reached a terminal state, or null while it is active.'), + "progress": zod.object({ + "answered_items": zod.int().min(assessmentAttemptTwoOneProgressAnsweredItemsMin).max(assessmentAttemptTwoOneProgressAnsweredItemsMax), + "max_items": zod.int().min(1).max(assessmentAttemptTwoOneProgressMaxItemsMax).describe('Item limit of the attempt: the form size in demo_basic, or the policy limit of scored and seed items together in adaptive.') +}).describe('Progress of the item part. It counts seed items like scored ones, so it does not reveal which items are scored. An adaptive attempt may end its item part before `max_items` by its stop rule. A finalize refused as premature does not list the unfinished parts; the client reads them here, in `current_item`, and in `practices`.'), + "current_item": zod.union([zod.object({ + "id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'), + "sequence": zod.int().min(1).max(assessmentAttemptTwoOneCurrentItemOneSequenceMax).describe('Position of the item in the attempt, from 1.'), + "prompt": zod.string().min(1).max(assessmentAttemptTwoOneCurrentItemOnePromptMax).describe('Statement in Russian. Plain text with line breaks; the client shows it as text, never as HTML.'), + "content": zod.union([zod.object({ + "format": zod.enum(['choice']), + "options": zod.array(zod.object({ + "id": zod.string().min(1).max(assessmentAttemptTwoOneCurrentItemOneContentOneOptionsItemIdMax).regex(assessmentAttemptTwoOneCurrentItemOneContentOneOptionsItemIdRegExp).describe('Opaque identifier of a choice option or an order element within one item instance. It is unrelated to the position or correctness of the option.'), + "text": zod.string().min(1).max(assessmentAttemptTwoOneCurrentItemOneContentOneOptionsItemTextMax).describe('Text of the option; the client shows it as text, never as HTML.') +}).describe('Choice option or order element. Plain text.')).min(assessmentAttemptTwoOneCurrentItemOneContentOneOptionsMin).max(assessmentAttemptTwoOneCurrentItemOneContentOneOptionsMax).describe('Options in the order of this instance.'), + "multiple": zod.boolean().describe('Whether more than one option may be selected. It is a property of the task family, fixed for every variant, and never derived from the key: a multiple-choice variant may have a single correct option.') +}).describe('Choose one option, or several when `multiple` is true. The content never says which options are correct or how many are.'),zod.object({ + "format": zod.enum(['number']), + "unit": zod.string().min(1).max(assessmentAttemptTwoOneCurrentItemOneContentTwoUnitMax).nullable().describe('Unit of the expected value, for example `ms`, or null.') +}).describe('Enter a number, optionally in the given unit.'),zod.object({ + "format": zod.enum(['string']), + "max_length": zod.int().min(1).max(assessmentAttemptTwoOneCurrentItemOneContentThreeMaxLengthMax).describe('Maximum length of the answer in characters. It is an input limit of the task family, never derived from the key, so it does not reveal the length of the correct answer.') +}).describe('Enter a short string, such as a command, a header name, or an address.'),zod.object({ + "format": zod.enum(['order']), + "elements": zod.array(zod.object({ + "id": zod.string().min(1).max(assessmentAttemptTwoOneCurrentItemOneContentFourElementsItemIdMax).regex(assessmentAttemptTwoOneCurrentItemOneContentFourElementsItemIdRegExp).describe('Opaque identifier of a choice option or an order element within one item instance. It is unrelated to the position or correctness of the option.'), + "text": zod.string().min(1).max(assessmentAttemptTwoOneCurrentItemOneContentFourElementsItemTextMax).describe('Text of the option; the client shows it as text, never as HTML.') +}).describe('Choice option or order element. Plain text.')).min(assessmentAttemptTwoOneCurrentItemOneContentFourElementsMin).max(assessmentAttemptTwoOneCurrentItemOneContentFourElementsMax) +}).describe('Put every element into the right order. The elements arrive in the order of this instance, which is never the answer.'),zod.object({ + "format": zod.enum(['find_error']), + "syntax": zod.string().min(1).max(assessmentAttemptTwoOneCurrentItemOneContentFiveSyntaxMax).regex(assessmentAttemptTwoOneCurrentItemOneContentFiveSyntaxRegExp).nullable().describe('Highlighting hint such as `go`, `python`, or `cisco_ios`, or null.'), + "lines": zod.array(zod.object({ + "number": zod.int().min(1).max(assessmentAttemptTwoOneCurrentItemOneContentFiveLinesItemNumberMax), + "text": zod.string().max(assessmentAttemptTwoOneCurrentItemOneContentFiveLinesItemTextMax) +}).describe('One numbered line of a code or configuration fragment. Plain text.')).min(1).max(assessmentAttemptTwoOneCurrentItemOneContentFiveLinesMax).describe('Lines numbered from 1 in order.'), + "max_selections": zod.int().min(1).max(assessmentAttemptTwoOneCurrentItemOneContentFiveMaxSelectionsMax).describe('Maximum number of lines the answer may select. It is a limit of the task family, fixed for every variant and never derived from the key; it is not the number of wrong lines.') +}).describe('Find the lines with the error in a code or configuration fragment and select up to `max_selections` line numbers.'),zod.object({ + "format": zod.enum(['configuration']), + "syntax": zod.string().min(1).max(assessmentAttemptTwoOneCurrentItemOneContentSixSyntaxMax).regex(assessmentAttemptTwoOneCurrentItemOneContentSixSyntaxRegExp).describe('Configuration syntax such as `cisco_ios`, `nginx`, or `yaml`.'), + "initial_config": zod.string().max(assessmentAttemptTwoOneCurrentItemOneContentSixInitialConfigMax).describe('Starting text to edit; empty when the candidate writes it from scratch.'), + "max_length": zod.int().min(1).max(assessmentAttemptTwoOneCurrentItemOneContentSixMaxLengthMax).describe('Maximum length of the submitted configuration in characters, an input limit of the task family that is never derived from the key.') +}).describe('Write or fix a configuration. The server checks the submitted text with the computed key or reference check of the task family; it never executes it as code.'),zod.object({ + "format": zod.enum(['practice']), + "languages": zod.array(zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.')).max(assessmentAttemptTwoOneCurrentItemOneContentSevenLanguagesMax).describe('Languages the solution may use. Empty when the task does not offer a choice; the submission then sends a null language.'), + "public_examples": zod.array(zod.object({ + "input": zod.string().max(assessmentAttemptTwoOneCurrentItemOneContentSevenPublicExamplesItemInputMax), + "expected_output": zod.string().max(assessmentAttemptTwoOneCurrentItemOneContentSevenPublicExamplesItemExpectedOutputMax) +}).describe('Public example of the practice task: an input and its expected output. Hidden checks are never listed.')).max(assessmentAttemptTwoOneCurrentItemOneContentSevenPublicExamplesMax), + "max_source_length": zod.int().min(1).max(assessmentAttemptTwoOneCurrentItemOneContentSevenMaxSourceLengthMax).describe('Maximum length of the solution source in characters.') +}).describe('Code practice. The candidate submits one final solution, which runs in the isolated sandbox against three groups of hidden checks. The content lists only the statement, the allowed languages, and public examples; hidden checks, their inputs, and seeds never reach the client.')]).describe('Format-specific part of an item, selected by `format`. It holds only what the candidate needs to answer: never an answer key, a correct option, a score, a family or variant identifier, a seed, or a hidden check. Limits such as `multiple`, `max_selections`, and `max_length` belong to the format or the task family and never reveal the key.') +}).describe('Item instance served to the candidate. The variant is fixed when it is first served: a reload, a retried request, or a resumed session returns the same instance with the same text and option order. The item never says whether an earlier answer was correct, and seed items, which are not scored, are indistinguishable from scored ones.'),zod.null()]).describe('Item to answer now: a test item in `in_progress`, the practice item to submit in `practice_pending` or `additional_practice_pending` while that practice is `not_started` or `failed`, and null otherwise.'), + "practices": zod.array(zod.object({ + "kind": zod.enum(['main', 'additional']).describe('Role of a practice in the attempt.\n\n- main: the practice that every attempt with practice requires before a decision.\n- additional: adaptive only; offered by finalize when the probability of reaching the grade is in the band below confirmation. It continues the same attempt and spends no new attempt.\n\nAdding a value is a contract change.'), + "item_id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'), + "status": zod.enum(['not_started', 'pending', 'finished', 'failed']).describe('State of a practice.\n\n- not_started: no solution was submitted yet.\n- pending: the submitted solution is queued or running in the sandbox.\n- finished: the sandbox ran the solution and returned a verdict; `verdict` holds it. Every outcome caused by the solution itself, such as a compilation error, a runtime error, a time limit, or a memory limit, is `finished` with the affected groups not passed.\n- failed: the sandbox infrastructure could not run the solution, for example because its queue was full or an executor broke, independently of the solution. The failure is not the candidate\'s and consumes nothing; the practice can be submitted again.'), + "submitted_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('Time of the latest submission, or null before the first one.'), + "verdict": zod.union([zod.object({ + "score": zod.int().min(assessmentAttemptTwoOnePracticesItemVerdictOneScoreMin).max(assessmentAttemptTwoOnePracticesItemVerdictOneScoreMax), + "max_score": zod.int().min(assessmentAttemptTwoOnePracticesItemVerdictOneMaxScoreMin).max(assessmentAttemptTwoOnePracticesItemVerdictOneMaxScoreMax), + "groups": zod.array(zod.object({ + "group": zod.int().min(1).max(assessmentAttemptTwoOnePracticesItemVerdictOneGroupsItemGroupMax), + "passed": zod.boolean() +}).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('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']), + "specialization": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'), + "target_grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'), + "root_attempt_id": zod.uuid(), + "chain_deadline": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.') +})).and(zod.object({ + "kind": zod.enum(['corrective']) +})),zod.object({ + "id": zod.uuid().describe('Attempt identifier.'), + "version": zod.int().min(1).describe('Version of an assessment attempt. A new attempt has version 1, and each committed change advances it by exactly one: an accepted answer, a practice submission or resubmission, a verdict, a decision of finalize, an explicit work-session start, and a server-side transition such as expiry or automatic finalization. Reads never change the attempt. A rejected command and a repeat that stores nothing leave it unchanged. Commands send the version they read as `expected_version`.'), + "specialization": zod.union([zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'),zod.null()]).describe('Null only for demo_express, which has no qualification category.'), + "target_grade": zod.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Null only for demo_express, which has no qualification category.'), + "task_language": zod.union([zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.'),zod.null()]).describe('Task language of the attempt, or null when none is selected.'), + "kind": zod.enum(['root', 'corrective', 'demo_express']).describe('Assessment track that distinguishes root, corrective, and training attempts.'), + "root_attempt_id": zod.union([zod.uuid(),zod.null()]).describe('Present only for a corrective real assessment. It identifies the root attempt whose quota and chain deadline this attempt shares.'), + "chain_deadline": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('Present only for a corrective real assessment. It is the immutable deadline derived from the root attempt and is not extended by a lower target grade.'), + "mode": zod.enum(['demo_basic', 'demo_express', 'adaptive']).describe('Method of an assessment attempt. For a real assessment, the server selects demo_basic or adaptive from the published bank. A candidate may explicitly request demo_express, which uses a separate training policy and creates no qualification evidence.\n\n- demo_basic: a fixed form of reviewed demo items scored by their keys against the pass mark of the versioned basic grading policy. It computes no ability estimate, standard error, or probability, so every uncertainty field of its result is null, its thresholds are uncalibrated, and its decision is binary: it never offers an additional practice.\n- adaptive: the adaptive test on task families with an ability estimate, its standard error, and the probability of reaching the grade threshold, as the versioned assessment policy defines them. A probability in the band below confirmation offers one additional practice in the same attempt.\n- demo_express: an interactive 3 to 5 minute training run under a separate policy. It does not assign a category or percentile, count toward the real-assessment quota, or create qualification evidence.\n\nAdding a value is a contract change.'), + "state": zod.enum(['in_progress', 'practice_pending', 'additional_practice_pending', 'ready_to_finalize', 'completed', 'expired', 'insufficient_bank']).describe('Lifecycle state of an attempt and the commands it accepts.\n\n- in_progress: items are being answered; `current_item` is the item to answer. Accepts SubmitMyAssessmentAnswer for that item.\n- practice_pending: the item part is finished, and the main practice has no finished verdict yet: it is not submitted, its verdict is pending in the sandbox, or the sandbox failed and the practice can be submitted again. Accepts SubmitMyAssessmentAnswer with the practice item while its status is `not_started` or `failed`. No grade is confirmed while the practice is unfinished, even when the adaptive stop rule has already ended the item part.\n- additional_practice_pending: adaptive only. Finalize found the probability of reaching the grade in the band below confirmation, so the attempt offers one additional practice without spending a new attempt; it keeps the time and session limits of the attempt. Accepts SubmitMyAssessmentAnswer with the additional practice item while its status is `not_started` or `failed`, and FinalizeMyAssessmentAttempt in the same statuses, which declines the offer and decides `not_confirmed` with the current evidence.\n- ready_to_finalize: every required part is done, including a submitted additional practice with a finished verdict. Accepts FinalizeMyAssessmentAttempt.\n- completed: a decision was made; the result is available.\n- expired: the time or session limit passed before the candidate finished the required parts. The result is available and confirms no grade.\n- insufficient_bank: the published bank could not supply the items required for coverage within the limit, and the attempt ended without a confirmed grade instead of repeating families. The result is available.\n\nWhen `expires_at` passes or the session limit is reached, a read returns the stored state without changing it. A command or background transition commits any due outcome and advances the version. A practice submitted before the limit and still `pending` is graded first. Then `ready_to_finalize` becomes `completed`; `additional_practice_pending` with the additional practice not submitted is finalized as declined and becomes `completed` with `not_confirmed`; `in_progress` and `practice_pending` become `expired`, with the result reason `expired` or `practice_incomplete`; and when the latest submission of a practice ended `failed`, the attempt becomes `expired` with the reason `sandbox_unavailable`, which is not the candidate\'s fault. `completed`, `expired`, and `insufficient_bank` are terminal and accept no command except the repeat of finalize described on FinalizeMyAssessmentAttempt. Adding a value is a contract change.'), + "versions": zod.object({ + "policy_version": zod.int().min(1).describe('Number of the `product` policy version whose assessment rules apply: thresholds, stop rules, item limits, time and session limits, and retry intervals.'), + "bank_version": zod.string().min(1).max(assessmentAttemptThreeOneVersionsBankVersionMax).regex(assessmentAttemptThreeOneVersionsBankVersionRegExp).describe('Opaque identifier of a published version, for example `backend-demo.2026-10.1`. Clients show it as text and never parse it.'), + "algorithm_version": zod.string().min(1).max(assessmentAttemptThreeOneVersionsAlgorithmVersionMax).regex(assessmentAttemptThreeOneVersionsAlgorithmVersionRegExp).describe('Opaque identifier of a published version, for example `backend-demo.2026-10.1`. Clients show it as text and never parse it.') +}).describe('Versions fixed when the attempt was created. They never change during the attempt, and a result is always reproduced from the stored answers with these versions; a later policy, bank, or algorithm version does not rewrite it.'), + "started_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'), + "expires_at": zod.iso.datetime({"offset":true}).describe('Server deadline. For demo_express it is 180 to 300 seconds after started_at; for a corrective assessment it does not exceed chain_deadline.'), + "sessions": zod.union([zod.object({ + "used": zod.int().min(1).max(assessmentAttemptThreeOneSessionsOneUsedMax).describe('Sessions started so far, including the current one.'), + "max": zod.int().min(1).max(assessmentAttemptThreeOneSessionsOneMaxMax), + "idle_timeout_seconds": zod.int().min(assessmentAttemptThreeOneSessionsOneIdleTimeoutSecondsMin).max(assessmentAttemptThreeOneSessionsOneIdleTimeoutSecondsMax).describe('Inactivity after which the current session ends.') +}).describe('Work sessions of the attempt, as the policy version limits them, for example two sessions within the time limit.\n\nSession 1 starts with attempt creation. After it ends due to `idle_timeout_seconds` of inactivity, the candidate explicitly starts or resumes work with StartMyAssessmentAttemptSession. GetMyAssessmentAttempt and GetMyAssessmentResult are read-only and never start a session. The session command checks the attempt deadline and `max_sessions`; when either limit has passed, it records the due terminal transition and returns the resulting attempt. Reads of terminal attempts do not change them.'),zod.null()]).describe('Session limit of the attempt, or null when its policy defines none.'), + "finished_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('Time the attempt reached a terminal state, or null while it is active.'), + "progress": zod.object({ + "answered_items": zod.int().min(assessmentAttemptThreeOneProgressAnsweredItemsMin).max(assessmentAttemptThreeOneProgressAnsweredItemsMax), + "max_items": zod.int().min(1).max(assessmentAttemptThreeOneProgressMaxItemsMax).describe('Item limit of the attempt: the form size in demo_basic, or the policy limit of scored and seed items together in adaptive.') +}).describe('Progress of the item part. It counts seed items like scored ones, so it does not reveal which items are scored. An adaptive attempt may end its item part before `max_items` by its stop rule. A finalize refused as premature does not list the unfinished parts; the client reads them here, in `current_item`, and in `practices`.'), + "current_item": zod.union([zod.object({ + "id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'), + "sequence": zod.int().min(1).max(assessmentAttemptThreeOneCurrentItemOneSequenceMax).describe('Position of the item in the attempt, from 1.'), + "prompt": zod.string().min(1).max(assessmentAttemptThreeOneCurrentItemOnePromptMax).describe('Statement in Russian. Plain text with line breaks; the client shows it as text, never as HTML.'), + "content": zod.union([zod.object({ + "format": zod.enum(['choice']), + "options": zod.array(zod.object({ + "id": zod.string().min(1).max(assessmentAttemptThreeOneCurrentItemOneContentOneOptionsItemIdMax).regex(assessmentAttemptThreeOneCurrentItemOneContentOneOptionsItemIdRegExp).describe('Opaque identifier of a choice option or an order element within one item instance. It is unrelated to the position or correctness of the option.'), + "text": zod.string().min(1).max(assessmentAttemptThreeOneCurrentItemOneContentOneOptionsItemTextMax).describe('Text of the option; the client shows it as text, never as HTML.') +}).describe('Choice option or order element. Plain text.')).min(assessmentAttemptThreeOneCurrentItemOneContentOneOptionsMin).max(assessmentAttemptThreeOneCurrentItemOneContentOneOptionsMax).describe('Options in the order of this instance.'), + "multiple": zod.boolean().describe('Whether more than one option may be selected. It is a property of the task family, fixed for every variant, and never derived from the key: a multiple-choice variant may have a single correct option.') +}).describe('Choose one option, or several when `multiple` is true. The content never says which options are correct or how many are.'),zod.object({ + "format": zod.enum(['number']), + "unit": zod.string().min(1).max(assessmentAttemptThreeOneCurrentItemOneContentTwoUnitMax).nullable().describe('Unit of the expected value, for example `ms`, or null.') +}).describe('Enter a number, optionally in the given unit.'),zod.object({ + "format": zod.enum(['string']), + "max_length": zod.int().min(1).max(assessmentAttemptThreeOneCurrentItemOneContentThreeMaxLengthMax).describe('Maximum length of the answer in characters. It is an input limit of the task family, never derived from the key, so it does not reveal the length of the correct answer.') +}).describe('Enter a short string, such as a command, a header name, or an address.'),zod.object({ + "format": zod.enum(['order']), + "elements": zod.array(zod.object({ + "id": zod.string().min(1).max(assessmentAttemptThreeOneCurrentItemOneContentFourElementsItemIdMax).regex(assessmentAttemptThreeOneCurrentItemOneContentFourElementsItemIdRegExp).describe('Opaque identifier of a choice option or an order element within one item instance. It is unrelated to the position or correctness of the option.'), + "text": zod.string().min(1).max(assessmentAttemptThreeOneCurrentItemOneContentFourElementsItemTextMax).describe('Text of the option; the client shows it as text, never as HTML.') +}).describe('Choice option or order element. Plain text.')).min(assessmentAttemptThreeOneCurrentItemOneContentFourElementsMin).max(assessmentAttemptThreeOneCurrentItemOneContentFourElementsMax) +}).describe('Put every element into the right order. The elements arrive in the order of this instance, which is never the answer.'),zod.object({ + "format": zod.enum(['find_error']), + "syntax": zod.string().min(1).max(assessmentAttemptThreeOneCurrentItemOneContentFiveSyntaxMax).regex(assessmentAttemptThreeOneCurrentItemOneContentFiveSyntaxRegExp).nullable().describe('Highlighting hint such as `go`, `python`, or `cisco_ios`, or null.'), + "lines": zod.array(zod.object({ + "number": zod.int().min(1).max(assessmentAttemptThreeOneCurrentItemOneContentFiveLinesItemNumberMax), + "text": zod.string().max(assessmentAttemptThreeOneCurrentItemOneContentFiveLinesItemTextMax) +}).describe('One numbered line of a code or configuration fragment. Plain text.')).min(1).max(assessmentAttemptThreeOneCurrentItemOneContentFiveLinesMax).describe('Lines numbered from 1 in order.'), + "max_selections": zod.int().min(1).max(assessmentAttemptThreeOneCurrentItemOneContentFiveMaxSelectionsMax).describe('Maximum number of lines the answer may select. It is a limit of the task family, fixed for every variant and never derived from the key; it is not the number of wrong lines.') +}).describe('Find the lines with the error in a code or configuration fragment and select up to `max_selections` line numbers.'),zod.object({ + "format": zod.enum(['configuration']), + "syntax": zod.string().min(1).max(assessmentAttemptThreeOneCurrentItemOneContentSixSyntaxMax).regex(assessmentAttemptThreeOneCurrentItemOneContentSixSyntaxRegExp).describe('Configuration syntax such as `cisco_ios`, `nginx`, or `yaml`.'), + "initial_config": zod.string().max(assessmentAttemptThreeOneCurrentItemOneContentSixInitialConfigMax).describe('Starting text to edit; empty when the candidate writes it from scratch.'), + "max_length": zod.int().min(1).max(assessmentAttemptThreeOneCurrentItemOneContentSixMaxLengthMax).describe('Maximum length of the submitted configuration in characters, an input limit of the task family that is never derived from the key.') +}).describe('Write or fix a configuration. The server checks the submitted text with the computed key or reference check of the task family; it never executes it as code.'),zod.object({ + "format": zod.enum(['practice']), + "languages": zod.array(zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.')).max(assessmentAttemptThreeOneCurrentItemOneContentSevenLanguagesMax).describe('Languages the solution may use. Empty when the task does not offer a choice; the submission then sends a null language.'), + "public_examples": zod.array(zod.object({ + "input": zod.string().max(assessmentAttemptThreeOneCurrentItemOneContentSevenPublicExamplesItemInputMax), + "expected_output": zod.string().max(assessmentAttemptThreeOneCurrentItemOneContentSevenPublicExamplesItemExpectedOutputMax) +}).describe('Public example of the practice task: an input and its expected output. Hidden checks are never listed.')).max(assessmentAttemptThreeOneCurrentItemOneContentSevenPublicExamplesMax), + "max_source_length": zod.int().min(1).max(assessmentAttemptThreeOneCurrentItemOneContentSevenMaxSourceLengthMax).describe('Maximum length of the solution source in characters.') +}).describe('Code practice. The candidate submits one final solution, which runs in the isolated sandbox against three groups of hidden checks. The content lists only the statement, the allowed languages, and public examples; hidden checks, their inputs, and seeds never reach the client.')]).describe('Format-specific part of an item, selected by `format`. It holds only what the candidate needs to answer: never an answer key, a correct option, a score, a family or variant identifier, a seed, or a hidden check. Limits such as `multiple`, `max_selections`, and `max_length` belong to the format or the task family and never reveal the key.') +}).describe('Item instance served to the candidate. The variant is fixed when it is first served: a reload, a retried request, or a resumed session returns the same instance with the same text and option order. The item never says whether an earlier answer was correct, and seed items, which are not scored, are indistinguishable from scored ones.'),zod.null()]).describe('Item to answer now: a test item in `in_progress`, the practice item to submit in `practice_pending` or `additional_practice_pending` while that practice is `not_started` or `failed`, and null otherwise.'), + "practices": zod.array(zod.object({ + "kind": zod.enum(['main', 'additional']).describe('Role of a practice in the attempt.\n\n- main: the practice that every attempt with practice requires before a decision.\n- additional: adaptive only; offered by finalize when the probability of reaching the grade is in the band below confirmation. It continues the same attempt and spends no new attempt.\n\nAdding a value is a contract change.'), + "item_id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'), + "status": zod.enum(['not_started', 'pending', 'finished', 'failed']).describe('State of a practice.\n\n- not_started: no solution was submitted yet.\n- pending: the submitted solution is queued or running in the sandbox.\n- finished: the sandbox ran the solution and returned a verdict; `verdict` holds it. Every outcome caused by the solution itself, such as a compilation error, a runtime error, a time limit, or a memory limit, is `finished` with the affected groups not passed.\n- failed: the sandbox infrastructure could not run the solution, for example because its queue was full or an executor broke, independently of the solution. The failure is not the candidate\'s and consumes nothing; the practice can be submitted again.'), + "submitted_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('Time of the latest submission, or null before the first one.'), + "verdict": zod.union([zod.object({ + "score": zod.int().min(assessmentAttemptThreeOnePracticesItemVerdictOneScoreMin).max(assessmentAttemptThreeOnePracticesItemVerdictOneScoreMax), + "max_score": zod.int().min(assessmentAttemptThreeOnePracticesItemVerdictOneMaxScoreMin).max(assessmentAttemptThreeOnePracticesItemVerdictOneMaxScoreMax), + "groups": zod.array(zod.object({ + "group": zod.int().min(1).max(assessmentAttemptThreeOnePracticesItemVerdictOneGroupsItemGroupMax), + "passed": zod.boolean() +}).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('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']), + "specialization": zod.null(), + "target_grade": zod.null(), + "task_language": zod.null(), + "root_attempt_id": zod.null(), + "chain_deadline": zod.null() +})).and(zod.object({ + "kind": zod.enum(['demo_express']) +}))]).describe('Candidate view of a real assessment, a corrective real assessment, or a demo_express training run. The variants keep training output separate from qualification attempts.') export type AssessmentAttempt = zod.input; export type AssessmentAttemptOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentAttemptCommon.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentAttemptCommon.zod.ts new file mode 100644 index 0000000..e8aada7 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentAttemptCommon.zod.ts @@ -0,0 +1,193 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + + + +export const assessmentAttemptCommonVersionsBankVersionMax = 64; + + +export const assessmentAttemptCommonVersionsBankVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$'); +export const assessmentAttemptCommonVersionsAlgorithmVersionMax = 64; + + +export const assessmentAttemptCommonVersionsAlgorithmVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$'); +export const assessmentAttemptCommonSessionsOneUsedMax = 10; + +export const assessmentAttemptCommonSessionsOneMaxMax = 10; + +export const assessmentAttemptCommonSessionsOneIdleTimeoutSecondsMin = 60; +export const assessmentAttemptCommonSessionsOneIdleTimeoutSecondsMax = 86400; + +export const assessmentAttemptCommonProgressAnsweredItemsMin = 0; +export const assessmentAttemptCommonProgressAnsweredItemsMax = 100; + +export const assessmentAttemptCommonProgressMaxItemsMax = 100; + +export const assessmentAttemptCommonCurrentItemOneSequenceMax = 100; + +export const assessmentAttemptCommonCurrentItemOnePromptMax = 20000; + +export const assessmentAttemptCommonCurrentItemOneContentOneOptionsItemIdMax = 32; + + +export const assessmentAttemptCommonCurrentItemOneContentOneOptionsItemIdRegExp = new RegExp('^[A-Za-z0-9_-]+$'); +export const assessmentAttemptCommonCurrentItemOneContentOneOptionsItemTextMax = 2000; + +export const assessmentAttemptCommonCurrentItemOneContentOneOptionsMin = 2; +export const assessmentAttemptCommonCurrentItemOneContentOneOptionsMax = 10; + +export const assessmentAttemptCommonCurrentItemOneContentTwoUnitMax = 32; + +export const assessmentAttemptCommonCurrentItemOneContentThreeMaxLengthMax = 500; + +export const assessmentAttemptCommonCurrentItemOneContentFourElementsItemIdMax = 32; + + +export const assessmentAttemptCommonCurrentItemOneContentFourElementsItemIdRegExp = new RegExp('^[A-Za-z0-9_-]+$'); +export const assessmentAttemptCommonCurrentItemOneContentFourElementsItemTextMax = 2000; + +export const assessmentAttemptCommonCurrentItemOneContentFourElementsMin = 2; +export const assessmentAttemptCommonCurrentItemOneContentFourElementsMax = 20; + +export const assessmentAttemptCommonCurrentItemOneContentFiveSyntaxMax = 32; + + +export const assessmentAttemptCommonCurrentItemOneContentFiveSyntaxRegExp = new RegExp('^[a-z0-9_+-]+$'); +export const assessmentAttemptCommonCurrentItemOneContentFiveLinesItemNumberMax = 500; + +export const assessmentAttemptCommonCurrentItemOneContentFiveLinesItemTextMax = 1000; + +export const assessmentAttemptCommonCurrentItemOneContentFiveLinesMax = 500; + +export const assessmentAttemptCommonCurrentItemOneContentFiveMaxSelectionsMax = 10; + +export const assessmentAttemptCommonCurrentItemOneContentSixSyntaxMax = 32; + + +export const assessmentAttemptCommonCurrentItemOneContentSixSyntaxRegExp = new RegExp('^[a-z0-9_+-]+$'); +export const assessmentAttemptCommonCurrentItemOneContentSixInitialConfigMax = 20000; + +export const assessmentAttemptCommonCurrentItemOneContentSixMaxLengthMax = 20000; + +export const assessmentAttemptCommonCurrentItemOneContentSevenLanguagesMax = 2; + +export const assessmentAttemptCommonCurrentItemOneContentSevenPublicExamplesItemInputMax = 10000; + +export const assessmentAttemptCommonCurrentItemOneContentSevenPublicExamplesItemExpectedOutputMax = 10000; + +export const assessmentAttemptCommonCurrentItemOneContentSevenPublicExamplesMax = 10; + +export const assessmentAttemptCommonCurrentItemOneContentSevenMaxSourceLengthMax = 65536; + +export const assessmentAttemptCommonPracticesItemVerdictOneScoreMin = 0; +export const assessmentAttemptCommonPracticesItemVerdictOneScoreMax = 3; + +export const assessmentAttemptCommonPracticesItemVerdictOneMaxScoreMin = 3; +export const assessmentAttemptCommonPracticesItemVerdictOneMaxScoreMax = 3; + +export const assessmentAttemptCommonPracticesItemVerdictOneGroupsItemGroupMax = 3; + +export const assessmentAttemptCommonPracticesItemVerdictOneGroupsMin = 3; +export const assessmentAttemptCommonPracticesItemVerdictOneGroupsMax = 3; + +export const assessmentAttemptCommonPracticesMax = 5; + + +export const AssessmentAttemptCommon = zod.object({ + "id": zod.uuid().describe('Attempt identifier.'), + "version": zod.int().min(1).describe('Version of an assessment attempt. A new attempt has version 1, and each committed change advances it by exactly one: an accepted answer, a practice submission or resubmission, a verdict, a decision of finalize, an explicit work-session start, and a server-side transition such as expiry or automatic finalization. Reads never change the attempt. A rejected command and a repeat that stores nothing leave it unchanged. Commands send the version they read as `expected_version`.'), + "specialization": zod.union([zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'),zod.null()]).describe('Null only for demo_express, which has no qualification category.'), + "target_grade": zod.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Null only for demo_express, which has no qualification category.'), + "task_language": zod.union([zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.'),zod.null()]).describe('Task language of the attempt, or null when none is selected.'), + "kind": zod.enum(['root', 'corrective', 'demo_express']).describe('Assessment track that distinguishes root, corrective, and training attempts.'), + "root_attempt_id": zod.union([zod.uuid(),zod.null()]).exactOptional().describe('Present only for a corrective real assessment. It identifies the root attempt whose quota and chain deadline this attempt shares.'), + "chain_deadline": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).exactOptional().describe('Present only for a corrective real assessment. It is the immutable deadline derived from the root attempt and is not extended by a lower target grade.'), + "mode": zod.enum(['demo_basic', 'demo_express', 'adaptive']).describe('Method of an assessment attempt. For a real assessment, the server selects demo_basic or adaptive from the published bank. A candidate may explicitly request demo_express, which uses a separate training policy and creates no qualification evidence.\n\n- demo_basic: a fixed form of reviewed demo items scored by their keys against the pass mark of the versioned basic grading policy. It computes no ability estimate, standard error, or probability, so every uncertainty field of its result is null, its thresholds are uncalibrated, and its decision is binary: it never offers an additional practice.\n- adaptive: the adaptive test on task families with an ability estimate, its standard error, and the probability of reaching the grade threshold, as the versioned assessment policy defines them. A probability in the band below confirmation offers one additional practice in the same attempt.\n- demo_express: an interactive 3 to 5 minute training run under a separate policy. It does not assign a category or percentile, count toward the real-assessment quota, or create qualification evidence.\n\nAdding a value is a contract change.'), + "state": zod.enum(['in_progress', 'practice_pending', 'additional_practice_pending', 'ready_to_finalize', 'completed', 'expired', 'insufficient_bank']).describe('Lifecycle state of an attempt and the commands it accepts.\n\n- in_progress: items are being answered; `current_item` is the item to answer. Accepts SubmitMyAssessmentAnswer for that item.\n- practice_pending: the item part is finished, and the main practice has no finished verdict yet: it is not submitted, its verdict is pending in the sandbox, or the sandbox failed and the practice can be submitted again. Accepts SubmitMyAssessmentAnswer with the practice item while its status is `not_started` or `failed`. No grade is confirmed while the practice is unfinished, even when the adaptive stop rule has already ended the item part.\n- additional_practice_pending: adaptive only. Finalize found the probability of reaching the grade in the band below confirmation, so the attempt offers one additional practice without spending a new attempt; it keeps the time and session limits of the attempt. Accepts SubmitMyAssessmentAnswer with the additional practice item while its status is `not_started` or `failed`, and FinalizeMyAssessmentAttempt in the same statuses, which declines the offer and decides `not_confirmed` with the current evidence.\n- ready_to_finalize: every required part is done, including a submitted additional practice with a finished verdict. Accepts FinalizeMyAssessmentAttempt.\n- completed: a decision was made; the result is available.\n- expired: the time or session limit passed before the candidate finished the required parts. The result is available and confirms no grade.\n- insufficient_bank: the published bank could not supply the items required for coverage within the limit, and the attempt ended without a confirmed grade instead of repeating families. The result is available.\n\nWhen `expires_at` passes or the session limit is reached, a read returns the stored state without changing it. A command or background transition commits any due outcome and advances the version. A practice submitted before the limit and still `pending` is graded first. Then `ready_to_finalize` becomes `completed`; `additional_practice_pending` with the additional practice not submitted is finalized as declined and becomes `completed` with `not_confirmed`; `in_progress` and `practice_pending` become `expired`, with the result reason `expired` or `practice_incomplete`; and when the latest submission of a practice ended `failed`, the attempt becomes `expired` with the reason `sandbox_unavailable`, which is not the candidate\'s fault. `completed`, `expired`, and `insufficient_bank` are terminal and accept no command except the repeat of finalize described on FinalizeMyAssessmentAttempt. Adding a value is a contract change.'), + "versions": zod.object({ + "policy_version": zod.int().min(1).describe('Number of the `product` policy version whose assessment rules apply: thresholds, stop rules, item limits, time and session limits, and retry intervals.'), + "bank_version": zod.string().min(1).max(assessmentAttemptCommonVersionsBankVersionMax).regex(assessmentAttemptCommonVersionsBankVersionRegExp).describe('Opaque identifier of a published version, for example `backend-demo.2026-10.1`. Clients show it as text and never parse it.'), + "algorithm_version": zod.string().min(1).max(assessmentAttemptCommonVersionsAlgorithmVersionMax).regex(assessmentAttemptCommonVersionsAlgorithmVersionRegExp).describe('Opaque identifier of a published version, for example `backend-demo.2026-10.1`. Clients show it as text and never parse it.') +}).describe('Versions fixed when the attempt was created. They never change during the attempt, and a result is always reproduced from the stored answers with these versions; a later policy, bank, or algorithm version does not rewrite it.'), + "started_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'), + "expires_at": zod.iso.datetime({"offset":true}).describe('Server deadline. For demo_express it is 180 to 300 seconds after started_at; for a corrective assessment it does not exceed chain_deadline.'), + "sessions": zod.union([zod.object({ + "used": zod.int().min(1).max(assessmentAttemptCommonSessionsOneUsedMax).describe('Sessions started so far, including the current one.'), + "max": zod.int().min(1).max(assessmentAttemptCommonSessionsOneMaxMax), + "idle_timeout_seconds": zod.int().min(assessmentAttemptCommonSessionsOneIdleTimeoutSecondsMin).max(assessmentAttemptCommonSessionsOneIdleTimeoutSecondsMax).describe('Inactivity after which the current session ends.') +}).describe('Work sessions of the attempt, as the policy version limits them, for example two sessions within the time limit.\n\nSession 1 starts with attempt creation. After it ends due to `idle_timeout_seconds` of inactivity, the candidate explicitly starts or resumes work with StartMyAssessmentAttemptSession. GetMyAssessmentAttempt and GetMyAssessmentResult are read-only and never start a session. The session command checks the attempt deadline and `max_sessions`; when either limit has passed, it records the due terminal transition and returns the resulting attempt. Reads of terminal attempts do not change them.'),zod.null()]).describe('Session limit of the attempt, or null when its policy defines none.'), + "finished_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('Time the attempt reached a terminal state, or null while it is active.'), + "progress": zod.object({ + "answered_items": zod.int().min(assessmentAttemptCommonProgressAnsweredItemsMin).max(assessmentAttemptCommonProgressAnsweredItemsMax), + "max_items": zod.int().min(1).max(assessmentAttemptCommonProgressMaxItemsMax).describe('Item limit of the attempt: the form size in demo_basic, or the policy limit of scored and seed items together in adaptive.') +}).describe('Progress of the item part. It counts seed items like scored ones, so it does not reveal which items are scored. An adaptive attempt may end its item part before `max_items` by its stop rule. A finalize refused as premature does not list the unfinished parts; the client reads them here, in `current_item`, and in `practices`.'), + "current_item": zod.union([zod.object({ + "id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'), + "sequence": zod.int().min(1).max(assessmentAttemptCommonCurrentItemOneSequenceMax).describe('Position of the item in the attempt, from 1.'), + "prompt": zod.string().min(1).max(assessmentAttemptCommonCurrentItemOnePromptMax).describe('Statement in Russian. Plain text with line breaks; the client shows it as text, never as HTML.'), + "content": zod.union([zod.object({ + "format": zod.enum(['choice']), + "options": zod.array(zod.object({ + "id": zod.string().min(1).max(assessmentAttemptCommonCurrentItemOneContentOneOptionsItemIdMax).regex(assessmentAttemptCommonCurrentItemOneContentOneOptionsItemIdRegExp).describe('Opaque identifier of a choice option or an order element within one item instance. It is unrelated to the position or correctness of the option.'), + "text": zod.string().min(1).max(assessmentAttemptCommonCurrentItemOneContentOneOptionsItemTextMax).describe('Text of the option; the client shows it as text, never as HTML.') +}).describe('Choice option or order element. Plain text.')).min(assessmentAttemptCommonCurrentItemOneContentOneOptionsMin).max(assessmentAttemptCommonCurrentItemOneContentOneOptionsMax).describe('Options in the order of this instance.'), + "multiple": zod.boolean().describe('Whether more than one option may be selected. It is a property of the task family, fixed for every variant, and never derived from the key: a multiple-choice variant may have a single correct option.') +}).describe('Choose one option, or several when `multiple` is true. The content never says which options are correct or how many are.'),zod.object({ + "format": zod.enum(['number']), + "unit": zod.string().min(1).max(assessmentAttemptCommonCurrentItemOneContentTwoUnitMax).nullable().describe('Unit of the expected value, for example `ms`, or null.') +}).describe('Enter a number, optionally in the given unit.'),zod.object({ + "format": zod.enum(['string']), + "max_length": zod.int().min(1).max(assessmentAttemptCommonCurrentItemOneContentThreeMaxLengthMax).describe('Maximum length of the answer in characters. It is an input limit of the task family, never derived from the key, so it does not reveal the length of the correct answer.') +}).describe('Enter a short string, such as a command, a header name, or an address.'),zod.object({ + "format": zod.enum(['order']), + "elements": zod.array(zod.object({ + "id": zod.string().min(1).max(assessmentAttemptCommonCurrentItemOneContentFourElementsItemIdMax).regex(assessmentAttemptCommonCurrentItemOneContentFourElementsItemIdRegExp).describe('Opaque identifier of a choice option or an order element within one item instance. It is unrelated to the position or correctness of the option.'), + "text": zod.string().min(1).max(assessmentAttemptCommonCurrentItemOneContentFourElementsItemTextMax).describe('Text of the option; the client shows it as text, never as HTML.') +}).describe('Choice option or order element. Plain text.')).min(assessmentAttemptCommonCurrentItemOneContentFourElementsMin).max(assessmentAttemptCommonCurrentItemOneContentFourElementsMax) +}).describe('Put every element into the right order. The elements arrive in the order of this instance, which is never the answer.'),zod.object({ + "format": zod.enum(['find_error']), + "syntax": zod.string().min(1).max(assessmentAttemptCommonCurrentItemOneContentFiveSyntaxMax).regex(assessmentAttemptCommonCurrentItemOneContentFiveSyntaxRegExp).nullable().describe('Highlighting hint such as `go`, `python`, or `cisco_ios`, or null.'), + "lines": zod.array(zod.object({ + "number": zod.int().min(1).max(assessmentAttemptCommonCurrentItemOneContentFiveLinesItemNumberMax), + "text": zod.string().max(assessmentAttemptCommonCurrentItemOneContentFiveLinesItemTextMax) +}).describe('One numbered line of a code or configuration fragment. Plain text.')).min(1).max(assessmentAttemptCommonCurrentItemOneContentFiveLinesMax).describe('Lines numbered from 1 in order.'), + "max_selections": zod.int().min(1).max(assessmentAttemptCommonCurrentItemOneContentFiveMaxSelectionsMax).describe('Maximum number of lines the answer may select. It is a limit of the task family, fixed for every variant and never derived from the key; it is not the number of wrong lines.') +}).describe('Find the lines with the error in a code or configuration fragment and select up to `max_selections` line numbers.'),zod.object({ + "format": zod.enum(['configuration']), + "syntax": zod.string().min(1).max(assessmentAttemptCommonCurrentItemOneContentSixSyntaxMax).regex(assessmentAttemptCommonCurrentItemOneContentSixSyntaxRegExp).describe('Configuration syntax such as `cisco_ios`, `nginx`, or `yaml`.'), + "initial_config": zod.string().max(assessmentAttemptCommonCurrentItemOneContentSixInitialConfigMax).describe('Starting text to edit; empty when the candidate writes it from scratch.'), + "max_length": zod.int().min(1).max(assessmentAttemptCommonCurrentItemOneContentSixMaxLengthMax).describe('Maximum length of the submitted configuration in characters, an input limit of the task family that is never derived from the key.') +}).describe('Write or fix a configuration. The server checks the submitted text with the computed key or reference check of the task family; it never executes it as code.'),zod.object({ + "format": zod.enum(['practice']), + "languages": zod.array(zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.')).max(assessmentAttemptCommonCurrentItemOneContentSevenLanguagesMax).describe('Languages the solution may use. Empty when the task does not offer a choice; the submission then sends a null language.'), + "public_examples": zod.array(zod.object({ + "input": zod.string().max(assessmentAttemptCommonCurrentItemOneContentSevenPublicExamplesItemInputMax), + "expected_output": zod.string().max(assessmentAttemptCommonCurrentItemOneContentSevenPublicExamplesItemExpectedOutputMax) +}).describe('Public example of the practice task: an input and its expected output. Hidden checks are never listed.')).max(assessmentAttemptCommonCurrentItemOneContentSevenPublicExamplesMax), + "max_source_length": zod.int().min(1).max(assessmentAttemptCommonCurrentItemOneContentSevenMaxSourceLengthMax).describe('Maximum length of the solution source in characters.') +}).describe('Code practice. The candidate submits one final solution, which runs in the isolated sandbox against three groups of hidden checks. The content lists only the statement, the allowed languages, and public examples; hidden checks, their inputs, and seeds never reach the client.')]).describe('Format-specific part of an item, selected by `format`. It holds only what the candidate needs to answer: never an answer key, a correct option, a score, a family or variant identifier, a seed, or a hidden check. Limits such as `multiple`, `max_selections`, and `max_length` belong to the format or the task family and never reveal the key.') +}).describe('Item instance served to the candidate. The variant is fixed when it is first served: a reload, a retried request, or a resumed session returns the same instance with the same text and option order. The item never says whether an earlier answer was correct, and seed items, which are not scored, are indistinguishable from scored ones.'),zod.null()]).describe('Item to answer now: a test item in `in_progress`, the practice item to submit in `practice_pending` or `additional_practice_pending` while that practice is `not_started` or `failed`, and null otherwise.'), + "practices": zod.array(zod.object({ + "kind": zod.enum(['main', 'additional']).describe('Role of a practice in the attempt.\n\n- main: the practice that every attempt with practice requires before a decision.\n- additional: adaptive only; offered by finalize when the probability of reaching the grade is in the band below confirmation. It continues the same attempt and spends no new attempt.\n\nAdding a value is a contract change.'), + "item_id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'), + "status": zod.enum(['not_started', 'pending', 'finished', 'failed']).describe('State of a practice.\n\n- not_started: no solution was submitted yet.\n- pending: the submitted solution is queued or running in the sandbox.\n- finished: the sandbox ran the solution and returned a verdict; `verdict` holds it. Every outcome caused by the solution itself, such as a compilation error, a runtime error, a time limit, or a memory limit, is `finished` with the affected groups not passed.\n- failed: the sandbox infrastructure could not run the solution, for example because its queue was full or an executor broke, independently of the solution. The failure is not the candidate\'s and consumes nothing; the practice can be submitted again.'), + "submitted_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('Time of the latest submission, or null before the first one.'), + "verdict": zod.union([zod.object({ + "score": zod.int().min(assessmentAttemptCommonPracticesItemVerdictOneScoreMin).max(assessmentAttemptCommonPracticesItemVerdictOneScoreMax), + "max_score": zod.int().min(assessmentAttemptCommonPracticesItemVerdictOneMaxScoreMin).max(assessmentAttemptCommonPracticesItemVerdictOneMaxScoreMax), + "groups": zod.array(zod.object({ + "group": zod.int().min(1).max(assessmentAttemptCommonPracticesItemVerdictOneGroupsItemGroupMax), + "passed": zod.boolean() +}).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('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; +export type AssessmentAttemptCommonOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentAttemptCreate.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentAttemptCreate.zod.ts index 38c1765..2b9c020 100644 --- a/frontend/src/shared/api/schemas/assessment/assessmentAttemptCreate.zod.ts +++ b/frontend/src/shared/api/schemas/assessment/assessmentAttemptCreate.zod.ts @@ -6,11 +6,20 @@ */ import * as zod from 'zod'; -export const AssessmentAttemptCreate = zod.object({ +export const AssessmentAttemptCreate = zod.union([zod.object({ + "kind": zod.enum(['root']).describe('Start a real-assessment chain and reserve one root quota slot.'), "specialization": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'), "target_grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'), "task_language": zod.union([zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.'),zod.null()]).describe('Task language of the attempt, one of the `task_languages` of the published bank, or null when the bank offers no choice of language. The questionnaire choice is the value the client offers first.') -}).describe('Category to assess: a specialization and the target grade, with the task language. The candidate comes from the session. The mode and versions are chosen by the server; unknown fields such as `mode`, `seed`, or `score` are rejected.') +}).describe('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.'),zod.object({ + "kind": zod.enum(['corrective']).describe('Continue the existing real-assessment chain without reserving another root slot.'), + "specialization": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'), + "target_grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'), + "task_language": zod.union([zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.'),zod.null()]).describe('Task language of the attempt, or null when the bank offers no choice.'), + "root_attempt_id": zod.uuid().describe('Root real-assessment attempt whose quota and deadline this attempt shares.') +}).describe('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 is never supplied by the client.'),zod.object({ + "kind": zod.enum(['demo_express']).describe('Explicitly request the training run; real modes cannot be selected by the client.') +}).describe('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.')]).describe('Start a real assessment, a corrective attempt in an existing chain, or an explicit training run. The required `kind` discriminator selects one of the three request shapes; `mode` remains server-selected for real assessments.') export type AssessmentAttemptCreate = zod.input; export type AssessmentAttemptCreateOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentAttemptKind.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentAttemptKind.zod.ts new file mode 100644 index 0000000..17c4f7e --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentAttemptKind.zod.ts @@ -0,0 +1,12 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const AssessmentAttemptKind = zod.enum(['root', 'corrective', 'demo_express']).describe('Assessment track that distinguishes root, corrective, and training attempts.') + +export type AssessmentAttemptKind = zod.input; +export type AssessmentAttemptKindOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentAttemptSessionStart.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentAttemptSessionStart.zod.ts new file mode 100644 index 0000000..df07bd5 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentAttemptSessionStart.zod.ts @@ -0,0 +1,16 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + + + +export const AssessmentAttemptSessionStart = zod.object({ + "expected_version": zod.int().min(1).describe('Version of an assessment attempt. A new attempt has version 1, and each committed change advances it by exactly one: an accepted answer, a practice submission or resubmission, a verdict, a decision of finalize, an explicit work-session start, and a server-side transition such as expiry or automatic finalization. Reads never change the attempt. A rejected command and a repeat that stores nothing leave it unchanged. Commands send the version they read as `expected_version`.') +}).describe('Start or resume a work session using the attempt version last read by the candidate.') + +export type AssessmentAttemptSessionStart = zod.input; +export type AssessmentAttemptSessionStartOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentAttemptState.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentAttemptState.zod.ts index d91cf8f..e207c22 100644 --- a/frontend/src/shared/api/schemas/assessment/assessmentAttemptState.zod.ts +++ b/frontend/src/shared/api/schemas/assessment/assessmentAttemptState.zod.ts @@ -6,7 +6,7 @@ */ import * as zod from 'zod'; -export const AssessmentAttemptState = zod.enum(['in_progress', 'practice_pending', 'additional_practice_pending', 'ready_to_finalize', 'completed', 'expired', 'insufficient_bank']).describe('Lifecycle state of an attempt and the commands it accepts.\n\n- in_progress: items are being answered; `current_item` is the item to answer. Accepts SubmitMyAssessmentAnswer for that item.\n- practice_pending: the item part is finished, and the main practice has no finished verdict yet: it is not submitted, its verdict is pending in the sandbox, or the sandbox failed and the practice can be submitted again. Accepts SubmitMyAssessmentAnswer with the practice item while its status is `not_started` or `failed`. No grade is confirmed while the practice is unfinished, even when the adaptive stop rule has already ended the item part.\n- additional_practice_pending: adaptive only. Finalize found the probability of reaching the grade in the band below confirmation, so the attempt offers one additional practice without spending a new attempt; it keeps the time and session limits of the attempt. Accepts SubmitMyAssessmentAnswer with the additional practice item while its status is `not_started` or `failed`, and FinalizeMyAssessmentAttempt in the same statuses, which declines the offer and decides `not_confirmed` with the current evidence.\n- ready_to_finalize: every required part is done, including a submitted additional practice with a finished verdict. Accepts FinalizeMyAssessmentAttempt.\n- completed: a decision was made; the result is available.\n- expired: the time or session limit passed before the candidate finished the required parts. The result is available and confirms no grade.\n- insufficient_bank: the published bank could not supply the items required for coverage within the limit, and the attempt ended without a confirmed grade instead of repeating families. The result is available.\n\nWhen `expires_at` passes or the session limit is reached, a practice submitted before that and still `pending` is graded first. Then the server decides without another command: `ready_to_finalize` is finalized and becomes `completed`; `additional_practice_pending` with the additional practice not submitted is finalized as declined and becomes `completed` with `not_confirmed`; `in_progress` and `practice_pending` become `expired`, with the result reason `expired` or `practice_incomplete`; and when the latest submission of a practice ended `failed`, the attempt becomes `expired` with the reason `sandbox_unavailable`, which is not the candidate\'s fault. `completed`, `expired`, and `insufficient_bank` are terminal and accept no command except the repeat of finalize described on FinalizeMyAssessmentAttempt. Adding a value is a contract change.') +export const AssessmentAttemptState = zod.enum(['in_progress', 'practice_pending', 'additional_practice_pending', 'ready_to_finalize', 'completed', 'expired', 'insufficient_bank']).describe('Lifecycle state of an attempt and the commands it accepts.\n\n- in_progress: items are being answered; `current_item` is the item to answer. Accepts SubmitMyAssessmentAnswer for that item.\n- practice_pending: the item part is finished, and the main practice has no finished verdict yet: it is not submitted, its verdict is pending in the sandbox, or the sandbox failed and the practice can be submitted again. Accepts SubmitMyAssessmentAnswer with the practice item while its status is `not_started` or `failed`. No grade is confirmed while the practice is unfinished, even when the adaptive stop rule has already ended the item part.\n- additional_practice_pending: adaptive only. Finalize found the probability of reaching the grade in the band below confirmation, so the attempt offers one additional practice without spending a new attempt; it keeps the time and session limits of the attempt. Accepts SubmitMyAssessmentAnswer with the additional practice item while its status is `not_started` or `failed`, and FinalizeMyAssessmentAttempt in the same statuses, which declines the offer and decides `not_confirmed` with the current evidence.\n- ready_to_finalize: every required part is done, including a submitted additional practice with a finished verdict. Accepts FinalizeMyAssessmentAttempt.\n- completed: a decision was made; the result is available.\n- expired: the time or session limit passed before the candidate finished the required parts. The result is available and confirms no grade.\n- insufficient_bank: the published bank could not supply the items required for coverage within the limit, and the attempt ended without a confirmed grade instead of repeating families. The result is available.\n\nWhen `expires_at` passes or the session limit is reached, a read returns the stored state without changing it. A command or background transition commits any due outcome and advances the version. A practice submitted before the limit and still `pending` is graded first. Then `ready_to_finalize` becomes `completed`; `additional_practice_pending` with the additional practice not submitted is finalized as declined and becomes `completed` with `not_confirmed`; `in_progress` and `practice_pending` become `expired`, with the result reason `expired` or `practice_incomplete`; and when the latest submission of a practice ended `failed`, the attempt becomes `expired` with the reason `sandbox_unavailable`, which is not the candidate\'s fault. `completed`, `expired`, and `insufficient_bank` are terminal and accept no command except the repeat of finalize described on FinalizeMyAssessmentAttempt. Adding a value is a contract change.') export type AssessmentAttemptState = zod.input; export type AssessmentAttemptStateOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentAttemptVersion.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentAttemptVersion.zod.ts index dde9454..4b67a61 100644 --- a/frontend/src/shared/api/schemas/assessment/assessmentAttemptVersion.zod.ts +++ b/frontend/src/shared/api/schemas/assessment/assessmentAttemptVersion.zod.ts @@ -8,7 +8,7 @@ import * as zod from 'zod'; -export const AssessmentAttemptVersion = zod.int().min(1).describe('Version of an assessment attempt. A new attempt has version 1, and each committed change advances it by exactly one: an accepted answer, a practice submission or resubmission, a verdict, a decision of finalize, a session start, and a server-side transition such as expiry or automatic finalization. A transition that the server applies when the attempt is read is committed before the response and also advances it. A rejected command and a repeat that stores nothing leave it unchanged. Commands send the version they read as `expected_version`.') +export const AssessmentAttemptVersion = zod.int().min(1).describe('Version of an assessment attempt. A new attempt has version 1, and each committed change advances it by exactly one: an accepted answer, a practice submission or resubmission, a verdict, a decision of finalize, an explicit work-session start, and a server-side transition such as expiry or automatic finalization. Reads never change the attempt. A rejected command and a repeat that stores nothing leave it unchanged. Commands send the version they read as `expected_version`.') export type AssessmentAttemptVersion = zod.input; export type AssessmentAttemptVersionOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentAvailability.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentAvailability.zod.ts index f38b708..598c659 100644 --- a/frontend/src/shared/api/schemas/assessment/assessmentAvailability.zod.ts +++ b/frontend/src/shared/api/schemas/assessment/assessmentAvailability.zod.ts @@ -24,7 +24,7 @@ export const AssessmentAvailability = zod.object({ "grades": zod.array(zod.object({ "grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'), "status": zod.enum(['available', 'active_attempt', 'cooldown', 'insufficient_bank']).describe('Whether an attempt for the grade can start now.\n\n- available: CreateMyAssessmentAttempt can start it.\n- active_attempt: the specialization has an active attempt; resume it by `active_attempt_id`.\n- cooldown: a retry or promotion interval or the attempt limit of the policy blocks it until `available_at`. Attempts that ended as `insufficient_bank` or `sandbox_unavailable` never cause it.\n- insufficient_bank: no published bank of the category, or not enough unseen families to cover the blueprint for this candidate. The server never fills the gap by repeating families.'), - "mode": zod.union([zod.enum(['demo_basic', 'adaptive']).describe('Measurement method of an attempt. The server selects it from the published task bank of the category; the client never chooses it.\n\n- demo_basic: a fixed form of reviewed demo items scored by their keys against the pass mark of the versioned basic grading policy. It computes no ability estimate, standard error, or probability, so every uncertainty field of its result is null, its thresholds are uncalibrated, and its decision is binary: it never offers an additional practice.\n- adaptive: the adaptive test on task families with an ability estimate, its standard error, and the probability of reaching the grade threshold, as the versioned assessment policy defines them. A probability in the band below confirmation offers one additional practice in the same attempt.\n\nAdding a value is a contract change.'),zod.null()]).describe('Mode that an attempt would use, or null when the status is `insufficient_bank`.'), + "mode": zod.union([zod.enum(['demo_basic', 'adaptive']).describe('Server-selected mode available to a real category assessment.'),zod.null()]).describe('Real-assessment mode that the server would use, or null when the status is `insufficient_bank`. `demo_express` is not a category assessment and is never returned here.'), "available_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('When the status is `cooldown`, the first time the attempt can start; otherwise null.'), "time_limit_seconds": zod.int().min(1).nullable().describe('Time from the start to `expires_at`.'), "max_sessions": zod.int().min(1).max(assessmentAvailabilitySpecializationsItemGradesItemMaxSessionsMax).nullable().describe('Session limit within the time limit.'), diff --git a/frontend/src/shared/api/schemas/assessment/assessmentCorrectiveAttempt.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentCorrectiveAttempt.zod.ts new file mode 100644 index 0000000..d7a7bc4 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentCorrectiveAttempt.zod.ts @@ -0,0 +1,202 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + + + +export const assessmentCorrectiveAttemptOneVersionsBankVersionMax = 64; + + +export const assessmentCorrectiveAttemptOneVersionsBankVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$'); +export const assessmentCorrectiveAttemptOneVersionsAlgorithmVersionMax = 64; + + +export const assessmentCorrectiveAttemptOneVersionsAlgorithmVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$'); +export const assessmentCorrectiveAttemptOneSessionsOneUsedMax = 10; + +export const assessmentCorrectiveAttemptOneSessionsOneMaxMax = 10; + +export const assessmentCorrectiveAttemptOneSessionsOneIdleTimeoutSecondsMin = 60; +export const assessmentCorrectiveAttemptOneSessionsOneIdleTimeoutSecondsMax = 86400; + +export const assessmentCorrectiveAttemptOneProgressAnsweredItemsMin = 0; +export const assessmentCorrectiveAttemptOneProgressAnsweredItemsMax = 100; + +export const assessmentCorrectiveAttemptOneProgressMaxItemsMax = 100; + +export const assessmentCorrectiveAttemptOneCurrentItemOneSequenceMax = 100; + +export const assessmentCorrectiveAttemptOneCurrentItemOnePromptMax = 20000; + +export const assessmentCorrectiveAttemptOneCurrentItemOneContentOneOptionsItemIdMax = 32; + + +export const assessmentCorrectiveAttemptOneCurrentItemOneContentOneOptionsItemIdRegExp = new RegExp('^[A-Za-z0-9_-]+$'); +export const assessmentCorrectiveAttemptOneCurrentItemOneContentOneOptionsItemTextMax = 2000; + +export const assessmentCorrectiveAttemptOneCurrentItemOneContentOneOptionsMin = 2; +export const assessmentCorrectiveAttemptOneCurrentItemOneContentOneOptionsMax = 10; + +export const assessmentCorrectiveAttemptOneCurrentItemOneContentTwoUnitMax = 32; + +export const assessmentCorrectiveAttemptOneCurrentItemOneContentThreeMaxLengthMax = 500; + +export const assessmentCorrectiveAttemptOneCurrentItemOneContentFourElementsItemIdMax = 32; + + +export const assessmentCorrectiveAttemptOneCurrentItemOneContentFourElementsItemIdRegExp = new RegExp('^[A-Za-z0-9_-]+$'); +export const assessmentCorrectiveAttemptOneCurrentItemOneContentFourElementsItemTextMax = 2000; + +export const assessmentCorrectiveAttemptOneCurrentItemOneContentFourElementsMin = 2; +export const assessmentCorrectiveAttemptOneCurrentItemOneContentFourElementsMax = 20; + +export const assessmentCorrectiveAttemptOneCurrentItemOneContentFiveSyntaxMax = 32; + + +export const assessmentCorrectiveAttemptOneCurrentItemOneContentFiveSyntaxRegExp = new RegExp('^[a-z0-9_+-]+$'); +export const assessmentCorrectiveAttemptOneCurrentItemOneContentFiveLinesItemNumberMax = 500; + +export const assessmentCorrectiveAttemptOneCurrentItemOneContentFiveLinesItemTextMax = 1000; + +export const assessmentCorrectiveAttemptOneCurrentItemOneContentFiveLinesMax = 500; + +export const assessmentCorrectiveAttemptOneCurrentItemOneContentFiveMaxSelectionsMax = 10; + +export const assessmentCorrectiveAttemptOneCurrentItemOneContentSixSyntaxMax = 32; + + +export const assessmentCorrectiveAttemptOneCurrentItemOneContentSixSyntaxRegExp = new RegExp('^[a-z0-9_+-]+$'); +export const assessmentCorrectiveAttemptOneCurrentItemOneContentSixInitialConfigMax = 20000; + +export const assessmentCorrectiveAttemptOneCurrentItemOneContentSixMaxLengthMax = 20000; + +export const assessmentCorrectiveAttemptOneCurrentItemOneContentSevenLanguagesMax = 2; + +export const assessmentCorrectiveAttemptOneCurrentItemOneContentSevenPublicExamplesItemInputMax = 10000; + +export const assessmentCorrectiveAttemptOneCurrentItemOneContentSevenPublicExamplesItemExpectedOutputMax = 10000; + +export const assessmentCorrectiveAttemptOneCurrentItemOneContentSevenPublicExamplesMax = 10; + +export const assessmentCorrectiveAttemptOneCurrentItemOneContentSevenMaxSourceLengthMax = 65536; + +export const assessmentCorrectiveAttemptOnePracticesItemVerdictOneScoreMin = 0; +export const assessmentCorrectiveAttemptOnePracticesItemVerdictOneScoreMax = 3; + +export const assessmentCorrectiveAttemptOnePracticesItemVerdictOneMaxScoreMin = 3; +export const assessmentCorrectiveAttemptOnePracticesItemVerdictOneMaxScoreMax = 3; + +export const assessmentCorrectiveAttemptOnePracticesItemVerdictOneGroupsItemGroupMax = 3; + +export const assessmentCorrectiveAttemptOnePracticesItemVerdictOneGroupsMin = 3; +export const assessmentCorrectiveAttemptOnePracticesItemVerdictOneGroupsMax = 3; + +export const assessmentCorrectiveAttemptOnePracticesMax = 5; + + +export const AssessmentCorrectiveAttempt = zod.object({ + "id": zod.uuid().describe('Attempt identifier.'), + "version": zod.int().min(1).describe('Version of an assessment attempt. A new attempt has version 1, and each committed change advances it by exactly one: an accepted answer, a practice submission or resubmission, a verdict, a decision of finalize, an explicit work-session start, and a server-side transition such as expiry or automatic finalization. Reads never change the attempt. A rejected command and a repeat that stores nothing leave it unchanged. Commands send the version they read as `expected_version`.'), + "specialization": zod.union([zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'),zod.null()]).describe('Null only for demo_express, which has no qualification category.'), + "target_grade": zod.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Null only for demo_express, which has no qualification category.'), + "task_language": zod.union([zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.'),zod.null()]).describe('Task language of the attempt, or null when none is selected.'), + "kind": zod.enum(['root', 'corrective', 'demo_express']).describe('Assessment track that distinguishes root, corrective, and training attempts.'), + "root_attempt_id": zod.union([zod.uuid(),zod.null()]).describe('Present only for a corrective real assessment. It identifies the root attempt whose quota and chain deadline this attempt shares.'), + "chain_deadline": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('Present only for a corrective real assessment. It is the immutable deadline derived from the root attempt and is not extended by a lower target grade.'), + "mode": zod.enum(['demo_basic', 'demo_express', 'adaptive']).describe('Method of an assessment attempt. For a real assessment, the server selects demo_basic or adaptive from the published bank. A candidate may explicitly request demo_express, which uses a separate training policy and creates no qualification evidence.\n\n- demo_basic: a fixed form of reviewed demo items scored by their keys against the pass mark of the versioned basic grading policy. It computes no ability estimate, standard error, or probability, so every uncertainty field of its result is null, its thresholds are uncalibrated, and its decision is binary: it never offers an additional practice.\n- adaptive: the adaptive test on task families with an ability estimate, its standard error, and the probability of reaching the grade threshold, as the versioned assessment policy defines them. A probability in the band below confirmation offers one additional practice in the same attempt.\n- demo_express: an interactive 3 to 5 minute training run under a separate policy. It does not assign a category or percentile, count toward the real-assessment quota, or create qualification evidence.\n\nAdding a value is a contract change.'), + "state": zod.enum(['in_progress', 'practice_pending', 'additional_practice_pending', 'ready_to_finalize', 'completed', 'expired', 'insufficient_bank']).describe('Lifecycle state of an attempt and the commands it accepts.\n\n- in_progress: items are being answered; `current_item` is the item to answer. Accepts SubmitMyAssessmentAnswer for that item.\n- practice_pending: the item part is finished, and the main practice has no finished verdict yet: it is not submitted, its verdict is pending in the sandbox, or the sandbox failed and the practice can be submitted again. Accepts SubmitMyAssessmentAnswer with the practice item while its status is `not_started` or `failed`. No grade is confirmed while the practice is unfinished, even when the adaptive stop rule has already ended the item part.\n- additional_practice_pending: adaptive only. Finalize found the probability of reaching the grade in the band below confirmation, so the attempt offers one additional practice without spending a new attempt; it keeps the time and session limits of the attempt. Accepts SubmitMyAssessmentAnswer with the additional practice item while its status is `not_started` or `failed`, and FinalizeMyAssessmentAttempt in the same statuses, which declines the offer and decides `not_confirmed` with the current evidence.\n- ready_to_finalize: every required part is done, including a submitted additional practice with a finished verdict. Accepts FinalizeMyAssessmentAttempt.\n- completed: a decision was made; the result is available.\n- expired: the time or session limit passed before the candidate finished the required parts. The result is available and confirms no grade.\n- insufficient_bank: the published bank could not supply the items required for coverage within the limit, and the attempt ended without a confirmed grade instead of repeating families. The result is available.\n\nWhen `expires_at` passes or the session limit is reached, a read returns the stored state without changing it. A command or background transition commits any due outcome and advances the version. A practice submitted before the limit and still `pending` is graded first. Then `ready_to_finalize` becomes `completed`; `additional_practice_pending` with the additional practice not submitted is finalized as declined and becomes `completed` with `not_confirmed`; `in_progress` and `practice_pending` become `expired`, with the result reason `expired` or `practice_incomplete`; and when the latest submission of a practice ended `failed`, the attempt becomes `expired` with the reason `sandbox_unavailable`, which is not the candidate\'s fault. `completed`, `expired`, and `insufficient_bank` are terminal and accept no command except the repeat of finalize described on FinalizeMyAssessmentAttempt. Adding a value is a contract change.'), + "versions": zod.object({ + "policy_version": zod.int().min(1).describe('Number of the `product` policy version whose assessment rules apply: thresholds, stop rules, item limits, time and session limits, and retry intervals.'), + "bank_version": zod.string().min(1).max(assessmentCorrectiveAttemptOneVersionsBankVersionMax).regex(assessmentCorrectiveAttemptOneVersionsBankVersionRegExp).describe('Opaque identifier of a published version, for example `backend-demo.2026-10.1`. Clients show it as text and never parse it.'), + "algorithm_version": zod.string().min(1).max(assessmentCorrectiveAttemptOneVersionsAlgorithmVersionMax).regex(assessmentCorrectiveAttemptOneVersionsAlgorithmVersionRegExp).describe('Opaque identifier of a published version, for example `backend-demo.2026-10.1`. Clients show it as text and never parse it.') +}).describe('Versions fixed when the attempt was created. They never change during the attempt, and a result is always reproduced from the stored answers with these versions; a later policy, bank, or algorithm version does not rewrite it.'), + "started_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'), + "expires_at": zod.iso.datetime({"offset":true}).describe('Server deadline. For demo_express it is 180 to 300 seconds after started_at; for a corrective assessment it does not exceed chain_deadline.'), + "sessions": zod.union([zod.object({ + "used": zod.int().min(1).max(assessmentCorrectiveAttemptOneSessionsOneUsedMax).describe('Sessions started so far, including the current one.'), + "max": zod.int().min(1).max(assessmentCorrectiveAttemptOneSessionsOneMaxMax), + "idle_timeout_seconds": zod.int().min(assessmentCorrectiveAttemptOneSessionsOneIdleTimeoutSecondsMin).max(assessmentCorrectiveAttemptOneSessionsOneIdleTimeoutSecondsMax).describe('Inactivity after which the current session ends.') +}).describe('Work sessions of the attempt, as the policy version limits them, for example two sessions within the time limit.\n\nSession 1 starts with attempt creation. After it ends due to `idle_timeout_seconds` of inactivity, the candidate explicitly starts or resumes work with StartMyAssessmentAttemptSession. GetMyAssessmentAttempt and GetMyAssessmentResult are read-only and never start a session. The session command checks the attempt deadline and `max_sessions`; when either limit has passed, it records the due terminal transition and returns the resulting attempt. Reads of terminal attempts do not change them.'),zod.null()]).describe('Session limit of the attempt, or null when its policy defines none.'), + "finished_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('Time the attempt reached a terminal state, or null while it is active.'), + "progress": zod.object({ + "answered_items": zod.int().min(assessmentCorrectiveAttemptOneProgressAnsweredItemsMin).max(assessmentCorrectiveAttemptOneProgressAnsweredItemsMax), + "max_items": zod.int().min(1).max(assessmentCorrectiveAttemptOneProgressMaxItemsMax).describe('Item limit of the attempt: the form size in demo_basic, or the policy limit of scored and seed items together in adaptive.') +}).describe('Progress of the item part. It counts seed items like scored ones, so it does not reveal which items are scored. An adaptive attempt may end its item part before `max_items` by its stop rule. A finalize refused as premature does not list the unfinished parts; the client reads them here, in `current_item`, and in `practices`.'), + "current_item": zod.union([zod.object({ + "id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'), + "sequence": zod.int().min(1).max(assessmentCorrectiveAttemptOneCurrentItemOneSequenceMax).describe('Position of the item in the attempt, from 1.'), + "prompt": zod.string().min(1).max(assessmentCorrectiveAttemptOneCurrentItemOnePromptMax).describe('Statement in Russian. Plain text with line breaks; the client shows it as text, never as HTML.'), + "content": zod.union([zod.object({ + "format": zod.enum(['choice']), + "options": zod.array(zod.object({ + "id": zod.string().min(1).max(assessmentCorrectiveAttemptOneCurrentItemOneContentOneOptionsItemIdMax).regex(assessmentCorrectiveAttemptOneCurrentItemOneContentOneOptionsItemIdRegExp).describe('Opaque identifier of a choice option or an order element within one item instance. It is unrelated to the position or correctness of the option.'), + "text": zod.string().min(1).max(assessmentCorrectiveAttemptOneCurrentItemOneContentOneOptionsItemTextMax).describe('Text of the option; the client shows it as text, never as HTML.') +}).describe('Choice option or order element. Plain text.')).min(assessmentCorrectiveAttemptOneCurrentItemOneContentOneOptionsMin).max(assessmentCorrectiveAttemptOneCurrentItemOneContentOneOptionsMax).describe('Options in the order of this instance.'), + "multiple": zod.boolean().describe('Whether more than one option may be selected. It is a property of the task family, fixed for every variant, and never derived from the key: a multiple-choice variant may have a single correct option.') +}).describe('Choose one option, or several when `multiple` is true. The content never says which options are correct or how many are.'),zod.object({ + "format": zod.enum(['number']), + "unit": zod.string().min(1).max(assessmentCorrectiveAttemptOneCurrentItemOneContentTwoUnitMax).nullable().describe('Unit of the expected value, for example `ms`, or null.') +}).describe('Enter a number, optionally in the given unit.'),zod.object({ + "format": zod.enum(['string']), + "max_length": zod.int().min(1).max(assessmentCorrectiveAttemptOneCurrentItemOneContentThreeMaxLengthMax).describe('Maximum length of the answer in characters. It is an input limit of the task family, never derived from the key, so it does not reveal the length of the correct answer.') +}).describe('Enter a short string, such as a command, a header name, or an address.'),zod.object({ + "format": zod.enum(['order']), + "elements": zod.array(zod.object({ + "id": zod.string().min(1).max(assessmentCorrectiveAttemptOneCurrentItemOneContentFourElementsItemIdMax).regex(assessmentCorrectiveAttemptOneCurrentItemOneContentFourElementsItemIdRegExp).describe('Opaque identifier of a choice option or an order element within one item instance. It is unrelated to the position or correctness of the option.'), + "text": zod.string().min(1).max(assessmentCorrectiveAttemptOneCurrentItemOneContentFourElementsItemTextMax).describe('Text of the option; the client shows it as text, never as HTML.') +}).describe('Choice option or order element. Plain text.')).min(assessmentCorrectiveAttemptOneCurrentItemOneContentFourElementsMin).max(assessmentCorrectiveAttemptOneCurrentItemOneContentFourElementsMax) +}).describe('Put every element into the right order. The elements arrive in the order of this instance, which is never the answer.'),zod.object({ + "format": zod.enum(['find_error']), + "syntax": zod.string().min(1).max(assessmentCorrectiveAttemptOneCurrentItemOneContentFiveSyntaxMax).regex(assessmentCorrectiveAttemptOneCurrentItemOneContentFiveSyntaxRegExp).nullable().describe('Highlighting hint such as `go`, `python`, or `cisco_ios`, or null.'), + "lines": zod.array(zod.object({ + "number": zod.int().min(1).max(assessmentCorrectiveAttemptOneCurrentItemOneContentFiveLinesItemNumberMax), + "text": zod.string().max(assessmentCorrectiveAttemptOneCurrentItemOneContentFiveLinesItemTextMax) +}).describe('One numbered line of a code or configuration fragment. Plain text.')).min(1).max(assessmentCorrectiveAttemptOneCurrentItemOneContentFiveLinesMax).describe('Lines numbered from 1 in order.'), + "max_selections": zod.int().min(1).max(assessmentCorrectiveAttemptOneCurrentItemOneContentFiveMaxSelectionsMax).describe('Maximum number of lines the answer may select. It is a limit of the task family, fixed for every variant and never derived from the key; it is not the number of wrong lines.') +}).describe('Find the lines with the error in a code or configuration fragment and select up to `max_selections` line numbers.'),zod.object({ + "format": zod.enum(['configuration']), + "syntax": zod.string().min(1).max(assessmentCorrectiveAttemptOneCurrentItemOneContentSixSyntaxMax).regex(assessmentCorrectiveAttemptOneCurrentItemOneContentSixSyntaxRegExp).describe('Configuration syntax such as `cisco_ios`, `nginx`, or `yaml`.'), + "initial_config": zod.string().max(assessmentCorrectiveAttemptOneCurrentItemOneContentSixInitialConfigMax).describe('Starting text to edit; empty when the candidate writes it from scratch.'), + "max_length": zod.int().min(1).max(assessmentCorrectiveAttemptOneCurrentItemOneContentSixMaxLengthMax).describe('Maximum length of the submitted configuration in characters, an input limit of the task family that is never derived from the key.') +}).describe('Write or fix a configuration. The server checks the submitted text with the computed key or reference check of the task family; it never executes it as code.'),zod.object({ + "format": zod.enum(['practice']), + "languages": zod.array(zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.')).max(assessmentCorrectiveAttemptOneCurrentItemOneContentSevenLanguagesMax).describe('Languages the solution may use. Empty when the task does not offer a choice; the submission then sends a null language.'), + "public_examples": zod.array(zod.object({ + "input": zod.string().max(assessmentCorrectiveAttemptOneCurrentItemOneContentSevenPublicExamplesItemInputMax), + "expected_output": zod.string().max(assessmentCorrectiveAttemptOneCurrentItemOneContentSevenPublicExamplesItemExpectedOutputMax) +}).describe('Public example of the practice task: an input and its expected output. Hidden checks are never listed.')).max(assessmentCorrectiveAttemptOneCurrentItemOneContentSevenPublicExamplesMax), + "max_source_length": zod.int().min(1).max(assessmentCorrectiveAttemptOneCurrentItemOneContentSevenMaxSourceLengthMax).describe('Maximum length of the solution source in characters.') +}).describe('Code practice. The candidate submits one final solution, which runs in the isolated sandbox against three groups of hidden checks. The content lists only the statement, the allowed languages, and public examples; hidden checks, their inputs, and seeds never reach the client.')]).describe('Format-specific part of an item, selected by `format`. It holds only what the candidate needs to answer: never an answer key, a correct option, a score, a family or variant identifier, a seed, or a hidden check. Limits such as `multiple`, `max_selections`, and `max_length` belong to the format or the task family and never reveal the key.') +}).describe('Item instance served to the candidate. The variant is fixed when it is first served: a reload, a retried request, or a resumed session returns the same instance with the same text and option order. The item never says whether an earlier answer was correct, and seed items, which are not scored, are indistinguishable from scored ones.'),zod.null()]).describe('Item to answer now: a test item in `in_progress`, the practice item to submit in `practice_pending` or `additional_practice_pending` while that practice is `not_started` or `failed`, and null otherwise.'), + "practices": zod.array(zod.object({ + "kind": zod.enum(['main', 'additional']).describe('Role of a practice in the attempt.\n\n- main: the practice that every attempt with practice requires before a decision.\n- additional: adaptive only; offered by finalize when the probability of reaching the grade is in the band below confirmation. It continues the same attempt and spends no new attempt.\n\nAdding a value is a contract change.'), + "item_id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'), + "status": zod.enum(['not_started', 'pending', 'finished', 'failed']).describe('State of a practice.\n\n- not_started: no solution was submitted yet.\n- pending: the submitted solution is queued or running in the sandbox.\n- finished: the sandbox ran the solution and returned a verdict; `verdict` holds it. Every outcome caused by the solution itself, such as a compilation error, a runtime error, a time limit, or a memory limit, is `finished` with the affected groups not passed.\n- failed: the sandbox infrastructure could not run the solution, for example because its queue was full or an executor broke, independently of the solution. The failure is not the candidate\'s and consumes nothing; the practice can be submitted again.'), + "submitted_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('Time of the latest submission, or null before the first one.'), + "verdict": zod.union([zod.object({ + "score": zod.int().min(assessmentCorrectiveAttemptOnePracticesItemVerdictOneScoreMin).max(assessmentCorrectiveAttemptOnePracticesItemVerdictOneScoreMax), + "max_score": zod.int().min(assessmentCorrectiveAttemptOnePracticesItemVerdictOneMaxScoreMin).max(assessmentCorrectiveAttemptOnePracticesItemVerdictOneMaxScoreMax), + "groups": zod.array(zod.object({ + "group": zod.int().min(1).max(assessmentCorrectiveAttemptOnePracticesItemVerdictOneGroupsItemGroupMax), + "passed": zod.boolean() +}).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('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']), + "specialization": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'), + "target_grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'), + "root_attempt_id": zod.uuid(), + "chain_deadline": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.') +})).and(zod.object({ + "kind": zod.enum(['corrective']) +})) + +export type AssessmentCorrectiveAttempt = zod.input; +export type AssessmentCorrectiveAttemptOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentCorrectiveAttemptCreate.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentCorrectiveAttemptCreate.zod.ts new file mode 100644 index 0000000..7bfec86 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentCorrectiveAttemptCreate.zod.ts @@ -0,0 +1,18 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const AssessmentCorrectiveAttemptCreate = zod.object({ + "kind": zod.enum(['corrective']).describe('Continue the existing real-assessment chain without reserving another root slot.'), + "specialization": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'), + "target_grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'), + "task_language": zod.union([zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.'),zod.null()]).describe('Task language of the attempt, or null when the bank offers no choice.'), + "root_attempt_id": zod.uuid().describe('Root real-assessment attempt whose quota and deadline this attempt shares.') +}).describe('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 is never supplied by the client.') + +export type AssessmentCorrectiveAttemptCreate = zod.input; +export type AssessmentCorrectiveAttemptCreateOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentCorrectiveResult.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentCorrectiveResult.zod.ts new file mode 100644 index 0000000..d6c46dd --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentCorrectiveResult.zod.ts @@ -0,0 +1,126 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + + +export const assessmentCorrectiveResultOneVersionsBankVersionMax = 64; + + +export const assessmentCorrectiveResultOneVersionsBankVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$'); +export const assessmentCorrectiveResultOneVersionsAlgorithmVersionMax = 64; + + +export const assessmentCorrectiveResultOneVersionsAlgorithmVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$'); +export const assessmentCorrectiveResultOneLimitationsMax = 10; + +export const assessmentCorrectiveResultOneUncertaintyOneStandardErrorMin = 0; + +export const assessmentCorrectiveResultOneUncertaintyOnePGradeMin = 0; +export const assessmentCorrectiveResultOneUncertaintyOnePGradeMax = 1; + +export const assessmentCorrectiveResultOneBasicScoreOnePointsMin = 0; + + + +export const assessmentCorrectiveResultOnePracticesItemVerdictScoreMin = 0; +export const assessmentCorrectiveResultOnePracticesItemVerdictScoreMax = 3; + +export const assessmentCorrectiveResultOnePracticesItemVerdictMaxScoreMin = 3; +export const assessmentCorrectiveResultOnePracticesItemVerdictMaxScoreMax = 3; + +export const assessmentCorrectiveResultOnePracticesItemVerdictGroupsItemGroupMax = 3; + +export const assessmentCorrectiveResultOnePracticesItemVerdictGroupsMin = 3; +export const assessmentCorrectiveResultOnePracticesItemVerdictGroupsMax = 3; + +export const assessmentCorrectiveResultOnePracticesMax = 5; + +export const assessmentCorrectiveResultOneGapsItemDomainMax = 64; + + +export const assessmentCorrectiveResultOneGapsItemDomainRegExp = new RegExp('^[a-z0-9_]+$'); +export const assessmentCorrectiveResultOneGapsItemTitleMax = 200; + +export const assessmentCorrectiveResultOneGapsMax = 20; + +export const assessmentCorrectiveResultOneDurationsItemsSecondsMin = 0; + +export const assessmentCorrectiveResultOneDurationsPracticeSecondsMin = 0; + +export const assessmentCorrectiveResultOneNextStepsMax = 5; + + +export const AssessmentCorrectiveResult = zod.object({ + "attempt_id": zod.uuid(), + "specialization": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'), + "target_grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'), + "root_attempt_id": zod.union([zod.uuid(),zod.null()]).describe('Root attempt of a corrective check, or null when this is not a corrective result. The corrective attempt keeps this link.'), + "chain_deadline": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('Immutable deadline shared by a corrective chain, or null when this result is not from a corrective check.'), + "task_language": zod.union([zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.'),zod.null()]), + "kind": zod.enum(['root', 'corrective']), + "mode": zod.enum(['demo_basic', 'adaptive']), + "versions": zod.object({ + "policy_version": zod.int().min(1).describe('Number of the `product` policy version whose assessment rules apply: thresholds, stop rules, item limits, time and session limits, and retry intervals.'), + "bank_version": zod.string().min(1).max(assessmentCorrectiveResultOneVersionsBankVersionMax).regex(assessmentCorrectiveResultOneVersionsBankVersionRegExp).describe('Opaque identifier of a published version, for example `backend-demo.2026-10.1`. Clients show it as text and never parse it.'), + "algorithm_version": zod.string().min(1).max(assessmentCorrectiveResultOneVersionsAlgorithmVersionMax).regex(assessmentCorrectiveResultOneVersionsAlgorithmVersionRegExp).describe('Opaque identifier of a published version, for example `backend-demo.2026-10.1`. Clients show it as text and never parse it.') +}).describe('Versions fixed when the attempt was created. They never change during the attempt, and a result is always reproduced from the stored answers with these versions; a later policy, bank, or algorithm version does not rewrite it.'), + "outcome": zod.enum(['confirmed', 'not_confirmed', 'not_determined']).describe('Grade decision of the attempt.\n\n- confirmed: the target grade is confirmed by the rule of the recorded policy version.\n- not_confirmed: the evidence is below the rule, including an adaptive attempt whose probability stayed below confirmation after the additional practice, or whose additional practice was declined or not submitted in time. The previously confirmed grade, if any, stays in force.\n- not_determined: the attempt gives no decision; `not_determined_reason` says why. The previously confirmed grade stays in force.\n\nA failed, expired, or flagged attempt never lowers a confirmed grade.'), + "not_determined_reason": zod.union([zod.enum(['expired', 'practice_incomplete', 'insufficient_bank', 'sandbox_unavailable']).describe('Why an attempt gives no decision. One root quota slot is reserved when a real root attempt starts; corrective checks in its chain do not reserve another slot.\n\n- expired: the time or session limit passed before the candidate finished the item part. Retry timing follows the recorded policy; a correction uses the existing root slot and does not reset the chain deadline or 30/90-day timers.\n- practice_incomplete: the item part was done, but the candidate did not submit the main practice before the limit. Retry timing follows the recorded policy; a correction uses the existing root slot and does not reset the chain deadline or 30/90-day timers.\n- insufficient_bank: the bank could not supply required coverage. A preflight refusal creates no attempt or root slot; a bank failure in an existing chain does not create a free new chain or another root slot.\n- sandbox_unavailable: the latest submission of a required or additional practice ended `failed` because of the sandbox infrastructure, and the limit passed before a verdict. It is a platform fault and does not create a new root slot or a free chain.'),zod.null()]).describe('The reason when `outcome` is `not_determined`, otherwise null.'), + "confirmed_grade": zod.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Grade that this attempt confirmed, the target grade, or null when it confirmed none. Together with the specialization it forms the category.'), + "previous_confirmed_grade": zod.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Confirmed grade of the specialization before this attempt, or null. When the attempt confirmed nothing, this grade stays in force.'), + "strength": zod.union([zod.enum(['high', 'medium']).describe('Strength of an adaptive confirmation: `high` or `medium`, by the probability bands of the recorded policy version.'),zod.null()]).describe('Strength of an adaptive confirmation, otherwise null.'), + "calibration_status": zod.enum(['uncalibrated', 'calibrated']).describe('Whether the thresholds of the recorded policy version are empirically calibrated. `uncalibrated` results are provisional: their thresholds come from expert judgement, and their probabilities are not claimed to be calibrated.'), + "limitations": zod.array(zod.enum(['uncalibrated_thresholds', 'demo_bank', 'practice_not_included', 'unproctored']).describe('Known limitation of the method behind a real-assessment result, shown with the result.\n\n- uncalibrated_thresholds: the thresholds are not yet validated on a pilot.\n- demo_bank: the result comes from the small reviewed demo bank.\n- practice_not_included: the attempt had no code practice because the sandbox was not enabled.\n- unproctored: the attempt was taken online without supervision.\nAdding a value is a contract change.')).max(assessmentCorrectiveResultOneLimitationsMax), + "uncertainty": zod.union([zod.object({ + "theta": zod.number(), + "standard_error": zod.number().min(assessmentCorrectiveResultOneUncertaintyOneStandardErrorMin), + "interval_95": zod.object({ + "low": zod.number(), + "high": zod.number() +}).describe('Interval on the ability scale.'), + "p_grade": zod.number().min(assessmentCorrectiveResultOneUncertaintyOnePGradeMin).max(assessmentCorrectiveResultOneUncertaintyOnePGradeMax).describe('Probability of reaching the threshold of the target grade.') +}).describe('Ability estimate of an adaptive attempt and its uncertainty: the EAP estimate on the specialization scale, its standard error, the 95% interval, and the probability of reaching the target grade threshold. The interval is reported but is not a separate stop condition.'),zod.null()]).describe('Ability estimate and uncertainty of an adaptive attempt with a decision; null for demo_basic, which computes none, and for an attempt without a decision.'), + "basic_score": zod.union([zod.object({ + "points": zod.int().min(assessmentCorrectiveResultOneBasicScoreOnePointsMin), + "max_points": zod.int().min(1), + "pass_points": zod.int().min(1) +}).describe('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.'),zod.null()]).describe('Raw score of a demo_basic attempt with a decision, otherwise null.'), + "practices": zod.array(zod.object({ + "kind": zod.enum(['main', 'additional']).describe('Role of a practice in the attempt.\n\n- main: the practice that every attempt with practice requires before a decision.\n- additional: adaptive only; offered by finalize when the probability of reaching the grade is in the band below confirmation. It continues the same attempt and spends no new attempt.\n\nAdding a value is a contract change.'), + "verdict": zod.object({ + "score": zod.int().min(assessmentCorrectiveResultOnePracticesItemVerdictScoreMin).max(assessmentCorrectiveResultOnePracticesItemVerdictScoreMax), + "max_score": zod.int().min(assessmentCorrectiveResultOnePracticesItemVerdictMaxScoreMin).max(assessmentCorrectiveResultOnePracticesItemVerdictMaxScoreMax), + "groups": zod.array(zod.object({ + "group": zod.int().min(1).max(assessmentCorrectiveResultOnePracticesItemVerdictGroupsItemGroupMax), + "passed": zod.boolean() +}).describe('Outcome of one hidden check group. It never contains the checks themselves.')).min(assessmentCorrectiveResultOnePracticesItemVerdictGroupsMin).max(assessmentCorrectiveResultOnePracticesItemVerdictGroupsMax) +}).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.') +}).describe('Verdict of one practice of the attempt.')).max(assessmentCorrectiveResultOnePracticesMax).describe('Verdicts of the practices that have one, main first.'), + "gaps": zod.array(zod.object({ + "domain": zod.string().min(1).max(assessmentCorrectiveResultOneGapsItemDomainMax).regex(assessmentCorrectiveResultOneGapsItemDomainRegExp).describe('Stable domain code of the bank blueprint.'), + "title": zod.string().min(1).max(assessmentCorrectiveResultOneGapsItemTitleMax).describe('Display name in Russian. Plain text.') +}).describe('Domain of the specialization where the evidence was weak.')).max(assessmentCorrectiveResultOneGapsMax).describe('Domains with weak evidence; empty when none were found or the method finds none.'), + "durations": zod.object({ + "items_seconds": zod.int().min(assessmentCorrectiveResultOneDurationsItemsSecondsMin), + "practice_seconds": zod.int().min(assessmentCorrectiveResultOneDurationsPracticeSecondsMin).nullable().describe('Time on all practices with a verdict, or null when no practice has one.') +}).describe('Working time recorded by the server. It is a separate label: it never enters the ability estimate or the grade decision.'), + "next_steps": zod.array(zod.object({ + "action": zod.enum(['retake_same_grade', 'take_lower_grade', 'accept_lower_grade', 'take_higher_grade']).describe('Step that the candidate may take next.\n\n- retake_same_grade: test the same grade again from `available_at`.\n- take_lower_grade: test the lower `grade`. After a failure, including the first test, it is allowed at once, outside the same-grade retry interval.\n- accept_lower_grade: accept the lower `grade` on the evidence of this attempt, when the data are sufficient (the command is planned).\n- take_higher_grade: test the higher `grade` from `available_at`. A first confirmation is not a promotion, so after it `available_at` is null; after a promotion the next one waits for the promotion interval of the policy.'), + "grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'), + "available_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('First time the step is allowed, or null when it is allowed now.') +}).describe('Step that the server allows after this result, computed when it was decided.')).max(assessmentCorrectiveResultOneNextStepsMax), + "decided_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.') +}).describe('Immutable result of a real assessment, visible only to its candidate. It records the method, versions, decision, uncertainty, and limitations. A corrective result also carries root_attempt_id and chain_deadline from the same chain. Later policy, bank, or algorithm versions never change it. It never contains answers, per-item correctness, keys, seeds, hidden checks, or anti-cheat signals. Fields the method does not compute are null, never zero.').and(zod.object({ + "kind": zod.enum(['corrective']), + "root_attempt_id": zod.uuid(), + "chain_deadline": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.') +})).and(zod.object({ + "kind": zod.enum(['corrective']) +})).describe('Result of a corrective real assessment. Both chain fields are present and identify the same immutable correction chain.') + +export type AssessmentCorrectiveResult = zod.input; +export type AssessmentCorrectiveResultOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentExpressAttempt.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentExpressAttempt.zod.ts new file mode 100644 index 0000000..849e2a6 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentExpressAttempt.zod.ts @@ -0,0 +1,203 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + + + +export const assessmentExpressAttemptOneVersionsBankVersionMax = 64; + + +export const assessmentExpressAttemptOneVersionsBankVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$'); +export const assessmentExpressAttemptOneVersionsAlgorithmVersionMax = 64; + + +export const assessmentExpressAttemptOneVersionsAlgorithmVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$'); +export const assessmentExpressAttemptOneSessionsOneUsedMax = 10; + +export const assessmentExpressAttemptOneSessionsOneMaxMax = 10; + +export const assessmentExpressAttemptOneSessionsOneIdleTimeoutSecondsMin = 60; +export const assessmentExpressAttemptOneSessionsOneIdleTimeoutSecondsMax = 86400; + +export const assessmentExpressAttemptOneProgressAnsweredItemsMin = 0; +export const assessmentExpressAttemptOneProgressAnsweredItemsMax = 100; + +export const assessmentExpressAttemptOneProgressMaxItemsMax = 100; + +export const assessmentExpressAttemptOneCurrentItemOneSequenceMax = 100; + +export const assessmentExpressAttemptOneCurrentItemOnePromptMax = 20000; + +export const assessmentExpressAttemptOneCurrentItemOneContentOneOptionsItemIdMax = 32; + + +export const assessmentExpressAttemptOneCurrentItemOneContentOneOptionsItemIdRegExp = new RegExp('^[A-Za-z0-9_-]+$'); +export const assessmentExpressAttemptOneCurrentItemOneContentOneOptionsItemTextMax = 2000; + +export const assessmentExpressAttemptOneCurrentItemOneContentOneOptionsMin = 2; +export const assessmentExpressAttemptOneCurrentItemOneContentOneOptionsMax = 10; + +export const assessmentExpressAttemptOneCurrentItemOneContentTwoUnitMax = 32; + +export const assessmentExpressAttemptOneCurrentItemOneContentThreeMaxLengthMax = 500; + +export const assessmentExpressAttemptOneCurrentItemOneContentFourElementsItemIdMax = 32; + + +export const assessmentExpressAttemptOneCurrentItemOneContentFourElementsItemIdRegExp = new RegExp('^[A-Za-z0-9_-]+$'); +export const assessmentExpressAttemptOneCurrentItemOneContentFourElementsItemTextMax = 2000; + +export const assessmentExpressAttemptOneCurrentItemOneContentFourElementsMin = 2; +export const assessmentExpressAttemptOneCurrentItemOneContentFourElementsMax = 20; + +export const assessmentExpressAttemptOneCurrentItemOneContentFiveSyntaxMax = 32; + + +export const assessmentExpressAttemptOneCurrentItemOneContentFiveSyntaxRegExp = new RegExp('^[a-z0-9_+-]+$'); +export const assessmentExpressAttemptOneCurrentItemOneContentFiveLinesItemNumberMax = 500; + +export const assessmentExpressAttemptOneCurrentItemOneContentFiveLinesItemTextMax = 1000; + +export const assessmentExpressAttemptOneCurrentItemOneContentFiveLinesMax = 500; + +export const assessmentExpressAttemptOneCurrentItemOneContentFiveMaxSelectionsMax = 10; + +export const assessmentExpressAttemptOneCurrentItemOneContentSixSyntaxMax = 32; + + +export const assessmentExpressAttemptOneCurrentItemOneContentSixSyntaxRegExp = new RegExp('^[a-z0-9_+-]+$'); +export const assessmentExpressAttemptOneCurrentItemOneContentSixInitialConfigMax = 20000; + +export const assessmentExpressAttemptOneCurrentItemOneContentSixMaxLengthMax = 20000; + +export const assessmentExpressAttemptOneCurrentItemOneContentSevenLanguagesMax = 2; + +export const assessmentExpressAttemptOneCurrentItemOneContentSevenPublicExamplesItemInputMax = 10000; + +export const assessmentExpressAttemptOneCurrentItemOneContentSevenPublicExamplesItemExpectedOutputMax = 10000; + +export const assessmentExpressAttemptOneCurrentItemOneContentSevenPublicExamplesMax = 10; + +export const assessmentExpressAttemptOneCurrentItemOneContentSevenMaxSourceLengthMax = 65536; + +export const assessmentExpressAttemptOnePracticesItemVerdictOneScoreMin = 0; +export const assessmentExpressAttemptOnePracticesItemVerdictOneScoreMax = 3; + +export const assessmentExpressAttemptOnePracticesItemVerdictOneMaxScoreMin = 3; +export const assessmentExpressAttemptOnePracticesItemVerdictOneMaxScoreMax = 3; + +export const assessmentExpressAttemptOnePracticesItemVerdictOneGroupsItemGroupMax = 3; + +export const assessmentExpressAttemptOnePracticesItemVerdictOneGroupsMin = 3; +export const assessmentExpressAttemptOnePracticesItemVerdictOneGroupsMax = 3; + +export const assessmentExpressAttemptOnePracticesMax = 5; + + +export const AssessmentExpressAttempt = zod.object({ + "id": zod.uuid().describe('Attempt identifier.'), + "version": zod.int().min(1).describe('Version of an assessment attempt. A new attempt has version 1, and each committed change advances it by exactly one: an accepted answer, a practice submission or resubmission, a verdict, a decision of finalize, an explicit work-session start, and a server-side transition such as expiry or automatic finalization. Reads never change the attempt. A rejected command and a repeat that stores nothing leave it unchanged. Commands send the version they read as `expected_version`.'), + "specialization": zod.union([zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'),zod.null()]).describe('Null only for demo_express, which has no qualification category.'), + "target_grade": zod.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Null only for demo_express, which has no qualification category.'), + "task_language": zod.union([zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.'),zod.null()]).describe('Task language of the attempt, or null when none is selected.'), + "kind": zod.enum(['root', 'corrective', 'demo_express']).describe('Assessment track that distinguishes root, corrective, and training attempts.'), + "root_attempt_id": zod.union([zod.uuid(),zod.null()]).describe('Present only for a corrective real assessment. It identifies the root attempt whose quota and chain deadline this attempt shares.'), + "chain_deadline": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('Present only for a corrective real assessment. It is the immutable deadline derived from the root attempt and is not extended by a lower target grade.'), + "mode": zod.enum(['demo_basic', 'demo_express', 'adaptive']).describe('Method of an assessment attempt. For a real assessment, the server selects demo_basic or adaptive from the published bank. A candidate may explicitly request demo_express, which uses a separate training policy and creates no qualification evidence.\n\n- demo_basic: a fixed form of reviewed demo items scored by their keys against the pass mark of the versioned basic grading policy. It computes no ability estimate, standard error, or probability, so every uncertainty field of its result is null, its thresholds are uncalibrated, and its decision is binary: it never offers an additional practice.\n- adaptive: the adaptive test on task families with an ability estimate, its standard error, and the probability of reaching the grade threshold, as the versioned assessment policy defines them. A probability in the band below confirmation offers one additional practice in the same attempt.\n- demo_express: an interactive 3 to 5 minute training run under a separate policy. It does not assign a category or percentile, count toward the real-assessment quota, or create qualification evidence.\n\nAdding a value is a contract change.'), + "state": zod.enum(['in_progress', 'practice_pending', 'additional_practice_pending', 'ready_to_finalize', 'completed', 'expired', 'insufficient_bank']).describe('Lifecycle state of an attempt and the commands it accepts.\n\n- in_progress: items are being answered; `current_item` is the item to answer. Accepts SubmitMyAssessmentAnswer for that item.\n- practice_pending: the item part is finished, and the main practice has no finished verdict yet: it is not submitted, its verdict is pending in the sandbox, or the sandbox failed and the practice can be submitted again. Accepts SubmitMyAssessmentAnswer with the practice item while its status is `not_started` or `failed`. No grade is confirmed while the practice is unfinished, even when the adaptive stop rule has already ended the item part.\n- additional_practice_pending: adaptive only. Finalize found the probability of reaching the grade in the band below confirmation, so the attempt offers one additional practice without spending a new attempt; it keeps the time and session limits of the attempt. Accepts SubmitMyAssessmentAnswer with the additional practice item while its status is `not_started` or `failed`, and FinalizeMyAssessmentAttempt in the same statuses, which declines the offer and decides `not_confirmed` with the current evidence.\n- ready_to_finalize: every required part is done, including a submitted additional practice with a finished verdict. Accepts FinalizeMyAssessmentAttempt.\n- completed: a decision was made; the result is available.\n- expired: the time or session limit passed before the candidate finished the required parts. The result is available and confirms no grade.\n- insufficient_bank: the published bank could not supply the items required for coverage within the limit, and the attempt ended without a confirmed grade instead of repeating families. The result is available.\n\nWhen `expires_at` passes or the session limit is reached, a read returns the stored state without changing it. A command or background transition commits any due outcome and advances the version. A practice submitted before the limit and still `pending` is graded first. Then `ready_to_finalize` becomes `completed`; `additional_practice_pending` with the additional practice not submitted is finalized as declined and becomes `completed` with `not_confirmed`; `in_progress` and `practice_pending` become `expired`, with the result reason `expired` or `practice_incomplete`; and when the latest submission of a practice ended `failed`, the attempt becomes `expired` with the reason `sandbox_unavailable`, which is not the candidate\'s fault. `completed`, `expired`, and `insufficient_bank` are terminal and accept no command except the repeat of finalize described on FinalizeMyAssessmentAttempt. Adding a value is a contract change.'), + "versions": zod.object({ + "policy_version": zod.int().min(1).describe('Number of the `product` policy version whose assessment rules apply: thresholds, stop rules, item limits, time and session limits, and retry intervals.'), + "bank_version": zod.string().min(1).max(assessmentExpressAttemptOneVersionsBankVersionMax).regex(assessmentExpressAttemptOneVersionsBankVersionRegExp).describe('Opaque identifier of a published version, for example `backend-demo.2026-10.1`. Clients show it as text and never parse it.'), + "algorithm_version": zod.string().min(1).max(assessmentExpressAttemptOneVersionsAlgorithmVersionMax).regex(assessmentExpressAttemptOneVersionsAlgorithmVersionRegExp).describe('Opaque identifier of a published version, for example `backend-demo.2026-10.1`. Clients show it as text and never parse it.') +}).describe('Versions fixed when the attempt was created. They never change during the attempt, and a result is always reproduced from the stored answers with these versions; a later policy, bank, or algorithm version does not rewrite it.'), + "started_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'), + "expires_at": zod.iso.datetime({"offset":true}).describe('Server deadline. For demo_express it is 180 to 300 seconds after started_at; for a corrective assessment it does not exceed chain_deadline.'), + "sessions": zod.union([zod.object({ + "used": zod.int().min(1).max(assessmentExpressAttemptOneSessionsOneUsedMax).describe('Sessions started so far, including the current one.'), + "max": zod.int().min(1).max(assessmentExpressAttemptOneSessionsOneMaxMax), + "idle_timeout_seconds": zod.int().min(assessmentExpressAttemptOneSessionsOneIdleTimeoutSecondsMin).max(assessmentExpressAttemptOneSessionsOneIdleTimeoutSecondsMax).describe('Inactivity after which the current session ends.') +}).describe('Work sessions of the attempt, as the policy version limits them, for example two sessions within the time limit.\n\nSession 1 starts with attempt creation. After it ends due to `idle_timeout_seconds` of inactivity, the candidate explicitly starts or resumes work with StartMyAssessmentAttemptSession. GetMyAssessmentAttempt and GetMyAssessmentResult are read-only and never start a session. The session command checks the attempt deadline and `max_sessions`; when either limit has passed, it records the due terminal transition and returns the resulting attempt. Reads of terminal attempts do not change them.'),zod.null()]).describe('Session limit of the attempt, or null when its policy defines none.'), + "finished_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('Time the attempt reached a terminal state, or null while it is active.'), + "progress": zod.object({ + "answered_items": zod.int().min(assessmentExpressAttemptOneProgressAnsweredItemsMin).max(assessmentExpressAttemptOneProgressAnsweredItemsMax), + "max_items": zod.int().min(1).max(assessmentExpressAttemptOneProgressMaxItemsMax).describe('Item limit of the attempt: the form size in demo_basic, or the policy limit of scored and seed items together in adaptive.') +}).describe('Progress of the item part. It counts seed items like scored ones, so it does not reveal which items are scored. An adaptive attempt may end its item part before `max_items` by its stop rule. A finalize refused as premature does not list the unfinished parts; the client reads them here, in `current_item`, and in `practices`.'), + "current_item": zod.union([zod.object({ + "id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'), + "sequence": zod.int().min(1).max(assessmentExpressAttemptOneCurrentItemOneSequenceMax).describe('Position of the item in the attempt, from 1.'), + "prompt": zod.string().min(1).max(assessmentExpressAttemptOneCurrentItemOnePromptMax).describe('Statement in Russian. Plain text with line breaks; the client shows it as text, never as HTML.'), + "content": zod.union([zod.object({ + "format": zod.enum(['choice']), + "options": zod.array(zod.object({ + "id": zod.string().min(1).max(assessmentExpressAttemptOneCurrentItemOneContentOneOptionsItemIdMax).regex(assessmentExpressAttemptOneCurrentItemOneContentOneOptionsItemIdRegExp).describe('Opaque identifier of a choice option or an order element within one item instance. It is unrelated to the position or correctness of the option.'), + "text": zod.string().min(1).max(assessmentExpressAttemptOneCurrentItemOneContentOneOptionsItemTextMax).describe('Text of the option; the client shows it as text, never as HTML.') +}).describe('Choice option or order element. Plain text.')).min(assessmentExpressAttemptOneCurrentItemOneContentOneOptionsMin).max(assessmentExpressAttemptOneCurrentItemOneContentOneOptionsMax).describe('Options in the order of this instance.'), + "multiple": zod.boolean().describe('Whether more than one option may be selected. It is a property of the task family, fixed for every variant, and never derived from the key: a multiple-choice variant may have a single correct option.') +}).describe('Choose one option, or several when `multiple` is true. The content never says which options are correct or how many are.'),zod.object({ + "format": zod.enum(['number']), + "unit": zod.string().min(1).max(assessmentExpressAttemptOneCurrentItemOneContentTwoUnitMax).nullable().describe('Unit of the expected value, for example `ms`, or null.') +}).describe('Enter a number, optionally in the given unit.'),zod.object({ + "format": zod.enum(['string']), + "max_length": zod.int().min(1).max(assessmentExpressAttemptOneCurrentItemOneContentThreeMaxLengthMax).describe('Maximum length of the answer in characters. It is an input limit of the task family, never derived from the key, so it does not reveal the length of the correct answer.') +}).describe('Enter a short string, such as a command, a header name, or an address.'),zod.object({ + "format": zod.enum(['order']), + "elements": zod.array(zod.object({ + "id": zod.string().min(1).max(assessmentExpressAttemptOneCurrentItemOneContentFourElementsItemIdMax).regex(assessmentExpressAttemptOneCurrentItemOneContentFourElementsItemIdRegExp).describe('Opaque identifier of a choice option or an order element within one item instance. It is unrelated to the position or correctness of the option.'), + "text": zod.string().min(1).max(assessmentExpressAttemptOneCurrentItemOneContentFourElementsItemTextMax).describe('Text of the option; the client shows it as text, never as HTML.') +}).describe('Choice option or order element. Plain text.')).min(assessmentExpressAttemptOneCurrentItemOneContentFourElementsMin).max(assessmentExpressAttemptOneCurrentItemOneContentFourElementsMax) +}).describe('Put every element into the right order. The elements arrive in the order of this instance, which is never the answer.'),zod.object({ + "format": zod.enum(['find_error']), + "syntax": zod.string().min(1).max(assessmentExpressAttemptOneCurrentItemOneContentFiveSyntaxMax).regex(assessmentExpressAttemptOneCurrentItemOneContentFiveSyntaxRegExp).nullable().describe('Highlighting hint such as `go`, `python`, or `cisco_ios`, or null.'), + "lines": zod.array(zod.object({ + "number": zod.int().min(1).max(assessmentExpressAttemptOneCurrentItemOneContentFiveLinesItemNumberMax), + "text": zod.string().max(assessmentExpressAttemptOneCurrentItemOneContentFiveLinesItemTextMax) +}).describe('One numbered line of a code or configuration fragment. Plain text.')).min(1).max(assessmentExpressAttemptOneCurrentItemOneContentFiveLinesMax).describe('Lines numbered from 1 in order.'), + "max_selections": zod.int().min(1).max(assessmentExpressAttemptOneCurrentItemOneContentFiveMaxSelectionsMax).describe('Maximum number of lines the answer may select. It is a limit of the task family, fixed for every variant and never derived from the key; it is not the number of wrong lines.') +}).describe('Find the lines with the error in a code or configuration fragment and select up to `max_selections` line numbers.'),zod.object({ + "format": zod.enum(['configuration']), + "syntax": zod.string().min(1).max(assessmentExpressAttemptOneCurrentItemOneContentSixSyntaxMax).regex(assessmentExpressAttemptOneCurrentItemOneContentSixSyntaxRegExp).describe('Configuration syntax such as `cisco_ios`, `nginx`, or `yaml`.'), + "initial_config": zod.string().max(assessmentExpressAttemptOneCurrentItemOneContentSixInitialConfigMax).describe('Starting text to edit; empty when the candidate writes it from scratch.'), + "max_length": zod.int().min(1).max(assessmentExpressAttemptOneCurrentItemOneContentSixMaxLengthMax).describe('Maximum length of the submitted configuration in characters, an input limit of the task family that is never derived from the key.') +}).describe('Write or fix a configuration. The server checks the submitted text with the computed key or reference check of the task family; it never executes it as code.'),zod.object({ + "format": zod.enum(['practice']), + "languages": zod.array(zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.')).max(assessmentExpressAttemptOneCurrentItemOneContentSevenLanguagesMax).describe('Languages the solution may use. Empty when the task does not offer a choice; the submission then sends a null language.'), + "public_examples": zod.array(zod.object({ + "input": zod.string().max(assessmentExpressAttemptOneCurrentItemOneContentSevenPublicExamplesItemInputMax), + "expected_output": zod.string().max(assessmentExpressAttemptOneCurrentItemOneContentSevenPublicExamplesItemExpectedOutputMax) +}).describe('Public example of the practice task: an input and its expected output. Hidden checks are never listed.')).max(assessmentExpressAttemptOneCurrentItemOneContentSevenPublicExamplesMax), + "max_source_length": zod.int().min(1).max(assessmentExpressAttemptOneCurrentItemOneContentSevenMaxSourceLengthMax).describe('Maximum length of the solution source in characters.') +}).describe('Code practice. The candidate submits one final solution, which runs in the isolated sandbox against three groups of hidden checks. The content lists only the statement, the allowed languages, and public examples; hidden checks, their inputs, and seeds never reach the client.')]).describe('Format-specific part of an item, selected by `format`. It holds only what the candidate needs to answer: never an answer key, a correct option, a score, a family or variant identifier, a seed, or a hidden check. Limits such as `multiple`, `max_selections`, and `max_length` belong to the format or the task family and never reveal the key.') +}).describe('Item instance served to the candidate. The variant is fixed when it is first served: a reload, a retried request, or a resumed session returns the same instance with the same text and option order. The item never says whether an earlier answer was correct, and seed items, which are not scored, are indistinguishable from scored ones.'),zod.null()]).describe('Item to answer now: a test item in `in_progress`, the practice item to submit in `practice_pending` or `additional_practice_pending` while that practice is `not_started` or `failed`, and null otherwise.'), + "practices": zod.array(zod.object({ + "kind": zod.enum(['main', 'additional']).describe('Role of a practice in the attempt.\n\n- main: the practice that every attempt with practice requires before a decision.\n- additional: adaptive only; offered by finalize when the probability of reaching the grade is in the band below confirmation. It continues the same attempt and spends no new attempt.\n\nAdding a value is a contract change.'), + "item_id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'), + "status": zod.enum(['not_started', 'pending', 'finished', 'failed']).describe('State of a practice.\n\n- not_started: no solution was submitted yet.\n- pending: the submitted solution is queued or running in the sandbox.\n- finished: the sandbox ran the solution and returned a verdict; `verdict` holds it. Every outcome caused by the solution itself, such as a compilation error, a runtime error, a time limit, or a memory limit, is `finished` with the affected groups not passed.\n- failed: the sandbox infrastructure could not run the solution, for example because its queue was full or an executor broke, independently of the solution. The failure is not the candidate\'s and consumes nothing; the practice can be submitted again.'), + "submitted_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('Time of the latest submission, or null before the first one.'), + "verdict": zod.union([zod.object({ + "score": zod.int().min(assessmentExpressAttemptOnePracticesItemVerdictOneScoreMin).max(assessmentExpressAttemptOnePracticesItemVerdictOneScoreMax), + "max_score": zod.int().min(assessmentExpressAttemptOnePracticesItemVerdictOneMaxScoreMin).max(assessmentExpressAttemptOnePracticesItemVerdictOneMaxScoreMax), + "groups": zod.array(zod.object({ + "group": zod.int().min(1).max(assessmentExpressAttemptOnePracticesItemVerdictOneGroupsItemGroupMax), + "passed": zod.boolean() +}).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('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']), + "specialization": zod.null(), + "target_grade": zod.null(), + "task_language": zod.null(), + "root_attempt_id": zod.null(), + "chain_deadline": zod.null() +})).and(zod.object({ + "kind": zod.enum(['demo_express']) +})) + +export type AssessmentExpressAttempt = zod.input; +export type AssessmentExpressAttemptOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentExpressAttemptCreate.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentExpressAttemptCreate.zod.ts new file mode 100644 index 0000000..1da548a --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentExpressAttemptCreate.zod.ts @@ -0,0 +1,14 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const AssessmentExpressAttemptCreate = zod.object({ + "kind": zod.enum(['demo_express']).describe('Explicitly request the training run; real modes cannot be selected by the client.') +}).describe('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.') + +export type AssessmentExpressAttemptCreate = zod.input; +export type AssessmentExpressAttemptCreateOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentExpressResult.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentExpressResult.zod.ts new file mode 100644 index 0000000..fac5f51 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentExpressResult.zod.ts @@ -0,0 +1,100 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + + +export const assessmentExpressResultVersionsBankVersionMax = 64; + + +export const assessmentExpressResultVersionsBankVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$'); +export const assessmentExpressResultVersionsAlgorithmVersionMax = 64; + + +export const assessmentExpressResultVersionsAlgorithmVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$'); +export const assessmentExpressResultLimitationsMax = 1; + +export const assessmentExpressResultPracticesItemVerdictScoreMin = 0; +export const assessmentExpressResultPracticesItemVerdictScoreMax = 3; + +export const assessmentExpressResultPracticesItemVerdictMaxScoreMin = 3; +export const assessmentExpressResultPracticesItemVerdictMaxScoreMax = 3; + +export const assessmentExpressResultPracticesItemVerdictGroupsItemGroupMax = 3; + +export const assessmentExpressResultPracticesItemVerdictGroupsMin = 3; +export const assessmentExpressResultPracticesItemVerdictGroupsMax = 3; + +export const assessmentExpressResultPracticesMax = 0; + +export const assessmentExpressResultGapsItemDomainMax = 64; + + +export const assessmentExpressResultGapsItemDomainRegExp = new RegExp('^[a-z0-9_]+$'); +export const assessmentExpressResultGapsItemTitleMax = 200; + +export const assessmentExpressResultGapsMax = 0; + +export const assessmentExpressResultDurationsItemsSecondsMin = 0; + +export const assessmentExpressResultDurationsPracticeSecondsMin = 0; + +export const assessmentExpressResultNextStepsMax = 0; + +export const assessmentExpressResultSummaryMax = 2000; + + +export const AssessmentExpressResult = zod.object({ + "attempt_id": zod.uuid(), + "specialization": zod.null().describe('Express training does not assess a specialization.'), + "target_grade": zod.null().describe('Express training does not assess a target grade.'), + "task_language": zod.null(), + "kind": zod.enum(['demo_express']), + "mode": zod.enum(['demo_express']), + "versions": zod.object({ + "policy_version": zod.int().min(1).describe('Number of the `product` policy version whose assessment rules apply: thresholds, stop rules, item limits, time and session limits, and retry intervals.'), + "bank_version": zod.string().min(1).max(assessmentExpressResultVersionsBankVersionMax).regex(assessmentExpressResultVersionsBankVersionRegExp).describe('Opaque identifier of a published version, for example `backend-demo.2026-10.1`. Clients show it as text and never parse it.'), + "algorithm_version": zod.string().min(1).max(assessmentExpressResultVersionsAlgorithmVersionMax).regex(assessmentExpressResultVersionsAlgorithmVersionRegExp).describe('Opaque identifier of a published version, for example `backend-demo.2026-10.1`. Clients show it as text and never parse it.') +}).describe('Versions fixed when the attempt was created. They never change during the attempt, and a result is always reproduced from the stored answers with these versions; a later policy, bank, or algorithm version does not rewrite it.'), + "outcome": zod.enum(['demonstration']), + "not_determined_reason": zod.null(), + "confirmed_grade": zod.null().describe('Express training never confirms a grade.'), + "previous_confirmed_grade": zod.null(), + "strength": zod.null(), + "calibration_status": zod.enum(['uncalibrated']), + "limitations": zod.array(zod.enum(['demonstration_only'])).min(1).max(assessmentExpressResultLimitationsMax), + "uncertainty": zod.null().describe('Express training computes no ability estimate or percentile.'), + "basic_score": zod.null(), + "practices": zod.array(zod.object({ + "kind": zod.enum(['main', 'additional']).describe('Role of a practice in the attempt.\n\n- main: the practice that every attempt with practice requires before a decision.\n- additional: adaptive only; offered by finalize when the probability of reaching the grade is in the band below confirmation. It continues the same attempt and spends no new attempt.\n\nAdding a value is a contract change.'), + "verdict": zod.object({ + "score": zod.int().min(assessmentExpressResultPracticesItemVerdictScoreMin).max(assessmentExpressResultPracticesItemVerdictScoreMax), + "max_score": zod.int().min(assessmentExpressResultPracticesItemVerdictMaxScoreMin).max(assessmentExpressResultPracticesItemVerdictMaxScoreMax), + "groups": zod.array(zod.object({ + "group": zod.int().min(1).max(assessmentExpressResultPracticesItemVerdictGroupsItemGroupMax), + "passed": zod.boolean() +}).describe('Outcome of one hidden check group. It never contains the checks themselves.')).min(assessmentExpressResultPracticesItemVerdictGroupsMin).max(assessmentExpressResultPracticesItemVerdictGroupsMax) +}).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.') +}).describe('Verdict of one practice of the attempt.')).max(assessmentExpressResultPracticesMax), + "gaps": zod.array(zod.object({ + "domain": zod.string().min(1).max(assessmentExpressResultGapsItemDomainMax).regex(assessmentExpressResultGapsItemDomainRegExp).describe('Stable domain code of the bank blueprint.'), + "title": zod.string().min(1).max(assessmentExpressResultGapsItemTitleMax).describe('Display name in Russian. Plain text.') +}).describe('Domain of the specialization where the evidence was weak.')).max(assessmentExpressResultGapsMax), + "durations": zod.object({ + "items_seconds": zod.int().min(assessmentExpressResultDurationsItemsSecondsMin), + "practice_seconds": zod.int().min(assessmentExpressResultDurationsPracticeSecondsMin).nullable().describe('Time on all practices with a verdict, or null when no practice has one.') +}).describe('Working time recorded by the server. It is a separate label: it never enters the ability estimate or the grade decision.'), + "next_steps": zod.array(zod.object({ + "action": zod.enum(['retake_same_grade', 'take_lower_grade', 'accept_lower_grade', 'take_higher_grade']).describe('Step that the candidate may take next.\n\n- retake_same_grade: test the same grade again from `available_at`.\n- take_lower_grade: test the lower `grade`. After a failure, including the first test, it is allowed at once, outside the same-grade retry interval.\n- accept_lower_grade: accept the lower `grade` on the evidence of this attempt, when the data are sufficient (the command is planned).\n- take_higher_grade: test the higher `grade` from `available_at`. A first confirmation is not a promotion, so after it `available_at` is null; after a promotion the next one waits for the promotion interval of the policy.'), + "grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'), + "available_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('First time the step is allowed, or null when it is allowed now.') +}).describe('Step that the server allows after this result, computed when it was decided.')).max(assessmentExpressResultNextStepsMax), + "summary": zod.string().min(1).max(assessmentExpressResultSummaryMax).describe('Short educational feedback about this training run.'), + "decided_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.') +}).describe('Immutable educational result of a demo_express run. It includes a short summary but cannot report a category, percentile, uncertainty, grade, strength, or qualification evidence. The result belongs only to the training mode and does not consume a real-assessment quota.') + +export type AssessmentExpressResult = zod.input; +export type AssessmentExpressResultOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentFinalization.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentFinalization.zod.ts index 2e6dffa..c0fc59b 100644 --- a/frontend/src/shared/api/schemas/assessment/assessmentFinalization.zod.ts +++ b/frontend/src/shared/api/schemas/assessment/assessmentFinalization.zod.ts @@ -9,7 +9,7 @@ import * as zod from 'zod'; export const AssessmentFinalization = zod.object({ - "expected_version": zod.int().min(1).describe('Version of an assessment attempt. A new attempt has version 1, and each committed change advances it by exactly one: an accepted answer, a practice submission or resubmission, a verdict, a decision of finalize, a session start, and a server-side transition such as expiry or automatic finalization. A transition that the server applies when the attempt is read is committed before the response and also advances it. A rejected command and a repeat that stores nothing leave it unchanged. Commands send the version they read as `expected_version`.') + "expected_version": zod.int().min(1).describe('Version of an assessment attempt. A new attempt has version 1, and each committed change advances it by exactly one: an accepted answer, a practice submission or resubmission, a verdict, a decision of finalize, an explicit work-session start, and a server-side transition such as expiry or automatic finalization. Reads never change the attempt. A rejected command and a repeat that stores nothing leave it unchanged. Commands send the version they read as `expected_version`.') }).describe('Command to finalize the attempt.') export type AssessmentFinalization = zod.input; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentGradeAvailability.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentGradeAvailability.zod.ts index 5804112..469d98d 100644 --- a/frontend/src/shared/api/schemas/assessment/assessmentGradeAvailability.zod.ts +++ b/frontend/src/shared/api/schemas/assessment/assessmentGradeAvailability.zod.ts @@ -15,7 +15,7 @@ export const assessmentGradeAvailabilityMaxItemsMax = 100; export const AssessmentGradeAvailability = zod.object({ "grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'), "status": zod.enum(['available', 'active_attempt', 'cooldown', 'insufficient_bank']).describe('Whether an attempt for the grade can start now.\n\n- available: CreateMyAssessmentAttempt can start it.\n- active_attempt: the specialization has an active attempt; resume it by `active_attempt_id`.\n- cooldown: a retry or promotion interval or the attempt limit of the policy blocks it until `available_at`. Attempts that ended as `insufficient_bank` or `sandbox_unavailable` never cause it.\n- insufficient_bank: no published bank of the category, or not enough unseen families to cover the blueprint for this candidate. The server never fills the gap by repeating families.'), - "mode": zod.union([zod.enum(['demo_basic', 'adaptive']).describe('Measurement method of an attempt. The server selects it from the published task bank of the category; the client never chooses it.\n\n- demo_basic: a fixed form of reviewed demo items scored by their keys against the pass mark of the versioned basic grading policy. It computes no ability estimate, standard error, or probability, so every uncertainty field of its result is null, its thresholds are uncalibrated, and its decision is binary: it never offers an additional practice.\n- adaptive: the adaptive test on task families with an ability estimate, its standard error, and the probability of reaching the grade threshold, as the versioned assessment policy defines them. A probability in the band below confirmation offers one additional practice in the same attempt.\n\nAdding a value is a contract change.'),zod.null()]).describe('Mode that an attempt would use, or null when the status is `insufficient_bank`.'), + "mode": zod.union([zod.enum(['demo_basic', 'adaptive']).describe('Server-selected mode available to a real category assessment.'),zod.null()]).describe('Real-assessment mode that the server would use, or null when the status is `insufficient_bank`. `demo_express` is not a category assessment and is never returned here.'), "available_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('When the status is `cooldown`, the first time the attempt can start; otherwise null.'), "time_limit_seconds": zod.int().min(1).nullable().describe('Time from the start to `expires_at`.'), "max_sessions": zod.int().min(1).max(assessmentGradeAvailabilityMaxSessionsMax).nullable().describe('Session limit within the time limit.'), diff --git a/frontend/src/shared/api/schemas/assessment/assessmentLimitation.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentLimitation.zod.ts index dab5b2b..1cb4698 100644 --- a/frontend/src/shared/api/schemas/assessment/assessmentLimitation.zod.ts +++ b/frontend/src/shared/api/schemas/assessment/assessmentLimitation.zod.ts @@ -6,7 +6,7 @@ */ import * as zod from 'zod'; -export const AssessmentLimitation = zod.enum(['uncalibrated_thresholds', 'demo_bank', 'practice_not_included', 'unproctored']).describe('Known limitation of the method behind a result, shown with the result.\n\n- uncalibrated_thresholds: the thresholds are not yet validated on a pilot.\n- demo_bank: the result comes from the small reviewed demo bank.\n- practice_not_included: the attempt had no code practice because the sandbox was not enabled.\n- unproctored: the attempt was taken online without supervision.\n\nAdding a value is a contract change.') +export const AssessmentLimitation = zod.enum(['uncalibrated_thresholds', 'demo_bank', 'practice_not_included', 'unproctored']).describe('Known limitation of the method behind a real-assessment result, shown with the result.\n\n- uncalibrated_thresholds: the thresholds are not yet validated on a pilot.\n- demo_bank: the result comes from the small reviewed demo bank.\n- practice_not_included: the attempt had no code practice because the sandbox was not enabled.\n- unproctored: the attempt was taken online without supervision.\nAdding a value is a contract change.') export type AssessmentLimitation = zod.input; export type AssessmentLimitationOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentMode.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentMode.zod.ts index ed4b459..09d75ce 100644 --- a/frontend/src/shared/api/schemas/assessment/assessmentMode.zod.ts +++ b/frontend/src/shared/api/schemas/assessment/assessmentMode.zod.ts @@ -6,7 +6,7 @@ */ import * as zod from 'zod'; -export const AssessmentMode = zod.enum(['demo_basic', 'adaptive']).describe('Measurement method of an attempt. The server selects it from the published task bank of the category; the client never chooses it.\n\n- demo_basic: a fixed form of reviewed demo items scored by their keys against the pass mark of the versioned basic grading policy. It computes no ability estimate, standard error, or probability, so every uncertainty field of its result is null, its thresholds are uncalibrated, and its decision is binary: it never offers an additional practice.\n- adaptive: the adaptive test on task families with an ability estimate, its standard error, and the probability of reaching the grade threshold, as the versioned assessment policy defines them. A probability in the band below confirmation offers one additional practice in the same attempt.\n\nAdding a value is a contract change.') +export const AssessmentMode = zod.enum(['demo_basic', 'demo_express', 'adaptive']).describe('Method of an assessment attempt. For a real assessment, the server selects demo_basic or adaptive from the published bank. A candidate may explicitly request demo_express, which uses a separate training policy and creates no qualification evidence.\n\n- demo_basic: a fixed form of reviewed demo items scored by their keys against the pass mark of the versioned basic grading policy. It computes no ability estimate, standard error, or probability, so every uncertainty field of its result is null, its thresholds are uncalibrated, and its decision is binary: it never offers an additional practice.\n- adaptive: the adaptive test on task families with an ability estimate, its standard error, and the probability of reaching the grade threshold, as the versioned assessment policy defines them. A probability in the band below confirmation offers one additional practice in the same attempt.\n- demo_express: an interactive 3 to 5 minute training run under a separate policy. It does not assign a category or percentile, count toward the real-assessment quota, or create qualification evidence.\n\nAdding a value is a contract change.') export type AssessmentMode = zod.input; export type AssessmentModeOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentNotDeterminedReason.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentNotDeterminedReason.zod.ts index 826b618..b2bbf7c 100644 --- a/frontend/src/shared/api/schemas/assessment/assessmentNotDeterminedReason.zod.ts +++ b/frontend/src/shared/api/schemas/assessment/assessmentNotDeterminedReason.zod.ts @@ -6,7 +6,7 @@ */ import * as zod from 'zod'; -export const AssessmentNotDeterminedReason = zod.enum(['expired', 'practice_incomplete', 'insufficient_bank', 'sandbox_unavailable']).describe('Why an attempt gives no decision, and whether it counts against the retry rules.\n\n- expired: the time or session limit passed before the candidate finished the item part. It is the candidate\'s attempt: it counts toward the attempt limit and starts the same-grade retry interval.\n- practice_incomplete: the item part was done, but the candidate did not submit the main practice before the limit. It counts like `expired`.\n- insufficient_bank: the bank could not supply the required coverage within the limit. It is a platform limitation: it never counts toward the attempt limit and starts no retry interval.\n- sandbox_unavailable: the latest submission of a required or additional practice ended `failed` because of the sandbox infrastructure, and the limit passed before a verdict. It is a platform fault: it never counts toward the attempt limit and starts no retry interval.') +export const AssessmentNotDeterminedReason = zod.enum(['expired', 'practice_incomplete', 'insufficient_bank', 'sandbox_unavailable']).describe('Why an attempt gives no decision. One root quota slot is reserved when a real root attempt starts; corrective checks in its chain do not reserve another slot.\n\n- expired: the time or session limit passed before the candidate finished the item part. Retry timing follows the recorded policy; a correction uses the existing root slot and does not reset the chain deadline or 30/90-day timers.\n- practice_incomplete: the item part was done, but the candidate did not submit the main practice before the limit. Retry timing follows the recorded policy; a correction uses the existing root slot and does not reset the chain deadline or 30/90-day timers.\n- insufficient_bank: the bank could not supply required coverage. A preflight refusal creates no attempt or root slot; a bank failure in an existing chain does not create a free new chain or another root slot.\n- sandbox_unavailable: the latest submission of a required or additional practice ended `failed` because of the sandbox infrastructure, and the limit passed before a verdict. It is a platform fault and does not create a new root slot or a free chain.') export type AssessmentNotDeterminedReason = zod.input; export type AssessmentNotDeterminedReasonOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentQualifiedAttempt.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentQualifiedAttempt.zod.ts new file mode 100644 index 0000000..0d873a1 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentQualifiedAttempt.zod.ts @@ -0,0 +1,202 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + + + +export const assessmentQualifiedAttemptOneVersionsBankVersionMax = 64; + + +export const assessmentQualifiedAttemptOneVersionsBankVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$'); +export const assessmentQualifiedAttemptOneVersionsAlgorithmVersionMax = 64; + + +export const assessmentQualifiedAttemptOneVersionsAlgorithmVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$'); +export const assessmentQualifiedAttemptOneSessionsOneUsedMax = 10; + +export const assessmentQualifiedAttemptOneSessionsOneMaxMax = 10; + +export const assessmentQualifiedAttemptOneSessionsOneIdleTimeoutSecondsMin = 60; +export const assessmentQualifiedAttemptOneSessionsOneIdleTimeoutSecondsMax = 86400; + +export const assessmentQualifiedAttemptOneProgressAnsweredItemsMin = 0; +export const assessmentQualifiedAttemptOneProgressAnsweredItemsMax = 100; + +export const assessmentQualifiedAttemptOneProgressMaxItemsMax = 100; + +export const assessmentQualifiedAttemptOneCurrentItemOneSequenceMax = 100; + +export const assessmentQualifiedAttemptOneCurrentItemOnePromptMax = 20000; + +export const assessmentQualifiedAttemptOneCurrentItemOneContentOneOptionsItemIdMax = 32; + + +export const assessmentQualifiedAttemptOneCurrentItemOneContentOneOptionsItemIdRegExp = new RegExp('^[A-Za-z0-9_-]+$'); +export const assessmentQualifiedAttemptOneCurrentItemOneContentOneOptionsItemTextMax = 2000; + +export const assessmentQualifiedAttemptOneCurrentItemOneContentOneOptionsMin = 2; +export const assessmentQualifiedAttemptOneCurrentItemOneContentOneOptionsMax = 10; + +export const assessmentQualifiedAttemptOneCurrentItemOneContentTwoUnitMax = 32; + +export const assessmentQualifiedAttemptOneCurrentItemOneContentThreeMaxLengthMax = 500; + +export const assessmentQualifiedAttemptOneCurrentItemOneContentFourElementsItemIdMax = 32; + + +export const assessmentQualifiedAttemptOneCurrentItemOneContentFourElementsItemIdRegExp = new RegExp('^[A-Za-z0-9_-]+$'); +export const assessmentQualifiedAttemptOneCurrentItemOneContentFourElementsItemTextMax = 2000; + +export const assessmentQualifiedAttemptOneCurrentItemOneContentFourElementsMin = 2; +export const assessmentQualifiedAttemptOneCurrentItemOneContentFourElementsMax = 20; + +export const assessmentQualifiedAttemptOneCurrentItemOneContentFiveSyntaxMax = 32; + + +export const assessmentQualifiedAttemptOneCurrentItemOneContentFiveSyntaxRegExp = new RegExp('^[a-z0-9_+-]+$'); +export const assessmentQualifiedAttemptOneCurrentItemOneContentFiveLinesItemNumberMax = 500; + +export const assessmentQualifiedAttemptOneCurrentItemOneContentFiveLinesItemTextMax = 1000; + +export const assessmentQualifiedAttemptOneCurrentItemOneContentFiveLinesMax = 500; + +export const assessmentQualifiedAttemptOneCurrentItemOneContentFiveMaxSelectionsMax = 10; + +export const assessmentQualifiedAttemptOneCurrentItemOneContentSixSyntaxMax = 32; + + +export const assessmentQualifiedAttemptOneCurrentItemOneContentSixSyntaxRegExp = new RegExp('^[a-z0-9_+-]+$'); +export const assessmentQualifiedAttemptOneCurrentItemOneContentSixInitialConfigMax = 20000; + +export const assessmentQualifiedAttemptOneCurrentItemOneContentSixMaxLengthMax = 20000; + +export const assessmentQualifiedAttemptOneCurrentItemOneContentSevenLanguagesMax = 2; + +export const assessmentQualifiedAttemptOneCurrentItemOneContentSevenPublicExamplesItemInputMax = 10000; + +export const assessmentQualifiedAttemptOneCurrentItemOneContentSevenPublicExamplesItemExpectedOutputMax = 10000; + +export const assessmentQualifiedAttemptOneCurrentItemOneContentSevenPublicExamplesMax = 10; + +export const assessmentQualifiedAttemptOneCurrentItemOneContentSevenMaxSourceLengthMax = 65536; + +export const assessmentQualifiedAttemptOnePracticesItemVerdictOneScoreMin = 0; +export const assessmentQualifiedAttemptOnePracticesItemVerdictOneScoreMax = 3; + +export const assessmentQualifiedAttemptOnePracticesItemVerdictOneMaxScoreMin = 3; +export const assessmentQualifiedAttemptOnePracticesItemVerdictOneMaxScoreMax = 3; + +export const assessmentQualifiedAttemptOnePracticesItemVerdictOneGroupsItemGroupMax = 3; + +export const assessmentQualifiedAttemptOnePracticesItemVerdictOneGroupsMin = 3; +export const assessmentQualifiedAttemptOnePracticesItemVerdictOneGroupsMax = 3; + +export const assessmentQualifiedAttemptOnePracticesMax = 5; + + +export const AssessmentQualifiedAttempt = zod.object({ + "id": zod.uuid().describe('Attempt identifier.'), + "version": zod.int().min(1).describe('Version of an assessment attempt. A new attempt has version 1, and each committed change advances it by exactly one: an accepted answer, a practice submission or resubmission, a verdict, a decision of finalize, an explicit work-session start, and a server-side transition such as expiry or automatic finalization. Reads never change the attempt. A rejected command and a repeat that stores nothing leave it unchanged. Commands send the version they read as `expected_version`.'), + "specialization": zod.union([zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'),zod.null()]).describe('Null only for demo_express, which has no qualification category.'), + "target_grade": zod.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Null only for demo_express, which has no qualification category.'), + "task_language": zod.union([zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.'),zod.null()]).describe('Task language of the attempt, or null when none is selected.'), + "kind": zod.enum(['root', 'corrective', 'demo_express']).describe('Assessment track that distinguishes root, corrective, and training attempts.'), + "root_attempt_id": zod.union([zod.uuid(),zod.null()]).describe('Present only for a corrective real assessment. It identifies the root attempt whose quota and chain deadline this attempt shares.'), + "chain_deadline": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('Present only for a corrective real assessment. It is the immutable deadline derived from the root attempt and is not extended by a lower target grade.'), + "mode": zod.enum(['demo_basic', 'demo_express', 'adaptive']).describe('Method of an assessment attempt. For a real assessment, the server selects demo_basic or adaptive from the published bank. A candidate may explicitly request demo_express, which uses a separate training policy and creates no qualification evidence.\n\n- demo_basic: a fixed form of reviewed demo items scored by their keys against the pass mark of the versioned basic grading policy. It computes no ability estimate, standard error, or probability, so every uncertainty field of its result is null, its thresholds are uncalibrated, and its decision is binary: it never offers an additional practice.\n- adaptive: the adaptive test on task families with an ability estimate, its standard error, and the probability of reaching the grade threshold, as the versioned assessment policy defines them. A probability in the band below confirmation offers one additional practice in the same attempt.\n- demo_express: an interactive 3 to 5 minute training run under a separate policy. It does not assign a category or percentile, count toward the real-assessment quota, or create qualification evidence.\n\nAdding a value is a contract change.'), + "state": zod.enum(['in_progress', 'practice_pending', 'additional_practice_pending', 'ready_to_finalize', 'completed', 'expired', 'insufficient_bank']).describe('Lifecycle state of an attempt and the commands it accepts.\n\n- in_progress: items are being answered; `current_item` is the item to answer. Accepts SubmitMyAssessmentAnswer for that item.\n- practice_pending: the item part is finished, and the main practice has no finished verdict yet: it is not submitted, its verdict is pending in the sandbox, or the sandbox failed and the practice can be submitted again. Accepts SubmitMyAssessmentAnswer with the practice item while its status is `not_started` or `failed`. No grade is confirmed while the practice is unfinished, even when the adaptive stop rule has already ended the item part.\n- additional_practice_pending: adaptive only. Finalize found the probability of reaching the grade in the band below confirmation, so the attempt offers one additional practice without spending a new attempt; it keeps the time and session limits of the attempt. Accepts SubmitMyAssessmentAnswer with the additional practice item while its status is `not_started` or `failed`, and FinalizeMyAssessmentAttempt in the same statuses, which declines the offer and decides `not_confirmed` with the current evidence.\n- ready_to_finalize: every required part is done, including a submitted additional practice with a finished verdict. Accepts FinalizeMyAssessmentAttempt.\n- completed: a decision was made; the result is available.\n- expired: the time or session limit passed before the candidate finished the required parts. The result is available and confirms no grade.\n- insufficient_bank: the published bank could not supply the items required for coverage within the limit, and the attempt ended without a confirmed grade instead of repeating families. The result is available.\n\nWhen `expires_at` passes or the session limit is reached, a read returns the stored state without changing it. A command or background transition commits any due outcome and advances the version. A practice submitted before the limit and still `pending` is graded first. Then `ready_to_finalize` becomes `completed`; `additional_practice_pending` with the additional practice not submitted is finalized as declined and becomes `completed` with `not_confirmed`; `in_progress` and `practice_pending` become `expired`, with the result reason `expired` or `practice_incomplete`; and when the latest submission of a practice ended `failed`, the attempt becomes `expired` with the reason `sandbox_unavailable`, which is not the candidate\'s fault. `completed`, `expired`, and `insufficient_bank` are terminal and accept no command except the repeat of finalize described on FinalizeMyAssessmentAttempt. Adding a value is a contract change.'), + "versions": zod.object({ + "policy_version": zod.int().min(1).describe('Number of the `product` policy version whose assessment rules apply: thresholds, stop rules, item limits, time and session limits, and retry intervals.'), + "bank_version": zod.string().min(1).max(assessmentQualifiedAttemptOneVersionsBankVersionMax).regex(assessmentQualifiedAttemptOneVersionsBankVersionRegExp).describe('Opaque identifier of a published version, for example `backend-demo.2026-10.1`. Clients show it as text and never parse it.'), + "algorithm_version": zod.string().min(1).max(assessmentQualifiedAttemptOneVersionsAlgorithmVersionMax).regex(assessmentQualifiedAttemptOneVersionsAlgorithmVersionRegExp).describe('Opaque identifier of a published version, for example `backend-demo.2026-10.1`. Clients show it as text and never parse it.') +}).describe('Versions fixed when the attempt was created. They never change during the attempt, and a result is always reproduced from the stored answers with these versions; a later policy, bank, or algorithm version does not rewrite it.'), + "started_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'), + "expires_at": zod.iso.datetime({"offset":true}).describe('Server deadline. For demo_express it is 180 to 300 seconds after started_at; for a corrective assessment it does not exceed chain_deadline.'), + "sessions": zod.union([zod.object({ + "used": zod.int().min(1).max(assessmentQualifiedAttemptOneSessionsOneUsedMax).describe('Sessions started so far, including the current one.'), + "max": zod.int().min(1).max(assessmentQualifiedAttemptOneSessionsOneMaxMax), + "idle_timeout_seconds": zod.int().min(assessmentQualifiedAttemptOneSessionsOneIdleTimeoutSecondsMin).max(assessmentQualifiedAttemptOneSessionsOneIdleTimeoutSecondsMax).describe('Inactivity after which the current session ends.') +}).describe('Work sessions of the attempt, as the policy version limits them, for example two sessions within the time limit.\n\nSession 1 starts with attempt creation. After it ends due to `idle_timeout_seconds` of inactivity, the candidate explicitly starts or resumes work with StartMyAssessmentAttemptSession. GetMyAssessmentAttempt and GetMyAssessmentResult are read-only and never start a session. The session command checks the attempt deadline and `max_sessions`; when either limit has passed, it records the due terminal transition and returns the resulting attempt. Reads of terminal attempts do not change them.'),zod.null()]).describe('Session limit of the attempt, or null when its policy defines none.'), + "finished_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('Time the attempt reached a terminal state, or null while it is active.'), + "progress": zod.object({ + "answered_items": zod.int().min(assessmentQualifiedAttemptOneProgressAnsweredItemsMin).max(assessmentQualifiedAttemptOneProgressAnsweredItemsMax), + "max_items": zod.int().min(1).max(assessmentQualifiedAttemptOneProgressMaxItemsMax).describe('Item limit of the attempt: the form size in demo_basic, or the policy limit of scored and seed items together in adaptive.') +}).describe('Progress of the item part. It counts seed items like scored ones, so it does not reveal which items are scored. An adaptive attempt may end its item part before `max_items` by its stop rule. A finalize refused as premature does not list the unfinished parts; the client reads them here, in `current_item`, and in `practices`.'), + "current_item": zod.union([zod.object({ + "id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'), + "sequence": zod.int().min(1).max(assessmentQualifiedAttemptOneCurrentItemOneSequenceMax).describe('Position of the item in the attempt, from 1.'), + "prompt": zod.string().min(1).max(assessmentQualifiedAttemptOneCurrentItemOnePromptMax).describe('Statement in Russian. Plain text with line breaks; the client shows it as text, never as HTML.'), + "content": zod.union([zod.object({ + "format": zod.enum(['choice']), + "options": zod.array(zod.object({ + "id": zod.string().min(1).max(assessmentQualifiedAttemptOneCurrentItemOneContentOneOptionsItemIdMax).regex(assessmentQualifiedAttemptOneCurrentItemOneContentOneOptionsItemIdRegExp).describe('Opaque identifier of a choice option or an order element within one item instance. It is unrelated to the position or correctness of the option.'), + "text": zod.string().min(1).max(assessmentQualifiedAttemptOneCurrentItemOneContentOneOptionsItemTextMax).describe('Text of the option; the client shows it as text, never as HTML.') +}).describe('Choice option or order element. Plain text.')).min(assessmentQualifiedAttemptOneCurrentItemOneContentOneOptionsMin).max(assessmentQualifiedAttemptOneCurrentItemOneContentOneOptionsMax).describe('Options in the order of this instance.'), + "multiple": zod.boolean().describe('Whether more than one option may be selected. It is a property of the task family, fixed for every variant, and never derived from the key: a multiple-choice variant may have a single correct option.') +}).describe('Choose one option, or several when `multiple` is true. The content never says which options are correct or how many are.'),zod.object({ + "format": zod.enum(['number']), + "unit": zod.string().min(1).max(assessmentQualifiedAttemptOneCurrentItemOneContentTwoUnitMax).nullable().describe('Unit of the expected value, for example `ms`, or null.') +}).describe('Enter a number, optionally in the given unit.'),zod.object({ + "format": zod.enum(['string']), + "max_length": zod.int().min(1).max(assessmentQualifiedAttemptOneCurrentItemOneContentThreeMaxLengthMax).describe('Maximum length of the answer in characters. It is an input limit of the task family, never derived from the key, so it does not reveal the length of the correct answer.') +}).describe('Enter a short string, such as a command, a header name, or an address.'),zod.object({ + "format": zod.enum(['order']), + "elements": zod.array(zod.object({ + "id": zod.string().min(1).max(assessmentQualifiedAttemptOneCurrentItemOneContentFourElementsItemIdMax).regex(assessmentQualifiedAttemptOneCurrentItemOneContentFourElementsItemIdRegExp).describe('Opaque identifier of a choice option or an order element within one item instance. It is unrelated to the position or correctness of the option.'), + "text": zod.string().min(1).max(assessmentQualifiedAttemptOneCurrentItemOneContentFourElementsItemTextMax).describe('Text of the option; the client shows it as text, never as HTML.') +}).describe('Choice option or order element. Plain text.')).min(assessmentQualifiedAttemptOneCurrentItemOneContentFourElementsMin).max(assessmentQualifiedAttemptOneCurrentItemOneContentFourElementsMax) +}).describe('Put every element into the right order. The elements arrive in the order of this instance, which is never the answer.'),zod.object({ + "format": zod.enum(['find_error']), + "syntax": zod.string().min(1).max(assessmentQualifiedAttemptOneCurrentItemOneContentFiveSyntaxMax).regex(assessmentQualifiedAttemptOneCurrentItemOneContentFiveSyntaxRegExp).nullable().describe('Highlighting hint such as `go`, `python`, or `cisco_ios`, or null.'), + "lines": zod.array(zod.object({ + "number": zod.int().min(1).max(assessmentQualifiedAttemptOneCurrentItemOneContentFiveLinesItemNumberMax), + "text": zod.string().max(assessmentQualifiedAttemptOneCurrentItemOneContentFiveLinesItemTextMax) +}).describe('One numbered line of a code or configuration fragment. Plain text.')).min(1).max(assessmentQualifiedAttemptOneCurrentItemOneContentFiveLinesMax).describe('Lines numbered from 1 in order.'), + "max_selections": zod.int().min(1).max(assessmentQualifiedAttemptOneCurrentItemOneContentFiveMaxSelectionsMax).describe('Maximum number of lines the answer may select. It is a limit of the task family, fixed for every variant and never derived from the key; it is not the number of wrong lines.') +}).describe('Find the lines with the error in a code or configuration fragment and select up to `max_selections` line numbers.'),zod.object({ + "format": zod.enum(['configuration']), + "syntax": zod.string().min(1).max(assessmentQualifiedAttemptOneCurrentItemOneContentSixSyntaxMax).regex(assessmentQualifiedAttemptOneCurrentItemOneContentSixSyntaxRegExp).describe('Configuration syntax such as `cisco_ios`, `nginx`, or `yaml`.'), + "initial_config": zod.string().max(assessmentQualifiedAttemptOneCurrentItemOneContentSixInitialConfigMax).describe('Starting text to edit; empty when the candidate writes it from scratch.'), + "max_length": zod.int().min(1).max(assessmentQualifiedAttemptOneCurrentItemOneContentSixMaxLengthMax).describe('Maximum length of the submitted configuration in characters, an input limit of the task family that is never derived from the key.') +}).describe('Write or fix a configuration. The server checks the submitted text with the computed key or reference check of the task family; it never executes it as code.'),zod.object({ + "format": zod.enum(['practice']), + "languages": zod.array(zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.')).max(assessmentQualifiedAttemptOneCurrentItemOneContentSevenLanguagesMax).describe('Languages the solution may use. Empty when the task does not offer a choice; the submission then sends a null language.'), + "public_examples": zod.array(zod.object({ + "input": zod.string().max(assessmentQualifiedAttemptOneCurrentItemOneContentSevenPublicExamplesItemInputMax), + "expected_output": zod.string().max(assessmentQualifiedAttemptOneCurrentItemOneContentSevenPublicExamplesItemExpectedOutputMax) +}).describe('Public example of the practice task: an input and its expected output. Hidden checks are never listed.')).max(assessmentQualifiedAttemptOneCurrentItemOneContentSevenPublicExamplesMax), + "max_source_length": zod.int().min(1).max(assessmentQualifiedAttemptOneCurrentItemOneContentSevenMaxSourceLengthMax).describe('Maximum length of the solution source in characters.') +}).describe('Code practice. The candidate submits one final solution, which runs in the isolated sandbox against three groups of hidden checks. The content lists only the statement, the allowed languages, and public examples; hidden checks, their inputs, and seeds never reach the client.')]).describe('Format-specific part of an item, selected by `format`. It holds only what the candidate needs to answer: never an answer key, a correct option, a score, a family or variant identifier, a seed, or a hidden check. Limits such as `multiple`, `max_selections`, and `max_length` belong to the format or the task family and never reveal the key.') +}).describe('Item instance served to the candidate. The variant is fixed when it is first served: a reload, a retried request, or a resumed session returns the same instance with the same text and option order. The item never says whether an earlier answer was correct, and seed items, which are not scored, are indistinguishable from scored ones.'),zod.null()]).describe('Item to answer now: a test item in `in_progress`, the practice item to submit in `practice_pending` or `additional_practice_pending` while that practice is `not_started` or `failed`, and null otherwise.'), + "practices": zod.array(zod.object({ + "kind": zod.enum(['main', 'additional']).describe('Role of a practice in the attempt.\n\n- main: the practice that every attempt with practice requires before a decision.\n- additional: adaptive only; offered by finalize when the probability of reaching the grade is in the band below confirmation. It continues the same attempt and spends no new attempt.\n\nAdding a value is a contract change.'), + "item_id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'), + "status": zod.enum(['not_started', 'pending', 'finished', 'failed']).describe('State of a practice.\n\n- not_started: no solution was submitted yet.\n- pending: the submitted solution is queued or running in the sandbox.\n- finished: the sandbox ran the solution and returned a verdict; `verdict` holds it. Every outcome caused by the solution itself, such as a compilation error, a runtime error, a time limit, or a memory limit, is `finished` with the affected groups not passed.\n- failed: the sandbox infrastructure could not run the solution, for example because its queue was full or an executor broke, independently of the solution. The failure is not the candidate\'s and consumes nothing; the practice can be submitted again.'), + "submitted_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('Time of the latest submission, or null before the first one.'), + "verdict": zod.union([zod.object({ + "score": zod.int().min(assessmentQualifiedAttemptOnePracticesItemVerdictOneScoreMin).max(assessmentQualifiedAttemptOnePracticesItemVerdictOneScoreMax), + "max_score": zod.int().min(assessmentQualifiedAttemptOnePracticesItemVerdictOneMaxScoreMin).max(assessmentQualifiedAttemptOnePracticesItemVerdictOneMaxScoreMax), + "groups": zod.array(zod.object({ + "group": zod.int().min(1).max(assessmentQualifiedAttemptOnePracticesItemVerdictOneGroupsItemGroupMax), + "passed": zod.boolean() +}).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('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']), + "specialization": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'), + "target_grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'), + "root_attempt_id": zod.null().describe('Root attempts have no parent attempt.'), + "chain_deadline": zod.null().describe('A root attempt has no correction-chain deadline.') +})).and(zod.object({ + "kind": zod.enum(['root']) +})) + +export type AssessmentQualifiedAttempt = zod.input; +export type AssessmentQualifiedAttemptOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentQualifiedAttemptCreate.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentQualifiedAttemptCreate.zod.ts new file mode 100644 index 0000000..6ad8e93 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentQualifiedAttemptCreate.zod.ts @@ -0,0 +1,17 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const AssessmentQualifiedAttemptCreate = zod.object({ + "kind": zod.enum(['root']).describe('Start a real-assessment chain and reserve one root quota slot.'), + "specialization": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'), + "target_grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'), + "task_language": zod.union([zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.'),zod.null()]).describe('Task language of the attempt, one of the `task_languages` of the published bank, or null when the bank offers no choice of language. The questionnaire choice is the value the client offers first.') +}).describe('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.') + +export type AssessmentQualifiedAttemptCreate = zod.input; +export type AssessmentQualifiedAttemptCreateOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentQualifiedResult.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentQualifiedResult.zod.ts new file mode 100644 index 0000000..9466a05 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentQualifiedResult.zod.ts @@ -0,0 +1,126 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + + +export const assessmentQualifiedResultOneVersionsBankVersionMax = 64; + + +export const assessmentQualifiedResultOneVersionsBankVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$'); +export const assessmentQualifiedResultOneVersionsAlgorithmVersionMax = 64; + + +export const assessmentQualifiedResultOneVersionsAlgorithmVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$'); +export const assessmentQualifiedResultOneLimitationsMax = 10; + +export const assessmentQualifiedResultOneUncertaintyOneStandardErrorMin = 0; + +export const assessmentQualifiedResultOneUncertaintyOnePGradeMin = 0; +export const assessmentQualifiedResultOneUncertaintyOnePGradeMax = 1; + +export const assessmentQualifiedResultOneBasicScoreOnePointsMin = 0; + + + +export const assessmentQualifiedResultOnePracticesItemVerdictScoreMin = 0; +export const assessmentQualifiedResultOnePracticesItemVerdictScoreMax = 3; + +export const assessmentQualifiedResultOnePracticesItemVerdictMaxScoreMin = 3; +export const assessmentQualifiedResultOnePracticesItemVerdictMaxScoreMax = 3; + +export const assessmentQualifiedResultOnePracticesItemVerdictGroupsItemGroupMax = 3; + +export const assessmentQualifiedResultOnePracticesItemVerdictGroupsMin = 3; +export const assessmentQualifiedResultOnePracticesItemVerdictGroupsMax = 3; + +export const assessmentQualifiedResultOnePracticesMax = 5; + +export const assessmentQualifiedResultOneGapsItemDomainMax = 64; + + +export const assessmentQualifiedResultOneGapsItemDomainRegExp = new RegExp('^[a-z0-9_]+$'); +export const assessmentQualifiedResultOneGapsItemTitleMax = 200; + +export const assessmentQualifiedResultOneGapsMax = 20; + +export const assessmentQualifiedResultOneDurationsItemsSecondsMin = 0; + +export const assessmentQualifiedResultOneDurationsPracticeSecondsMin = 0; + +export const assessmentQualifiedResultOneNextStepsMax = 5; + + +export const AssessmentQualifiedResult = zod.object({ + "attempt_id": zod.uuid(), + "specialization": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'), + "target_grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'), + "root_attempt_id": zod.union([zod.uuid(),zod.null()]).describe('Root attempt of a corrective check, or null when this is not a corrective result. The corrective attempt keeps this link.'), + "chain_deadline": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('Immutable deadline shared by a corrective chain, or null when this result is not from a corrective check.'), + "task_language": zod.union([zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.'),zod.null()]), + "kind": zod.enum(['root', 'corrective']), + "mode": zod.enum(['demo_basic', 'adaptive']), + "versions": zod.object({ + "policy_version": zod.int().min(1).describe('Number of the `product` policy version whose assessment rules apply: thresholds, stop rules, item limits, time and session limits, and retry intervals.'), + "bank_version": zod.string().min(1).max(assessmentQualifiedResultOneVersionsBankVersionMax).regex(assessmentQualifiedResultOneVersionsBankVersionRegExp).describe('Opaque identifier of a published version, for example `backend-demo.2026-10.1`. Clients show it as text and never parse it.'), + "algorithm_version": zod.string().min(1).max(assessmentQualifiedResultOneVersionsAlgorithmVersionMax).regex(assessmentQualifiedResultOneVersionsAlgorithmVersionRegExp).describe('Opaque identifier of a published version, for example `backend-demo.2026-10.1`. Clients show it as text and never parse it.') +}).describe('Versions fixed when the attempt was created. They never change during the attempt, and a result is always reproduced from the stored answers with these versions; a later policy, bank, or algorithm version does not rewrite it.'), + "outcome": zod.enum(['confirmed', 'not_confirmed', 'not_determined']).describe('Grade decision of the attempt.\n\n- confirmed: the target grade is confirmed by the rule of the recorded policy version.\n- not_confirmed: the evidence is below the rule, including an adaptive attempt whose probability stayed below confirmation after the additional practice, or whose additional practice was declined or not submitted in time. The previously confirmed grade, if any, stays in force.\n- not_determined: the attempt gives no decision; `not_determined_reason` says why. The previously confirmed grade stays in force.\n\nA failed, expired, or flagged attempt never lowers a confirmed grade.'), + "not_determined_reason": zod.union([zod.enum(['expired', 'practice_incomplete', 'insufficient_bank', 'sandbox_unavailable']).describe('Why an attempt gives no decision. One root quota slot is reserved when a real root attempt starts; corrective checks in its chain do not reserve another slot.\n\n- expired: the time or session limit passed before the candidate finished the item part. Retry timing follows the recorded policy; a correction uses the existing root slot and does not reset the chain deadline or 30/90-day timers.\n- practice_incomplete: the item part was done, but the candidate did not submit the main practice before the limit. Retry timing follows the recorded policy; a correction uses the existing root slot and does not reset the chain deadline or 30/90-day timers.\n- insufficient_bank: the bank could not supply required coverage. A preflight refusal creates no attempt or root slot; a bank failure in an existing chain does not create a free new chain or another root slot.\n- sandbox_unavailable: the latest submission of a required or additional practice ended `failed` because of the sandbox infrastructure, and the limit passed before a verdict. It is a platform fault and does not create a new root slot or a free chain.'),zod.null()]).describe('The reason when `outcome` is `not_determined`, otherwise null.'), + "confirmed_grade": zod.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Grade that this attempt confirmed, the target grade, or null when it confirmed none. Together with the specialization it forms the category.'), + "previous_confirmed_grade": zod.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Confirmed grade of the specialization before this attempt, or null. When the attempt confirmed nothing, this grade stays in force.'), + "strength": zod.union([zod.enum(['high', 'medium']).describe('Strength of an adaptive confirmation: `high` or `medium`, by the probability bands of the recorded policy version.'),zod.null()]).describe('Strength of an adaptive confirmation, otherwise null.'), + "calibration_status": zod.enum(['uncalibrated', 'calibrated']).describe('Whether the thresholds of the recorded policy version are empirically calibrated. `uncalibrated` results are provisional: their thresholds come from expert judgement, and their probabilities are not claimed to be calibrated.'), + "limitations": zod.array(zod.enum(['uncalibrated_thresholds', 'demo_bank', 'practice_not_included', 'unproctored']).describe('Known limitation of the method behind a real-assessment result, shown with the result.\n\n- uncalibrated_thresholds: the thresholds are not yet validated on a pilot.\n- demo_bank: the result comes from the small reviewed demo bank.\n- practice_not_included: the attempt had no code practice because the sandbox was not enabled.\n- unproctored: the attempt was taken online without supervision.\nAdding a value is a contract change.')).max(assessmentQualifiedResultOneLimitationsMax), + "uncertainty": zod.union([zod.object({ + "theta": zod.number(), + "standard_error": zod.number().min(assessmentQualifiedResultOneUncertaintyOneStandardErrorMin), + "interval_95": zod.object({ + "low": zod.number(), + "high": zod.number() +}).describe('Interval on the ability scale.'), + "p_grade": zod.number().min(assessmentQualifiedResultOneUncertaintyOnePGradeMin).max(assessmentQualifiedResultOneUncertaintyOnePGradeMax).describe('Probability of reaching the threshold of the target grade.') +}).describe('Ability estimate of an adaptive attempt and its uncertainty: the EAP estimate on the specialization scale, its standard error, the 95% interval, and the probability of reaching the target grade threshold. The interval is reported but is not a separate stop condition.'),zod.null()]).describe('Ability estimate and uncertainty of an adaptive attempt with a decision; null for demo_basic, which computes none, and for an attempt without a decision.'), + "basic_score": zod.union([zod.object({ + "points": zod.int().min(assessmentQualifiedResultOneBasicScoreOnePointsMin), + "max_points": zod.int().min(1), + "pass_points": zod.int().min(1) +}).describe('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.'),zod.null()]).describe('Raw score of a demo_basic attempt with a decision, otherwise null.'), + "practices": zod.array(zod.object({ + "kind": zod.enum(['main', 'additional']).describe('Role of a practice in the attempt.\n\n- main: the practice that every attempt with practice requires before a decision.\n- additional: adaptive only; offered by finalize when the probability of reaching the grade is in the band below confirmation. It continues the same attempt and spends no new attempt.\n\nAdding a value is a contract change.'), + "verdict": zod.object({ + "score": zod.int().min(assessmentQualifiedResultOnePracticesItemVerdictScoreMin).max(assessmentQualifiedResultOnePracticesItemVerdictScoreMax), + "max_score": zod.int().min(assessmentQualifiedResultOnePracticesItemVerdictMaxScoreMin).max(assessmentQualifiedResultOnePracticesItemVerdictMaxScoreMax), + "groups": zod.array(zod.object({ + "group": zod.int().min(1).max(assessmentQualifiedResultOnePracticesItemVerdictGroupsItemGroupMax), + "passed": zod.boolean() +}).describe('Outcome of one hidden check group. It never contains the checks themselves.')).min(assessmentQualifiedResultOnePracticesItemVerdictGroupsMin).max(assessmentQualifiedResultOnePracticesItemVerdictGroupsMax) +}).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.') +}).describe('Verdict of one practice of the attempt.')).max(assessmentQualifiedResultOnePracticesMax).describe('Verdicts of the practices that have one, main first.'), + "gaps": zod.array(zod.object({ + "domain": zod.string().min(1).max(assessmentQualifiedResultOneGapsItemDomainMax).regex(assessmentQualifiedResultOneGapsItemDomainRegExp).describe('Stable domain code of the bank blueprint.'), + "title": zod.string().min(1).max(assessmentQualifiedResultOneGapsItemTitleMax).describe('Display name in Russian. Plain text.') +}).describe('Domain of the specialization where the evidence was weak.')).max(assessmentQualifiedResultOneGapsMax).describe('Domains with weak evidence; empty when none were found or the method finds none.'), + "durations": zod.object({ + "items_seconds": zod.int().min(assessmentQualifiedResultOneDurationsItemsSecondsMin), + "practice_seconds": zod.int().min(assessmentQualifiedResultOneDurationsPracticeSecondsMin).nullable().describe('Time on all practices with a verdict, or null when no practice has one.') +}).describe('Working time recorded by the server. It is a separate label: it never enters the ability estimate or the grade decision.'), + "next_steps": zod.array(zod.object({ + "action": zod.enum(['retake_same_grade', 'take_lower_grade', 'accept_lower_grade', 'take_higher_grade']).describe('Step that the candidate may take next.\n\n- retake_same_grade: test the same grade again from `available_at`.\n- take_lower_grade: test the lower `grade`. After a failure, including the first test, it is allowed at once, outside the same-grade retry interval.\n- accept_lower_grade: accept the lower `grade` on the evidence of this attempt, when the data are sufficient (the command is planned).\n- take_higher_grade: test the higher `grade` from `available_at`. A first confirmation is not a promotion, so after it `available_at` is null; after a promotion the next one waits for the promotion interval of the policy.'), + "grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'), + "available_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('First time the step is allowed, or null when it is allowed now.') +}).describe('Step that the server allows after this result, computed when it was decided.')).max(assessmentQualifiedResultOneNextStepsMax), + "decided_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.') +}).describe('Immutable result of a real assessment, visible only to its candidate. It records the method, versions, decision, uncertainty, and limitations. A corrective result also carries root_attempt_id and chain_deadline from the same chain. Later policy, bank, or algorithm versions never change it. It never contains answers, per-item correctness, keys, seeds, hidden checks, or anti-cheat signals. Fields the method does not compute are null, never zero.').and(zod.object({ + "kind": zod.enum(['root']), + "root_attempt_id": zod.null(), + "chain_deadline": zod.null() +})).and(zod.object({ + "kind": zod.enum(['root']) +})).describe('Result of a real assessment that is not a corrective attempt. The correction-chain fields are explicitly null.') + +export type AssessmentQualifiedResult = zod.input; +export type AssessmentQualifiedResultOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentRealMode.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentRealMode.zod.ts new file mode 100644 index 0000000..66cde06 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentRealMode.zod.ts @@ -0,0 +1,12 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const AssessmentRealMode = zod.enum(['demo_basic', 'adaptive']).describe('Server-selected mode available to a real category assessment.') + +export type AssessmentRealMode = zod.input; +export type AssessmentRealModeOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentRealResultCommon.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentRealResultCommon.zod.ts new file mode 100644 index 0000000..7a65ef7 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/assessmentRealResultCommon.zod.ts @@ -0,0 +1,120 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + + +export const assessmentRealResultCommonVersionsBankVersionMax = 64; + + +export const assessmentRealResultCommonVersionsBankVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$'); +export const assessmentRealResultCommonVersionsAlgorithmVersionMax = 64; + + +export const assessmentRealResultCommonVersionsAlgorithmVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$'); +export const assessmentRealResultCommonLimitationsMax = 10; + +export const assessmentRealResultCommonUncertaintyOneStandardErrorMin = 0; + +export const assessmentRealResultCommonUncertaintyOnePGradeMin = 0; +export const assessmentRealResultCommonUncertaintyOnePGradeMax = 1; + +export const assessmentRealResultCommonBasicScoreOnePointsMin = 0; + + + +export const assessmentRealResultCommonPracticesItemVerdictScoreMin = 0; +export const assessmentRealResultCommonPracticesItemVerdictScoreMax = 3; + +export const assessmentRealResultCommonPracticesItemVerdictMaxScoreMin = 3; +export const assessmentRealResultCommonPracticesItemVerdictMaxScoreMax = 3; + +export const assessmentRealResultCommonPracticesItemVerdictGroupsItemGroupMax = 3; + +export const assessmentRealResultCommonPracticesItemVerdictGroupsMin = 3; +export const assessmentRealResultCommonPracticesItemVerdictGroupsMax = 3; + +export const assessmentRealResultCommonPracticesMax = 5; + +export const assessmentRealResultCommonGapsItemDomainMax = 64; + + +export const assessmentRealResultCommonGapsItemDomainRegExp = new RegExp('^[a-z0-9_]+$'); +export const assessmentRealResultCommonGapsItemTitleMax = 200; + +export const assessmentRealResultCommonGapsMax = 20; + +export const assessmentRealResultCommonDurationsItemsSecondsMin = 0; + +export const assessmentRealResultCommonDurationsPracticeSecondsMin = 0; + +export const assessmentRealResultCommonNextStepsMax = 5; + + +export const AssessmentRealResultCommon = zod.object({ + "attempt_id": zod.uuid(), + "specialization": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'), + "target_grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'), + "root_attempt_id": zod.union([zod.uuid(),zod.null()]).exactOptional().describe('Root attempt of a corrective check, or null when this is not a corrective result. The corrective attempt keeps this link.'), + "chain_deadline": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).exactOptional().describe('Immutable deadline shared by a corrective chain, or null when this result is not from a corrective check.'), + "task_language": zod.union([zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.'),zod.null()]), + "kind": zod.enum(['root', 'corrective']), + "mode": zod.enum(['demo_basic', 'adaptive']), + "versions": zod.object({ + "policy_version": zod.int().min(1).describe('Number of the `product` policy version whose assessment rules apply: thresholds, stop rules, item limits, time and session limits, and retry intervals.'), + "bank_version": zod.string().min(1).max(assessmentRealResultCommonVersionsBankVersionMax).regex(assessmentRealResultCommonVersionsBankVersionRegExp).describe('Opaque identifier of a published version, for example `backend-demo.2026-10.1`. Clients show it as text and never parse it.'), + "algorithm_version": zod.string().min(1).max(assessmentRealResultCommonVersionsAlgorithmVersionMax).regex(assessmentRealResultCommonVersionsAlgorithmVersionRegExp).describe('Opaque identifier of a published version, for example `backend-demo.2026-10.1`. Clients show it as text and never parse it.') +}).describe('Versions fixed when the attempt was created. They never change during the attempt, and a result is always reproduced from the stored answers with these versions; a later policy, bank, or algorithm version does not rewrite it.'), + "outcome": zod.enum(['confirmed', 'not_confirmed', 'not_determined']).describe('Grade decision of the attempt.\n\n- confirmed: the target grade is confirmed by the rule of the recorded policy version.\n- not_confirmed: the evidence is below the rule, including an adaptive attempt whose probability stayed below confirmation after the additional practice, or whose additional practice was declined or not submitted in time. The previously confirmed grade, if any, stays in force.\n- not_determined: the attempt gives no decision; `not_determined_reason` says why. The previously confirmed grade stays in force.\n\nA failed, expired, or flagged attempt never lowers a confirmed grade.'), + "not_determined_reason": zod.union([zod.enum(['expired', 'practice_incomplete', 'insufficient_bank', 'sandbox_unavailable']).describe('Why an attempt gives no decision. One root quota slot is reserved when a real root attempt starts; corrective checks in its chain do not reserve another slot.\n\n- expired: the time or session limit passed before the candidate finished the item part. Retry timing follows the recorded policy; a correction uses the existing root slot and does not reset the chain deadline or 30/90-day timers.\n- practice_incomplete: the item part was done, but the candidate did not submit the main practice before the limit. Retry timing follows the recorded policy; a correction uses the existing root slot and does not reset the chain deadline or 30/90-day timers.\n- insufficient_bank: the bank could not supply required coverage. A preflight refusal creates no attempt or root slot; a bank failure in an existing chain does not create a free new chain or another root slot.\n- sandbox_unavailable: the latest submission of a required or additional practice ended `failed` because of the sandbox infrastructure, and the limit passed before a verdict. It is a platform fault and does not create a new root slot or a free chain.'),zod.null()]).describe('The reason when `outcome` is `not_determined`, otherwise null.'), + "confirmed_grade": zod.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Grade that this attempt confirmed, the target grade, or null when it confirmed none. Together with the specialization it forms the category.'), + "previous_confirmed_grade": zod.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Confirmed grade of the specialization before this attempt, or null. When the attempt confirmed nothing, this grade stays in force.'), + "strength": zod.union([zod.enum(['high', 'medium']).describe('Strength of an adaptive confirmation: `high` or `medium`, by the probability bands of the recorded policy version.'),zod.null()]).describe('Strength of an adaptive confirmation, otherwise null.'), + "calibration_status": zod.enum(['uncalibrated', 'calibrated']).describe('Whether the thresholds of the recorded policy version are empirically calibrated. `uncalibrated` results are provisional: their thresholds come from expert judgement, and their probabilities are not claimed to be calibrated.'), + "limitations": zod.array(zod.enum(['uncalibrated_thresholds', 'demo_bank', 'practice_not_included', 'unproctored']).describe('Known limitation of the method behind a real-assessment result, shown with the result.\n\n- uncalibrated_thresholds: the thresholds are not yet validated on a pilot.\n- demo_bank: the result comes from the small reviewed demo bank.\n- practice_not_included: the attempt had no code practice because the sandbox was not enabled.\n- unproctored: the attempt was taken online without supervision.\nAdding a value is a contract change.')).max(assessmentRealResultCommonLimitationsMax), + "uncertainty": zod.union([zod.object({ + "theta": zod.number(), + "standard_error": zod.number().min(assessmentRealResultCommonUncertaintyOneStandardErrorMin), + "interval_95": zod.object({ + "low": zod.number(), + "high": zod.number() +}).describe('Interval on the ability scale.'), + "p_grade": zod.number().min(assessmentRealResultCommonUncertaintyOnePGradeMin).max(assessmentRealResultCommonUncertaintyOnePGradeMax).describe('Probability of reaching the threshold of the target grade.') +}).describe('Ability estimate of an adaptive attempt and its uncertainty: the EAP estimate on the specialization scale, its standard error, the 95% interval, and the probability of reaching the target grade threshold. The interval is reported but is not a separate stop condition.'),zod.null()]).describe('Ability estimate and uncertainty of an adaptive attempt with a decision; null for demo_basic, which computes none, and for an attempt without a decision.'), + "basic_score": zod.union([zod.object({ + "points": zod.int().min(assessmentRealResultCommonBasicScoreOnePointsMin), + "max_points": zod.int().min(1), + "pass_points": zod.int().min(1) +}).describe('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.'),zod.null()]).describe('Raw score of a demo_basic attempt with a decision, otherwise null.'), + "practices": zod.array(zod.object({ + "kind": zod.enum(['main', 'additional']).describe('Role of a practice in the attempt.\n\n- main: the practice that every attempt with practice requires before a decision.\n- additional: adaptive only; offered by finalize when the probability of reaching the grade is in the band below confirmation. It continues the same attempt and spends no new attempt.\n\nAdding a value is a contract change.'), + "verdict": zod.object({ + "score": zod.int().min(assessmentRealResultCommonPracticesItemVerdictScoreMin).max(assessmentRealResultCommonPracticesItemVerdictScoreMax), + "max_score": zod.int().min(assessmentRealResultCommonPracticesItemVerdictMaxScoreMin).max(assessmentRealResultCommonPracticesItemVerdictMaxScoreMax), + "groups": zod.array(zod.object({ + "group": zod.int().min(1).max(assessmentRealResultCommonPracticesItemVerdictGroupsItemGroupMax), + "passed": zod.boolean() +}).describe('Outcome of one hidden check group. It never contains the checks themselves.')).min(assessmentRealResultCommonPracticesItemVerdictGroupsMin).max(assessmentRealResultCommonPracticesItemVerdictGroupsMax) +}).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.') +}).describe('Verdict of one practice of the attempt.')).max(assessmentRealResultCommonPracticesMax).describe('Verdicts of the practices that have one, main first.'), + "gaps": zod.array(zod.object({ + "domain": zod.string().min(1).max(assessmentRealResultCommonGapsItemDomainMax).regex(assessmentRealResultCommonGapsItemDomainRegExp).describe('Stable domain code of the bank blueprint.'), + "title": zod.string().min(1).max(assessmentRealResultCommonGapsItemTitleMax).describe('Display name in Russian. Plain text.') +}).describe('Domain of the specialization where the evidence was weak.')).max(assessmentRealResultCommonGapsMax).describe('Domains with weak evidence; empty when none were found or the method finds none.'), + "durations": zod.object({ + "items_seconds": zod.int().min(assessmentRealResultCommonDurationsItemsSecondsMin), + "practice_seconds": zod.int().min(assessmentRealResultCommonDurationsPracticeSecondsMin).nullable().describe('Time on all practices with a verdict, or null when no practice has one.') +}).describe('Working time recorded by the server. It is a separate label: it never enters the ability estimate or the grade decision.'), + "next_steps": zod.array(zod.object({ + "action": zod.enum(['retake_same_grade', 'take_lower_grade', 'accept_lower_grade', 'take_higher_grade']).describe('Step that the candidate may take next.\n\n- retake_same_grade: test the same grade again from `available_at`.\n- take_lower_grade: test the lower `grade`. After a failure, including the first test, it is allowed at once, outside the same-grade retry interval.\n- accept_lower_grade: accept the lower `grade` on the evidence of this attempt, when the data are sufficient (the command is planned).\n- take_higher_grade: test the higher `grade` from `available_at`. A first confirmation is not a promotion, so after it `available_at` is null; after a promotion the next one waits for the promotion interval of the policy.'), + "grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'), + "available_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('First time the step is allowed, or null when it is allowed now.') +}).describe('Step that the server allows after this result, computed when it was decided.')).max(assessmentRealResultCommonNextStepsMax), + "decided_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.') +}).describe('Immutable result of a real assessment, visible only to its candidate. It records the method, versions, decision, uncertainty, and limitations. A corrective result also carries root_attempt_id and chain_deadline from the same chain. Later policy, bank, or algorithm versions never change it. It never contains answers, per-item correctness, keys, seeds, hidden checks, or anti-cheat signals. Fields the method does not compute are null, never zero.') + +export type AssessmentRealResultCommon = zod.input; +export type AssessmentRealResultCommonOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentResult.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentResult.zod.ts index 814f27f..0e27da8 100644 --- a/frontend/src/shared/api/schemas/assessment/assessmentResult.zod.ts +++ b/frontend/src/shared/api/schemas/assessment/assessmentResult.zod.ts @@ -7,111 +7,320 @@ import * as zod from 'zod'; -export const assessmentResultVersionsBankVersionMax = 64; +export const assessmentResultOneOneVersionsBankVersionMax = 64; -export const assessmentResultVersionsBankVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$'); -export const assessmentResultVersionsAlgorithmVersionMax = 64; +export const assessmentResultOneOneVersionsBankVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$'); +export const assessmentResultOneOneVersionsAlgorithmVersionMax = 64; -export const assessmentResultVersionsAlgorithmVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$'); -export const assessmentResultLimitationsMax = 10; +export const assessmentResultOneOneVersionsAlgorithmVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$'); +export const assessmentResultOneOneLimitationsMax = 10; -export const assessmentResultUncertaintyOneStandardErrorMin = 0; +export const assessmentResultOneOneUncertaintyOneStandardErrorMin = 0; -export const assessmentResultUncertaintyOnePGradeMin = 0; -export const assessmentResultUncertaintyOnePGradeMax = 1; +export const assessmentResultOneOneUncertaintyOnePGradeMin = 0; +export const assessmentResultOneOneUncertaintyOnePGradeMax = 1; -export const assessmentResultBasicScoreOnePointsMin = 0; +export const assessmentResultOneOneBasicScoreOnePointsMin = 0; -export const assessmentResultPracticesItemVerdictScoreMin = 0; -export const assessmentResultPracticesItemVerdictScoreMax = 3; +export const assessmentResultOneOnePracticesItemVerdictScoreMin = 0; +export const assessmentResultOneOnePracticesItemVerdictScoreMax = 3; -export const assessmentResultPracticesItemVerdictMaxScoreMin = 3; -export const assessmentResultPracticesItemVerdictMaxScoreMax = 3; +export const assessmentResultOneOnePracticesItemVerdictMaxScoreMin = 3; +export const assessmentResultOneOnePracticesItemVerdictMaxScoreMax = 3; -export const assessmentResultPracticesItemVerdictGroupsItemGroupMax = 3; +export const assessmentResultOneOnePracticesItemVerdictGroupsItemGroupMax = 3; -export const assessmentResultPracticesItemVerdictGroupsMin = 3; -export const assessmentResultPracticesItemVerdictGroupsMax = 3; +export const assessmentResultOneOnePracticesItemVerdictGroupsMin = 3; +export const assessmentResultOneOnePracticesItemVerdictGroupsMax = 3; -export const assessmentResultPracticesMax = 5; +export const assessmentResultOneOnePracticesMax = 5; -export const assessmentResultGapsItemDomainMax = 64; +export const assessmentResultOneOneGapsItemDomainMax = 64; -export const assessmentResultGapsItemDomainRegExp = new RegExp('^[a-z0-9_]+$'); -export const assessmentResultGapsItemTitleMax = 200; +export const assessmentResultOneOneGapsItemDomainRegExp = new RegExp('^[a-z0-9_]+$'); +export const assessmentResultOneOneGapsItemTitleMax = 200; -export const assessmentResultGapsMax = 20; +export const assessmentResultOneOneGapsMax = 20; -export const assessmentResultDurationsItemsSecondsMin = 0; +export const assessmentResultOneOneDurationsItemsSecondsMin = 0; -export const assessmentResultDurationsPracticeSecondsMin = 0; +export const assessmentResultOneOneDurationsPracticeSecondsMin = 0; -export const assessmentResultNextStepsMax = 5; +export const assessmentResultOneOneNextStepsMax = 5; -export const AssessmentResult = zod.object({ +export const assessmentResultTwoOneVersionsBankVersionMax = 64; + + +export const assessmentResultTwoOneVersionsBankVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$'); +export const assessmentResultTwoOneVersionsAlgorithmVersionMax = 64; + + +export const assessmentResultTwoOneVersionsAlgorithmVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$'); +export const assessmentResultTwoOneLimitationsMax = 10; + +export const assessmentResultTwoOneUncertaintyOneStandardErrorMin = 0; + +export const assessmentResultTwoOneUncertaintyOnePGradeMin = 0; +export const assessmentResultTwoOneUncertaintyOnePGradeMax = 1; + +export const assessmentResultTwoOneBasicScoreOnePointsMin = 0; + + + +export const assessmentResultTwoOnePracticesItemVerdictScoreMin = 0; +export const assessmentResultTwoOnePracticesItemVerdictScoreMax = 3; + +export const assessmentResultTwoOnePracticesItemVerdictMaxScoreMin = 3; +export const assessmentResultTwoOnePracticesItemVerdictMaxScoreMax = 3; + +export const assessmentResultTwoOnePracticesItemVerdictGroupsItemGroupMax = 3; + +export const assessmentResultTwoOnePracticesItemVerdictGroupsMin = 3; +export const assessmentResultTwoOnePracticesItemVerdictGroupsMax = 3; + +export const assessmentResultTwoOnePracticesMax = 5; + +export const assessmentResultTwoOneGapsItemDomainMax = 64; + + +export const assessmentResultTwoOneGapsItemDomainRegExp = new RegExp('^[a-z0-9_]+$'); +export const assessmentResultTwoOneGapsItemTitleMax = 200; + +export const assessmentResultTwoOneGapsMax = 20; + +export const assessmentResultTwoOneDurationsItemsSecondsMin = 0; + +export const assessmentResultTwoOneDurationsPracticeSecondsMin = 0; + +export const assessmentResultTwoOneNextStepsMax = 5; + + +export const assessmentResultThreeVersionsBankVersionMax = 64; + + +export const assessmentResultThreeVersionsBankVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$'); +export const assessmentResultThreeVersionsAlgorithmVersionMax = 64; + + +export const assessmentResultThreeVersionsAlgorithmVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$'); +export const assessmentResultThreeLimitationsMax = 1; + +export const assessmentResultThreePracticesItemVerdictScoreMin = 0; +export const assessmentResultThreePracticesItemVerdictScoreMax = 3; + +export const assessmentResultThreePracticesItemVerdictMaxScoreMin = 3; +export const assessmentResultThreePracticesItemVerdictMaxScoreMax = 3; + +export const assessmentResultThreePracticesItemVerdictGroupsItemGroupMax = 3; + +export const assessmentResultThreePracticesItemVerdictGroupsMin = 3; +export const assessmentResultThreePracticesItemVerdictGroupsMax = 3; + +export const assessmentResultThreePracticesMax = 0; + +export const assessmentResultThreeGapsItemDomainMax = 64; + + +export const assessmentResultThreeGapsItemDomainRegExp = new RegExp('^[a-z0-9_]+$'); +export const assessmentResultThreeGapsItemTitleMax = 200; + +export const assessmentResultThreeGapsMax = 0; + +export const assessmentResultThreeDurationsItemsSecondsMin = 0; + +export const assessmentResultThreeDurationsPracticeSecondsMin = 0; + +export const assessmentResultThreeNextStepsMax = 0; + +export const assessmentResultThreeSummaryMax = 2000; + + +export const AssessmentResult = zod.union([zod.object({ "attempt_id": zod.uuid(), "specialization": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'), "target_grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'), + "root_attempt_id": zod.union([zod.uuid(),zod.null()]).describe('Root attempt of a corrective check, or null when this is not a corrective result. The corrective attempt keeps this link.'), + "chain_deadline": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('Immutable deadline shared by a corrective chain, or null when this result is not from a corrective check.'), "task_language": zod.union([zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.'),zod.null()]), - "mode": zod.enum(['demo_basic', 'adaptive']).describe('Measurement method of an attempt. The server selects it from the published task bank of the category; the client never chooses it.\n\n- demo_basic: a fixed form of reviewed demo items scored by their keys against the pass mark of the versioned basic grading policy. It computes no ability estimate, standard error, or probability, so every uncertainty field of its result is null, its thresholds are uncalibrated, and its decision is binary: it never offers an additional practice.\n- adaptive: the adaptive test on task families with an ability estimate, its standard error, and the probability of reaching the grade threshold, as the versioned assessment policy defines them. A probability in the band below confirmation offers one additional practice in the same attempt.\n\nAdding a value is a contract change.'), + "kind": zod.enum(['root', 'corrective']), + "mode": zod.enum(['demo_basic', 'adaptive']), "versions": zod.object({ "policy_version": zod.int().min(1).describe('Number of the `product` policy version whose assessment rules apply: thresholds, stop rules, item limits, time and session limits, and retry intervals.'), - "bank_version": zod.string().min(1).max(assessmentResultVersionsBankVersionMax).regex(assessmentResultVersionsBankVersionRegExp).describe('Opaque identifier of a published version, for example `backend-demo.2026-10.1`. Clients show it as text and never parse it.'), - "algorithm_version": zod.string().min(1).max(assessmentResultVersionsAlgorithmVersionMax).regex(assessmentResultVersionsAlgorithmVersionRegExp).describe('Opaque identifier of a published version, for example `backend-demo.2026-10.1`. Clients show it as text and never parse it.') + "bank_version": zod.string().min(1).max(assessmentResultOneOneVersionsBankVersionMax).regex(assessmentResultOneOneVersionsBankVersionRegExp).describe('Opaque identifier of a published version, for example `backend-demo.2026-10.1`. Clients show it as text and never parse it.'), + "algorithm_version": zod.string().min(1).max(assessmentResultOneOneVersionsAlgorithmVersionMax).regex(assessmentResultOneOneVersionsAlgorithmVersionRegExp).describe('Opaque identifier of a published version, for example `backend-demo.2026-10.1`. Clients show it as text and never parse it.') }).describe('Versions fixed when the attempt was created. They never change during the attempt, and a result is always reproduced from the stored answers with these versions; a later policy, bank, or algorithm version does not rewrite it.'), "outcome": zod.enum(['confirmed', 'not_confirmed', 'not_determined']).describe('Grade decision of the attempt.\n\n- confirmed: the target grade is confirmed by the rule of the recorded policy version.\n- not_confirmed: the evidence is below the rule, including an adaptive attempt whose probability stayed below confirmation after the additional practice, or whose additional practice was declined or not submitted in time. The previously confirmed grade, if any, stays in force.\n- not_determined: the attempt gives no decision; `not_determined_reason` says why. The previously confirmed grade stays in force.\n\nA failed, expired, or flagged attempt never lowers a confirmed grade.'), - "not_determined_reason": zod.union([zod.enum(['expired', 'practice_incomplete', 'insufficient_bank', 'sandbox_unavailable']).describe('Why an attempt gives no decision, and whether it counts against the retry rules.\n\n- expired: the time or session limit passed before the candidate finished the item part. It is the candidate\'s attempt: it counts toward the attempt limit and starts the same-grade retry interval.\n- practice_incomplete: the item part was done, but the candidate did not submit the main practice before the limit. It counts like `expired`.\n- insufficient_bank: the bank could not supply the required coverage within the limit. It is a platform limitation: it never counts toward the attempt limit and starts no retry interval.\n- sandbox_unavailable: the latest submission of a required or additional practice ended `failed` because of the sandbox infrastructure, and the limit passed before a verdict. It is a platform fault: it never counts toward the attempt limit and starts no retry interval.'),zod.null()]).describe('The reason when `outcome` is `not_determined`, otherwise null.'), + "not_determined_reason": zod.union([zod.enum(['expired', 'practice_incomplete', 'insufficient_bank', 'sandbox_unavailable']).describe('Why an attempt gives no decision. One root quota slot is reserved when a real root attempt starts; corrective checks in its chain do not reserve another slot.\n\n- expired: the time or session limit passed before the candidate finished the item part. Retry timing follows the recorded policy; a correction uses the existing root slot and does not reset the chain deadline or 30/90-day timers.\n- practice_incomplete: the item part was done, but the candidate did not submit the main practice before the limit. Retry timing follows the recorded policy; a correction uses the existing root slot and does not reset the chain deadline or 30/90-day timers.\n- insufficient_bank: the bank could not supply required coverage. A preflight refusal creates no attempt or root slot; a bank failure in an existing chain does not create a free new chain or another root slot.\n- sandbox_unavailable: the latest submission of a required or additional practice ended `failed` because of the sandbox infrastructure, and the limit passed before a verdict. It is a platform fault and does not create a new root slot or a free chain.'),zod.null()]).describe('The reason when `outcome` is `not_determined`, otherwise null.'), "confirmed_grade": zod.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Grade that this attempt confirmed, the target grade, or null when it confirmed none. Together with the specialization it forms the category.'), "previous_confirmed_grade": zod.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Confirmed grade of the specialization before this attempt, or null. When the attempt confirmed nothing, this grade stays in force.'), "strength": zod.union([zod.enum(['high', 'medium']).describe('Strength of an adaptive confirmation: `high` or `medium`, by the probability bands of the recorded policy version.'),zod.null()]).describe('Strength of an adaptive confirmation, otherwise null.'), "calibration_status": zod.enum(['uncalibrated', 'calibrated']).describe('Whether the thresholds of the recorded policy version are empirically calibrated. `uncalibrated` results are provisional: their thresholds come from expert judgement, and their probabilities are not claimed to be calibrated.'), - "limitations": zod.array(zod.enum(['uncalibrated_thresholds', 'demo_bank', 'practice_not_included', 'unproctored']).describe('Known limitation of the method behind a result, shown with the result.\n\n- uncalibrated_thresholds: the thresholds are not yet validated on a pilot.\n- demo_bank: the result comes from the small reviewed demo bank.\n- practice_not_included: the attempt had no code practice because the sandbox was not enabled.\n- unproctored: the attempt was taken online without supervision.\n\nAdding a value is a contract change.')).max(assessmentResultLimitationsMax), + "limitations": zod.array(zod.enum(['uncalibrated_thresholds', 'demo_bank', 'practice_not_included', 'unproctored']).describe('Known limitation of the method behind a real-assessment result, shown with the result.\n\n- uncalibrated_thresholds: the thresholds are not yet validated on a pilot.\n- demo_bank: the result comes from the small reviewed demo bank.\n- practice_not_included: the attempt had no code practice because the sandbox was not enabled.\n- unproctored: the attempt was taken online without supervision.\nAdding a value is a contract change.')).max(assessmentResultOneOneLimitationsMax), "uncertainty": zod.union([zod.object({ "theta": zod.number(), - "standard_error": zod.number().min(assessmentResultUncertaintyOneStandardErrorMin), + "standard_error": zod.number().min(assessmentResultOneOneUncertaintyOneStandardErrorMin), "interval_95": zod.object({ "low": zod.number(), "high": zod.number() }).describe('Interval on the ability scale.'), - "p_grade": zod.number().min(assessmentResultUncertaintyOnePGradeMin).max(assessmentResultUncertaintyOnePGradeMax).describe('Probability of reaching the threshold of the target grade.') + "p_grade": zod.number().min(assessmentResultOneOneUncertaintyOnePGradeMin).max(assessmentResultOneOneUncertaintyOnePGradeMax).describe('Probability of reaching the threshold of the target grade.') }).describe('Ability estimate of an adaptive attempt and its uncertainty: the EAP estimate on the specialization scale, its standard error, the 95% interval, and the probability of reaching the target grade threshold. The interval is reported but is not a separate stop condition.'),zod.null()]).describe('Ability estimate and uncertainty of an adaptive attempt with a decision; null for demo_basic, which computes none, and for an attempt without a decision.'), "basic_score": zod.union([zod.object({ - "points": zod.int().min(assessmentResultBasicScoreOnePointsMin), + "points": zod.int().min(assessmentResultOneOneBasicScoreOnePointsMin), "max_points": zod.int().min(1), "pass_points": zod.int().min(1) }).describe('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.'),zod.null()]).describe('Raw score of a demo_basic attempt with a decision, otherwise null.'), "practices": zod.array(zod.object({ "kind": zod.enum(['main', 'additional']).describe('Role of a practice in the attempt.\n\n- main: the practice that every attempt with practice requires before a decision.\n- additional: adaptive only; offered by finalize when the probability of reaching the grade is in the band below confirmation. It continues the same attempt and spends no new attempt.\n\nAdding a value is a contract change.'), "verdict": zod.object({ - "score": zod.int().min(assessmentResultPracticesItemVerdictScoreMin).max(assessmentResultPracticesItemVerdictScoreMax), - "max_score": zod.int().min(assessmentResultPracticesItemVerdictMaxScoreMin).max(assessmentResultPracticesItemVerdictMaxScoreMax), + "score": zod.int().min(assessmentResultOneOnePracticesItemVerdictScoreMin).max(assessmentResultOneOnePracticesItemVerdictScoreMax), + "max_score": zod.int().min(assessmentResultOneOnePracticesItemVerdictMaxScoreMin).max(assessmentResultOneOnePracticesItemVerdictMaxScoreMax), "groups": zod.array(zod.object({ - "group": zod.int().min(1).max(assessmentResultPracticesItemVerdictGroupsItemGroupMax), + "group": zod.int().min(1).max(assessmentResultOneOnePracticesItemVerdictGroupsItemGroupMax), "passed": zod.boolean() -}).describe('Outcome of one hidden check group. It never contains the checks themselves.')).min(assessmentResultPracticesItemVerdictGroupsMin).max(assessmentResultPracticesItemVerdictGroupsMax) +}).describe('Outcome of one hidden check group. It never contains the checks themselves.')).min(assessmentResultOneOnePracticesItemVerdictGroupsMin).max(assessmentResultOneOnePracticesItemVerdictGroupsMax) }).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.') -}).describe('Verdict of one practice of the attempt.')).max(assessmentResultPracticesMax).describe('Verdicts of the practices that have one, main first.'), +}).describe('Verdict of one practice of the attempt.')).max(assessmentResultOneOnePracticesMax).describe('Verdicts of the practices that have one, main first.'), "gaps": zod.array(zod.object({ - "domain": zod.string().min(1).max(assessmentResultGapsItemDomainMax).regex(assessmentResultGapsItemDomainRegExp).describe('Stable domain code of the bank blueprint.'), - "title": zod.string().min(1).max(assessmentResultGapsItemTitleMax).describe('Display name in Russian. Plain text.') -}).describe('Domain of the specialization where the evidence was weak.')).max(assessmentResultGapsMax).describe('Domains with weak evidence; empty when none were found or the method finds none.'), + "domain": zod.string().min(1).max(assessmentResultOneOneGapsItemDomainMax).regex(assessmentResultOneOneGapsItemDomainRegExp).describe('Stable domain code of the bank blueprint.'), + "title": zod.string().min(1).max(assessmentResultOneOneGapsItemTitleMax).describe('Display name in Russian. Plain text.') +}).describe('Domain of the specialization where the evidence was weak.')).max(assessmentResultOneOneGapsMax).describe('Domains with weak evidence; empty when none were found or the method finds none.'), "durations": zod.object({ - "items_seconds": zod.int().min(assessmentResultDurationsItemsSecondsMin), - "practice_seconds": zod.int().min(assessmentResultDurationsPracticeSecondsMin).nullable().describe('Time on all practices with a verdict, or null when no practice has one.') + "items_seconds": zod.int().min(assessmentResultOneOneDurationsItemsSecondsMin), + "practice_seconds": zod.int().min(assessmentResultOneOneDurationsPracticeSecondsMin).nullable().describe('Time on all practices with a verdict, or null when no practice has one.') }).describe('Working time recorded by the server. It is a separate label: it never enters the ability estimate or the grade decision.'), "next_steps": zod.array(zod.object({ "action": zod.enum(['retake_same_grade', 'take_lower_grade', 'accept_lower_grade', 'take_higher_grade']).describe('Step that the candidate may take next.\n\n- retake_same_grade: test the same grade again from `available_at`.\n- take_lower_grade: test the lower `grade`. After a failure, including the first test, it is allowed at once, outside the same-grade retry interval.\n- accept_lower_grade: accept the lower `grade` on the evidence of this attempt, when the data are sufficient (the command is planned).\n- take_higher_grade: test the higher `grade` from `available_at`. A first confirmation is not a promotion, so after it `available_at` is null; after a promotion the next one waits for the promotion interval of the policy.'), "grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'), "available_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('First time the step is allowed, or null when it is allowed now.') -}).describe('Step that the server allows after this result, computed when it was decided.')).max(assessmentResultNextStepsMax), +}).describe('Step that the server allows after this result, computed when it was decided.')).max(assessmentResultOneOneNextStepsMax), "decided_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.') -}).describe('Immutable result of a terminal attempt, visible only to its candidate. It records the method, the versions, the decision, its uncertainty, and its limitations; a later policy, bank, or algorithm version never changes it. It never contains answers, per-item correctness, answer keys, seeds, hidden checks, or anti-cheat signals. Fields that the method does not compute are null, never zero: demo_basic has null `uncertainty` and `strength`, and adaptive has null `basic_score`.') +}).describe('Immutable result of a real assessment, visible only to its candidate. It records the method, versions, decision, uncertainty, and limitations. A corrective result also carries root_attempt_id and chain_deadline from the same chain. Later policy, bank, or algorithm versions never change it. It never contains answers, per-item correctness, keys, seeds, hidden checks, or anti-cheat signals. Fields the method does not compute are null, never zero.').and(zod.object({ + "kind": zod.enum(['root']), + "root_attempt_id": zod.null(), + "chain_deadline": zod.null() +})).and(zod.object({ + "kind": zod.enum(['root']) +})).describe('Result of a real assessment that is not a corrective attempt. The correction-chain fields are explicitly null.'),zod.object({ + "attempt_id": zod.uuid(), + "specialization": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'), + "target_grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'), + "root_attempt_id": zod.union([zod.uuid(),zod.null()]).describe('Root attempt of a corrective check, or null when this is not a corrective result. The corrective attempt keeps this link.'), + "chain_deadline": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('Immutable deadline shared by a corrective chain, or null when this result is not from a corrective check.'), + "task_language": zod.union([zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.'),zod.null()]), + "kind": zod.enum(['root', 'corrective']), + "mode": zod.enum(['demo_basic', 'adaptive']), + "versions": zod.object({ + "policy_version": zod.int().min(1).describe('Number of the `product` policy version whose assessment rules apply: thresholds, stop rules, item limits, time and session limits, and retry intervals.'), + "bank_version": zod.string().min(1).max(assessmentResultTwoOneVersionsBankVersionMax).regex(assessmentResultTwoOneVersionsBankVersionRegExp).describe('Opaque identifier of a published version, for example `backend-demo.2026-10.1`. Clients show it as text and never parse it.'), + "algorithm_version": zod.string().min(1).max(assessmentResultTwoOneVersionsAlgorithmVersionMax).regex(assessmentResultTwoOneVersionsAlgorithmVersionRegExp).describe('Opaque identifier of a published version, for example `backend-demo.2026-10.1`. Clients show it as text and never parse it.') +}).describe('Versions fixed when the attempt was created. They never change during the attempt, and a result is always reproduced from the stored answers with these versions; a later policy, bank, or algorithm version does not rewrite it.'), + "outcome": zod.enum(['confirmed', 'not_confirmed', 'not_determined']).describe('Grade decision of the attempt.\n\n- confirmed: the target grade is confirmed by the rule of the recorded policy version.\n- not_confirmed: the evidence is below the rule, including an adaptive attempt whose probability stayed below confirmation after the additional practice, or whose additional practice was declined or not submitted in time. The previously confirmed grade, if any, stays in force.\n- not_determined: the attempt gives no decision; `not_determined_reason` says why. The previously confirmed grade stays in force.\n\nA failed, expired, or flagged attempt never lowers a confirmed grade.'), + "not_determined_reason": zod.union([zod.enum(['expired', 'practice_incomplete', 'insufficient_bank', 'sandbox_unavailable']).describe('Why an attempt gives no decision. One root quota slot is reserved when a real root attempt starts; corrective checks in its chain do not reserve another slot.\n\n- expired: the time or session limit passed before the candidate finished the item part. Retry timing follows the recorded policy; a correction uses the existing root slot and does not reset the chain deadline or 30/90-day timers.\n- practice_incomplete: the item part was done, but the candidate did not submit the main practice before the limit. Retry timing follows the recorded policy; a correction uses the existing root slot and does not reset the chain deadline or 30/90-day timers.\n- insufficient_bank: the bank could not supply required coverage. A preflight refusal creates no attempt or root slot; a bank failure in an existing chain does not create a free new chain or another root slot.\n- sandbox_unavailable: the latest submission of a required or additional practice ended `failed` because of the sandbox infrastructure, and the limit passed before a verdict. It is a platform fault and does not create a new root slot or a free chain.'),zod.null()]).describe('The reason when `outcome` is `not_determined`, otherwise null.'), + "confirmed_grade": zod.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Grade that this attempt confirmed, the target grade, or null when it confirmed none. Together with the specialization it forms the category.'), + "previous_confirmed_grade": zod.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Confirmed grade of the specialization before this attempt, or null. When the attempt confirmed nothing, this grade stays in force.'), + "strength": zod.union([zod.enum(['high', 'medium']).describe('Strength of an adaptive confirmation: `high` or `medium`, by the probability bands of the recorded policy version.'),zod.null()]).describe('Strength of an adaptive confirmation, otherwise null.'), + "calibration_status": zod.enum(['uncalibrated', 'calibrated']).describe('Whether the thresholds of the recorded policy version are empirically calibrated. `uncalibrated` results are provisional: their thresholds come from expert judgement, and their probabilities are not claimed to be calibrated.'), + "limitations": zod.array(zod.enum(['uncalibrated_thresholds', 'demo_bank', 'practice_not_included', 'unproctored']).describe('Known limitation of the method behind a real-assessment result, shown with the result.\n\n- uncalibrated_thresholds: the thresholds are not yet validated on a pilot.\n- demo_bank: the result comes from the small reviewed demo bank.\n- practice_not_included: the attempt had no code practice because the sandbox was not enabled.\n- unproctored: the attempt was taken online without supervision.\nAdding a value is a contract change.')).max(assessmentResultTwoOneLimitationsMax), + "uncertainty": zod.union([zod.object({ + "theta": zod.number(), + "standard_error": zod.number().min(assessmentResultTwoOneUncertaintyOneStandardErrorMin), + "interval_95": zod.object({ + "low": zod.number(), + "high": zod.number() +}).describe('Interval on the ability scale.'), + "p_grade": zod.number().min(assessmentResultTwoOneUncertaintyOnePGradeMin).max(assessmentResultTwoOneUncertaintyOnePGradeMax).describe('Probability of reaching the threshold of the target grade.') +}).describe('Ability estimate of an adaptive attempt and its uncertainty: the EAP estimate on the specialization scale, its standard error, the 95% interval, and the probability of reaching the target grade threshold. The interval is reported but is not a separate stop condition.'),zod.null()]).describe('Ability estimate and uncertainty of an adaptive attempt with a decision; null for demo_basic, which computes none, and for an attempt without a decision.'), + "basic_score": zod.union([zod.object({ + "points": zod.int().min(assessmentResultTwoOneBasicScoreOnePointsMin), + "max_points": zod.int().min(1), + "pass_points": zod.int().min(1) +}).describe('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.'),zod.null()]).describe('Raw score of a demo_basic attempt with a decision, otherwise null.'), + "practices": zod.array(zod.object({ + "kind": zod.enum(['main', 'additional']).describe('Role of a practice in the attempt.\n\n- main: the practice that every attempt with practice requires before a decision.\n- additional: adaptive only; offered by finalize when the probability of reaching the grade is in the band below confirmation. It continues the same attempt and spends no new attempt.\n\nAdding a value is a contract change.'), + "verdict": zod.object({ + "score": zod.int().min(assessmentResultTwoOnePracticesItemVerdictScoreMin).max(assessmentResultTwoOnePracticesItemVerdictScoreMax), + "max_score": zod.int().min(assessmentResultTwoOnePracticesItemVerdictMaxScoreMin).max(assessmentResultTwoOnePracticesItemVerdictMaxScoreMax), + "groups": zod.array(zod.object({ + "group": zod.int().min(1).max(assessmentResultTwoOnePracticesItemVerdictGroupsItemGroupMax), + "passed": zod.boolean() +}).describe('Outcome of one hidden check group. It never contains the checks themselves.')).min(assessmentResultTwoOnePracticesItemVerdictGroupsMin).max(assessmentResultTwoOnePracticesItemVerdictGroupsMax) +}).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.') +}).describe('Verdict of one practice of the attempt.')).max(assessmentResultTwoOnePracticesMax).describe('Verdicts of the practices that have one, main first.'), + "gaps": zod.array(zod.object({ + "domain": zod.string().min(1).max(assessmentResultTwoOneGapsItemDomainMax).regex(assessmentResultTwoOneGapsItemDomainRegExp).describe('Stable domain code of the bank blueprint.'), + "title": zod.string().min(1).max(assessmentResultTwoOneGapsItemTitleMax).describe('Display name in Russian. Plain text.') +}).describe('Domain of the specialization where the evidence was weak.')).max(assessmentResultTwoOneGapsMax).describe('Domains with weak evidence; empty when none were found or the method finds none.'), + "durations": zod.object({ + "items_seconds": zod.int().min(assessmentResultTwoOneDurationsItemsSecondsMin), + "practice_seconds": zod.int().min(assessmentResultTwoOneDurationsPracticeSecondsMin).nullable().describe('Time on all practices with a verdict, or null when no practice has one.') +}).describe('Working time recorded by the server. It is a separate label: it never enters the ability estimate or the grade decision.'), + "next_steps": zod.array(zod.object({ + "action": zod.enum(['retake_same_grade', 'take_lower_grade', 'accept_lower_grade', 'take_higher_grade']).describe('Step that the candidate may take next.\n\n- retake_same_grade: test the same grade again from `available_at`.\n- take_lower_grade: test the lower `grade`. After a failure, including the first test, it is allowed at once, outside the same-grade retry interval.\n- accept_lower_grade: accept the lower `grade` on the evidence of this attempt, when the data are sufficient (the command is planned).\n- take_higher_grade: test the higher `grade` from `available_at`. A first confirmation is not a promotion, so after it `available_at` is null; after a promotion the next one waits for the promotion interval of the policy.'), + "grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'), + "available_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('First time the step is allowed, or null when it is allowed now.') +}).describe('Step that the server allows after this result, computed when it was decided.')).max(assessmentResultTwoOneNextStepsMax), + "decided_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.') +}).describe('Immutable result of a real assessment, visible only to its candidate. It records the method, versions, decision, uncertainty, and limitations. A corrective result also carries root_attempt_id and chain_deadline from the same chain. Later policy, bank, or algorithm versions never change it. It never contains answers, per-item correctness, keys, seeds, hidden checks, or anti-cheat signals. Fields the method does not compute are null, never zero.').and(zod.object({ + "kind": zod.enum(['corrective']), + "root_attempt_id": zod.uuid(), + "chain_deadline": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.') +})).and(zod.object({ + "kind": zod.enum(['corrective']) +})).describe('Result of a corrective real assessment. Both chain fields are present and identify the same immutable correction chain.'),zod.object({ + "attempt_id": zod.uuid(), + "specialization": zod.null().describe('Express training does not assess a specialization.'), + "target_grade": zod.null().describe('Express training does not assess a target grade.'), + "task_language": zod.null(), + "kind": zod.enum(['demo_express']), + "mode": zod.enum(['demo_express']), + "versions": zod.object({ + "policy_version": zod.int().min(1).describe('Number of the `product` policy version whose assessment rules apply: thresholds, stop rules, item limits, time and session limits, and retry intervals.'), + "bank_version": zod.string().min(1).max(assessmentResultThreeVersionsBankVersionMax).regex(assessmentResultThreeVersionsBankVersionRegExp).describe('Opaque identifier of a published version, for example `backend-demo.2026-10.1`. Clients show it as text and never parse it.'), + "algorithm_version": zod.string().min(1).max(assessmentResultThreeVersionsAlgorithmVersionMax).regex(assessmentResultThreeVersionsAlgorithmVersionRegExp).describe('Opaque identifier of a published version, for example `backend-demo.2026-10.1`. Clients show it as text and never parse it.') +}).describe('Versions fixed when the attempt was created. They never change during the attempt, and a result is always reproduced from the stored answers with these versions; a later policy, bank, or algorithm version does not rewrite it.'), + "outcome": zod.enum(['demonstration']), + "not_determined_reason": zod.null(), + "confirmed_grade": zod.null().describe('Express training never confirms a grade.'), + "previous_confirmed_grade": zod.null(), + "strength": zod.null(), + "calibration_status": zod.enum(['uncalibrated']), + "limitations": zod.array(zod.enum(['demonstration_only'])).min(1).max(assessmentResultThreeLimitationsMax), + "uncertainty": zod.null().describe('Express training computes no ability estimate or percentile.'), + "basic_score": zod.null(), + "practices": zod.array(zod.object({ + "kind": zod.enum(['main', 'additional']).describe('Role of a practice in the attempt.\n\n- main: the practice that every attempt with practice requires before a decision.\n- additional: adaptive only; offered by finalize when the probability of reaching the grade is in the band below confirmation. It continues the same attempt and spends no new attempt.\n\nAdding a value is a contract change.'), + "verdict": zod.object({ + "score": zod.int().min(assessmentResultThreePracticesItemVerdictScoreMin).max(assessmentResultThreePracticesItemVerdictScoreMax), + "max_score": zod.int().min(assessmentResultThreePracticesItemVerdictMaxScoreMin).max(assessmentResultThreePracticesItemVerdictMaxScoreMax), + "groups": zod.array(zod.object({ + "group": zod.int().min(1).max(assessmentResultThreePracticesItemVerdictGroupsItemGroupMax), + "passed": zod.boolean() +}).describe('Outcome of one hidden check group. It never contains the checks themselves.')).min(assessmentResultThreePracticesItemVerdictGroupsMin).max(assessmentResultThreePracticesItemVerdictGroupsMax) +}).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.') +}).describe('Verdict of one practice of the attempt.')).max(assessmentResultThreePracticesMax), + "gaps": zod.array(zod.object({ + "domain": zod.string().min(1).max(assessmentResultThreeGapsItemDomainMax).regex(assessmentResultThreeGapsItemDomainRegExp).describe('Stable domain code of the bank blueprint.'), + "title": zod.string().min(1).max(assessmentResultThreeGapsItemTitleMax).describe('Display name in Russian. Plain text.') +}).describe('Domain of the specialization where the evidence was weak.')).max(assessmentResultThreeGapsMax), + "durations": zod.object({ + "items_seconds": zod.int().min(assessmentResultThreeDurationsItemsSecondsMin), + "practice_seconds": zod.int().min(assessmentResultThreeDurationsPracticeSecondsMin).nullable().describe('Time on all practices with a verdict, or null when no practice has one.') +}).describe('Working time recorded by the server. It is a separate label: it never enters the ability estimate or the grade decision.'), + "next_steps": zod.array(zod.object({ + "action": zod.enum(['retake_same_grade', 'take_lower_grade', 'accept_lower_grade', 'take_higher_grade']).describe('Step that the candidate may take next.\n\n- retake_same_grade: test the same grade again from `available_at`.\n- take_lower_grade: test the lower `grade`. After a failure, including the first test, it is allowed at once, outside the same-grade retry interval.\n- accept_lower_grade: accept the lower `grade` on the evidence of this attempt, when the data are sufficient (the command is planned).\n- take_higher_grade: test the higher `grade` from `available_at`. A first confirmation is not a promotion, so after it `available_at` is null; after a promotion the next one waits for the promotion interval of the policy.'), + "grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'), + "available_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('First time the step is allowed, or null when it is allowed now.') +}).describe('Step that the server allows after this result, computed when it was decided.')).max(assessmentResultThreeNextStepsMax), + "summary": zod.string().min(1).max(assessmentResultThreeSummaryMax).describe('Short educational feedback about this training run.'), + "decided_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.') +}).describe('Immutable educational result of a demo_express run. It includes a short summary but cannot report a category, percentile, uncertainty, grade, strength, or qualification evidence. The result belongs only to the training mode and does not consume a real-assessment quota.')]).describe('Immutable result of a terminal assessment attempt. The result shape distinguishes real grade decisions from demo_express training output.') export type AssessmentResult = zod.input; export type AssessmentResultOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentSessions.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentSessions.zod.ts index ac3b059..4c6c3e6 100644 --- a/frontend/src/shared/api/schemas/assessment/assessmentSessions.zod.ts +++ b/frontend/src/shared/api/schemas/assessment/assessmentSessions.zod.ts @@ -18,7 +18,7 @@ export const AssessmentSessions = zod.object({ "used": zod.int().min(1).max(assessmentSessionsUsedMax).describe('Sessions started so far, including the current one.'), "max": zod.int().min(1).max(assessmentSessionsMaxMax), "idle_timeout_seconds": zod.int().min(assessmentSessionsIdleTimeoutSecondsMin).max(assessmentSessionsIdleTimeoutSecondsMax).describe('Inactivity after which the current session ends.') -}).describe('Work sessions of the attempt, as the policy version limits them, for example two sessions within the time limit.\n\nA session starts with the creation of the attempt or, after the previous session ended, with the next GetMyAssessmentAttempt or command on the active attempt. It ends after `idle_timeout_seconds` without such a request. A request that would start a session beyond `max_sessions` starts none: the server moves the attempt to `expired` and answers with it (a read) or with 409 state_conflict (a command). Reading a terminal attempt or a result never starts a session.') +}).describe('Work sessions of the attempt, as the policy version limits them, for example two sessions within the time limit.\n\nSession 1 starts with attempt creation. After it ends due to `idle_timeout_seconds` of inactivity, the candidate explicitly starts or resumes work with StartMyAssessmentAttemptSession. GetMyAssessmentAttempt and GetMyAssessmentResult are read-only and never start a session. The session command checks the attempt deadline and `max_sessions`; when either limit has passed, it records the due terminal transition and returns the resulting attempt. Reads of terminal attempts do not change them.') export type AssessmentSessions = zod.input; export type AssessmentSessionsOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/assessmentSpecializationAvailability.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentSpecializationAvailability.zod.ts index c70bced..e06009b 100644 --- a/frontend/src/shared/api/schemas/assessment/assessmentSpecializationAvailability.zod.ts +++ b/frontend/src/shared/api/schemas/assessment/assessmentSpecializationAvailability.zod.ts @@ -21,7 +21,7 @@ export const AssessmentSpecializationAvailability = zod.object({ "grades": zod.array(zod.object({ "grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'), "status": zod.enum(['available', 'active_attempt', 'cooldown', 'insufficient_bank']).describe('Whether an attempt for the grade can start now.\n\n- available: CreateMyAssessmentAttempt can start it.\n- active_attempt: the specialization has an active attempt; resume it by `active_attempt_id`.\n- cooldown: a retry or promotion interval or the attempt limit of the policy blocks it until `available_at`. Attempts that ended as `insufficient_bank` or `sandbox_unavailable` never cause it.\n- insufficient_bank: no published bank of the category, or not enough unseen families to cover the blueprint for this candidate. The server never fills the gap by repeating families.'), - "mode": zod.union([zod.enum(['demo_basic', 'adaptive']).describe('Measurement method of an attempt. The server selects it from the published task bank of the category; the client never chooses it.\n\n- demo_basic: a fixed form of reviewed demo items scored by their keys against the pass mark of the versioned basic grading policy. It computes no ability estimate, standard error, or probability, so every uncertainty field of its result is null, its thresholds are uncalibrated, and its decision is binary: it never offers an additional practice.\n- adaptive: the adaptive test on task families with an ability estimate, its standard error, and the probability of reaching the grade threshold, as the versioned assessment policy defines them. A probability in the band below confirmation offers one additional practice in the same attempt.\n\nAdding a value is a contract change.'),zod.null()]).describe('Mode that an attempt would use, or null when the status is `insufficient_bank`.'), + "mode": zod.union([zod.enum(['demo_basic', 'adaptive']).describe('Server-selected mode available to a real category assessment.'),zod.null()]).describe('Real-assessment mode that the server would use, or null when the status is `insufficient_bank`. `demo_express` is not a category assessment and is never returned here.'), "available_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('When the status is `cooldown`, the first time the attempt can start; otherwise null.'), "time_limit_seconds": zod.int().min(1).nullable().describe('Time from the start to `expires_at`.'), "max_sessions": zod.int().min(1).max(assessmentSpecializationAvailabilityGradesItemMaxSessionsMax).nullable().describe('Session limit within the time limit.'), diff --git a/frontend/src/shared/api/schemas/assessment/createMyAssessmentAttemptBody.zod.ts b/frontend/src/shared/api/schemas/assessment/createMyAssessmentAttemptBody.zod.ts index 0cdaf0d..20eb30d 100644 --- a/frontend/src/shared/api/schemas/assessment/createMyAssessmentAttemptBody.zod.ts +++ b/frontend/src/shared/api/schemas/assessment/createMyAssessmentAttemptBody.zod.ts @@ -6,11 +6,20 @@ */ import * as zod from 'zod'; -export const CreateMyAssessmentAttemptBody = zod.object({ +export const CreateMyAssessmentAttemptBody = zod.union([zod.object({ + "kind": zod.enum(['root']).describe('Start a real-assessment chain and reserve one root quota slot.'), "specialization": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'), "target_grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'), "task_language": zod.union([zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.'),zod.null()]).describe('Task language of the attempt, one of the `task_languages` of the published bank, or null when the bank offers no choice of language. The questionnaire choice is the value the client offers first.') -}).describe('Category to assess: a specialization and the target grade, with the task language. The candidate comes from the session. The mode and versions are chosen by the server; unknown fields such as `mode`, `seed`, or `score` are rejected.') +}).describe('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.'),zod.object({ + "kind": zod.enum(['corrective']).describe('Continue the existing real-assessment chain without reserving another root slot.'), + "specialization": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'), + "target_grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'), + "task_language": zod.union([zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.'),zod.null()]).describe('Task language of the attempt, or null when the bank offers no choice.'), + "root_attempt_id": zod.uuid().describe('Root real-assessment attempt whose quota and deadline this attempt shares.') +}).describe('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 is never supplied by the client.'),zod.object({ + "kind": zod.enum(['demo_express']).describe('Explicitly request the training run; real modes cannot be selected by the client.') +}).describe('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.')]).describe('Start a real assessment, a corrective attempt in an existing chain, or an explicit training run. The required `kind` discriminator selects one of the three request shapes; `mode` remains server-selected for real assessments.') export type CreateMyAssessmentAttemptBody = zod.input; export type CreateMyAssessmentAttemptBodyOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/finalizeMyAssessmentAttemptBody.zod.ts b/frontend/src/shared/api/schemas/assessment/finalizeMyAssessmentAttemptBody.zod.ts index 9c1c945..78220f0 100644 --- a/frontend/src/shared/api/schemas/assessment/finalizeMyAssessmentAttemptBody.zod.ts +++ b/frontend/src/shared/api/schemas/assessment/finalizeMyAssessmentAttemptBody.zod.ts @@ -9,7 +9,7 @@ import * as zod from 'zod'; export const FinalizeMyAssessmentAttemptBody = zod.object({ - "expected_version": zod.int().min(1).describe('Version of an assessment attempt. A new attempt has version 1, and each committed change advances it by exactly one: an accepted answer, a practice submission or resubmission, a verdict, a decision of finalize, a session start, and a server-side transition such as expiry or automatic finalization. A transition that the server applies when the attempt is read is committed before the response and also advances it. A rejected command and a repeat that stores nothing leave it unchanged. Commands send the version they read as `expected_version`.') + "expected_version": zod.int().min(1).describe('Version of an assessment attempt. A new attempt has version 1, and each committed change advances it by exactly one: an accepted answer, a practice submission or resubmission, a verdict, a decision of finalize, an explicit work-session start, and a server-side transition such as expiry or automatic finalization. Reads never change the attempt. A rejected command and a repeat that stores nothing leave it unchanged. Commands send the version they read as `expected_version`.') }).describe('Command to finalize the attempt.') export type FinalizeMyAssessmentAttemptBody = zod.input; diff --git a/frontend/src/shared/api/schemas/assessment/index.ts b/frontend/src/shared/api/schemas/assessment/index.ts index fb4c33d..d84c546 100644 --- a/frontend/src/shared/api/schemas/assessment/index.ts +++ b/frontend/src/shared/api/schemas/assessment/index.ts @@ -8,11 +8,20 @@ export * from './assessmentAnswer.zod'; export * from './assessmentAnswerSubmission.zod'; export * from './assessmentAttempt.zod'; +export * from './assessmentAttemptCommon.zod'; export * from './assessmentAttemptCreate.zod'; +export * from './assessmentAttemptKind.zod'; +export * from './assessmentAttemptSessionStart.zod'; export * from './assessmentAttemptState.zod'; export * from './assessmentAttemptVersion.zod'; export * from './assessmentAvailability.zod'; +export * from './assessmentCorrectiveAttempt.zod'; +export * from './assessmentCorrectiveAttemptCreate.zod'; +export * from './assessmentCorrectiveResult.zod'; export * from './assessmentDurations.zod'; +export * from './assessmentExpressAttempt.zod'; +export * from './assessmentExpressAttemptCreate.zod'; +export * from './assessmentExpressResult.zod'; export * from './assessmentFinalization.zod'; export * from './assessmentGap.zod'; export * from './assessmentGradeAvailability.zod'; @@ -31,6 +40,11 @@ export * from './assessmentOutcome.zod'; export * from './assessmentPractice.zod'; export * from './assessmentPracticeResult.zod'; export * from './assessmentProgress.zod'; +export * from './assessmentQualifiedAttempt.zod'; +export * from './assessmentQualifiedAttemptCreate.zod'; +export * from './assessmentQualifiedResult.zod'; +export * from './assessmentRealMode.zod'; +export * from './assessmentRealResultCommon.zod'; export * from './assessmentResult.zod'; export * from './assessmentSessions.zod'; export * from './assessmentSpecializationAvailability.zod'; @@ -64,6 +78,8 @@ export * from './practiceItemContent.zod'; export * from './practiceKind.zod'; export * from './practiceStatus.zod'; export * from './practiceVerdict.zod'; +export * from './startMyAssessmentAttemptSessionBody.zod'; +export * from './startMyAssessmentAttemptSessionHeaders.zod'; export * from './stringAnswer.zod'; export * from './stringItemContent.zod'; export * from './submitMyAssessmentAnswerBody.zod'; diff --git a/frontend/src/shared/api/schemas/assessment/startMyAssessmentAttemptSessionBody.zod.ts b/frontend/src/shared/api/schemas/assessment/startMyAssessmentAttemptSessionBody.zod.ts new file mode 100644 index 0000000..3f65b94 --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/startMyAssessmentAttemptSessionBody.zod.ts @@ -0,0 +1,16 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + + + +export const StartMyAssessmentAttemptSessionBody = zod.object({ + "expected_version": zod.int().min(1).describe('Version of an assessment attempt. A new attempt has version 1, and each committed change advances it by exactly one: an accepted answer, a practice submission or resubmission, a verdict, a decision of finalize, an explicit work-session start, and a server-side transition such as expiry or automatic finalization. Reads never change the attempt. A rejected command and a repeat that stores nothing leave it unchanged. Commands send the version they read as `expected_version`.') +}).describe('Start or resume a work session using the attempt version last read by the candidate.') + +export type StartMyAssessmentAttemptSessionBody = zod.input; +export type StartMyAssessmentAttemptSessionBodyOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/startMyAssessmentAttemptSessionHeaders.zod.ts b/frontend/src/shared/api/schemas/assessment/startMyAssessmentAttemptSessionHeaders.zod.ts new file mode 100644 index 0000000..21aef5d --- /dev/null +++ b/frontend/src/shared/api/schemas/assessment/startMyAssessmentAttemptSessionHeaders.zod.ts @@ -0,0 +1,19 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const startMyAssessmentAttemptSessionHeadersIdempotencyKeyMax = 255; + + +export const startMyAssessmentAttemptSessionHeadersIdempotencyKeyRegExp = new RegExp('^[A-Za-z0-9._:-]+$'); + +export const StartMyAssessmentAttemptSessionHeaders = zod.object({ + "Idempotency-Key": zod.string().min(1).max(startMyAssessmentAttemptSessionHeadersIdempotencyKeyMax).regex(startMyAssessmentAttemptSessionHeadersIdempotencyKeyRegExp) +}) + +export type StartMyAssessmentAttemptSessionHeaders = zod.input; +export type StartMyAssessmentAttemptSessionHeadersOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/assessment/submitMyAssessmentAnswerBody.zod.ts b/frontend/src/shared/api/schemas/assessment/submitMyAssessmentAnswerBody.zod.ts index d9ff93d..1768512 100644 --- a/frontend/src/shared/api/schemas/assessment/submitMyAssessmentAnswerBody.zod.ts +++ b/frontend/src/shared/api/schemas/assessment/submitMyAssessmentAnswerBody.zod.ts @@ -32,7 +32,7 @@ export const submitMyAssessmentAnswerBodyAnswerSevenSourceCodeMax = 65536; export const SubmitMyAssessmentAnswerBody = zod.object({ - "expected_version": zod.int().min(1).describe('Version of an assessment attempt. A new attempt has version 1, and each committed change advances it by exactly one: an accepted answer, a practice submission or resubmission, a verdict, a decision of finalize, a session start, and a server-side transition such as expiry or automatic finalization. A transition that the server applies when the attempt is read is committed before the response and also advances it. A rejected command and a repeat that stores nothing leave it unchanged. Commands send the version they read as `expected_version`.'), + "expected_version": zod.int().min(1).describe('Version of an assessment attempt. A new attempt has version 1, and each committed change advances it by exactly one: an accepted answer, a practice submission or resubmission, a verdict, a decision of finalize, an explicit work-session start, and a server-side transition such as expiry or automatic finalization. Reads never change the attempt. A rejected command and a repeat that stores nothing leave it unchanged. Commands send the version they read as `expected_version`.'), "item_id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'), "answer": zod.union([zod.object({ "format": zod.enum(['choice']), diff --git a/scripts/merge-schemas.py b/scripts/merge-schemas.py index 655bf62..750dc24 100644 --- a/scripts/merge-schemas.py +++ b/scripts/merge-schemas.py @@ -133,6 +133,43 @@ def rewrite_schema_references( name_mapping, schema_paths, ) + elif key == "discriminator" and isinstance(item, dict): + discriminator: dict[Any, Any] = {} + for discriminator_key, discriminator_value in item.items(): + if discriminator_key == "mapping" and isinstance( + discriminator_value, dict + ): + mapping: dict[Any, Any] = {} + for tag, reference in discriminator_value.items(): + if isinstance(reference, str): + mapping[tag] = rewrite_schema_reference( + reference, + source_path, + contract_root, + merged_path, + name_mapping, + schema_paths, + ) + else: + mapping[tag] = rewrite_schema_references( + reference, + source_path, + contract_root, + merged_path, + name_mapping, + schema_paths, + ) + discriminator[discriminator_key] = mapping + else: + discriminator[discriminator_key] = rewrite_schema_references( + discriminator_value, + source_path, + contract_root, + merged_path, + name_mapping, + schema_paths, + ) + rewritten[key] = discriminator else: rewritten[key] = rewrite_schema_references( item, @@ -159,13 +196,35 @@ def rewrite_schema_references( def collect_references(value: Any, location: str = "$") -> list[tuple[str, str]]: - """Return every nested $ref and its YAML location.""" + """Return nested $ref and discriminator mapping targets with their locations.""" references: list[tuple[str, str]] = [] if isinstance(value, dict): for key, item in value.items(): child_location = f"{location}.{key}" if key == "$ref" and isinstance(item, str): references.append((item, child_location)) + elif key == "discriminator" and isinstance(item, dict): + for discriminator_key, discriminator_value in item.items(): + if discriminator_key == "mapping" and isinstance( + discriminator_value, dict + ): + for tag, target in discriminator_value.items(): + target_location = ( + f"{child_location}.mapping.{tag}" + ) + if isinstance(target, str): + references.append((target, target_location)) + else: + references.extend( + collect_references(target, target_location) + ) + else: + references.extend( + collect_references( + discriminator_value, + f"{child_location}.{discriminator_key}", + ) + ) else: references.extend(collect_references(item, child_location)) elif isinstance(value, list): diff --git a/scripts/test_assessment_contract.py b/scripts/test_assessment_contract.py new file mode 100644 index 0000000..12a5c1d --- /dev/null +++ b/scripts/test_assessment_contract.py @@ -0,0 +1,367 @@ +"""Pin assessment mode, correction-chain, and read-side-effect contracts.""" + +from __future__ import annotations + +import unittest +from pathlib import Path +from typing import Any + +import yaml + + +API_DIR = Path(__file__).resolve().parents[1] / "api" +CORE_BUNDLE = API_DIR / "core" / "openapi.bundle.yml" + + +def load_bundle() -> dict[str, Any]: + with CORE_BUNDLE.open(encoding="utf-8") as stream: + document = yaml.safe_load(stream) + if not isinstance(document, dict): + raise AssertionError(f"{CORE_BUNDLE} is not an OpenAPI document") + return document + + +def resolve_schema(schema: dict[str, Any], schemas: dict[str, Any]) -> dict[str, Any]: + current = schema + visited: set[str] = set() + while "$ref" in current: + reference = current["$ref"] + if not reference.startswith("#/components/schemas/"): + raise AssertionError(f"unexpected bundled schema reference: {reference}") + name = reference.rsplit("/", 1)[1] + if name in visited: + raise AssertionError(f"cyclic schema reference: {name}") + visited.add(name) + current = schemas[name] + return current + + +def referenced_schema_name(schema: dict[str, Any]) -> str: + reference = schema.get("$ref", "") + if not reference.startswith("#/components/schemas/"): + raise AssertionError(f"expected a bundled schema reference, got {reference!r}") + return reference.rsplit("/", 1)[1] + + +def properties_across_all_of( + schema: dict[str, Any], schemas: dict[str, Any] +) -> dict[str, Any]: + resolved = resolve_schema(schema, schemas) + properties = dict(resolved.get("properties", {})) + for part in resolved.get("allOf", []): + properties.update(properties_across_all_of(part, schemas)) + return properties + + +def union_enum_values(schema: dict[str, Any], schemas: dict[str, Any]) -> set[str]: + resolved = resolve_schema(schema, schemas) + values: set[str] = set() + for branch in resolved.get("oneOf", []): + branch_properties = properties_across_all_of(branch, schemas) + format_schema = branch_properties.get("format", {}) + values.update(format_schema.get("enum", [])) + return values + + +def required_across_all_of(schema: dict[str, Any], schemas: dict[str, Any]) -> set[str]: + resolved = resolve_schema(schema, schemas) + required = set(resolved.get("required", [])) + for part in resolved.get("allOf", []): + required.update(required_across_all_of(part, schemas)) + return required + + +def example_value(example: dict[str, Any], examples: dict[str, Any]) -> dict[str, Any]: + current = example + visited: set[str] = set() + while "$ref" in current: + reference = current["$ref"] + if not reference.startswith("#/components/examples/"): + raise AssertionError(f"unexpected bundled example reference: {reference}") + name = reference.rsplit("/", 1)[1] + if name in visited: + raise AssertionError(f"cyclic example reference: {name}") + visited.add(name) + current = examples[name] + value = current.get("value") + if not isinstance(value, dict): + raise AssertionError("assessment example must contain an object value") + return value + + +class AssessmentContractTest(unittest.TestCase): + def setUp(self) -> None: + self.document = load_bundle() + self.schemas = self.document["components"]["schemas"] + self.paths = self.document["paths"] + + def test_create_has_disjoint_real_corrective_and_express_shapes(self) -> None: + self.assertEqual( + set(self.schemas["AssessmentMode"]["enum"]), + {"demo_basic", "demo_express", "adaptive"}, + ) + self.assertEqual( + set(self.schemas["AssessmentRealMode"]["enum"]), + {"demo_basic", "adaptive"}, + ) + create = resolve_schema(self.schemas["AssessmentAttemptCreate"], self.schemas) + self.assertEqual(len(create["oneOf"]), 3) + self.assertEqual(create["discriminator"]["propertyName"], "kind") + self.assertEqual( + set(create["discriminator"]["mapping"]), + {"root", "corrective", "demo_express"}, + ) + variants = { + referenced_schema_name(branch): resolve_schema(branch, self.schemas) + for branch in create["oneOf"] + } + self.assertIn("AssessmentQualifiedAttemptCreate", variants) + self.assertIn("AssessmentCorrectiveAttemptCreate", variants) + self.assertIn("AssessmentExpressAttemptCreate", variants) + + real = variants["AssessmentQualifiedAttemptCreate"] + corrective = variants["AssessmentCorrectiveAttemptCreate"] + express = variants["AssessmentExpressAttemptCreate"] + self.assertFalse(real.get("additionalProperties", True)) + self.assertNotIn("root_attempt_id", real.get("properties", {})) + self.assertEqual(real["properties"]["kind"]["enum"], ["root"]) + self.assertFalse(corrective.get("additionalProperties", True)) + self.assertIn("root_attempt_id", corrective["required"]) + self.assertNotIn("chain_deadline", corrective.get("properties", {})) + self.assertEqual(corrective["properties"]["kind"]["enum"], ["corrective"]) + self.assertEqual(express["required"], ["kind"]) + self.assertEqual(express["properties"]["kind"]["enum"], ["demo_express"]) + self.assertEqual(set(express["properties"]), {"kind"}) + + availability = resolve_schema( + self.schemas["AssessmentGradeAvailability"], self.schemas + ) + mode = availability["properties"]["mode"]["oneOf"][0] + self.assertEqual(referenced_schema_name(mode), "AssessmentRealMode") + + def test_attempt_and_result_one_of_keep_express_out_of_qualification(self) -> None: + attempt = resolve_schema(self.schemas["AssessmentAttempt"], self.schemas) + self.assertEqual(attempt["discriminator"]["propertyName"], "kind") + self.assertEqual( + set(attempt["discriminator"]["mapping"]), + {"root", "corrective", "demo_express"}, + ) + attempt_variants = { + referenced_schema_name(branch): branch for branch in attempt["oneOf"] + } + self.assertEqual( + set(attempt_variants), + { + "AssessmentQualifiedAttempt", + "AssessmentCorrectiveAttempt", + "AssessmentExpressAttempt", + }, + ) + corrective_properties = properties_across_all_of( + attempt_variants["AssessmentCorrectiveAttempt"], self.schemas + ) + corrective_required = required_across_all_of( + attempt_variants["AssessmentCorrectiveAttempt"], self.schemas + ) + self.assertTrue({"root_attempt_id", "chain_deadline"}.issubset(corrective_properties)) + self.assertTrue({"root_attempt_id", "chain_deadline"}.issubset(corrective_required)) + self.assertEqual(corrective_properties["chain_deadline"]["$ref"], "#/components/schemas/Timestamp") + qualified_attempt = resolve_schema( + attempt_variants["AssessmentQualifiedAttempt"], self.schemas + ) + qualified_attempt_properties = properties_across_all_of( + attempt_variants["AssessmentQualifiedAttempt"], self.schemas + ) + self.assertEqual( + set(qualified_attempt_properties["mode"]["enum"]), + {"demo_basic", "adaptive"}, + ) + self.assertEqual(qualified_attempt_properties["root_attempt_id"]["type"], "null") + self.assertEqual(qualified_attempt_properties["chain_deadline"]["type"], "null") + self.assertTrue( + {"root_attempt_id", "chain_deadline"}.issubset( + required_across_all_of( + attempt_variants["AssessmentQualifiedAttempt"], self.schemas + ) + ) + ) + self.assertNotIn("not", qualified_attempt["allOf"][1]) + express_attempt = properties_across_all_of( + attempt_variants["AssessmentExpressAttempt"], self.schemas + ) + self.assertEqual(express_attempt["mode"]["enum"], ["demo_express"]) + for name in ("specialization", "target_grade", "task_language", "root_attempt_id", "chain_deadline"): + self.assertEqual(express_attempt[name]["type"], "null", name) + + result = resolve_schema(self.schemas["AssessmentResult"], self.schemas) + self.assertEqual(result["discriminator"]["propertyName"], "kind") + self.assertEqual( + set(result["discriminator"]["mapping"]), + {"root", "corrective", "demo_express"}, + ) + result_variants = {referenced_schema_name(branch): branch for branch in result["oneOf"]} + self.assertEqual( + set(result_variants), + {"AssessmentQualifiedResult", "AssessmentCorrectiveResult", "AssessmentExpressResult"}, + ) + qualified_properties = properties_across_all_of( + result_variants["AssessmentQualifiedResult"], self.schemas + ) + self.assertEqual( + set(qualified_properties["mode"]["enum"]), + {"demo_basic", "adaptive"}, + ) + corrective_properties = properties_across_all_of( + result_variants["AssessmentCorrectiveResult"], self.schemas + ) + for variant_name, variant, properties, expected_type in ( + ( + "qualified", + result_variants["AssessmentQualifiedResult"], + qualified_properties, + "null", + ), + ( + "corrective", + result_variants["AssessmentCorrectiveResult"], + corrective_properties, + "string", + ), + ): + required = required_across_all_of(variant, self.schemas) + self.assertTrue({"root_attempt_id", "chain_deadline"}.issubset(required), variant_name) + self.assertEqual(properties["root_attempt_id"]["type"], expected_type, variant_name) + if expected_type == "null": + self.assertEqual(properties["chain_deadline"]["type"], "null", variant_name) + else: + self.assertEqual( + properties["chain_deadline"]["$ref"], + "#/components/schemas/Timestamp", + variant_name, + ) + + express = resolve_schema(result_variants["AssessmentExpressResult"], self.schemas) + express_properties = express["properties"] + self.assertEqual(express_properties["mode"]["enum"], ["demo_express"]) + for name in ("specialization", "target_grade", "confirmed_grade", "strength", "uncertainty", "basic_score"): + self.assertEqual(express_properties[name]["type"], "null", name) + self.assertEqual(express_properties["outcome"]["enum"], ["demonstration"]) + self.assertEqual(express_properties["limitations"]["items"]["enum"], ["demonstration_only"]) + self.assertIn("$ref", express_properties["practices"]["items"]) + self.assertIn("$ref", express_properties["gaps"]["items"]) + self.assertIn("$ref", express_properties["next_steps"]["items"]) + self.assertFalse(express.get("additionalProperties", True)) + self.assertNotIn("percentile", express_properties) + self.assertNotIn("score", express_properties) + self.assertIn("summary", express_properties) + + def test_assessment_examples_match_discriminators_and_chain_pairs(self) -> None: + examples = self.document["components"]["examples"] + + def operation_examples(path: str, method: str, location: tuple[str, ...]) -> list[dict[str, Any]]: + value: Any = self.paths[path][method] + for key in location: + value = value[key] + return [example_value(item, examples) for item in value.values()] + + create_requests = operation_examples( + "/api/v1/me/assessment-attempts", + "post", + ("requestBody", "content", "application/json", "examples"), + ) + self.assertEqual({value["kind"] for value in create_requests}, {"root", "corrective", "demo_express"}) + requests_by_kind = {value["kind"]: value for value in create_requests} + self.assertNotIn("root_attempt_id", requests_by_kind["root"]) + self.assertIn("root_attempt_id", requests_by_kind["corrective"]) + self.assertNotIn("chain_deadline", requests_by_kind["corrective"]) + self.assertEqual(set(requests_by_kind["demo_express"]), {"kind"}) + + created_attempts = operation_examples( + "/api/v1/me/assessment-attempts", + "post", + ("responses", "201", "content", "application/json", "examples"), + ) + self.assertEqual({value["kind"] for value in created_attempts}, {"root", "corrective", "demo_express"}) + for value in created_attempts: + if value["kind"] == "corrective": + self.assertIsNotNone(value["root_attempt_id"]) + self.assertIsNotNone(value["chain_deadline"]) + else: + self.assertIsNone(value["root_attempt_id"]) + self.assertIsNone(value["chain_deadline"]) + + results = operation_examples( + "/api/v1/me/assessment-attempts/{attempt_id}/result", + "get", + ("responses", "200", "content", "application/json", "examples"), + ) + self.assertEqual({value["kind"] for value in results}, {"root", "corrective", "demo_express"}) + for value in results: + if value["kind"] == "corrective": + self.assertIsNotNone(value["root_attempt_id"]) + self.assertIsNotNone(value["chain_deadline"]) + elif value["kind"] == "root": + self.assertIsNone(value["root_attempt_id"]) + self.assertIsNone(value["chain_deadline"]) + else: + self.assertNotIn("root_attempt_id", value) + self.assertNotIn("chain_deadline", value) + + def test_session_start_is_explicit_versioned_and_idempotent(self) -> None: + operation = self.paths[ + "/api/v1/me/assessment-attempts/{attempt_id}/sessions" + ]["post"] + body = operation["requestBody"]["content"]["application/json"]["schema"] + session_start = resolve_schema(body, self.schemas) + self.assertEqual(session_start["required"], ["expected_version"]) + self.assertIn( + "#/components/parameters/IdempotencyKey", + [parameter.get("$ref") for parameter in operation["parameters"]], + ) + self.assertIn("412", operation["responses"]) + self.assertIn("sessionCsrf", operation["security"][0]) + + def test_get_attempt_and_result_are_read_only_projections(self) -> None: + attempt = self.paths["/api/v1/me/assessment-attempts/{attempt_id}"]["get"] + result = self.paths[ + "/api/v1/me/assessment-attempts/{attempt_id}/result" + ]["get"] + for operation in (attempt, result): + self.assertNotIn("requestBody", operation) + self.assertIn("read-only", operation["description"].lower()) + self.assertNotIn("sessionCsrf", operation["security"][0]) + self.assertNotIn("post", self.paths["/api/v1/me/assessment-attempts/{attempt_id}"]) + self.assertNotIn("post", self.paths["/api/v1/me/assessment-attempts/{attempt_id}/result"]) + + def test_attempt_items_and_answers_keep_the_seven_public_formats(self) -> None: + expected = { + "choice", + "number", + "string", + "order", + "find_error", + "configuration", + "practice", + } + self.assertEqual(union_enum_values(self.schemas["ItemContent"], self.schemas), expected) + self.assertEqual(union_enum_values(self.schemas["AssessmentAnswer"], self.schemas), expected) + + def test_candidate_schemas_do_not_name_secrets_or_employer_access(self) -> None: + forbidden = {"answer_key", "answer_keys", "seed", "hidden_seed", "hidden_checks"} + for name in ("AssessmentAttemptCommon", "AssessmentRealResultCommon", "AssessmentExpressResult"): + schema = self.schemas[name] + self.assertFalse(forbidden.intersection(schema.get("properties", {})), name) + + attempt_description = self.paths[ + "/api/v1/me/assessment-attempts/{attempt_id}" + ]["get"]["description"].lower() + result_description = self.paths[ + "/api/v1/me/assessment-attempts/{attempt_id}/result" + ]["get"]["description"].lower() + self.assertIn("employer", attempt_description) + self.assertIn("employer", result_description) + self.assertIn("404", self.paths["/api/v1/me/assessment-attempts/{attempt_id}"]["get"]["responses"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/test_merge_schemas.py b/scripts/test_merge_schemas.py index 7232439..ff89f83 100644 --- a/scripts/test_merge_schemas.py +++ b/scripts/test_merge_schemas.py @@ -118,6 +118,101 @@ class MergeSchemasTest(unittest.TestCase): "#/Contact/properties/email", ) + def test_rewrites_only_schema_targets_in_discriminator_mappings(self) -> None: + self.write_yaml( + "components/schemas/common_schemas.yml", + { + "schemas": { + "entity.Contact": {"type": "object"}, + "entity.Status": {"type": "string"}, + } + }, + ) + profile_path = self.write_yaml( + "components/schemas/profile_schemas.yml", + { + "schemas": { + "response.Profile": { + "type": "object", + "discriminator": { + "propertyName": "kind", + "mapping": { + "profile": "#/schemas/response.Profile", + "status": "#/schemas/entity.Status", + "contact": "./common_schemas.yml#/schemas/entity.Contact", + "external": "https://schemas.example.test/external.yml#/schemas/External", + }, + }, + "mapping": {"example": "#/schemas/entity.Status"}, + "example": {"mapping": {"example": "#/schemas/entity.Status"}}, + } + } + }, + ) + + source_schema = MERGE.load_yaml(profile_path)["schemas"]["response.Profile"] + references = MERGE.collect_references(source_schema) + self.assertIn(("#/schemas/response.Profile", "$.discriminator.mapping.profile"), references) + self.assertIn( + ( + "./common_schemas.yml#/schemas/entity.Contact", + "$.discriminator.mapping.contact", + ), + references, + ) + self.assertNotIn(("#/schemas/entity.Status", "$.mapping.example"), references) + + MERGE.merge_contract(self.contract_root) + profile = self.read_yaml("components/schemas.yml")["Profile"] + mapping = profile["discriminator"]["mapping"] + self.assertEqual(mapping["profile"], "#/Profile") + self.assertEqual(mapping["status"], "#/Status") + self.assertEqual(mapping["contact"], "#/Contact") + self.assertEqual( + mapping["external"], + "https://schemas.example.test/external.yml#/schemas/External", + ) + self.assertEqual(profile["mapping"]["example"], "#/schemas/entity.Status") + self.assertEqual( + profile["example"]["mapping"]["example"], "#/schemas/entity.Status" + ) + + def test_stale_discriminator_mapping_route_refs_are_rejected(self) -> None: + self.write_yaml( + "components/schemas/health_schemas.yml", + {"schemas": {"response.Health": {"type": "object"}}}, + ) + self.write_yaml( + "routes/health.yml", + { + "get": { + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "oneOf": [], + "discriminator": { + "propertyName": "kind", + "mapping": { + "health": "../components/schemas.yml#/schemas/response.Health" + }, + }, + } + } + } + } + } + } + }, + ) + + with self.assertRaisesRegex(MERGE.MergeError, "stale schema references") as error: + MERGE.merge_contract(self.contract_root) + + self.assertIn("discriminator.mapping.health", str(error.exception)) + self.assertFalse((self.contract_root / "components" / "schemas.yml").exists()) + def test_duplicate_normalized_names_fail_without_overwriting_output(self) -> None: self.write_yaml( "components/schemas/auth_schemas.yml",