feat(api): add candidate assessment attempt contract

This commit is contained in:
shira committed 2026-10-06 03:28:44 +03:00
1 parent 6c86c4e559
commit 565ef8d4f5
100 files changed
+30314 -74

No files matched your search

+82 -1
View File
@@ -14,7 +14,7 @@ From the repository root, `make -C api check` checks contracts and `make generat
## Contract conventions
`api/core/` fixes these conventions as reusable components in `openapi.yml` and the files under `components/`: schemas in `components/schemas/*_schemas.yml`, parameters in `parameters.yml`, response headers in `headers.yml`, responses in `responses.yml`, and examples in `examples.yml`. Operations reference them as they are added. Currently implemented: problem responses for errors of the Go public API and the ML service. Idempotency-Key storage, If-Match checks, and pagination are planned behavior for business operations; the declared `RegisterAccount` operation requires Idempotency-Key, but no operation stores keys yet.
`api/core/` fixes these conventions as reusable components in `openapi.yml` and the files under `components/`: schemas in `components/schemas/*_schemas.yml`, parameters in `parameters.yml`, response headers in `headers.yml`, responses in `responses.yml`, and examples in `examples.yml`. Operations reference them as they are added. Currently implemented: problem responses for errors of the Go public API and the ML service. Idempotency-Key storage, If-Match checks, and pagination are planned behavior for business operations; the declared `RegisterAccount` operation and the assessment commands require Idempotency-Key, but no operation stores keys yet.
### Errors
@@ -163,6 +163,80 @@ Questionnaire:
- PUT replaces the whole questionnaire and needs no Idempotency-Key. A body equal to the stored state changes nothing, keeps the version, and answers 200 even with an older `expected_version`, so a retry after a lost response does not fail with 412.
- Order of checks for a save: session (401), CSRF and Origin (403), request validation (400), account scenario (403 `forbidden`), domain rules (400), version (412). `TestQuestionnaireSchemaValidationPrecedesImplementation` checks the schema rejections through the generated server.
### Assessment
The `assessment` tag covers the assessment attempts of the current candidate (PRD FR04 and FR05): availability, start and resume, answers including the code practice, finalization, and the result. The operations are in the contract; their business logic is not implemented yet, so every one answers 401 `unauthenticated` until sessions exist (`v1.DenyAllSecurity`).
| Method and path | operationId | Security | Success | Specific errors |
| --- | --- | --- | --- | --- |
| `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}/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` |
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.
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.
- 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.
Attempt lifecycle, with the commands each state accepts:
| State | Meaning | Accepts |
| --- | --- | --- |
| `in_progress` | Items are being answered; `current_item` is the item to answer | an answer to `current_item` |
| `practice_pending` | The item part is done; the main practice has no finished verdict (not submitted, `pending`, or `failed`) | a practice solution while it is `not_started` or `failed` |
| `additional_practice_pending` | Adaptive only: finalize found the probability in the band below confirmation and offered one additional practice in the same attempt | the additional practice solution while it is `not_started` or `failed`; finalize in the same statuses declines the offer |
| `ready_to_finalize` | Every required part is done | finalize |
| `completed` | A decision was made; the result is available | only the repeat of finalize |
| `expired` | The time or session limit passed before the candidate finished; the result confirms no grade | none |
| `insufficient_bank` | The bank could not cover the blueprint within the limit; the result confirms no grade | none |
- 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.
- No new problem code is added, so TASK-157 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.
Items and answers:
- An item has an `id` (the instance), `sequence`, a plain-text `prompt`, and `content` (`ItemContent`) in one of the formats `choice`, `number`, `string`, `order`, `find_error`, `configuration`, and `practice`. It never contains an answer key, a correct option, a score, a family or variant identifier, a seed, or a hidden check, and seed items look like scored ones. `multiple`, `max_selections`, and `max_length` are properties of the format or the task family and never derived from the key. The variant is fixed when first served, so a reload, a retry, or a resumed session returns the same instance.
- An answer (`AssessmentAnswer`) has the same seven formats and carries only the answer. Unknown fields such as `score`, `duration`, or `seed` answer 400. The server records the times and scores the answer with the key of the item instance; time never enters the grade decision. Responses never say whether an answer was correct.
- The practice solution runs asynchronously in the sandbox against three hidden check groups; the client polls the attempt while it is `pending`. The verdict shows only the score 0-3 and the pass state of each group. Every outcome caused by the solution (a compilation or runtime error, a time or memory limit) is `finished` with groups not passed. `failed` (`sandbox_busy` or `sandbox_error`) means only that the infrastructure could not run it; it consumes nothing. This keeps `failed` from acting as an oracle for hidden checks and from allowing endless retries. After `finished` no other solution is accepted.
- If the latest submission is still `failed` when the limit passes, the result is `not_determined` with the reason `sandbox_unavailable`. A practice never submitted gives `practice_incomplete`.
- An attempt has no practice only in `demo_basic` while code practice is disabled until the sandbox isolation is verified; the result then lists the `practice_not_included` limitation.
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.
- 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. This deviates from the wording of the TASK-155 test step and of TASK-152, which say 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 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.
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.
- `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.
Planned, additive: a short approach description of up to 1500 characters next to the practice, which never decides the grade (PRD FR05); the debug run operation of the practice; the notice and storage of the anti-cheat signals (time, focus changes, pastes, parallel sessions), which lead to a review and an appeal, never to a public label and never to the employer (PRD FR05).
### Generator checks
`testdata/openapi-3.2.0.yml` contains test operations that use the components above: pagination, Idempotency-Key, If-Match, ETag, and problem responses. ogen does not resolve external references, so the fixture keeps copies of the api/core components; `scripts/test_contract_copies.py` (part of `make -C api check`) checks that they, the fixture responses, and the ML `Problem` copy match api/core.
@@ -190,4 +264,11 @@ Known generator limitations:
- Orval Zod schemas ignore `uniqueItems` and do not reject unknown fields of `additionalProperties: false` objects; the server stays authoritative for both.
- Orval clears `src/shared/api/endpoints/` and `src/shared/api/schemas/` before generation (`clean: true`), because a schema used by several tags moves from a tag directory to the schema root.
#### Format unions
- Format unions such as `ItemContent` and `AssessmentAnswer` are `oneOf` without a `discriminator` object. Redocly resolves `discriminator.mapping` values as references, and `scripts/merge-schemas.py` rewrites only `$ref`, so a mapping in a split schema file cannot resolve in the merged `components/schemas.yml`. Every variant fixes `format` with a one-value enum; ogen discriminates by that value and by the fields unique to a variant and rejects a body that matches several variants, and Orval generates a Zod union.
- Orval names the constants of an inline property `<Schema><Property>`, so a property name that repeats another schema name collides in `index.ts` (TS2308). The union of item formats is therefore `ItemContent`, not `AssessmentItemContent`, next to the `AssessmentItem.content` property.
Generated Zod is not strict. A body that mixes the fields of two formats or carries an extra `score` or `seed` is accepted after unknown keys are silently stripped, and `uniqueItems` is not checked; only the server rejects such bodies. `frontend/src/shared/api/assessment-contract.test.ts` pins the accepted formats and that no answer or item DTO has a score, key, seed, or correctness field.
See the [development guide](../docs/en/DEVELOPMENT.md).
+82 -1
View File
@@ -14,7 +14,7 @@
## Соглашения контракта
`api/core/` закрепляет эти соглашения как переиспользуемые компоненты в `openapi.yml` и файлах `components/`: схемы в `components/schemas/*_schemas.yml`, параметры в `parameters.yml`, заголовки ответов в `headers.yml`, ответы в `responses.yml`, примеры в `examples.yml`. Операции ссылаются на них по мере появления. Сейчас реализованы problem-ответы для ошибок публичного Go API и ML-сервиса. Хранение Idempotency-Key, проверки If-Match и пагинация - запланированное поведение бизнес-операций; объявленная операция `RegisterAccount` требует Idempotency-Key, но ни одна операция пока не хранит ключи.
`api/core/` закрепляет эти соглашения как переиспользуемые компоненты в `openapi.yml` и файлах `components/`: схемы в `components/schemas/*_schemas.yml`, параметры в `parameters.yml`, заголовки ответов в `headers.yml`, ответы в `responses.yml`, примеры в `examples.yml`. Операции ссылаются на них по мере появления. Сейчас реализованы problem-ответы для ошибок публичного Go API и ML-сервиса. Хранение Idempotency-Key, проверки If-Match и пагинация - запланированное поведение бизнес-операций; объявленная операция `RegisterAccount` и команды оценки требуют Idempotency-Key, но ни одна операция пока не хранит ключи.
### Ошибки
@@ -163,6 +163,80 @@ ML-сервис отвечает на ошибки той же схемой `Pro
- PUT заменяет анкету целиком, и Idempotency-Key ему не нужен. Тело, равное сохраненному состоянию, ничего не меняет, сохраняет версию и дает 200 даже со старым `expected_version`, поэтому повтор после потерянного ответа не падает с 412.
- Порядок проверок при сохранении: сессия (401), CSRF и Origin (403), валидация запроса (400), сценарий аккаунта (403 `forbidden`), доменные правила (400), версия (412). `TestQuestionnaireSchemaValidationPrecedesImplementation` проверяет отказы схемы через сгенерированный сервер.
### Оценка
Тег `assessment` описывает попытки оценки текущего кандидата (FR04 и FR05 в PRD): доступность, старт и возобновление, ответы вместе с кодовой практикой, завершение и результат. Операции есть в контракте, бизнес-логика еще не реализована, поэтому каждая отвечает 401 `unauthenticated`, пока сессий нет (`v1.DenyAllSecurity`).
| Метод и путь | operationId | Защита | Успех | Конкретные ошибки |
| --- | --- | --- | --- | --- |
| `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}/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` |
Каждая операция также объявляет problem-ответ `default`.
Доступ:
- Кандидат берется только из сессии; ни одна операция не принимает идентификатор кандидата. Аккаунт работодателя получает 403 `forbidden`. Попытка другого кандидата дает 404 `not_found`, как и неизвестный идентификатор, поэтому идентификаторы попыток нельзя перебирать.
- Ни одна операция не дает работодателю ответы, историю попыток или античит-сигналы. Работодатель будет видеть только текущую категорию через отдельную проекцию.
Режимы и версии:
- `mode` - это `demo_basic` или `adaptive`. Сервер выбирает его по опубликованному банку категории; клиент режим не передает. `demo_basic` оценивает фиксированную форму проверенных демо-заданий по их ключам относительно проходного балла версионированной базовой политики, не вычисляет оценку способности и решает за один шаг: дополнительную практику он не предлагает. `adaptive` - адаптивный тест из FR04.
- Создание фиксирует `versions`: `policy_version` (номер версии политики `product`), `bank_version` и `algorithm_version`. Попытка и ее результат хранят их, поэтому результат воспроизводится по сохраненным ответам и этим версиям, а более поздняя версия его не переписывает.
- `version` попытки растет ровно на единицу с каждым зафиксированным изменением, включая серверные переходы: вердикт, начало сессии, истечение, автоматическое завершение. Переход, примененный при чтении попытки, фиксируется до ответа и тоже увеличивает версию.
Жизненный цикл попытки и команды, которые принимает каждое состояние:
| Состояние | Значение | Принимает |
| --- | --- | --- |
| `in_progress` | Идут ответы на задания; `current_item` - задание, на которое нужно ответить | ответ на `current_item` |
| `practice_pending` | Задания пройдены; у основной практики нет готового вердикта (не отправлена, `pending` или `failed`) | решение практики, пока она `not_started` или `failed` |
| `additional_practice_pending` | Только adaptive: завершение нашло вероятность в полосе ниже подтверждения и предложило одну дополнительную практику в той же попытке | решение дополнительной практики, пока она `not_started` или `failed`; завершение в тех же статусах отклоняет предложение |
| `ready_to_finalize` | Все обязательные части выполнены | завершение |
| `completed` | Решение принято; результат доступен | только повтор завершения |
| `expired` | Лимит времени или сессий истек раньше, чем кандидат закончил; результат не подтверждает грейд | ничего |
| `insufficient_bank` | Банк не смог обеспечить покрытие в пределах лимита; результат не подтверждает грейд | ничего |
- Дополнительная практика (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` завершает ее без подтвержденного грейда вместо повтора семейств.
- Новый код проблемы не добавлен, поэтому TASK-157 получает 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` - сбои платформы: они не учитываются и не запускают интервал. После неудачи, включая первый тест, меньший грейд можно проверить сразу.
Задания и ответы:
- У задания есть `id` (экземпляр), `sequence`, `prompt` простым текстом и `content` (`ItemContent`) в одном из форматов `choice`, `number`, `string`, `order`, `find_error`, `configuration` и `practice`. Оно никогда не содержит ключ ответа, правильный вариант, балл, идентификатор семейства или варианта, seed или скрытую проверку, а посевные задания выглядят так же, как оцениваемые. `multiple`, `max_selections` и `max_length` - свойства формата или семейства заданий и никогда не выводятся из ключа. Вариант фиксируется при первой выдаче, поэтому перезагрузка, повтор запроса и возобновление сессии возвращают тот же экземпляр.
- Ответ (`AssessmentAnswer`) имеет те же семь форматов и несет только ответ. Неизвестные поля вроде `score`, `duration` или `seed` дают 400. Сервер сам записывает время и оценивает ответ по ключу экземпляра задания; время не входит в решение о грейде. Ответы API никогда не сообщают, был ли ответ правильным.
- Решение практики исполняется в песочнице асинхронно на трех группах скрытых проверок; клиент опрашивает попытку, пока оно `pending`. Вердикт показывает только балл 0-3 и прохождение каждой группы. Любой исход, вызванный самим решением (ошибка компиляции или выполнения, лимит времени или памяти), - это `finished` с непройденными группами. `failed` (`sandbox_busy` или `sandbox_error`) означает только, что инфраструктура не смогла исполнить решение; он ничего не расходует. Так `failed` не становится оракулом для скрытых проверок и не дает бесконечных повторов. После `finished` другое решение не принимается.
- Если к истечению лимита последняя отправка все еще `failed`, результат - `not_determined` с причиной `sandbox_unavailable`. Неотправленная практика дает `practice_incomplete`.
- Попытка бывает без практики только в `demo_basic`, пока кодовая практика выключена до проверки изоляции песочницы; результат тогда содержит ограничение `practice_not_included`.
Команды, повторы и версии:
- Создание, ответ и завершение требуют 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. Это отступление от формулировки шага проверки TASK-155 и TASK-152, где указан 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` проверяет отказы схемы через сгенерированный сервер.
Результат:
- `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`.
- `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, скрытые проверки или античит-сигналы.
Запланировано, добавляется без ломающих изменений: краткое описание подхода до 1500 знаков рядом с практикой, которое не определяет грейд (FR05 в PRD); операция отладочных запусков практики; уведомление о собираемых античит-сигналах (время, переключение фокуса, вставки, параллельные сессии) и их хранение; сигналы ведут к перепроверке и апелляции, а не к публичному ярлыку, и работодателю не показываются (FR05 в PRD).
### Проверки генераторов
`testdata/openapi-3.2.0.yml` содержит тестовые операции с перечисленными компонентами: пагинацией, Idempotency-Key, If-Match, ETag и problem-ответами. ogen не разрешает внешние ссылки, поэтому фикстура хранит копии компонентов api/core; `scripts/test_contract_copies.py` (входит в `make -C api check`) проверяет, что они, ответы фикстуры и ML-копия `Problem` совпадают с api/core.
@@ -190,4 +264,11 @@ ML-сервис отвечает на ошибки той же схемой `Pro
- Zod-схемы Orval игнорируют `uniqueItems` и не отклоняют неизвестные поля объектов с `additionalProperties: false`; в обоих случаях решает сервер.
- Orval очищает `src/shared/api/endpoints/` и `src/shared/api/schemas/` перед генерацией (`clean: true`), потому что схема, используемая несколькими тегами, переезжает из каталога тега в корень схем.
#### Объединения форматов
- Объединения форматов, например `ItemContent` и `AssessmentAnswer`, - это `oneOf` без объекта `discriminator`. Redocly разрешает значения `discriminator.mapping` как ссылки, а `scripts/merge-schemas.py` переписывает только `$ref`, поэтому mapping из отдельного файла схем не разрешается в объединенном `components/schemas.yml`. Каждый вариант фиксирует `format` перечислением из одного значения; ogen различает варианты по этому значению и по полям, уникальным для варианта, и отклоняет тело, подходящее под несколько вариантов, а Orval генерирует Zod-объединение.
- Orval называет константы встроенного свойства `<Schema><Property>`, поэтому имя свойства, повторяющее имя другой схемы, дает конфликт в `index.ts` (TS2308). Поэтому объединение форматов задания называется `ItemContent`, а не `AssessmentItemContent`, рядом со свойством `AssessmentItem.content`.
Сгенерированный Zod не строгий. Тело, смешивающее поля двух форматов или содержащее лишние `score` или `seed`, принимается после молчаливого удаления неизвестных ключей, а `uniqueItems` не проверяется; такие тела отклоняет только сервер. `frontend/src/shared/api/assessment-contract.test.ts` закрепляет принимаемые форматы и отсутствие в DTO ответа и задания полей балла, ключа, seed или правильности.
Подробнее: [разработка](../docs/ru/DEVELOPMENT.md).
+916
View File
@@ -425,3 +425,919 @@ QuestionnaireRepeatedSpecialization:
pointer: /specializations/1/specialization
code: invalid
message: The value does not match the contract.
AssessmentAvailability:
summary: Backend open in demo_basic, Network Engineer blocked
description: >-
Illustrative values. Backend junior and middle can start in the
demo_basic mode, with their limits shown before the start; intern and
senior have no sufficient bank. Network Engineer junior waits for its
same-grade retry interval after an unconfirmed attempt.
value:
specializations:
- specialization: backend
confirmed_grade: null
active_attempt_id: null
grades:
- grade: intern
status: insufficient_bank
mode: null
available_at: null
time_limit_seconds: null
max_sessions: null
max_items: null
practice_required: null
- grade: junior
status: available
mode: demo_basic
available_at: null
time_limit_seconds: 259200
max_sessions: 2
max_items: 12
practice_required: false
- grade: middle
status: available
mode: demo_basic
available_at: null
time_limit_seconds: 259200
max_sessions: 2
max_items: 12
practice_required: false
- grade: senior
status: insufficient_bank
mode: null
available_at: null
time_limit_seconds: null
max_sessions: null
max_items: null
practice_required: null
- specialization: network_engineer
confirmed_grade: null
active_attempt_id: null
grades:
- grade: intern
status: insufficient_bank
mode: null
available_at: null
time_limit_seconds: null
max_sessions: null
max_items: null
practice_required: null
- grade: junior
status: cooldown
mode: demo_basic
available_at: "2026-11-12T00:00:00Z"
time_limit_seconds: 259200
max_sessions: 2
max_items: 10
practice_required: false
- grade: middle
status: available
mode: demo_basic
available_at: null
time_limit_seconds: 259200
max_sessions: 2
max_items: 10
practice_required: false
- grade: senior
status: insufficient_bank
mode: null
available_at: null
time_limit_seconds: null
max_sessions: null
max_items: null
practice_required: null
AssessmentAttemptCreateBackendJunior:
summary: Start Backend junior with Go tasks
value:
specialization: backend
target_grade: junior
task_language: go
AssessmentAttemptCreated:
summary: New demo_basic attempt with its first item
description: >-
The server chose demo_basic from the published bank and fixed the policy,
bank, and algorithm versions; creation started session 1. A retry of
this create with the same Idempotency-Key and body within 24 hours
replays exactly this 201 response and creates nothing; read the attempt
for its current state. The attempt has no practice, because code
practice stays disabled until the sandbox isolation is verified.
value:
id: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b
version: 1
specialization: backend
target_grade: junior
task_language: go
mode: demo_basic
state: in_progress
versions:
policy_version: 1
bank_version: backend-demo.2026-10.1
algorithm_version: basic-raw-score.1
started_at: "2026-10-08T10:00:00Z"
expires_at: "2026-10-11T10:00:00Z"
sessions:
used: 1
max: 2
idle_timeout_seconds: 1800
finished_at: null
progress:
answered_items: 0
max_items: 12
current_item:
id: 01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d01
sequence: 1
prompt: "Какой HTTP-статус вернуть, если запрос валиден, но ресурс находится в состоянии, не допускающем операцию?"
content:
format: choice
multiple: false
options:
- id: k7
text: "400"
- id: p2
text: "404"
- id: x9
text: "409"
- id: c4
text: "500"
practices: []
AssessmentAnswerAccepted:
summary: Answer to item 1 stored; item 2 follows
description: >-
The answer of AssessmentChoiceAnswer was stored and the version advanced
from 1 to 2. The response does not say whether the answer was correct.
A retry with the same Idempotency-Key replays exactly this response.
Sending the same answer to item 1 again, even with a new key or the
older expected_version 1, stores nothing and returns 200 with the
current attempt. AssessmentOrderAnswer answers item 2 next.
value:
id: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b
version: 2
specialization: backend
target_grade: junior
task_language: go
mode: demo_basic
state: in_progress
versions:
policy_version: 1
bank_version: backend-demo.2026-10.1
algorithm_version: basic-raw-score.1
started_at: "2026-10-08T10:00:00Z"
expires_at: "2026-10-11T10:00:00Z"
sessions:
used: 1
max: 2
idle_timeout_seconds: 1800
finished_at: null
progress:
answered_items: 1
max_items: 12
current_item:
id: 01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d02
sequence: 2
prompt: "Упорядочите шаги обработки запроса в обработчике HTTP."
content:
format: order
elements:
- id: d3
text: Записать ответ
- id: a7
text: Проверить сессию
- id: c2
text: Выполнить операцию
- id: b1
text: Разобрать и проверить тело
practices: []
AssessmentAttemptCompleted:
summary: demo_basic attempt finalized; read the result next
value:
id: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b
version: 14
specialization: backend
target_grade: junior
task_language: go
mode: demo_basic
state: completed
versions:
policy_version: 1
bank_version: backend-demo.2026-10.1
algorithm_version: basic-raw-score.1
started_at: "2026-10-08T10:00:00Z"
expires_at: "2026-10-11T10:00:00Z"
sessions:
used: 1
max: 2
idle_timeout_seconds: 1800
finished_at: "2026-10-08T10:24:00Z"
progress:
answered_items: 12
max_items: 12
current_item: null
practices: []
AssessmentAttemptResumed:
summary: Adaptive attempt resumed on its sixth item in session 2
description: >-
A reload or a new session returns the same item instance with the same
lines; nothing tells whether the five earlier answers were correct, and
seed items look like scored ones. The retest started from the previous
ability estimate of the specialization.
value:
id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d
version: 7
specialization: backend
target_grade: middle
task_language: python
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-20T09:00:00Z"
expires_at: "2026-11-23T09:00:00Z"
sessions:
used: 2
max: 2
idle_timeout_seconds: 1800
finished_at: null
progress:
answered_items: 5
max_items: 25
current_item:
id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c06
sequence: 6
prompt: "Найдите строку, из-за которой соединения с базой данных не возвращаются в пул."
content:
format: find_error
syntax: python
max_selections: 1
lines:
- number: 1
text: "def load_user(pool, user_id):"
- number: 2
text: " conn = pool.acquire()"
- number: 3
text: " row = conn.fetchrow(QUERY, user_id)"
- number: 4
text: " if row is None:"
- number: 5
text: " raise NotFound(user_id)"
- number: 6
text: " pool.release(conn)"
- number: 7
text: " return row"
practices:
- kind: main
item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99
status: not_started
submitted_at: null
verdict: null
failure_reason: null
AssessmentAttemptPracticePending:
summary: Item part finished, main practice not submitted
description: >-
The adaptive stop rule ended the item part after 14 items, but no grade
is decided until the main practice has a finished verdict. The current
item is the practice; hidden checks and seeds are not part of it.
value:
id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d
version: 16
specialization: backend
target_grade: middle
task_language: python
mode: adaptive
state: practice_pending
versions:
policy_version: 2
bank_version: backend.2026-11.3
algorithm_version: irt-1pl-eap.1
started_at: "2026-11-20T09:00:00Z"
expires_at: "2026-11-23T09:00:00Z"
sessions:
used: 2
max: 2
idle_timeout_seconds: 1800
finished_at: null
progress:
answered_items: 14
max_items: 25
current_item:
id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99
sequence: 15
prompt: "Реализуйте функцию merge_intervals: на вход список пар [start, end], на выход объединенные пересекающиеся интервалы, отсортированные по началу."
content:
format: practice
languages: [python]
max_source_length: 20000
public_examples:
- input: "[[1,3],[2,6],[8,10]]"
expected_output: "[[1,6],[8,10]]"
practices:
- kind: main
item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99
status: not_started
submitted_at: null
verdict: null
failure_reason: null
AssessmentAttemptPracticeVerdictPending:
summary: Practice submitted, verdict pending in the sandbox
value:
id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d
version: 17
specialization: backend
target_grade: middle
task_language: python
mode: adaptive
state: practice_pending
versions:
policy_version: 2
bank_version: backend.2026-11.3
algorithm_version: irt-1pl-eap.1
started_at: "2026-11-20T09:00:00Z"
expires_at: "2026-11-23T09:00:00Z"
sessions:
used: 2
max: 2
idle_timeout_seconds: 1800
finished_at: null
progress:
answered_items: 14
max_items: 25
current_item: null
practices:
- kind: main
item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99
status: pending
submitted_at: "2026-11-20T10:05:00Z"
verdict: null
failure_reason: null
AssessmentAttemptSandboxFailed:
summary: Sandbox queue was full; the practice can be submitted again
description: >-
The failure does not depend on the solution and consumes nothing. The
practice item is current again; a resubmission, with the same or a
different solution, queues it again and advances the version.
value:
id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d
version: 18
specialization: backend
target_grade: middle
task_language: python
mode: adaptive
state: practice_pending
versions:
policy_version: 2
bank_version: backend.2026-11.3
algorithm_version: irt-1pl-eap.1
started_at: "2026-11-20T09:00:00Z"
expires_at: "2026-11-23T09:00:00Z"
sessions:
used: 2
max: 2
idle_timeout_seconds: 1800
finished_at: null
progress:
answered_items: 14
max_items: 25
current_item:
id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99
sequence: 15
prompt: "Реализуйте функцию merge_intervals: на вход список пар [start, end], на выход объединенные пересекающиеся интервалы, отсортированные по началу."
content:
format: practice
languages: [python]
max_source_length: 20000
public_examples:
- input: "[[1,3],[2,6],[8,10]]"
expected_output: "[[1,6],[8,10]]"
practices:
- kind: main
item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99
status: failed
submitted_at: "2026-11-20T10:05:00Z"
verdict: null
failure_reason: sandbox_busy
AssessmentAttemptReadyToFinalize:
summary: Main practice verdict finished, ready to finalize
value:
id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d
version: 20
specialization: backend
target_grade: middle
task_language: python
mode: adaptive
state: ready_to_finalize
versions:
policy_version: 2
bank_version: backend.2026-11.3
algorithm_version: irt-1pl-eap.1
started_at: "2026-11-20T09:00:00Z"
expires_at: "2026-11-23T09:00:00Z"
sessions:
used: 2
max: 2
idle_timeout_seconds: 1800
finished_at: null
progress:
answered_items: 14
max_items: 25
current_item: null
practices:
- kind: main
item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99
status: finished
submitted_at: "2026-11-20T10:09:00Z"
verdict:
score: 2
max_score: 3
groups:
- group: 1
passed: true
- group: 2
passed: true
- group: 3
passed: false
failure_reason: null
AssessmentAttemptAdditionalPracticePending:
summary: Finalize offered an additional practice in the same attempt
description: >-
The probability of reaching middle was in the band below confirmation,
so finalize decided nothing yet: it appended an additional practice and
returned the attempt instead of a result. The attempt keeps its time and
session limits and spends no new attempt. Submitting the additional
practice leads back to ready_to_finalize; finalizing now declines it
and gives not_confirmed. A retry of that finalize with a new key and
the old expected_version 20 answers 412 and cannot decline by accident.
value:
id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d
version: 21
specialization: backend
target_grade: middle
task_language: python
mode: adaptive
state: additional_practice_pending
versions:
policy_version: 2
bank_version: backend.2026-11.3
algorithm_version: irt-1pl-eap.1
started_at: "2026-11-20T09:00:00Z"
expires_at: "2026-11-23T09:00:00Z"
sessions:
used: 2
max: 2
idle_timeout_seconds: 1800
finished_at: null
progress:
answered_items: 14
max_items: 25
current_item:
id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8ca0
sequence: 16
prompt: "Реализуйте LRU-кеш с операциями get и put за O(1)."
content:
format: practice
languages: [python]
max_source_length: 20000
public_examples:
- input: "put(1,1); put(2,2); get(1); put(3,3); get(2)"
expected_output: "1, -1"
practices:
- kind: main
item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99
status: finished
submitted_at: "2026-11-20T10:09:00Z"
verdict:
score: 2
max_score: 3
groups:
- group: 1
passed: true
- group: 2
passed: true
- group: 3
passed: false
failure_reason: null
- kind: additional
item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8ca0
status: not_started
submitted_at: null
verdict: null
failure_reason: null
AssessmentAttemptInsufficientBank:
summary: Attempt ended because the bank could not cover the blueprint
description: >-
The bank ran out of unseen families for a required domain within the
item limit. The attempt ended without a confirmed grade instead of
repeating a family; its result has outcome not_determined, and it does
not count against the retry rules.
value:
id: 01928f7c-5555-7a2b-8c3d-4e5f6a7b8c9d
version: 10
specialization: network_engineer
target_grade: middle
task_language: null
mode: adaptive
state: insufficient_bank
versions:
policy_version: 2
bank_version: network.2026-11.1
algorithm_version: irt-1pl-eap.1
started_at: "2026-11-21T12:00:00Z"
expires_at: "2026-11-24T12:00:00Z"
sessions:
used: 1
max: 2
idle_timeout_seconds: 1800
finished_at: "2026-11-21T12:31:00Z"
progress:
answered_items: 8
max_items: 25
current_item: null
practices:
- kind: main
item_id: 01928f7c-6666-7a2b-8c3d-4e5f6a7b8c99
status: not_started
submitted_at: null
verdict: null
failure_reason: null
AssessmentChoiceAnswer:
summary: Answer item 1 of version 1
value:
expected_version: 1
item_id: 01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d01
answer:
format: choice
option_ids: [x9]
AssessmentOrderAnswer:
summary: Answer item 2 with every element once
value:
expected_version: 2
item_id: 01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d02
answer:
format: order
element_ids: [a7, b1, c2, d3]
AssessmentNumberAnswer:
summary: Number answer
value:
expected_version: 3
item_id: 01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d03
answer:
format: number
number: 254
AssessmentStringAnswer:
summary: String answer
value:
expected_version: 4
item_id: 01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d04
answer:
format: string
text: Retry-After
AssessmentFindErrorAnswer:
summary: Find-error answer for the resumed item
value:
expected_version: 7
item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c06
answer:
format: find_error
line_numbers: [5]
AssessmentConfigurationAnswer:
summary: Configuration answer
value:
expected_version: 7
item_id: 01928f7c-6666-7a2b-8c3d-4e5f6a7b8c07
answer:
format: configuration
config: |-
interface GigabitEthernet0/1
ip access-group BLOCK_TELNET in
AssessmentPracticeAnswer:
summary: Main practice solution
description: >-
Sent with expected_version 16 for the first submission. After a failed
verdict the client sends it again with the current version, such as 18
in AssessmentAttemptSandboxFailed; the same source then queues again.
value:
expected_version: 16
item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99
answer:
format: practice
language: python
source_code: |-
def merge_intervals(intervals):
result = []
for start, end in sorted(intervals):
if result and start <= result[-1][1]:
result[-1][1] = max(result[-1][1], end)
else:
result.append([start, end])
return result
AssessmentFinalization:
summary: Finalize version 20
value:
expected_version: 20
AssessmentDemoBasicResult:
summary: demo_basic result with a confirmed grade and no uncertainty
description: >-
demo_basic computes no ability estimate, so `uncertainty` and `strength`
are null rather than zero, and no percentile is shown. The pass mark
comes from basic grading policy version 1, and the limitations name the
uncalibrated thresholds, the demo bank, and the missing practice. A
first confirmation is not a promotion, so the higher grade can be
tested at once. The result never changes; a repeated finalize returns
the completed attempt, and this read returns the same result.
value:
attempt_id: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b
specialization: backend
target_grade: junior
task_language: go
mode: demo_basic
versions:
policy_version: 1
bank_version: backend-demo.2026-10.1
algorithm_version: basic-raw-score.1
outcome: confirmed
not_determined_reason: null
confirmed_grade: junior
previous_confirmed_grade: null
strength: null
calibration_status: uncalibrated
limitations:
[uncalibrated_thresholds, demo_bank, practice_not_included, unproctored]
uncertainty: null
basic_score:
points: 9
max_points: 12
pass_points: 8
practices: []
gaps: []
durations:
items_seconds: 1260
practice_seconds: null
next_steps:
- action: take_higher_grade
grade: middle
available_at: null
decided_at: "2026-10-08T10:24:00Z"
AssessmentAdaptiveResult:
summary: Adaptive promotion confirmed with medium strength
description: >-
Illustrative values, continuing AssessmentAttemptAdditionalPracticePending.
The additional practice raised P_G to 0.84, in the medium band of the
policy version, so the grade is confirmed with medium strength. The
candidate already had junior, so this is a
promotion, and the next one waits for the promotion interval. The
thresholds are uncalibrated until the pilot.
value:
attempt_id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d
specialization: backend
target_grade: middle
task_language: python
mode: adaptive
versions:
policy_version: 2
bank_version: backend.2026-11.3
algorithm_version: irt-1pl-eap.1
outcome: confirmed
not_determined_reason: null
confirmed_grade: middle
previous_confirmed_grade: junior
strength: medium
calibration_status: uncalibrated
limitations: [uncalibrated_thresholds, unproctored]
uncertainty:
theta: 0.62
standard_error: 0.24
interval_95:
low: 0.15
high: 1.09
p_grade: 0.84
basic_score: null
practices:
- kind: main
verdict:
score: 2
max_score: 3
groups:
- group: 1
passed: true
- group: 2
passed: true
- group: 3
passed: false
- kind: additional
verdict:
score: 3
max_score: 3
groups:
- group: 1
passed: true
- group: 2
passed: true
- group: 3
passed: true
gaps:
- domain: concurrency
title: Конкурентность
durations:
items_seconds: 1980
practice_seconds: 1500
next_steps:
- action: take_higher_grade
grade: senior
available_at: "2027-02-18T10:30:00Z"
decided_at: "2026-11-20T10:30:00Z"
AssessmentNotConfirmedResult:
summary: Adaptive attempt not confirmed after the additional practice
description: >-
P_G stayed below 0.80 after the additional practice, so middle is not
confirmed, and the candidate keeps no confirmed grade. After a failure,
including the first test, junior can be tested at once; accepting junior
on the evidence of this attempt is offered; middle opens again after the
same-grade retry interval.
value:
attempt_id: 01928f7d-7777-7a2b-8c3d-4e5f6a7b8c9d
specialization: backend
target_grade: middle
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: null
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:
- kind: main
verdict:
score: 1
max_score: 3
groups:
- group: 1
passed: true
- group: 2
passed: false
- group: 3
passed: false
- kind: additional
verdict:
score: 1
max_score: 3
groups:
- group: 1
passed: true
- group: 2
passed: false
- group: 3
passed: false
gaps:
- domain: databases
title: Базы данных
durations:
items_seconds: 2100
practice_seconds: 1800
next_steps:
- action: take_lower_grade
grade: junior
available_at: null
- action: accept_lower_grade
grade: junior
available_at: null
- action: retake_same_grade
grade: middle
available_at: "2026-12-22T11:00:00Z"
decided_at: "2026-11-22T11:00:00Z"
AssessmentInsufficientBankResult:
summary: Attempt without a decision because the bank was insufficient
value:
attempt_id: 01928f7c-5555-7a2b-8c3d-4e5f6a7b8c9d
specialization: network_engineer
target_grade: middle
task_language: null
mode: adaptive
versions:
policy_version: 2
bank_version: network.2026-11.1
algorithm_version: irt-1pl-eap.1
outcome: not_determined
not_determined_reason: insufficient_bank
confirmed_grade: null
previous_confirmed_grade: junior
strength: null
calibration_status: uncalibrated
limitations: [uncalibrated_thresholds, unproctored]
uncertainty: null
basic_score: null
practices: []
gaps: []
durations:
items_seconds: 1860
practice_seconds: null
next_steps: []
decided_at: "2026-11-21T12:31:00Z"
AssessmentSpecializationNotInQuestionnaire:
summary: The specialization is not in the questionnaire
value:
type: urn:lincodex:problem:validation_failed
title: Request validation failed
status: 400
code: validation_failed
detail: One or more request fields are invalid.
trace_id: 9f0a1b2c-3d4e-4f5a-8b6c-7d8e9f0a1b2c
errors:
- in: body
pointer: /specialization
code: invalid
message: The value does not match the contract.
AssessmentAnswerUnknownOption:
summary: The selected option does not belong to the item
value:
type: urn:lincodex:problem:validation_failed
title: Request validation failed
status: 400
code: validation_failed
detail: One or more request fields are invalid.
trace_id: 0a1b2c3d-4e5f-4a6b-9c7d-8e9f0a1b2c3d
errors:
- in: body
pointer: /answer/option_ids/0
code: invalid
message: The value does not match the contract.
AssessmentAnswerUnknownField:
summary: The client sent its own score
value:
type: urn:lincodex:problem:validation_failed
title: Request validation failed
status: 400
code: validation_failed
detail: One or more request fields are invalid.
trace_id: 1b2c3d4e-5f6a-4b7c-8d8e-9f0a1b2c3d4e
errors:
- in: body
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
AssessmentFinalizeNotReady:
summary: Premature finalize; the problem does not list the unfinished parts
description: >-
Problem has no extension fields. The client reads what remains from the
attempt: `state`, `progress`, `current_item`, and `practices`.
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: 6a7b8c9d-0e1f-4a2b-8c3d-4e5f6a7b8c9e
AssessmentAttemptNotAvailable:
summary: No attempt can start for the category now
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: 3d4e5f6a-7b8c-4d9e-8f0a-1b2c3d4e5f6a
AssessmentResultNotReady:
summary: The attempt has no result yet
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: 4e5f6a7b-8c9d-4e0f-9a1b-2c3d4e5f6a7b
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
+12
View File
@@ -56,3 +56,15 @@ PageCursor:
minLength: 1
maxLength: 512
pattern: "^[A-Za-z0-9_-]+$"
AssessmentAttemptId:
name: attempt_id
in: path
required: true
description: >-
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.
schema:
type: string
format: uuid
example: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b
+113
View File
@@ -261,3 +261,116 @@ QuestionnaireVersionConflict:
examples:
version_conflict:
$ref: ./examples.yml#/VersionConflict
AssessmentAttemptCreateValidationFailed:
description: >-
The body does not match the contract or violates an assessment rule: an
unknown specialization, grade, or task language, an unknown field such
as mode or seed, a specialization that is not in the questionnaire, or
a task language that the published bank does not offer; code
validation_failed with body pointers. Nothing was created, and the
outcome is not stored under the Idempotency-Key.
content:
application/problem+json:
schema:
$ref: ./schemas.yml#/Problem
examples:
specialization_not_in_questionnaire:
$ref: ./examples.yml#/AssessmentSpecializationNotInQuestionnaire
AssessmentAnswerValidationFailed:
description: >-
The body does not match the contract or the answer does not fit the
item: a format other than the item format, an option, element, or line
that the item does not have, an order that is not a permutation of every
element, more selections than the item allows, a text longer than the
item allows, a language that the practice does not offer, or an unknown
field such as score or duration; code validation_failed with body
pointers. When the decoder does not record the path of a nested field,
the pointer is the whole body. Nothing was stored, and the outcome is
not stored under the Idempotency-Key.
content:
application/problem+json:
schema:
$ref: ./schemas.yml#/Problem
examples:
unknown_option:
$ref: ./examples.yml#/AssessmentAnswerUnknownOption
score_sent_by_client:
$ref: ./examples.yml#/AssessmentAnswerUnknownField
AssessmentCommandConflict:
description: >-
The attempt state does not allow the answer at the current version, code
state_conflict: the attempt is terminal or past its limits, the item is
not the current item, the item already has a different answer, or the
practice has a pending or finished verdict and the submission differs.
Or a request with the same Idempotency-Key is still running, code
idempotency_in_progress. Nothing was changed in either case; read the
attempt to see its state.
content:
application/problem+json:
schema:
$ref: ./schemas.yml#/Problem
examples:
state_conflict:
$ref: ./examples.yml#/AssessmentItemNotCurrent
idempotency_in_progress:
$ref: ./examples.yml#/IdempotencyInProgress
AssessmentFinalizeConflict:
description: >-
The attempt state does not allow finalize at the current version, code
state_conflict: items or the main practice are unfinished, a practice
verdict is pending, or the attempt ended as expired or insufficient_bank.
The problem does not list the unfinished parts, because Problem allows
no extension fields; the attempt shows them in `state`, `progress`,
`current_item`, and `practices`. Or a request with the same
Idempotency-Key is still running, code idempotency_in_progress. Nothing
was changed in either case.
content:
application/problem+json:
schema:
$ref: ./schemas.yml#/Problem
examples:
state_conflict:
$ref: ./examples.yml#/AssessmentFinalizeNotReady
idempotency_in_progress:
$ref: ./examples.yml#/IdempotencyInProgress
AssessmentCreateConflict:
description: >-
No attempt can start for the category now, code state_conflict: the
specialization already has an active attempt, a retry or promotion
interval or the attempt limit blocks the grade, or the bank is
insufficient. GetMyAssessmentAvailability tells which, with the date
when a blocked attempt opens. Or a request with the same Idempotency-Key
is still running, code idempotency_in_progress. Nothing was created in
either case.
content:
application/problem+json:
schema:
$ref: ./schemas.yml#/Problem
examples:
state_conflict:
$ref: ./examples.yml#/AssessmentAttemptNotAvailable
idempotency_in_progress:
$ref: ./examples.yml#/IdempotencyInProgress
AssessmentResultNotReady:
description: >-
The attempt is still active, so it has no result yet; code
state_conflict. The attempt state tells what remains to be done.
content:
application/problem+json:
schema:
$ref: ./schemas.yml#/Problem
examples:
state_conflict:
$ref: ./examples.yml#/AssessmentResultNotReady
AssessmentVersionConflict:
description: >-
`expected_version` is not the current attempt version; code
version_conflict. Nothing was changed, and the outcome is not stored
under the Idempotency-Key; read the attempt again before retrying.
content:
application/problem+json:
schema:
$ref: ./schemas.yml#/Problem
examples:
version_conflict:
$ref: ./examples.yml#/AssessmentStaleVersion
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+147
View File
@@ -21,6 +21,11 @@ tags:
Data of the current candidate, such as the questionnaire with the
chosen specializations and self-assessed grades. Confirmed grades and
categories come only from assessment results.
- name: assessment
description: >-
Assessment attempts of the current candidate: availability, start and
resume, answers and the code practice, finalization, and the result.
Answers, keys, and attempt history are visible only to the candidate.
# Operations require a session unless they declare `security: []`, so a new
# operation that omits security is protected by default.
security:
@@ -46,6 +51,18 @@ paths:
$ref: ./routes/catalog_specializations.yml
/api/v1/me/questionnaire:
$ref: ./routes/candidate_questionnaire.yml
/api/v1/me/assessment-availability:
$ref: ./routes/candidate_assessment_availability.yml
/api/v1/me/assessment-attempts:
$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}/answers:
$ref: ./routes/candidate_assessment_attempt_answers.yml
/api/v1/me/assessment-attempts/{attempt_id}/finalize:
$ref: ./routes/candidate_assessment_attempt_finalize.yml
/api/v1/me/assessment-attempts/{attempt_id}/result:
$ref: ./routes/candidate_assessment_attempt_result.yml
components:
schemas:
Problem:
@@ -134,6 +151,120 @@ components:
$ref: ./components/schemas.yml#/CandidateQuestionnaire
CandidateQuestionnaireUpdate:
$ref: ./components/schemas.yml#/CandidateQuestionnaireUpdate
AssessmentMode:
$ref: ./components/schemas.yml#/AssessmentMode
AssessmentAttemptVersion:
$ref: ./components/schemas.yml#/AssessmentAttemptVersion
AssessmentAttemptState:
$ref: ./components/schemas.yml#/AssessmentAttemptState
AssessmentVersionLabel:
$ref: ./components/schemas.yml#/AssessmentVersionLabel
AssessmentVersions:
$ref: ./components/schemas.yml#/AssessmentVersions
AssessmentSessions:
$ref: ./components/schemas.yml#/AssessmentSessions
AssessmentAttemptCreate:
$ref: ./components/schemas.yml#/AssessmentAttemptCreate
AssessmentItemId:
$ref: ./components/schemas.yml#/AssessmentItemId
AssessmentOptionId:
$ref: ./components/schemas.yml#/AssessmentOptionId
AssessmentOption:
$ref: ./components/schemas.yml#/AssessmentOption
ChoiceItemContent:
$ref: ./components/schemas.yml#/ChoiceItemContent
NumberItemContent:
$ref: ./components/schemas.yml#/NumberItemContent
StringItemContent:
$ref: ./components/schemas.yml#/StringItemContent
OrderItemContent:
$ref: ./components/schemas.yml#/OrderItemContent
CodeLine:
$ref: ./components/schemas.yml#/CodeLine
FindErrorItemContent:
$ref: ./components/schemas.yml#/FindErrorItemContent
ConfigurationItemContent:
$ref: ./components/schemas.yml#/ConfigurationItemContent
PracticeExample:
$ref: ./components/schemas.yml#/PracticeExample
PracticeItemContent:
$ref: ./components/schemas.yml#/PracticeItemContent
ItemContent:
$ref: ./components/schemas.yml#/ItemContent
AssessmentItem:
$ref: ./components/schemas.yml#/AssessmentItem
AssessmentProgress:
$ref: ./components/schemas.yml#/AssessmentProgress
PracticeKind:
$ref: ./components/schemas.yml#/PracticeKind
PracticeStatus:
$ref: ./components/schemas.yml#/PracticeStatus
PracticeFailureReason:
$ref: ./components/schemas.yml#/PracticeFailureReason
PracticeGroupResult:
$ref: ./components/schemas.yml#/PracticeGroupResult
PracticeVerdict:
$ref: ./components/schemas.yml#/PracticeVerdict
AssessmentPractice:
$ref: ./components/schemas.yml#/AssessmentPractice
AssessmentAttempt:
$ref: ./components/schemas.yml#/AssessmentAttempt
ChoiceAnswer:
$ref: ./components/schemas.yml#/ChoiceAnswer
NumberAnswer:
$ref: ./components/schemas.yml#/NumberAnswer
StringAnswer:
$ref: ./components/schemas.yml#/StringAnswer
OrderAnswer:
$ref: ./components/schemas.yml#/OrderAnswer
FindErrorAnswer:
$ref: ./components/schemas.yml#/FindErrorAnswer
ConfigurationAnswer:
$ref: ./components/schemas.yml#/ConfigurationAnswer
PracticeAnswer:
$ref: ./components/schemas.yml#/PracticeAnswer
AssessmentAnswer:
$ref: ./components/schemas.yml#/AssessmentAnswer
AssessmentAnswerSubmission:
$ref: ./components/schemas.yml#/AssessmentAnswerSubmission
AssessmentFinalization:
$ref: ./components/schemas.yml#/AssessmentFinalization
AssessmentOutcome:
$ref: ./components/schemas.yml#/AssessmentOutcome
AssessmentNotDeterminedReason:
$ref: ./components/schemas.yml#/AssessmentNotDeterminedReason
AssessmentStrength:
$ref: ./components/schemas.yml#/AssessmentStrength
CalibrationStatus:
$ref: ./components/schemas.yml#/CalibrationStatus
AssessmentLimitation:
$ref: ./components/schemas.yml#/AssessmentLimitation
AssessmentInterval:
$ref: ./components/schemas.yml#/AssessmentInterval
AssessmentUncertainty:
$ref: ./components/schemas.yml#/AssessmentUncertainty
BasicScore:
$ref: ./components/schemas.yml#/BasicScore
AssessmentGap:
$ref: ./components/schemas.yml#/AssessmentGap
AssessmentDurations:
$ref: ./components/schemas.yml#/AssessmentDurations
AssessmentPracticeResult:
$ref: ./components/schemas.yml#/AssessmentPracticeResult
AssessmentNextAction:
$ref: ./components/schemas.yml#/AssessmentNextAction
AssessmentNextStep:
$ref: ./components/schemas.yml#/AssessmentNextStep
AssessmentResult:
$ref: ./components/schemas.yml#/AssessmentResult
AssessmentGradeAvailabilityStatus:
$ref: ./components/schemas.yml#/AssessmentGradeAvailabilityStatus
AssessmentGradeAvailability:
$ref: ./components/schemas.yml#/AssessmentGradeAvailability
AssessmentSpecializationAvailability:
$ref: ./components/schemas.yml#/AssessmentSpecializationAvailability
AssessmentAvailability:
$ref: ./components/schemas.yml#/AssessmentAvailability
parameters:
IdempotencyKey:
$ref: ./components/parameters.yml#/IdempotencyKey
@@ -143,6 +274,8 @@ components:
$ref: ./components/parameters.yml#/PageLimit
PageCursor:
$ref: ./components/parameters.yml#/PageCursor
AssessmentAttemptId:
$ref: ./components/parameters.yml#/AssessmentAttemptId
headers:
ETag:
$ref: ./components/headers.yml#/ETag
@@ -197,6 +330,20 @@ components:
$ref: ./components/responses.yml#/QuestionnaireValidationFailed
QuestionnaireVersionConflict:
$ref: ./components/responses.yml#/QuestionnaireVersionConflict
AssessmentAttemptCreateValidationFailed:
$ref: ./components/responses.yml#/AssessmentAttemptCreateValidationFailed
AssessmentAnswerValidationFailed:
$ref: ./components/responses.yml#/AssessmentAnswerValidationFailed
AssessmentCommandConflict:
$ref: ./components/responses.yml#/AssessmentCommandConflict
AssessmentFinalizeConflict:
$ref: ./components/responses.yml#/AssessmentFinalizeConflict
AssessmentCreateConflict:
$ref: ./components/responses.yml#/AssessmentCreateConflict
AssessmentResultNotReady:
$ref: ./components/responses.yml#/AssessmentResultNotReady
AssessmentVersionConflict:
$ref: ./components/responses.yml#/AssessmentVersionConflict
securitySchemes:
sessionCookie:
type: apiKey
@@ -0,0 +1,50 @@
get:
operationId: GetMyAssessmentAttempt
summary: Read or resume 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.
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.
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.
security:
- sessionCookie: []
tags:
- assessment
parameters:
- $ref: ../components/parameters.yml#/AssessmentAttemptId
responses:
"200":
description: The attempt.
headers:
Cache-Control:
$ref: ../components/headers.yml#/CacheControlNoStore
content:
application/json:
schema:
$ref: ../components/schemas.yml#/AssessmentAttempt
examples:
adaptive_resumed:
$ref: ../components/examples.yml#/AssessmentAttemptResumed
practice_pending:
$ref: ../components/examples.yml#/AssessmentAttemptPracticePending
practice_verdict_pending:
$ref: ../components/examples.yml#/AssessmentAttemptPracticeVerdictPending
sandbox_failed:
$ref: ../components/examples.yml#/AssessmentAttemptSandboxFailed
ready_to_finalize:
$ref: ../components/examples.yml#/AssessmentAttemptReadyToFinalize
additional_practice_pending:
$ref: ../components/examples.yml#/AssessmentAttemptAdditionalPracticePending
completed:
$ref: ../components/examples.yml#/AssessmentAttemptCompleted
insufficient_bank:
$ref: ../components/examples.yml#/AssessmentAttemptInsufficientBank
"401":
$ref: ../components/responses.yml#/Unauthenticated
"403":
$ref: ../components/responses.yml#/Forbidden
"404":
$ref: ../components/responses.yml#/NotFound
default:
$ref: ../components/responses.yml#/Problem
@@ -0,0 +1,83 @@
post:
operationId: SubmitMyAssessmentAnswer
summary: Answer the current item or submit a practice of an 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 item and carries the answer in the format of that item: `choice`, `number`, `string`, `order`, `find_error`, `configuration`, or `practice`. It never carries a score, a duration, or a correctness flag; the server records the times itself and scores the answer with the key of the fixed item instance. Time never enters the ability estimate or the grade decision.
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.
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:
- A retry with the same Idempotency-Key and body within 24 hours replays the stored response.
- Sending the answer already stored for the item again, even with a new key or an older `expected_version`, stores nothing, keeps the version, and answers 200 with the current attempt. Each answer format defines equality: 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 item that already has one answers 409 state_conflict when `expected_version` is current; with a stale version the version check comes first and answers 412.
- Exception for a practice whose latest verdict is `failed`: the repeat rule does not apply. A submission with the same or a different solution, with the current `expected_version`, queues it again and advances the version.
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.
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#/AssessmentAnswerSubmission
examples:
choice:
$ref: ../components/examples.yml#/AssessmentChoiceAnswer
order:
$ref: ../components/examples.yml#/AssessmentOrderAnswer
number:
$ref: ../components/examples.yml#/AssessmentNumberAnswer
string:
$ref: ../components/examples.yml#/AssessmentStringAnswer
find_error:
$ref: ../components/examples.yml#/AssessmentFindErrorAnswer
configuration:
$ref: ../components/examples.yml#/AssessmentConfigurationAnswer
practice:
$ref: ../components/examples.yml#/AssessmentPracticeAnswer
responses:
"200":
description: >-
The answer was stored, or this exact answer was already stored, and
the response is the attempt with the next item.
headers:
Cache-Control:
$ref: ../components/headers.yml#/CacheControlNoStore
content:
application/json:
schema:
$ref: ../components/schemas.yml#/AssessmentAttempt
examples:
accepted:
$ref: ../components/examples.yml#/AssessmentAnswerAccepted
practice_submitted:
$ref: ../components/examples.yml#/AssessmentAttemptPracticeVerdictPending
"400":
$ref: ../components/responses.yml#/AssessmentAnswerValidationFailed
"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
@@ -0,0 +1,67 @@
post:
operationId: FinalizeMyAssessmentAttempt
summary: Ask for the grade decision of an 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. 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.
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.
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.
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#/AssessmentFinalization
examples:
finalize:
$ref: ../components/examples.yml#/AssessmentFinalization
responses:
"200":
description: >-
The attempt after the decision: `completed`, with the result available
from GetMyAssessmentResult, or `additional_practice_pending` when an
adaptive attempt offers an additional practice.
headers:
Cache-Control:
$ref: ../components/headers.yml#/CacheControlNoStore
content:
application/json:
schema:
$ref: ../components/schemas.yml#/AssessmentAttempt
examples:
demo_basic_completed:
$ref: ../components/examples.yml#/AssessmentAttemptCompleted
additional_practice_offered:
$ref: ../components/examples.yml#/AssessmentAttemptAdditionalPracticePending
"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#/AssessmentFinalizeConflict
"412":
$ref: ../components/responses.yml#/AssessmentVersionConflict
"422":
$ref: ../components/responses.yml#/UnprocessableContent
default:
$ref: ../components/responses.yml#/Problem
@@ -0,0 +1,44 @@
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.
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.
security:
- sessionCookie: []
tags:
- assessment
parameters:
- $ref: ../components/parameters.yml#/AssessmentAttemptId
responses:
"200":
description: The result.
headers:
Cache-Control:
$ref: ../components/headers.yml#/CacheControlNoStore
content:
application/json:
schema:
$ref: ../components/schemas.yml#/AssessmentResult
examples:
demo_basic:
$ref: ../components/examples.yml#/AssessmentDemoBasicResult
adaptive_confirmed:
$ref: ../components/examples.yml#/AssessmentAdaptiveResult
adaptive_not_confirmed:
$ref: ../components/examples.yml#/AssessmentNotConfirmedResult
insufficient_bank:
$ref: ../components/examples.yml#/AssessmentInsufficientBankResult
"401":
$ref: ../components/responses.yml#/Unauthenticated
"403":
$ref: ../components/responses.yml#/Forbidden
"404":
$ref: ../components/responses.yml#/NotFound
"409":
$ref: ../components/responses.yml#/AssessmentResultNotReady
default:
$ref: ../components/responses.yml#/Problem
@@ -0,0 +1,58 @@
post:
operationId: CreateMyAssessmentAttempt
summary: Start an assessment attempt for a category of the current candidate.
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.
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.
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.
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.
security:
- sessionCookie: []
sessionCsrf: []
tags:
- assessment
parameters:
- $ref: ../components/parameters.yml#/IdempotencyKey
requestBody:
required: true
content:
application/json:
schema:
$ref: ../components/schemas.yml#/AssessmentAttemptCreate
examples:
backend_junior_go:
$ref: ../components/examples.yml#/AssessmentAttemptCreateBackendJunior
responses:
"201":
description: >-
The attempt was created, or a retry with the same Idempotency-Key
replayed its creation.
headers:
Cache-Control:
$ref: ../components/headers.yml#/CacheControlNoStore
content:
application/json:
schema:
$ref: ../components/schemas.yml#/AssessmentAttempt
examples:
demo_basic_created:
$ref: ../components/examples.yml#/AssessmentAttemptCreated
"400":
$ref: ../components/responses.yml#/AssessmentAttemptCreateValidationFailed
"401":
$ref: ../components/responses.yml#/Unauthenticated
"403":
$ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden
"409":
$ref: ../components/responses.yml#/AssessmentCreateConflict
"422":
$ref: ../components/responses.yml#/UnprocessableContent
"429":
$ref: ../components/responses.yml#/TooManyRequests
default:
$ref: ../components/responses.yml#/Problem
@@ -0,0 +1,32 @@
get:
operationId: GetMyAssessmentAvailability
summary: Read which assessment attempts the current candidate can start.
description: |-
Requires the session cookie of a candidate account; the candidate comes from the session. For each specialization of the questionnaire, returns the confirmed grade, the active attempt, and for every grade whether an attempt can start now, in which mode, and with which limits: the time limit, the session limit, the item limit, and whether a code practice is required. The client shows them before the start, together with the method and the signals that are collected, and resumes an active attempt by `active_attempt_id`, for example after it lost the response of CreateMyAssessmentAttempt.
`insufficient_bank` is the state of a category whose bank is not published or has too few families that this candidate has not seen; the server limits attempts instead of repeating families. `cooldown` carries the date when the attempt opens, so the client can explain a blocked attempt with that date and offer support. Specializations and their retry intervals are independent. Attempts that ended as `insufficient_bank` or with the reason `sandbox_unavailable` are platform limitations and never cause a `cooldown`.
A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden.
security:
- sessionCookie: []
tags:
- assessment
responses:
"200":
description: Assessment availability of the current candidate.
headers:
Cache-Control:
$ref: ../components/headers.yml#/CacheControlNoStore
content:
application/json:
schema:
$ref: ../components/schemas.yml#/AssessmentAvailability
examples:
backend_and_network_engineer:
$ref: ../components/examples.yml#/AssessmentAvailability
"401":
$ref: ../components/responses.yml#/Unauthenticated
"403":
$ref: ../components/responses.yml#/Forbidden
default:
$ref: ../components/responses.yml#/Problem
@@ -21,6 +21,8 @@ var regexMap = map[string]ogenregex.Regexp{
"^[A-Za-z0-9._-]+$": ogenregex.MustCompile("^[A-Za-z0-9._-]+$"),
"^[A-Za-z0-9._:-]+$": ogenregex.MustCompile("^[A-Za-z0-9._:-]+$"),
"^[A-Za-z0-9_-]+$": ogenregex.MustCompile("^[A-Za-z0-9_-]+$"),
"^[a-z0-9_+-]+$": ogenregex.MustCompile("^[a-z0-9_+-]+$"),
"^[a-z0-9_]+$": ogenregex.MustCompile("^[a-z0-9_]+$"),
"^[a-z][a-z0-9_]*$": ogenregex.MustCompile("^[a-z][a-z0-9_]*$"),
"^\\S(?:.*\\S)?$": ogenregex.MustCompile("^\\S(?:.*\\S)?$"),
"^__Host-lincodex_session=": ogenregex.MustCompile("^__Host-lincodex_session="),
File diff suppressed because it is too large. Load diff
@@ -5,6 +5,14 @@ type ConfirmEmailRes interface {
confirmEmailRes()
}
type CreateMyAssessmentAttemptRes interface {
createMyAssessmentAttemptRes()
}
type FinalizeMyAssessmentAttemptRes interface {
finalizeMyAssessmentAttemptRes()
}
type GetConsentTextRes interface {
getConsentTextRes()
}
@@ -17,6 +25,18 @@ type GetCurrentSessionRes interface {
getCurrentSessionRes()
}
type GetMyAssessmentAttemptRes interface {
getMyAssessmentAttemptRes()
}
type GetMyAssessmentAvailabilityRes interface {
getMyAssessmentAvailabilityRes()
}
type GetMyAssessmentResultRes interface {
getMyAssessmentResultRes()
}
type GetMyQuestionnaireRes interface {
getMyQuestionnaireRes()
}
@@ -40,3 +60,7 @@ type ResendEmailVerificationRes interface {
type SaveMyQuestionnaireRes interface {
saveMyQuestionnaireRes()
}
type SubmitMyAssessmentAnswerRes interface {
submitMyAssessmentAnswerRes()
}
File diff suppressed because it is too large. Load diff
@@ -6,16 +6,22 @@ package api
type OperationName = string
const (
ConfirmEmailOperation OperationName = "ConfirmEmail"
GetConsentTextOperation OperationName = "GetConsentText"
GetCurrentAccountOperation OperationName = "GetCurrentAccount"
GetCurrentSessionOperation OperationName = "GetCurrentSession"
GetHealthzOperation OperationName = "GetHealthz"
GetMyQuestionnaireOperation OperationName = "GetMyQuestionnaire"
GetSpecializationCatalogOperation OperationName = "GetSpecializationCatalog"
LoginOperation OperationName = "Login"
LogoutOperation OperationName = "Logout"
RegisterAccountOperation OperationName = "RegisterAccount"
ResendEmailVerificationOperation OperationName = "ResendEmailVerification"
SaveMyQuestionnaireOperation OperationName = "SaveMyQuestionnaire"
ConfirmEmailOperation OperationName = "ConfirmEmail"
CreateMyAssessmentAttemptOperation OperationName = "CreateMyAssessmentAttempt"
FinalizeMyAssessmentAttemptOperation OperationName = "FinalizeMyAssessmentAttempt"
GetConsentTextOperation OperationName = "GetConsentText"
GetCurrentAccountOperation OperationName = "GetCurrentAccount"
GetCurrentSessionOperation OperationName = "GetCurrentSession"
GetHealthzOperation OperationName = "GetHealthz"
GetMyAssessmentAttemptOperation OperationName = "GetMyAssessmentAttempt"
GetMyAssessmentAvailabilityOperation OperationName = "GetMyAssessmentAvailability"
GetMyAssessmentResultOperation OperationName = "GetMyAssessmentResult"
GetMyQuestionnaireOperation OperationName = "GetMyQuestionnaire"
GetSpecializationCatalogOperation OperationName = "GetSpecializationCatalog"
LoginOperation OperationName = "Login"
LogoutOperation OperationName = "Logout"
RegisterAccountOperation OperationName = "RegisterAccount"
ResendEmailVerificationOperation OperationName = "ResendEmailVerification"
SaveMyQuestionnaireOperation OperationName = "SaveMyQuestionnaire"
SubmitMyAssessmentAnswerOperation OperationName = "SubmitMyAssessmentAnswer"
)
@@ -7,6 +7,7 @@ import (
"net/url"
"github.com/go-faster/errors"
"github.com/google/uuid"
"github.com/ogen-go/ogen/conv"
"github.com/ogen-go/ogen/middleware"
"github.com/ogen-go/ogen/ogenerrors"
@@ -14,6 +15,249 @@ import (
"github.com/ogen-go/ogen/validate"
)
// CreateMyAssessmentAttemptParams is parameters of CreateMyAssessmentAttempt operation.
type CreateMyAssessmentAttemptParams struct {
// 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 unpackCreateMyAssessmentAttemptParams(packed middleware.Parameters) (params CreateMyAssessmentAttemptParams) {
{
key := middleware.ParameterKey{
Name: "Idempotency-Key",
In: "header",
}
params.IdempotencyKey = packed[key].(string)
}
return params
}
func decodeCreateMyAssessmentAttemptParams(args [0]string, argsEscaped bool, r *http.Request) (params CreateMyAssessmentAttemptParams, _ error) {
h := uri.NewHeaderDecoder(r.Header)
// 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
}
// FinalizeMyAssessmentAttemptParams is parameters of FinalizeMyAssessmentAttempt operation.
type FinalizeMyAssessmentAttemptParams 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 unpackFinalizeMyAssessmentAttemptParams(packed middleware.Parameters) (params FinalizeMyAssessmentAttemptParams) {
{
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 decodeFinalizeMyAssessmentAttemptParams(args [1]string, argsEscaped bool, r *http.Request) (params FinalizeMyAssessmentAttemptParams, _ 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
}
// GetConsentTextParams is parameters of GetConsentText operation.
type GetConsentTextParams struct {
// Consent whose text is requested.
@@ -88,6 +332,140 @@ func decodeGetConsentTextParams(args [1]string, argsEscaped bool, r *http.Reques
return params, nil
}
// GetMyAssessmentAttemptParams is parameters of GetMyAssessmentAttempt operation.
type GetMyAssessmentAttemptParams 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
}
func unpackGetMyAssessmentAttemptParams(packed middleware.Parameters) (params GetMyAssessmentAttemptParams) {
{
key := middleware.ParameterKey{
Name: "attempt_id",
In: "path",
}
params.AttemptID = packed[key].(uuid.UUID)
}
return params
}
func decodeGetMyAssessmentAttemptParams(args [1]string, argsEscaped bool, r *http.Request) (params GetMyAssessmentAttemptParams, _ error) {
// 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,
}
}
return params, nil
}
// GetMyAssessmentResultParams is parameters of GetMyAssessmentResult operation.
type GetMyAssessmentResultParams 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
}
func unpackGetMyAssessmentResultParams(packed middleware.Parameters) (params GetMyAssessmentResultParams) {
{
key := middleware.ParameterKey{
Name: "attempt_id",
In: "path",
}
params.AttemptID = packed[key].(uuid.UUID)
}
return params
}
func decodeGetMyAssessmentResultParams(args [1]string, argsEscaped bool, r *http.Request) (params GetMyAssessmentResultParams, _ error) {
// 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,
}
}
return params, nil
}
// RegisterAccountParams is parameters of RegisterAccount operation.
type RegisterAccountParams struct {
// Client-generated key that makes a retried mutating command safe; a UUID v4 is recommended. The value
@@ -181,3 +559,152 @@ func decodeRegisterAccountParams(args [0]string, argsEscaped bool, r *http.Reque
}
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
// 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 unpackSubmitMyAssessmentAnswerParams(packed middleware.Parameters) (params SubmitMyAssessmentAnswerParams) {
{
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 decodeSubmitMyAssessmentAnswerParams(args [1]string, argsEscaped bool, r *http.Request) (params SubmitMyAssessmentAnswerParams, _ 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
}
@@ -93,6 +93,164 @@ func (s *Server) decodeConfirmEmailRequest(r *http.Request) (
}
}
func (s *Server) decodeCreateMyAssessmentAttemptRequest(r *http.Request) (
req *AssessmentAttemptCreate,
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 AssessmentAttemptCreate
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) decodeFinalizeMyAssessmentAttemptRequest(r *http.Request) (
req *AssessmentFinalization,
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 AssessmentFinalization
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) decodeLoginRequest(r *http.Request) (
req *LoginRequest,
rawBody []byte,
@@ -408,3 +566,82 @@ func (s *Server) decodeSaveMyQuestionnaireRequest(r *http.Request) (
return req, rawBody, close, validate.InvalidContentType(ct)
}
}
func (s *Server) decodeSubmitMyAssessmentAnswerRequest(r *http.Request) (
req *AssessmentAnswerSubmission,
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 AssessmentAnswerSubmission
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)
}
}
@@ -89,6 +89,252 @@ func encodeConfirmEmailResponse(response ConfirmEmailRes, w http.ResponseWriter,
}
}
func encodeCreateMyAssessmentAttemptResponse(response CreateMyAssessmentAttemptRes, 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(201)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *CreateMyAssessmentAttemptBadRequest:
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 *CreateMyAssessmentAttemptUnauthorized:
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 *CreateMyAssessmentAttemptForbidden:
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 *CreateMyAssessmentAttemptConflict:
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 *CreateMyAssessmentAttemptUnprocessableEntity:
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 encodeFinalizeMyAssessmentAttemptResponse(response FinalizeMyAssessmentAttemptRes, 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 *FinalizeMyAssessmentAttemptBadRequest:
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 *FinalizeMyAssessmentAttemptUnauthorized:
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 *FinalizeMyAssessmentAttemptForbidden:
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 *FinalizeMyAssessmentAttemptNotFound:
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 *FinalizeMyAssessmentAttemptConflict:
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 *FinalizeMyAssessmentAttemptPreconditionFailed:
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 *FinalizeMyAssessmentAttemptUnprocessableEntity:
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
default:
return errors.Errorf("unexpected response type: %T", response)
}
}
func encodeGetConsentTextResponse(response GetConsentTextRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *ConsentText:
@@ -227,6 +473,219 @@ func encodeGetHealthzResponse(response *HealthResponse, w http.ResponseWriter, s
return nil
}
func encodeGetMyAssessmentAttemptResponse(response GetMyAssessmentAttemptRes, 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 *GetMyAssessmentAttemptUnauthorized:
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 *GetMyAssessmentAttemptForbidden:
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 *GetMyAssessmentAttemptNotFound:
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
default:
return errors.Errorf("unexpected response type: %T", response)
}
}
func encodeGetMyAssessmentAvailabilityResponse(response GetMyAssessmentAvailabilityRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *AssessmentAvailabilityHeaders:
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 *GetMyAssessmentAvailabilityUnauthorized:
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 *GetMyAssessmentAvailabilityForbidden:
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
default:
return errors.Errorf("unexpected response type: %T", response)
}
}
func encodeGetMyAssessmentResultResponse(response GetMyAssessmentResultRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *AssessmentResultHeaders:
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 *GetMyAssessmentResultUnauthorized:
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 *GetMyAssessmentResultForbidden:
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 *GetMyAssessmentResultNotFound:
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 *GetMyAssessmentResultConflict:
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
default:
return errors.Errorf("unexpected response type: %T", response)
}
}
func encodeGetMyQuestionnaireResponse(response GetMyQuestionnaireRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *CandidateQuestionnaireHeaders:
@@ -742,6 +1201,157 @@ func encodeSaveMyQuestionnaireResponse(response SaveMyQuestionnaireRes, w http.R
}
}
func encodeSubmitMyAssessmentAnswerResponse(response SubmitMyAssessmentAnswerRes, 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 *SubmitMyAssessmentAnswerBadRequest:
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 *SubmitMyAssessmentAnswerUnauthorized:
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 *SubmitMyAssessmentAnswerForbidden:
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 *SubmitMyAssessmentAnswerNotFound:
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 *SubmitMyAssessmentAnswerConflict:
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 *SubmitMyAssessmentAnswerPreconditionFailed:
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 *SubmitMyAssessmentAnswerUnprocessableEntity:
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 encodeErrorResponse(response *ProblemStatusCode, w http.ResponseWriter, span trace.Span) error {
w.Header().Set("Content-Type", "application/problem+json")
code := response.StatusCode
@@ -11,22 +11,31 @@ import (
)
var (
rn14AllowedHeaders = map[string]string{
rn23AllowedHeaders = map[string]string{
"POST": "Content-Type",
}
rn1AllowedHeaders = map[string]string{
"POST": "Content-Type",
}
rn12AllowedHeaders = map[string]string{
rn21AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key",
}
rn11AllowedHeaders = map[string]string{
rn20AllowedHeaders = map[string]string{
"POST": "Content-Type",
}
rn6AllowedHeaders = map[string]string{
rn11AllowedHeaders = map[string]string{
"DELETE": "X-Csrf-Token",
}
rn9AllowedHeaders = map[string]string{
rn3AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn24AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn6AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn18AllowedHeaders = map[string]string{
"PUT": "Content-Type,X-Csrf-Token",
}
)
@@ -183,7 +192,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn14AllowedHeaders,
allowedHeaders: rn23AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -260,7 +269,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn12AllowedHeaders,
allowedHeaders: rn21AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -284,7 +293,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn11AllowedHeaders,
allowedHeaders: rn20AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -311,7 +320,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "DELETE,GET",
allowedHeaders: rn6AllowedHeaders,
allowedHeaders: rn11AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -324,31 +333,242 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
case 'm': // Prefix: "me/questionnaire"
case 'm': // Prefix: "me/"
if l := len("me/questionnaire"); len(elem) >= l && elem[0:l] == "me/questionnaire" {
if l := len("me/"); len(elem) >= l && elem[0:l] == "me/" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch r.Method {
case "GET":
s.handleGetMyQuestionnaireRequest([0]string{}, elemIsEscaped, w, r)
case "PUT":
s.handleSaveMyQuestionnaireRequest([0]string{}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET,PUT",
allowedHeaders: rn9AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
break
}
switch elem[0] {
case 'a': // Prefix: "assessment-a"
if l := len("assessment-a"); len(elem) >= l && elem[0:l] == "assessment-a" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
break
}
switch elem[0] {
case 't': // Prefix: "ttempts"
if l := len("ttempts"); len(elem) >= l && elem[0:l] == "ttempts" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
switch r.Method {
case "POST":
s.handleCreateMyAssessmentAttemptRequest([0]string{}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn3AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
}
return
}
switch elem[0] {
case '/': // Prefix: "/"
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
elem = elem[l:]
} else {
break
}
// Param: "attempt_id"
// Match until "/"
idx := strings.IndexByte(elem, '/')
if idx < 0 {
idx = len(elem)
}
args[0] = elem[:idx]
elem = elem[idx:]
if len(elem) == 0 {
switch r.Method {
case "GET":
s.handleGetMyAssessmentAttemptRequest([1]string{
args[0],
}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET",
allowedHeaders: nil,
acceptPost: "",
acceptPatch: "",
})
}
return
}
switch elem[0] {
case '/': // Prefix: "/"
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
break
}
switch elem[0] {
case 'a': // Prefix: "answers"
if l := len("answers"); len(elem) >= l && elem[0:l] == "answers" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch r.Method {
case "POST":
s.handleSubmitMyAssessmentAnswerRequest([1]string{
args[0],
}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn24AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
}
return
}
case 'f': // Prefix: "finalize"
if l := len("finalize"); len(elem) >= l && elem[0:l] == "finalize" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch r.Method {
case "POST":
s.handleFinalizeMyAssessmentAttemptRequest([1]string{
args[0],
}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn6AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
}
return
}
case 'r': // Prefix: "result"
if l := len("result"); len(elem) >= l && elem[0:l] == "result" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch r.Method {
case "GET":
s.handleGetMyAssessmentResultRequest([1]string{
args[0],
}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET",
allowedHeaders: nil,
acceptPost: "",
acceptPatch: "",
})
}
return
}
}
}
}
case 'v': // Prefix: "vailability"
if l := len("vailability"); len(elem) >= l && elem[0:l] == "vailability" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch r.Method {
case "GET":
s.handleGetMyAssessmentAvailabilityRequest([0]string{}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET",
allowedHeaders: nil,
acceptPost: "",
acceptPatch: "",
})
}
return
}
}
case 'q': // Prefix: "questionnaire"
if l := len("questionnaire"); len(elem) >= l && elem[0:l] == "questionnaire" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch r.Method {
case "GET":
s.handleGetMyQuestionnaireRequest([0]string{}, elemIsEscaped, w, r)
case "PUT":
s.handleSaveMyQuestionnaireRequest([0]string{}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET,PUT",
allowedHeaders: rn18AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
}
return
}
return
}
case 's': // Prefix: "specializations"
@@ -723,38 +943,241 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) {
}
case 'm': // Prefix: "me/questionnaire"
case 'm': // Prefix: "me/"
if l := len("me/questionnaire"); len(elem) >= l && elem[0:l] == "me/questionnaire" {
if l := len("me/"); len(elem) >= l && elem[0:l] == "me/" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch method {
case "GET":
r.name = GetMyQuestionnaireOperation
r.summary = "Read the questionnaire of the current candidate."
r.operationID = "GetMyQuestionnaire"
r.operationGroup = ""
r.pathPattern = "/api/v1/me/questionnaire"
r.args = args
r.count = 0
return r, true
case "PUT":
r.name = SaveMyQuestionnaireOperation
r.summary = "Replace the questionnaire of the current candidate."
r.operationID = "SaveMyQuestionnaire"
r.operationGroup = ""
r.pathPattern = "/api/v1/me/questionnaire"
r.args = args
r.count = 0
return r, true
default:
return
break
}
switch elem[0] {
case 'a': // Prefix: "assessment-a"
if l := len("assessment-a"); len(elem) >= l && elem[0:l] == "assessment-a" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
break
}
switch elem[0] {
case 't': // Prefix: "ttempts"
if l := len("ttempts"); len(elem) >= l && elem[0:l] == "ttempts" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
switch method {
case "POST":
r.name = CreateMyAssessmentAttemptOperation
r.summary = "Start an assessment attempt for a category of the current candidate."
r.operationID = "CreateMyAssessmentAttempt"
r.operationGroup = ""
r.pathPattern = "/api/v1/me/assessment-attempts"
r.args = args
r.count = 0
return r, true
default:
return
}
}
switch elem[0] {
case '/': // Prefix: "/"
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
elem = elem[l:]
} else {
break
}
// Param: "attempt_id"
// Match until "/"
idx := strings.IndexByte(elem, '/')
if idx < 0 {
idx = len(elem)
}
args[0] = elem[:idx]
elem = elem[idx:]
if len(elem) == 0 {
switch method {
case "GET":
r.name = GetMyAssessmentAttemptOperation
r.summary = "Read or resume an assessment attempt of the current candidate."
r.operationID = "GetMyAssessmentAttempt"
r.operationGroup = ""
r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}"
r.args = args
r.count = 1
return r, true
default:
return
}
}
switch elem[0] {
case '/': // Prefix: "/"
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
break
}
switch elem[0] {
case 'a': // Prefix: "answers"
if l := len("answers"); len(elem) >= l && elem[0:l] == "answers" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch method {
case "POST":
r.name = SubmitMyAssessmentAnswerOperation
r.summary = "Answer the current item or submit a practice of an assessment attempt."
r.operationID = "SubmitMyAssessmentAnswer"
r.operationGroup = ""
r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}/answers"
r.args = args
r.count = 1
return r, true
default:
return
}
}
case 'f': // Prefix: "finalize"
if l := len("finalize"); len(elem) >= l && elem[0:l] == "finalize" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch method {
case "POST":
r.name = FinalizeMyAssessmentAttemptOperation
r.summary = "Ask for the grade decision of an assessment attempt."
r.operationID = "FinalizeMyAssessmentAttempt"
r.operationGroup = ""
r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}/finalize"
r.args = args
r.count = 1
return r, true
default:
return
}
}
case 'r': // Prefix: "result"
if l := len("result"); len(elem) >= l && elem[0:l] == "result" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch method {
case "GET":
r.name = GetMyAssessmentResultOperation
r.summary = "Read the result of an assessment attempt of the current candidate."
r.operationID = "GetMyAssessmentResult"
r.operationGroup = ""
r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}/result"
r.args = args
r.count = 1
return r, true
default:
return
}
}
}
}
}
case 'v': // Prefix: "vailability"
if l := len("vailability"); len(elem) >= l && elem[0:l] == "vailability" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch method {
case "GET":
r.name = GetMyAssessmentAvailabilityOperation
r.summary = "Read which assessment attempts the current candidate can start."
r.operationID = "GetMyAssessmentAvailability"
r.operationGroup = ""
r.pathPattern = "/api/v1/me/assessment-availability"
r.args = args
r.count = 0
return r, true
default:
return
}
}
}
case 'q': // Prefix: "questionnaire"
if l := len("questionnaire"); len(elem) >= l && elem[0:l] == "questionnaire" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch method {
case "GET":
r.name = GetMyQuestionnaireOperation
r.summary = "Read the questionnaire of the current candidate."
r.operationID = "GetMyQuestionnaire"
r.operationGroup = ""
r.pathPattern = "/api/v1/me/questionnaire"
r.args = args
r.count = 0
return r, true
case "PUT":
r.name = SaveMyQuestionnaireOperation
r.summary = "Replace the questionnaire of the current candidate."
r.operationID = "SaveMyQuestionnaire"
r.operationGroup = ""
r.pathPattern = "/api/v1/me/questionnaire"
r.args = args
r.count = 0
return r, true
default:
return
}
}
}
case 's': // Prefix: "specializations"
File diff suppressed because it is too large. Load diff
@@ -56,11 +56,17 @@ func findAuthorization(h http.Header, prefix string) (string, bool) {
// operationRolesSessionCookie is a private map storing roles per operation.
var operationRolesSessionCookie = map[string][]string{
GetCurrentAccountOperation: []string{},
GetCurrentSessionOperation: []string{},
GetMyQuestionnaireOperation: []string{},
LogoutOperation: []string{},
SaveMyQuestionnaireOperation: []string{},
CreateMyAssessmentAttemptOperation: []string{},
FinalizeMyAssessmentAttemptOperation: []string{},
GetCurrentAccountOperation: []string{},
GetCurrentSessionOperation: []string{},
GetMyAssessmentAttemptOperation: []string{},
GetMyAssessmentAvailabilityOperation: []string{},
GetMyAssessmentResultOperation: []string{},
GetMyQuestionnaireOperation: []string{},
LogoutOperation: []string{},
SaveMyQuestionnaireOperation: []string{},
SubmitMyAssessmentAnswerOperation: []string{},
}
// GetRolesForSessionCookie returns the required roles for the given operation.
@@ -86,8 +92,11 @@ func GetRolesForSessionCookie(operation string) []string {
// operationRolesSessionCsrf is a private map storing roles per operation.
var operationRolesSessionCsrf = map[string][]string{
LogoutOperation: []string{},
SaveMyQuestionnaireOperation: []string{},
CreateMyAssessmentAttemptOperation: []string{},
FinalizeMyAssessmentAttemptOperation: []string{},
LogoutOperation: []string{},
SaveMyQuestionnaireOperation: []string{},
SubmitMyAssessmentAnswerOperation: []string{},
}
// GetRolesForSessionCsrf returns the required roles for the given operation.
@@ -35,6 +35,91 @@ type Handler interface {
//
// POST /api/v1/identity/email-verifications
ConfirmEmail(ctx context.Context, req *EmailVerificationRequest) (ConfirmEmailRes, error)
// 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.
//
// 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.
//
// 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.
//
// 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.
//
// POST /api/v1/me/assessment-attempts
CreateMyAssessmentAttempt(ctx context.Context, req *AssessmentAttemptCreate, params CreateMyAssessmentAttemptParams) (CreateMyAssessmentAttemptRes, error)
// FinalizeMyAssessmentAttempt implements FinalizeMyAssessmentAttempt 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. 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.
//
// 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.
//
// 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.
//
// POST /api/v1/me/assessment-attempts/{attempt_id}/finalize
FinalizeMyAssessmentAttempt(ctx context.Context, req *AssessmentFinalization, params FinalizeMyAssessmentAttemptParams) (FinalizeMyAssessmentAttemptRes, error)
// GetConsentText implements GetConsentText operation.
//
// Public operation without a session. Returns the current text of a consent that is given before an
@@ -71,6 +156,71 @@ type Handler interface {
//
// GET /api/v1/healthz
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.
//
// 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.
//
// 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.
//
// GET /api/v1/me/assessment-attempts/{attempt_id}
GetMyAssessmentAttempt(ctx context.Context, params GetMyAssessmentAttemptParams) (GetMyAssessmentAttemptRes, error)
// GetMyAssessmentAvailability implements GetMyAssessmentAvailability operation.
//
// Requires the session cookie of a candidate account; the candidate comes from the session. For each
// specialization of the questionnaire, returns the confirmed grade, the active attempt, and for every
// grade whether an attempt can start now, in which mode, and with which limits: the time limit, the
// session limit, the item limit, and whether a code practice is required. The client shows them before
// the start, together with the method and the signals that are collected, and resumes an active
// attempt by `active_attempt_id`, for example after it lost the response of CreateMyAssessmentAttempt.
//
// `insufficient_bank` is the state of a category whose bank is not published or has too few families
// that this candidate has not seen; the server limits attempts instead of repeating families.
// `cooldown` carries the date when the attempt opens, so the client can explain a blocked attempt with
// that date and offer support. Specializations and their retry intervals are independent. Attempts
// that ended as `insufficient_bank` or with the reason `sandbox_unavailable` are platform limitations
// and never cause a `cooldown`.
//
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account
// answers 403 forbidden.
//
// GET /api/v1/me/assessment-availability
GetMyAssessmentAvailability(ctx context.Context) (GetMyAssessmentAvailabilityRes, error)
// 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.
//
// 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.
//
// GET /api/v1/me/assessment-attempts/{attempt_id}/result
GetMyAssessmentResult(ctx context.Context, params GetMyAssessmentResultParams) (GetMyAssessmentResultRes, error)
// GetMyQuestionnaire implements GetMyQuestionnaire operation.
//
// Requires the session cookie of a candidate account. The candidate comes from the session, never from
@@ -234,6 +384,63 @@ type Handler interface {
//
// PUT /api/v1/me/questionnaire
SaveMyQuestionnaire(ctx context.Context, req *CandidateQuestionnaireUpdate) (SaveMyQuestionnaireRes, error)
// SubmitMyAssessmentAnswer implements SubmitMyAssessmentAnswer 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 item and carries the answer in the
// format of that item: `choice`, `number`, `string`, `order`, `find_error`, `configuration`, or
// `practice`. It never carries a score, a duration, or a correctness flag; the server records the
// times itself and scores the answer with the key of the fixed item instance. Time never enters the
// ability estimate or the grade decision.
//
// 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.
//
// 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:
//
// - A retry with the same Idempotency-Key and body within 24 hours replays the stored response.
// - Sending the answer already stored for the item again, even with a new key or an older
// `expected_version`, stores nothing, keeps the version, and answers 200 with the current attempt.
// Each answer format defines equality: 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 item that already has one answers 409 state_conflict when
// `expected_version` is current; with a stale version the version check comes first and answers
// 412.
// - Exception for a practice whose latest verdict is `failed`: the repeat rule does not apply. A
// submission with the same or a different solution, with the current `expected_version`, queues it
// again and advances the version.
//
// 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.
//
// POST /api/v1/me/assessment-attempts/{attempt_id}/answers
SubmitMyAssessmentAnswer(ctx context.Context, req *AssessmentAnswerSubmission, params SubmitMyAssessmentAnswerParams) (SubmitMyAssessmentAnswerRes, error)
// NewError creates *ProblemStatusCode from error returned by handler.
//
// Used for common default response.
@@ -43,6 +43,97 @@ func (UnimplementedHandler) ConfirmEmail(ctx context.Context, req *EmailVerifica
return r, ht.ErrNotImplemented
}
// 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.
//
// 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.
//
// 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.
//
// 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.
//
// POST /api/v1/me/assessment-attempts
func (UnimplementedHandler) CreateMyAssessmentAttempt(ctx context.Context, req *AssessmentAttemptCreate, params CreateMyAssessmentAttemptParams) (r CreateMyAssessmentAttemptRes, _ error) {
return r, ht.ErrNotImplemented
}
// FinalizeMyAssessmentAttempt implements FinalizeMyAssessmentAttempt 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. 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.
//
// 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.
//
// 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.
//
// POST /api/v1/me/assessment-attempts/{attempt_id}/finalize
func (UnimplementedHandler) FinalizeMyAssessmentAttempt(ctx context.Context, req *AssessmentFinalization, params FinalizeMyAssessmentAttemptParams) (r FinalizeMyAssessmentAttemptRes, _ error) {
return r, ht.ErrNotImplemented
}
// GetConsentText implements GetConsentText operation.
//
// Public operation without a session. Returns the current text of a consent that is given before an
@@ -91,6 +182,80 @@ func (UnimplementedHandler) GetHealthz(ctx context.Context) (r *HealthResponse,
return r, ht.ErrNotImplemented
}
// 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.
//
// 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.
//
// 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.
//
// GET /api/v1/me/assessment-attempts/{attempt_id}
func (UnimplementedHandler) GetMyAssessmentAttempt(ctx context.Context, params GetMyAssessmentAttemptParams) (r GetMyAssessmentAttemptRes, _ error) {
return r, ht.ErrNotImplemented
}
// GetMyAssessmentAvailability implements GetMyAssessmentAvailability operation.
//
// Requires the session cookie of a candidate account; the candidate comes from the session. For each
// specialization of the questionnaire, returns the confirmed grade, the active attempt, and for every
// grade whether an attempt can start now, in which mode, and with which limits: the time limit, the
// session limit, the item limit, and whether a code practice is required. The client shows them before
// the start, together with the method and the signals that are collected, and resumes an active
// attempt by `active_attempt_id`, for example after it lost the response of CreateMyAssessmentAttempt.
//
// `insufficient_bank` is the state of a category whose bank is not published or has too few families
// that this candidate has not seen; the server limits attempts instead of repeating families.
// `cooldown` carries the date when the attempt opens, so the client can explain a blocked attempt with
// that date and offer support. Specializations and their retry intervals are independent. Attempts
// that ended as `insufficient_bank` or with the reason `sandbox_unavailable` are platform limitations
// and never cause a `cooldown`.
//
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account
// answers 403 forbidden.
//
// GET /api/v1/me/assessment-availability
func (UnimplementedHandler) GetMyAssessmentAvailability(ctx context.Context) (r GetMyAssessmentAvailabilityRes, _ error) {
return r, ht.ErrNotImplemented
}
// 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.
//
// 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.
//
// GET /api/v1/me/assessment-attempts/{attempt_id}/result
func (UnimplementedHandler) GetMyAssessmentResult(ctx context.Context, params GetMyAssessmentResultParams) (r GetMyAssessmentResultRes, _ error) {
return r, ht.ErrNotImplemented
}
// GetMyQuestionnaire implements GetMyQuestionnaire operation.
//
// Requires the session cookie of a candidate account. The candidate comes from the session, never from
@@ -275,6 +440,66 @@ func (UnimplementedHandler) SaveMyQuestionnaire(ctx context.Context, req *Candid
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,
// an allowed Origin, and an Idempotency-Key. The body names the item and carries the answer in the
// format of that item: `choice`, `number`, `string`, `order`, `find_error`, `configuration`, or
// `practice`. It never carries a score, a duration, or a correctness flag; the server records the
// times itself and scores the answer with the key of the fixed item instance. Time never enters the
// ability estimate or the grade decision.
//
// 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.
//
// 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:
//
// - A retry with the same Idempotency-Key and body within 24 hours replays the stored response.
// - Sending the answer already stored for the item again, even with a new key or an older
// `expected_version`, stores nothing, keeps the version, and answers 200 with the current attempt.
// Each answer format defines equality: 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 item that already has one answers 409 state_conflict when
// `expected_version` is current; with a stale version the version check comes first and answers
// 412.
// - Exception for a practice whose latest verdict is `failed`: the repeat rule does not apply. A
// submission with the same or a different solution, with the current `expected_version`, queues it
// again and advances the version.
//
// 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.
//
// POST /api/v1/me/assessment-attempts/{attempt_id}/answers
func (UnimplementedHandler) SubmitMyAssessmentAnswer(ctx context.Context, req *AssessmentAnswerSubmission, params SubmitMyAssessmentAnswerParams) (r SubmitMyAssessmentAnswerRes, _ error) {
return r, ht.ErrNotImplemented
}
// NewError creates *ProblemStatusCode from error returned by handler.
//
// Used for common default response.
File diff suppressed because it is too large. Load diff
@@ -564,6 +564,198 @@ func TestCatalogAndQuestionnaireAccessBeforeImplementation(t *testing.T) {
}
}
// Assessment request fixtures shared by the assessment tests.
const (
assessmentAttemptsPath = "/api/v1/me/assessment-attempts"
assessmentAttemptPath = assessmentAttemptsPath + "/01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b"
assessmentAnswersPath = assessmentAttemptPath + "/answers"
assessmentFinalizePath = assessmentAttemptPath + "/finalize"
assessmentResultPath = assessmentAttemptPath + "/result"
assessmentItemID = "01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d01"
validAttemptCreate = `{"specialization":"backend","target_grade":"junior","task_language":"go"}`
)
// assessmentAnswerBody returns a SubmitMyAssessmentAnswer body for version 1
// of the attempt with the given answer.
func assessmentAnswerBody(answer string) string {
return `{"expected_version":1,"item_id":"` + assessmentItemID + `","answer":` + answer + `}`
}
// The schema alone must accept every answer format of FR05 and reject what a
// candidate may never send: a score, a seed, a mode, a format mixed with the
// fields of another format, or a missing version or Idempotency-Key. Security
// accepts the session here, so the request reaches validation; a valid request
// then answers 501 until the assessment is implemented.
func TestAssessmentSchemaValidationPrecedesImplementation(t *testing.T) {
session := map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken}
command := map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken, "Idempotency-Key": testIdempotencyKey}
for _, test := range []struct {
name string
request identityRequest
location api.ProblemFieldLocation
pointer string
code string
}{
{
name: "availability",
request: identityRequest{method: http.MethodGet, path: "/api/v1/me/assessment-availability", headers: session},
},
{
name: "create",
request: identityRequest{method: http.MethodPost, path: assessmentAttemptsPath, body: validAttemptCreate, headers: command},
},
{
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},
},
{
// The server picks the mode from the published bank.
name: "create with a mode chosen by the client",
request: identityRequest{method: http.MethodPost, path: assessmentAttemptsPath, body: strings.Replace(validAttemptCreate, `}`, `,"mode":"demo_basic"}`, 1), headers: command},
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
},
{
name: "create for a grade outside the MVP scale",
request: identityRequest{method: http.MethodPost, path: assessmentAttemptsPath, body: strings.Replace(validAttemptCreate, `"junior"`, `"lead"`, 1), headers: command},
location: api.ProblemFieldLocationBody, pointer: "/target_grade", code: "invalid",
},
{
name: "create without an Idempotency-Key",
request: identityRequest{method: http.MethodPost, path: assessmentAttemptsPath, body: validAttemptCreate, headers: session},
location: api.ProblemFieldLocationHeader, pointer: "/Idempotency-Key", code: "required",
},
{
name: "resume",
request: identityRequest{method: http.MethodGet, path: assessmentAttemptPath, headers: session},
},
{
name: "resume with an identifier that is not a UUID",
request: identityRequest{method: http.MethodGet, path: assessmentAttemptsPath + "/1", headers: session},
location: api.ProblemFieldLocationPath, pointer: "/attempt_id", code: "invalid",
},
{
name: "choice answer",
request: identityRequest{method: http.MethodPost, path: assessmentAnswersPath, body: assessmentAnswerBody(`{"format":"choice","option_ids":["x9"]}`), headers: command},
},
{
name: "number answer",
request: identityRequest{method: http.MethodPost, path: assessmentAnswersPath, body: assessmentAnswerBody(`{"format":"number","number":254}`), headers: command},
},
{
name: "string answer",
request: identityRequest{method: http.MethodPost, path: assessmentAnswersPath, body: assessmentAnswerBody(`{"format":"string","text":"Retry-After"}`), headers: command},
},
{
name: "order answer",
request: identityRequest{method: http.MethodPost, path: assessmentAnswersPath, body: assessmentAnswerBody(`{"format":"order","element_ids":["b1","a7","d3"]}`), headers: command},
},
{
name: "find-error answer",
request: identityRequest{method: http.MethodPost, path: assessmentAnswersPath, body: assessmentAnswerBody(`{"format":"find_error","line_numbers":[5]}`), headers: command},
},
{
name: "configuration answer",
request: identityRequest{method: http.MethodPost, path: assessmentAnswersPath, body: assessmentAnswerBody(`{"format":"configuration","config":"interface Gi0/1"}`), headers: command},
},
{
name: "practice answer",
request: identityRequest{method: http.MethodPost, path: assessmentAnswersPath, body: assessmentAnswerBody(`{"format":"practice","language":"python","source_code":"print(1)"}`), headers: command},
},
{
// The server scores the answer with the key of the item instance.
name: "answer with a score set by the candidate",
request: identityRequest{method: http.MethodPost, path: assessmentAnswersPath, body: strings.Replace(assessmentAnswerBody(`{"format":"choice","option_ids":["x9"]}`), `{"expected_version"`, `{"score":1,"expected_version"`, 1), headers: command},
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
},
{
name: "practice answer with a seed",
request: identityRequest{method: http.MethodPost, path: assessmentAnswersPath, body: assessmentAnswerBody(`{"format":"practice","language":"python","source_code":"print(1)","seed":42}`), headers: command},
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
},
{
name: "format with the fields of another format",
request: identityRequest{method: http.MethodPost, path: assessmentAnswersPath, body: assessmentAnswerBody(`{"format":"choice","number":254}`), headers: command},
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
},
{
name: "unknown answer format",
request: identityRequest{method: http.MethodPost, path: assessmentAnswersPath, body: assessmentAnswerBody(`{"format":"essay","text":"..."}`), headers: command},
location: api.ProblemFieldLocationBody, pointer: "/answer/format", code: "invalid",
},
{
name: "choice answer without an option",
request: identityRequest{method: http.MethodPost, path: assessmentAnswersPath, body: assessmentAnswerBody(`{"format":"choice","option_ids":[]}`), headers: command},
location: api.ProblemFieldLocationBody, pointer: "/answer/option_ids", code: "invalid",
},
{
name: "answer without an expected version",
request: identityRequest{method: http.MethodPost, path: assessmentAnswersPath, body: `{"item_id":"` + assessmentItemID + `","answer":{"format":"number","number":1}}`, headers: command},
location: api.ProblemFieldLocationBody, pointer: "/expected_version", code: "required",
},
{
name: "answer without an Idempotency-Key",
request: identityRequest{method: http.MethodPost, path: assessmentAnswersPath, body: assessmentAnswerBody(`{"format":"number","number":1}`), headers: session},
location: api.ProblemFieldLocationHeader, pointer: "/Idempotency-Key", code: "required",
},
{
name: "finalize",
request: identityRequest{method: http.MethodPost, path: assessmentFinalizePath, body: `{"expected_version":17}`, headers: command},
},
{
name: "finalize with version zero",
request: identityRequest{method: http.MethodPost, path: assessmentFinalizePath, body: `{"expected_version":0}`, headers: command},
location: api.ProblemFieldLocationBody, pointer: "/expected_version", code: "invalid",
},
{
name: "result",
request: identityRequest{method: http.MethodGet, path: assessmentResultPath, headers: session},
},
} {
t.Run(test.name, func(t *testing.T) {
logger := slog.New(slog.DiscardHandler)
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
response := serveIdentityRequest(t, router, test.request)
if test.code == "" {
requireProblem(t, response, http.StatusNotImplemented, api.ProblemCodeNotImplemented)
return
}
body := requireProblem(t, response, http.StatusBadRequest, api.ProblemCodeValidationFailed)
want := api.ProblemFieldError{In: test.location, Pointer: test.pointer, Code: test.code}
for _, field := range body.Errors {
if field.In == want.In && field.Pointer == want.Pointer && field.Code == want.Code {
return
}
}
t.Fatalf("errors = %+v, want an entry %+v", body.Errors, want)
})
}
}
// Every assessment operation requires a candidate session; DenyAllSecurity
// grants none, with or without a cookie and a CSRF token.
func TestAssessmentAccessBeforeImplementation(t *testing.T) {
command := map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken, "Idempotency-Key": testIdempotencyKey}
for _, test := range []identityRequest{
{method: http.MethodGet, path: "/api/v1/me/assessment-availability"},
{method: http.MethodPost, path: assessmentAttemptsPath, body: validAttemptCreate, headers: command},
{method: http.MethodGet, path: assessmentAttemptPath},
{method: http.MethodGet, path: assessmentAttemptPath, headers: map[string]string{"Cookie": testSessionCookie}},
{method: http.MethodPost, path: assessmentAnswersPath, body: assessmentAnswerBody(`{"format":"number","number":1}`), headers: command},
{method: http.MethodPost, path: assessmentFinalizePath, body: `{"expected_version":1}`, headers: command},
{method: http.MethodGet, path: assessmentResultPath},
} {
t.Run(test.method+" "+test.path, func(t *testing.T) {
router := newTestRouter(t, func(context.Context) error { return nil })
requireProblem(t, serveIdentityRequest(t, router, test), http.StatusUnauthorized, api.ProblemCodeUnauthenticated)
})
}
}
func TestPublicOperationInternalErrorIsLoggedButNotExposed(t *testing.T) {
var logs bytes.Buffer
logger := slog.New(slog.NewJSONHandler(&logs, nil))
@@ -0,0 +1,113 @@
import { describe, expect, expectTypeOf, it } from "vitest";
import { submitMyAssessmentAnswer } from "./endpoints/assessment/assessment";
import {
AssessmentAnswerSubmission,
AssessmentItem,
ItemContent,
SubmitMyAssessmentAnswerBody,
} from "./schemas";
// These tests pin the generated assessment contract that the FSD adapters
// consume. They fail when regeneration drops an answer format or adds a field
// that would carry a score, a key, or a seed between the client and the server.
const itemId = "01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d01";
const answers = {
choice: { format: "choice", option_ids: ["x9"] },
number: { format: "number", number: 254 },
string: { format: "string", text: "Retry-After" },
order: { format: "order", element_ids: ["a7", "b1", "c2", "d3"] },
find_error: { format: "find_error", line_numbers: [5] },
configuration: { format: "configuration", config: "interface Gi0/1" },
practice: { format: "practice", language: "python", source_code: "print(1)" },
} as const;
const bodySchemas = [
["AssessmentAnswerSubmission", AssessmentAnswerSubmission],
["SubmitMyAssessmentAnswerBody", SubmitMyAssessmentAnswerBody],
] as const;
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 });
expect(parsed.answer.format).toBe(format);
});
it("rejects an unknown answer format", () => {
const result = schema.safeParse({
expected_version: 1,
item_id: itemId,
answer: { format: "essay", text: "..." },
});
expect(result.success).toBe(false);
});
it("rejects version 0, which no attempt has", () => {
const result = schema.safeParse({
expected_version: 0,
item_id: itemId,
answer: answers.choice,
});
expect(result.success).toBe(false);
expect(result.error?.issues).toEqual([expect.objectContaining({ path: ["expected_version"] })]);
});
it("never carries a client score or seed in the parsed body", () => {
const parsed = schema.parse({
expected_version: 1,
item_id: itemId,
score: 1,
answer: { ...answers.practice, seed: 42 },
});
// Generated Zod strips unknown keys; the server rejects them with 400.
expect(parsed).not.toHaveProperty("score");
expect(parsed.answer).not.toHaveProperty("seed");
});
});
it("parses a practice item without hidden checks", () => {
const parsed = AssessmentItem.parse({
id: itemId,
sequence: 15,
prompt: "Реализуйте функцию merge_intervals.",
content: {
format: "practice",
languages: ["python"],
max_source_length: 20000,
public_examples: [{ input: "[[1,3],[2,6]]", expected_output: "[[1,6]]" }],
hidden_tests: [{ input: "secret" }],
},
});
expect(parsed.content.format).toBe("practice");
expect(parsed.content).not.toHaveProperty("hidden_tests");
});
// Every key of every variant of a union.
type KeysOf<T> = T extends unknown ? keyof T : never;
type ForbiddenKey =
| "score"
| "points"
| "seed"
| "key"
| "answer_key"
| "correct"
| "is_correct"
| "correct_option_ids"
| "hidden_tests"
| "family_id";
it("exposes answer and item DTOs without scores, keys, seeds, or correctness", () => {
expectTypeOf<Extract<KeysOf<AssessmentAnswerSubmission>, ForbiddenKey>>().toEqualTypeOf<never>();
expectTypeOf<
Extract<KeysOf<AssessmentAnswerSubmission["answer"]>, ForbiddenKey>
>().toEqualTypeOf<never>();
expectTypeOf<Extract<KeysOf<AssessmentItem>, ForbiddenKey>>().toEqualTypeOf<never>();
expectTypeOf<Extract<KeysOf<ItemContent>, ForbiddenKey>>().toEqualTypeOf<never>();
expectTypeOf(submitMyAssessmentAnswer).parameter(1).toEqualTypeOf<AssessmentAnswerSubmission>();
});
@@ -0,0 +1,230 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import {
faker
} from '@faker-js/faker';
import {
HttpResponse,
http
} from 'msw';
import type {
RequestHandlerOptions
} from 'msw';
import {
AssessmentAttemptState,
AssessmentGradeAvailabilityStatus,
AssessmentLimitation,
AssessmentMode,
AssessmentNextAction,
AssessmentNotDeterminedReason,
AssessmentOutcome,
AssessmentStrength,
CalibrationStatus,
GradeCode,
PracticeFailureReason,
PracticeKind,
PracticeStatus,
SpecializationCode,
TaskLanguage
} from '../../schemas';
import type {
AssessmentAttempt,
AssessmentAvailability,
AssessmentItem,
AssessmentResult,
AssessmentSessions,
AssessmentUncertainty,
BasicScore,
ChoiceItemContent,
ConfigurationItemContent,
FindErrorItemContent,
NumberItemContent,
OrderItemContent,
PracticeItemContent,
PracticeVerdict,
StringItemContent
} from '../../schemas';
export const getGetMyAssessmentAvailabilityResponseMock = (overrideResponse: Partial<Extract<AssessmentAvailability, object>> = {}): AssessmentAvailability => ({specializations: Array.from({ length: faker.number.int({min: 1, max: 2}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(Object.values(SpecializationCode)), confirmed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(GradeCode)),null,]), active_attempt_id: faker.helpers.arrayElement([faker.string.uuid(), null]), grades: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({grade: faker.helpers.arrayElement(Object.values(GradeCode)), status: faker.helpers.arrayElement(Object.values(AssessmentGradeAvailabilityStatus)), mode: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(AssessmentMode)),null,]), available_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), time_limit_seconds: faker.helpers.arrayElement([faker.number.int({min: 1}), null]), max_sessions: faker.helpers.arrayElement([faker.number.int({min: 1, max: 10}), null]), max_items: faker.helpers.arrayElement([faker.number.int({min: 1, max: 100}), null]), practice_required: faker.helpers.arrayElement([faker.datatype.boolean(), null])}))})), ...overrideResponse})
export const getCreateMyAssessmentAttemptResponseAssessmentSessionsMock = (overrideResponse: Partial<AssessmentSessions> = {}): 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 getCreateMyAssessmentAttemptResponseChoiceItemContentMock = (overrideResponse: Partial<ChoiceItemContent> = {}): ChoiceItemContent => ({...{format: faker.helpers.arrayElement(['choice'] as const), options: Array.from({ length: faker.number.int({min: 2, max: 10}) }, (_, i) => i + 1).map(() => ({id: faker.helpers.fromRegExp("^[A-Za-z0-9_-]+$"), text: faker.string.alpha({length: {min: 1, max: 2000}})})), multiple: faker.datatype.boolean()}, ...overrideResponse});
export const getCreateMyAssessmentAttemptResponseNumberItemContentMock = (overrideResponse: Partial<NumberItemContent> = {}): NumberItemContent => ({...{format: faker.helpers.arrayElement(['number'] as const), unit: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 32}}), null])}, ...overrideResponse});
export const getCreateMyAssessmentAttemptResponseStringItemContentMock = (overrideResponse: Partial<StringItemContent> = {}): StringItemContent => ({...{format: faker.helpers.arrayElement(['string'] as const), max_length: faker.number.int({min: 1, max: 500})}, ...overrideResponse});
export const getCreateMyAssessmentAttemptResponseOrderItemContentMock = (overrideResponse: Partial<OrderItemContent> = {}): OrderItemContent => ({...{format: faker.helpers.arrayElement(['order'] as const), elements: Array.from({ length: faker.number.int({min: 2, max: 20}) }, (_, i) => i + 1).map(() => ({id: faker.helpers.fromRegExp("^[A-Za-z0-9_-]+$"), text: faker.string.alpha({length: {min: 1, max: 2000}})}))}, ...overrideResponse});
export const getCreateMyAssessmentAttemptResponseFindErrorItemContentMock = (overrideResponse: Partial<FindErrorItemContent> = {}): FindErrorItemContent => ({...{format: faker.helpers.arrayElement(['find_error'] as const), syntax: faker.helpers.arrayElement([faker.helpers.fromRegExp("^[a-z0-9_+-]+$"), 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 getCreateMyAssessmentAttemptResponseConfigurationItemContentMock = (overrideResponse: Partial<ConfigurationItemContent> = {}): ConfigurationItemContent => ({...{format: faker.helpers.arrayElement(['configuration'] as const), syntax: faker.helpers.fromRegExp("^[a-z0-9_+-]+$"), initial_config: faker.string.alpha({length: {min: 10, max: 20000}}), max_length: faker.number.int({min: 1, max: 20000})}, ...overrideResponse});
export const getCreateMyAssessmentAttemptResponsePracticeItemContentMock = (overrideResponse: Partial<PracticeItemContent> = {}): PracticeItemContent => ({...{format: faker.helpers.arrayElement(['practice'] as const), languages: faker.helpers.arrayElements(Object.values(TaskLanguage)), 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 getCreateMyAssessmentAttemptResponseAssessmentItemMock = (overrideResponse: Partial<AssessmentItem> = {}): 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([{...getCreateMyAssessmentAttemptResponseChoiceItemContentMock()},{...getCreateMyAssessmentAttemptResponseNumberItemContentMock()},{...getCreateMyAssessmentAttemptResponseStringItemContentMock()},{...getCreateMyAssessmentAttemptResponseOrderItemContentMock()},{...getCreateMyAssessmentAttemptResponseFindErrorItemContentMock()},{...getCreateMyAssessmentAttemptResponseConfigurationItemContentMock()},{...getCreateMyAssessmentAttemptResponsePracticeItemContentMock()},])}, ...overrideResponse});
export const getCreateMyAssessmentAttemptResponsePracticeVerdictMock = (overrideResponse: Partial<PracticeVerdict> = {}): PracticeVerdict => ({...{score: faker.number.int({min: 0, max: 3}), max_score: faker.number.int({min: 3, max: 3}), groups: Array.from({ length: faker.number.int({min: 3, max: 3}) }, (_, i) => i + 1).map(() => ({group: faker.number.int({min: 1, max: 3}), passed: faker.datatype.boolean()}))}, ...overrideResponse});
export const getCreateMyAssessmentAttemptResponseMock = (overrideResponse: Partial<Extract<AssessmentAttempt, object>> = {}): AssessmentAttempt => ({id: faker.string.uuid(), version: faker.number.int({min: 1}), specialization: faker.helpers.arrayElement(Object.values(SpecializationCode)), target_grade: faker.helpers.arrayElement(Object.values(GradeCode)), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(TaskLanguage)),null,]), mode: faker.helpers.arrayElement(Object.values(AssessmentMode)), state: faker.helpers.arrayElement(Object.values(AssessmentAttemptState)), versions: {policy_version: faker.number.int({min: 1}), bank_version: faker.helpers.fromRegExp("^[A-Za-z0-9._-]+$"), algorithm_version: faker.helpers.fromRegExp("^[A-Za-z0-9._-]+$")}, 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(Object.values(PracticeKind)), item_id: faker.string.uuid(), status: faker.helpers.arrayElement(Object.values(PracticeStatus)), 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(Object.values(PracticeFailureReason)),null,])})), ...overrideResponse})
export const getGetMyAssessmentAttemptResponseAssessmentSessionsMock = (overrideResponse: Partial<AssessmentSessions> = {}): 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 getGetMyAssessmentAttemptResponseChoiceItemContentMock = (overrideResponse: Partial<ChoiceItemContent> = {}): ChoiceItemContent => ({...{format: faker.helpers.arrayElement(['choice'] as const), options: Array.from({ length: faker.number.int({min: 2, max: 10}) }, (_, i) => i + 1).map(() => ({id: faker.helpers.fromRegExp("^[A-Za-z0-9_-]+$"), text: faker.string.alpha({length: {min: 1, max: 2000}})})), multiple: faker.datatype.boolean()}, ...overrideResponse});
export const getGetMyAssessmentAttemptResponseNumberItemContentMock = (overrideResponse: Partial<NumberItemContent> = {}): NumberItemContent => ({...{format: faker.helpers.arrayElement(['number'] as const), unit: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 32}}), null])}, ...overrideResponse});
export const getGetMyAssessmentAttemptResponseStringItemContentMock = (overrideResponse: Partial<StringItemContent> = {}): StringItemContent => ({...{format: faker.helpers.arrayElement(['string'] as const), max_length: faker.number.int({min: 1, max: 500})}, ...overrideResponse});
export const getGetMyAssessmentAttemptResponseOrderItemContentMock = (overrideResponse: Partial<OrderItemContent> = {}): OrderItemContent => ({...{format: faker.helpers.arrayElement(['order'] as const), elements: Array.from({ length: faker.number.int({min: 2, max: 20}) }, (_, i) => i + 1).map(() => ({id: faker.helpers.fromRegExp("^[A-Za-z0-9_-]+$"), text: faker.string.alpha({length: {min: 1, max: 2000}})}))}, ...overrideResponse});
export const getGetMyAssessmentAttemptResponseFindErrorItemContentMock = (overrideResponse: Partial<FindErrorItemContent> = {}): FindErrorItemContent => ({...{format: faker.helpers.arrayElement(['find_error'] as const), syntax: faker.helpers.arrayElement([faker.helpers.fromRegExp("^[a-z0-9_+-]+$"), 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 getGetMyAssessmentAttemptResponseConfigurationItemContentMock = (overrideResponse: Partial<ConfigurationItemContent> = {}): ConfigurationItemContent => ({...{format: faker.helpers.arrayElement(['configuration'] as const), syntax: faker.helpers.fromRegExp("^[a-z0-9_+-]+$"), initial_config: faker.string.alpha({length: {min: 10, max: 20000}}), max_length: faker.number.int({min: 1, max: 20000})}, ...overrideResponse});
export const getGetMyAssessmentAttemptResponsePracticeItemContentMock = (overrideResponse: Partial<PracticeItemContent> = {}): PracticeItemContent => ({...{format: faker.helpers.arrayElement(['practice'] as const), languages: faker.helpers.arrayElements(Object.values(TaskLanguage)), 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 getGetMyAssessmentAttemptResponseAssessmentItemMock = (overrideResponse: Partial<AssessmentItem> = {}): 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([{...getGetMyAssessmentAttemptResponseChoiceItemContentMock()},{...getGetMyAssessmentAttemptResponseNumberItemContentMock()},{...getGetMyAssessmentAttemptResponseStringItemContentMock()},{...getGetMyAssessmentAttemptResponseOrderItemContentMock()},{...getGetMyAssessmentAttemptResponseFindErrorItemContentMock()},{...getGetMyAssessmentAttemptResponseConfigurationItemContentMock()},{...getGetMyAssessmentAttemptResponsePracticeItemContentMock()},])}, ...overrideResponse});
export const getGetMyAssessmentAttemptResponsePracticeVerdictMock = (overrideResponse: Partial<PracticeVerdict> = {}): PracticeVerdict => ({...{score: faker.number.int({min: 0, max: 3}), max_score: faker.number.int({min: 3, max: 3}), groups: Array.from({ length: faker.number.int({min: 3, max: 3}) }, (_, i) => i + 1).map(() => ({group: faker.number.int({min: 1, max: 3}), passed: faker.datatype.boolean()}))}, ...overrideResponse});
export const getGetMyAssessmentAttemptResponseMock = (overrideResponse: Partial<Extract<AssessmentAttempt, object>> = {}): AssessmentAttempt => ({id: faker.string.uuid(), version: faker.number.int({min: 1}), specialization: faker.helpers.arrayElement(Object.values(SpecializationCode)), target_grade: faker.helpers.arrayElement(Object.values(GradeCode)), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(TaskLanguage)),null,]), mode: faker.helpers.arrayElement(Object.values(AssessmentMode)), state: faker.helpers.arrayElement(Object.values(AssessmentAttemptState)), versions: {policy_version: faker.number.int({min: 1}), bank_version: faker.helpers.fromRegExp("^[A-Za-z0-9._-]+$"), algorithm_version: faker.helpers.fromRegExp("^[A-Za-z0-9._-]+$")}, 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(Object.values(PracticeKind)), item_id: faker.string.uuid(), status: faker.helpers.arrayElement(Object.values(PracticeStatus)), 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(Object.values(PracticeFailureReason)),null,])})), ...overrideResponse})
export const getSubmitMyAssessmentAnswerResponseAssessmentSessionsMock = (overrideResponse: Partial<AssessmentSessions> = {}): 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 getSubmitMyAssessmentAnswerResponseChoiceItemContentMock = (overrideResponse: Partial<ChoiceItemContent> = {}): ChoiceItemContent => ({...{format: faker.helpers.arrayElement(['choice'] as const), options: Array.from({ length: faker.number.int({min: 2, max: 10}) }, (_, i) => i + 1).map(() => ({id: faker.helpers.fromRegExp("^[A-Za-z0-9_-]+$"), text: faker.string.alpha({length: {min: 1, max: 2000}})})), multiple: faker.datatype.boolean()}, ...overrideResponse});
export const getSubmitMyAssessmentAnswerResponseNumberItemContentMock = (overrideResponse: Partial<NumberItemContent> = {}): NumberItemContent => ({...{format: faker.helpers.arrayElement(['number'] as const), unit: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 32}}), null])}, ...overrideResponse});
export const getSubmitMyAssessmentAnswerResponseStringItemContentMock = (overrideResponse: Partial<StringItemContent> = {}): StringItemContent => ({...{format: faker.helpers.arrayElement(['string'] as const), max_length: faker.number.int({min: 1, max: 500})}, ...overrideResponse});
export const getSubmitMyAssessmentAnswerResponseOrderItemContentMock = (overrideResponse: Partial<OrderItemContent> = {}): OrderItemContent => ({...{format: faker.helpers.arrayElement(['order'] as const), elements: Array.from({ length: faker.number.int({min: 2, max: 20}) }, (_, i) => i + 1).map(() => ({id: faker.helpers.fromRegExp("^[A-Za-z0-9_-]+$"), text: faker.string.alpha({length: {min: 1, max: 2000}})}))}, ...overrideResponse});
export const getSubmitMyAssessmentAnswerResponseFindErrorItemContentMock = (overrideResponse: Partial<FindErrorItemContent> = {}): FindErrorItemContent => ({...{format: faker.helpers.arrayElement(['find_error'] as const), syntax: faker.helpers.arrayElement([faker.helpers.fromRegExp("^[a-z0-9_+-]+$"), 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 getSubmitMyAssessmentAnswerResponseConfigurationItemContentMock = (overrideResponse: Partial<ConfigurationItemContent> = {}): ConfigurationItemContent => ({...{format: faker.helpers.arrayElement(['configuration'] as const), syntax: faker.helpers.fromRegExp("^[a-z0-9_+-]+$"), initial_config: faker.string.alpha({length: {min: 10, max: 20000}}), max_length: faker.number.int({min: 1, max: 20000})}, ...overrideResponse});
export const getSubmitMyAssessmentAnswerResponsePracticeItemContentMock = (overrideResponse: Partial<PracticeItemContent> = {}): PracticeItemContent => ({...{format: faker.helpers.arrayElement(['practice'] as const), languages: faker.helpers.arrayElements(Object.values(TaskLanguage)), 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 getSubmitMyAssessmentAnswerResponseAssessmentItemMock = (overrideResponse: Partial<AssessmentItem> = {}): 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([{...getSubmitMyAssessmentAnswerResponseChoiceItemContentMock()},{...getSubmitMyAssessmentAnswerResponseNumberItemContentMock()},{...getSubmitMyAssessmentAnswerResponseStringItemContentMock()},{...getSubmitMyAssessmentAnswerResponseOrderItemContentMock()},{...getSubmitMyAssessmentAnswerResponseFindErrorItemContentMock()},{...getSubmitMyAssessmentAnswerResponseConfigurationItemContentMock()},{...getSubmitMyAssessmentAnswerResponsePracticeItemContentMock()},])}, ...overrideResponse});
export const getSubmitMyAssessmentAnswerResponsePracticeVerdictMock = (overrideResponse: Partial<PracticeVerdict> = {}): PracticeVerdict => ({...{score: faker.number.int({min: 0, max: 3}), max_score: faker.number.int({min: 3, max: 3}), groups: Array.from({ length: faker.number.int({min: 3, max: 3}) }, (_, i) => i + 1).map(() => ({group: faker.number.int({min: 1, max: 3}), passed: faker.datatype.boolean()}))}, ...overrideResponse});
export const getSubmitMyAssessmentAnswerResponseMock = (overrideResponse: Partial<Extract<AssessmentAttempt, object>> = {}): AssessmentAttempt => ({id: faker.string.uuid(), version: faker.number.int({min: 1}), specialization: faker.helpers.arrayElement(Object.values(SpecializationCode)), target_grade: faker.helpers.arrayElement(Object.values(GradeCode)), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(TaskLanguage)),null,]), mode: faker.helpers.arrayElement(Object.values(AssessmentMode)), state: faker.helpers.arrayElement(Object.values(AssessmentAttemptState)), versions: {policy_version: faker.number.int({min: 1}), bank_version: faker.helpers.fromRegExp("^[A-Za-z0-9._-]+$"), algorithm_version: faker.helpers.fromRegExp("^[A-Za-z0-9._-]+$")}, 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(Object.values(PracticeKind)), item_id: faker.string.uuid(), status: faker.helpers.arrayElement(Object.values(PracticeStatus)), 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(Object.values(PracticeFailureReason)),null,])})), ...overrideResponse})
export const getFinalizeMyAssessmentAttemptResponseAssessmentSessionsMock = (overrideResponse: Partial<AssessmentSessions> = {}): 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 getFinalizeMyAssessmentAttemptResponseChoiceItemContentMock = (overrideResponse: Partial<ChoiceItemContent> = {}): ChoiceItemContent => ({...{format: faker.helpers.arrayElement(['choice'] as const), options: Array.from({ length: faker.number.int({min: 2, max: 10}) }, (_, i) => i + 1).map(() => ({id: faker.helpers.fromRegExp("^[A-Za-z0-9_-]+$"), text: faker.string.alpha({length: {min: 1, max: 2000}})})), multiple: faker.datatype.boolean()}, ...overrideResponse});
export const getFinalizeMyAssessmentAttemptResponseNumberItemContentMock = (overrideResponse: Partial<NumberItemContent> = {}): NumberItemContent => ({...{format: faker.helpers.arrayElement(['number'] as const), unit: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 32}}), null])}, ...overrideResponse});
export const getFinalizeMyAssessmentAttemptResponseStringItemContentMock = (overrideResponse: Partial<StringItemContent> = {}): StringItemContent => ({...{format: faker.helpers.arrayElement(['string'] as const), max_length: faker.number.int({min: 1, max: 500})}, ...overrideResponse});
export const getFinalizeMyAssessmentAttemptResponseOrderItemContentMock = (overrideResponse: Partial<OrderItemContent> = {}): OrderItemContent => ({...{format: faker.helpers.arrayElement(['order'] as const), elements: Array.from({ length: faker.number.int({min: 2, max: 20}) }, (_, i) => i + 1).map(() => ({id: faker.helpers.fromRegExp("^[A-Za-z0-9_-]+$"), text: faker.string.alpha({length: {min: 1, max: 2000}})}))}, ...overrideResponse});
export const getFinalizeMyAssessmentAttemptResponseFindErrorItemContentMock = (overrideResponse: Partial<FindErrorItemContent> = {}): FindErrorItemContent => ({...{format: faker.helpers.arrayElement(['find_error'] as const), syntax: faker.helpers.arrayElement([faker.helpers.fromRegExp("^[a-z0-9_+-]+$"), 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 getFinalizeMyAssessmentAttemptResponseConfigurationItemContentMock = (overrideResponse: Partial<ConfigurationItemContent> = {}): ConfigurationItemContent => ({...{format: faker.helpers.arrayElement(['configuration'] as const), syntax: faker.helpers.fromRegExp("^[a-z0-9_+-]+$"), initial_config: faker.string.alpha({length: {min: 10, max: 20000}}), max_length: faker.number.int({min: 1, max: 20000})}, ...overrideResponse});
export const getFinalizeMyAssessmentAttemptResponsePracticeItemContentMock = (overrideResponse: Partial<PracticeItemContent> = {}): PracticeItemContent => ({...{format: faker.helpers.arrayElement(['practice'] as const), languages: faker.helpers.arrayElements(Object.values(TaskLanguage)), 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 getFinalizeMyAssessmentAttemptResponseAssessmentItemMock = (overrideResponse: Partial<AssessmentItem> = {}): 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([{...getFinalizeMyAssessmentAttemptResponseChoiceItemContentMock()},{...getFinalizeMyAssessmentAttemptResponseNumberItemContentMock()},{...getFinalizeMyAssessmentAttemptResponseStringItemContentMock()},{...getFinalizeMyAssessmentAttemptResponseOrderItemContentMock()},{...getFinalizeMyAssessmentAttemptResponseFindErrorItemContentMock()},{...getFinalizeMyAssessmentAttemptResponseConfigurationItemContentMock()},{...getFinalizeMyAssessmentAttemptResponsePracticeItemContentMock()},])}, ...overrideResponse});
export const getFinalizeMyAssessmentAttemptResponsePracticeVerdictMock = (overrideResponse: Partial<PracticeVerdict> = {}): PracticeVerdict => ({...{score: faker.number.int({min: 0, max: 3}), max_score: faker.number.int({min: 3, max: 3}), groups: Array.from({ length: faker.number.int({min: 3, max: 3}) }, (_, i) => i + 1).map(() => ({group: faker.number.int({min: 1, max: 3}), passed: faker.datatype.boolean()}))}, ...overrideResponse});
export const getFinalizeMyAssessmentAttemptResponseMock = (overrideResponse: Partial<Extract<AssessmentAttempt, object>> = {}): AssessmentAttempt => ({id: faker.string.uuid(), version: faker.number.int({min: 1}), specialization: faker.helpers.arrayElement(Object.values(SpecializationCode)), target_grade: faker.helpers.arrayElement(Object.values(GradeCode)), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(TaskLanguage)),null,]), mode: faker.helpers.arrayElement(Object.values(AssessmentMode)), state: faker.helpers.arrayElement(Object.values(AssessmentAttemptState)), versions: {policy_version: faker.number.int({min: 1}), bank_version: faker.helpers.fromRegExp("^[A-Za-z0-9._-]+$"), algorithm_version: faker.helpers.fromRegExp("^[A-Za-z0-9._-]+$")}, 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(Object.values(PracticeKind)), item_id: faker.string.uuid(), status: faker.helpers.arrayElement(Object.values(PracticeStatus)), 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(Object.values(PracticeFailureReason)),null,])})), ...overrideResponse})
export const getGetMyAssessmentResultResponseAssessmentUncertaintyMock = (overrideResponse: Partial<AssessmentUncertainty> = {}): 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> = {}): 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<Extract<AssessmentResult, object>> = {}): AssessmentResult => ({attempt_id: faker.string.uuid(), specialization: faker.helpers.arrayElement(Object.values(SpecializationCode)), target_grade: faker.helpers.arrayElement(Object.values(GradeCode)), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(TaskLanguage)),null,]), mode: faker.helpers.arrayElement(Object.values(AssessmentMode)), versions: {policy_version: faker.number.int({min: 1}), bank_version: faker.helpers.fromRegExp("^[A-Za-z0-9._-]+$"), algorithm_version: faker.helpers.fromRegExp("^[A-Za-z0-9._-]+$")}, outcome: faker.helpers.arrayElement(Object.values(AssessmentOutcome)), not_determined_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(AssessmentNotDeterminedReason)),null,]), confirmed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(GradeCode)),null,]), previous_confirmed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(GradeCode)),null,]), strength: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(AssessmentStrength)),null,]), calibration_status: faker.helpers.arrayElement(Object.values(CalibrationStatus)), limitations: faker.helpers.arrayElements(Object.values(AssessmentLimitation)), 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(Object.values(PracticeKind)), 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: faker.helpers.fromRegExp("^[a-z0-9_]+$"), 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(Object.values(AssessmentNextAction)), grade: faker.helpers.arrayElement(Object.values(GradeCode)), 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 getGetMyAssessmentAvailabilityMockHandler = (overrideResponse?: AssessmentAvailability | ((info: Parameters<Parameters<typeof http.get>[1]>[0]) => Promise<AssessmentAvailability> | AssessmentAvailability), options?: RequestHandlerOptions) => {
return http.get('*/api/v1/me/assessment-availability', async (info: Parameters<Parameters<typeof http.get>[1]>[0]) => {
return HttpResponse.json(overrideResponse !== undefined
? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse)
: getGetMyAssessmentAvailabilityResponseMock(),
{ status: 200
})
}, options)
}
export const getCreateMyAssessmentAttemptMockHandler = (overrideResponse?: AssessmentAttempt | ((info: Parameters<Parameters<typeof http.post>[1]>[0]) => Promise<AssessmentAttempt> | AssessmentAttempt), options?: RequestHandlerOptions) => {
return http.post('*/api/v1/me/assessment-attempts', async (info: Parameters<Parameters<typeof http.post>[1]>[0]) => {
return HttpResponse.json(overrideResponse !== undefined
? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse)
: getCreateMyAssessmentAttemptResponseMock(),
{ status: 201
})
}, options)
}
export const getGetMyAssessmentAttemptMockHandler = (overrideResponse?: AssessmentAttempt | ((info: Parameters<Parameters<typeof http.get>[1]>[0]) => Promise<AssessmentAttempt> | AssessmentAttempt), options?: RequestHandlerOptions) => {
return http.get('*/api/v1/me/assessment-attempts/:attemptId', async (info: Parameters<Parameters<typeof http.get>[1]>[0]) => {
return HttpResponse.json(overrideResponse !== undefined
? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse)
: getGetMyAssessmentAttemptResponseMock(),
{ status: 200
})
}, options)
}
export const getSubmitMyAssessmentAnswerMockHandler = (overrideResponse?: AssessmentAttempt | ((info: Parameters<Parameters<typeof http.post>[1]>[0]) => Promise<AssessmentAttempt> | AssessmentAttempt), options?: RequestHandlerOptions) => {
return http.post('*/api/v1/me/assessment-attempts/:attemptId/answers', async (info: Parameters<Parameters<typeof http.post>[1]>[0]) => {
return HttpResponse.json(overrideResponse !== undefined
? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse)
: getSubmitMyAssessmentAnswerResponseMock(),
{ status: 200
})
}, options)
}
export const getFinalizeMyAssessmentAttemptMockHandler = (overrideResponse?: AssessmentAttempt | ((info: Parameters<Parameters<typeof http.post>[1]>[0]) => Promise<AssessmentAttempt> | AssessmentAttempt), options?: RequestHandlerOptions) => {
return http.post('*/api/v1/me/assessment-attempts/:attemptId/finalize', async (info: Parameters<Parameters<typeof http.post>[1]>[0]) => {
return HttpResponse.json(overrideResponse !== undefined
? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse)
: getFinalizeMyAssessmentAttemptResponseMock(),
{ status: 200
})
}, options)
}
export const getGetMyAssessmentResultMockHandler = (overrideResponse?: AssessmentResult | ((info: Parameters<Parameters<typeof http.get>[1]>[0]) => Promise<AssessmentResult> | AssessmentResult), options?: RequestHandlerOptions) => {
return http.get('*/api/v1/me/assessment-attempts/:attemptId/result', async (info: Parameters<Parameters<typeof http.get>[1]>[0]) => {
return HttpResponse.json(overrideResponse !== undefined
? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse)
: getGetMyAssessmentResultResponseMock(),
{ status: 200
})
}, options)
}
export const getAssessmentMock = () => [
getGetMyAssessmentAvailabilityMockHandler(),
getCreateMyAssessmentAttemptMockHandler(),
getGetMyAssessmentAttemptMockHandler(),
getSubmitMyAssessmentAnswerMockHandler(),
getFinalizeMyAssessmentAttemptMockHandler(),
getGetMyAssessmentResultMockHandler()
]
@@ -0,0 +1,678 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import {
useMutation,
useQuery
} from '@tanstack/react-query';
import type {
DataTag,
DefinedInitialDataOptions,
DefinedUseQueryResult,
MutationFunction,
QueryClient,
QueryFunction,
QueryKey,
UndefinedInitialDataOptions,
UseMutationOptions,
UseMutationResult,
UseQueryOptions,
UseQueryResult
} from '@tanstack/react-query';
import type {
AssessmentAnswerSubmission,
AssessmentAttempt,
AssessmentAttemptCreate,
AssessmentAvailability,
AssessmentFinalization,
AssessmentResult,
CreateMyAssessmentAttemptHeaders,
FinalizeMyAssessmentAttemptHeaders,
Problem,
SubmitMyAssessmentAnswerHeaders
} from '../../schemas';
import { apiRequest } from '../../client';
import type { ErrorType } from '../../client';
type SecondParameter<T extends (...args: never) => unknown> = Parameters<T>[1];
const withQueryKey = <T extends object, K>(query: T, queryKey: K): T & { queryKey: K } => {
const result = { queryKey } as T & { queryKey: K };
for (const key of Object.keys(query)) {
// The explicit queryKey always wins, matching the previous
// `{ ...query, queryKey }` spread where it was set last.
if (key === 'queryKey') continue;
Object.defineProperty(result, key, {
enumerable: true,
configurable: true,
get: () => (query as Record<string, unknown>)[key],
});
}
return result;
};
export const getGetMyAssessmentAvailabilityUrl = () => {
return `/api/v1/me/assessment-availability`
}
/**
* Requires the session cookie of a candidate account; the candidate comes from the session. For each specialization of the questionnaire, returns the confirmed grade, the active attempt, and for every grade whether an attempt can start now, in which mode, and with which limits: the time limit, the session limit, the item limit, and whether a code practice is required. The client shows them before the start, together with the method and the signals that are collected, and resumes an active attempt by `active_attempt_id`, for example after it lost the response of CreateMyAssessmentAttempt.
*
* `insufficient_bank` is the state of a category whose bank is not published or has too few families that this candidate has not seen; the server limits attempts instead of repeating families. `cooldown` carries the date when the attempt opens, so the client can explain a blocked attempt with that date and offer support. Specializations and their retry intervals are independent. Attempts that ended as `insufficient_bank` or with the reason `sandbox_unavailable` are platform limitations and never cause a `cooldown`.
*
* A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden.
* @summary Read which assessment attempts the current candidate can start.
*/
export const getMyAssessmentAvailability = async ( options?: Parameters<typeof apiRequest>[1]): Promise<AssessmentAvailability> => {
return apiRequest<AssessmentAvailability>(getGetMyAssessmentAvailabilityUrl(),
{
...options,
method: 'GET'
}
);}
export const getGetMyAssessmentAvailabilityQueryKey = () => {
return [
`/api/v1/me/assessment-availability`
] as const;
}
export const getGetMyAssessmentAvailabilityQueryOptions = <TData = Awaited<ReturnType<typeof getMyAssessmentAvailability>>, TError = ErrorType<Problem>>( options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getMyAssessmentAvailability>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
) => {
const {query: queryOptions, request: requestOptions} = options ?? {};
const queryKey = queryOptions?.queryKey ?? getGetMyAssessmentAvailabilityQueryKey();
const queryFn: QueryFunction<Awaited<ReturnType<typeof getMyAssessmentAvailability>>> = ({ signal }) => getMyAssessmentAvailability({ signal, ...requestOptions });
return { queryKey, queryFn, ...queryOptions} as UseQueryOptions<Awaited<ReturnType<typeof getMyAssessmentAvailability>>, TError, TData> & { queryKey: DataTag<QueryKey, TData, TError> }
}
export type GetMyAssessmentAvailabilityQueryResult = NonNullable<Awaited<ReturnType<typeof getMyAssessmentAvailability>>>
export type GetMyAssessmentAvailabilityQueryError = ErrorType<Problem>
export function useGetMyAssessmentAvailability<TData = Awaited<ReturnType<typeof getMyAssessmentAvailability>>, TError = ErrorType<Problem>>(
options: { query:Partial<UseQueryOptions<Awaited<ReturnType<typeof getMyAssessmentAvailability>>, TError, TData>> & Pick<
DefinedInitialDataOptions<
Awaited<ReturnType<typeof getMyAssessmentAvailability>>,
TError,
Awaited<ReturnType<typeof getMyAssessmentAvailability>>
> , 'initialData'
>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient
): DefinedUseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
export function useGetMyAssessmentAvailability<TData = Awaited<ReturnType<typeof getMyAssessmentAvailability>>, TError = ErrorType<Problem>>(
options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getMyAssessmentAvailability>>, TError, TData>> & Pick<
UndefinedInitialDataOptions<
Awaited<ReturnType<typeof getMyAssessmentAvailability>>,
TError,
Awaited<ReturnType<typeof getMyAssessmentAvailability>>
> , 'initialData'
>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
export function useGetMyAssessmentAvailability<TData = Awaited<ReturnType<typeof getMyAssessmentAvailability>>, TError = ErrorType<Problem>>(
options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getMyAssessmentAvailability>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
/**
* @summary Read which assessment attempts the current candidate can start.
*/
export function useGetMyAssessmentAvailability<TData = Awaited<ReturnType<typeof getMyAssessmentAvailability>>, TError = ErrorType<Problem>>(
options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getMyAssessmentAvailability>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> } {
const queryOptions = getGetMyAssessmentAvailabilityQueryOptions(options)
const query = useQuery(queryOptions, queryClient) as UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> };
return withQueryKey(query, queryOptions.queryKey);
}
export const getCreateMyAssessmentAttemptUrl = () => {
return `/api/v1/me/assessment-attempts`
}
/**
* 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.
*
* 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.
*
* 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.
*
* 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.
*/
export const createMyAssessmentAttempt = async (assessmentAttemptCreate: AssessmentAttemptCreate,
headers: CreateMyAssessmentAttemptHeaders, options?: Parameters<typeof apiRequest>[1]): Promise<AssessmentAttempt> => {
const getHeaders = (h?: NonNullable<RequestInit['headers']>): Record<string, string | readonly string[]> => {
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<Iterable<string>>, (entry) => Array.from(entry) as [string, string]),
);
}
const headers: Record<string, string | readonly string[]> = {};
for (const [name, value] of Object.entries<string | readonly string[] | undefined>(h)) {
if (value !== undefined) headers[name] = value;
}
return headers;
};
return apiRequest<AssessmentAttempt>(getCreateMyAssessmentAttemptUrl(),
{
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json',...headers, ...getHeaders(options?.headers) },
body: JSON.stringify(assessmentAttemptCreate)
}
);}
export const getCreateMyAssessmentAttemptMutationKey = () => ['createMyAssessmentAttempt'] as const;
export const getCreateMyAssessmentAttemptMutationOptions = <TError = ErrorType<Problem>,
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof createMyAssessmentAttempt>>, TError,CreateMyAssessmentAttemptMutationVariables, TContext>, request?: SecondParameter<typeof apiRequest>}
): UseMutationOptions<Awaited<ReturnType<typeof createMyAssessmentAttempt>>, TError,CreateMyAssessmentAttemptMutationVariables, TContext> => {
const mutationKey = getCreateMyAssessmentAttemptMutationKey();
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<Awaited<ReturnType<typeof createMyAssessmentAttempt>>, CreateMyAssessmentAttemptMutationVariables> = (props) => {
const {data,headers} = props ?? {};
return createMyAssessmentAttempt(data,headers,requestOptions)
}
return { mutationFn, ...mutationOptions }}
export type CreateMyAssessmentAttemptMutationResult = NonNullable<Awaited<ReturnType<typeof createMyAssessmentAttempt>>>
export type CreateMyAssessmentAttemptMutationBody = AssessmentAttemptCreate
export type CreateMyAssessmentAttemptMutationError = ErrorType<Problem>
export type CreateMyAssessmentAttemptMutationVariables = {data: AssessmentAttemptCreate;headers: CreateMyAssessmentAttemptHeaders}
/**
* @summary Start an assessment attempt for a category of the current candidate.
*/
export const useCreateMyAssessmentAttempt = <TError = ErrorType<Problem>,
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof createMyAssessmentAttempt>>, TError,CreateMyAssessmentAttemptMutationVariables, TContext>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient): UseMutationResult<
Awaited<ReturnType<typeof createMyAssessmentAttempt>>,
TError,
CreateMyAssessmentAttemptMutationVariables,
TContext
> => {
return useMutation(getCreateMyAssessmentAttemptMutationOptions(options), queryClient);
}
export const getGetMyAssessmentAttemptUrl = (attemptId: string,) => {
return `/api/v1/me/assessment-attempts/${attemptId}`
}
/**
* 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.
*
* 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.
*
* 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.
*/
export const getMyAssessmentAttempt = async (attemptId: string, options?: Parameters<typeof apiRequest>[1]): Promise<AssessmentAttempt> => {
return apiRequest<AssessmentAttempt>(getGetMyAssessmentAttemptUrl(attemptId),
{
...options,
method: 'GET'
}
);}
export const getGetMyAssessmentAttemptQueryKey = (attemptId: string,) => {
return [
`/api/v1/me/assessment-attempts/${attemptId}`
] as const;
}
export const getGetMyAssessmentAttemptQueryOptions = <TData = Awaited<ReturnType<typeof getMyAssessmentAttempt>>, TError = ErrorType<Problem>>(attemptId: string, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getMyAssessmentAttempt>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
) => {
const {query: queryOptions, request: requestOptions} = options ?? {};
const queryKey = queryOptions?.queryKey ?? getGetMyAssessmentAttemptQueryKey(attemptId);
const queryFn: QueryFunction<Awaited<ReturnType<typeof getMyAssessmentAttempt>>> = ({ signal }) => getMyAssessmentAttempt(attemptId, { signal, ...requestOptions });
return { queryKey, queryFn, enabled: attemptId !== null && attemptId !== undefined, ...queryOptions} as UseQueryOptions<Awaited<ReturnType<typeof getMyAssessmentAttempt>>, TError, TData> & { queryKey: DataTag<QueryKey, TData, TError> }
}
export type GetMyAssessmentAttemptQueryResult = NonNullable<Awaited<ReturnType<typeof getMyAssessmentAttempt>>>
export type GetMyAssessmentAttemptQueryError = ErrorType<Problem>
export function useGetMyAssessmentAttempt<TData = Awaited<ReturnType<typeof getMyAssessmentAttempt>>, TError = ErrorType<Problem>>(
attemptId: string, options: { query:Partial<UseQueryOptions<Awaited<ReturnType<typeof getMyAssessmentAttempt>>, TError, TData>> & Pick<
DefinedInitialDataOptions<
Awaited<ReturnType<typeof getMyAssessmentAttempt>>,
TError,
Awaited<ReturnType<typeof getMyAssessmentAttempt>>
> , 'initialData'
>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient
): DefinedUseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
export function useGetMyAssessmentAttempt<TData = Awaited<ReturnType<typeof getMyAssessmentAttempt>>, TError = ErrorType<Problem>>(
attemptId: string, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getMyAssessmentAttempt>>, TError, TData>> & Pick<
UndefinedInitialDataOptions<
Awaited<ReturnType<typeof getMyAssessmentAttempt>>,
TError,
Awaited<ReturnType<typeof getMyAssessmentAttempt>>
> , 'initialData'
>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
export function useGetMyAssessmentAttempt<TData = Awaited<ReturnType<typeof getMyAssessmentAttempt>>, TError = ErrorType<Problem>>(
attemptId: string, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getMyAssessmentAttempt>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
/**
* @summary Read or resume an assessment attempt of the current candidate.
*/
export function useGetMyAssessmentAttempt<TData = Awaited<ReturnType<typeof getMyAssessmentAttempt>>, TError = ErrorType<Problem>>(
attemptId: string, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getMyAssessmentAttempt>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> } {
const queryOptions = getGetMyAssessmentAttemptQueryOptions(attemptId,options)
const query = useQuery(queryOptions, queryClient) as UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> };
return withQueryKey(query, queryOptions.queryKey);
}
export const getSubmitMyAssessmentAnswerUrl = (attemptId: string,) => {
return `/api/v1/me/assessment-attempts/${attemptId}/answers`
}
/**
* 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 item and carries the answer in the format of that item: `choice`, `number`, `string`, `order`, `find_error`, `configuration`, or `practice`. It never carries a score, a duration, or a correctness flag; the server records the times itself and scores the answer with the key of the fixed item instance. Time never enters the ability estimate or the grade decision.
*
* 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.
*
* 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:
* - A retry with the same Idempotency-Key and body within 24 hours replays the stored response.
* - Sending the answer already stored for the item again, even with a new key or an older `expected_version`, stores nothing, keeps the version, and answers 200 with the current attempt. Each answer format defines equality: 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 item that already has one answers 409 state_conflict when `expected_version` is current; with a stale version the version check comes first and answers 412.
* - Exception for a practice whose latest verdict is `failed`: the repeat rule does not apply. A submission with the same or a different solution, with the current `expected_version`, queues it again and advances the version.
*
* 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.
* @summary Answer the current item or submit a practice of an assessment attempt.
*/
export const submitMyAssessmentAnswer = async (attemptId: string,
assessmentAnswerSubmission: AssessmentAnswerSubmission,
headers: SubmitMyAssessmentAnswerHeaders, options?: Parameters<typeof apiRequest>[1]): Promise<AssessmentAttempt> => {
const getHeaders = (h?: NonNullable<RequestInit['headers']>): Record<string, string | readonly string[]> => {
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<Iterable<string>>, (entry) => Array.from(entry) as [string, string]),
);
}
const headers: Record<string, string | readonly string[]> = {};
for (const [name, value] of Object.entries<string | readonly string[] | undefined>(h)) {
if (value !== undefined) headers[name] = value;
}
return headers;
};
return apiRequest<AssessmentAttempt>(getSubmitMyAssessmentAnswerUrl(attemptId),
{
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json',...headers, ...getHeaders(options?.headers) },
body: JSON.stringify(assessmentAnswerSubmission)
}
);}
export const getSubmitMyAssessmentAnswerMutationKey = () => ['submitMyAssessmentAnswer'] as const;
export const getSubmitMyAssessmentAnswerMutationOptions = <TError = ErrorType<Problem>,
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof submitMyAssessmentAnswer>>, TError,SubmitMyAssessmentAnswerMutationVariables, TContext>, request?: SecondParameter<typeof apiRequest>}
): UseMutationOptions<Awaited<ReturnType<typeof submitMyAssessmentAnswer>>, TError,SubmitMyAssessmentAnswerMutationVariables, TContext> => {
const mutationKey = getSubmitMyAssessmentAnswerMutationKey();
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<Awaited<ReturnType<typeof submitMyAssessmentAnswer>>, SubmitMyAssessmentAnswerMutationVariables> = (props) => {
const {attemptId,data,headers} = props ?? {};
return submitMyAssessmentAnswer(attemptId,data,headers,requestOptions)
}
return { mutationFn, ...mutationOptions }}
export type SubmitMyAssessmentAnswerMutationResult = NonNullable<Awaited<ReturnType<typeof submitMyAssessmentAnswer>>>
export type SubmitMyAssessmentAnswerMutationBody = AssessmentAnswerSubmission
export type SubmitMyAssessmentAnswerMutationError = ErrorType<Problem>
export type SubmitMyAssessmentAnswerMutationVariables = {attemptId: string;data: AssessmentAnswerSubmission;headers: SubmitMyAssessmentAnswerHeaders}
/**
* @summary Answer the current item or submit a practice of an assessment attempt.
*/
export const useSubmitMyAssessmentAnswer = <TError = ErrorType<Problem>,
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof submitMyAssessmentAnswer>>, TError,SubmitMyAssessmentAnswerMutationVariables, TContext>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient): UseMutationResult<
Awaited<ReturnType<typeof submitMyAssessmentAnswer>>,
TError,
SubmitMyAssessmentAnswerMutationVariables,
TContext
> => {
return useMutation(getSubmitMyAssessmentAnswerMutationOptions(options), queryClient);
}
export const getFinalizeMyAssessmentAttemptUrl = (attemptId: string,) => {
return `/api/v1/me/assessment-attempts/${attemptId}/finalize`
}
/**
* 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.
*
* 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.
*
* 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.
* @summary Ask for the grade decision of an assessment attempt.
*/
export const finalizeMyAssessmentAttempt = async (attemptId: string,
assessmentFinalization: AssessmentFinalization,
headers: FinalizeMyAssessmentAttemptHeaders, options?: Parameters<typeof apiRequest>[1]): Promise<AssessmentAttempt> => {
const getHeaders = (h?: NonNullable<RequestInit['headers']>): Record<string, string | readonly string[]> => {
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<Iterable<string>>, (entry) => Array.from(entry) as [string, string]),
);
}
const headers: Record<string, string | readonly string[]> = {};
for (const [name, value] of Object.entries<string | readonly string[] | undefined>(h)) {
if (value !== undefined) headers[name] = value;
}
return headers;
};
return apiRequest<AssessmentAttempt>(getFinalizeMyAssessmentAttemptUrl(attemptId),
{
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json',...headers, ...getHeaders(options?.headers) },
body: JSON.stringify(assessmentFinalization)
}
);}
export const getFinalizeMyAssessmentAttemptMutationKey = () => ['finalizeMyAssessmentAttempt'] as const;
export const getFinalizeMyAssessmentAttemptMutationOptions = <TError = ErrorType<Problem>,
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof finalizeMyAssessmentAttempt>>, TError,FinalizeMyAssessmentAttemptMutationVariables, TContext>, request?: SecondParameter<typeof apiRequest>}
): UseMutationOptions<Awaited<ReturnType<typeof finalizeMyAssessmentAttempt>>, TError,FinalizeMyAssessmentAttemptMutationVariables, TContext> => {
const mutationKey = getFinalizeMyAssessmentAttemptMutationKey();
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<Awaited<ReturnType<typeof finalizeMyAssessmentAttempt>>, FinalizeMyAssessmentAttemptMutationVariables> = (props) => {
const {attemptId,data,headers} = props ?? {};
return finalizeMyAssessmentAttempt(attemptId,data,headers,requestOptions)
}
return { mutationFn, ...mutationOptions }}
export type FinalizeMyAssessmentAttemptMutationResult = NonNullable<Awaited<ReturnType<typeof finalizeMyAssessmentAttempt>>>
export type FinalizeMyAssessmentAttemptMutationBody = AssessmentFinalization
export type FinalizeMyAssessmentAttemptMutationError = ErrorType<Problem>
export type FinalizeMyAssessmentAttemptMutationVariables = {attemptId: string;data: AssessmentFinalization;headers: FinalizeMyAssessmentAttemptHeaders}
/**
* @summary Ask for the grade decision of an assessment attempt.
*/
export const useFinalizeMyAssessmentAttempt = <TError = ErrorType<Problem>,
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof finalizeMyAssessmentAttempt>>, TError,FinalizeMyAssessmentAttemptMutationVariables, TContext>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient): UseMutationResult<
Awaited<ReturnType<typeof finalizeMyAssessmentAttempt>>,
TError,
FinalizeMyAssessmentAttemptMutationVariables,
TContext
> => {
return useMutation(getFinalizeMyAssessmentAttemptMutationOptions(options), queryClient);
}
export const getGetMyAssessmentResultUrl = (attemptId: string,) => {
return `/api/v1/me/assessment-attempts/${attemptId}/result`
}
/**
* 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.
*
* 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.
* @summary Read the result of an assessment attempt of the current candidate.
*/
export const getMyAssessmentResult = async (attemptId: string, options?: Parameters<typeof apiRequest>[1]): Promise<AssessmentResult> => {
return apiRequest<AssessmentResult>(getGetMyAssessmentResultUrl(attemptId),
{
...options,
method: 'GET'
}
);}
export const getGetMyAssessmentResultQueryKey = (attemptId: string,) => {
return [
`/api/v1/me/assessment-attempts/${attemptId}/result`
] as const;
}
export const getGetMyAssessmentResultQueryOptions = <TData = Awaited<ReturnType<typeof getMyAssessmentResult>>, TError = ErrorType<Problem>>(attemptId: string, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getMyAssessmentResult>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
) => {
const {query: queryOptions, request: requestOptions} = options ?? {};
const queryKey = queryOptions?.queryKey ?? getGetMyAssessmentResultQueryKey(attemptId);
const queryFn: QueryFunction<Awaited<ReturnType<typeof getMyAssessmentResult>>> = ({ signal }) => getMyAssessmentResult(attemptId, { signal, ...requestOptions });
return { queryKey, queryFn, enabled: attemptId !== null && attemptId !== undefined, ...queryOptions} as UseQueryOptions<Awaited<ReturnType<typeof getMyAssessmentResult>>, TError, TData> & { queryKey: DataTag<QueryKey, TData, TError> }
}
export type GetMyAssessmentResultQueryResult = NonNullable<Awaited<ReturnType<typeof getMyAssessmentResult>>>
export type GetMyAssessmentResultQueryError = ErrorType<Problem>
export function useGetMyAssessmentResult<TData = Awaited<ReturnType<typeof getMyAssessmentResult>>, TError = ErrorType<Problem>>(
attemptId: string, options: { query:Partial<UseQueryOptions<Awaited<ReturnType<typeof getMyAssessmentResult>>, TError, TData>> & Pick<
DefinedInitialDataOptions<
Awaited<ReturnType<typeof getMyAssessmentResult>>,
TError,
Awaited<ReturnType<typeof getMyAssessmentResult>>
> , 'initialData'
>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient
): DefinedUseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
export function useGetMyAssessmentResult<TData = Awaited<ReturnType<typeof getMyAssessmentResult>>, TError = ErrorType<Problem>>(
attemptId: string, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getMyAssessmentResult>>, TError, TData>> & Pick<
UndefinedInitialDataOptions<
Awaited<ReturnType<typeof getMyAssessmentResult>>,
TError,
Awaited<ReturnType<typeof getMyAssessmentResult>>
> , 'initialData'
>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
export function useGetMyAssessmentResult<TData = Awaited<ReturnType<typeof getMyAssessmentResult>>, TError = ErrorType<Problem>>(
attemptId: string, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getMyAssessmentResult>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
/**
* @summary Read the result of an assessment attempt of the current candidate.
*/
export function useGetMyAssessmentResult<TData = Awaited<ReturnType<typeof getMyAssessmentResult>>, TError = ErrorType<Problem>>(
attemptId: string, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getMyAssessmentResult>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> } {
const queryOptions = getGetMyAssessmentResultQueryOptions(attemptId,options)
const query = useQuery(queryOptions, queryClient) as UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> };
return withQueryKey(query, queryOptions.queryKey);
}
@@ -1,3 +1,4 @@
export { getAssessmentMock } from './assessment/assessment.msw'
export { getCandidateMock } from './candidate/candidate.msw'
export { getCatalogMock } from './catalog/catalog.msw'
export { getHealthMock } from './health/health.msw'
@@ -1,3 +1,4 @@
export * from './assessment/assessment';
export * from './candidate/candidate';
export * from './catalog/catalog';
export * from './health/health';
@@ -0,0 +1,58 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const assessmentAnswerOneOptionIdsItemMax = 32;
export const assessmentAnswerOneOptionIdsItemRegExp = new RegExp('^[A-Za-z0-9_-]+$');
export const assessmentAnswerOneOptionIdsMax = 10;
export const assessmentAnswerThreeTextMax = 500;
export const assessmentAnswerFourElementIdsItemMax = 32;
export const assessmentAnswerFourElementIdsItemRegExp = new RegExp('^[A-Za-z0-9_-]+$');
export const assessmentAnswerFourElementIdsMin = 2;
export const assessmentAnswerFourElementIdsMax = 20;
export const assessmentAnswerFiveLineNumbersItemMax = 500;
export const assessmentAnswerFiveLineNumbersMax = 10;
export const assessmentAnswerSixConfigMax = 20000;
export const assessmentAnswerSevenSourceCodeMax = 65536;
export const AssessmentAnswer = zod.union([zod.object({
"format": zod.enum(['choice']),
"option_ids": zod.array(zod.string().min(1).max(assessmentAnswerOneOptionIdsItemMax).regex(assessmentAnswerOneOptionIdsItemRegExp).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.')).min(1).max(assessmentAnswerOneOptionIdsMax)
}).describe('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.'),zod.object({
"format": zod.enum(['number']),
"number": zod.number()
}).describe('Numeric answer in the unit of the item. Two answers are equal when their decoded values are numerically equal, so 254 and 254.0 are the same answer.'),zod.object({
"format": zod.enum(['string']),
"text": zod.string().min(1).max(assessmentAnswerThreeTextMax)
}).describe('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.'),zod.object({
"format": zod.enum(['order']),
"element_ids": zod.array(zod.string().min(1).max(assessmentAnswerFourElementIdsItemMax).regex(assessmentAnswerFourElementIdsItemRegExp).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.')).min(assessmentAnswerFourElementIdsMin).max(assessmentAnswerFourElementIdsMax)
}).describe('Every element of the item exactly once, in the chosen order. Two answers are equal only when the sequences are identical.'),zod.object({
"format": zod.enum(['find_error']),
"line_numbers": zod.array(zod.int().min(1).max(assessmentAnswerFiveLineNumbersItemMax)).min(1).max(assessmentAnswerFiveLineNumbersMax)
}).describe('Selected line numbers, at most the `max_selections` of the item. Two answers are equal when they select the same set of lines, in any order.'),zod.object({
"format": zod.enum(['configuration']),
"config": zod.string().min(1).max(assessmentAnswerSixConfigMax)
}).describe('Submitted configuration text, at most the `max_length` of the item. Two answers are equal only when their texts are identical, including whitespace and line breaks.'),zod.object({
"format": zod.enum(['practice']),
"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('One of the `languages` of the practice item, or null when the item offers none.'),
"source_code": zod.string().min(1).max(assessmentAnswerSevenSourceCodeMax)
}).describe('Practice solution. It runs in the isolated sandbox without network access, secrets, or business data. Two submissions are equal only when the language is the same and the source texts are identical. The source is never echoed in a response or a problem.')]).describe('Candidate answer, selected by `format`, which must equal the format of the answered item. It carries only the answer: no score, duration, correctness flag, or seed. The server records the times itself and scores the answer with the key of the fixed item instance. Each format defines when two answers are equal, which decides whether a repeated submission is the same answer.')
export type AssessmentAnswer = zod.input<typeof AssessmentAnswer>;
export type AssessmentAnswerOutput = zod.output<typeof AssessmentAnswer>;
@@ -0,0 +1,63 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const assessmentAnswerSubmissionAnswerOneOptionIdsItemMax = 32;
export const assessmentAnswerSubmissionAnswerOneOptionIdsItemRegExp = new RegExp('^[A-Za-z0-9_-]+$');
export const assessmentAnswerSubmissionAnswerOneOptionIdsMax = 10;
export const assessmentAnswerSubmissionAnswerThreeTextMax = 500;
export const assessmentAnswerSubmissionAnswerFourElementIdsItemMax = 32;
export const assessmentAnswerSubmissionAnswerFourElementIdsItemRegExp = new RegExp('^[A-Za-z0-9_-]+$');
export const assessmentAnswerSubmissionAnswerFourElementIdsMin = 2;
export const assessmentAnswerSubmissionAnswerFourElementIdsMax = 20;
export const assessmentAnswerSubmissionAnswerFiveLineNumbersItemMax = 500;
export const assessmentAnswerSubmissionAnswerFiveLineNumbersMax = 10;
export const assessmentAnswerSubmissionAnswerSixConfigMax = 20000;
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`.'),
"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']),
"option_ids": zod.array(zod.string().min(1).max(assessmentAnswerSubmissionAnswerOneOptionIdsItemMax).regex(assessmentAnswerSubmissionAnswerOneOptionIdsItemRegExp).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.')).min(1).max(assessmentAnswerSubmissionAnswerOneOptionIdsMax)
}).describe('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.'),zod.object({
"format": zod.enum(['number']),
"number": zod.number()
}).describe('Numeric answer in the unit of the item. Two answers are equal when their decoded values are numerically equal, so 254 and 254.0 are the same answer.'),zod.object({
"format": zod.enum(['string']),
"text": zod.string().min(1).max(assessmentAnswerSubmissionAnswerThreeTextMax)
}).describe('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.'),zod.object({
"format": zod.enum(['order']),
"element_ids": zod.array(zod.string().min(1).max(assessmentAnswerSubmissionAnswerFourElementIdsItemMax).regex(assessmentAnswerSubmissionAnswerFourElementIdsItemRegExp).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.')).min(assessmentAnswerSubmissionAnswerFourElementIdsMin).max(assessmentAnswerSubmissionAnswerFourElementIdsMax)
}).describe('Every element of the item exactly once, in the chosen order. Two answers are equal only when the sequences are identical.'),zod.object({
"format": zod.enum(['find_error']),
"line_numbers": zod.array(zod.int().min(1).max(assessmentAnswerSubmissionAnswerFiveLineNumbersItemMax)).min(1).max(assessmentAnswerSubmissionAnswerFiveLineNumbersMax)
}).describe('Selected line numbers, at most the `max_selections` of the item. Two answers are equal when they select the same set of lines, in any order.'),zod.object({
"format": zod.enum(['configuration']),
"config": zod.string().min(1).max(assessmentAnswerSubmissionAnswerSixConfigMax)
}).describe('Submitted configuration text, at most the `max_length` of the item. Two answers are equal only when their texts are identical, including whitespace and line breaks.'),zod.object({
"format": zod.enum(['practice']),
"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('One of the `languages` of the practice item, or null when the item offers none.'),
"source_code": zod.string().min(1).max(assessmentAnswerSubmissionAnswerSevenSourceCodeMax)
}).describe('Practice solution. It runs in the isolated sandbox without network access, secrets, or business data. Two submissions are equal only when the language is the same and the source texts are identical. The source is never echoed in a response or a problem.')]).describe('Candidate answer, selected by `format`, which must equal the format of the answered item. It carries only the answer: no score, duration, correctness flag, or seed. The server records the times itself and scores the answer with the key of the fixed item instance. Each format defines when two answers are equal, which decides whether a repeated submission is the same answer.')
}).describe('Answer to one item of the attempt. Unknown fields are rejected, so a request cannot send a score, a duration, or a correctness flag.')
export type AssessmentAnswerSubmission = zod.input<typeof AssessmentAnswerSubmission>;
export type AssessmentAnswerSubmissionOutput = zod.output<typeof AssessmentAnswerSubmission>;
@@ -0,0 +1,190 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const assessmentAttemptVersionsBankVersionMax = 64;
export const assessmentAttemptVersionsBankVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$');
export const assessmentAttemptVersionsAlgorithmVersionMax = 64;
export const assessmentAttemptVersionsAlgorithmVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$');
export const assessmentAttemptSessionsOneUsedMax = 10;
export const assessmentAttemptSessionsOneMaxMax = 10;
export const assessmentAttemptSessionsOneIdleTimeoutSecondsMin = 60;
export const assessmentAttemptSessionsOneIdleTimeoutSecondsMax = 86400;
export const assessmentAttemptProgressAnsweredItemsMin = 0;
export const assessmentAttemptProgressAnsweredItemsMax = 100;
export const assessmentAttemptProgressMaxItemsMax = 100;
export const assessmentAttemptCurrentItemOneSequenceMax = 100;
export const assessmentAttemptCurrentItemOnePromptMax = 20000;
export const assessmentAttemptCurrentItemOneContentOneOptionsItemIdMax = 32;
export const assessmentAttemptCurrentItemOneContentOneOptionsItemIdRegExp = new RegExp('^[A-Za-z0-9_-]+$');
export const assessmentAttemptCurrentItemOneContentOneOptionsItemTextMax = 2000;
export const assessmentAttemptCurrentItemOneContentOneOptionsMin = 2;
export const assessmentAttemptCurrentItemOneContentOneOptionsMax = 10;
export const assessmentAttemptCurrentItemOneContentTwoUnitMax = 32;
export const assessmentAttemptCurrentItemOneContentThreeMaxLengthMax = 500;
export const assessmentAttemptCurrentItemOneContentFourElementsItemIdMax = 32;
export const assessmentAttemptCurrentItemOneContentFourElementsItemIdRegExp = new RegExp('^[A-Za-z0-9_-]+$');
export const assessmentAttemptCurrentItemOneContentFourElementsItemTextMax = 2000;
export const assessmentAttemptCurrentItemOneContentFourElementsMin = 2;
export const assessmentAttemptCurrentItemOneContentFourElementsMax = 20;
export const assessmentAttemptCurrentItemOneContentFiveSyntaxMax = 32;
export const assessmentAttemptCurrentItemOneContentFiveSyntaxRegExp = new RegExp('^[a-z0-9_+-]+$');
export const assessmentAttemptCurrentItemOneContentFiveLinesItemNumberMax = 500;
export const assessmentAttemptCurrentItemOneContentFiveLinesItemTextMax = 1000;
export const assessmentAttemptCurrentItemOneContentFiveLinesMax = 500;
export const assessmentAttemptCurrentItemOneContentFiveMaxSelectionsMax = 10;
export const assessmentAttemptCurrentItemOneContentSixSyntaxMax = 32;
export const assessmentAttemptCurrentItemOneContentSixSyntaxRegExp = new RegExp('^[a-z0-9_+-]+$');
export const assessmentAttemptCurrentItemOneContentSixInitialConfigMax = 20000;
export const assessmentAttemptCurrentItemOneContentSixMaxLengthMax = 20000;
export const assessmentAttemptCurrentItemOneContentSevenLanguagesMax = 2;
export const assessmentAttemptCurrentItemOneContentSevenPublicExamplesItemInputMax = 10000;
export const assessmentAttemptCurrentItemOneContentSevenPublicExamplesItemExpectedOutputMax = 10000;
export const assessmentAttemptCurrentItemOneContentSevenPublicExamplesMax = 10;
export const assessmentAttemptCurrentItemOneContentSevenMaxSourceLengthMax = 65536;
export const assessmentAttemptPracticesItemVerdictOneScoreMin = 0;
export const assessmentAttemptPracticesItemVerdictOneScoreMax = 3;
export const assessmentAttemptPracticesItemVerdictOneMaxScoreMin = 3;
export const assessmentAttemptPracticesItemVerdictOneMaxScoreMax = 3;
export const assessmentAttemptPracticesItemVerdictOneGroupsItemGroupMax = 3;
export const assessmentAttemptPracticesItemVerdictOneGroupsMin = 3;
export const assessmentAttemptPracticesItemVerdictOneGroupsMax = 3;
export const assessmentAttemptPracticesMax = 5;
export const AssessmentAttempt = 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.'),
"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.')
}).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.'),
"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.'),
"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.')
}).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.'),
"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.'),
"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.')
}).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.')
}).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)
}).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.'),
"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.')
}).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.')
}).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.'),
"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.')
}).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(assessmentAttemptPracticesItemVerdictOneScoreMin).max(assessmentAttemptPracticesItemVerdictOneScoreMax),
"max_score": zod.int().min(assessmentAttemptPracticesItemVerdictOneMaxScoreMin).max(assessmentAttemptPracticesItemVerdictOneMaxScoreMax),
"groups": zod.array(zod.object({
"group": zod.int().min(1).max(assessmentAttemptPracticesItemVerdictOneGroupsItemGroupMax),
"passed": zod.boolean()
}).describe('Outcome of one hidden check group. It never contains the checks themselves.')).min(assessmentAttemptPracticesItemVerdictOneGroupsMin).max(assessmentAttemptPracticesItemVerdictOneGroupsMax)
}).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.')
export type AssessmentAttempt = zod.input<typeof AssessmentAttempt>;
export type AssessmentAttemptOutput = zod.output<typeof AssessmentAttempt>;
@@ -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 AssessmentAttemptCreate = zod.object({
"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.')
export type AssessmentAttemptCreate = zod.input<typeof AssessmentAttemptCreate>;
export type AssessmentAttemptCreateOutput = zod.output<typeof AssessmentAttemptCreate>;
@@ -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 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 type AssessmentAttemptState = zod.input<typeof AssessmentAttemptState>;
export type AssessmentAttemptStateOutput = zod.output<typeof AssessmentAttemptState>;
@@ -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 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 type AssessmentAttemptVersion = zod.input<typeof AssessmentAttemptVersion>;
export type AssessmentAttemptVersionOutput = zod.output<typeof AssessmentAttemptVersion>;
@@ -0,0 +1,38 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const assessmentAvailabilitySpecializationsItemGradesItemMaxSessionsMax = 10;
export const assessmentAvailabilitySpecializationsItemGradesItemMaxItemsMax = 100;
export const assessmentAvailabilitySpecializationsItemGradesMax = 10;
export const assessmentAvailabilitySpecializationsMax = 2;
export const AssessmentAvailability = zod.object({
"specializations": zod.array(zod.object({
"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.'),
"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('Currently confirmed grade of the specialization, or null.'),
"active_attempt_id": zod.uuid().nullable().describe('Identifier of the active attempt of the specialization, or null.'),
"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`.'),
"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.'),
"max_items": zod.int().min(1).max(assessmentAvailabilitySpecializationsItemGradesItemMaxItemsMax).nullable().describe('Item limit, as in `AssessmentProgress.max_items`.'),
"practice_required": zod.boolean().nullable().describe('Whether the attempt would include a main code practice.')
}).describe('Availability of an attempt for one grade of a specialization, with the limits that an attempt would have, so the client can show them before the start. The limit fields are null when the status is `insufficient_bank` or the policy defines no such limit.')).max(assessmentAvailabilitySpecializationsItemGradesMax).describe('Every grade of the scale in ascending order.')
}).describe('Assessment state of one questionnaire specialization. Specializations are assessed independently, with independent retry intervals.')).max(assessmentAvailabilitySpecializationsMax).describe('Questionnaire specializations in questionnaire order.')
}).describe('Assessment availability for the specializations of the current candidate\'s questionnaire, derived at the time of the request.')
export type AssessmentAvailability = zod.input<typeof AssessmentAvailability>;
export type AssessmentAvailabilityOutput = zod.output<typeof AssessmentAvailability>;
@@ -0,0 +1,20 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const assessmentDurationsItemsSecondsMin = 0;
export const assessmentDurationsPracticeSecondsMin = 0;
export const AssessmentDurations = zod.object({
"items_seconds": zod.int().min(assessmentDurationsItemsSecondsMin),
"practice_seconds": zod.int().min(assessmentDurationsPracticeSecondsMin).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.')
export type AssessmentDurations = zod.input<typeof AssessmentDurations>;
export type AssessmentDurationsOutput = zod.output<typeof AssessmentDurations>;
@@ -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 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`.')
}).describe('Command to finalize the attempt.')
export type AssessmentFinalization = zod.input<typeof AssessmentFinalization>;
export type AssessmentFinalizationOutput = zod.output<typeof AssessmentFinalization>;
@@ -0,0 +1,22 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const assessmentGapDomainMax = 64;
export const assessmentGapDomainRegExp = new RegExp('^[a-z0-9_]+$');
export const assessmentGapTitleMax = 200;
export const AssessmentGap = zod.object({
"domain": zod.string().min(1).max(assessmentGapDomainMax).regex(assessmentGapDomainRegExp).describe('Stable domain code of the bank blueprint.'),
"title": zod.string().min(1).max(assessmentGapTitleMax).describe('Display name in Russian. Plain text.')
}).describe('Domain of the specialization where the evidence was weak.')
export type AssessmentGap = zod.input<typeof AssessmentGap>;
export type AssessmentGapOutput = zod.output<typeof AssessmentGap>;
@@ -0,0 +1,27 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const assessmentGradeAvailabilityMaxSessionsMax = 10;
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`.'),
"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.'),
"max_items": zod.int().min(1).max(assessmentGradeAvailabilityMaxItemsMax).nullable().describe('Item limit, as in `AssessmentProgress.max_items`.'),
"practice_required": zod.boolean().nullable().describe('Whether the attempt would include a main code practice.')
}).describe('Availability of an attempt for one grade of a specialization, with the limits that an attempt would have, so the client can show them before the start. The limit fields are null when the status is `insufficient_bank` or the policy defines no such limit.')
export type AssessmentGradeAvailability = zod.input<typeof AssessmentGradeAvailability>;
export type AssessmentGradeAvailabilityOutput = zod.output<typeof AssessmentGradeAvailability>;
@@ -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 AssessmentGradeAvailabilityStatus = 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.')
export type AssessmentGradeAvailabilityStatus = zod.input<typeof AssessmentGradeAvailabilityStatus>;
export type AssessmentGradeAvailabilityStatusOutput = zod.output<typeof AssessmentGradeAvailabilityStatus>;
@@ -0,0 +1,15 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const AssessmentInterval = zod.object({
"low": zod.number(),
"high": zod.number()
}).describe('Interval on the ability scale.')
export type AssessmentInterval = zod.input<typeof AssessmentInterval>;
export type AssessmentIntervalOutput = zod.output<typeof AssessmentInterval>;
@@ -0,0 +1,114 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const assessmentItemSequenceMax = 100;
export const assessmentItemPromptMax = 20000;
export const assessmentItemContentOneOptionsItemIdMax = 32;
export const assessmentItemContentOneOptionsItemIdRegExp = new RegExp('^[A-Za-z0-9_-]+$');
export const assessmentItemContentOneOptionsItemTextMax = 2000;
export const assessmentItemContentOneOptionsMin = 2;
export const assessmentItemContentOneOptionsMax = 10;
export const assessmentItemContentTwoUnitMax = 32;
export const assessmentItemContentThreeMaxLengthMax = 500;
export const assessmentItemContentFourElementsItemIdMax = 32;
export const assessmentItemContentFourElementsItemIdRegExp = new RegExp('^[A-Za-z0-9_-]+$');
export const assessmentItemContentFourElementsItemTextMax = 2000;
export const assessmentItemContentFourElementsMin = 2;
export const assessmentItemContentFourElementsMax = 20;
export const assessmentItemContentFiveSyntaxMax = 32;
export const assessmentItemContentFiveSyntaxRegExp = new RegExp('^[a-z0-9_+-]+$');
export const assessmentItemContentFiveLinesItemNumberMax = 500;
export const assessmentItemContentFiveLinesItemTextMax = 1000;
export const assessmentItemContentFiveLinesMax = 500;
export const assessmentItemContentFiveMaxSelectionsMax = 10;
export const assessmentItemContentSixSyntaxMax = 32;
export const assessmentItemContentSixSyntaxRegExp = new RegExp('^[a-z0-9_+-]+$');
export const assessmentItemContentSixInitialConfigMax = 20000;
export const assessmentItemContentSixMaxLengthMax = 20000;
export const assessmentItemContentSevenLanguagesMax = 2;
export const assessmentItemContentSevenPublicExamplesItemInputMax = 10000;
export const assessmentItemContentSevenPublicExamplesItemExpectedOutputMax = 10000;
export const assessmentItemContentSevenPublicExamplesMax = 10;
export const assessmentItemContentSevenMaxSourceLengthMax = 65536;
export const AssessmentItem = 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(assessmentItemSequenceMax).describe('Position of the item in the attempt, from 1.'),
"prompt": zod.string().min(1).max(assessmentItemPromptMax).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(assessmentItemContentOneOptionsItemIdMax).regex(assessmentItemContentOneOptionsItemIdRegExp).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(assessmentItemContentOneOptionsItemTextMax).describe('Text of the option; the client shows it as text, never as HTML.')
}).describe('Choice option or order element. Plain text.')).min(assessmentItemContentOneOptionsMin).max(assessmentItemContentOneOptionsMax).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(assessmentItemContentTwoUnitMax).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(assessmentItemContentThreeMaxLengthMax).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(assessmentItemContentFourElementsItemIdMax).regex(assessmentItemContentFourElementsItemIdRegExp).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(assessmentItemContentFourElementsItemTextMax).describe('Text of the option; the client shows it as text, never as HTML.')
}).describe('Choice option or order element. Plain text.')).min(assessmentItemContentFourElementsMin).max(assessmentItemContentFourElementsMax)
}).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(assessmentItemContentFiveSyntaxMax).regex(assessmentItemContentFiveSyntaxRegExp).nullable().describe('Highlighting hint such as `go`, `python`, or `cisco_ios`, or null.'),
"lines": zod.array(zod.object({
"number": zod.int().min(1).max(assessmentItemContentFiveLinesItemNumberMax),
"text": zod.string().max(assessmentItemContentFiveLinesItemTextMax)
}).describe('One numbered line of a code or configuration fragment. Plain text.')).min(1).max(assessmentItemContentFiveLinesMax).describe('Lines numbered from 1 in order.'),
"max_selections": zod.int().min(1).max(assessmentItemContentFiveMaxSelectionsMax).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(assessmentItemContentSixSyntaxMax).regex(assessmentItemContentSixSyntaxRegExp).describe('Configuration syntax such as `cisco_ios`, `nginx`, or `yaml`.'),
"initial_config": zod.string().max(assessmentItemContentSixInitialConfigMax).describe('Starting text to edit; empty when the candidate writes it from scratch.'),
"max_length": zod.int().min(1).max(assessmentItemContentSixMaxLengthMax).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(assessmentItemContentSevenLanguagesMax).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(assessmentItemContentSevenPublicExamplesItemInputMax),
"expected_output": zod.string().max(assessmentItemContentSevenPublicExamplesItemExpectedOutputMax)
}).describe('Public example of the practice task: an input and its expected output. Hidden checks are never listed.')).max(assessmentItemContentSevenPublicExamplesMax),
"max_source_length": zod.int().min(1).max(assessmentItemContentSevenMaxSourceLengthMax).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.')
export type AssessmentItem = zod.input<typeof AssessmentItem>;
export type AssessmentItemOutput = zod.output<typeof AssessmentItem>;
@@ -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 AssessmentItemId = 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.')
export type AssessmentItemId = zod.input<typeof AssessmentItemId>;
export type AssessmentItemIdOutput = zod.output<typeof AssessmentItemId>;
@@ -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 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 type AssessmentLimitation = zod.input<typeof AssessmentLimitation>;
export type AssessmentLimitationOutput = zod.output<typeof AssessmentLimitation>;
@@ -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 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 type AssessmentMode = zod.input<typeof AssessmentMode>;
export type AssessmentModeOutput = zod.output<typeof AssessmentMode>;
@@ -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 AssessmentNextAction = 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.')
export type AssessmentNextAction = zod.input<typeof AssessmentNextAction>;
export type AssessmentNextActionOutput = zod.output<typeof AssessmentNextAction>;
@@ -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 AssessmentNextStep = 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.')
export type AssessmentNextStep = zod.input<typeof AssessmentNextStep>;
export type AssessmentNextStepOutput = zod.output<typeof AssessmentNextStep>;
@@ -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 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 type AssessmentNotDeterminedReason = zod.input<typeof AssessmentNotDeterminedReason>;
export type AssessmentNotDeterminedReasonOutput = zod.output<typeof AssessmentNotDeterminedReason>;
@@ -0,0 +1,22 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const assessmentOptionIdMax = 32;
export const assessmentOptionIdRegExp = new RegExp('^[A-Za-z0-9_-]+$');
export const assessmentOptionTextMax = 2000;
export const AssessmentOption = zod.object({
"id": zod.string().min(1).max(assessmentOptionIdMax).regex(assessmentOptionIdRegExp).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(assessmentOptionTextMax).describe('Text of the option; the client shows it as text, never as HTML.')
}).describe('Choice option or order element. Plain text.')
export type AssessmentOption = zod.input<typeof AssessmentOption>;
export type AssessmentOptionOutput = zod.output<typeof AssessmentOption>;
@@ -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 AssessmentOptionIdMax = 32;
export const AssessmentOptionIdRegExp = new RegExp('^[A-Za-z0-9_-]+$');
export const AssessmentOptionId = zod.string().min(1).max(AssessmentOptionIdMax).regex(AssessmentOptionIdRegExp).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.')
export type AssessmentOptionId = zod.input<typeof AssessmentOptionId>;
export type AssessmentOptionIdOutput = zod.output<typeof AssessmentOptionId>;
@@ -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 AssessmentOutcome = 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.')
export type AssessmentOutcome = zod.input<typeof AssessmentOutcome>;
export type AssessmentOutcomeOutput = zod.output<typeof AssessmentOutcome>;
@@ -0,0 +1,38 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const assessmentPracticeVerdictOneScoreMin = 0;
export const assessmentPracticeVerdictOneScoreMax = 3;
export const assessmentPracticeVerdictOneMaxScoreMin = 3;
export const assessmentPracticeVerdictOneMaxScoreMax = 3;
export const assessmentPracticeVerdictOneGroupsItemGroupMax = 3;
export const assessmentPracticeVerdictOneGroupsMin = 3;
export const assessmentPracticeVerdictOneGroupsMax = 3;
export const AssessmentPractice = 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(assessmentPracticeVerdictOneScoreMin).max(assessmentPracticeVerdictOneScoreMax),
"max_score": zod.int().min(assessmentPracticeVerdictOneMaxScoreMin).max(assessmentPracticeVerdictOneMaxScoreMax),
"groups": zod.array(zod.object({
"group": zod.int().min(1).max(assessmentPracticeVerdictOneGroupsItemGroupMax),
"passed": zod.boolean()
}).describe('Outcome of one hidden check group. It never contains the checks themselves.')).min(assessmentPracticeVerdictOneGroupsMin).max(assessmentPracticeVerdictOneGroupsMax)
}).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.')
export type AssessmentPractice = zod.input<typeof AssessmentPractice>;
export type AssessmentPracticeOutput = zod.output<typeof AssessmentPractice>;
@@ -0,0 +1,34 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const assessmentPracticeResultVerdictScoreMin = 0;
export const assessmentPracticeResultVerdictScoreMax = 3;
export const assessmentPracticeResultVerdictMaxScoreMin = 3;
export const assessmentPracticeResultVerdictMaxScoreMax = 3;
export const assessmentPracticeResultVerdictGroupsItemGroupMax = 3;
export const assessmentPracticeResultVerdictGroupsMin = 3;
export const assessmentPracticeResultVerdictGroupsMax = 3;
export const AssessmentPracticeResult = 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(assessmentPracticeResultVerdictScoreMin).max(assessmentPracticeResultVerdictScoreMax),
"max_score": zod.int().min(assessmentPracticeResultVerdictMaxScoreMin).max(assessmentPracticeResultVerdictMaxScoreMax),
"groups": zod.array(zod.object({
"group": zod.int().min(1).max(assessmentPracticeResultVerdictGroupsItemGroupMax),
"passed": zod.boolean()
}).describe('Outcome of one hidden check group. It never contains the checks themselves.')).min(assessmentPracticeResultVerdictGroupsMin).max(assessmentPracticeResultVerdictGroupsMax)
}).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.')
export type AssessmentPracticeResult = zod.input<typeof AssessmentPracticeResult>;
export type AssessmentPracticeResultOutput = zod.output<typeof AssessmentPracticeResult>;
@@ -0,0 +1,21 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const assessmentProgressAnsweredItemsMin = 0;
export const assessmentProgressAnsweredItemsMax = 100;
export const assessmentProgressMaxItemsMax = 100;
export const AssessmentProgress = zod.object({
"answered_items": zod.int().min(assessmentProgressAnsweredItemsMin).max(assessmentProgressAnsweredItemsMax),
"max_items": zod.int().min(1).max(assessmentProgressMaxItemsMax).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`.')
export type AssessmentProgress = zod.input<typeof AssessmentProgress>;
export type AssessmentProgressOutput = zod.output<typeof AssessmentProgress>;
@@ -0,0 +1,117 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const assessmentResultVersionsBankVersionMax = 64;
export const assessmentResultVersionsBankVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$');
export const assessmentResultVersionsAlgorithmVersionMax = 64;
export const assessmentResultVersionsAlgorithmVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$');
export const assessmentResultLimitationsMax = 10;
export const assessmentResultUncertaintyOneStandardErrorMin = 0;
export const assessmentResultUncertaintyOnePGradeMin = 0;
export const assessmentResultUncertaintyOnePGradeMax = 1;
export const assessmentResultBasicScoreOnePointsMin = 0;
export const assessmentResultPracticesItemVerdictScoreMin = 0;
export const assessmentResultPracticesItemVerdictScoreMax = 3;
export const assessmentResultPracticesItemVerdictMaxScoreMin = 3;
export const assessmentResultPracticesItemVerdictMaxScoreMax = 3;
export const assessmentResultPracticesItemVerdictGroupsItemGroupMax = 3;
export const assessmentResultPracticesItemVerdictGroupsMin = 3;
export const assessmentResultPracticesItemVerdictGroupsMax = 3;
export const assessmentResultPracticesMax = 5;
export const assessmentResultGapsItemDomainMax = 64;
export const assessmentResultGapsItemDomainRegExp = new RegExp('^[a-z0-9_]+$');
export const assessmentResultGapsItemTitleMax = 200;
export const assessmentResultGapsMax = 20;
export const assessmentResultDurationsItemsSecondsMin = 0;
export const assessmentResultDurationsPracticeSecondsMin = 0;
export const assessmentResultNextStepsMax = 5;
export const AssessmentResult = 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.'),
"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.'),
"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.')
}).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.'),
"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),
"uncertainty": zod.union([zod.object({
"theta": zod.number(),
"standard_error": zod.number().min(assessmentResultUncertaintyOneStandardErrorMin),
"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.')
}).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),
"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),
"groups": zod.array(zod.object({
"group": zod.int().min(1).max(assessmentResultPracticesItemVerdictGroupsItemGroupMax),
"passed": zod.boolean()
}).describe('Outcome of one hidden check group. It never contains the checks themselves.')).min(assessmentResultPracticesItemVerdictGroupsMin).max(assessmentResultPracticesItemVerdictGroupsMax)
}).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.'),
"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.'),
"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.')
}).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),
"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`.')
export type AssessmentResult = zod.input<typeof AssessmentResult>;
export type AssessmentResultOutput = zod.output<typeof AssessmentResult>;
@@ -0,0 +1,24 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const assessmentSessionsUsedMax = 10;
export const assessmentSessionsMaxMax = 10;
export const assessmentSessionsIdleTimeoutSecondsMin = 60;
export const assessmentSessionsIdleTimeoutSecondsMax = 86400;
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.')
export type AssessmentSessions = zod.input<typeof AssessmentSessions>;
export type AssessmentSessionsOutput = zod.output<typeof AssessmentSessions>;
@@ -0,0 +1,34 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const assessmentSpecializationAvailabilityGradesItemMaxSessionsMax = 10;
export const assessmentSpecializationAvailabilityGradesItemMaxItemsMax = 100;
export const assessmentSpecializationAvailabilityGradesMax = 10;
export const AssessmentSpecializationAvailability = zod.object({
"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.'),
"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('Currently confirmed grade of the specialization, or null.'),
"active_attempt_id": zod.uuid().nullable().describe('Identifier of the active attempt of the specialization, or null.'),
"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`.'),
"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.'),
"max_items": zod.int().min(1).max(assessmentSpecializationAvailabilityGradesItemMaxItemsMax).nullable().describe('Item limit, as in `AssessmentProgress.max_items`.'),
"practice_required": zod.boolean().nullable().describe('Whether the attempt would include a main code practice.')
}).describe('Availability of an attempt for one grade of a specialization, with the limits that an attempt would have, so the client can show them before the start. The limit fields are null when the status is `insufficient_bank` or the policy defines no such limit.')).max(assessmentSpecializationAvailabilityGradesMax).describe('Every grade of the scale in ascending order.')
}).describe('Assessment state of one questionnaire specialization. Specializations are assessed independently, with independent retry intervals.')
export type AssessmentSpecializationAvailability = zod.input<typeof AssessmentSpecializationAvailability>;
export type AssessmentSpecializationAvailabilityOutput = zod.output<typeof AssessmentSpecializationAvailability>;
@@ -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 AssessmentStrength = zod.enum(['high', 'medium']).describe('Strength of an adaptive confirmation: `high` or `medium`, by the probability bands of the recorded policy version.')
export type AssessmentStrength = zod.input<typeof AssessmentStrength>;
export type AssessmentStrengthOutput = zod.output<typeof AssessmentStrength>;
@@ -0,0 +1,26 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const assessmentUncertaintyStandardErrorMin = 0;
export const assessmentUncertaintyPGradeMin = 0;
export const assessmentUncertaintyPGradeMax = 1;
export const AssessmentUncertainty = zod.object({
"theta": zod.number(),
"standard_error": zod.number().min(assessmentUncertaintyStandardErrorMin),
"interval_95": zod.object({
"low": zod.number(),
"high": zod.number()
}).describe('Interval on the ability scale.'),
"p_grade": zod.number().min(assessmentUncertaintyPGradeMin).max(assessmentUncertaintyPGradeMax).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.')
export type AssessmentUncertainty = zod.input<typeof AssessmentUncertainty>;
export type AssessmentUncertaintyOutput = zod.output<typeof AssessmentUncertainty>;
@@ -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 AssessmentVersionLabelMax = 64;
export const AssessmentVersionLabelRegExp = new RegExp('^[A-Za-z0-9._-]+$');
export const AssessmentVersionLabel = zod.string().min(1).max(AssessmentVersionLabelMax).regex(AssessmentVersionLabelRegExp).describe('Opaque identifier of a published version, for example `backend-demo.2026-10.1`. Clients show it as text and never parse it.')
export type AssessmentVersionLabel = zod.input<typeof AssessmentVersionLabel>;
export type AssessmentVersionLabelOutput = zod.output<typeof AssessmentVersionLabel>;
@@ -0,0 +1,26 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const assessmentVersionsBankVersionMax = 64;
export const assessmentVersionsBankVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$');
export const assessmentVersionsAlgorithmVersionMax = 64;
export const assessmentVersionsAlgorithmVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$');
export const AssessmentVersions = 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(assessmentVersionsBankVersionMax).regex(assessmentVersionsBankVersionRegExp).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(assessmentVersionsAlgorithmVersionMax).regex(assessmentVersionsAlgorithmVersionRegExp).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.')
export type AssessmentVersions = zod.input<typeof AssessmentVersions>;
export type AssessmentVersionsOutput = zod.output<typeof AssessmentVersions>;
@@ -0,0 +1,21 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const basicScorePointsMin = 0;
export const BasicScore = zod.object({
"points": zod.int().min(basicScorePointsMin),
"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.')
export type BasicScore = zod.input<typeof BasicScore>;
export type BasicScoreOutput = zod.output<typeof BasicScore>;
@@ -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 CalibrationStatus = 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.')
export type CalibrationStatus = zod.input<typeof CalibrationStatus>;
export type CalibrationStatusOutput = zod.output<typeof CalibrationStatus>;
@@ -0,0 +1,22 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const choiceAnswerOptionIdsItemMax = 32;
export const choiceAnswerOptionIdsItemRegExp = new RegExp('^[A-Za-z0-9_-]+$');
export const choiceAnswerOptionIdsMax = 10;
export const ChoiceAnswer = zod.object({
"format": zod.enum(['choice']),
"option_ids": zod.array(zod.string().min(1).max(choiceAnswerOptionIdsItemMax).regex(choiceAnswerOptionIdsItemRegExp).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.')).min(1).max(choiceAnswerOptionIdsMax)
}).describe('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.')
export type ChoiceAnswer = zod.input<typeof ChoiceAnswer>;
export type ChoiceAnswerOutput = zod.output<typeof ChoiceAnswer>;
@@ -0,0 +1,29 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const choiceItemContentOptionsItemIdMax = 32;
export const choiceItemContentOptionsItemIdRegExp = new RegExp('^[A-Za-z0-9_-]+$');
export const choiceItemContentOptionsItemTextMax = 2000;
export const choiceItemContentOptionsMin = 2;
export const choiceItemContentOptionsMax = 10;
export const ChoiceItemContent = zod.object({
"format": zod.enum(['choice']),
"options": zod.array(zod.object({
"id": zod.string().min(1).max(choiceItemContentOptionsItemIdMax).regex(choiceItemContentOptionsItemIdRegExp).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(choiceItemContentOptionsItemTextMax).describe('Text of the option; the client shows it as text, never as HTML.')
}).describe('Choice option or order element. Plain text.')).min(choiceItemContentOptionsMin).max(choiceItemContentOptionsMax).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.')
export type ChoiceItemContent = zod.input<typeof ChoiceItemContent>;
export type ChoiceItemContentOutput = zod.output<typeof ChoiceItemContent>;
@@ -0,0 +1,20 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const codeLineNumberMax = 500;
export const codeLineTextMax = 1000;
export const CodeLine = zod.object({
"number": zod.int().min(1).max(codeLineNumberMax),
"text": zod.string().max(codeLineTextMax)
}).describe('One numbered line of a code or configuration fragment. Plain text.')
export type CodeLine = zod.input<typeof CodeLine>;
export type CodeLineOutput = zod.output<typeof CodeLine>;
@@ -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 configurationAnswerConfigMax = 20000;
export const ConfigurationAnswer = zod.object({
"format": zod.enum(['configuration']),
"config": zod.string().min(1).max(configurationAnswerConfigMax)
}).describe('Submitted configuration text, at most the `max_length` of the item. Two answers are equal only when their texts are identical, including whitespace and line breaks.')
export type ConfigurationAnswer = zod.input<typeof ConfigurationAnswer>;
export type ConfigurationAnswerOutput = zod.output<typeof ConfigurationAnswer>;
@@ -0,0 +1,26 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const configurationItemContentSyntaxMax = 32;
export const configurationItemContentSyntaxRegExp = new RegExp('^[a-z0-9_+-]+$');
export const configurationItemContentInitialConfigMax = 20000;
export const configurationItemContentMaxLengthMax = 20000;
export const ConfigurationItemContent = zod.object({
"format": zod.enum(['configuration']),
"syntax": zod.string().min(1).max(configurationItemContentSyntaxMax).regex(configurationItemContentSyntaxRegExp).describe('Configuration syntax such as `cisco_ios`, `nginx`, or `yaml`.'),
"initial_config": zod.string().max(configurationItemContentInitialConfigMax).describe('Starting text to edit; empty when the candidate writes it from scratch.'),
"max_length": zod.int().min(1).max(configurationItemContentMaxLengthMax).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.')
export type ConfigurationItemContent = zod.input<typeof ConfigurationItemContent>;
export type ConfigurationItemContentOutput = zod.output<typeof ConfigurationItemContent>;
@@ -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 CreateMyAssessmentAttemptBody = zod.object({
"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.')
export type CreateMyAssessmentAttemptBody = zod.input<typeof CreateMyAssessmentAttemptBody>;
export type CreateMyAssessmentAttemptBodyOutput = zod.output<typeof CreateMyAssessmentAttemptBody>;
@@ -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 createMyAssessmentAttemptHeadersIdempotencyKeyMax = 255;
export const createMyAssessmentAttemptHeadersIdempotencyKeyRegExp = new RegExp('^[A-Za-z0-9._:-]+$');
export const CreateMyAssessmentAttemptHeaders = zod.object({
"Idempotency-Key": zod.string().min(1).max(createMyAssessmentAttemptHeadersIdempotencyKeyMax).regex(createMyAssessmentAttemptHeadersIdempotencyKeyRegExp)
})
export type CreateMyAssessmentAttemptHeaders = zod.input<typeof CreateMyAssessmentAttemptHeaders>;
export type CreateMyAssessmentAttemptHeadersOutput = zod.output<typeof CreateMyAssessmentAttemptHeaders>;
@@ -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 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`.')
}).describe('Command to finalize the attempt.')
export type FinalizeMyAssessmentAttemptBody = zod.input<typeof FinalizeMyAssessmentAttemptBody>;
export type FinalizeMyAssessmentAttemptBodyOutput = zod.output<typeof FinalizeMyAssessmentAttemptBody>;
@@ -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 finalizeMyAssessmentAttemptHeadersIdempotencyKeyMax = 255;
export const finalizeMyAssessmentAttemptHeadersIdempotencyKeyRegExp = new RegExp('^[A-Za-z0-9._:-]+$');
export const FinalizeMyAssessmentAttemptHeaders = zod.object({
"Idempotency-Key": zod.string().min(1).max(finalizeMyAssessmentAttemptHeadersIdempotencyKeyMax).regex(finalizeMyAssessmentAttemptHeadersIdempotencyKeyRegExp)
})
export type FinalizeMyAssessmentAttemptHeaders = zod.input<typeof FinalizeMyAssessmentAttemptHeaders>;
export type FinalizeMyAssessmentAttemptHeadersOutput = zod.output<typeof FinalizeMyAssessmentAttemptHeaders>;
@@ -0,0 +1,20 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const findErrorAnswerLineNumbersItemMax = 500;
export const findErrorAnswerLineNumbersMax = 10;
export const FindErrorAnswer = zod.object({
"format": zod.enum(['find_error']),
"line_numbers": zod.array(zod.int().min(1).max(findErrorAnswerLineNumbersItemMax)).min(1).max(findErrorAnswerLineNumbersMax)
}).describe('Selected line numbers, at most the `max_selections` of the item. Two answers are equal when they select the same set of lines, in any order.')
export type FindErrorAnswer = zod.input<typeof FindErrorAnswer>;
export type FindErrorAnswerOutput = zod.output<typeof FindErrorAnswer>;
@@ -0,0 +1,33 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const findErrorItemContentSyntaxMax = 32;
export const findErrorItemContentSyntaxRegExp = new RegExp('^[a-z0-9_+-]+$');
export const findErrorItemContentLinesItemNumberMax = 500;
export const findErrorItemContentLinesItemTextMax = 1000;
export const findErrorItemContentLinesMax = 500;
export const findErrorItemContentMaxSelectionsMax = 10;
export const FindErrorItemContent = zod.object({
"format": zod.enum(['find_error']),
"syntax": zod.string().min(1).max(findErrorItemContentSyntaxMax).regex(findErrorItemContentSyntaxRegExp).nullable().describe('Highlighting hint such as `go`, `python`, or `cisco_ios`, or null.'),
"lines": zod.array(zod.object({
"number": zod.int().min(1).max(findErrorItemContentLinesItemNumberMax),
"text": zod.string().max(findErrorItemContentLinesItemTextMax)
}).describe('One numbered line of a code or configuration fragment. Plain text.')).min(1).max(findErrorItemContentLinesMax).describe('Lines numbered from 1 in order.'),
"max_selections": zod.int().min(1).max(findErrorItemContentMaxSelectionsMax).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.')
export type FindErrorItemContent = zod.input<typeof FindErrorItemContent>;
export type FindErrorItemContentOutput = zod.output<typeof FindErrorItemContent>;
@@ -0,0 +1,70 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
export * from './assessmentAnswer.zod';
export * from './assessmentAnswerSubmission.zod';
export * from './assessmentAttempt.zod';
export * from './assessmentAttemptCreate.zod';
export * from './assessmentAttemptState.zod';
export * from './assessmentAttemptVersion.zod';
export * from './assessmentAvailability.zod';
export * from './assessmentDurations.zod';
export * from './assessmentFinalization.zod';
export * from './assessmentGap.zod';
export * from './assessmentGradeAvailability.zod';
export * from './assessmentGradeAvailabilityStatus.zod';
export * from './assessmentInterval.zod';
export * from './assessmentItem.zod';
export * from './assessmentItemId.zod';
export * from './assessmentLimitation.zod';
export * from './assessmentMode.zod';
export * from './assessmentNextAction.zod';
export * from './assessmentNextStep.zod';
export * from './assessmentNotDeterminedReason.zod';
export * from './assessmentOption.zod';
export * from './assessmentOptionId.zod';
export * from './assessmentOutcome.zod';
export * from './assessmentPractice.zod';
export * from './assessmentPracticeResult.zod';
export * from './assessmentProgress.zod';
export * from './assessmentResult.zod';
export * from './assessmentSessions.zod';
export * from './assessmentSpecializationAvailability.zod';
export * from './assessmentStrength.zod';
export * from './assessmentUncertainty.zod';
export * from './assessmentVersionLabel.zod';
export * from './assessmentVersions.zod';
export * from './basicScore.zod';
export * from './calibrationStatus.zod';
export * from './choiceAnswer.zod';
export * from './choiceItemContent.zod';
export * from './codeLine.zod';
export * from './configurationAnswer.zod';
export * from './configurationItemContent.zod';
export * from './createMyAssessmentAttemptBody.zod';
export * from './createMyAssessmentAttemptHeaders.zod';
export * from './finalizeMyAssessmentAttemptBody.zod';
export * from './finalizeMyAssessmentAttemptHeaders.zod';
export * from './findErrorAnswer.zod';
export * from './findErrorItemContent.zod';
export * from './itemContent.zod';
export * from './numberAnswer.zod';
export * from './numberItemContent.zod';
export * from './orderAnswer.zod';
export * from './orderItemContent.zod';
export * from './practiceAnswer.zod';
export * from './practiceExample.zod';
export * from './practiceFailureReason.zod';
export * from './practiceGroupResult.zod';
export * from './practiceItemContent.zod';
export * from './practiceKind.zod';
export * from './practiceStatus.zod';
export * from './practiceVerdict.zod';
export * from './stringAnswer.zod';
export * from './stringItemContent.zod';
export * from './submitMyAssessmentAnswerBody.zod';
export * from './submitMyAssessmentAnswerHeaders.zod';
@@ -0,0 +1,105 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const itemContentOneOptionsItemIdMax = 32;
export const itemContentOneOptionsItemIdRegExp = new RegExp('^[A-Za-z0-9_-]+$');
export const itemContentOneOptionsItemTextMax = 2000;
export const itemContentOneOptionsMin = 2;
export const itemContentOneOptionsMax = 10;
export const itemContentTwoUnitMax = 32;
export const itemContentThreeMaxLengthMax = 500;
export const itemContentFourElementsItemIdMax = 32;
export const itemContentFourElementsItemIdRegExp = new RegExp('^[A-Za-z0-9_-]+$');
export const itemContentFourElementsItemTextMax = 2000;
export const itemContentFourElementsMin = 2;
export const itemContentFourElementsMax = 20;
export const itemContentFiveSyntaxMax = 32;
export const itemContentFiveSyntaxRegExp = new RegExp('^[a-z0-9_+-]+$');
export const itemContentFiveLinesItemNumberMax = 500;
export const itemContentFiveLinesItemTextMax = 1000;
export const itemContentFiveLinesMax = 500;
export const itemContentFiveMaxSelectionsMax = 10;
export const itemContentSixSyntaxMax = 32;
export const itemContentSixSyntaxRegExp = new RegExp('^[a-z0-9_+-]+$');
export const itemContentSixInitialConfigMax = 20000;
export const itemContentSixMaxLengthMax = 20000;
export const itemContentSevenLanguagesMax = 2;
export const itemContentSevenPublicExamplesItemInputMax = 10000;
export const itemContentSevenPublicExamplesItemExpectedOutputMax = 10000;
export const itemContentSevenPublicExamplesMax = 10;
export const itemContentSevenMaxSourceLengthMax = 65536;
export const ItemContent = zod.union([zod.object({
"format": zod.enum(['choice']),
"options": zod.array(zod.object({
"id": zod.string().min(1).max(itemContentOneOptionsItemIdMax).regex(itemContentOneOptionsItemIdRegExp).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(itemContentOneOptionsItemTextMax).describe('Text of the option; the client shows it as text, never as HTML.')
}).describe('Choice option or order element. Plain text.')).min(itemContentOneOptionsMin).max(itemContentOneOptionsMax).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(itemContentTwoUnitMax).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(itemContentThreeMaxLengthMax).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(itemContentFourElementsItemIdMax).regex(itemContentFourElementsItemIdRegExp).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(itemContentFourElementsItemTextMax).describe('Text of the option; the client shows it as text, never as HTML.')
}).describe('Choice option or order element. Plain text.')).min(itemContentFourElementsMin).max(itemContentFourElementsMax)
}).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(itemContentFiveSyntaxMax).regex(itemContentFiveSyntaxRegExp).nullable().describe('Highlighting hint such as `go`, `python`, or `cisco_ios`, or null.'),
"lines": zod.array(zod.object({
"number": zod.int().min(1).max(itemContentFiveLinesItemNumberMax),
"text": zod.string().max(itemContentFiveLinesItemTextMax)
}).describe('One numbered line of a code or configuration fragment. Plain text.')).min(1).max(itemContentFiveLinesMax).describe('Lines numbered from 1 in order.'),
"max_selections": zod.int().min(1).max(itemContentFiveMaxSelectionsMax).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(itemContentSixSyntaxMax).regex(itemContentSixSyntaxRegExp).describe('Configuration syntax such as `cisco_ios`, `nginx`, or `yaml`.'),
"initial_config": zod.string().max(itemContentSixInitialConfigMax).describe('Starting text to edit; empty when the candidate writes it from scratch.'),
"max_length": zod.int().min(1).max(itemContentSixMaxLengthMax).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(itemContentSevenLanguagesMax).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(itemContentSevenPublicExamplesItemInputMax),
"expected_output": zod.string().max(itemContentSevenPublicExamplesItemExpectedOutputMax)
}).describe('Public example of the practice task: an input and its expected output. Hidden checks are never listed.')).max(itemContentSevenPublicExamplesMax),
"max_source_length": zod.int().min(1).max(itemContentSevenMaxSourceLengthMax).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.')
export type ItemContent = zod.input<typeof ItemContent>;
export type ItemContentOutput = zod.output<typeof ItemContent>;
@@ -0,0 +1,15 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const NumberAnswer = zod.object({
"format": zod.enum(['number']),
"number": zod.number()
}).describe('Numeric answer in the unit of the item. Two answers are equal when their decoded values are numerically equal, so 254 and 254.0 are the same answer.')
export type NumberAnswer = zod.input<typeof NumberAnswer>;
export type NumberAnswerOutput = zod.output<typeof NumberAnswer>;
@@ -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 numberItemContentUnitMax = 32;
export const NumberItemContent = zod.object({
"format": zod.enum(['number']),
"unit": zod.string().min(1).max(numberItemContentUnitMax).nullable().describe('Unit of the expected value, for example `ms`, or null.')
}).describe('Enter a number, optionally in the given unit.')
export type NumberItemContent = zod.input<typeof NumberItemContent>;
export type NumberItemContentOutput = zod.output<typeof NumberItemContent>;
@@ -0,0 +1,23 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const orderAnswerElementIdsItemMax = 32;
export const orderAnswerElementIdsItemRegExp = new RegExp('^[A-Za-z0-9_-]+$');
export const orderAnswerElementIdsMin = 2;
export const orderAnswerElementIdsMax = 20;
export const OrderAnswer = zod.object({
"format": zod.enum(['order']),
"element_ids": zod.array(zod.string().min(1).max(orderAnswerElementIdsItemMax).regex(orderAnswerElementIdsItemRegExp).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.')).min(orderAnswerElementIdsMin).max(orderAnswerElementIdsMax)
}).describe('Every element of the item exactly once, in the chosen order. Two answers are equal only when the sequences are identical.')
export type OrderAnswer = zod.input<typeof OrderAnswer>;
export type OrderAnswerOutput = zod.output<typeof OrderAnswer>;
@@ -0,0 +1,28 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const orderItemContentElementsItemIdMax = 32;
export const orderItemContentElementsItemIdRegExp = new RegExp('^[A-Za-z0-9_-]+$');
export const orderItemContentElementsItemTextMax = 2000;
export const orderItemContentElementsMin = 2;
export const orderItemContentElementsMax = 20;
export const OrderItemContent = zod.object({
"format": zod.enum(['order']),
"elements": zod.array(zod.object({
"id": zod.string().min(1).max(orderItemContentElementsItemIdMax).regex(orderItemContentElementsItemIdRegExp).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(orderItemContentElementsItemTextMax).describe('Text of the option; the client shows it as text, never as HTML.')
}).describe('Choice option or order element. Plain text.')).min(orderItemContentElementsMin).max(orderItemContentElementsMax)
}).describe('Put every element into the right order. The elements arrive in the order of this instance, which is never the answer.')
export type OrderItemContent = zod.input<typeof OrderItemContent>;
export type OrderItemContentOutput = zod.output<typeof OrderItemContent>;
@@ -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 practiceAnswerSourceCodeMax = 65536;
export const PracticeAnswer = zod.object({
"format": zod.enum(['practice']),
"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('One of the `languages` of the practice item, or null when the item offers none.'),
"source_code": zod.string().min(1).max(practiceAnswerSourceCodeMax)
}).describe('Practice solution. It runs in the isolated sandbox without network access, secrets, or business data. Two submissions are equal only when the language is the same and the source texts are identical. The source is never echoed in a response or a problem.')
export type PracticeAnswer = zod.input<typeof PracticeAnswer>;
export type PracticeAnswerOutput = zod.output<typeof PracticeAnswer>;
@@ -0,0 +1,20 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const practiceExampleInputMax = 10000;
export const practiceExampleExpectedOutputMax = 10000;
export const PracticeExample = zod.object({
"input": zod.string().max(practiceExampleInputMax),
"expected_output": zod.string().max(practiceExampleExpectedOutputMax)
}).describe('Public example of the practice task: an input and its expected output. Hidden checks are never listed.')
export type PracticeExample = zod.input<typeof PracticeExample>;
export type PracticeExampleOutput = zod.output<typeof PracticeExample>;
@@ -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 PracticeFailureReason = 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.')
export type PracticeFailureReason = zod.input<typeof PracticeFailureReason>;
export type PracticeFailureReasonOutput = zod.output<typeof PracticeFailureReason>;
@@ -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 practiceGroupResultGroupMax = 3;
export const PracticeGroupResult = zod.object({
"group": zod.int().min(1).max(practiceGroupResultGroupMax),
"passed": zod.boolean()
}).describe('Outcome of one hidden check group. It never contains the checks themselves.')
export type PracticeGroupResult = zod.input<typeof PracticeGroupResult>;
export type PracticeGroupResultOutput = zod.output<typeof PracticeGroupResult>;
@@ -0,0 +1,31 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const practiceItemContentLanguagesMax = 2;
export const practiceItemContentPublicExamplesItemInputMax = 10000;
export const practiceItemContentPublicExamplesItemExpectedOutputMax = 10000;
export const practiceItemContentPublicExamplesMax = 10;
export const practiceItemContentMaxSourceLengthMax = 65536;
export const PracticeItemContent = 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(practiceItemContentLanguagesMax).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(practiceItemContentPublicExamplesItemInputMax),
"expected_output": zod.string().max(practiceItemContentPublicExamplesItemExpectedOutputMax)
}).describe('Public example of the practice task: an input and its expected output. Hidden checks are never listed.')).max(practiceItemContentPublicExamplesMax),
"max_source_length": zod.int().min(1).max(practiceItemContentMaxSourceLengthMax).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.')
export type PracticeItemContent = zod.input<typeof PracticeItemContent>;
export type PracticeItemContentOutput = zod.output<typeof PracticeItemContent>;
@@ -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 PracticeKind = 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.')
export type PracticeKind = zod.input<typeof PracticeKind>;
export type PracticeKindOutput = zod.output<typeof PracticeKind>;
@@ -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 PracticeStatus = 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.')
export type PracticeStatus = zod.input<typeof PracticeStatus>;
export type PracticeStatusOutput = zod.output<typeof PracticeStatus>;
@@ -0,0 +1,31 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const practiceVerdictScoreMin = 0;
export const practiceVerdictScoreMax = 3;
export const practiceVerdictMaxScoreMin = 3;
export const practiceVerdictMaxScoreMax = 3;
export const practiceVerdictGroupsItemGroupMax = 3;
export const practiceVerdictGroupsMin = 3;
export const practiceVerdictGroupsMax = 3;
export const PracticeVerdict = zod.object({
"score": zod.int().min(practiceVerdictScoreMin).max(practiceVerdictScoreMax),
"max_score": zod.int().min(practiceVerdictMaxScoreMin).max(practiceVerdictMaxScoreMax),
"groups": zod.array(zod.object({
"group": zod.int().min(1).max(practiceVerdictGroupsItemGroupMax),
"passed": zod.boolean()
}).describe('Outcome of one hidden check group. It never contains the checks themselves.')).min(practiceVerdictGroupsMin).max(practiceVerdictGroupsMax)
}).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.')
export type PracticeVerdict = zod.input<typeof PracticeVerdict>;
export type PracticeVerdictOutput = zod.output<typeof PracticeVerdict>;
@@ -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 stringAnswerTextMax = 500;
export const StringAnswer = zod.object({
"format": zod.enum(['string']),
"text": zod.string().min(1).max(stringAnswerTextMax)
}).describe('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.')
export type StringAnswer = zod.input<typeof StringAnswer>;
export type StringAnswerOutput = zod.output<typeof StringAnswer>;
@@ -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 stringItemContentMaxLengthMax = 500;
export const StringItemContent = zod.object({
"format": zod.enum(['string']),
"max_length": zod.int().min(1).max(stringItemContentMaxLengthMax).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.')
export type StringItemContent = zod.input<typeof StringItemContent>;
export type StringItemContentOutput = zod.output<typeof StringItemContent>;
@@ -0,0 +1,63 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const submitMyAssessmentAnswerBodyAnswerOneOptionIdsItemMax = 32;
export const submitMyAssessmentAnswerBodyAnswerOneOptionIdsItemRegExp = new RegExp('^[A-Za-z0-9_-]+$');
export const submitMyAssessmentAnswerBodyAnswerOneOptionIdsMax = 10;
export const submitMyAssessmentAnswerBodyAnswerThreeTextMax = 500;
export const submitMyAssessmentAnswerBodyAnswerFourElementIdsItemMax = 32;
export const submitMyAssessmentAnswerBodyAnswerFourElementIdsItemRegExp = new RegExp('^[A-Za-z0-9_-]+$');
export const submitMyAssessmentAnswerBodyAnswerFourElementIdsMin = 2;
export const submitMyAssessmentAnswerBodyAnswerFourElementIdsMax = 20;
export const submitMyAssessmentAnswerBodyAnswerFiveLineNumbersItemMax = 500;
export const submitMyAssessmentAnswerBodyAnswerFiveLineNumbersMax = 10;
export const submitMyAssessmentAnswerBodyAnswerSixConfigMax = 20000;
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`.'),
"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']),
"option_ids": zod.array(zod.string().min(1).max(submitMyAssessmentAnswerBodyAnswerOneOptionIdsItemMax).regex(submitMyAssessmentAnswerBodyAnswerOneOptionIdsItemRegExp).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.')).min(1).max(submitMyAssessmentAnswerBodyAnswerOneOptionIdsMax)
}).describe('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.'),zod.object({
"format": zod.enum(['number']),
"number": zod.number()
}).describe('Numeric answer in the unit of the item. Two answers are equal when their decoded values are numerically equal, so 254 and 254.0 are the same answer.'),zod.object({
"format": zod.enum(['string']),
"text": zod.string().min(1).max(submitMyAssessmentAnswerBodyAnswerThreeTextMax)
}).describe('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.'),zod.object({
"format": zod.enum(['order']),
"element_ids": zod.array(zod.string().min(1).max(submitMyAssessmentAnswerBodyAnswerFourElementIdsItemMax).regex(submitMyAssessmentAnswerBodyAnswerFourElementIdsItemRegExp).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.')).min(submitMyAssessmentAnswerBodyAnswerFourElementIdsMin).max(submitMyAssessmentAnswerBodyAnswerFourElementIdsMax)
}).describe('Every element of the item exactly once, in the chosen order. Two answers are equal only when the sequences are identical.'),zod.object({
"format": zod.enum(['find_error']),
"line_numbers": zod.array(zod.int().min(1).max(submitMyAssessmentAnswerBodyAnswerFiveLineNumbersItemMax)).min(1).max(submitMyAssessmentAnswerBodyAnswerFiveLineNumbersMax)
}).describe('Selected line numbers, at most the `max_selections` of the item. Two answers are equal when they select the same set of lines, in any order.'),zod.object({
"format": zod.enum(['configuration']),
"config": zod.string().min(1).max(submitMyAssessmentAnswerBodyAnswerSixConfigMax)
}).describe('Submitted configuration text, at most the `max_length` of the item. Two answers are equal only when their texts are identical, including whitespace and line breaks.'),zod.object({
"format": zod.enum(['practice']),
"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('One of the `languages` of the practice item, or null when the item offers none.'),
"source_code": zod.string().min(1).max(submitMyAssessmentAnswerBodyAnswerSevenSourceCodeMax)
}).describe('Practice solution. It runs in the isolated sandbox without network access, secrets, or business data. Two submissions are equal only when the language is the same and the source texts are identical. The source is never echoed in a response or a problem.')]).describe('Candidate answer, selected by `format`, which must equal the format of the answered item. It carries only the answer: no score, duration, correctness flag, or seed. The server records the times itself and scores the answer with the key of the fixed item instance. Each format defines when two answers are equal, which decides whether a repeated submission is the same answer.')
}).describe('Answer to one item of the attempt. Unknown fields are rejected, so a request cannot send a score, a duration, or a correctness flag.')
export type SubmitMyAssessmentAnswerBody = zod.input<typeof SubmitMyAssessmentAnswerBody>;
export type SubmitMyAssessmentAnswerBodyOutput = zod.output<typeof SubmitMyAssessmentAnswerBody>;
@@ -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 submitMyAssessmentAnswerHeadersIdempotencyKeyMax = 255;
export const submitMyAssessmentAnswerHeadersIdempotencyKeyRegExp = new RegExp('^[A-Za-z0-9._:-]+$');
export const SubmitMyAssessmentAnswerHeaders = zod.object({
"Idempotency-Key": zod.string().min(1).max(submitMyAssessmentAnswerHeadersIdempotencyKeyMax).regex(submitMyAssessmentAnswerHeadersIdempotencyKeyRegExp)
})
export type SubmitMyAssessmentAnswerHeaders = zod.input<typeof SubmitMyAssessmentAnswerHeaders>;
export type SubmitMyAssessmentAnswerHeadersOutput = zod.output<typeof SubmitMyAssessmentAnswerHeaders>;
+1
View File
@@ -14,6 +14,7 @@ export * from './problemFieldLocation.zod';
export * from './specializationCode.zod';
export * from './taskLanguage.zod';
export * from './timestamp.zod';
export * from './assessment';
export * from './candidate';
export * from './catalog';
export * from './health';