feat(assessment): assign the demonstration category and keep result history
This commit is contained in:
1 parent
b3c6dc870b
commit
8277133712
61 files changed
+4338
-268
No files matched your search
@@ -251,6 +251,7 @@ The `assessment` tag covers the assessment attempts of the current candidate (PR
|
||||
| `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` |
|
||||
| `GET /api/v1/me/assessment-results` | `ListMyAssessmentResults` | session | 200 `AssessmentResultHistoryPage`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `forbidden` |
|
||||
| `GET /api/v1/me/assessment-signal-notice` | `GetMyAssessmentSignalNotice` | session | 200 `AssessmentSignalNotice`, `Cache-Control: no-store` | 401, 403 `forbidden` |
|
||||
| `PUT /api/v1/me/assessment-signal-notice` | `AcknowledgeMyAssessmentSignalNotice` | session and CSRF | 200 `AssessmentSignalNotice`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `csrf_check_failed` or `forbidden`, 409 `state_conflict` |
|
||||
|
||||
@@ -316,6 +317,8 @@ Result:
|
||||
- `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.
|
||||
- Category from a `demo_basic` result. A real result carries `category_decision`: `status` (`not_eligible`, `not_confirmed`, `assigned`, `unchanged`), the grade in force before and after the attempt, `method` (`demo_basic_pass_mark`), `source` (`synthetic_demo`), and `calibration_status`. The threshold comes from the accepted policy version pinned to the attempt: reaching it counts, and no request parameter sets it. A category is assigned only when `ASSESSMENT_DEMO_CATEGORIES_ENABLED` is on, the policy version is a complete demonstration policy with `demo_basic` (its threshold is its own `basic_pass_mark_bp`), and an operator attestation exists for the opening, its manifest, and the policy version; otherwise `status` is `not_eligible` and `confirmed_grade` is null even though `outcome` may be `confirmed`. `confirmed_grade` is set only when a reviewed source accepted the confirmation (`assigned` or `unchanged`). A failure, an equal grade, or a lower grade neither lowers nor changes the current category. `demo_express` never gets a `category_decision` and never creates a category. A result stored before category decisions existed has no `category_decision`: its current grade is not reconstructed afterwards.
|
||||
- `GET /api/v1/me/assessment-results` returns the history of the candidate only: completed `root` and `corrective` results, newest first by `decided_at` and `attempt_id`. The cursor is opaque, bound to the candidate, and uses only `[A-Za-z0-9_-]`; a foreign, altered, or malformed cursor answers 400 `validation_failed` with pointer `/cursor`. An employer account gets 403. A later change of the current policy, bank, or category changes no stored record. An employer receives only the current category (specialization, grade, and the coarse strength `standard`) through the anonymous card when the candidate published the `categories` field; the projection holds no attempt, score, version, or reason for a missing confirmation.
|
||||
|
||||
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 server signals of the anti-cheat layer (answer time, parallel sessions, address changes), which lead to a review and an appeal, never to a public label and never to the employer (PRD FR05).
|
||||
|
||||
|
||||
@@ -251,6 +251,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro
|
||||
| `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` |
|
||||
| `GET /api/v1/me/assessment-results` | `ListMyAssessmentResults` | сессия | 200 `AssessmentResultHistoryPage`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `forbidden` |
|
||||
| `GET /api/v1/me/assessment-signal-notice` | `GetMyAssessmentSignalNotice` | сессия | 200 `AssessmentSignalNotice`, `Cache-Control: no-store` | 401, 403 `forbidden` |
|
||||
| `PUT /api/v1/me/assessment-signal-notice` | `AcknowledgeMyAssessmentSignalNotice` | сессия и CSRF | 200 `AssessmentSignalNotice`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `csrf_check_failed` или `forbidden`, 409 `state_conflict` |
|
||||
|
||||
@@ -316,6 +317,8 @@ ML-сервис отвечает на ошибки той же схемой `Pro
|
||||
- `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, скрытые проверки или античит-сигналы.
|
||||
- Категория по результату `demo_basic`. Результат реальной попытки содержит `category_decision`: `status` (`not_eligible`, `not_confirmed`, `assigned`, `unchanged`), грейд, действовавший до попытки и после нее, `method` (`demo_basic_pass_mark`), `source` (`synthetic_demo`) и `calibration_status`. Порог берется из принятой версии политики, закрепленной за попыткой: достижение порога засчитывается, параметр запроса его не задает. Категория присваивается, только если включен `ASSESSMENT_DEMO_CATEGORIES_ENABLED`, версия политики является полной демонстрационной политикой с `demo_basic` (порог - ее собственный `basic_pass_mark_bp`), а для открытия, манифеста и версии политики есть аттестация оператора; иначе `status` равен `not_eligible`, `confirmed_grade` равен null, хотя `outcome` может быть `confirmed`. `confirmed_grade` заполнен, только когда подтверждение принято проверенным источником (`assigned` или `unchanged`). Неудача, равный или более низкий грейд не понижают и не меняют текущую категорию. `demo_express` никогда не получает `category_decision` и не создает категорию. Результат, сохраненный до появления решений о категориях, не содержит `category_decision`: его текущий грейд не восстанавливается задним числом.
|
||||
- `GET /api/v1/me/assessment-results` возвращает историю только самого кандидата: завершенные `root` и `corrective` результаты от новых к старым по `decided_at` и `attempt_id`. Курсор непрозрачен, привязан к кандидату и содержит только символы `[A-Za-z0-9_-]`; чужой, измененный или некорректный курсор дает 400 `validation_failed` с pointer `/cursor`. Аккаунт работодателя получает 403. Смена текущей политики, банка или категории не меняет ни одну сохраненную запись. Работодатель получает только текущую категорию (специализация, грейд и грубая сила `standard`) через анонимную карточку, если кандидат опубликовал поле `categories`; ни попытки, ни баллы, ни версии, ни причины неподтверждения в этой проекции нет.
|
||||
|
||||
Запланировано, добавляется без ломающих изменений: краткое описание подхода до 1500 знаков рядом с практикой, которое не определяет грейд (FR05 в PRD); операция отладочных запусков практики; серверные сигналы античит-слоя (время ответа, параллельные сессии, смена адреса); сигналы ведут к перепроверке и апелляции, а не к публичному ярлыку, и работодателю не показываются (FR05 в PRD).
|
||||
|
||||
|
||||
@@ -49,6 +49,14 @@ assessment-review-build: ## Build the local assessment review operator command
|
||||
@mkdir -p bin
|
||||
$(GO) build -buildvcs=false -trimpath -o bin/assessment-review ./cmd/assessment-review
|
||||
|
||||
.PHONY: assessment-category-attest assessment-category-attest-build
|
||||
assessment-category-attest: ## Attest a category opening for synthetic demonstration categories (set ARGS)
|
||||
$(GO) run ./cmd/assessment-category-attest $(ARGS)
|
||||
|
||||
assessment-category-attest-build: ## Build the local category attestation operator command
|
||||
@mkdir -p bin
|
||||
$(GO) build -buildvcs=false -trimpath -o bin/assessment-category-attest ./cmd/assessment-category-attest
|
||||
|
||||
.PHONY: deps install install-tools
|
||||
deps: ## Download pinned Go module dependencies
|
||||
$(GO) mod download
|
||||
|
||||
@@ -88,7 +88,11 @@ Creation pins the policy, bank and algorithm versions, the published family mani
|
||||
|
||||
Repeating a command with the same key and body returns its stored response for 24 hours. Reusing a key with another body returns 422; an unavailable bank or exhausted quota returns 409 `state_conflict`. PostgreSQL serializes quota checks and session updates, and domain time is read after lock waits. Migration 24 adds attempts, question instances, training bindings, and stored command responses; rolling it back deletes these records.
|
||||
|
||||
Answer submission evaluates the frozen server key and stores each answer once. Numeric comparison preserves the JSON number token without floating-point rounding; order answers must include every task exactly once. Finalization rejects unfinished required questions with their IDs, then stores the raw basic score, policy rationale, version pins, and result projection in one transaction. Reads use that immutable result. Duration does not add points, trailing seed items are unscored, and express results contain no qualification score. Migration 29 refuses rollback while command or result records depend on it. Category assignment remains separate work; a basic threshold is not evidence of calibration.
|
||||
Answer submission evaluates the frozen server key and stores each answer once. Numeric comparison preserves the JSON number token without floating-point rounding; order answers must include every task exactly once. Finalization rejects unfinished required questions with their IDs, then stores the raw basic score, policy rationale, version pins, and result projection in one transaction. Reads use that immutable result. Duration does not add points, trailing seed items are unscored, and express results contain no qualification score. Migration 29 refuses rollback while command or result records depend on it. A basic threshold is not evidence of calibration.
|
||||
|
||||
Demonstration category. Finalizing a real attempt writes a version 2 result: the immutable document gains a category decision and the grade in force at the moment of the decision (migration 31). A `demo_express` result stays a version 1 record without these fields and never creates a category. The decision depends on the `basic_pass_mark_bp` threshold of the policy version pinned to the attempt; the HTTP handler sets no parameter. A current category row (`candidate_assessment_categories`, one per candidate and specialization) appears only when all of the following hold: `ASSESSMENT_DEMO_CATEGORIES_ENABLED` is on (off by default; turn it on only on a synthetic stand), the pinned policy is a complete demonstration policy with `demo_basic` (its threshold is the policy's own `basic_pass_mark_bp`), the result is confirmed, and an operator attestation exists for the exact category opening, catalog manifest, and policy version (`assessment_synthetic_category_reviews`, `source = synthetic_demo`). Otherwise the decision is stored as `not_eligible` or `not_confirmed`. A candidate and specialization lock serializes promotions; the database accepts only a strict upgrade, forbids deletion and manual replacement of the source, and a current category always points at a stored version 2 result of the same candidate. A failure, an equal grade, or a lower grade keep the category in force, and both attempts stay in the history.
|
||||
|
||||
The candidate reads the history through `GET /api/v1/me/assessment-results` (`usecase/assessment/category_history.go`): own `root` and `corrective` results only, paged by a cursor that a server HMAC binds to the candidate. An employer gets no history; a separate projection of the current category is part of the visible-candidate query (`privacy_cohort.sql`) and selects only the specialization and grade, so the anonymous card shows the category with strength `standard` when the candidate published the `categories` field. A change of the current policy changes no stored result or category; opened categories are bound to the policy they were opened under, so no attempt is created after a new policy version until the categories are opened again. The attestation is created by the local command `make -C backend assessment-category-attest` (see [DEPLOY.md](../docs/en/DEPLOY.md#demonstration-categories-on-a-stand)). Calibration of the threshold is not implemented.
|
||||
|
||||
## Assessment signals
|
||||
|
||||
|
||||
+5
-1
@@ -88,7 +88,11 @@
|
||||
|
||||
Повтор команды с тем же ключом и телом возвращает сохраненный ответ в течение 24 часов. Повтор ключа с другим телом возвращает 422; недоступный банк или исчерпанная квота - 409 `state_conflict`. PostgreSQL сериализует проверку квоты и изменения сессии, а доменное время берется после ожидания блокировок. Миграция 24 добавляет попытки, экземпляры вопросов, учебные привязки и сохраненные ответы команд; ее откат удаляет эти данные.
|
||||
|
||||
Прием ответа проверяет закрепленный серверный ключ и сохраняет каждый ответ один раз. Сравнение чисел сохраняет исходную числовую запись JSON без округления через плавающую точку; ответ с порядком должен содержать каждую задачу ровно один раз. Завершение отклоняет неотвеченные обязательные вопросы с перечнем их ID, затем сохраняет сырой базовый балл, правило политики, закрепленные версии и представление результата в одной транзакции. Чтение использует этот неизменяемый результат. Длительность не добавляет баллы, последние seed-вопросы не оцениваются, а экспресс-результат не содержит квалификационного балла. Миграция 29 запрещает откат при наличии зависящих от нее записей команд или результатов. Присвоение категории остается отдельной работой; базовый порог не подтверждает калибровку.
|
||||
Прием ответа проверяет закрепленный серверный ключ и сохраняет каждый ответ один раз. Сравнение чисел сохраняет исходную числовую запись JSON без округления через плавающую точку; ответ с порядком должен содержать каждую задачу ровно один раз. Завершение отклоняет неотвеченные обязательные вопросы с перечнем их ID, затем сохраняет сырой базовый балл, правило политики, закрепленные версии и представление результата в одной транзакции. Чтение использует этот неизменяемый результат. Длительность не добавляет баллы, последние seed-вопросы не оцениваются, а экспресс-результат не содержит квалификационного балла. Миграция 29 запрещает откат при наличии зависящих от нее записей команд или результатов. Базовый порог не подтверждает калибровку.
|
||||
|
||||
Демонстрационная категория. Завершение реальной попытки записывает результат версии 2: к неизменяемому документу добавляются решение о категории и грейд, действовавший на момент решения (миграция 31). Результат `demo_express` остается записью версии 1 без этих полей и никогда не создает категорию. Решение зависит от порога `basic_pass_mark_bp` версии политики, закрепленной за попыткой; обработчик HTTP параметров не задает. Строка текущей категории (`candidate_assessment_categories`, по одной на кандидата и специализацию) появляется, только если одновременно выполнено следующее: включен `ASSESSMENT_DEMO_CATEGORIES_ENABLED` (по умолчанию выключен; включать только на синтетическом стенде), закрепленная политика является полной демонстрационной политикой с `demo_basic` (порог берется из ее `basic_pass_mark_bp`), результат подтвержден, а для точного открытия категории, манифеста каталога и версии политики есть аттестация оператора (`assessment_synthetic_category_reviews`, `source = synthetic_demo`). Иначе решение записывается как `not_eligible` или `not_confirmed`. Блокировка кандидата и специализации сериализует повышения; база принимает только строгое повышение, запрещает удаление и ручную подмену источника, а текущая категория всегда ссылается на сохраненный результат версии 2 того же кандидата. Неудача, равный или более низкий грейд сохраняют действующую категорию, а обе попытки остаются в истории.
|
||||
|
||||
История кандидата читается через `GET /api/v1/me/assessment-results` (`usecase/assessment/category_history.go`): только собственные `root` и `corrective` результаты, постранично, с курсором, привязанным к кандидату серверным HMAC. Работодатель историю не получает; отдельная проекция текущей категории входит в запрос видимых кандидатов (`privacy_cohort.sql`) и выбирает только специализацию и грейд, поэтому анонимная карточка показывает категорию с силой `standard`, если кандидат опубликовал поле `categories`. Смена текущей политики не меняет сохраненные результаты и категории; открытые категории привязаны к политике, под которой их открыли, поэтому после новой версии политики попытки не создаются, пока категории не открыты заново. Аттестацию создает локальная команда `make -C backend assessment-category-attest` (см. [DEPLOY.md](../docs/ru/DEPLOY.md#демонстрационные-категории-на-стенде)). Не реализована калибровка порога.
|
||||
|
||||
## Сигналы прохождения оценки
|
||||
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
// Command assessment-category-attest attests the current opening of one
|
||||
// assessment category as a source of synthetic demonstration categories. It
|
||||
// is for isolated synthetic stands only and changes nothing else.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/cli/categoryattest"
|
||||
)
|
||||
|
||||
func main() {
|
||||
os.Exit(run())
|
||||
}
|
||||
|
||||
func run() int {
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
if err := categoryattest.Run(ctx, os.Args[1:], os.LookupEnv, os.Stdout); err != nil {
|
||||
_, _ = fmt.Fprintf(os.Stderr, "assessment-category-attest: %v\n", err)
|
||||
return 2
|
||||
}
|
||||
return 0
|
||||
}
|
||||
@@ -97,12 +97,11 @@ BEGIN
|
||||
AND policy.policy_key = 'product'
|
||||
AND policy.kind = 'demo'
|
||||
AND policy.version = NEW.product_policy_version
|
||||
AND policy.document #>> '{assessment,attempt,real_mode}' = 'demo_basic'
|
||||
AND policy.document #>> '{assessment,attempt,basic_pass_mark_bp}' = '8000';
|
||||
AND policy.document #>> '{assessment,attempt,real_mode}' = 'demo_basic';
|
||||
IF NOT FOUND OR policy_version <> NEW.product_policy_version THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = '23514', CONSTRAINT = 'assessment_synthetic_category_review_policy',
|
||||
MESSAGE = 'synthetic category review policy is not an explicit demo basic policy';
|
||||
MESSAGE = 'synthetic category review policy is not a demo basic policy';
|
||||
END IF;
|
||||
|
||||
NEW.reviewed_at := clock_timestamp();
|
||||
@@ -263,6 +262,7 @@ LANGUAGE plpgsql AS $$
|
||||
DECLARE
|
||||
review assessment_synthetic_category_reviews%ROWTYPE;
|
||||
attempt assessment_attempts%ROWTYPE;
|
||||
pass_mark_text text;
|
||||
BEGIN
|
||||
IF NEW.schema_version = 1 THEN
|
||||
RETURN NEW;
|
||||
@@ -337,6 +337,21 @@ BEGIN
|
||||
ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_result_category_assignment',
|
||||
MESSAGE = 'category assignment is not a passing reviewed demo decision';
|
||||
END IF;
|
||||
|
||||
-- The threshold that confirmed the result is the pass mark of the policy
|
||||
-- version pinned to the attempt, read from the stored document and not
|
||||
-- from a constant. The text is checked before the cast.
|
||||
IF NEW.category_decision->>'status' = 'assigned' THEN
|
||||
SELECT policy.document #>> '{assessment,attempt,basic_pass_mark_bp}' INTO pass_mark_text
|
||||
FROM policy_versions AS policy
|
||||
WHERE policy.id = NEW.product_policy_version_id AND policy.policy_key = 'product';
|
||||
IF NOT FOUND OR pass_mark_text IS NULL OR pass_mark_text !~ '^[0-9]{1,5}$' OR
|
||||
NEW.pass_mark_basis_points IS DISTINCT FROM pass_mark_text::integer THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_result_category_threshold',
|
||||
MESSAGE = 'category assignment does not use the pass mark of its pinned policy version';
|
||||
END IF;
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
|
||||
@@ -21,7 +21,8 @@ INSERT INTO assessment_attempt_results (
|
||||
-- Returns both immutable result versions. NULL category fields identify a
|
||||
-- legacy v1 record and must not be reconstructed from current state.
|
||||
-- name: GetAssessmentAttemptResultHistoryEntry :one
|
||||
SELECT schema_version, result_snapshot::text, category_decision::text, current_confirmed_grade
|
||||
SELECT schema_version, result_snapshot::text,
|
||||
COALESCE(category_decision::text, '')::text AS category_decision, current_confirmed_grade
|
||||
FROM assessment_attempt_results
|
||||
WHERE user_id = sqlc.arg(user_id) AND attempt_id = sqlc.arg(attempt_id);
|
||||
|
||||
@@ -29,7 +30,7 @@ WHERE user_id = sqlc.arg(user_id) AND attempt_id = sqlc.arg(attempt_id);
|
||||
-- applies the keyset to the same stable order and fetches one extra row.
|
||||
-- name: ListCandidateAssessmentResults :many
|
||||
SELECT attempt_id, user_id, schema_version, result_snapshot::text,
|
||||
category_decision::text, current_confirmed_grade, decided_at
|
||||
COALESCE(category_decision::text, '')::text AS category_decision, current_confirmed_grade, decided_at
|
||||
FROM assessment_attempt_results
|
||||
WHERE user_id = sqlc.arg(user_id)
|
||||
AND kind IN ('root', 'corrective')
|
||||
@@ -69,8 +70,10 @@ WHERE review.opening_id = sqlc.arg(opening_id)
|
||||
AND opening.policy_version_id = sqlc.arg(grading_policy_version_id);
|
||||
|
||||
-- The application accepts only a validated immutable review snapshot. The
|
||||
-- trigger independently checks the source opening, manifest and policy.
|
||||
-- name: InsertSyntheticCategoryReview :exec
|
||||
-- trigger independently checks the source opening, manifest and policy. A
|
||||
-- concurrent or repeated attestation of the same exact source inserts nothing,
|
||||
-- and the caller reads the stored one.
|
||||
-- name: InsertSyntheticCategoryReview :execrows
|
||||
INSERT INTO assessment_synthetic_category_reviews (
|
||||
id, opening_id, category, source, opening_manifest_sha256,
|
||||
product_policy_version_id, product_policy_version, reviewed_by, reviewed_at
|
||||
@@ -78,10 +81,13 @@ INSERT INTO assessment_synthetic_category_reviews (
|
||||
sqlc.arg(id), sqlc.arg(opening_id), sqlc.arg(category), sqlc.arg(source),
|
||||
sqlc.arg(opening_manifest_sha256), sqlc.arg(product_policy_version_id),
|
||||
sqlc.arg(product_policy_version), sqlc.arg(reviewed_by), sqlc.arg(reviewed_at)
|
||||
);
|
||||
)
|
||||
ON CONFLICT ON CONSTRAINT assessment_synthetic_category_reviews_exact_source_key DO NOTHING;
|
||||
|
||||
-- Only strict grade upgrades replace the current row. The trigger enforces
|
||||
-- the same monotonic rule as a final guard against adapter mistakes.
|
||||
-- the same monotonic rule as a final guard against adapter mistakes. The
|
||||
-- grading policy is read from the immutable opening, and the guard trigger
|
||||
-- compares it with the policy captured in the assigned result.
|
||||
-- name: SaveCandidateAssessmentCategory :execrows
|
||||
INSERT INTO candidate_assessment_categories (
|
||||
candidate_id, specialization, grade, source_attempt_id, source_review_id,
|
||||
@@ -90,7 +96,12 @@ INSERT INTO candidate_assessment_categories (
|
||||
) VALUES (
|
||||
sqlc.arg(candidate_id), sqlc.arg(specialization), sqlc.arg(grade), sqlc.arg(source_attempt_id),
|
||||
sqlc.arg(source_review_id), sqlc.arg(product_policy_version_id), sqlc.arg(product_policy_version),
|
||||
sqlc.arg(grading_policy_version_id), sqlc.arg(opening_id), sqlc.arg(opening_manifest_sha256),
|
||||
(
|
||||
SELECT opening.policy_version_id
|
||||
FROM assessment_category_openings AS opening
|
||||
WHERE opening.id = sqlc.arg(opening_id)
|
||||
),
|
||||
sqlc.arg(opening_id), sqlc.arg(opening_manifest_sha256),
|
||||
sqlc.arg(source), sqlc.arg(calibration_status), sqlc.arg(assigned_at)
|
||||
)
|
||||
ON CONFLICT (candidate_id, specialization) DO UPDATE SET
|
||||
|
||||
@@ -4,7 +4,9 @@
|
||||
-- candidates hidden from this organization before any profile value is read.
|
||||
-- The projection reads only stack, declared role, and experience dates. It
|
||||
-- deliberately excludes names, contacts, salary, location, soft skills,
|
||||
-- employer names, summaries, and imported excerpts.
|
||||
-- employer names, summaries, and imported excerpts. The only assessment data
|
||||
-- is the current category (specialization and grade) of the separate current
|
||||
-- category table; it carries no attempt, score, review, policy, or history.
|
||||
-- name: ListVisibleCandidateViewSources :many
|
||||
SELECT
|
||||
effective.user_id,
|
||||
@@ -47,7 +49,18 @@ SELECT
|
||||
WHERE overlap.user_id = effective.user_id
|
||||
),
|
||||
'[]'::text
|
||||
) AS parallel_period_acknowledgements
|
||||
) AS parallel_period_acknowledgements,
|
||||
COALESCE(
|
||||
(
|
||||
SELECT jsonb_agg(
|
||||
jsonb_build_object('specialization', category.specialization, 'grade', category.grade)
|
||||
ORDER BY category.specialization
|
||||
)::text
|
||||
FROM candidate_assessment_categories AS category
|
||||
WHERE category.candidate_id = effective.user_id
|
||||
),
|
||||
'[]'::text
|
||||
) AS confirmed_categories
|
||||
FROM candidate_effective_publications AS effective
|
||||
LEFT JOIN candidate_profile_claims AS claim
|
||||
ON claim.user_id = effective.user_id
|
||||
@@ -170,7 +183,18 @@ SELECT
|
||||
WHERE overlap.user_id = effective.user_id
|
||||
),
|
||||
'[]'::text
|
||||
) AS parallel_period_acknowledgements
|
||||
) AS parallel_period_acknowledgements,
|
||||
COALESCE(
|
||||
(
|
||||
SELECT jsonb_agg(
|
||||
jsonb_build_object('specialization', category.specialization, 'grade', category.grade)
|
||||
ORDER BY category.specialization
|
||||
)::text
|
||||
FROM candidate_assessment_categories AS category
|
||||
WHERE category.candidate_id = effective.user_id
|
||||
),
|
||||
'[]'::text
|
||||
) AS confirmed_categories
|
||||
FROM candidate_effective_publications AS effective
|
||||
LEFT JOIN candidate_profile_claims AS claim
|
||||
ON claim.user_id = effective.user_id
|
||||
|
||||
@@ -491,6 +491,18 @@ type assessmentAttemptHTTPHarness struct {
|
||||
}
|
||||
|
||||
func newAssessmentAttemptHTTPHarness(ctx context.Context, t *testing.T, env *testEnvironment) *assessmentAttemptHTTPHarness {
|
||||
t.Helper()
|
||||
return newAssessmentAttemptHTTPHarnessWithCategories(ctx, t, env, assessment.AssessmentCategoryDecisionSettings{})
|
||||
}
|
||||
|
||||
// newAssessmentAttemptHTTPHarnessWithCategories builds the attempt router with
|
||||
// explicit category assignment settings. The zero settings deny assignment.
|
||||
func newAssessmentAttemptHTTPHarnessWithCategories(
|
||||
ctx context.Context,
|
||||
t *testing.T,
|
||||
env *testEnvironment,
|
||||
categories assessment.AssessmentCategoryDecisionSettings,
|
||||
) *assessmentAttemptHTTPHarness {
|
||||
t.Helper()
|
||||
pool := env.newPool(ctx, t)
|
||||
store := postgresadapter.NewIdentityStore(pool)
|
||||
@@ -521,9 +533,9 @@ func newAssessmentAttemptHTTPHarness(ctx context.Context, t *testing.T, env *tes
|
||||
)
|
||||
questionnaireHandler := v1.NewQuestionnaireHandler(questionnaireusecase.NewService(transactor, clock.Now))
|
||||
catalogHandler := v1.NewCatalogHandler(assessment.NewBank(transactor))
|
||||
attemptService, err := assessment.NewAttemptService(transactor, transactor, keyring, clock.Now)
|
||||
attemptService, err := assessment.NewAttemptServiceWithCategorySettings(transactor, transactor, keyring, clock.Now, categories)
|
||||
if err != nil {
|
||||
t.Fatalf("NewAttemptService() error = %v", err)
|
||||
t.Fatalf("NewAttemptServiceWithCategorySettings() error = %v", err)
|
||||
}
|
||||
signalObserver, err := assessment.NewSignalObserver(keyring)
|
||||
if err != nil {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -353,6 +353,10 @@ func TestOrganizationNeedsStorage(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
// needCreationResultMigrationVersion is the migration that creates
|
||||
// organization_need_creation_results.
|
||||
const needCreationResultMigrationVersion = 26
|
||||
|
||||
func TestNeedCreationResultMigrationRollbackPreflight(t *testing.T) {
|
||||
env := bootstrap(t, postgresService)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), organizationTestTimeout)
|
||||
@@ -362,6 +366,10 @@ func TestNeedCreationResultMigrationRollbackPreflight(t *testing.T) {
|
||||
if _, err := migrator.Up(ctx); err != nil {
|
||||
t.Fatalf("apply migrations to rollback test database: %v", err)
|
||||
}
|
||||
// The preflight belongs to the migration that created the replay table, so
|
||||
// the migrations added after it are rolled back first. The database holds
|
||||
// no data yet, which keeps their own guarded rollbacks out of this test.
|
||||
rollBackAboveMigration(ctx, t, migrator, needCreationResultMigrationVersion)
|
||||
pool := newPoolFor(ctx, t, databaseURL)
|
||||
now := time.Now().UTC().Truncate(time.Microsecond)
|
||||
fixture := organizationFixture{
|
||||
|
||||
@@ -49,7 +49,7 @@ var (
|
||||
{"candidate_questionnaire_specializations"}, {"candidate_questionnaires"},
|
||||
}
|
||||
assessmentAttemptTables = []pgx.Identifier{
|
||||
{"assessment_attempt_results"},
|
||||
{"candidate_assessment_categories"}, {"assessment_attempt_results"},
|
||||
{"assessment_signal_idempotency_outcomes"}, {"assessment_signal_events"}, {"assessment_signal_batches"},
|
||||
{"assessment_answer_observations"}, {"assessment_attempt_origin_marks"}, {"assessment_attempt_reviews"},
|
||||
{"assessment_attempt_items"}, {"assessment_attempts"}, {"assessment_attempt_idempotency_outcomes"},
|
||||
@@ -57,10 +57,15 @@ var (
|
||||
supportCaseTables = []pgx.Identifier{
|
||||
{"support_case_events"}, {"support_cases"}, {"support_case_create_outcomes"}, {"support_case_request_events"},
|
||||
}
|
||||
// userNoticeTables hold per-user notices that refer to users and, for the
|
||||
// inbox, to organizations.
|
||||
userNoticeTables = []pgx.Identifier{
|
||||
{"assessment_signal_notice_acknowledgements"}, {"notification_inbox_events"},
|
||||
}
|
||||
// usersDependentTables is every table that references users, directly or
|
||||
// through another table of the list. A TRUNCATE of users must name all of
|
||||
// them, so a migration that adds such a table adds it here.
|
||||
usersDependentTables = slices.Concat(identityTables, deliveryTables, consentTables, organizationTables, candidateProfileTables, candidateQuestionnaireTables, candidatePrivacyTables, assessmentAttemptTables, supportCaseTables)
|
||||
usersDependentTables = slices.Concat(identityTables, deliveryTables, consentTables, organizationTables, candidateProfileTables, candidateQuestionnaireTables, candidatePrivacyTables, assessmentAttemptTables, supportCaseTables, userNoticeTables)
|
||||
)
|
||||
|
||||
// organizationFixture works on the bootstrap database. The tables are
|
||||
|
||||
@@ -249,7 +249,8 @@ func TestPolicyVersions(t *testing.T) {
|
||||
assessment_training_bank_binding_families, assessment_attempts, assessment_attempt_items,
|
||||
support_cases, support_case_events, assessment_signal_idempotency_outcomes,
|
||||
assessment_signal_events, assessment_signal_batches, assessment_attempt_results,
|
||||
assessment_attempt_reviews, assessment_answer_observations, assessment_attempt_origin_marks`},
|
||||
assessment_attempt_reviews, assessment_answer_observations, assessment_attempt_origin_marks,
|
||||
assessment_synthetic_category_reviews, candidate_assessment_categories`},
|
||||
}
|
||||
for _, statement := range statements {
|
||||
_, err := fixture.pool.Exec(ctx, statement.sql, statement.args...)
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
// Package categoryattest implements the local operator command that attests the
|
||||
// current opening of an assessment category as a source of synthetic
|
||||
// demonstration categories. It is meant for isolated synthetic stands: a
|
||||
// category is assigned only when the runtime gate
|
||||
// ASSESSMENT_DEMO_CATEGORIES_ENABLED is also on.
|
||||
package categoryattest
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"lincodex/backend/config"
|
||||
"lincodex/backend/internal/adapter/secondary/postgres"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
"lincodex/backend/internal/usecase/assessment"
|
||||
)
|
||||
|
||||
// syntheticOnlyWarning is printed before any work, also when the command fails.
|
||||
const syntheticOnlyWarning = "warning: synthetic demonstration categories are enabled by this attestation; never on a production stand\n"
|
||||
|
||||
const usage = "usage: assessment-category-attest attest --specialization <code> --grade <code> [--task-language <code>] --actor operator:<handle>"
|
||||
|
||||
// Command is a parsed, validated attestation request.
|
||||
type Command struct {
|
||||
Specialization domain.SpecializationCode
|
||||
Grade domain.GradeCode
|
||||
TaskLanguage *domain.TaskLanguageCode
|
||||
Actor string
|
||||
}
|
||||
|
||||
// Attestor stores an attestation.
|
||||
type Attestor interface {
|
||||
Attest(
|
||||
ctx context.Context,
|
||||
specialization domain.SpecializationCode,
|
||||
grade domain.GradeCode,
|
||||
language *domain.TaskLanguageCode,
|
||||
actor string,
|
||||
) (assessment.CategoryAttestation, error)
|
||||
}
|
||||
|
||||
// Parse validates every argument before Run reads configuration or connects
|
||||
// to PostgreSQL.
|
||||
func Parse(args []string) (Command, error) {
|
||||
if len(args) == 0 || args[0] != "attest" {
|
||||
return Command{}, errors.New(usage)
|
||||
}
|
||||
flags := flag.NewFlagSet("assessment-category-attest attest", flag.ContinueOnError)
|
||||
flags.SetOutput(io.Discard)
|
||||
specialization := flags.String("specialization", "", "specialization code")
|
||||
grade := flags.String("grade", "", "grade code")
|
||||
language := flags.String("task-language", "", "task language code")
|
||||
actor := flags.String("actor", "", "operator handle")
|
||||
if err := flags.Parse(args[1:]); err != nil || flags.NArg() != 0 {
|
||||
return Command{}, errors.New(usage)
|
||||
}
|
||||
command := Command{
|
||||
Specialization: domain.SpecializationCode(strings.TrimSpace(*specialization)),
|
||||
Grade: domain.GradeCode(strings.TrimSpace(*grade)),
|
||||
Actor: strings.TrimSpace(*actor),
|
||||
}
|
||||
if !command.Specialization.IsKnown() {
|
||||
return Command{}, errors.New("specialization must be a known specialization code")
|
||||
}
|
||||
if !command.Grade.IsKnown() {
|
||||
return Command{}, errors.New("grade must be intern, junior, middle, or senior")
|
||||
}
|
||||
if trimmed := strings.TrimSpace(*language); trimmed != "" {
|
||||
taskLanguage := domain.TaskLanguageCode(trimmed)
|
||||
if !taskLanguage.IsKnown() {
|
||||
return Command{}, errors.New("task language must be a known task language code")
|
||||
}
|
||||
command.TaskLanguage = &taskLanguage
|
||||
}
|
||||
if _, err := domain.ParseAssessmentOperator(command.Actor); err != nil {
|
||||
return Command{}, errors.New("actor must be operator:<handle>")
|
||||
}
|
||||
return command, nil
|
||||
}
|
||||
|
||||
// Run parses the command, loads only DATABASE_URL from the supplied
|
||||
// environment, and executes the attestation. It does not load dotenv files.
|
||||
func Run(ctx context.Context, args []string, lookup config.LookupEnv, output io.Writer) error {
|
||||
command, err := Parse(args)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if lookup == nil || output == nil {
|
||||
return errors.New("category attestation command dependencies are required")
|
||||
}
|
||||
databaseURL := config.DatabaseURLFromEnv(lookup)
|
||||
if databaseURL == "" {
|
||||
return errors.New("DATABASE_URL is not set")
|
||||
}
|
||||
pool, err := postgres.NewPool(ctx, databaseURL)
|
||||
if err != nil {
|
||||
return errors.New("database configuration is invalid")
|
||||
}
|
||||
defer pool.Close()
|
||||
if err := pool.Ping(ctx); err != nil {
|
||||
return errors.New("database is unavailable")
|
||||
}
|
||||
attestor, err := assessment.NewCategoryAttestor(postgres.NewTransactor(pool))
|
||||
if err != nil {
|
||||
return errors.New("category attestation is unavailable")
|
||||
}
|
||||
return Execute(ctx, command, attestor, output)
|
||||
}
|
||||
|
||||
// Execute stores the attestation and prints identifiers and versions only; it
|
||||
// prints no candidate, answer, or contact data.
|
||||
func Execute(ctx context.Context, command Command, attestor Attestor, output io.Writer) error {
|
||||
if attestor == nil || output == nil {
|
||||
return errors.New("category attestation command dependencies are required")
|
||||
}
|
||||
if _, err := io.WriteString(output, syntheticOnlyWarning); err != nil {
|
||||
return errors.New("could not write the result")
|
||||
}
|
||||
attestation, err := attestor.Attest(ctx, command.Specialization, command.Grade, command.TaskLanguage, command.Actor)
|
||||
if err != nil {
|
||||
return safeOperationError(err)
|
||||
}
|
||||
status := "already attested"
|
||||
if attestation.Created {
|
||||
status = "attested"
|
||||
}
|
||||
if _, err := fmt.Fprintf(output,
|
||||
"%s: category %s, opening %s, review %s, policy_version %d, by %s\n"+
|
||||
"note: synthetic demonstration only; categories are assigned only while ASSESSMENT_DEMO_CATEGORIES_ENABLED is true on this stand\n",
|
||||
status, attestation.Category, attestation.OpeningID, attestation.ReviewID, attestation.ProductPolicyVersion, attestation.ReviewedBy,
|
||||
); err != nil {
|
||||
return errors.New("could not write the result")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func safeOperationError(err error) error {
|
||||
switch {
|
||||
case errors.Is(err, outbound.ErrAssessmentSelectionUnavailable), errors.Is(err, outbound.ErrAssessmentSelectionAmbiguous):
|
||||
return errors.New("no single current reviewed category matches the request")
|
||||
case errors.Is(err, domain.ErrInvalidAssessmentCategory):
|
||||
return errors.New("the request is invalid or the current policy is not the explicit demo_basic demonstration policy")
|
||||
default:
|
||||
return errors.New("category attestation failed")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package categoryattest
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/config"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
"lincodex/backend/internal/usecase/assessment"
|
||||
)
|
||||
|
||||
type attestorFake struct {
|
||||
attestation assessment.CategoryAttestation
|
||||
err error
|
||||
calls int
|
||||
command Command
|
||||
}
|
||||
|
||||
func (attestor *attestorFake) Attest(
|
||||
_ context.Context,
|
||||
specialization domain.SpecializationCode,
|
||||
grade domain.GradeCode,
|
||||
language *domain.TaskLanguageCode,
|
||||
actor string,
|
||||
) (assessment.CategoryAttestation, error) {
|
||||
attestor.calls++
|
||||
attestor.command = Command{Specialization: specialization, Grade: grade, TaskLanguage: language, Actor: actor}
|
||||
return attestor.attestation, attestor.err
|
||||
}
|
||||
|
||||
func TestParseRequiresATrackAndAnOperatorHandle(t *testing.T) {
|
||||
command, err := Parse([]string{"attest", "--specialization", "backend", "--grade", "intern", "--task-language", "go", "--actor", "operator:night"})
|
||||
if err != nil || command.Specialization != domain.SpecializationBackend || command.Grade != domain.GradeIntern ||
|
||||
command.TaskLanguage == nil || *command.TaskLanguage != domain.TaskLanguageGo || command.Actor != "operator:night" {
|
||||
t.Fatalf("Parse(valid) = %+v, %v", command, err)
|
||||
}
|
||||
if command, err := Parse([]string{"attest", "--specialization", "backend", "--grade", "junior", "--actor", "operator:night"}); err != nil || command.TaskLanguage != nil {
|
||||
t.Fatalf("Parse(without language) = %+v, %v", command, err)
|
||||
}
|
||||
for _, args := range [][]string{
|
||||
nil,
|
||||
{"list"},
|
||||
{"attest"},
|
||||
{"attest", "--specialization", "backend", "--grade", "junior"},
|
||||
{"attest", "--specialization", "backend", "--grade", "junior", "--actor", "alice"},
|
||||
{"attest", "--specialization", "chef", "--grade", "junior", "--actor", "operator:night"},
|
||||
{"attest", "--specialization", "backend", "--grade", "lead", "--actor", "operator:night"},
|
||||
{"attest", "--specialization", "backend", "--grade", "junior", "--task-language", "cobol", "--actor", "operator:night"},
|
||||
{"attest", "--specialization", "backend", "--grade", "junior", "--actor", "operator:night", "extra"},
|
||||
} {
|
||||
if _, err := Parse(args); err == nil {
|
||||
t.Errorf("Parse(%v) accepted invalid arguments", args)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunValidatesArgumentsBeforeReadingTheEnvironment(t *testing.T) {
|
||||
lookup := func(string) (string, bool) {
|
||||
t.Fatal("environment read before arguments were validated")
|
||||
return "", false
|
||||
}
|
||||
if err := Run(context.Background(), []string{"attest"}, lookup, &bytes.Buffer{}); err == nil {
|
||||
t.Fatal("Run(invalid arguments) succeeded")
|
||||
}
|
||||
var noDatabase config.LookupEnv = func(string) (string, bool) { return "", false }
|
||||
err := Run(context.Background(), []string{"attest", "--specialization", "backend", "--grade", "intern", "--actor", "operator:night"}, noDatabase, &bytes.Buffer{})
|
||||
if err == nil || !strings.Contains(err.Error(), "DATABASE_URL") {
|
||||
t.Fatalf("Run(no database) error = %v, want a DATABASE_URL message", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecutePrintsIdentifiersAndTheSyntheticOnlyNote(t *testing.T) {
|
||||
attestor := &attestorFake{attestation: assessment.CategoryAttestation{
|
||||
ReviewID: uuid.New(), OpeningID: uuid.New(), Category: "backend-intern", ProductPolicyVersion: 2,
|
||||
ReviewedBy: "operator:night", Created: true,
|
||||
}}
|
||||
var output bytes.Buffer
|
||||
command := Command{Specialization: domain.SpecializationBackend, Grade: domain.GradeIntern, Actor: "operator:night"}
|
||||
if err := Execute(context.Background(), command, attestor, &output); err != nil {
|
||||
t.Fatalf("Execute() error = %v", err)
|
||||
}
|
||||
if !strings.HasPrefix(output.String(), "warning: synthetic demonstration categories are enabled by this attestation; never on a production stand") {
|
||||
t.Errorf("output does not start with the synthetic-only warning:\n%s", output.String())
|
||||
}
|
||||
for _, want := range []string{"attested: category backend-intern", attestor.attestation.ReviewID.String(), "policy_version 2", "by operator:night", "synthetic demonstration only", "ASSESSMENT_DEMO_CATEGORIES_ENABLED"} {
|
||||
if !strings.Contains(output.String(), want) {
|
||||
t.Errorf("output lacks %q:\n%s", want, output.String())
|
||||
}
|
||||
}
|
||||
attestor.attestation.Created = false
|
||||
output.Reset()
|
||||
if err := Execute(context.Background(), command, attestor, &output); err != nil || !strings.Contains(output.String(), "\nalready attested") {
|
||||
t.Fatalf("Execute(repeat) = %v, %q, want an already attested line", err, output.String())
|
||||
}
|
||||
if attestor.calls != 2 || attestor.command.Actor != "operator:night" || attestor.command.Grade != domain.GradeIntern {
|
||||
t.Fatalf("attestor calls/command = %d/%+v, want the parsed request", attestor.calls, attestor.command)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecuteMapsFailuresToSafeMessages(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
err error
|
||||
want string
|
||||
}{
|
||||
{outbound.ErrAssessmentSelectionUnavailable, "no single current reviewed category"},
|
||||
{domain.ErrInvalidAssessmentCategory, "demo_basic"},
|
||||
{errors.New("pq: password authentication failed for user lincodex at 10.0.0.5"), "attestation failed"},
|
||||
} {
|
||||
err := Execute(context.Background(), Command{}, &attestorFake{err: test.err}, &bytes.Buffer{})
|
||||
if err == nil || !strings.Contains(err.Error(), test.want) || strings.Contains(err.Error(), "10.0.0.5") {
|
||||
t.Errorf("Execute(%v) error = %v, want a safe %q message", test.err, err, test.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -302,6 +302,9 @@ func TestAnonymousCardReachesNoProfileOrContactSchema(t *testing.T) {
|
||||
continue
|
||||
}
|
||||
for reached := range reachableSchemas(index, mustJSONValue(t, schema)) {
|
||||
if searchResultMayReachCardBand(name, reached) {
|
||||
continue
|
||||
}
|
||||
if isPrivacySchema(reached) && reached != "AnonymousCardContent" && reached != "CardCategory" && reached != "CardField" && reached != "CardFieldSet" {
|
||||
t.Errorf("%s reaches the candidate-private schema %s", name, reached)
|
||||
}
|
||||
@@ -320,6 +323,9 @@ func TestAnonymousCardReachesNoProfileOrContactSchema(t *testing.T) {
|
||||
}, reached) {
|
||||
continue
|
||||
}
|
||||
if path == "/api/v1/organizations/{org_id}/matches" && searchResultMayReachCardBand("Match", reached) {
|
||||
continue
|
||||
}
|
||||
if isPrivacySchema(reached) {
|
||||
t.Errorf("%s reaches the candidate-private schema %s", path, reached)
|
||||
}
|
||||
@@ -332,6 +338,18 @@ func TestAnonymousCardReachesNoProfileOrContactSchema(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// searchResultMayReachCardBand reports whether a match search schema reaches
|
||||
// one of the two coarse leaves that the anonymous card itself carries: the
|
||||
// salary compatibility (a compatible or not_compatible verdict, never an
|
||||
// amount) and the experience band (a coarse bucket, never a date). The search
|
||||
// contract reuses the card content, so its filters and results legitimately
|
||||
// name these leaves. Only match schemas get this allowance; no other
|
||||
// organization-visible schema may reach a privacy schema.
|
||||
func searchResultMayReachCardBand(schema, reached string) bool {
|
||||
return strings.HasPrefix(schema, "Match") &&
|
||||
(reached == "CandidateSalaryCompatibility" || reached == "CandidateExperienceBand")
|
||||
}
|
||||
|
||||
// The generated request DTOs carry only what the candidate may choose: no
|
||||
// consent identifier, time, interval, or policy version.
|
||||
func TestGeneratedPrivacyDTOsCarryNoServerOwnedFields(t *testing.T) {
|
||||
|
||||
@@ -36,6 +36,10 @@ var ownerCompanyOperations = map[apiadapter.OperationName]struct{}{
|
||||
apiadapter.GetOrganizationInvitationContactsOperation: {},
|
||||
apiadapter.WithdrawOrganizationInvitationOperation: {},
|
||||
apiadapter.RaiseOrganizationInvitationSalaryOperation: {},
|
||||
// The match search contract requires an active owner membership. The
|
||||
// operation has no handler yet; classifying it here keeps it closed to
|
||||
// every other role when the handler arrives.
|
||||
apiadapter.SearchOrganizationMatchesOperation: {},
|
||||
}
|
||||
|
||||
// NewCompanyContextMiddleware verifies every owner-scoped company operation
|
||||
|
||||
@@ -124,8 +124,8 @@ func TestCompanyContextOperationInventoryMatchesOpenAPI(t *testing.T) {
|
||||
if err := yaml.Unmarshal(data, &document); err != nil {
|
||||
t.Fatalf("decode OpenAPI bundle: %v", err)
|
||||
}
|
||||
if len(ownerCompanyOperations) != 14 {
|
||||
t.Fatalf("owner operation inventory has %d entries, want 14", len(ownerCompanyOperations))
|
||||
if len(ownerCompanyOperations) != 15 {
|
||||
t.Fatalf("owner operation inventory has %d entries, want 15", len(ownerCompanyOperations))
|
||||
}
|
||||
candidateExceptions := map[string]string{
|
||||
"HideOrganization": "/api/v1/me/privacy/hidden-organizations/{org_id}",
|
||||
|
||||
@@ -507,25 +507,40 @@ func assessmentResultResponse(result assessmentusecase.AssessmentAttemptResult)
|
||||
NextSteps: []api.AssessmentNextStep{}, Summary: result.Summary, DecidedAt: api.Timestamp(result.DecidedAt),
|
||||
}), nil
|
||||
}
|
||||
if result.Attempt.Kind != domain.AssessmentAttemptKindRoot && result.Attempt.Kind != domain.AssessmentAttemptKindCorrective {
|
||||
return api.AssessmentResult{}, errors.New("real result kind is invalid")
|
||||
}
|
||||
if result.Attempt.Specialization == nil || result.Attempt.TargetGrade == nil || result.DecidedAt.IsZero() {
|
||||
return api.AssessmentResult{}, errors.New("real result track or decision time is incomplete")
|
||||
}
|
||||
fields, err := assessmentRealResultFields(result)
|
||||
realResult, err := assessmentRealResultResponse(result)
|
||||
if err != nil {
|
||||
return api.AssessmentResult{}, err
|
||||
}
|
||||
if realResult.Type == api.AssessmentQualifiedResultAssessmentRealResult {
|
||||
return api.NewAssessmentQualifiedResultAssessmentResult(realResult.AssessmentQualifiedResult), nil
|
||||
}
|
||||
return api.NewAssessmentCorrectiveResultAssessmentResult(realResult.AssessmentCorrectiveResult), nil
|
||||
}
|
||||
|
||||
// assessmentRealResultResponse maps a completed root or corrective result. It
|
||||
// serves both the single result read and the owner's history, so the two never
|
||||
// describe the same stored result differently.
|
||||
func assessmentRealResultResponse(result assessmentusecase.AssessmentAttemptResult) (api.AssessmentRealResult, error) {
|
||||
if result.Attempt.Kind != domain.AssessmentAttemptKindRoot && result.Attempt.Kind != domain.AssessmentAttemptKindCorrective {
|
||||
return api.AssessmentRealResult{}, errors.New("real result kind is invalid")
|
||||
}
|
||||
if result.Attempt.Specialization == nil || result.Attempt.TargetGrade == nil || result.DecidedAt.IsZero() {
|
||||
return api.AssessmentRealResult{}, errors.New("real result track or decision time is incomplete")
|
||||
}
|
||||
fields, err := assessmentRealResultFields(result)
|
||||
if err != nil {
|
||||
return api.AssessmentRealResult{}, err
|
||||
}
|
||||
if result.Attempt.Kind == domain.AssessmentAttemptKindRoot {
|
||||
return api.NewAssessmentQualifiedResultAssessmentResult(api.AssessmentQualifiedResult{
|
||||
return api.NewAssessmentQualifiedResultAssessmentRealResult(api.AssessmentQualifiedResult{
|
||||
AttemptID: result.Attempt.ID.UUID(), Specialization: api.SpecializationCode(*result.Attempt.Specialization),
|
||||
TargetGrade: api.GradeCode(*result.Attempt.TargetGrade), RootAttemptID: fields.rootAttemptID,
|
||||
ChainDeadline: fields.chainDeadline, TaskLanguage: fields.taskLanguage,
|
||||
Kind: api.AssessmentQualifiedResultKindRoot, Mode: api.AssessmentQualifiedResultMode(result.Attempt.Mode),
|
||||
Versions: assessmentResultVersions(result.Attempt), Outcome: fields.outcome,
|
||||
NotDeterminedReason: fields.reason, ConfirmedGrade: fields.confirmedGrade,
|
||||
PreviousConfirmedGrade: fields.previousGrade, Strength: fields.strength,
|
||||
PreviousConfirmedGrade: fields.previousGrade, CategoryDecision: fields.categoryDecision,
|
||||
Strength: fields.strength,
|
||||
CalibrationStatus: api.CalibrationStatusUncalibrated, Limitations: fields.limitations,
|
||||
Uncertainty: fields.uncertainty, BasicScore: fields.basicScore, Practices: []api.AssessmentPracticeResult{},
|
||||
Gaps: []api.AssessmentGap{}, Durations: api.AssessmentDurations{ItemsSeconds: assessmentItemsSeconds(result), PracticeSeconds: nilInt32()},
|
||||
@@ -533,16 +548,17 @@ func assessmentResultResponse(result assessmentusecase.AssessmentAttemptResult)
|
||||
}), nil
|
||||
}
|
||||
if result.Attempt.RootAttemptID == nil || result.Attempt.ChainDeadline == nil {
|
||||
return api.AssessmentResult{}, errors.New("corrective result chain is incomplete")
|
||||
return api.AssessmentRealResult{}, errors.New("corrective result chain is incomplete")
|
||||
}
|
||||
return api.NewAssessmentCorrectiveResultAssessmentResult(api.AssessmentCorrectiveResult{
|
||||
return api.NewAssessmentCorrectiveResultAssessmentRealResult(api.AssessmentCorrectiveResult{
|
||||
AttemptID: result.Attempt.ID.UUID(), Specialization: api.SpecializationCode(*result.Attempt.Specialization),
|
||||
TargetGrade: api.GradeCode(*result.Attempt.TargetGrade), RootAttemptID: fields.rootAttemptID,
|
||||
ChainDeadline: fields.chainDeadline, TaskLanguage: fields.taskLanguage,
|
||||
Kind: api.AssessmentCorrectiveResultKindCorrective, Mode: api.AssessmentCorrectiveResultMode(result.Attempt.Mode),
|
||||
Versions: assessmentResultVersions(result.Attempt), Outcome: fields.outcome,
|
||||
NotDeterminedReason: fields.reason, ConfirmedGrade: fields.confirmedGrade,
|
||||
PreviousConfirmedGrade: fields.previousGrade, Strength: fields.strength,
|
||||
PreviousConfirmedGrade: fields.previousGrade, CategoryDecision: fields.categoryDecision,
|
||||
Strength: fields.strength,
|
||||
CalibrationStatus: api.CalibrationStatusUncalibrated, Limitations: fields.limitations,
|
||||
Uncertainty: fields.uncertainty, BasicScore: fields.basicScore, Practices: []api.AssessmentPracticeResult{},
|
||||
Gaps: []api.AssessmentGap{}, Durations: api.AssessmentDurations{ItemsSeconds: assessmentItemsSeconds(result), PracticeSeconds: nilInt32()},
|
||||
@@ -558,10 +574,13 @@ type assessmentRealResultResponseFields struct {
|
||||
reason api.NilAssessmentNotDeterminedReason
|
||||
confirmedGrade api.NilGradeCode
|
||||
previousGrade api.NilGradeCode
|
||||
strength api.NilAssessmentStrength
|
||||
limitations []api.AssessmentLimitation
|
||||
uncertainty api.NilAssessmentUncertainty
|
||||
basicScore api.NilBasicScore
|
||||
// categoryDecision is absent for a legacy result stored before category
|
||||
// decisions existed; its grade is never inferred from the current state.
|
||||
categoryDecision api.OptAssessmentCategoryDecisionView
|
||||
strength api.NilAssessmentStrength
|
||||
limitations []api.AssessmentLimitation
|
||||
uncertainty api.NilAssessmentUncertainty
|
||||
basicScore api.NilBasicScore
|
||||
}
|
||||
|
||||
func assessmentRealResultFields(result assessmentusecase.AssessmentAttemptResult) (assessmentRealResultResponseFields, error) {
|
||||
@@ -588,8 +607,7 @@ func assessmentRealResultFields(result assessmentusecase.AssessmentAttemptResult
|
||||
} else {
|
||||
fields.reason.SetTo(api.AssessmentNotDeterminedReason(result.NotDeterminedReason))
|
||||
}
|
||||
fields.confirmedGrade.SetToNull()
|
||||
fields.previousGrade.SetToNull()
|
||||
setAssessmentCategoryFields(&fields, result.CategoryDecision)
|
||||
fields.strength.SetToNull()
|
||||
fields.uncertainty.SetToNull()
|
||||
if result.BasicScore == nil {
|
||||
@@ -605,6 +623,45 @@ func assessmentRealResultFields(result assessmentusecase.AssessmentAttemptResult
|
||||
return fields, nil
|
||||
}
|
||||
|
||||
// setAssessmentCategoryFields copies the stored category decision. A result
|
||||
// confirms its target grade only when a reviewed synthetic source accepted the
|
||||
// outcome (assigned, or unchanged because the grade was not higher); a passing
|
||||
// score without such a source claims no category.
|
||||
func setAssessmentCategoryFields(fields *assessmentRealResultResponseFields, decision *domain.AssessmentCategoryDecisionSnapshot) {
|
||||
fields.confirmedGrade.SetToNull()
|
||||
fields.previousGrade.SetToNull()
|
||||
if decision == nil {
|
||||
return
|
||||
}
|
||||
view := api.AssessmentCategoryDecisionView{Status: api.AssessmentCategoryDecisionViewStatus(decision.Status)}
|
||||
view.PreviousConfirmedGrade.SetToNull()
|
||||
view.CurrentConfirmedGrade.SetToNull()
|
||||
view.Method.SetToNull()
|
||||
view.Source.SetToNull()
|
||||
view.CalibrationStatus.SetToNull()
|
||||
if decision.PreviousGrade != nil {
|
||||
fields.previousGrade.SetTo(api.GradeCode(*decision.PreviousGrade))
|
||||
view.PreviousConfirmedGrade.SetTo(api.GradeCode(*decision.PreviousGrade))
|
||||
}
|
||||
if decision.CurrentGrade != nil {
|
||||
view.CurrentConfirmedGrade.SetTo(api.GradeCode(*decision.CurrentGrade))
|
||||
}
|
||||
if decision.Method != "" {
|
||||
view.Method.SetTo(api.AssessmentCategoryDecisionViewMethod(decision.Method))
|
||||
}
|
||||
if decision.Source != "" {
|
||||
view.Source.SetTo(api.AssessmentCategoryDecisionViewSource(decision.Source))
|
||||
}
|
||||
if decision.CalibrationStatus != "" {
|
||||
view.CalibrationStatus.SetTo(api.CalibrationStatus(decision.CalibrationStatus))
|
||||
}
|
||||
if (decision.Status == domain.AssessmentCategoryDecisionAssigned || decision.Status == domain.AssessmentCategoryDecisionUnchanged) &&
|
||||
decision.AttemptedGrade != nil {
|
||||
fields.confirmedGrade.SetTo(api.GradeCode(*decision.AttemptedGrade))
|
||||
}
|
||||
fields.categoryDecision.SetTo(view)
|
||||
}
|
||||
|
||||
func assessmentResultVersions(snapshot domain.AssessmentAttemptPublicSnapshot) api.AssessmentVersions {
|
||||
return api.AssessmentVersions{
|
||||
PolicyVersion: snapshot.PolicyVersion, BankVersion: api.AssessmentVersionLabel(snapshot.BankVersion),
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/http/api"
|
||||
"lincodex/backend/internal/adapter/primary/http/problem"
|
||||
assessmentusecase "lincodex/backend/internal/usecase/assessment"
|
||||
)
|
||||
|
||||
// AssessmentResultOperations reads the candidate's immutable result history.
|
||||
// An employer has no operation here; the current category reaches an employer
|
||||
// only through the anonymous card.
|
||||
type AssessmentResultOperations interface {
|
||||
ListMyResults(ctx context.Context, userID uuid.UUID, cursor string, limit int32) (assessmentusecase.AssessmentResultHistoryPage, error)
|
||||
}
|
||||
|
||||
func (handler *Handler) ListMyAssessmentResults(
|
||||
ctx context.Context,
|
||||
params api.ListMyAssessmentResultsParams,
|
||||
) (api.ListMyAssessmentResultsRes, error) {
|
||||
if handler.assessment == nil {
|
||||
return handler.UnimplementedHandler.ListMyAssessmentResults(ctx, params)
|
||||
}
|
||||
return handler.assessment.ListMyAssessmentResults(ctx, params)
|
||||
}
|
||||
|
||||
// ListMyAssessmentResults serves the owner-only history. The operations of
|
||||
// AssessmentHandler provide it as an optional capability, like GetMyResult.
|
||||
func (handler *AssessmentHandler) ListMyAssessmentResults(
|
||||
ctx context.Context,
|
||||
params api.ListMyAssessmentResultsParams,
|
||||
) (api.ListMyAssessmentResultsRes, error) {
|
||||
const location = "AssessmentHandler.ListMyAssessmentResults"
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.ListMyAssessmentResultsUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
operations, ok := handler.operations.(AssessmentResultOperations)
|
||||
if !ok {
|
||||
return nil, errors.New(location + " - result history operation is unavailable")
|
||||
}
|
||||
// The generated validator has already bounded limit to the contract range.
|
||||
page, err := operations.ListMyResults(ctx, principal.UserID, params.Cursor.Or(""), params.Limit.Or(0))
|
||||
if err != nil {
|
||||
return assessmentResultsFailure(ctx, err)
|
||||
}
|
||||
items := make([]api.AssessmentRealResult, 0, len(page.Entries))
|
||||
for _, entry := range page.Entries {
|
||||
item, err := assessmentRealResultResponse(assessmentusecase.AssessmentAttemptResultFromHistoryEntry(entry))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - map stored result: %w", location, err)
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
next := api.NilString{}
|
||||
if page.NextCursor == "" {
|
||||
next.SetToNull()
|
||||
} else {
|
||||
next.SetTo(page.NextCursor)
|
||||
}
|
||||
return &api.AssessmentResultHistoryPageHeaders{
|
||||
CacheControl: api.CacheControlNoStoreNoStore,
|
||||
Response: api.AssessmentResultHistoryPage{Items: items, Page: api.PageInfo{HasMore: page.NextCursor != "", NextCursor: next}},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func assessmentResultsFailure(ctx context.Context, err error) (api.ListMyAssessmentResultsRes, error) {
|
||||
switch {
|
||||
case errors.Is(err, assessmentusecase.ErrInvalidAssessmentResultHistoryRequest):
|
||||
return (*api.ListMyAssessmentResultsBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationQuery, "/cursor").Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptForbidden), errors.Is(err, assessmentusecase.ErrAttemptEmailNotVerified):
|
||||
return (*api.ListMyAssessmentResultsForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
)
|
||||
|
||||
func gradePtr(grade domain.GradeCode) *domain.GradeCode { return &grade }
|
||||
|
||||
func TestAssessmentCategoryFieldsClaimAGradeOnlyForAReviewedConfirmation(t *testing.T) {
|
||||
specialization := domain.SpecializationBackend
|
||||
reviewed := func(status domain.AssessmentCategoryDecisionStatus, attempted domain.GradeCode, previous, current *domain.GradeCode) *domain.AssessmentCategoryDecisionSnapshot {
|
||||
return &domain.AssessmentCategoryDecisionSnapshot{
|
||||
AttemptID: domain.AssessmentAttemptID(uuid.New()), Specialization: &specialization, AttemptedGrade: gradePtr(attempted),
|
||||
PreviousGrade: previous, CurrentGrade: current, Status: status,
|
||||
Method: domain.AssessmentCategoryDecisionDemoBasicPassMark, Source: domain.AssessmentCategorySourceSyntheticDemo,
|
||||
CalibrationStatus: domain.AssessmentCategoryCalibrationUncalibrated, DecidedAt: time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC),
|
||||
}
|
||||
}
|
||||
notEligible := &domain.AssessmentCategoryDecisionSnapshot{
|
||||
AttemptID: domain.AssessmentAttemptID(uuid.New()), Specialization: &specialization, AttemptedGrade: gradePtr(domain.GradeJunior),
|
||||
PreviousGrade: gradePtr(domain.GradeIntern), CurrentGrade: gradePtr(domain.GradeIntern),
|
||||
Status: domain.AssessmentCategoryDecisionNotEligible,
|
||||
}
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
decision *domain.AssessmentCategoryDecisionSnapshot
|
||||
wantConfirmed string
|
||||
wantPrevious string
|
||||
wantView bool
|
||||
}{
|
||||
{name: "legacy result without a decision", decision: nil},
|
||||
{name: "assigned", decision: reviewed(domain.AssessmentCategoryDecisionAssigned, domain.GradeJunior, gradePtr(domain.GradeIntern), gradePtr(domain.GradeJunior)),
|
||||
wantConfirmed: "junior", wantPrevious: "intern", wantView: true},
|
||||
{name: "unchanged", decision: reviewed(domain.AssessmentCategoryDecisionUnchanged, domain.GradeIntern, gradePtr(domain.GradeMiddle), gradePtr(domain.GradeMiddle)),
|
||||
wantConfirmed: "intern", wantPrevious: "middle", wantView: true},
|
||||
{name: "not confirmed keeps the previous grade", decision: reviewed(domain.AssessmentCategoryDecisionNotConfirmed, domain.GradeJunior, gradePtr(domain.GradeIntern), gradePtr(domain.GradeIntern)),
|
||||
wantPrevious: "intern", wantView: true},
|
||||
{name: "not eligible claims no grade", decision: notEligible, wantPrevious: "intern", wantView: true},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
var fields assessmentRealResultResponseFields
|
||||
setAssessmentCategoryFields(&fields, test.decision)
|
||||
confirmed, confirmedSet := fields.confirmedGrade.Get()
|
||||
previous, previousSet := fields.previousGrade.Get()
|
||||
if (test.wantConfirmed == "") == confirmedSet || confirmedSet && string(confirmed) != test.wantConfirmed {
|
||||
t.Fatalf("confirmed_grade = %q (set %v), want %q", confirmed, confirmedSet, test.wantConfirmed)
|
||||
}
|
||||
if (test.wantPrevious == "") == previousSet || previousSet && string(previous) != test.wantPrevious {
|
||||
t.Fatalf("previous_confirmed_grade = %q (set %v), want %q", previous, previousSet, test.wantPrevious)
|
||||
}
|
||||
if fields.categoryDecision.IsSet() != test.wantView {
|
||||
t.Fatalf("category_decision present = %v, want %v", fields.categoryDecision.IsSet(), test.wantView)
|
||||
}
|
||||
if view, ok := fields.categoryDecision.Get(); ok && test.decision.Status == domain.AssessmentCategoryDecisionNotEligible {
|
||||
_, hasMethod := view.Method.Get()
|
||||
_, hasSource := view.Source.Get()
|
||||
if hasMethod || hasSource {
|
||||
t.Fatalf("not eligible view names a method or source: %+v", view)
|
||||
}
|
||||
}
|
||||
if view, ok := fields.categoryDecision.Get(); ok && string(view.Status) != string(test.decision.Status) {
|
||||
t.Fatalf("view status = %s, want %s", view.Status, test.decision.Status)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -566,50 +566,20 @@ func (repository assessmentAttemptRepository) SaveResult(
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - encode result snapshot: %w", location, err)
|
||||
}
|
||||
var gradingPolicyID, openingID, trainingBindingID pgtype.UUID
|
||||
var openingHash, trainingHash []byte
|
||||
if validated.Pins.GradingPolicyVersionID != domain.PolicyVersionID(uuid.Nil) {
|
||||
gradingPolicyID = pgUUID(uuid.UUID(validated.Pins.GradingPolicyVersionID))
|
||||
}
|
||||
if validated.Pins.OpeningID != uuid.Nil {
|
||||
openingID = pgUUID(validated.Pins.OpeningID)
|
||||
}
|
||||
if validated.Pins.TrainingBindingID != uuid.Nil {
|
||||
trainingBindingID = pgUUID(validated.Pins.TrainingBindingID)
|
||||
}
|
||||
if validated.Pins.OpeningManifestHash != [sha256.Size]byte{} {
|
||||
openingHash = bytes.Clone(validated.Pins.OpeningManifestHash[:])
|
||||
}
|
||||
if validated.Pins.TrainingManifestHash != [sha256.Size]byte{} {
|
||||
trainingHash = bytes.Clone(validated.Pins.TrainingManifestHash[:])
|
||||
}
|
||||
var passMark pgtype.Int4
|
||||
var scoredItems, rawScore, passPoints pgtype.Int2
|
||||
if score := validated.BasicScore; score != nil {
|
||||
scoredItems, err = assessmentSmallint(validated.Rationale.ScoredItems)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - scored item count exceeds storage range: %w", location, err)
|
||||
}
|
||||
rawScore, err = assessmentSmallint(score.Points)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - raw score exceeds storage range: %w", location, err)
|
||||
}
|
||||
passPoints, err = assessmentSmallint(score.PassPoints)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - pass points exceed storage range: %w", location, err)
|
||||
}
|
||||
passMark = pgtype.Int4{Int32: validated.Rationale.PassMarkBasisPoints, Valid: true}
|
||||
columns, err := newAssessmentResultColumns(validated)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - build result columns: %w", location, domain.ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
if err := repository.queries.InsertAssessmentAttemptResult(ctx, sqlc.InsertAssessmentAttemptResultParams{
|
||||
AttemptID: pgUUID(validated.Attempt.ID.UUID()), UserID: pgUUID(userID),
|
||||
ResultSnapshot: encoded, Kind: string(validated.Attempt.Kind), Mode: string(validated.Attempt.Mode),
|
||||
Outcome: string(validated.Outcome), ProductPolicyVersionID: pgUUID(uuid.UUID(validated.Pins.ProductPolicyVersionID)),
|
||||
ProductPolicyVersion: validated.Pins.ProductPolicyVersion, GradingPolicyVersionID: gradingPolicyID,
|
||||
OpeningID: openingID, OpeningManifestSha256: openingHash, TrainingBindingID: trainingBindingID,
|
||||
TrainingManifestSha256: trainingHash, BankVersion: validated.Pins.BankVersion,
|
||||
ProductPolicyVersion: validated.Pins.ProductPolicyVersion, GradingPolicyVersionID: columns.gradingPolicyID,
|
||||
OpeningID: columns.openingID, OpeningManifestSha256: columns.openingHash, TrainingBindingID: columns.trainingBindingID,
|
||||
TrainingManifestSha256: columns.trainingHash, BankVersion: validated.Pins.BankVersion,
|
||||
AlgorithmVersion: validated.Pins.AlgorithmVersion, RationaleRule: validated.Rationale.Rule,
|
||||
PassMarkBasisPoints: passMark, ScoredItems: scoredItems, RawScore: rawScore,
|
||||
PassPoints: passPoints, DecidedAt: pgTime(validated.DecidedAt),
|
||||
PassMarkBasisPoints: columns.passMark, ScoredItems: columns.scoredItems, RawScore: columns.rawScore,
|
||||
PassPoints: columns.passPoints, DecidedAt: pgTime(validated.DecidedAt),
|
||||
}); err != nil {
|
||||
return fmt.Errorf("%s - insert immutable result: %w", location, mapAssessmentAttemptError(err))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,467 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
const maxAssessmentCategoryDecisionBytes = 4096
|
||||
|
||||
// assessmentCategoryDecisionDocument is the stored category extension of one
|
||||
// result. The key names are read by the migration constraints and triggers, so
|
||||
// they are part of the storage contract. Optional review fields are omitted,
|
||||
// not written as null, for decisions that have no reviewed source.
|
||||
type assessmentCategoryDecisionDocument struct {
|
||||
AttemptID uuid.UUID `json:"attempt_id"`
|
||||
BankCategory domain.AssessmentCategory `json:"bank_category"`
|
||||
Specialization domain.SpecializationCode `json:"specialization"`
|
||||
AttemptedGrade domain.GradeCode `json:"attempted_grade"`
|
||||
PreviousGrade *domain.GradeCode `json:"previous_grade"`
|
||||
CurrentGrade *domain.GradeCode `json:"current_grade"`
|
||||
Status domain.AssessmentCategoryDecisionStatus `json:"status"`
|
||||
Method domain.AssessmentCategoryDecisionMethod `json:"method,omitempty"`
|
||||
ProductPolicyVersionID uuid.UUID `json:"product_policy_version_id"`
|
||||
ProductPolicyVersion int32 `json:"product_policy_version"`
|
||||
GradingPolicyVersionID uuid.UUID `json:"grading_policy_version_id"`
|
||||
OpeningID uuid.UUID `json:"opening_id"`
|
||||
OpeningManifestHash string `json:"opening_manifest_sha256"`
|
||||
ReviewID *uuid.UUID `json:"review_id,omitempty"`
|
||||
Source domain.AssessmentCategorySource `json:"source,omitempty"`
|
||||
CalibrationStatus domain.AssessmentCategoryCalibrationStatus `json:"calibration_status,omitempty"`
|
||||
DecidedAt time.Time `json:"decided_at"`
|
||||
}
|
||||
|
||||
func marshalAssessmentCategoryDecision(decision domain.AssessmentCategoryDecisionSnapshot) ([]byte, error) {
|
||||
const location = "postgres.marshalAssessmentCategoryDecision"
|
||||
if decision.Specialization == nil || decision.AttemptedGrade == nil {
|
||||
return nil, fmt.Errorf("%s - decision has no track: %w", location, domain.ErrInvalidAssessmentCategory)
|
||||
}
|
||||
document := assessmentCategoryDecisionDocument{
|
||||
AttemptID: decision.AttemptID.UUID(), BankCategory: decision.BankCategory,
|
||||
Specialization: *decision.Specialization, AttemptedGrade: *decision.AttemptedGrade,
|
||||
PreviousGrade: decision.PreviousGrade, CurrentGrade: decision.CurrentGrade,
|
||||
Status: decision.Status, Method: decision.Method,
|
||||
ProductPolicyVersionID: uuid.UUID(decision.ProductPolicyVersionID),
|
||||
ProductPolicyVersion: decision.ProductPolicyVersion,
|
||||
GradingPolicyVersionID: uuid.UUID(decision.GradingPolicyVersionID),
|
||||
OpeningID: decision.OpeningID, OpeningManifestHash: hex.EncodeToString(decision.OpeningManifestHash[:]),
|
||||
Source: decision.Source, CalibrationStatus: decision.CalibrationStatus, DecidedAt: decision.DecidedAt.UTC(),
|
||||
}
|
||||
if decision.ReviewID != uuid.Nil {
|
||||
reviewID := decision.ReviewID
|
||||
document.ReviewID = &reviewID
|
||||
}
|
||||
encoded, err := json.Marshal(document)
|
||||
if err != nil || len(encoded) > maxAssessmentCategoryDecisionBytes {
|
||||
return nil, fmt.Errorf("%s - encode bounded decision: %w", location, domain.ErrInvalidAssessmentCategory)
|
||||
}
|
||||
return encoded, nil
|
||||
}
|
||||
|
||||
func decodeAssessmentCategoryDecision(encoded string) (domain.AssessmentCategoryDecisionSnapshot, error) {
|
||||
const location = "postgres.decodeAssessmentCategoryDecision"
|
||||
if encoded == "" || len(encoded) > maxAssessmentCategoryDecisionBytes {
|
||||
return domain.AssessmentCategoryDecisionSnapshot{}, fmt.Errorf("%s - stored decision size is invalid: %w", location, domain.ErrInvalidAssessmentCategory)
|
||||
}
|
||||
decoder := json.NewDecoder(bytes.NewReader([]byte(encoded)))
|
||||
decoder.DisallowUnknownFields()
|
||||
var document assessmentCategoryDecisionDocument
|
||||
if err := decoder.Decode(&document); err != nil {
|
||||
return domain.AssessmentCategoryDecisionSnapshot{}, fmt.Errorf("%s - decode stored decision: %w", location, domain.ErrInvalidAssessmentCategory)
|
||||
}
|
||||
var extra any
|
||||
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
|
||||
return domain.AssessmentCategoryDecisionSnapshot{}, fmt.Errorf("%s - stored decision has trailing data: %w", location, domain.ErrInvalidAssessmentCategory)
|
||||
}
|
||||
manifestHash, err := restoreOptionalAssessmentDigest(&document.OpeningManifestHash)
|
||||
if err != nil {
|
||||
return domain.AssessmentCategoryDecisionSnapshot{}, fmt.Errorf("%s - stored manifest digest is invalid: %w", location, domain.ErrInvalidAssessmentCategory)
|
||||
}
|
||||
specialization, attempted := document.Specialization, document.AttemptedGrade
|
||||
snapshot := domain.AssessmentCategoryDecisionSnapshot{
|
||||
AttemptID: domain.AssessmentAttemptID(document.AttemptID), BankCategory: document.BankCategory,
|
||||
Specialization: &specialization, AttemptedGrade: &attempted,
|
||||
PreviousGrade: document.PreviousGrade, CurrentGrade: document.CurrentGrade,
|
||||
Status: document.Status, Method: document.Method,
|
||||
ProductPolicyVersionID: domain.PolicyVersionID(document.ProductPolicyVersionID),
|
||||
ProductPolicyVersion: document.ProductPolicyVersion,
|
||||
GradingPolicyVersionID: domain.PolicyVersionID(document.GradingPolicyVersionID),
|
||||
OpeningID: document.OpeningID, OpeningManifestHash: manifestHash,
|
||||
Source: document.Source, CalibrationStatus: document.CalibrationStatus, DecidedAt: document.DecidedAt,
|
||||
}
|
||||
if document.ReviewID != nil {
|
||||
snapshot.ReviewID = *document.ReviewID
|
||||
}
|
||||
return snapshot, nil
|
||||
}
|
||||
|
||||
// assessmentResultColumns are the denormalized, query-visible copies of a
|
||||
// result document that the table constraints compare with the snapshot.
|
||||
type assessmentResultColumns struct {
|
||||
gradingPolicyID, openingID, trainingBindingID pgtype.UUID
|
||||
openingHash, trainingHash []byte
|
||||
passMark pgtype.Int4
|
||||
scoredItems, rawScore, passPoints pgtype.Int2
|
||||
}
|
||||
|
||||
func newAssessmentResultColumns(result domain.AssessmentAttemptResultSnapshot) (assessmentResultColumns, error) {
|
||||
var columns assessmentResultColumns
|
||||
pins := result.Pins
|
||||
if pins.GradingPolicyVersionID != domain.PolicyVersionID(uuid.Nil) {
|
||||
columns.gradingPolicyID = pgUUID(uuid.UUID(pins.GradingPolicyVersionID))
|
||||
}
|
||||
if pins.OpeningID != uuid.Nil {
|
||||
columns.openingID = pgUUID(pins.OpeningID)
|
||||
}
|
||||
if pins.TrainingBindingID != uuid.Nil {
|
||||
columns.trainingBindingID = pgUUID(pins.TrainingBindingID)
|
||||
}
|
||||
if pins.OpeningManifestHash != [sha256.Size]byte{} {
|
||||
columns.openingHash = bytes.Clone(pins.OpeningManifestHash[:])
|
||||
}
|
||||
if pins.TrainingManifestHash != [sha256.Size]byte{} {
|
||||
columns.trainingHash = bytes.Clone(pins.TrainingManifestHash[:])
|
||||
}
|
||||
score := result.BasicScore
|
||||
if score == nil {
|
||||
return columns, nil
|
||||
}
|
||||
var err error
|
||||
if columns.scoredItems, err = assessmentSmallint(result.Rationale.ScoredItems); err != nil {
|
||||
return assessmentResultColumns{}, fmt.Errorf("scored item count exceeds storage range: %w", err)
|
||||
}
|
||||
if columns.rawScore, err = assessmentSmallint(score.Points); err != nil {
|
||||
return assessmentResultColumns{}, fmt.Errorf("raw score exceeds storage range: %w", err)
|
||||
}
|
||||
if columns.passPoints, err = assessmentSmallint(score.PassPoints); err != nil {
|
||||
return assessmentResultColumns{}, fmt.Errorf("pass points exceed storage range: %w", err)
|
||||
}
|
||||
columns.passMark = pgtype.Int4{Int32: result.Rationale.PassMarkBasisPoints, Valid: true}
|
||||
return columns, nil
|
||||
}
|
||||
|
||||
// SaveResultHistoryEntry stores a legacy v1 result unchanged or a v2 result
|
||||
// with its category decision in one immutable row.
|
||||
func (repository assessmentAttemptRepository) SaveResultHistoryEntry(
|
||||
ctx context.Context,
|
||||
userID uuid.UUID,
|
||||
entry domain.AssessmentAttemptResultHistoryEntry,
|
||||
) error {
|
||||
const location = "assessmentAttemptRepository.SaveResultHistoryEntry"
|
||||
if userID == uuid.Nil {
|
||||
return fmt.Errorf("%s - owner ID is required: %w", location, domain.ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
validated, err := domain.RestoreAssessmentAttemptResultHistoryEntry(entry)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - result history entry is invalid: %w", location, err)
|
||||
}
|
||||
if validated.SchemaVersion == domain.AssessmentAttemptResultHistorySchemaV1 {
|
||||
if err := repository.SaveResult(ctx, userID, validated.Result); err != nil {
|
||||
return fmt.Errorf("%s - store legacy result: %w", location, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
result := validated.Result
|
||||
encodedResult, err := marshalAssessmentAttemptResultDocument(result)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - encode result snapshot: %w", location, err)
|
||||
}
|
||||
encodedDecision, err := marshalAssessmentCategoryDecision(*validated.CategoryDecision)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - encode category decision: %w", location, err)
|
||||
}
|
||||
columns, err := newAssessmentResultColumns(result)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - build result columns: %w", location, domain.ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
if err := repository.queries.InsertAssessmentAttemptResultV2(ctx, sqlc.InsertAssessmentAttemptResultV2Params{
|
||||
AttemptID: pgUUID(result.Attempt.ID.UUID()), UserID: pgUUID(userID),
|
||||
ResultSnapshot: encodedResult, CategoryDecision: encodedDecision,
|
||||
CurrentConfirmedGrade: pgNullableAttemptText(validated.CurrentConfirmedGrade),
|
||||
Kind: string(result.Attempt.Kind), Mode: string(result.Attempt.Mode),
|
||||
Outcome: string(result.Outcome),
|
||||
ProductPolicyVersionID: pgUUID(uuid.UUID(result.Pins.ProductPolicyVersionID)),
|
||||
ProductPolicyVersion: result.Pins.ProductPolicyVersion, GradingPolicyVersionID: columns.gradingPolicyID,
|
||||
OpeningID: columns.openingID, OpeningManifestSha256: columns.openingHash,
|
||||
BankVersion: result.Pins.BankVersion, AlgorithmVersion: result.Pins.AlgorithmVersion,
|
||||
RationaleRule: result.Rationale.Rule, PassMarkBasisPoints: columns.passMark,
|
||||
ScoredItems: columns.scoredItems, RawScore: columns.rawScore, PassPoints: columns.passPoints,
|
||||
DecidedAt: pgTime(result.DecidedAt),
|
||||
}); err != nil {
|
||||
return fmt.Errorf("%s - insert immutable category result: %w", location, mapAssessmentAttemptError(err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetResultHistoryEntry returns the exact stored record; a v1 row carries no
|
||||
// category data and none is reconstructed from the current category.
|
||||
func (repository assessmentAttemptRepository) GetResultHistoryEntry(
|
||||
ctx context.Context,
|
||||
userID uuid.UUID,
|
||||
attemptID domain.AssessmentAttemptID,
|
||||
) (domain.AssessmentAttemptResultHistoryEntry, error) {
|
||||
const location = "assessmentAttemptRepository.GetResultHistoryEntry"
|
||||
if userID == uuid.Nil || attemptID.IsZero() {
|
||||
return domain.AssessmentAttemptResultHistoryEntry{}, fmt.Errorf("%s - owner and attempt IDs are required: %w", location, domain.ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
row, err := repository.queries.GetAssessmentAttemptResultHistoryEntry(ctx, sqlc.GetAssessmentAttemptResultHistoryEntryParams{
|
||||
UserID: pgUUID(userID), AttemptID: pgUUID(attemptID.UUID()),
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.AssessmentAttemptResultHistoryEntry{}, fmt.Errorf("%s - immutable result is missing: %w", location, outbound.ErrAssessmentAttemptResultNotFound)
|
||||
}
|
||||
if err != nil {
|
||||
return domain.AssessmentAttemptResultHistoryEntry{}, fmt.Errorf("%s - select immutable result: %w", location, mapAssessmentAttemptError(err))
|
||||
}
|
||||
entry, err := restoreStoredResultHistoryEntry(row.SchemaVersion, row.ResultSnapshot, row.CategoryDecision, row.CurrentConfirmedGrade)
|
||||
if err != nil || entry.Result.Attempt.ID != attemptID {
|
||||
return domain.AssessmentAttemptResultHistoryEntry{}, fmt.Errorf("%s - stored result is invalid: %w", location, domain.ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
return entry, nil
|
||||
}
|
||||
|
||||
// ListCandidateAssessmentResults reads one owner-scoped keyset page. It asks
|
||||
// for one row more than limit and reports that row as HasMore.
|
||||
func (repository assessmentAttemptRepository) ListCandidateAssessmentResults(
|
||||
ctx context.Context,
|
||||
userID uuid.UUID,
|
||||
cursor *outbound.AssessmentAttemptResultCursor,
|
||||
limit int32,
|
||||
) (outbound.AssessmentAttemptResultPage, error) {
|
||||
const location = "assessmentAttemptRepository.ListCandidateAssessmentResults"
|
||||
if userID == uuid.Nil || limit < 1 || cursor != nil && (cursor.AttemptID.IsZero() || cursor.DecidedAt.IsZero()) {
|
||||
return outbound.AssessmentAttemptResultPage{}, fmt.Errorf("%s - owner, limit or cursor is invalid: %w", location, domain.ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
params := sqlc.ListCandidateAssessmentResultsParams{UserID: pgUUID(userID), LimitCount: limit}
|
||||
if cursor != nil {
|
||||
params.CursorDecidedAt = pgTime(cursor.DecidedAt)
|
||||
params.CursorAttemptID = pgUUID(cursor.AttemptID.UUID())
|
||||
}
|
||||
rows, err := repository.queries.ListCandidateAssessmentResults(ctx, params)
|
||||
if err != nil {
|
||||
return outbound.AssessmentAttemptResultPage{}, fmt.Errorf("%s - select result history: %w", location, mapAssessmentAttemptError(err))
|
||||
}
|
||||
page := outbound.AssessmentAttemptResultPage{HasMore: len(rows) > int(limit)}
|
||||
if page.HasMore {
|
||||
rows = rows[:limit]
|
||||
}
|
||||
page.Records = make([]outbound.AssessmentAttemptResultRecord, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
entry, err := restoreStoredResultHistoryEntry(row.SchemaVersion, row.ResultSnapshot, row.CategoryDecision, row.CurrentConfirmedGrade)
|
||||
if err != nil || !row.AttemptID.Valid || !row.UserID.Valid || entry.Result.Attempt.ID.UUID() != row.AttemptID.Bytes {
|
||||
return outbound.AssessmentAttemptResultPage{}, fmt.Errorf("%s - stored result is invalid: %w", location, domain.ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
page.Records = append(page.Records, outbound.AssessmentAttemptResultRecord{UserID: row.UserID.Bytes, Entry: entry})
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func restoreStoredResultHistoryEntry(
|
||||
schemaVersion int16,
|
||||
resultSnapshot, categoryDecision string,
|
||||
currentGrade pgtype.Text,
|
||||
) (domain.AssessmentAttemptResultHistoryEntry, error) {
|
||||
result, err := decodeAssessmentAttemptResultDocument([]byte(resultSnapshot))
|
||||
if err != nil {
|
||||
return domain.AssessmentAttemptResultHistoryEntry{}, err
|
||||
}
|
||||
entry := domain.AssessmentAttemptResultHistoryEntry{SchemaVersion: int32(schemaVersion), Result: result}
|
||||
if categoryDecision != "" {
|
||||
decision, err := decodeAssessmentCategoryDecision(categoryDecision)
|
||||
if err != nil {
|
||||
return domain.AssessmentAttemptResultHistoryEntry{}, err
|
||||
}
|
||||
entry.CategoryDecision = &decision
|
||||
}
|
||||
if currentGrade.Valid {
|
||||
grade := domain.GradeCode(currentGrade.String)
|
||||
entry.CurrentConfirmedGrade = &grade
|
||||
}
|
||||
return domain.RestoreAssessmentAttemptResultHistoryEntry(entry)
|
||||
}
|
||||
|
||||
// LockCandidateCategory serializes category upgrades of one candidate and
|
||||
// specialization for the rest of the transaction.
|
||||
func (repository assessmentAttemptRepository) LockCandidateCategory(
|
||||
ctx context.Context,
|
||||
candidateID uuid.UUID,
|
||||
specialization domain.SpecializationCode,
|
||||
) error {
|
||||
const location = "assessmentAttemptRepository.LockCandidateCategory"
|
||||
if candidateID == uuid.Nil || !specialization.IsKnown() {
|
||||
return fmt.Errorf("%s - candidate scope is invalid: %w", location, domain.ErrInvalidAssessmentCategory)
|
||||
}
|
||||
if err := repository.queries.LockCandidateAssessmentCategory(ctx, sqlc.LockCandidateAssessmentCategoryParams{
|
||||
CandidateID: candidateID.String(), Specialization: string(specialization),
|
||||
}); err != nil {
|
||||
return fmt.Errorf("%s - lock candidate category: %w", location, mapAssessmentAttemptError(err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository assessmentAttemptRepository) GetCandidateCategory(
|
||||
ctx context.Context,
|
||||
candidateID uuid.UUID,
|
||||
specialization domain.SpecializationCode,
|
||||
) (domain.CandidateAssessmentCategory, bool, error) {
|
||||
const location = "assessmentAttemptRepository.GetCandidateCategory"
|
||||
if candidateID == uuid.Nil || !specialization.IsKnown() {
|
||||
return domain.CandidateAssessmentCategory{}, false, fmt.Errorf("%s - candidate scope is invalid: %w", location, domain.ErrInvalidAssessmentCategory)
|
||||
}
|
||||
row, err := repository.queries.GetCandidateAssessmentCategory(ctx, sqlc.GetCandidateAssessmentCategoryParams{
|
||||
CandidateID: pgUUID(candidateID), Specialization: string(specialization),
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.CandidateAssessmentCategory{}, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return domain.CandidateAssessmentCategory{}, false, fmt.Errorf("%s - select current category: %w", location, mapAssessmentAttemptError(err))
|
||||
}
|
||||
category, err := restoreCandidateAssessmentCategory(row)
|
||||
if err != nil {
|
||||
return domain.CandidateAssessmentCategory{}, false, fmt.Errorf("%s - stored category is invalid: %w", location, err)
|
||||
}
|
||||
return category, true, nil
|
||||
}
|
||||
|
||||
func restoreCandidateAssessmentCategory(row sqlc.CandidateAssessmentCategory) (domain.CandidateAssessmentCategory, error) {
|
||||
manifestHash, err := assessmentManifestHash(row.OpeningManifestSha256)
|
||||
if err != nil || !row.CandidateID.Valid || !row.SourceAttemptID.Valid || !row.SourceReviewID.Valid ||
|
||||
!row.ProductPolicyVersionID.Valid || !row.OpeningID.Valid || !row.AssignedAt.Valid {
|
||||
return domain.CandidateAssessmentCategory{}, domain.ErrInvalidAssessmentCategory
|
||||
}
|
||||
return domain.RestoreCandidateAssessmentCategory(domain.CandidateAssessmentCategorySnapshot{
|
||||
CandidateID: row.CandidateID.Bytes, Specialization: domain.SpecializationCode(row.Specialization),
|
||||
Grade: domain.GradeCode(row.Grade), SourceAttemptID: domain.AssessmentAttemptID(row.SourceAttemptID.Bytes),
|
||||
SourceReviewID: row.SourceReviewID.Bytes,
|
||||
ProductPolicyVersionID: domain.PolicyVersionID(row.ProductPolicyVersionID.Bytes),
|
||||
ProductPolicyVersion: row.ProductPolicyVersion, OpeningID: row.OpeningID.Bytes,
|
||||
OpeningManifestHash: manifestHash, Source: domain.AssessmentCategorySource(row.Source),
|
||||
CalibrationStatus: domain.AssessmentCategoryCalibrationStatus(row.CalibrationStatus),
|
||||
AssignedAt: row.AssignedAt.Time,
|
||||
})
|
||||
}
|
||||
|
||||
func assessmentManifestHash(value []byte) ([sha256.Size]byte, error) {
|
||||
var hash [sha256.Size]byte
|
||||
if len(value) != sha256.Size {
|
||||
return hash, domain.ErrInvalidAssessmentCategory
|
||||
}
|
||||
copy(hash[:], value)
|
||||
return hash, nil
|
||||
}
|
||||
|
||||
// GetSyntheticCategoryReview finds the attestation that matches the exact
|
||||
// opening, manifest, product policy and the opening's grading policy.
|
||||
func (repository assessmentAttemptRepository) GetSyntheticCategoryReview(
|
||||
ctx context.Context,
|
||||
openingID uuid.UUID,
|
||||
category domain.AssessmentCategory,
|
||||
openingManifestHash [32]byte,
|
||||
productPolicyID domain.PolicyVersionID,
|
||||
productPolicyVersion int32,
|
||||
gradingPolicyID domain.PolicyVersionID,
|
||||
) (domain.AssessmentSyntheticCategoryReview, bool, error) {
|
||||
const location = "assessmentAttemptRepository.GetSyntheticCategoryReview"
|
||||
if openingID == uuid.Nil || openingManifestHash == [32]byte{} || productPolicyID.IsZero() ||
|
||||
productPolicyVersion <= 0 || gradingPolicyID.IsZero() {
|
||||
return domain.AssessmentSyntheticCategoryReview{}, false, fmt.Errorf("%s - review pins are invalid: %w", location, domain.ErrInvalidAssessmentCategory)
|
||||
}
|
||||
row, err := repository.queries.GetSyntheticCategoryReview(ctx, sqlc.GetSyntheticCategoryReviewParams{
|
||||
OpeningID: pgUUID(openingID), Category: string(category),
|
||||
OpeningManifestSha256: bytes.Clone(openingManifestHash[:]),
|
||||
ProductPolicyVersionID: pgUUID(productPolicyID.UUID()), ProductPolicyVersion: productPolicyVersion,
|
||||
GradingPolicyVersionID: pgUUID(gradingPolicyID.UUID()),
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.AssessmentSyntheticCategoryReview{}, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return domain.AssessmentSyntheticCategoryReview{}, false, fmt.Errorf("%s - select review: %w", location, mapAssessmentAttemptError(err))
|
||||
}
|
||||
manifestHash, err := assessmentManifestHash(row.OpeningManifestSha256)
|
||||
if err != nil || !row.ID.Valid || !row.OpeningID.Valid || !row.ProductPolicyVersionID.Valid || !row.ReviewedAt.Valid {
|
||||
return domain.AssessmentSyntheticCategoryReview{}, false, fmt.Errorf("%s - stored review is invalid: %w", location, domain.ErrInvalidAssessmentCategory)
|
||||
}
|
||||
review, err := domain.RestoreAssessmentSyntheticCategoryReview(domain.AssessmentSyntheticCategoryReviewSnapshot{
|
||||
ID: row.ID.Bytes, OpeningID: row.OpeningID.Bytes, Category: domain.AssessmentCategory(row.Category),
|
||||
Source: domain.AssessmentCategorySource(row.Source), OpeningManifestHash: manifestHash,
|
||||
ProductPolicyVersionID: domain.PolicyVersionID(row.ProductPolicyVersionID.Bytes),
|
||||
ProductPolicyVersion: row.ProductPolicyVersion, ReviewedBy: domain.AssessmentOperator(row.ReviewedBy),
|
||||
ReviewedAt: row.ReviewedAt.Time,
|
||||
})
|
||||
if err != nil {
|
||||
return domain.AssessmentSyntheticCategoryReview{}, false, fmt.Errorf("%s - restore review: %w", location, err)
|
||||
}
|
||||
return review, true, nil
|
||||
}
|
||||
|
||||
// CreateSyntheticCategoryReview stores one attestation. The database stamps the
|
||||
// review time and re-checks the opening, manifest and policy it names. A
|
||||
// duplicate of the same exact source stores nothing and reports false.
|
||||
func (repository assessmentAttemptRepository) CreateSyntheticCategoryReview(
|
||||
ctx context.Context,
|
||||
review domain.AssessmentSyntheticCategoryReview,
|
||||
) (bool, error) {
|
||||
const location = "assessmentAttemptRepository.CreateSyntheticCategoryReview"
|
||||
if review.IsZero() {
|
||||
return false, fmt.Errorf("%s - review is required: %w", location, domain.ErrInvalidAssessmentCategory)
|
||||
}
|
||||
snapshot := review.Snapshot()
|
||||
rows, err := repository.queries.InsertSyntheticCategoryReview(ctx, sqlc.InsertSyntheticCategoryReviewParams{
|
||||
ID: pgUUID(snapshot.ID), OpeningID: pgUUID(snapshot.OpeningID), Category: string(snapshot.Category),
|
||||
Source: string(snapshot.Source), OpeningManifestSha256: bytes.Clone(snapshot.OpeningManifestHash[:]),
|
||||
ProductPolicyVersionID: pgUUID(snapshot.ProductPolicyVersionID.UUID()),
|
||||
ProductPolicyVersion: snapshot.ProductPolicyVersion, ReviewedBy: string(snapshot.ReviewedBy),
|
||||
ReviewedAt: pgTime(snapshot.ReviewedAt),
|
||||
})
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("%s - insert review: %w", location, mapAssessmentAttemptError(err))
|
||||
}
|
||||
return rows == 1, nil
|
||||
}
|
||||
|
||||
// SaveCandidateAssessmentCategory writes a strict upgrade. Zero affected rows
|
||||
// mean the stored grade is not lower than the new one, which the caller's
|
||||
// category lock should have made impossible.
|
||||
func (repository assessmentAttemptRepository) SaveCandidateAssessmentCategory(
|
||||
ctx context.Context,
|
||||
category domain.CandidateAssessmentCategory,
|
||||
) error {
|
||||
const location = "assessmentAttemptRepository.SaveCandidateAssessmentCategory"
|
||||
if category.IsZero() {
|
||||
return fmt.Errorf("%s - category is required: %w", location, domain.ErrInvalidAssessmentCategory)
|
||||
}
|
||||
snapshot := category.Snapshot()
|
||||
rows, err := repository.queries.SaveCandidateAssessmentCategory(ctx, sqlc.SaveCandidateAssessmentCategoryParams{
|
||||
CandidateID: pgUUID(snapshot.CandidateID), Specialization: string(snapshot.Specialization),
|
||||
Grade: string(snapshot.Grade), SourceAttemptID: pgUUID(snapshot.SourceAttemptID.UUID()),
|
||||
SourceReviewID: pgUUID(snapshot.SourceReviewID),
|
||||
ProductPolicyVersionID: pgUUID(snapshot.ProductPolicyVersionID.UUID()),
|
||||
ProductPolicyVersion: snapshot.ProductPolicyVersion, OpeningID: pgUUID(snapshot.OpeningID),
|
||||
OpeningManifestSha256: bytes.Clone(snapshot.OpeningManifestHash[:]), Source: string(snapshot.Source),
|
||||
CalibrationStatus: string(snapshot.CalibrationStatus), AssignedAt: pgTime(snapshot.AssignedAt),
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - upsert current category: %w", location, mapAssessmentAttemptError(err))
|
||||
}
|
||||
if rows != 1 {
|
||||
return fmt.Errorf("%s - category was not upgraded: %w", location, outbound.ErrAssessmentCategoryConflict)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -184,21 +184,9 @@ func notificationInboxOptionalUUID(value *uuid.UUID) pgtype.UUID {
|
||||
return pgUUID(*value)
|
||||
}
|
||||
|
||||
func notificationInboxEntryFromRow(row sqlc.GetNotificationInboxEventRow) (domain.NotificationInboxEntry, error) {
|
||||
return restoreNotificationInboxEntryRow(
|
||||
row.RecipientUserID, row.EventID, row.OrganizationID, row.EventType,
|
||||
row.SchemaVersion, row.SourceType, row.SourceID, row.OccurredAt, row.ReadAt,
|
||||
)
|
||||
}
|
||||
|
||||
func notificationInboxEntryFromListRow(row sqlc.ListNotificationInboxEventsRow) (domain.NotificationInboxEntry, error) {
|
||||
return restoreNotificationInboxEntryRow(
|
||||
row.RecipientUserID, row.EventID, row.OrganizationID, row.EventType,
|
||||
row.SchemaVersion, row.SourceType, row.SourceID, row.OccurredAt, row.ReadAt,
|
||||
)
|
||||
}
|
||||
|
||||
func notificationInboxEntryFromReadRow(row sqlc.MarkNotificationInboxEventReadRow) (domain.NotificationInboxEntry, error) {
|
||||
// The three inbox queries select every column of the table in table order, so
|
||||
// sqlc returns the shared model type for all of them.
|
||||
func notificationInboxEntryFromRow(row sqlc.NotificationInboxEvent) (domain.NotificationInboxEntry, error) {
|
||||
return restoreNotificationInboxEntryRow(
|
||||
row.RecipientUserID, row.EventID, row.OrganizationID, row.EventType,
|
||||
row.SchemaVersion, row.SourceType, row.SourceID, row.OccurredAt, row.ReadAt,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
@@ -55,6 +56,7 @@ type privacyCohortCandidate struct {
|
||||
claims []domain.StoredProfileClaim
|
||||
acknowledgements []domain.ProfileParallelPeriodAcknowledgement
|
||||
workFormats []domain.QuestionnaireWorkFormat
|
||||
categories []domain.CandidateViewConfirmedCategoryInput
|
||||
}
|
||||
|
||||
func (repository privacyCohortRepository) ListVisibleCandidateViewSources(
|
||||
@@ -88,7 +90,7 @@ func (repository privacyCohortRepository) ListVisibleCandidateViewSources(
|
||||
current = privacyCohortCandidate{}
|
||||
}
|
||||
if current.id == uuid.Nil {
|
||||
current, err = newPrivacyCohortCandidate(candidateID, row.Fields, row.WorkFormats, row.ParallelPeriodAcknowledgements)
|
||||
current, err = newPrivacyCohortCandidate(candidateID, row.Fields, row.WorkFormats, row.ParallelPeriodAcknowledgements, row.ConfirmedCategories)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - restore candidate source: %w", location, err)
|
||||
}
|
||||
@@ -114,6 +116,7 @@ func newPrivacyCohortCandidate(
|
||||
fieldCodes []string,
|
||||
workFormatCodes []string,
|
||||
acknowledgementsValue any,
|
||||
confirmedCategoriesValue any,
|
||||
) (privacyCohortCandidate, error) {
|
||||
fields := make([]domain.CardField, 0, len(fieldCodes))
|
||||
for _, code := range fieldCodes {
|
||||
@@ -135,12 +138,47 @@ func newPrivacyCohortCandidate(
|
||||
if err := json.Unmarshal(acknowledgementsJSON, &acknowledgements); err != nil {
|
||||
return privacyCohortCandidate{}, fmt.Errorf("invalid overlap acknowledgements: %w", domain.ErrInvalidCandidateProfile)
|
||||
}
|
||||
categories, err := privacyCohortConfirmedCategories(confirmedCategoriesValue)
|
||||
if err != nil {
|
||||
return privacyCohortCandidate{}, err
|
||||
}
|
||||
return privacyCohortCandidate{
|
||||
id: candidateID, fields: fieldSet, workFormats: workFormats,
|
||||
acknowledgements: acknowledgements,
|
||||
acknowledgements: acknowledgements, categories: categories,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// privacyCohortCategoryStrength is the card strength of a demonstration
|
||||
// category. The synthetic demo source has no adaptive confirmation, so no
|
||||
// category is reported as strong.
|
||||
const privacyCohortCategoryStrength = domain.CandidateViewStrengthStandard
|
||||
|
||||
// privacyCohortConfirmedCategories reads the current categories selected by
|
||||
// the cohort query: only a specialization and a grade of each, never the
|
||||
// attempt, score, policy, or review that produced it.
|
||||
func privacyCohortConfirmedCategories(value any) ([]domain.CandidateViewConfirmedCategoryInput, error) {
|
||||
encoded, err := privacyCohortEncodedJSONBytes(value)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid confirmed categories: %w", domain.ErrInvalidCandidateViewSource)
|
||||
}
|
||||
var stored []struct {
|
||||
Specialization domain.SpecializationCode `json:"specialization"`
|
||||
Grade domain.GradeCode `json:"grade"`
|
||||
}
|
||||
decoder := json.NewDecoder(bytes.NewReader(encoded))
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(&stored); err != nil {
|
||||
return nil, fmt.Errorf("invalid confirmed categories: %w", domain.ErrInvalidCandidateViewSource)
|
||||
}
|
||||
categories := make([]domain.CandidateViewConfirmedCategoryInput, 0, len(stored))
|
||||
for _, category := range stored {
|
||||
categories = append(categories, domain.CandidateViewConfirmedCategoryInput{
|
||||
Specialization: category.Specialization, Grade: category.Grade, Strength: privacyCohortCategoryStrength,
|
||||
})
|
||||
}
|
||||
return categories, nil
|
||||
}
|
||||
|
||||
func privacyCohortStoredClaim(row sqlc.ListVisibleCandidateViewSourcesRow) (domain.StoredProfileClaim, error) {
|
||||
value, err := privacyCohortJSONBytes(row.SafeValue)
|
||||
if err != nil {
|
||||
@@ -166,7 +204,7 @@ func buildPrivacyCohortSource(candidate privacyCohortCandidate) (domain.Candidat
|
||||
return domain.CandidateViewSource{}, fmt.Errorf("validate safe profile claims: %w", domain.ErrInvalidCandidateViewSource)
|
||||
}
|
||||
return domain.NewCandidateViewSource(
|
||||
candidate.id, candidate.fields, domain.CandidateViewProfileFromContent(content), nil,
|
||||
candidate.id, candidate.fields, domain.CandidateViewProfileFromContent(content), candidate.categories,
|
||||
candidate.workFormats, nil,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -117,7 +117,7 @@ func buildPreviewCandidateViewSource(
|
||||
if got, err := privacyCohortUUID(first.UserID); err != nil || got != candidateID {
|
||||
return domain.CandidateViewSource{}, fmt.Errorf("%s - projection identity is invalid: %w", location, domain.ErrInvalidCandidateViewSource)
|
||||
}
|
||||
candidate, err := newPrivacyCohortCandidate(candidateID, first.Fields, first.WorkFormats, first.ParallelPeriodAcknowledgements)
|
||||
candidate, err := newPrivacyCohortCandidate(candidateID, first.Fields, first.WorkFormats, first.ParallelPeriodAcknowledgements, first.ConfirmedCategories)
|
||||
if err != nil {
|
||||
return domain.CandidateViewSource{}, fmt.Errorf("%s - restore candidate input: %w", location, err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,403 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: assessment_results.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const getAssessmentAttemptResultHistoryEntry = `-- name: GetAssessmentAttemptResultHistoryEntry :one
|
||||
SELECT schema_version, result_snapshot::text,
|
||||
COALESCE(category_decision::text, '')::text AS category_decision, current_confirmed_grade
|
||||
FROM assessment_attempt_results
|
||||
WHERE user_id = $1 AND attempt_id = $2
|
||||
`
|
||||
|
||||
type GetAssessmentAttemptResultHistoryEntryParams struct {
|
||||
UserID pgtype.UUID
|
||||
AttemptID pgtype.UUID
|
||||
}
|
||||
|
||||
type GetAssessmentAttemptResultHistoryEntryRow struct {
|
||||
SchemaVersion int16
|
||||
ResultSnapshot string
|
||||
CategoryDecision string
|
||||
CurrentConfirmedGrade pgtype.Text
|
||||
}
|
||||
|
||||
// Returns both immutable result versions. NULL category fields identify a
|
||||
// legacy v1 record and must not be reconstructed from current state.
|
||||
func (q *Queries) GetAssessmentAttemptResultHistoryEntry(ctx context.Context, arg GetAssessmentAttemptResultHistoryEntryParams) (GetAssessmentAttemptResultHistoryEntryRow, error) {
|
||||
row := q.db.QueryRow(ctx, getAssessmentAttemptResultHistoryEntry, arg.UserID, arg.AttemptID)
|
||||
var i GetAssessmentAttemptResultHistoryEntryRow
|
||||
err := row.Scan(
|
||||
&i.SchemaVersion,
|
||||
&i.ResultSnapshot,
|
||||
&i.CategoryDecision,
|
||||
&i.CurrentConfirmedGrade,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getCandidateAssessmentCategory = `-- name: GetCandidateAssessmentCategory :one
|
||||
SELECT candidate_id, specialization, grade, source_attempt_id, source_review_id,
|
||||
product_policy_version_id, product_policy_version, grading_policy_version_id,
|
||||
opening_id, opening_manifest_sha256, source, calibration_status, assigned_at
|
||||
FROM candidate_assessment_categories
|
||||
WHERE candidate_id = $1 AND specialization = $2
|
||||
`
|
||||
|
||||
type GetCandidateAssessmentCategoryParams struct {
|
||||
CandidateID pgtype.UUID
|
||||
Specialization string
|
||||
}
|
||||
|
||||
func (q *Queries) GetCandidateAssessmentCategory(ctx context.Context, arg GetCandidateAssessmentCategoryParams) (CandidateAssessmentCategory, error) {
|
||||
row := q.db.QueryRow(ctx, getCandidateAssessmentCategory, arg.CandidateID, arg.Specialization)
|
||||
var i CandidateAssessmentCategory
|
||||
err := row.Scan(
|
||||
&i.CandidateID,
|
||||
&i.Specialization,
|
||||
&i.Grade,
|
||||
&i.SourceAttemptID,
|
||||
&i.SourceReviewID,
|
||||
&i.ProductPolicyVersionID,
|
||||
&i.ProductPolicyVersion,
|
||||
&i.GradingPolicyVersionID,
|
||||
&i.OpeningID,
|
||||
&i.OpeningManifestSha256,
|
||||
&i.Source,
|
||||
&i.CalibrationStatus,
|
||||
&i.AssignedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getSyntheticCategoryReview = `-- name: GetSyntheticCategoryReview :one
|
||||
SELECT review.id, review.opening_id, review.category, review.source,
|
||||
review.opening_manifest_sha256, review.product_policy_version_id,
|
||||
review.product_policy_version, review.reviewed_by, review.reviewed_at
|
||||
FROM assessment_synthetic_category_reviews AS review
|
||||
JOIN assessment_category_openings AS opening ON opening.id = review.opening_id
|
||||
WHERE review.opening_id = $1
|
||||
AND review.category = $2
|
||||
AND review.source = 'synthetic_demo'
|
||||
AND review.opening_manifest_sha256 = $3
|
||||
AND review.product_policy_version_id = $4
|
||||
AND review.product_policy_version = $5
|
||||
AND opening.policy_version_id = $6
|
||||
`
|
||||
|
||||
type GetSyntheticCategoryReviewParams struct {
|
||||
OpeningID pgtype.UUID
|
||||
Category string
|
||||
OpeningManifestSha256 []byte
|
||||
ProductPolicyVersionID pgtype.UUID
|
||||
ProductPolicyVersion int32
|
||||
GradingPolicyVersionID pgtype.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) GetSyntheticCategoryReview(ctx context.Context, arg GetSyntheticCategoryReviewParams) (AssessmentSyntheticCategoryReview, error) {
|
||||
row := q.db.QueryRow(ctx, getSyntheticCategoryReview,
|
||||
arg.OpeningID,
|
||||
arg.Category,
|
||||
arg.OpeningManifestSha256,
|
||||
arg.ProductPolicyVersionID,
|
||||
arg.ProductPolicyVersion,
|
||||
arg.GradingPolicyVersionID,
|
||||
)
|
||||
var i AssessmentSyntheticCategoryReview
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.OpeningID,
|
||||
&i.Category,
|
||||
&i.Source,
|
||||
&i.OpeningManifestSha256,
|
||||
&i.ProductPolicyVersionID,
|
||||
&i.ProductPolicyVersion,
|
||||
&i.ReviewedBy,
|
||||
&i.ReviewedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const insertAssessmentAttemptResultV2 = `-- name: InsertAssessmentAttemptResultV2 :exec
|
||||
INSERT INTO assessment_attempt_results (
|
||||
attempt_id, user_id, result_snapshot, schema_version, category_decision,
|
||||
current_confirmed_grade, kind, mode, outcome, product_policy_version_id,
|
||||
product_policy_version, grading_policy_version_id, opening_id,
|
||||
opening_manifest_sha256, training_binding_id, training_manifest_sha256,
|
||||
bank_version, algorithm_version, rationale_rule, pass_mark_basis_points,
|
||||
scored_items, raw_score, pass_points, decided_at
|
||||
) VALUES (
|
||||
$1, $2, $3, 2,
|
||||
$4::jsonb, $5,
|
||||
$6, $7, $8, $9,
|
||||
$10, $11, $12,
|
||||
$13, NULL, NULL, $14,
|
||||
$15, $16, $17,
|
||||
$18, $19, $20, $21
|
||||
)
|
||||
`
|
||||
|
||||
type InsertAssessmentAttemptResultV2Params struct {
|
||||
AttemptID pgtype.UUID
|
||||
UserID pgtype.UUID
|
||||
ResultSnapshot []byte
|
||||
CategoryDecision []byte
|
||||
CurrentConfirmedGrade pgtype.Text
|
||||
Kind string
|
||||
Mode string
|
||||
Outcome string
|
||||
ProductPolicyVersionID pgtype.UUID
|
||||
ProductPolicyVersion int32
|
||||
GradingPolicyVersionID pgtype.UUID
|
||||
OpeningID pgtype.UUID
|
||||
OpeningManifestSha256 []byte
|
||||
BankVersion string
|
||||
AlgorithmVersion string
|
||||
RationaleRule string
|
||||
PassMarkBasisPoints pgtype.Int4
|
||||
ScoredItems pgtype.Int2
|
||||
RawScore pgtype.Int2
|
||||
PassPoints pgtype.Int2
|
||||
DecidedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// Stores the category decision and current grade captured at real-attempt
|
||||
// finalization. The base result document remains its original v1 shape.
|
||||
func (q *Queries) InsertAssessmentAttemptResultV2(ctx context.Context, arg InsertAssessmentAttemptResultV2Params) error {
|
||||
_, err := q.db.Exec(ctx, insertAssessmentAttemptResultV2,
|
||||
arg.AttemptID,
|
||||
arg.UserID,
|
||||
arg.ResultSnapshot,
|
||||
arg.CategoryDecision,
|
||||
arg.CurrentConfirmedGrade,
|
||||
arg.Kind,
|
||||
arg.Mode,
|
||||
arg.Outcome,
|
||||
arg.ProductPolicyVersionID,
|
||||
arg.ProductPolicyVersion,
|
||||
arg.GradingPolicyVersionID,
|
||||
arg.OpeningID,
|
||||
arg.OpeningManifestSha256,
|
||||
arg.BankVersion,
|
||||
arg.AlgorithmVersion,
|
||||
arg.RationaleRule,
|
||||
arg.PassMarkBasisPoints,
|
||||
arg.ScoredItems,
|
||||
arg.RawScore,
|
||||
arg.PassPoints,
|
||||
arg.DecidedAt,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const insertSyntheticCategoryReview = `-- name: InsertSyntheticCategoryReview :execrows
|
||||
INSERT INTO assessment_synthetic_category_reviews (
|
||||
id, opening_id, category, source, opening_manifest_sha256,
|
||||
product_policy_version_id, product_policy_version, reviewed_by, reviewed_at
|
||||
) VALUES (
|
||||
$1, $2, $3, $4,
|
||||
$5, $6,
|
||||
$7, $8, $9
|
||||
)
|
||||
ON CONFLICT ON CONSTRAINT assessment_synthetic_category_reviews_exact_source_key DO NOTHING
|
||||
`
|
||||
|
||||
type InsertSyntheticCategoryReviewParams struct {
|
||||
ID pgtype.UUID
|
||||
OpeningID pgtype.UUID
|
||||
Category string
|
||||
Source string
|
||||
OpeningManifestSha256 []byte
|
||||
ProductPolicyVersionID pgtype.UUID
|
||||
ProductPolicyVersion int32
|
||||
ReviewedBy string
|
||||
ReviewedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// The application accepts only a validated immutable review snapshot. The
|
||||
// trigger independently checks the source opening, manifest and policy. A
|
||||
// concurrent or repeated attestation of the same exact source inserts nothing,
|
||||
// and the caller reads the stored one.
|
||||
func (q *Queries) InsertSyntheticCategoryReview(ctx context.Context, arg InsertSyntheticCategoryReviewParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, insertSyntheticCategoryReview,
|
||||
arg.ID,
|
||||
arg.OpeningID,
|
||||
arg.Category,
|
||||
arg.Source,
|
||||
arg.OpeningManifestSha256,
|
||||
arg.ProductPolicyVersionID,
|
||||
arg.ProductPolicyVersion,
|
||||
arg.ReviewedBy,
|
||||
arg.ReviewedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const listCandidateAssessmentResults = `-- name: ListCandidateAssessmentResults :many
|
||||
SELECT attempt_id, user_id, schema_version, result_snapshot::text,
|
||||
COALESCE(category_decision::text, '')::text AS category_decision, current_confirmed_grade, decided_at
|
||||
FROM assessment_attempt_results
|
||||
WHERE user_id = $1
|
||||
AND kind IN ('root', 'corrective')
|
||||
AND ($2::timestamptz IS NULL OR
|
||||
(decided_at, attempt_id) <
|
||||
($2::timestamptz, $3::uuid))
|
||||
ORDER BY decided_at DESC, attempt_id DESC
|
||||
LIMIT $4::integer + 1
|
||||
`
|
||||
|
||||
type ListCandidateAssessmentResultsParams struct {
|
||||
UserID pgtype.UUID
|
||||
CursorDecidedAt pgtype.Timestamptz
|
||||
CursorAttemptID pgtype.UUID
|
||||
LimitCount int32
|
||||
}
|
||||
|
||||
type ListCandidateAssessmentResultsRow struct {
|
||||
AttemptID pgtype.UUID
|
||||
UserID pgtype.UUID
|
||||
SchemaVersion int16
|
||||
ResultSnapshot string
|
||||
CategoryDecision string
|
||||
CurrentConfirmedGrade pgtype.Text
|
||||
DecidedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// The caller validates and signs an opaque owner-bound cursor. This query
|
||||
// applies the keyset to the same stable order and fetches one extra row.
|
||||
func (q *Queries) ListCandidateAssessmentResults(ctx context.Context, arg ListCandidateAssessmentResultsParams) ([]ListCandidateAssessmentResultsRow, error) {
|
||||
rows, err := q.db.Query(ctx, listCandidateAssessmentResults,
|
||||
arg.UserID,
|
||||
arg.CursorDecidedAt,
|
||||
arg.CursorAttemptID,
|
||||
arg.LimitCount,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []ListCandidateAssessmentResultsRow
|
||||
for rows.Next() {
|
||||
var i ListCandidateAssessmentResultsRow
|
||||
if err := rows.Scan(
|
||||
&i.AttemptID,
|
||||
&i.UserID,
|
||||
&i.SchemaVersion,
|
||||
&i.ResultSnapshot,
|
||||
&i.CategoryDecision,
|
||||
&i.CurrentConfirmedGrade,
|
||||
&i.DecidedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const lockCandidateAssessmentCategory = `-- name: LockCandidateAssessmentCategory :exec
|
||||
SELECT pg_advisory_xact_lock(hashtextextended(
|
||||
'lincodex.assessment.category:candidate:' || $1::text || ':' || $2::text,
|
||||
0
|
||||
))
|
||||
`
|
||||
|
||||
type LockCandidateAssessmentCategoryParams struct {
|
||||
CandidateID string
|
||||
Specialization string
|
||||
}
|
||||
|
||||
// Acquired after C3, candidate/specialization scope, and attempt row locks.
|
||||
// This independent lock serializes current category upgrades for one scope.
|
||||
func (q *Queries) LockCandidateAssessmentCategory(ctx context.Context, arg LockCandidateAssessmentCategoryParams) error {
|
||||
_, err := q.db.Exec(ctx, lockCandidateAssessmentCategory, arg.CandidateID, arg.Specialization)
|
||||
return err
|
||||
}
|
||||
|
||||
const saveCandidateAssessmentCategory = `-- name: SaveCandidateAssessmentCategory :execrows
|
||||
INSERT INTO candidate_assessment_categories (
|
||||
candidate_id, specialization, grade, source_attempt_id, source_review_id,
|
||||
product_policy_version_id, product_policy_version, grading_policy_version_id,
|
||||
opening_id, opening_manifest_sha256, source, calibration_status, assigned_at
|
||||
) VALUES (
|
||||
$1, $2, $3, $4,
|
||||
$5, $6, $7,
|
||||
(
|
||||
SELECT opening.policy_version_id
|
||||
FROM assessment_category_openings AS opening
|
||||
WHERE opening.id = $8
|
||||
),
|
||||
$8, $9,
|
||||
$10, $11, $12
|
||||
)
|
||||
ON CONFLICT (candidate_id, specialization) DO UPDATE SET
|
||||
grade = EXCLUDED.grade,
|
||||
source_attempt_id = EXCLUDED.source_attempt_id,
|
||||
source_review_id = EXCLUDED.source_review_id,
|
||||
product_policy_version_id = EXCLUDED.product_policy_version_id,
|
||||
product_policy_version = EXCLUDED.product_policy_version,
|
||||
grading_policy_version_id = EXCLUDED.grading_policy_version_id,
|
||||
opening_id = EXCLUDED.opening_id,
|
||||
opening_manifest_sha256 = EXCLUDED.opening_manifest_sha256,
|
||||
source = EXCLUDED.source,
|
||||
calibration_status = EXCLUDED.calibration_status,
|
||||
assigned_at = EXCLUDED.assigned_at
|
||||
WHERE CASE candidate_assessment_categories.grade
|
||||
WHEN 'intern' THEN 0 WHEN 'junior' THEN 1 WHEN 'middle' THEN 2 WHEN 'senior' THEN 3 ELSE -1 END
|
||||
< CASE EXCLUDED.grade
|
||||
WHEN 'intern' THEN 0 WHEN 'junior' THEN 1 WHEN 'middle' THEN 2 WHEN 'senior' THEN 3 ELSE -1 END
|
||||
`
|
||||
|
||||
type SaveCandidateAssessmentCategoryParams struct {
|
||||
CandidateID pgtype.UUID
|
||||
Specialization string
|
||||
Grade string
|
||||
SourceAttemptID pgtype.UUID
|
||||
SourceReviewID pgtype.UUID
|
||||
ProductPolicyVersionID pgtype.UUID
|
||||
ProductPolicyVersion int32
|
||||
OpeningID pgtype.UUID
|
||||
OpeningManifestSha256 []byte
|
||||
Source string
|
||||
CalibrationStatus string
|
||||
AssignedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// Only strict grade upgrades replace the current row. The trigger enforces
|
||||
// the same monotonic rule as a final guard against adapter mistakes. The
|
||||
// grading policy is read from the immutable opening, and the guard trigger
|
||||
// compares it with the policy captured in the assigned result.
|
||||
func (q *Queries) SaveCandidateAssessmentCategory(ctx context.Context, arg SaveCandidateAssessmentCategoryParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, saveCandidateAssessmentCategory,
|
||||
arg.CandidateID,
|
||||
arg.Specialization,
|
||||
arg.Grade,
|
||||
arg.SourceAttemptID,
|
||||
arg.SourceReviewID,
|
||||
arg.ProductPolicyVersionID,
|
||||
arg.ProductPolicyVersion,
|
||||
arg.OpeningID,
|
||||
arg.OpeningManifestSha256,
|
||||
arg.Source,
|
||||
arg.CalibrationStatus,
|
||||
arg.AssignedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
@@ -134,6 +134,8 @@ type AssessmentAttemptResult struct {
|
||||
RawScore pgtype.Int2
|
||||
PassPoints pgtype.Int2
|
||||
DecidedAt pgtype.Timestamptz
|
||||
CategoryDecision []byte
|
||||
CurrentConfirmedGrade pgtype.Text
|
||||
}
|
||||
|
||||
type AssessmentAttemptReview struct {
|
||||
@@ -240,6 +242,18 @@ type AssessmentSignalNoticeAcknowledgement struct {
|
||||
AcknowledgedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type AssessmentSyntheticCategoryReview struct {
|
||||
ID pgtype.UUID
|
||||
OpeningID pgtype.UUID
|
||||
Category string
|
||||
Source string
|
||||
OpeningManifestSha256 []byte
|
||||
ProductPolicyVersionID pgtype.UUID
|
||||
ProductPolicyVersion int32
|
||||
ReviewedBy string
|
||||
ReviewedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type AssessmentTrainingBankBinding struct {
|
||||
ID pgtype.UUID
|
||||
Category string
|
||||
@@ -260,6 +274,22 @@ type AssessmentTrainingBankBindingFamily struct {
|
||||
ContentSha256 []byte
|
||||
}
|
||||
|
||||
type CandidateAssessmentCategory struct {
|
||||
CandidateID pgtype.UUID
|
||||
Specialization string
|
||||
Grade string
|
||||
SourceAttemptID pgtype.UUID
|
||||
SourceReviewID pgtype.UUID
|
||||
ProductPolicyVersionID pgtype.UUID
|
||||
ProductPolicyVersion int32
|
||||
GradingPolicyVersionID pgtype.UUID
|
||||
OpeningID pgtype.UUID
|
||||
OpeningManifestSha256 []byte
|
||||
Source string
|
||||
CalibrationStatus string
|
||||
AssignedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type CandidateCardAccessEvent struct {
|
||||
ID pgtype.UUID
|
||||
CandidateID pgtype.UUID
|
||||
@@ -584,6 +614,18 @@ type Membership struct {
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type NotificationInboxEvent struct {
|
||||
RecipientUserID pgtype.UUID
|
||||
EventID pgtype.UUID
|
||||
OrganizationID pgtype.UUID
|
||||
EventType string
|
||||
SchemaVersion int32
|
||||
SourceType string
|
||||
SourceID pgtype.UUID
|
||||
OccurredAt pgtype.Timestamptz
|
||||
ReadAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type Organization struct {
|
||||
ID pgtype.UUID
|
||||
Name string
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: notification_inbox.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const getNotificationInboxEvent = `-- name: GetNotificationInboxEvent :one
|
||||
SELECT
|
||||
recipient_user_id,
|
||||
event_id,
|
||||
organization_id,
|
||||
event_type,
|
||||
schema_version,
|
||||
source_type,
|
||||
source_id,
|
||||
occurred_at,
|
||||
read_at
|
||||
FROM notification_inbox_events
|
||||
WHERE recipient_user_id = $1
|
||||
AND event_id = $2
|
||||
`
|
||||
|
||||
type GetNotificationInboxEventParams struct {
|
||||
RecipientUserID pgtype.UUID
|
||||
EventID pgtype.UUID
|
||||
}
|
||||
|
||||
// Read the existing row after a duplicate insert so the repository can reject
|
||||
// an event ID whose immutable metadata changed on redelivery.
|
||||
func (q *Queries) GetNotificationInboxEvent(ctx context.Context, arg GetNotificationInboxEventParams) (NotificationInboxEvent, error) {
|
||||
row := q.db.QueryRow(ctx, getNotificationInboxEvent, arg.RecipientUserID, arg.EventID)
|
||||
var i NotificationInboxEvent
|
||||
err := row.Scan(
|
||||
&i.RecipientUserID,
|
||||
&i.EventID,
|
||||
&i.OrganizationID,
|
||||
&i.EventType,
|
||||
&i.SchemaVersion,
|
||||
&i.SourceType,
|
||||
&i.SourceID,
|
||||
&i.OccurredAt,
|
||||
&i.ReadAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const insertNotificationInboxEvent = `-- name: InsertNotificationInboxEvent :execrows
|
||||
INSERT INTO notification_inbox_events (
|
||||
recipient_user_id,
|
||||
event_id,
|
||||
organization_id,
|
||||
event_type,
|
||||
schema_version,
|
||||
source_type,
|
||||
source_id,
|
||||
occurred_at
|
||||
) VALUES (
|
||||
$1,
|
||||
$2,
|
||||
$3,
|
||||
$4,
|
||||
$5,
|
||||
$6,
|
||||
$7,
|
||||
$8
|
||||
)
|
||||
ON CONFLICT (recipient_user_id, event_id) DO NOTHING
|
||||
`
|
||||
|
||||
type InsertNotificationInboxEventParams struct {
|
||||
RecipientUserID pgtype.UUID
|
||||
EventID pgtype.UUID
|
||||
OrganizationID pgtype.UUID
|
||||
EventType string
|
||||
SchemaVersion int32
|
||||
SourceType string
|
||||
SourceID pgtype.UUID
|
||||
OccurredAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// Store one recipient's reference to a delivered invitation event. The
|
||||
// unique key absorbs at-least-once redelivery without copying event content.
|
||||
func (q *Queries) InsertNotificationInboxEvent(ctx context.Context, arg InsertNotificationInboxEventParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, insertNotificationInboxEvent,
|
||||
arg.RecipientUserID,
|
||||
arg.EventID,
|
||||
arg.OrganizationID,
|
||||
arg.EventType,
|
||||
arg.SchemaVersion,
|
||||
arg.SourceType,
|
||||
arg.SourceID,
|
||||
arg.OccurredAt,
|
||||
)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const listNotificationInboxEvents = `-- name: ListNotificationInboxEvents :many
|
||||
SELECT
|
||||
recipient_user_id,
|
||||
event_id,
|
||||
organization_id,
|
||||
event_type,
|
||||
schema_version,
|
||||
source_type,
|
||||
source_id,
|
||||
occurred_at,
|
||||
read_at
|
||||
FROM notification_inbox_events
|
||||
WHERE recipient_user_id = $1
|
||||
AND (
|
||||
$2::uuid IS NULL
|
||||
OR organization_id = $2::uuid
|
||||
)
|
||||
AND (
|
||||
$3::timestamptz IS NULL
|
||||
OR (occurred_at, event_id) < (
|
||||
$3::timestamptz,
|
||||
$4::uuid
|
||||
)
|
||||
)
|
||||
ORDER BY occurred_at DESC, event_id DESC
|
||||
LIMIT $5
|
||||
`
|
||||
|
||||
type ListNotificationInboxEventsParams struct {
|
||||
RecipientUserID pgtype.UUID
|
||||
OrganizationID pgtype.UUID
|
||||
AfterOccurredAt pgtype.Timestamptz
|
||||
AfterEventID pgtype.UUID
|
||||
PageLimit int32
|
||||
}
|
||||
|
||||
// List only the authenticated recipient's rows, optionally narrowed to one
|
||||
// organization context. The caller resolves current source visibility before
|
||||
// returning content.
|
||||
func (q *Queries) ListNotificationInboxEvents(ctx context.Context, arg ListNotificationInboxEventsParams) ([]NotificationInboxEvent, error) {
|
||||
rows, err := q.db.Query(ctx, listNotificationInboxEvents,
|
||||
arg.RecipientUserID,
|
||||
arg.OrganizationID,
|
||||
arg.AfterOccurredAt,
|
||||
arg.AfterEventID,
|
||||
arg.PageLimit,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []NotificationInboxEvent
|
||||
for rows.Next() {
|
||||
var i NotificationInboxEvent
|
||||
if err := rows.Scan(
|
||||
&i.RecipientUserID,
|
||||
&i.EventID,
|
||||
&i.OrganizationID,
|
||||
&i.EventType,
|
||||
&i.SchemaVersion,
|
||||
&i.SourceType,
|
||||
&i.SourceID,
|
||||
&i.OccurredAt,
|
||||
&i.ReadAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const markNotificationInboxEventRead = `-- name: MarkNotificationInboxEventRead :one
|
||||
UPDATE notification_inbox_events
|
||||
SET read_at = COALESCE(read_at, $1::timestamptz)
|
||||
WHERE recipient_user_id = $2
|
||||
AND organization_id = $3
|
||||
AND event_id = $4
|
||||
RETURNING
|
||||
recipient_user_id,
|
||||
event_id,
|
||||
organization_id,
|
||||
event_type,
|
||||
schema_version,
|
||||
source_type,
|
||||
source_id,
|
||||
occurred_at,
|
||||
read_at
|
||||
`
|
||||
|
||||
type MarkNotificationInboxEventReadParams struct {
|
||||
ReadAt pgtype.Timestamptz
|
||||
RecipientUserID pgtype.UUID
|
||||
OrganizationID pgtype.UUID
|
||||
EventID pgtype.UUID
|
||||
}
|
||||
|
||||
// Persist the first read time under exact recipient and organization scope.
|
||||
// Repeated calls preserve the original read timestamp.
|
||||
func (q *Queries) MarkNotificationInboxEventRead(ctx context.Context, arg MarkNotificationInboxEventReadParams) (NotificationInboxEvent, error) {
|
||||
row := q.db.QueryRow(ctx, markNotificationInboxEventRead,
|
||||
arg.ReadAt,
|
||||
arg.RecipientUserID,
|
||||
arg.OrganizationID,
|
||||
arg.EventID,
|
||||
)
|
||||
var i NotificationInboxEvent
|
||||
err := row.Scan(
|
||||
&i.RecipientUserID,
|
||||
&i.EventID,
|
||||
&i.OrganizationID,
|
||||
&i.EventType,
|
||||
&i.SchemaVersion,
|
||||
&i.SourceType,
|
||||
&i.SourceID,
|
||||
&i.OccurredAt,
|
||||
&i.ReadAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -53,7 +53,18 @@ SELECT
|
||||
WHERE overlap.user_id = effective.user_id
|
||||
),
|
||||
'[]'::text
|
||||
) AS parallel_period_acknowledgements
|
||||
) AS parallel_period_acknowledgements,
|
||||
COALESCE(
|
||||
(
|
||||
SELECT jsonb_agg(
|
||||
jsonb_build_object('specialization', category.specialization, 'grade', category.grade)
|
||||
ORDER BY category.specialization
|
||||
)::text
|
||||
FROM candidate_assessment_categories AS category
|
||||
WHERE category.candidate_id = effective.user_id
|
||||
),
|
||||
'[]'::text
|
||||
) AS confirmed_categories
|
||||
FROM candidate_effective_publications AS effective
|
||||
LEFT JOIN candidate_profile_claims AS claim
|
||||
ON claim.user_id = effective.user_id
|
||||
@@ -82,6 +93,7 @@ type ListVisibleCandidateViewSourcesRow struct {
|
||||
ConfirmedAt pgtype.Timestamptz
|
||||
WorkFormats []string
|
||||
ParallelPeriodAcknowledgements interface{}
|
||||
ConfirmedCategories interface{}
|
||||
}
|
||||
|
||||
// Organization-facing anonymous candidate projection inputs. The calling
|
||||
@@ -90,7 +102,9 @@ type ListVisibleCandidateViewSourcesRow struct {
|
||||
// candidates hidden from this organization before any profile value is read.
|
||||
// The projection reads only stack, declared role, and experience dates. It
|
||||
// deliberately excludes names, contacts, salary, location, soft skills,
|
||||
// employer names, summaries, and imported excerpts.
|
||||
// employer names, summaries, and imported excerpts. The only assessment data
|
||||
// is the current category (specialization and grade) of the separate current
|
||||
// category table; it carries no attempt, score, review, policy, or history.
|
||||
func (q *Queries) ListVisibleCandidateViewSources(ctx context.Context, organizationID pgtype.UUID) ([]ListVisibleCandidateViewSourcesRow, error) {
|
||||
rows, err := q.db.Query(ctx, listVisibleCandidateViewSources, organizationID)
|
||||
if err != nil {
|
||||
@@ -113,6 +127,7 @@ func (q *Queries) ListVisibleCandidateViewSources(ctx context.Context, organizat
|
||||
&i.ConfirmedAt,
|
||||
&i.WorkFormats,
|
||||
&i.ParallelPeriodAcknowledgements,
|
||||
&i.ConfirmedCategories,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -267,7 +282,18 @@ SELECT
|
||||
WHERE overlap.user_id = effective.user_id
|
||||
),
|
||||
'[]'::text
|
||||
) AS parallel_period_acknowledgements
|
||||
) AS parallel_period_acknowledgements,
|
||||
COALESCE(
|
||||
(
|
||||
SELECT jsonb_agg(
|
||||
jsonb_build_object('specialization', category.specialization, 'grade', category.grade)
|
||||
ORDER BY category.specialization
|
||||
)::text
|
||||
FROM candidate_assessment_categories AS category
|
||||
WHERE category.candidate_id = effective.user_id
|
||||
),
|
||||
'[]'::text
|
||||
) AS confirmed_categories
|
||||
FROM candidate_effective_publications AS effective
|
||||
LEFT JOIN candidate_profile_claims AS claim
|
||||
ON claim.user_id = effective.user_id
|
||||
@@ -291,6 +317,7 @@ type ReadCandidateViewSourceForPreviewRow struct {
|
||||
ConfirmedAt pgtype.Timestamptz
|
||||
WorkFormats []string
|
||||
ParallelPeriodAcknowledgements interface{}
|
||||
ConfirmedCategories interface{}
|
||||
}
|
||||
|
||||
// Read the candidate's current private projection inputs after the caller
|
||||
@@ -318,6 +345,7 @@ func (q *Queries) ReadCandidateViewSourceForPreview(ctx context.Context, candida
|
||||
&i.ConfirmedAt,
|
||||
&i.WorkFormats,
|
||||
&i.ParallelPeriodAcknowledgements,
|
||||
&i.ConfirmedCategories,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -227,6 +227,9 @@ type Querier interface {
|
||||
GetAssessmentAttemptKindForCandidate(ctx context.Context, arg GetAssessmentAttemptKindForCandidateParams) (string, error)
|
||||
// Reads a result only for the owning candidate.
|
||||
GetAssessmentAttemptResult(ctx context.Context, arg GetAssessmentAttemptResultParams) (string, error)
|
||||
// Returns both immutable result versions. NULL category fields identify a
|
||||
// legacy v1 record and must not be reconstructed from current state.
|
||||
GetAssessmentAttemptResultHistoryEntry(ctx context.Context, arg GetAssessmentAttemptResultHistoryEntryParams) (GetAssessmentAttemptResultHistoryEntryRow, error)
|
||||
GetAssessmentAttemptReview(ctx context.Context, attemptID pgtype.UUID) (GetAssessmentAttemptReviewRow, error)
|
||||
// Reads an active real attempt without taking the write lock used by create.
|
||||
// The availability GET never expires or otherwise mutates this row.
|
||||
@@ -245,6 +248,7 @@ type Querier interface {
|
||||
GetAssessmentSignalNoticeAcknowledgement(ctx context.Context, arg GetAssessmentSignalNoticeAcknowledgementParams) (pgtype.Timestamptz, error)
|
||||
// Read only the receipt associated with the reserved idempotency scope.
|
||||
GetAssessmentSignalOutcome(ctx context.Context, scopeHash []byte) (GetAssessmentSignalOutcomeRow, error)
|
||||
GetCandidateAssessmentCategory(ctx context.Context, arg GetCandidateAssessmentCategoryParams) (CandidateAssessmentCategory, error)
|
||||
// Reads one hiding of the candidate with the current name of the
|
||||
// organization.
|
||||
GetCandidateHiddenOrganization(ctx context.Context, arg GetCandidateHiddenOrganizationParams) (GetCandidateHiddenOrganizationRow, error)
|
||||
@@ -297,6 +301,9 @@ type Querier interface {
|
||||
GetMailQuotaUsage(ctx context.Context, arg GetMailQuotaUsageParams) ([]GetMailQuotaUsageRow, error)
|
||||
// Reads the membership of one account in one organization, in any state.
|
||||
GetMembership(ctx context.Context, arg GetMembershipParams) (Membership, error)
|
||||
// Read the existing row after a duplicate insert so the repository can reject
|
||||
// an event ID whose immutable metadata changed on redelivery.
|
||||
GetNotificationInboxEvent(ctx context.Context, arg GetNotificationInboxEventParams) (NotificationInboxEvent, error)
|
||||
// Reads only the historical result. It intentionally does not join the live
|
||||
// organization or membership, whose profile and state may have since changed.
|
||||
GetOrganizationCreationResult(ctx context.Context, scopeHash []byte) ([]byte, error)
|
||||
@@ -334,6 +341,7 @@ type Querier interface {
|
||||
// selects no token hash. A missing binding or token row gives NULL token
|
||||
// columns.
|
||||
GetServiceMailState(ctx context.Context, id pgtype.UUID) (GetServiceMailStateRow, error)
|
||||
GetSyntheticCategoryReview(ctx context.Context, arg GetSyntheticCategoryReviewParams) (AssessmentSyntheticCategoryReview, error)
|
||||
GetUnrevokedConsentRecordByVersion(ctx context.Context, arg GetUnrevokedConsentRecordByVersionParams) (GetUnrevokedConsentRecordByVersionRow, error)
|
||||
GetUserByEmailNormalized(ctx context.Context, emailNormalized string) (User, error)
|
||||
GetUserByID(ctx context.Context, id pgtype.UUID) (User, error)
|
||||
@@ -347,6 +355,9 @@ type Querier interface {
|
||||
// Stores one immutable candidate-visible result with the decision rationale
|
||||
// and source versions used by its finalized attempt.
|
||||
InsertAssessmentAttemptResult(ctx context.Context, arg InsertAssessmentAttemptResultParams) error
|
||||
// Stores the category decision and current grade captured at real-attempt
|
||||
// finalization. The base result document remains its original v1 shape.
|
||||
InsertAssessmentAttemptResultV2(ctx context.Context, arg InsertAssessmentAttemptResultV2Params) error
|
||||
// Stores an explicit mapping against a newly-created immutable opening. The
|
||||
// insert trigger checks the opening, declared reviewer, current policy, and
|
||||
// live coverage; the adapter supplies the fingerprint of the published set.
|
||||
@@ -439,6 +450,9 @@ type Querier interface {
|
||||
InsertMailQuotaReservation(ctx context.Context, arg InsertMailQuotaReservationParams) error
|
||||
InsertMailRequest(ctx context.Context, arg InsertMailRequestParams) error
|
||||
InsertMembership(ctx context.Context, arg InsertMembershipParams) error
|
||||
// Store one recipient's reference to a delivered invitation event. The
|
||||
// unique key absorbs at-least-once redelivery without copying event content.
|
||||
InsertNotificationInboxEvent(ctx context.Context, arg InsertNotificationInboxEventParams) (int64, error)
|
||||
// Stores a new organization with the verification level that the domain
|
||||
// gave it. The deferred constraint organizations_owner_required fails the
|
||||
// transaction at commit unless an active owner membership was inserted in
|
||||
@@ -483,6 +497,11 @@ type Querier interface {
|
||||
InsertSupportCaseCreateOutcome(ctx context.Context, arg InsertSupportCaseCreateOutcomeParams) error
|
||||
InsertSupportCaseEvent(ctx context.Context, arg InsertSupportCaseEventParams) error
|
||||
InsertSupportCaseRequestEvent(ctx context.Context, arg InsertSupportCaseRequestEventParams) error
|
||||
// The application accepts only a validated immutable review snapshot. The
|
||||
// trigger independently checks the source opening, manifest and policy. A
|
||||
// concurrent or repeated attestation of the same exact source inserts nothing,
|
||||
// and the caller reads the stored one.
|
||||
InsertSyntheticCategoryReview(ctx context.Context, arg InsertSyntheticCategoryReviewParams) (int64, error)
|
||||
InsertUser(ctx context.Context, arg InsertUserParams) error
|
||||
InvalidateActiveEmailTokens(ctx context.Context, arg InvalidateActiveEmailTokensParams) (int64, error)
|
||||
// Read the latest serialized event so a temporarily regressing application
|
||||
@@ -523,6 +542,9 @@ type Querier interface {
|
||||
ListAssessmentOriginMarks(ctx context.Context, attemptID pgtype.UUID) ([]AssessmentAttemptOriginMark, error)
|
||||
// Reads the exact family membership pinned by a training binding.
|
||||
ListAssessmentTrainingBindingFamilies(ctx context.Context, bindingID pgtype.UUID) ([]ListAssessmentTrainingBindingFamiliesRow, error)
|
||||
// The caller validates and signs an opaque owner-bound cursor. This query
|
||||
// applies the keyset to the same stable order and fetches one extra row.
|
||||
ListCandidateAssessmentResults(ctx context.Context, arg ListCandidateAssessmentResultsParams) ([]ListCandidateAssessmentResultsRow, error)
|
||||
// Lists only the current candidate's own access history. It deliberately
|
||||
// omits the employee, requested card fields, and search context. The privacy
|
||||
// read adapter resolves an organization name only through this recorded
|
||||
@@ -559,6 +581,10 @@ type Querier interface {
|
||||
// fingerprint; stale bindings are omitted fail-closed.
|
||||
ListCurrentSpecializationAvailability(ctx context.Context) ([]ListCurrentSpecializationAvailabilityRow, error)
|
||||
ListDeliveryAttempts(ctx context.Context, deliveryID pgtype.UUID) ([]DeliveryAttempt, error)
|
||||
// List only the authenticated recipient's rows, optionally narrowed to one
|
||||
// organization context. The caller resolves current source visibility before
|
||||
// returning content.
|
||||
ListNotificationInboxEvents(ctx context.Context, arg ListNotificationInboxEventsParams) ([]NotificationInboxEvent, error)
|
||||
// Read one bounded newest-first page of current needs. Both the organization
|
||||
// scope and the tuple cursor are applied before the limit.
|
||||
ListOrganizationNeeds(ctx context.Context, arg ListOrganizationNeedsParams) ([]ListOrganizationNeedsRow, error)
|
||||
@@ -579,7 +605,9 @@ type Querier interface {
|
||||
// candidates hidden from this organization before any profile value is read.
|
||||
// The projection reads only stack, declared role, and experience dates. It
|
||||
// deliberately excludes names, contacts, salary, location, soft skills,
|
||||
// employer names, summaries, and imported excerpts.
|
||||
// employer names, summaries, and imported excerpts. The only assessment data
|
||||
// is the current category (specialization and grade) of the separate current
|
||||
// category table; it carries no attempt, score, review, policy, or history.
|
||||
ListVisibleCandidateViewSources(ctx context.Context, organizationID pgtype.UUID) ([]ListVisibleCandidateViewSourcesRow, error)
|
||||
// Locks the organization first and then the active membership, using the
|
||||
// same order as organization profile writes. A company operation keeps both
|
||||
@@ -604,6 +632,9 @@ type Querier interface {
|
||||
// a hide either commits before the later visibility recheck or waits for the
|
||||
// read transaction to finish.
|
||||
LockCandidateAccountForView(ctx context.Context, candidateID pgtype.UUID) (pgtype.UUID, error)
|
||||
// Acquired after C3, candidate/specialization scope, and attempt row locks.
|
||||
// This independent lock serializes current category upgrades for one scope.
|
||||
LockCandidateAssessmentCategory(ctx context.Context, arg LockCandidateAssessmentCategoryParams) error
|
||||
// Locks the candidate's published row only when it refers to a C2 record
|
||||
// revoked by this transaction. The setting remains linked to that immutable
|
||||
// record; ReadCandidatePublication computes the effective closed state and
|
||||
@@ -685,6 +716,9 @@ type Querier interface {
|
||||
// gate stops admitting sends until the window resets or an operator raises
|
||||
// the limit. The caller holds the row lock.
|
||||
MarkMailQuotaExhausted(ctx context.Context, arg MarkMailQuotaExhaustedParams) (int64, error)
|
||||
// Persist the first read time under exact recipient and organization scope.
|
||||
// Repeated calls preserve the original read timestamp.
|
||||
MarkNotificationInboxEventRead(ctx context.Context, arg MarkNotificationInboxEventReadParams) (NotificationInboxEvent, error)
|
||||
// Marks the events that the broker acknowledged. The relay passes only IDs
|
||||
// whose rows its own transaction locked, so the statement never waits and the
|
||||
// count equals the number of distinct IDs.
|
||||
@@ -835,6 +869,11 @@ type Querier interface {
|
||||
RevokeContactConsentRecords(ctx context.Context, arg RevokeContactConsentRecordsParams) ([]RevokeContactConsentRecordsRow, error)
|
||||
RevokeSession(ctx context.Context, arg RevokeSessionParams) (int64, error)
|
||||
RevokeUserSessions(ctx context.Context, arg RevokeUserSessionsParams) (int64, error)
|
||||
// Only strict grade upgrades replace the current row. The trigger enforces
|
||||
// the same monotonic rule as a final guard against adapter mistakes. The
|
||||
// grading policy is read from the immutable opening, and the guard trigger
|
||||
// compares it with the policy captured in the assigned result.
|
||||
SaveCandidateAssessmentCategory(ctx context.Context, arg SaveCandidateAssessmentCategoryParams) (int64, error)
|
||||
SaveCompanyCardViewQuotaUsage(ctx context.Context, arg SaveCompanyCardViewQuotaUsageParams) error
|
||||
// Stores the immutable domain snapshot of a successful create command. The
|
||||
// generic idempotency row and this result are committed with the organization
|
||||
|
||||
@@ -32,6 +32,10 @@ func newAssessmentHandler(
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("bootstrap.newAssessmentHandler - create pool: %w", err)
|
||||
}
|
||||
if settings.AssessmentDemoCategoriesEnabled {
|
||||
logger.Warn("synthetic demonstration categories are enabled; never on a production stand",
|
||||
slog.String("setting", "ASSESSMENT_DEMO_CATEGORIES_ENABLED"))
|
||||
}
|
||||
transactor := postgres.NewTransactor(pool)
|
||||
service, err := assessment.NewAttemptServiceWithCategorySettings(
|
||||
transactor,
|
||||
|
||||
@@ -292,40 +292,36 @@ func newRealCategoryDecision(
|
||||
}
|
||||
|
||||
func eligibleSyntheticCategoryPolicy(policy PolicyVersion, result AssessmentAttemptResultSnapshot) bool {
|
||||
product := policy.Policy()
|
||||
return policy.Kind() == PolicyKindDemo && policy.Key() == ProductPolicyKey &&
|
||||
sameAssessmentPolicy(product.Assessment, DemoProductPolicyV2().Assessment) &&
|
||||
return completeDemoBasicPolicy(policy) &&
|
||||
result.Attempt.Mode == AssessmentAttemptModeDemoBasic && result.Rationale.Rule == assessmentResultRuleBasicPassMark &&
|
||||
int32(product.Assessment.Attempt.BasicPassMark) == result.Rationale.PassMarkBasisPoints &&
|
||||
int32(policy.Policy().Assessment.Attempt.BasicPassMark) == result.Rationale.PassMarkBasisPoints &&
|
||||
(result.Outcome == AssessmentAttemptOutcomeConfirmed || result.Outcome == AssessmentAttemptOutcomeNotConfirmed)
|
||||
}
|
||||
|
||||
func sameAssessmentPolicy(left, right AssessmentPolicy) bool {
|
||||
return sameAssessmentPolicyRules(left, right) &&
|
||||
sameOptionalAssessmentAttemptPolicy(left.Attempt, right.Attempt) &&
|
||||
sameOptionalAssessmentTrainingPolicy(left.Training, right.Training)
|
||||
}
|
||||
|
||||
func sameAssessmentPolicyRules(left, right AssessmentPolicy) bool {
|
||||
return left.Calibration == right.Calibration && left.SameGradeRetryAfter == right.SameGradeRetryAfter &&
|
||||
left.MaxAttemptsPerWindow == right.MaxAttemptsPerWindow && left.AttemptWindow == right.AttemptWindow &&
|
||||
left.PromotionMinInterval == right.PromotionMinInterval && left.ConfirmationThreshold == right.ConfirmationThreshold &&
|
||||
left.HighStrengthThreshold == right.HighStrengthThreshold && left.PracticeRequired == right.PracticeRequired &&
|
||||
left.StopRule == right.StopRule
|
||||
}
|
||||
|
||||
func sameOptionalAssessmentAttemptPolicy(left, right *AssessmentAttemptPolicy) bool {
|
||||
if left == nil || right == nil {
|
||||
return left == right
|
||||
// completeDemoBasicPolicy reports whether a stored policy version is a demo
|
||||
// policy whose assessment section is complete for the demo_basic mode: explicit
|
||||
// attempt and training settings and an uncalibrated method. The stored version
|
||||
// has already passed policy validation, so its own pass mark is the threshold;
|
||||
// no fixed value is compared.
|
||||
func completeDemoBasicPolicy(policy PolicyVersion) bool {
|
||||
if policy.IsZero() || policy.Key() != ProductPolicyKey || policy.Kind() != PolicyKindDemo {
|
||||
return false
|
||||
}
|
||||
return *left == *right
|
||||
assessment := policy.Policy().Assessment
|
||||
return assessment.Calibration == AssessmentCalibrationUncalibratedInitial &&
|
||||
assessment.Attempt != nil && assessment.Attempt.RealMode == AssessmentRealModeDemoBasic &&
|
||||
assessment.Training != nil
|
||||
}
|
||||
|
||||
func sameOptionalAssessmentTrainingPolicy(left, right *AssessmentTrainingPolicy) bool {
|
||||
if left == nil || right == nil {
|
||||
return left == right
|
||||
// ValidateSyntheticCategoryPolicy reports whether a policy version is a
|
||||
// complete demonstration policy with the demo_basic mode, the only kind of
|
||||
// policy under which a synthetic demonstration category may be attested.
|
||||
func ValidateSyntheticCategoryPolicy(policy PolicyVersion) error {
|
||||
const location = "domain.ValidateSyntheticCategoryPolicy"
|
||||
if !completeDemoBasicPolicy(policy) {
|
||||
return fmt.Errorf("%s - the policy is not a complete demo_basic demonstration policy: %w", location, ErrInvalidAssessmentCategory)
|
||||
}
|
||||
return *left == *right
|
||||
return nil
|
||||
}
|
||||
|
||||
func reviewMatchesCategoryAttempt(
|
||||
|
||||
@@ -227,25 +227,41 @@ func TestDecideAssessmentCategoryIsDefaultOffEvenWithReviewedSource(t *testing.T
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyntheticCategoryPolicyRequiresTheCompleteAcceptedAssessmentPolicy(t *testing.T) {
|
||||
accepted := DemoProductPolicyV2().Assessment
|
||||
if !sameAssessmentPolicy(accepted, DemoProductPolicyV2().Assessment) {
|
||||
t.Fatal("sameAssessmentPolicy(accepted) = false, want exact accepted policy")
|
||||
func categoryTestPolicyVersion(t *testing.T, policy ProductPolicy, version int32) PolicyVersion {
|
||||
t.Helper()
|
||||
draft, err := NewPolicyVersionDraft(NewPolicyVersionDraftInput{
|
||||
Key: ProductPolicyKey, Kind: PolicyKindDemo, Author: DemoPolicySeedAuthor,
|
||||
EffectiveAt: testPolicyEffectiveAt, Policy: policy,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewPolicyVersionDraft() error = %v", err)
|
||||
}
|
||||
changed := DemoProductPolicyV2().Assessment
|
||||
changed.StopRule.SeedItems++
|
||||
if sameAssessmentPolicy(changed, accepted) {
|
||||
t.Fatal("sameAssessmentPolicy(changed stop rule) = true, want false")
|
||||
numbered, err := draft.WithVersion(version)
|
||||
if err != nil {
|
||||
t.Fatalf("WithVersion() error = %v", err)
|
||||
}
|
||||
changed = DemoProductPolicyV2().Assessment
|
||||
changed.Attempt.IdleTimeoutSeconds++
|
||||
if sameAssessmentPolicy(changed, accepted) {
|
||||
t.Fatal("sameAssessmentPolicy(changed session settings) = true, want false")
|
||||
return mustRestore(t, storedFrom(numbered))
|
||||
}
|
||||
|
||||
func TestSyntheticCategoryPolicyIsAnyCompleteDemoBasicPolicyWithItsOwnThreshold(t *testing.T) {
|
||||
if err := ValidateSyntheticCategoryPolicy(testCategoryPolicyVersion(t)); err != nil {
|
||||
t.Fatalf("ValidateSyntheticCategoryPolicy(demo v2) error = %v", err)
|
||||
}
|
||||
changed = DemoProductPolicyV2().Assessment
|
||||
changed.Training = nil
|
||||
if sameAssessmentPolicy(changed, accepted) {
|
||||
t.Fatal("sameAssessmentPolicy(missing training settings) = true, want false")
|
||||
stricter := DemoProductPolicyV2()
|
||||
stricter.Assessment.Attempt.BasicPassMark = 9000
|
||||
if err := ValidateSyntheticCategoryPolicy(categoryTestPolicyVersion(t, stricter, 3)); err != nil {
|
||||
t.Fatalf("ValidateSyntheticCategoryPolicy(pass mark 9000) error = %v, want the policy's own threshold accepted", err)
|
||||
}
|
||||
if err := ValidateSyntheticCategoryPolicy(PolicyVersion{}); !errors.Is(err, ErrInvalidAssessmentCategory) {
|
||||
t.Fatalf("ValidateSyntheticCategoryPolicy(zero) error = %v, want invalid category", err)
|
||||
}
|
||||
if err := ValidateSyntheticCategoryPolicy(categoryTestPolicyVersion(t, DemoProductPolicyV1(), 1)); !errors.Is(err, ErrInvalidAssessmentCategory) {
|
||||
t.Fatalf("ValidateSyntheticCategoryPolicy(no attempt settings) error = %v, want invalid category", err)
|
||||
}
|
||||
noTraining := DemoProductPolicyV2()
|
||||
noTraining.Assessment.Training = nil
|
||||
if err := ValidateSyntheticCategoryPolicy(categoryTestPolicyVersion(t, noTraining, 4)); !errors.Is(err, ErrInvalidAssessmentCategory) {
|
||||
t.Fatalf("ValidateSyntheticCategoryPolicy(no training settings) error = %v, want invalid category", err)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -287,7 +287,10 @@ type AssessmentAttemptRepository interface {
|
||||
|
||||
// CreateSyntheticCategoryReview stores an operator-attributed immutable
|
||||
// attestation after the domain has validated its explicit synthetic source.
|
||||
CreateSyntheticCategoryReview(ctx context.Context, review domain.AssessmentSyntheticCategoryReview) error
|
||||
// It reports false, and stores nothing, when an attestation of the same
|
||||
// opening, manifest, and policy already exists, also when a concurrent
|
||||
// transaction created it; the caller then reads the stored one.
|
||||
CreateSyntheticCategoryReview(ctx context.Context, review domain.AssessmentSyntheticCategoryReview) (bool, error)
|
||||
|
||||
// SaveCandidateAssessmentCategory writes only an assigned category upgrade.
|
||||
SaveCandidateAssessmentCategory(ctx context.Context, category domain.CandidateAssessmentCategory) error
|
||||
|
||||
@@ -21,8 +21,6 @@ type AssessmentCategoryDecisionSettings struct {
|
||||
SyntheticDemoAssignmentsEnabled bool
|
||||
}
|
||||
|
||||
// AssessmentCategoryReviewPins identify one exact reviewed source. The
|
||||
// repository must not substitute a current opening or a different manifest.
|
||||
// AssessmentCategoryDecisionRepository is bound to the finalization
|
||||
// transaction. Its category lock is acquired after the caller has obtained
|
||||
// C3, candidate/specialization scope, and the attempt row lock, in that order.
|
||||
@@ -35,6 +33,9 @@ type AssessmentCategoryDecisionRepository interface {
|
||||
candidateID uuid.UUID,
|
||||
specialization domain.SpecializationCode,
|
||||
) (domain.CandidateAssessmentCategory, bool, error)
|
||||
// GetSyntheticCategoryReview takes the pins of one exact reviewed source.
|
||||
// The repository must not substitute a current opening or a different
|
||||
// manifest.
|
||||
GetSyntheticCategoryReview(
|
||||
ctx context.Context,
|
||||
openingID uuid.UUID,
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
package assessment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
// CategoryAttestation describes one stored attestation of a synthetic
|
||||
// demonstration category. It holds no candidate data.
|
||||
type CategoryAttestation struct {
|
||||
ReviewID uuid.UUID
|
||||
OpeningID uuid.UUID
|
||||
Category domain.AssessmentCategory
|
||||
ProductPolicyVersion int32
|
||||
ReviewedBy domain.AssessmentOperator
|
||||
// Created is false when an identical attestation already existed.
|
||||
Created bool
|
||||
}
|
||||
|
||||
// CategoryAttestor lets an operator attest the exact current opening of a
|
||||
// category, its published manifest, and the product policy now in force as a
|
||||
// source for synthetic demonstration categories. The attestation row is the
|
||||
// audit record: it is immutable and keeps the operator handle and the database
|
||||
// time. It grants nothing by itself; assignment also needs the runtime gate.
|
||||
type CategoryAttestor struct {
|
||||
transactor outbound.Transactor
|
||||
}
|
||||
|
||||
func NewCategoryAttestor(transactor outbound.Transactor) (*CategoryAttestor, error) {
|
||||
if transactor == nil {
|
||||
return nil, errors.New("assessment.NewCategoryAttestor - transactor must be set")
|
||||
}
|
||||
return &CategoryAttestor{transactor: transactor}, nil
|
||||
}
|
||||
|
||||
// Attest resolves the same current selection that a new attempt would pin and
|
||||
// stores the attestation in one transaction. The policy must be the complete
|
||||
// explicit demo_basic demonstration policy. Repeating the call for the same
|
||||
// opening, manifest, and policy returns the stored attestation unchanged.
|
||||
func (attestor *CategoryAttestor) Attest(
|
||||
ctx context.Context,
|
||||
specialization domain.SpecializationCode,
|
||||
grade domain.GradeCode,
|
||||
language *domain.TaskLanguageCode,
|
||||
actor string,
|
||||
) (CategoryAttestation, error) {
|
||||
const location = "CategoryAttestor.Attest"
|
||||
operator, err := domain.ParseAssessmentOperator(actor)
|
||||
if err != nil || !specialization.IsKnown() || !grade.IsKnown() || language != nil && !language.IsKnown() {
|
||||
return CategoryAttestation{}, fmt.Errorf("%s - validate request: %w", location, domain.ErrInvalidAssessmentCategory)
|
||||
}
|
||||
reviewID, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
return CategoryAttestation{}, fmt.Errorf("%s - generate review ID: %w", location, err)
|
||||
}
|
||||
var result CategoryAttestation
|
||||
err = attestor.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
selection, err := unit.AssessmentBank().ResolveCurrentSelection(ctx, specialization, grade, language)
|
||||
if err != nil {
|
||||
return fmt.Errorf("resolve current selection: %w", err)
|
||||
}
|
||||
policy, err := unit.Policies().GetByID(ctx, selection.ProductPolicyVersionID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read product policy: %w", err)
|
||||
}
|
||||
if err := domain.ValidateSyntheticCategoryPolicy(policy); err != nil {
|
||||
return err
|
||||
}
|
||||
result, err = storeCategoryAttestation(ctx, unit, selection, policy, operator, reviewID)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return CategoryAttestation{}, fmt.Errorf("%s - transaction: %w", location, err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// storeCategoryAttestation returns the stored attestation of the exact opening,
|
||||
// manifest, and policy, or creates it.
|
||||
func storeCategoryAttestation(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
selection outbound.AssessmentBankSelection,
|
||||
policy domain.PolicyVersion,
|
||||
operator domain.AssessmentOperator,
|
||||
reviewID uuid.UUID,
|
||||
) (CategoryAttestation, error) {
|
||||
repository := unit.AssessmentAttempts()
|
||||
category := selection.Opening.Category
|
||||
stored, err := readStoredCategoryAttestation(ctx, repository, selection, policy)
|
||||
if err == nil {
|
||||
return stored, nil
|
||||
}
|
||||
if !errors.Is(err, errCategoryAttestationMissing) {
|
||||
return CategoryAttestation{}, err
|
||||
}
|
||||
at, err := unit.AssessmentBank().DatabaseTime(ctx)
|
||||
if err != nil {
|
||||
return CategoryAttestation{}, fmt.Errorf("read database time: %w", err)
|
||||
}
|
||||
review, err := domain.NewAssessmentSyntheticCategoryReview(domain.AssessmentSyntheticCategoryReviewSnapshot{
|
||||
ID: reviewID, OpeningID: selection.Opening.ID, Category: category,
|
||||
Source: domain.AssessmentCategorySourceSyntheticDemo, OpeningManifestHash: selection.ManifestSHA,
|
||||
ProductPolicyVersionID: policy.ID(), ProductPolicyVersion: policy.Version(),
|
||||
ReviewedBy: operator, ReviewedAt: at.UTC().Truncate(time.Microsecond),
|
||||
})
|
||||
if err != nil {
|
||||
return CategoryAttestation{}, fmt.Errorf("build attestation: %w", err)
|
||||
}
|
||||
created, err := repository.CreateSyntheticCategoryReview(ctx, review)
|
||||
if err != nil {
|
||||
return CategoryAttestation{}, fmt.Errorf("store attestation: %w", err)
|
||||
}
|
||||
if !created {
|
||||
// A concurrent operator stored the same exact source first.
|
||||
stored, err := readStoredCategoryAttestation(ctx, repository, selection, policy)
|
||||
if errors.Is(err, errCategoryAttestationMissing) {
|
||||
return CategoryAttestation{}, fmt.Errorf("attestation vanished after a conflict: %w", err)
|
||||
}
|
||||
return stored, err
|
||||
}
|
||||
return CategoryAttestation{
|
||||
ReviewID: reviewID, OpeningID: selection.Opening.ID, Category: category,
|
||||
ProductPolicyVersion: policy.Version(), ReviewedBy: operator, Created: true,
|
||||
}, nil
|
||||
}
|
||||
|
||||
var errCategoryAttestationMissing = errors.New("category attestation is missing")
|
||||
|
||||
// readStoredCategoryAttestation reads the attestation of the exact opening,
|
||||
// manifest, and policy, or reports errCategoryAttestationMissing.
|
||||
func readStoredCategoryAttestation(
|
||||
ctx context.Context,
|
||||
repository outbound.AssessmentAttemptRepository,
|
||||
selection outbound.AssessmentBankSelection,
|
||||
policy domain.PolicyVersion,
|
||||
) (CategoryAttestation, error) {
|
||||
category := selection.Opening.Category
|
||||
existing, found, err := repository.GetSyntheticCategoryReview(
|
||||
ctx, selection.Opening.ID, category, selection.ManifestSHA,
|
||||
policy.ID(), policy.Version(), selection.Opening.PolicyVersionID,
|
||||
)
|
||||
if err != nil {
|
||||
return CategoryAttestation{}, fmt.Errorf("read existing attestation: %w", err)
|
||||
}
|
||||
if !found {
|
||||
return CategoryAttestation{}, errCategoryAttestationMissing
|
||||
}
|
||||
snapshot := existing.Snapshot()
|
||||
return CategoryAttestation{
|
||||
ReviewID: snapshot.ID, OpeningID: snapshot.OpeningID, Category: category,
|
||||
ProductPolicyVersion: snapshot.ProductPolicyVersion, ReviewedBy: snapshot.ReviewedBy,
|
||||
}, nil
|
||||
}
|
||||
@@ -4,9 +4,9 @@ import (
|
||||
"context"
|
||||
"crypto/hmac"
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -48,12 +48,18 @@ type AssessmentResultHistoryPage struct {
|
||||
NextCursor string
|
||||
}
|
||||
|
||||
type AssessmentResultHistoryService struct {
|
||||
repository AssessmentResultHistoryRepository
|
||||
keyring Keyring
|
||||
// ResultHistoryCursorSigner signs history page positions under a key that no
|
||||
// other operation uses.
|
||||
type ResultHistoryCursorSigner interface {
|
||||
ResultHistoryCursorSignature(position, candidateID string) [outbound.IdempotencyDigestSize]byte
|
||||
}
|
||||
|
||||
func NewAssessmentResultHistoryService(repository AssessmentResultHistoryRepository, keyring Keyring) AssessmentResultHistoryService {
|
||||
type AssessmentResultHistoryService struct {
|
||||
repository AssessmentResultHistoryRepository
|
||||
keyring ResultHistoryCursorSigner
|
||||
}
|
||||
|
||||
func NewAssessmentResultHistoryService(repository AssessmentResultHistoryRepository, keyring ResultHistoryCursorSigner) AssessmentResultHistoryService {
|
||||
return AssessmentResultHistoryService{repository: repository, keyring: keyring}
|
||||
}
|
||||
|
||||
@@ -99,9 +105,40 @@ func (service AssessmentResultHistoryService) ListMine(
|
||||
return AssessmentResultHistoryPage{Entries: entries, NextCursor: nextCursor}, nil
|
||||
}
|
||||
|
||||
// ListMyResults serves the candidate's result history. The candidate account
|
||||
// check and the page read share one read-only snapshot, so a page never mixes
|
||||
// states of two moments. The page contains only the candidate's own immutable
|
||||
// root and corrective results; an employer account is refused.
|
||||
func (service *AttemptService) ListMyResults(
|
||||
ctx context.Context,
|
||||
userID uuid.UUID,
|
||||
cursor string,
|
||||
limit int32,
|
||||
) (AssessmentResultHistoryPage, error) {
|
||||
const location = "AttemptService.ListMyResults"
|
||||
var page AssessmentResultHistoryPage
|
||||
err := service.snapshotExecutor.WithinReadOnlySnapshot(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if err := requireAttemptCandidate(ctx, unit, userID, location); err != nil {
|
||||
return err
|
||||
}
|
||||
var listErr error
|
||||
signer, ok := service.keyring.(ResultHistoryCursorSigner)
|
||||
if !ok {
|
||||
return fmt.Errorf("%s - the keyring cannot sign history cursors", location)
|
||||
}
|
||||
page, listErr = NewAssessmentResultHistoryService(unit.AssessmentAttempts(), signer).
|
||||
ListMine(ctx, userID, cursor, limit)
|
||||
return listErr
|
||||
})
|
||||
if err != nil {
|
||||
return AssessmentResultHistoryPage{}, fmt.Errorf("%s - read snapshot: %w", location, err)
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func invalidAssessmentResultHistoryRequest(
|
||||
repository AssessmentResultHistoryRepository,
|
||||
keyring Keyring,
|
||||
keyring ResultHistoryCursorSigner,
|
||||
candidateID uuid.UUID,
|
||||
cursor string,
|
||||
limit int32,
|
||||
@@ -110,12 +147,12 @@ func invalidAssessmentResultHistoryRequest(
|
||||
len(cursor) > assessmentResultHistoryMaxCursorBytes
|
||||
}
|
||||
|
||||
const assessmentResultHistoryCursorOperation = "assessment.result-history.cursor.v1"
|
||||
|
||||
const assessmentResultHistoryCursorPayloadSize = 8 + 4 + 16
|
||||
|
||||
// The cursor is base64url(MAC || position). The position is the decimal
|
||||
// microsecond timestamp and the attempt ID of the last returned row, so the
|
||||
// token holds only [A-Za-z0-9_-] as the contract requires. The MAC binds the
|
||||
// position to the candidate and the listing.
|
||||
func encodeAssessmentResultHistoryCursor(
|
||||
keyring Keyring,
|
||||
keyring ResultHistoryCursorSigner,
|
||||
candidateID uuid.UUID,
|
||||
cursor outbound.AssessmentAttemptResultCursor,
|
||||
) (string, error) {
|
||||
@@ -123,18 +160,13 @@ func encodeAssessmentResultHistoryCursor(
|
||||
cursor.DecidedAt.Nanosecond()%1000 != 0 {
|
||||
return "", ErrInvalidAssessmentResultHistoryRequest
|
||||
}
|
||||
payload := make([]byte, assessmentResultHistoryCursorPayloadSize)
|
||||
binary.BigEndian.PutUint64(payload[:8], uint64(cursor.DecidedAt.Unix()))
|
||||
binary.BigEndian.PutUint32(payload[8:12], uint32(cursor.DecidedAt.Nanosecond()))
|
||||
attemptID := cursor.AttemptID.UUID()
|
||||
copy(payload[12:], attemptID[:])
|
||||
encodedPayload := base64.RawURLEncoding.EncodeToString(payload)
|
||||
mac := keyring.IdempotencyScope(assessmentResultHistoryCursorOperation, encodedPayload, candidateID.String())
|
||||
return encodedPayload + "." + base64.RawURLEncoding.EncodeToString(mac[:]), nil
|
||||
position := strconv.FormatInt(cursor.DecidedAt.UnixMicro(), 10) + ":" + cursor.AttemptID.String()
|
||||
mac := keyring.ResultHistoryCursorSignature(position, candidateID.String())
|
||||
return base64.RawURLEncoding.EncodeToString(append(mac[:], position...)), nil
|
||||
}
|
||||
|
||||
func decodeAssessmentResultHistoryCursor(
|
||||
keyring Keyring,
|
||||
keyring ResultHistoryCursorSigner,
|
||||
candidateID uuid.UUID,
|
||||
token string,
|
||||
) (*outbound.AssessmentAttemptResultCursor, error) {
|
||||
@@ -144,40 +176,26 @@ func decodeAssessmentResultHistoryCursor(
|
||||
if keyring == nil || candidateID == uuid.Nil || len(token) > assessmentResultHistoryMaxCursorBytes {
|
||||
return nil, ErrInvalidAssessmentResultHistoryRequest
|
||||
}
|
||||
encodedPayload, encodedMAC, found := strings.Cut(token, ".")
|
||||
if !found || encodedPayload == "" || encodedMAC == "" || strings.Contains(encodedMAC, ".") {
|
||||
raw, err := base64.RawURLEncoding.DecodeString(token)
|
||||
if err != nil || len(raw) <= outbound.IdempotencyDigestSize || base64.RawURLEncoding.EncodeToString(raw) != token {
|
||||
return nil, ErrInvalidAssessmentResultHistoryRequest
|
||||
}
|
||||
payload, err := base64.RawURLEncoding.DecodeString(encodedPayload)
|
||||
if err != nil || len(payload) != assessmentResultHistoryCursorPayloadSize ||
|
||||
base64.RawURLEncoding.EncodeToString(payload) != encodedPayload {
|
||||
return nil, ErrInvalidAssessmentResultHistoryRequest
|
||||
}
|
||||
suppliedMAC, err := base64.RawURLEncoding.DecodeString(encodedMAC)
|
||||
if err != nil || len(suppliedMAC) != outbound.IdempotencyDigestSize ||
|
||||
base64.RawURLEncoding.EncodeToString(suppliedMAC) != encodedMAC {
|
||||
return nil, ErrInvalidAssessmentResultHistoryRequest
|
||||
}
|
||||
expectedMAC := keyring.IdempotencyScope(assessmentResultHistoryCursorOperation, encodedPayload, candidateID.String())
|
||||
suppliedMAC, position := raw[:outbound.IdempotencyDigestSize], string(raw[outbound.IdempotencyDigestSize:])
|
||||
expectedMAC := keyring.ResultHistoryCursorSignature(position, candidateID.String())
|
||||
if !hmac.Equal(suppliedMAC, expectedMAC[:]) {
|
||||
return nil, ErrInvalidAssessmentResultHistoryRequest
|
||||
}
|
||||
seconds := int64(binary.BigEndian.Uint64(payload[:8]))
|
||||
nanos := binary.BigEndian.Uint32(payload[8:12])
|
||||
if nanos >= uint32(time.Second) || nanos%1000 != 0 {
|
||||
microseconds, attemptText, found := strings.Cut(position, ":")
|
||||
if !found {
|
||||
return nil, ErrInvalidAssessmentResultHistoryRequest
|
||||
}
|
||||
var attemptUUID uuid.UUID
|
||||
copy(attemptUUID[:], payload[12:])
|
||||
decidedMicro, err := strconv.ParseInt(microseconds, 10, 64)
|
||||
attemptUUID, uuidErr := uuid.Parse(attemptText)
|
||||
attemptID := domain.AssessmentAttemptID(attemptUUID)
|
||||
if attemptID.IsZero() {
|
||||
if err != nil || uuidErr != nil || attemptID.IsZero() {
|
||||
return nil, ErrInvalidAssessmentResultHistoryRequest
|
||||
}
|
||||
decidedAt := time.Unix(seconds, int64(nanos)).UTC()
|
||||
if decidedAt.Unix() != seconds || uint32(decidedAt.Nanosecond()) != nanos {
|
||||
return nil, ErrInvalidAssessmentResultHistoryRequest
|
||||
}
|
||||
return &outbound.AssessmentAttemptResultCursor{DecidedAt: decidedAt, AttemptID: attemptID}, nil
|
||||
return &outbound.AssessmentAttemptResultCursor{DecidedAt: time.UnixMicro(decidedMicro).UTC(), AttemptID: attemptID}, nil
|
||||
}
|
||||
|
||||
func restoreAssessmentResultHistoryPage(
|
||||
|
||||
@@ -2,7 +2,9 @@ package assessment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -10,32 +12,86 @@ import (
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
func legacyHistoryRecord(t *testing.T, ownerID uuid.UUID, result domain.AssessmentAttemptResultSnapshot) outbound.AssessmentAttemptResultRecord {
|
||||
t.Helper()
|
||||
entry, err := domain.NewLegacyAssessmentAttemptResultHistoryEntry(result)
|
||||
if err != nil {
|
||||
t.Fatalf("NewLegacyAssessmentAttemptResultHistoryEntry() error = %v", err)
|
||||
}
|
||||
return outbound.AssessmentAttemptResultRecord{UserID: ownerID, Entry: entry}
|
||||
}
|
||||
|
||||
func TestAssessmentResultHistoryReadsOwnerScopedV1WithoutInventingGrade(t *testing.T) {
|
||||
ownerID := uuid.New()
|
||||
policy := categoryServiceTestPolicy(t)
|
||||
_, result := completedCategoryServiceAttempt(t, policy, ownerID, categoryServiceTestTime)
|
||||
entry, err := domain.NewLegacyAssessmentAttemptResultHistoryEntry(result)
|
||||
if err != nil {
|
||||
t.Fatalf("NewLegacyAssessmentAttemptResultHistoryEntry() error = %v", err)
|
||||
}
|
||||
repository := &assessmentResultHistoryRepositoryFake{page: AssessmentResultHistoryRepositoryPage{
|
||||
Records: []AssessmentResultHistoryRecord{{CandidateID: ownerID, Entry: entry}}, NextCursor: "next-page-token",
|
||||
record := legacyHistoryRecord(t, ownerID, result)
|
||||
repository := &assessmentResultHistoryRepositoryFake{page: outbound.AssessmentAttemptResultPage{
|
||||
Records: []outbound.AssessmentAttemptResultRecord{record}, HasMore: true,
|
||||
}}
|
||||
service := NewAssessmentResultHistoryService(repository)
|
||||
service := NewAssessmentResultHistoryService(repository, historyCursorSigner{})
|
||||
|
||||
page, err := service.ListMine(t.Context(), ownerID, "", 0)
|
||||
if err != nil {
|
||||
t.Fatalf("ListMine(default limit) error = %v", err)
|
||||
}
|
||||
if repository.ownerID != ownerID || repository.cursor != "" || repository.limit != AssessmentResultHistoryDefaultLimit {
|
||||
t.Fatalf("repository request = owner %s cursor %q limit %d", repository.ownerID, repository.cursor, repository.limit)
|
||||
if repository.ownerID != ownerID || repository.cursor != nil || repository.limit != AssessmentResultHistoryDefaultLimit {
|
||||
t.Fatalf("repository request = owner %s cursor %v limit %d", repository.ownerID, repository.cursor, repository.limit)
|
||||
}
|
||||
if len(page.Entries) != 1 || page.NextCursor != "next-page-token" ||
|
||||
if !regexp.MustCompile(`^[A-Za-z0-9_-]{1,512}$`).MatchString(page.NextCursor) {
|
||||
t.Fatalf("next cursor %q is outside the contract alphabet [A-Za-z0-9_-]", page.NextCursor)
|
||||
}
|
||||
if len(page.Entries) != 1 || page.NextCursor == "" ||
|
||||
page.Entries[0].SchemaVersion != domain.AssessmentAttemptResultHistorySchemaV1 ||
|
||||
page.Entries[0].CategoryDecision != nil || page.Entries[0].CurrentConfirmedGrade != nil {
|
||||
t.Fatalf("history page = %+v, want one legacy result with unknown category", page)
|
||||
t.Fatalf("history page = %+v, want one legacy result with unknown category and a next cursor", page)
|
||||
}
|
||||
|
||||
// The next-page token resumes after the last returned row of the same owner.
|
||||
repository.page = outbound.AssessmentAttemptResultPage{}
|
||||
if _, err := service.ListMine(t.Context(), ownerID, page.NextCursor, 5); err != nil {
|
||||
t.Fatalf("ListMine(next cursor) error = %v", err)
|
||||
}
|
||||
last := page.Entries[0].Result
|
||||
if repository.cursor == nil || !repository.cursor.DecidedAt.Equal(last.DecidedAt) || repository.cursor.AttemptID != last.Attempt.ID || repository.limit != 5 {
|
||||
t.Fatalf("repository keyset = %+v limit %d, want the last row %s at %s", repository.cursor, repository.limit, last.Attempt.ID, last.DecidedAt)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAssessmentResultHistoryCursorIsBoundToItsOwner(t *testing.T) {
|
||||
ownerID := uuid.New()
|
||||
policy := categoryServiceTestPolicy(t)
|
||||
_, result := completedCategoryServiceAttempt(t, policy, ownerID, categoryServiceTestTime)
|
||||
repository := &assessmentResultHistoryRepositoryFake{page: outbound.AssessmentAttemptResultPage{
|
||||
Records: []outbound.AssessmentAttemptResultRecord{legacyHistoryRecord(t, ownerID, result)}, HasMore: true,
|
||||
}}
|
||||
service := NewAssessmentResultHistoryService(repository, historyCursorSigner{})
|
||||
page, err := service.ListMine(t.Context(), ownerID, "", 1)
|
||||
if err != nil {
|
||||
t.Fatalf("ListMine() error = %v", err)
|
||||
}
|
||||
repository.ownerID = uuid.Nil
|
||||
tampered := page.NextCursor[:len(page.NextCursor)-1] + "A"
|
||||
if page.NextCursor == tampered {
|
||||
tampered = page.NextCursor[:len(page.NextCursor)-1] + "B"
|
||||
}
|
||||
for name, test := range map[string]struct {
|
||||
owner uuid.UUID
|
||||
cursor string
|
||||
}{
|
||||
"foreign owner": {owner: uuid.New(), cursor: page.NextCursor},
|
||||
"tampered token": {owner: ownerID, cursor: tampered},
|
||||
"not a token": {owner: ownerID, cursor: "cursor"},
|
||||
} {
|
||||
if _, err := service.ListMine(t.Context(), test.owner, test.cursor, 1); !errors.Is(err, ErrInvalidAssessmentResultHistoryRequest) {
|
||||
t.Fatalf("ListMine(%s) error = %v, want invalid request", name, err)
|
||||
}
|
||||
}
|
||||
if repository.ownerID != uuid.Nil {
|
||||
t.Fatal("a rejected cursor reached the repository")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -43,25 +99,17 @@ func TestAssessmentResultHistoryRejectsForeignOwnerAndExpressRows(t *testing.T)
|
||||
ownerID := uuid.New()
|
||||
policy := categoryServiceTestPolicy(t)
|
||||
attempt, result := completedCategoryServiceAttempt(t, policy, ownerID, categoryServiceTestTime)
|
||||
entry, err := domain.NewLegacyAssessmentAttemptResultHistoryEntry(result)
|
||||
if err != nil {
|
||||
t.Fatalf("NewLegacyAssessmentAttemptResultHistoryEntry() error = %v", err)
|
||||
}
|
||||
service := NewAssessmentResultHistoryService(&assessmentResultHistoryRepositoryFake{
|
||||
page: AssessmentResultHistoryRepositoryPage{Records: []AssessmentResultHistoryRecord{{CandidateID: uuid.New(), Entry: entry}}},
|
||||
})
|
||||
page: outbound.AssessmentAttemptResultPage{Records: []outbound.AssessmentAttemptResultRecord{legacyHistoryRecord(t, uuid.New(), result)}},
|
||||
}, historyCursorSigner{})
|
||||
if _, err := service.ListMine(t.Context(), ownerID, "", 10); !errors.Is(err, ErrAssessmentCategoryHistoryInvalid) {
|
||||
t.Fatalf("ListMine(foreign owner) error = %v, want invalid history", err)
|
||||
}
|
||||
|
||||
express, expressResult := completedExpressCategoryServiceAttempt(t, policy, ownerID, categoryServiceTestTime)
|
||||
expressEntry, err := domain.NewLegacyAssessmentAttemptResultHistoryEntry(expressResult)
|
||||
if err != nil {
|
||||
t.Fatalf("NewLegacyAssessmentAttemptResultHistoryEntry(express) error = %v", err)
|
||||
}
|
||||
service = NewAssessmentResultHistoryService(&assessmentResultHistoryRepositoryFake{
|
||||
page: AssessmentResultHistoryRepositoryPage{Records: []AssessmentResultHistoryRecord{{CandidateID: ownerID, Entry: expressEntry}}},
|
||||
})
|
||||
page: outbound.AssessmentAttemptResultPage{Records: []outbound.AssessmentAttemptResultRecord{legacyHistoryRecord(t, ownerID, expressResult)}},
|
||||
}, historyCursorSigner{})
|
||||
if _, err := service.ListMine(t.Context(), ownerID, "", 10); !errors.Is(err, ErrAssessmentCategoryHistoryInvalid) {
|
||||
t.Fatalf("ListMine(express row) error = %v, want invalid history", err)
|
||||
}
|
||||
@@ -74,31 +122,32 @@ func TestAssessmentResultHistoryRejectsInvalidBoundsAndDuplicateResults(t *testi
|
||||
ownerID := uuid.New()
|
||||
policy := categoryServiceTestPolicy(t)
|
||||
_, result := completedCategoryServiceAttempt(t, policy, ownerID, categoryServiceTestTime)
|
||||
entry, err := domain.NewLegacyAssessmentAttemptResultHistoryEntry(result)
|
||||
if err != nil {
|
||||
t.Fatalf("NewLegacyAssessmentAttemptResultHistoryEntry() error = %v", err)
|
||||
}
|
||||
repository := &assessmentResultHistoryRepositoryFake{page: AssessmentResultHistoryRepositoryPage{
|
||||
Records: []AssessmentResultHistoryRecord{{CandidateID: ownerID, Entry: entry}},
|
||||
record := legacyHistoryRecord(t, ownerID, result)
|
||||
repository := &assessmentResultHistoryRepositoryFake{page: outbound.AssessmentAttemptResultPage{
|
||||
Records: []outbound.AssessmentAttemptResultRecord{record},
|
||||
}}
|
||||
service := NewAssessmentResultHistoryService(repository)
|
||||
service := NewAssessmentResultHistoryService(repository, historyCursorSigner{})
|
||||
if _, err := service.ListMine(t.Context(), ownerID, strings.Repeat("x", assessmentResultHistoryMaxCursorBytes+1), 1); !errors.Is(err, ErrInvalidAssessmentResultHistoryRequest) {
|
||||
t.Fatalf("ListMine(oversized cursor) error = %v, want invalid request", err)
|
||||
}
|
||||
if _, err := service.ListMine(t.Context(), ownerID, "", AssessmentResultHistoryMaxLimit+1); !errors.Is(err, ErrInvalidAssessmentResultHistoryRequest) {
|
||||
t.Fatalf("ListMine(oversized limit) error = %v, want invalid request", err)
|
||||
}
|
||||
repository.page.NextCursor = strings.Repeat("x", assessmentResultHistoryMaxCursorBytes+1)
|
||||
if _, err := service.ListMine(t.Context(), ownerID, "", 1); !errors.Is(err, ErrAssessmentCategoryHistoryInvalid) {
|
||||
t.Fatalf("ListMine(oversized next cursor) error = %v, want invalid history", err)
|
||||
if _, err := service.ListMine(t.Context(), uuid.Nil, "", 1); !errors.Is(err, ErrInvalidAssessmentResultHistoryRequest) {
|
||||
t.Fatalf("ListMine(nil owner) error = %v, want invalid request", err)
|
||||
}
|
||||
repository.page.NextCursor = ""
|
||||
|
||||
repository.page.Records = append(repository.page.Records,
|
||||
AssessmentResultHistoryRecord{CandidateID: ownerID, Entry: entry})
|
||||
repository.page.Records = append(repository.page.Records, record)
|
||||
if _, err := service.ListMine(t.Context(), ownerID, "", 1); !errors.Is(err, ErrAssessmentCategoryHistoryInvalid) {
|
||||
t.Fatalf("ListMine(more rows than the limit) error = %v, want invalid history", err)
|
||||
}
|
||||
if _, err := service.ListMine(t.Context(), ownerID, "", 2); !errors.Is(err, ErrAssessmentCategoryHistoryInvalid) {
|
||||
t.Fatalf("ListMine(duplicate result) error = %v, want invalid history", err)
|
||||
}
|
||||
repository.page = outbound.AssessmentAttemptResultPage{HasMore: true}
|
||||
if _, err := service.ListMine(t.Context(), ownerID, "", 1); !errors.Is(err, ErrAssessmentCategoryHistoryInvalid) {
|
||||
t.Fatalf("ListMine(HasMore without rows) error = %v, want invalid history", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAssessmentResultHistoryOrdersTiedDecisionsByAttemptIDDescending(t *testing.T) {
|
||||
@@ -107,27 +156,20 @@ func TestAssessmentResultHistoryOrdersTiedDecisionsByAttemptIDDescending(t *test
|
||||
_, result := completedCategoryServiceAttempt(t, policy, ownerID, categoryServiceTestTime)
|
||||
decidedAt := time.Date(2026, time.September, 1, 11, 0, 0, 0, time.UTC)
|
||||
|
||||
entryForID := func(id string) domain.AssessmentAttemptResultHistoryEntry {
|
||||
recordForID := func(id string) outbound.AssessmentAttemptResultRecord {
|
||||
t.Helper()
|
||||
resultCopy := result
|
||||
resultCopy.Attempt.ID = domain.AssessmentAttemptID(uuid.MustParse(id))
|
||||
resultCopy.DecidedAt = decidedAt
|
||||
resultCopy.Attempt.FinishedAt = &decidedAt
|
||||
entry, err := domain.NewLegacyAssessmentAttemptResultHistoryEntry(resultCopy)
|
||||
if err != nil {
|
||||
t.Fatalf("NewLegacyAssessmentAttemptResultHistoryEntry(%s) error = %v", id, err)
|
||||
}
|
||||
return entry
|
||||
return legacyHistoryRecord(t, ownerID, resultCopy)
|
||||
}
|
||||
|
||||
higherID := entryForID("ffffffff-ffff-4fff-bfff-ffffffffffff")
|
||||
lowerID := entryForID("00000000-0000-4000-8000-000000000001")
|
||||
higherID := recordForID("ffffffff-ffff-4fff-bfff-ffffffffffff")
|
||||
lowerID := recordForID("00000000-0000-4000-8000-000000000001")
|
||||
service := NewAssessmentResultHistoryService(&assessmentResultHistoryRepositoryFake{
|
||||
page: AssessmentResultHistoryRepositoryPage{Records: []AssessmentResultHistoryRecord{
|
||||
{CandidateID: ownerID, Entry: higherID},
|
||||
{CandidateID: ownerID, Entry: lowerID},
|
||||
}},
|
||||
})
|
||||
page: outbound.AssessmentAttemptResultPage{Records: []outbound.AssessmentAttemptResultRecord{higherID, lowerID}},
|
||||
}, historyCursorSigner{})
|
||||
page, err := service.ListMine(t.Context(), ownerID, "", 2)
|
||||
if err != nil {
|
||||
t.Fatalf("ListMine(descending tie order) error = %v", err)
|
||||
@@ -139,20 +181,17 @@ func TestAssessmentResultHistoryOrdersTiedDecisionsByAttemptIDDescending(t *test
|
||||
}
|
||||
|
||||
service = NewAssessmentResultHistoryService(&assessmentResultHistoryRepositoryFake{
|
||||
page: AssessmentResultHistoryRepositoryPage{Records: []AssessmentResultHistoryRecord{
|
||||
{CandidateID: ownerID, Entry: lowerID},
|
||||
{CandidateID: ownerID, Entry: higherID},
|
||||
}},
|
||||
})
|
||||
page: outbound.AssessmentAttemptResultPage{Records: []outbound.AssessmentAttemptResultRecord{lowerID, higherID}},
|
||||
}, historyCursorSigner{})
|
||||
if _, err := service.ListMine(t.Context(), ownerID, "", 2); !errors.Is(err, ErrAssessmentCategoryHistoryInvalid) {
|
||||
t.Fatalf("ListMine(ascending tie order) error = %v, want invalid history", err)
|
||||
}
|
||||
}
|
||||
|
||||
type assessmentResultHistoryRepositoryFake struct {
|
||||
page AssessmentResultHistoryRepositoryPage
|
||||
page outbound.AssessmentAttemptResultPage
|
||||
ownerID uuid.UUID
|
||||
cursor string
|
||||
cursor *outbound.AssessmentAttemptResultCursor
|
||||
limit int32
|
||||
readErr error
|
||||
}
|
||||
@@ -160,9 +199,15 @@ type assessmentResultHistoryRepositoryFake struct {
|
||||
func (repository *assessmentResultHistoryRepositoryFake) ListCandidateAssessmentResults(
|
||||
_ context.Context,
|
||||
ownerID uuid.UUID,
|
||||
cursor string,
|
||||
cursor *outbound.AssessmentAttemptResultCursor,
|
||||
limit int32,
|
||||
) (AssessmentResultHistoryRepositoryPage, error) {
|
||||
) (outbound.AssessmentAttemptResultPage, error) {
|
||||
repository.ownerID, repository.cursor, repository.limit = ownerID, cursor, limit
|
||||
return repository.page, repository.readErr
|
||||
}
|
||||
|
||||
type historyCursorSigner struct{}
|
||||
|
||||
func (historyCursorSigner) ResultHistoryCursorSignature(position, candidateID string) [32]byte {
|
||||
return sha256.Sum256([]byte("cursor\x00" + position + "\x00" + candidateID))
|
||||
}
|
||||
@@ -60,7 +60,8 @@ func TestAssessmentCategoryDecisionServiceAssignsOnlyTheExactReviewedPolicySourc
|
||||
repository.reviewPins.OpeningID != result.Pins.OpeningID ||
|
||||
repository.reviewPins.OpeningManifestHash != result.Pins.OpeningManifestHash ||
|
||||
repository.reviewPins.ProductPolicyVersionID != result.Pins.ProductPolicyVersionID ||
|
||||
repository.reviewPins.ProductPolicyVersion != result.Pins.ProductPolicyVersion {
|
||||
repository.reviewPins.ProductPolicyVersion != result.Pins.ProductPolicyVersion ||
|
||||
repository.reviewPins.GradingPolicyVersionID != result.Pins.GradingPolicyVersionID {
|
||||
t.Fatalf("review query pins = %+v, want exact finalized source pins", repository.reviewPins)
|
||||
}
|
||||
}
|
||||
@@ -89,7 +90,18 @@ type categoryDecisionRepositoryFake struct {
|
||||
calls []string
|
||||
current *domain.CandidateAssessmentCategory
|
||||
review *domain.AssessmentSyntheticCategoryReview
|
||||
reviewPins AssessmentCategoryReviewPins
|
||||
reviewPins categoryReviewQuery
|
||||
}
|
||||
|
||||
// categoryReviewQuery records the pins that the service passes to the
|
||||
// repository when it looks for a reviewed source.
|
||||
type categoryReviewQuery struct {
|
||||
OpeningID uuid.UUID
|
||||
Category domain.AssessmentCategory
|
||||
OpeningManifestHash [32]byte
|
||||
ProductPolicyVersionID domain.PolicyVersionID
|
||||
ProductPolicyVersion int32
|
||||
GradingPolicyVersionID domain.PolicyVersionID
|
||||
}
|
||||
|
||||
func (repository *categoryDecisionRepositoryFake) LockCandidateCategory(
|
||||
@@ -115,8 +127,18 @@ func (repository *categoryDecisionRepositoryFake) GetCandidateCategory(
|
||||
|
||||
func (repository *categoryDecisionRepositoryFake) GetSyntheticCategoryReview(
|
||||
_ context.Context,
|
||||
pins AssessmentCategoryReviewPins,
|
||||
openingID uuid.UUID,
|
||||
category domain.AssessmentCategory,
|
||||
openingManifestHash [32]byte,
|
||||
productPolicyID domain.PolicyVersionID,
|
||||
productPolicyVersion int32,
|
||||
gradingPolicyID domain.PolicyVersionID,
|
||||
) (domain.AssessmentSyntheticCategoryReview, bool, error) {
|
||||
pins := categoryReviewQuery{
|
||||
OpeningID: openingID, Category: category, OpeningManifestHash: openingManifestHash,
|
||||
ProductPolicyVersionID: productPolicyID, ProductPolicyVersion: productPolicyVersion,
|
||||
GradingPolicyVersionID: gradingPolicyID,
|
||||
}
|
||||
repository.calls = append(repository.calls, "review")
|
||||
repository.reviewPins = pins
|
||||
if repository.review == nil {
|
||||
|
||||
@@ -170,13 +170,21 @@ func lockAttemptForFinalize(
|
||||
}
|
||||
return domain.AssessmentAttempt{}, fmt.Errorf("%s - lock owner-scoped attempt: %w", location, err)
|
||||
}
|
||||
if current.Kind() != kind || current.Snapshot().Specialization == nil && selectedSnapshot.Specialization != nil ||
|
||||
current.Snapshot().Specialization != nil && (selectedSnapshot.Specialization == nil || *current.Snapshot().Specialization != *selectedSnapshot.Specialization) {
|
||||
if current.Kind() != kind || !sameAttemptSpecialization(current.Snapshot().Specialization, selectedSnapshot.Specialization) {
|
||||
return domain.AssessmentAttempt{}, fmt.Errorf("%s - immutable attempt scope changed: %w", location, domain.ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
return current, nil
|
||||
}
|
||||
|
||||
// sameAttemptSpecialization compares the optional specializations of two reads
|
||||
// of one attempt; training attempts have none.
|
||||
func sameAttemptSpecialization(left, right *domain.SpecializationCode) bool {
|
||||
if left == nil || right == nil {
|
||||
return left == right
|
||||
}
|
||||
return *left == *right
|
||||
}
|
||||
|
||||
func storeCompletedFinalize(
|
||||
ctx context.Context,
|
||||
repository outbound.AssessmentAttemptRepository,
|
||||
@@ -394,9 +402,7 @@ func readCompletedAttemptResult(
|
||||
if err != nil {
|
||||
return AssessmentAttemptResult{}, fmt.Errorf("%s - restore stored category result: %w", location, err)
|
||||
}
|
||||
result := assessmentAttemptResultFromSnapshot(entry.Result)
|
||||
result.CategoryDecision = entry.CategoryDecision
|
||||
return result, nil
|
||||
return AssessmentAttemptResultFromHistoryEntry(entry), nil
|
||||
}
|
||||
|
||||
func terminalAttemptResult(attempt domain.AssessmentAttempt) (AssessmentAttemptResult, error) {
|
||||
@@ -448,3 +454,15 @@ func assessmentAttemptResultFromSnapshot(
|
||||
Summary: snapshot.Summary, DecidedAt: snapshot.DecidedAt,
|
||||
}
|
||||
}
|
||||
|
||||
// AssessmentAttemptResultFromHistoryEntry is the candidate-visible form of one
|
||||
// stored result, with the category decision captured when it was stored. A
|
||||
// legacy v1 entry has no decision.
|
||||
func AssessmentAttemptResultFromHistoryEntry(entry domain.AssessmentAttemptResultHistoryEntry) AssessmentAttemptResult {
|
||||
result := assessmentAttemptResultFromSnapshot(entry.Result)
|
||||
if entry.CategoryDecision != nil {
|
||||
decision := *entry.CategoryDecision
|
||||
result.CategoryDecision = &decision
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -31,6 +31,7 @@ const (
|
||||
labelAnswerFingerprint = "lincodex/assessment/answer-fingerprint/v1"
|
||||
labelSignalSession = "lincodex/assessment/signal-session/v1"
|
||||
labelSignalNetwork = "lincodex/assessment/signal-network/v1"
|
||||
labelResultCursor = "lincodex/assessment/result-history-cursor/v1"
|
||||
)
|
||||
|
||||
// Keyring computes the keyed digests of the anonymous identity operations:
|
||||
@@ -49,6 +50,7 @@ type Keyring struct {
|
||||
answerKey []byte
|
||||
signalSessionKey []byte
|
||||
signalNetworkKey []byte
|
||||
resultCursorKey []byte
|
||||
}
|
||||
|
||||
// NewKeyring derives the purpose keys from secret.
|
||||
@@ -67,6 +69,7 @@ func NewKeyring(secret []byte) (*Keyring, error) {
|
||||
answerKey: derive(secret, labelAnswerFingerprint),
|
||||
signalSessionKey: derive(secret, labelSignalSession),
|
||||
signalNetworkKey: derive(secret, labelSignalNetwork),
|
||||
resultCursorKey: derive(secret, labelResultCursor),
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -103,6 +106,17 @@ func (keyring *Keyring) IdempotencyScope(operation, key, normalizedEmail string)
|
||||
return [outbound.IdempotencyDigestSize]byte(mac.Sum(nil))
|
||||
}
|
||||
|
||||
// ResultHistoryCursorSignature signs the position of a result history page for
|
||||
// one candidate under a key of its own, so a cursor can never be replayed as an
|
||||
// idempotency scope or the other way round.
|
||||
func (keyring *Keyring) ResultHistoryCursorSignature(position, candidateID string) [outbound.IdempotencyDigestSize]byte {
|
||||
mac := hmac.New(sha256.New, keyring.resultCursorKey)
|
||||
mac.Write([]byte(position))
|
||||
mac.Write([]byte{0})
|
||||
mac.Write([]byte(candidateID))
|
||||
return [outbound.IdempotencyDigestSize]byte(mac.Sum(nil))
|
||||
}
|
||||
|
||||
// Fingerprint identifies a request by its canonical body.
|
||||
func (keyring *Keyring) Fingerprint(canonicalBody []byte) [outbound.IdempotencyDigestSize]byte {
|
||||
mac := hmac.New(sha256.New, keyring.fingerprintKey)
|
||||
|
||||
@@ -3,6 +3,7 @@ package identity
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
@@ -123,3 +124,22 @@ func TestAssessmentSessionAndNetworkDigestsAreBoundToTheAttempt(t *testing.T) {
|
||||
t.Fatal("session and network digests share a key")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResultHistoryCursorKeyIsSeparateFromIdempotencyAndBoundToTheCandidate(t *testing.T) {
|
||||
keyring, err := NewKeyring([]byte(strings.Repeat("k", MinKeySecretBytes)))
|
||||
if err != nil {
|
||||
t.Fatalf("NewKeyring() error = %v", err)
|
||||
}
|
||||
signature := keyring.ResultHistoryCursorSignature("position", "candidate-a")
|
||||
if signature != keyring.ResultHistoryCursorSignature("position", "candidate-a") {
|
||||
t.Fatal("the cursor signature is not deterministic")
|
||||
}
|
||||
if signature == keyring.ResultHistoryCursorSignature("position", "candidate-b") ||
|
||||
signature == keyring.ResultHistoryCursorSignature("other", "candidate-a") {
|
||||
t.Fatal("the cursor signature does not depend on the position and the candidate")
|
||||
}
|
||||
if signature == keyring.IdempotencyScope("position", "", "candidate-a") ||
|
||||
signature == keyring.IdempotencyScope("assessment.result-history.cursor.v1", "position", "candidate-a") {
|
||||
t.Fatal("the cursor signature shares a key with the idempotency scope")
|
||||
}
|
||||
}
|
||||
@@ -57,7 +57,8 @@ func validInboxText(value string, maxRunes int, allowNewlines bool) bool {
|
||||
return false
|
||||
}
|
||||
for _, character := range value {
|
||||
if character == 0 || (character < 0x20 && !(allowNewlines && (character == '\n' || character == '\t'))) || character == 0x7f {
|
||||
allowedControl := allowNewlines && (character == '\n' || character == '\t')
|
||||
if character == 0 || (character < 0x20 && !allowedControl) || character == 0x7f {
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -173,11 +174,12 @@ func (service *InboxService) List(ctx context.Context, request InboxListRequest)
|
||||
}
|
||||
item := InboxItem{Entry: entry}
|
||||
content, resolveErr := service.resolver.Resolve(ctx, entry)
|
||||
if errors.Is(resolveErr, ErrInboxContentUnavailable) {
|
||||
switch {
|
||||
case errors.Is(resolveErr, ErrInboxContentUnavailable):
|
||||
item.ContentUnavailable = true
|
||||
} else if resolveErr != nil {
|
||||
case resolveErr != nil:
|
||||
return InboxPage{}, fmt.Errorf("%s - resolve current event content: %w", location, resolveErr)
|
||||
} else {
|
||||
default:
|
||||
item.Content = &content
|
||||
}
|
||||
page.Items = append(page.Items, item)
|
||||
|
||||
@@ -327,6 +327,24 @@ make -C backend assessment-review ARGS='inspect --attempt <uuid> --actor operato
|
||||
- To use thresholds other than the demo values, publish a policy version with an `assessment.signals` section through the policy publisher. `DemoProductPolicyV3` is the demo example and is published only explicitly (the isolated browser fixture does so); the startup seed publishes version 1 only. Attempts that already started keep the version they started with. The demo duplicate thresholds assume a population: a copied pair is flagged only from about 26 answers per family (attention) and 61 (review) at 13 items, or 9 and 14 at 23 items. To try the feature on a smaller stand, publish a policy version with lower `duplicate_bits_attention` and `duplicate_bits_review` (the integration tests use 4 and 6); do not edit the demo policy. A review is a point-in-time evaluation, run again by the job at the deadline. The job logs one line per run with the number of reviews and its duration (`assessment review job finished`).
|
||||
- The rows hold counts, durations, and keyed digests (HMAC-SHA-256 under keys derived from `IDENTITY_KEY_SECRET`, each with a key version) and no answer text. Rotating the secret keeps the stored rows but makes new fingerprints incomparable with old ones. Deleting an account deletes its attempts and, by cascade, their facts and reviews; the audit rows keep only the attempt ID and the handle. The digests are kept for the lifetime of the attempt; no retention period is defined yet.
|
||||
|
||||
## Demonstration categories on a stand
|
||||
|
||||
A category from a `demo_basic` result is assigned only on an isolated synthetic stand. It is not calibrated and must not appear in an environment with real candidates. Two independent steps enable it on a stand:
|
||||
|
||||
1. Set `ASSESSMENT_DEMO_CATEGORIES_ENABLED=true` in the backend environment (default `false`; Compose passes the value) and restart the backend. At startup the backend logs the warning `synthetic demonstration categories are enabled; never on a production stand`; the attestation command prints the same warning before it works.
|
||||
2. Attest each opened category as an operator:
|
||||
|
||||
```sh
|
||||
make -C backend assessment-category-attest ARGS='attest --specialization backend --grade intern --task-language go --actor operator:<handle>'
|
||||
```
|
||||
|
||||
- The command takes the same current selection that a new attempt will pin: the exact category opening, its published catalog manifest, and the product policy version in force. That version must be a complete demonstration policy (kind `demo`, an uncalibrated method, explicit attempt settings with `real_mode = demo_basic`, and training settings); otherwise the command refuses. The pass mark `basic_pass_mark_bp` is the policy version's own; neither the command nor the database requires a fixed value. Pass `--task-language` when the selection holds several languages.
|
||||
- The command needs only `DATABASE_URL`; it reads no other environment variable and no dotenv file, validates its arguments before connecting, and stores the attestation in one transaction. A repeat for the same opening, manifest, and policy version changes nothing and prints `already attested`. The output holds identifiers, the policy version, and the handle, and no candidate data.
|
||||
- An attestation pins the opening, the manifest, and the policy version. After a new policy version or a new opening of the category, attempts are not created until the category is opened again, and a new opening with a new policy version needs a new attestation.
|
||||
- A row in `assessment_synthetic_category_reviews` is the audit record: it holds the `operator:<handle>` handle, the database time, and the pinned versions. The table refuses UPDATE and DELETE. The handle is an audit label, not authentication: local database access is the operator boundary.
|
||||
- The attestation trigger accepts a policy of kind `demo` with `real_mode = demo_basic`. When a category is assigned, the database compares the threshold of the result with `basic_pass_mark_bp` of the policy version pinned to the attempt, so a 9000 threshold in an accepted policy works like 8000. A result decided before the attestation gets no category; only a result decided after it can assign one.
|
||||
- Without either step a result that reached the threshold is stored as `not_eligible`: the candidate sees the score and no category. `demo_express` never creates a category under any setting. `make -C backend assessment-category-attest-build` builds `backend/bin/assessment-category-attest`.
|
||||
|
||||
## Separate ML Compose project
|
||||
|
||||
ML uses a separate Compose file and project; it does not require or start Redis or SeaweedFS in the current scaffold. Its default host bind is 127.0.0.1:8000. Set ML_BIND_ADDRESS only after choosing a private address and preparing firewall rules. Prometheus does not scrape remote ML while ML_METRICS_TARGET is empty.
|
||||
|
||||
@@ -329,6 +329,24 @@ make -C backend assessment-review ARGS='inspect --attempt <uuid> --actor operato
|
||||
- Чтобы использовать пороги, отличные от демо, опубликуйте версию политики с разделом `assessment.signals` через публикатор политик. `DemoProductPolicyV3` - демо-пример, он публикуется только явно (так делает изолированная браузерная фикстура); стартовый seed публикует только версию 1. Попытки, которые уже начались, сохраняют версию, с которой начались. Демо-пороги дубликатов рассчитаны на совокупность: скопированная пара помечается лишь примерно от 26 ответов на семейство («внимание») и 61 («проверить») при 13 заданиях или от 9 и 14 при 23. Чтобы попробовать функцию на меньшем стенде, опубликуйте версию политики с меньшими `duplicate_bits_attention` и `duplicate_bits_review` (интеграционные тесты используют 4 и 6); демо-политику не редактируйте. Проверка - оценка на момент, задание на дедлайне запускает ее снова. Задание пишет в журнал одну строку на запуск с числом проверок и длительностью (`assessment review job finished`).
|
||||
- Строки хранят числа, длительности и ключевые дайджесты (HMAC-SHA-256 под ключами, выведенными из `IDENTITY_KEY_SECRET`, у каждого есть версия ключа) и не хранят текст ответа. Смена секрета сохраняет строки, но делает новые отпечатки несравнимыми со старыми. Удаление аккаунта удаляет его попытки и каскадом их факты и проверки; строки аудита хранят только идентификатор попытки и имя. Дайджесты хранятся столько же, сколько попытка; срок хранения пока не определен.
|
||||
|
||||
## Демонстрационные категории на стенде
|
||||
|
||||
Категория по результату `demo_basic` присваивается только на изолированном синтетическом стенде. Она не калибрована и не должна появляться в рабочей среде с реальными кандидатами. Чтобы включить ее на стенде, нужны два независимых шага:
|
||||
|
||||
1. Выставить `ASSESSMENT_DEMO_CATEGORIES_ENABLED=true` в окружении backend (по умолчанию `false`; Compose пробрасывает значение) и перезапустить backend. При старте backend пишет предупреждение `synthetic demonstration categories are enabled; never on a production stand`; команда аттестации печатает такое же предупреждение перед работой.
|
||||
2. Для каждой открытой категории выполнить аттестацию оператора:
|
||||
|
||||
```sh
|
||||
make -C backend assessment-category-attest ARGS='attest --specialization backend --grade intern --task-language go --actor operator:<handle>'
|
||||
```
|
||||
|
||||
- Команда берет ту же текущую выборку, которую закрепит новая попытка: точное открытие категории, опубликованный манифест каталога и действующую версию политики. Версия политики должна быть полной демонстрационной политикой (вид `demo`, неоткалиброванный метод, явные настройки попытки с `real_mode = demo_basic` и учебного запуска); иначе команда отказывает. Порог `basic_pass_mark_bp` задает сама версия политики, никакого фиксированного значения команда и база не требуют. `--task-language` указывается, если выборка содержит несколько языков.
|
||||
- Команде нужен только `DATABASE_URL`; она не читает другие переменные окружения и dotenv-файл, проверяет аргументы до подключения и в одной транзакции записывает аттестацию. Повтор для того же открытия, манифеста и версии политики ничего не меняет и выводит `already attested`. В выводе только идентификаторы, версия политики и handle, без данных кандидатов.
|
||||
- Аттестация закрепляет открытие, манифест и версию политики. После публикации новой версии политики или нового открытия категории попытки не создаются, пока категория не открыта заново, а для нового открытия и новой версии политики нужна новая аттестация.
|
||||
- Запись в `assessment_synthetic_category_reviews` служит журналом: в ней handle `operator:<handle>`, время БД и закрепленные версии. Таблица запрещает UPDATE и DELETE. Handle - метка для аудита, а не аутентификация: границей оператора служит локальный доступ к базе.
|
||||
- Триггер аттестации принимает политику вида `demo` с `real_mode = demo_basic`. При присвоении категории база сверяет порог результата с `basic_pass_mark_bp` версии политики, закрепленной за попыткой, поэтому порог 9000 в принятой политике работает так же, как 8000. Попытки, по которым решение принято до аттестации, категории не получают; категорию присваивает только результат, принятый после нее.
|
||||
- Без любого из шагов результат с пройденным порогом сохраняется как `not_eligible`: кандидат видит оценку, категории нет. `demo_express` категорию не создает ни при каких настройках. `make -C backend assessment-category-attest-build` собирает `backend/bin/assessment-category-attest`.
|
||||
|
||||
## Отдельный ML Compose
|
||||
|
||||
ML имеет отдельный Compose-файл и проект; Redis и SeaweedFS ему пока не требуются и здесь не запускаются. По умолчанию он слушает на 127.0.0.1:8000. Настройте ML_BIND_ADDRESS только если выбранный приватный адрес и firewall уже подготовлены. Метрики удаленного ML target не собираются, пока ML_METRICS_TARGET пуст.
|
||||
|
||||
@@ -106,6 +106,12 @@ function project(inputTarget: string, endpoints: string, schemas: string): Optio
|
||||
zod: {
|
||||
exactOptional: true,
|
||||
},
|
||||
// The same strictness applies to the MSW mocks: an optional property
|
||||
// is either absent or valid, never present with the value undefined,
|
||||
// which the exact optional property types reject.
|
||||
mock: {
|
||||
exactOptional: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
@@ -31,15 +31,90 @@ function result(patch: Record<string, unknown>): AssessmentResult {
|
||||
}
|
||||
|
||||
describe("assessmentResultSummary", () => {
|
||||
it("restates a confirmed grade without deriving one", () => {
|
||||
const decision = (status: string, patch: Record<string, unknown> = {}) => ({
|
||||
status,
|
||||
previous_confirmed_grade: null,
|
||||
current_confirmed_grade: null,
|
||||
method: "demo_basic_pass_mark",
|
||||
source: "synthetic_demo",
|
||||
calibration_status: "uncalibrated",
|
||||
...patch,
|
||||
});
|
||||
|
||||
it("restates an assigned grade without deriving one", () => {
|
||||
const summary = assessmentResultSummary(
|
||||
result({ outcome: "confirmed", confirmed_grade: "middle" }),
|
||||
result({
|
||||
outcome: "confirmed",
|
||||
confirmed_grade: "middle",
|
||||
category_decision: decision("assigned", { current_confirmed_grade: "middle" }),
|
||||
}),
|
||||
);
|
||||
expect(summary.text).toBe("Уровень подтвержден: Backend, Middle.");
|
||||
expect(summary.reason).toBeNull();
|
||||
expect(summary.reason).toBe(
|
||||
"Это демонстрационная категория: пороги не калибровались, банк заданий демонстрационный.",
|
||||
);
|
||||
expect(summary.isDemonstration).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps the higher grade when a reviewed result does not change the category", () => {
|
||||
const summary = assessmentResultSummary(
|
||||
result({
|
||||
outcome: "confirmed",
|
||||
confirmed_grade: "middle",
|
||||
previous_confirmed_grade: "senior",
|
||||
category_decision: decision("unchanged", {
|
||||
previous_confirmed_grade: "senior",
|
||||
current_confirmed_grade: "senior",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(summary.text).toBe("Уровень подтвержден: Backend, Middle.");
|
||||
expect(summary.reason).toBe(
|
||||
"Прежний подтвержденный уровень Senior сохраняется. Это демонстрационная категория: пороги не калибровались, банк заданий демонстрационный.",
|
||||
);
|
||||
});
|
||||
|
||||
it("adds no demonstration note when neither calibration nor the bank says so", () => {
|
||||
const summary = assessmentResultSummary(
|
||||
result({
|
||||
outcome: "confirmed",
|
||||
confirmed_grade: "middle",
|
||||
calibration_status: "calibrated",
|
||||
limitations: [],
|
||||
category_decision: decision("assigned", {
|
||||
current_confirmed_grade: "middle",
|
||||
calibration_status: "calibrated",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(summary.reason).toBeNull();
|
||||
});
|
||||
|
||||
it("says that the threshold was reached but no category was assigned", () => {
|
||||
const summary = assessmentResultSummary(
|
||||
result({
|
||||
outcome: "confirmed",
|
||||
confirmed_grade: null,
|
||||
category_decision: decision("not_eligible", {
|
||||
method: null,
|
||||
source: null,
|
||||
calibration_status: null,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(summary.text).toBe("Порог пройден, категория не присвоена: Backend, Middle.");
|
||||
expect(summary.text).not.toContain("Уровень подтвержден");
|
||||
expect(summary.reason).toContain("отключены");
|
||||
});
|
||||
|
||||
it("does not claim a grade for a result stored before category decisions", () => {
|
||||
const summary = assessmentResultSummary(
|
||||
result({ outcome: "confirmed", confirmed_grade: null }),
|
||||
);
|
||||
expect(summary.text).toBe("Порог пройден, категория не присвоена: Backend, Middle.");
|
||||
expect(summary.reason).toContain("без решения о категории");
|
||||
});
|
||||
|
||||
it("keeps the previous grade when nothing was confirmed", () => {
|
||||
const summary = assessmentResultSummary(
|
||||
result({ outcome: "not_confirmed", previous_confirmed_grade: "junior" }),
|
||||
|
||||
@@ -21,6 +21,14 @@ const notDeterminedReasons: Readonly<Record<NotDeterminedReason, string>> = {
|
||||
sandbox_unavailable: "Проверка практического решения была недоступна по технической причине.",
|
||||
};
|
||||
|
||||
/** Plain words for a passed threshold without an assigned category. */
|
||||
function noCategoryReason(status: string | undefined): string {
|
||||
if (status === "not_eligible") {
|
||||
return "Демонстрационные категории на этом стенде отключены или для этой проверки нет подтверждения оператора, поэтому уровень не присваивается.";
|
||||
}
|
||||
return "Результат сохранен без решения о категории, поэтому уровень не присваивается.";
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the text shown for a finished attempt. It only restates fields of
|
||||
* the server result and never derives a grade on its own.
|
||||
@@ -42,10 +50,35 @@ export function assessmentResultSummary(result: AssessmentResult): AssessmentRes
|
||||
|
||||
switch (result.outcome) {
|
||||
case "confirmed": {
|
||||
const grade = result.confirmed_grade ?? result.target_grade;
|
||||
const decisionStatus = result.category_decision?.status;
|
||||
if (
|
||||
result.confirmed_grade === null ||
|
||||
decisionStatus === "not_eligible" ||
|
||||
decisionStatus === undefined
|
||||
) {
|
||||
// The score reached the threshold, but the server assigned no category:
|
||||
// never present a grade that the server did not confirm.
|
||||
return {
|
||||
text: `Порог пройден, категория не присвоена: ${specialization}, ${gradeLabels[result.target_grade]}.`,
|
||||
reason: noCategoryReason(decisionStatus),
|
||||
isDemonstration,
|
||||
};
|
||||
}
|
||||
const demonstrational =
|
||||
result.category_decision?.calibration_status === "uncalibrated" ||
|
||||
result.calibration_status === "uncalibrated" ||
|
||||
result.limitations.includes("demo_bank");
|
||||
const reason = [
|
||||
decisionStatus === "unchanged" ? keptGrade : null,
|
||||
demonstrational
|
||||
? "Это демонстрационная категория: пороги не калибровались, банк заданий демонстрационный."
|
||||
: null,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" ");
|
||||
return {
|
||||
text: `${outcomeLabels.confirmed}: ${specialization}, ${gradeLabels[grade]}.`,
|
||||
reason: null,
|
||||
text: `${outcomeLabels.confirmed}: ${specialization}, ${gradeLabels[result.confirmed_grade]}.`,
|
||||
reason: reason === "" ? null : reason,
|
||||
isDemonstration,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -31,6 +31,7 @@ import type {
|
||||
AssessmentQualifiedAttempt,
|
||||
AssessmentQualifiedResult,
|
||||
AssessmentResult,
|
||||
AssessmentResultHistoryPage,
|
||||
AssessmentSessions,
|
||||
AssessmentSignalNotice,
|
||||
AssessmentSignalReceipt,
|
||||
@@ -49,6 +50,16 @@ import type {
|
||||
|
||||
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(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), confirmed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),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(['intern','junior','middle','senior'] as const), status: faker.helpers.arrayElement(['available','active_attempt','cooldown','insufficient_bank'] as const), mode: faker.helpers.arrayElement([faker.helpers.arrayElement(['demo_basic','adaptive'] as const),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 getListMyAssessmentResultsResponseAssessmentUncertaintyMock = (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 getListMyAssessmentResultsResponseBasicScoreMock = (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 getListMyAssessmentResultsResponseAssessmentQualifiedResultMock = (overrideResponse: Partial<AssessmentQualifiedResult> = {}): AssessmentQualifiedResult => ({...{...{...{attempt_id: faker.string.uuid(), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), target_grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), root_attempt_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), chain_deadline: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(['python','go'] as const),null,]), kind: faker.helpers.arrayElement(['root','corrective'] as const), mode: faker.helpers.arrayElement(['demo_basic','adaptive'] as const), versions: {policy_version: faker.number.int({min: 1}), bank_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), algorithm_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64})}, outcome: faker.helpers.arrayElement(['confirmed','not_confirmed','not_determined'] as const), not_determined_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['expired','practice_incomplete','insufficient_bank','sandbox_unavailable'] as const),null,]), confirmed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), previous_confirmed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), ...(faker.datatype.boolean() ? {category_decision: {status: faker.helpers.arrayElement(['not_eligible','not_confirmed','assigned','unchanged'] as const), previous_confirmed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), current_confirmed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), method: faker.helpers.arrayElement([faker.helpers.arrayElement(['demo_basic_pass_mark'] as const),null,]), source: faker.helpers.arrayElement([faker.helpers.arrayElement(['synthetic_demo'] as const),null,]), calibration_status: faker.helpers.arrayElement([faker.helpers.arrayElement(['uncalibrated','calibrated'] as const),null,])}} : {}), strength: faker.helpers.arrayElement([faker.helpers.arrayElement(['high','medium'] as const),null,]), calibration_status: faker.helpers.arrayElement(['uncalibrated','calibrated'] as const), limitations: faker.helpers.arrayElements(['uncalibrated_thresholds','demo_bank','practice_not_included','unproctored'] as const), uncertainty: faker.helpers.arrayElement([{...getListMyAssessmentResultsResponseAssessmentUncertaintyMock()},null,]), basic_score: faker.helpers.arrayElement([{...getListMyAssessmentResultsResponseBasicScoreMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(['main','additional'] as const), verdict: {score: faker.number.int({min: 0, max: 3}), max_score: faker.number.int({min: 3, max: 3}), groups: Array.from({ length: faker.number.int({min: 3, max: 3}) }, (_, i) => i + 1).map(() => ({group: faker.number.int({min: 1, max: 3}), passed: faker.datatype.boolean()}))}})), gaps: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => ({domain: fakeFromPattern("^[a-z0-9_]+$", {minLength: 1, maxLength: 64}), title: faker.string.alpha({length: {min: 1, max: 200}})})), durations: {items_seconds: faker.number.int({min: 0}), practice_seconds: faker.helpers.arrayElement([faker.number.int({min: 0}), null])}, next_steps: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({action: faker.helpers.arrayElement(['retake_same_grade','take_lower_grade','accept_lower_grade','take_higher_grade'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), available_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])})), decided_at: faker.date.past().toISOString().slice(0, 19) + 'Z'},...{kind: faker.helpers.arrayElement(['root'] as const), root_attempt_id: null, chain_deadline: null},}, kind: faker.helpers.arrayElement(['root'] as const)}, ...overrideResponse});
|
||||
|
||||
export const getListMyAssessmentResultsResponseAssessmentCorrectiveResultMock = (overrideResponse: Partial<AssessmentCorrectiveResult> = {}): AssessmentCorrectiveResult => ({...{...{...{attempt_id: faker.string.uuid(), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), target_grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), root_attempt_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), chain_deadline: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(['python','go'] as const),null,]), kind: faker.helpers.arrayElement(['root','corrective'] as const), mode: faker.helpers.arrayElement(['demo_basic','adaptive'] as const), versions: {policy_version: faker.number.int({min: 1}), bank_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), algorithm_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64})}, outcome: faker.helpers.arrayElement(['confirmed','not_confirmed','not_determined'] as const), not_determined_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['expired','practice_incomplete','insufficient_bank','sandbox_unavailable'] as const),null,]), confirmed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), previous_confirmed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), ...(faker.datatype.boolean() ? {category_decision: {status: faker.helpers.arrayElement(['not_eligible','not_confirmed','assigned','unchanged'] as const), previous_confirmed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), current_confirmed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), method: faker.helpers.arrayElement([faker.helpers.arrayElement(['demo_basic_pass_mark'] as const),null,]), source: faker.helpers.arrayElement([faker.helpers.arrayElement(['synthetic_demo'] as const),null,]), calibration_status: faker.helpers.arrayElement([faker.helpers.arrayElement(['uncalibrated','calibrated'] as const),null,])}} : {}), strength: faker.helpers.arrayElement([faker.helpers.arrayElement(['high','medium'] as const),null,]), calibration_status: faker.helpers.arrayElement(['uncalibrated','calibrated'] as const), limitations: faker.helpers.arrayElements(['uncalibrated_thresholds','demo_bank','practice_not_included','unproctored'] as const), uncertainty: faker.helpers.arrayElement([{...getListMyAssessmentResultsResponseAssessmentUncertaintyMock()},null,]), basic_score: faker.helpers.arrayElement([{...getListMyAssessmentResultsResponseBasicScoreMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(['main','additional'] as const), verdict: {score: faker.number.int({min: 0, max: 3}), max_score: faker.number.int({min: 3, max: 3}), groups: Array.from({ length: faker.number.int({min: 3, max: 3}) }, (_, i) => i + 1).map(() => ({group: faker.number.int({min: 1, max: 3}), passed: faker.datatype.boolean()}))}})), gaps: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => ({domain: fakeFromPattern("^[a-z0-9_]+$", {minLength: 1, maxLength: 64}), title: faker.string.alpha({length: {min: 1, max: 200}})})), durations: {items_seconds: faker.number.int({min: 0}), practice_seconds: faker.helpers.arrayElement([faker.number.int({min: 0}), null])}, next_steps: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({action: faker.helpers.arrayElement(['retake_same_grade','take_lower_grade','accept_lower_grade','take_higher_grade'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), available_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])})), decided_at: faker.date.past().toISOString().slice(0, 19) + 'Z'},...{kind: faker.helpers.arrayElement(['corrective'] as const), root_attempt_id: faker.string.uuid(), chain_deadline: faker.date.past().toISOString().slice(0, 19) + 'Z'},}, kind: faker.helpers.arrayElement(['corrective'] as const)}, ...overrideResponse});
|
||||
|
||||
export const getListMyAssessmentResultsResponseMock = (overrideResponse: Partial<Extract<AssessmentResultHistoryPage, object>> = {}): AssessmentResultHistoryPage => ({items: Array.from({ length: faker.number.int({min: 1, max: 50}) }, (_, i) => i + 1).map(() => (faker.helpers.arrayElement([{...getListMyAssessmentResultsResponseAssessmentQualifiedResultMock()},{...getListMyAssessmentResultsResponseAssessmentCorrectiveResultMock()},]))), page: {has_more: faker.datatype.boolean(), next_cursor: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 512}), null])}, ...overrideResponse})
|
||||
|
||||
export const getGetMyAssessmentSignalNoticeResponseMock = (overrideResponse: Partial<Extract<AssessmentSignalNotice, object>> = {}): AssessmentSignalNotice => ({notice_version: faker.number.int({min: 1, max: 2147483647}), acknowledged: faker.datatype.boolean(), acknowledged_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), ...overrideResponse})
|
||||
|
||||
export const getAcknowledgeMyAssessmentSignalNoticeResponseMock = (overrideResponse: Partial<Extract<AssessmentSignalNotice, object>> = {}): AssessmentSignalNotice => ({notice_version: faker.number.int({min: 1, max: 2147483647}), acknowledged: faker.datatype.boolean(), acknowledged_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), ...overrideResponse})
|
||||
@@ -199,9 +210,9 @@ export const getGetMyAssessmentResultResponseAssessmentUncertaintyMock = (overri
|
||||
|
||||
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 getGetMyAssessmentResultResponseAssessmentQualifiedResultMock = (overrideResponse: Partial<AssessmentQualifiedResult> = {}): AssessmentQualifiedResult => ({...{...{...{attempt_id: faker.string.uuid(), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), target_grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), root_attempt_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), chain_deadline: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(['python','go'] as const),null,]), kind: faker.helpers.arrayElement(['root','corrective'] as const), mode: faker.helpers.arrayElement(['demo_basic','adaptive'] as const), versions: {policy_version: faker.number.int({min: 1}), bank_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), algorithm_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64})}, outcome: faker.helpers.arrayElement(['confirmed','not_confirmed','not_determined'] as const), not_determined_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['expired','practice_incomplete','insufficient_bank','sandbox_unavailable'] as const),null,]), confirmed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), previous_confirmed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), strength: faker.helpers.arrayElement([faker.helpers.arrayElement(['high','medium'] as const),null,]), calibration_status: faker.helpers.arrayElement(['uncalibrated','calibrated'] as const), limitations: faker.helpers.arrayElements(['uncalibrated_thresholds','demo_bank','practice_not_included','unproctored'] as const), uncertainty: faker.helpers.arrayElement([{...getGetMyAssessmentResultResponseAssessmentUncertaintyMock()},null,]), basic_score: faker.helpers.arrayElement([{...getGetMyAssessmentResultResponseBasicScoreMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(['main','additional'] as const), verdict: {score: faker.number.int({min: 0, max: 3}), max_score: faker.number.int({min: 3, max: 3}), groups: Array.from({ length: faker.number.int({min: 3, max: 3}) }, (_, i) => i + 1).map(() => ({group: faker.number.int({min: 1, max: 3}), passed: faker.datatype.boolean()}))}})), gaps: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => ({domain: fakeFromPattern("^[a-z0-9_]+$", {minLength: 1, maxLength: 64}), title: faker.string.alpha({length: {min: 1, max: 200}})})), durations: {items_seconds: faker.number.int({min: 0}), practice_seconds: faker.helpers.arrayElement([faker.number.int({min: 0}), null])}, next_steps: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({action: faker.helpers.arrayElement(['retake_same_grade','take_lower_grade','accept_lower_grade','take_higher_grade'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), available_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])})), decided_at: faker.date.past().toISOString().slice(0, 19) + 'Z'},...{kind: faker.helpers.arrayElement(['root'] as const), root_attempt_id: null, chain_deadline: null},}, kind: faker.helpers.arrayElement(['root'] as const)}, ...overrideResponse});
|
||||
export const getGetMyAssessmentResultResponseAssessmentQualifiedResultMock = (overrideResponse: Partial<AssessmentQualifiedResult> = {}): AssessmentQualifiedResult => ({...{...{...{attempt_id: faker.string.uuid(), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), target_grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), root_attempt_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), chain_deadline: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(['python','go'] as const),null,]), kind: faker.helpers.arrayElement(['root','corrective'] as const), mode: faker.helpers.arrayElement(['demo_basic','adaptive'] as const), versions: {policy_version: faker.number.int({min: 1}), bank_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), algorithm_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64})}, outcome: faker.helpers.arrayElement(['confirmed','not_confirmed','not_determined'] as const), not_determined_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['expired','practice_incomplete','insufficient_bank','sandbox_unavailable'] as const),null,]), confirmed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), previous_confirmed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), ...(faker.datatype.boolean() ? {category_decision: {status: faker.helpers.arrayElement(['not_eligible','not_confirmed','assigned','unchanged'] as const), previous_confirmed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), current_confirmed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), method: faker.helpers.arrayElement([faker.helpers.arrayElement(['demo_basic_pass_mark'] as const),null,]), source: faker.helpers.arrayElement([faker.helpers.arrayElement(['synthetic_demo'] as const),null,]), calibration_status: faker.helpers.arrayElement([faker.helpers.arrayElement(['uncalibrated','calibrated'] as const),null,])}} : {}), strength: faker.helpers.arrayElement([faker.helpers.arrayElement(['high','medium'] as const),null,]), calibration_status: faker.helpers.arrayElement(['uncalibrated','calibrated'] as const), limitations: faker.helpers.arrayElements(['uncalibrated_thresholds','demo_bank','practice_not_included','unproctored'] as const), uncertainty: faker.helpers.arrayElement([{...getGetMyAssessmentResultResponseAssessmentUncertaintyMock()},null,]), basic_score: faker.helpers.arrayElement([{...getGetMyAssessmentResultResponseBasicScoreMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(['main','additional'] as const), verdict: {score: faker.number.int({min: 0, max: 3}), max_score: faker.number.int({min: 3, max: 3}), groups: Array.from({ length: faker.number.int({min: 3, max: 3}) }, (_, i) => i + 1).map(() => ({group: faker.number.int({min: 1, max: 3}), passed: faker.datatype.boolean()}))}})), gaps: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => ({domain: fakeFromPattern("^[a-z0-9_]+$", {minLength: 1, maxLength: 64}), title: faker.string.alpha({length: {min: 1, max: 200}})})), durations: {items_seconds: faker.number.int({min: 0}), practice_seconds: faker.helpers.arrayElement([faker.number.int({min: 0}), null])}, next_steps: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({action: faker.helpers.arrayElement(['retake_same_grade','take_lower_grade','accept_lower_grade','take_higher_grade'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), available_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])})), decided_at: faker.date.past().toISOString().slice(0, 19) + 'Z'},...{kind: faker.helpers.arrayElement(['root'] as const), root_attempt_id: null, chain_deadline: null},}, kind: faker.helpers.arrayElement(['root'] as const)}, ...overrideResponse});
|
||||
|
||||
export const getGetMyAssessmentResultResponseAssessmentCorrectiveResultMock = (overrideResponse: Partial<AssessmentCorrectiveResult> = {}): AssessmentCorrectiveResult => ({...{...{...{attempt_id: faker.string.uuid(), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), target_grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), root_attempt_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), chain_deadline: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(['python','go'] as const),null,]), kind: faker.helpers.arrayElement(['root','corrective'] as const), mode: faker.helpers.arrayElement(['demo_basic','adaptive'] as const), versions: {policy_version: faker.number.int({min: 1}), bank_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), algorithm_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64})}, outcome: faker.helpers.arrayElement(['confirmed','not_confirmed','not_determined'] as const), not_determined_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['expired','practice_incomplete','insufficient_bank','sandbox_unavailable'] as const),null,]), confirmed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), previous_confirmed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), strength: faker.helpers.arrayElement([faker.helpers.arrayElement(['high','medium'] as const),null,]), calibration_status: faker.helpers.arrayElement(['uncalibrated','calibrated'] as const), limitations: faker.helpers.arrayElements(['uncalibrated_thresholds','demo_bank','practice_not_included','unproctored'] as const), uncertainty: faker.helpers.arrayElement([{...getGetMyAssessmentResultResponseAssessmentUncertaintyMock()},null,]), basic_score: faker.helpers.arrayElement([{...getGetMyAssessmentResultResponseBasicScoreMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(['main','additional'] as const), verdict: {score: faker.number.int({min: 0, max: 3}), max_score: faker.number.int({min: 3, max: 3}), groups: Array.from({ length: faker.number.int({min: 3, max: 3}) }, (_, i) => i + 1).map(() => ({group: faker.number.int({min: 1, max: 3}), passed: faker.datatype.boolean()}))}})), gaps: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => ({domain: fakeFromPattern("^[a-z0-9_]+$", {minLength: 1, maxLength: 64}), title: faker.string.alpha({length: {min: 1, max: 200}})})), durations: {items_seconds: faker.number.int({min: 0}), practice_seconds: faker.helpers.arrayElement([faker.number.int({min: 0}), null])}, next_steps: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({action: faker.helpers.arrayElement(['retake_same_grade','take_lower_grade','accept_lower_grade','take_higher_grade'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), available_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])})), decided_at: faker.date.past().toISOString().slice(0, 19) + 'Z'},...{kind: faker.helpers.arrayElement(['corrective'] as const), root_attempt_id: faker.string.uuid(), chain_deadline: faker.date.past().toISOString().slice(0, 19) + 'Z'},}, kind: faker.helpers.arrayElement(['corrective'] as const)}, ...overrideResponse});
|
||||
export const getGetMyAssessmentResultResponseAssessmentCorrectiveResultMock = (overrideResponse: Partial<AssessmentCorrectiveResult> = {}): AssessmentCorrectiveResult => ({...{...{...{attempt_id: faker.string.uuid(), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), target_grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), root_attempt_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), chain_deadline: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(['python','go'] as const),null,]), kind: faker.helpers.arrayElement(['root','corrective'] as const), mode: faker.helpers.arrayElement(['demo_basic','adaptive'] as const), versions: {policy_version: faker.number.int({min: 1}), bank_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), algorithm_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64})}, outcome: faker.helpers.arrayElement(['confirmed','not_confirmed','not_determined'] as const), not_determined_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['expired','practice_incomplete','insufficient_bank','sandbox_unavailable'] as const),null,]), confirmed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), previous_confirmed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), ...(faker.datatype.boolean() ? {category_decision: {status: faker.helpers.arrayElement(['not_eligible','not_confirmed','assigned','unchanged'] as const), previous_confirmed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), current_confirmed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), method: faker.helpers.arrayElement([faker.helpers.arrayElement(['demo_basic_pass_mark'] as const),null,]), source: faker.helpers.arrayElement([faker.helpers.arrayElement(['synthetic_demo'] as const),null,]), calibration_status: faker.helpers.arrayElement([faker.helpers.arrayElement(['uncalibrated','calibrated'] as const),null,])}} : {}), strength: faker.helpers.arrayElement([faker.helpers.arrayElement(['high','medium'] as const),null,]), calibration_status: faker.helpers.arrayElement(['uncalibrated','calibrated'] as const), limitations: faker.helpers.arrayElements(['uncalibrated_thresholds','demo_bank','practice_not_included','unproctored'] as const), uncertainty: faker.helpers.arrayElement([{...getGetMyAssessmentResultResponseAssessmentUncertaintyMock()},null,]), basic_score: faker.helpers.arrayElement([{...getGetMyAssessmentResultResponseBasicScoreMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(['main','additional'] as const), verdict: {score: faker.number.int({min: 0, max: 3}), max_score: faker.number.int({min: 3, max: 3}), groups: Array.from({ length: faker.number.int({min: 3, max: 3}) }, (_, i) => i + 1).map(() => ({group: faker.number.int({min: 1, max: 3}), passed: faker.datatype.boolean()}))}})), gaps: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => ({domain: fakeFromPattern("^[a-z0-9_]+$", {minLength: 1, maxLength: 64}), title: faker.string.alpha({length: {min: 1, max: 200}})})), durations: {items_seconds: faker.number.int({min: 0}), practice_seconds: faker.helpers.arrayElement([faker.number.int({min: 0}), null])}, next_steps: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({action: faker.helpers.arrayElement(['retake_same_grade','take_lower_grade','accept_lower_grade','take_higher_grade'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), available_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])})), decided_at: faker.date.past().toISOString().slice(0, 19) + 'Z'},...{kind: faker.helpers.arrayElement(['corrective'] as const), root_attempt_id: faker.string.uuid(), chain_deadline: faker.date.past().toISOString().slice(0, 19) + 'Z'},}, kind: faker.helpers.arrayElement(['corrective'] as const)}, ...overrideResponse});
|
||||
|
||||
export const getGetMyAssessmentResultResponseAssessmentExpressResultMock = (overrideResponse: Partial<AssessmentExpressResult> = {}): AssessmentExpressResult => ({...{attempt_id: faker.string.uuid(), specialization: null, target_grade: null, task_language: null, kind: faker.helpers.arrayElement(['demo_express'] as const), mode: faker.helpers.arrayElement(['demo_express'] as const), versions: {policy_version: faker.number.int({min: 1}), bank_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), algorithm_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64})}, outcome: faker.helpers.arrayElement(['demonstration'] as const), not_determined_reason: null, confirmed_grade: null, previous_confirmed_grade: null, strength: null, calibration_status: faker.helpers.arrayElement(['uncalibrated'] as const), limitations: faker.helpers.arrayElements(['demonstration_only'] as const), uncertainty: null, basic_score: null, practices: Array.from({ length: faker.number.int({min: 0, max: 0}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(['main','additional'] as const), verdict: {score: faker.number.int({min: 0, max: 3}), max_score: faker.number.int({min: 3, max: 3}), groups: Array.from({ length: faker.number.int({min: 3, max: 3}) }, (_, i) => i + 1).map(() => ({group: faker.number.int({min: 1, max: 3}), passed: faker.datatype.boolean()}))}})), gaps: Array.from({ length: faker.number.int({min: 0, max: 0}) }, (_, i) => i + 1).map(() => ({domain: fakeFromPattern("^[a-z0-9_]+$", {minLength: 1, maxLength: 64}), title: faker.string.alpha({length: {min: 1, max: 200}})})), durations: {items_seconds: faker.number.int({min: 0}), practice_seconds: faker.helpers.arrayElement([faker.number.int({min: 0}), null])}, next_steps: Array.from({ length: faker.number.int({min: 0, max: 0}) }, (_, i) => i + 1).map(() => ({action: faker.helpers.arrayElement(['retake_same_grade','take_lower_grade','accept_lower_grade','take_higher_grade'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), available_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])})), summary: faker.string.alpha({length: {min: 1, max: 2000}}), decided_at: faker.date.past().toISOString().slice(0, 19) + 'Z'}, ...overrideResponse});
|
||||
|
||||
@@ -220,6 +231,18 @@ export const getGetMyAssessmentAvailabilityMockHandler = (overrideResponse?: Ass
|
||||
}, options)
|
||||
}
|
||||
|
||||
export const getListMyAssessmentResultsMockHandler = (overrideResponse?: AssessmentResultHistoryPage | ((info: Parameters<Parameters<typeof http.get>[1]>[0]) => Promise<AssessmentResultHistoryPage> | AssessmentResultHistoryPage), options?: RequestHandlerOptions) => {
|
||||
return http.get('*/api/v1/me/assessment-results', async (info: Parameters<Parameters<typeof http.get>[1]>[0]) => {
|
||||
|
||||
|
||||
return HttpResponse.json(overrideResponse !== undefined
|
||||
? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse)
|
||||
: getListMyAssessmentResultsResponseMock(),
|
||||
{ status: 200
|
||||
})
|
||||
}, options)
|
||||
}
|
||||
|
||||
export const getGetMyAssessmentSignalNoticeMockHandler = (overrideResponse?: AssessmentSignalNotice | ((info: Parameters<Parameters<typeof http.get>[1]>[0]) => Promise<AssessmentSignalNotice> | AssessmentSignalNotice), options?: RequestHandlerOptions) => {
|
||||
return http.get('*/api/v1/me/assessment-signal-notice', async (info: Parameters<Parameters<typeof http.get>[1]>[0]) => {
|
||||
|
||||
@@ -329,6 +352,7 @@ export const getGetMyAssessmentResultMockHandler = (overrideResponse?: Assessmen
|
||||
}
|
||||
export const getAssessmentMock = () => [
|
||||
getGetMyAssessmentAvailabilityMockHandler(),
|
||||
getListMyAssessmentResultsMockHandler(),
|
||||
getGetMyAssessmentSignalNoticeMockHandler(),
|
||||
getAcknowledgeMyAssessmentSignalNoticeMockHandler(),
|
||||
getCreateMyAssessmentAttemptMockHandler(),
|
||||
|
||||
@@ -32,12 +32,14 @@ import type {
|
||||
AssessmentFinalization,
|
||||
AssessmentFinalizeConflictProblem,
|
||||
AssessmentResult,
|
||||
AssessmentResultHistoryPage,
|
||||
AssessmentSignalBatch,
|
||||
AssessmentSignalNotice,
|
||||
AssessmentSignalNoticeAcknowledgement,
|
||||
AssessmentSignalReceipt,
|
||||
CreateMyAssessmentAttemptHeaders,
|
||||
FinalizeMyAssessmentAttemptHeaders,
|
||||
ListMyAssessmentResultsParams,
|
||||
Problem,
|
||||
RecordMyAssessmentAttemptSignalsHeaders,
|
||||
StartMyAssessmentAttemptSessionHeaders,
|
||||
@@ -172,6 +174,116 @@ export function useGetMyAssessmentAvailability<TData = Awaited<ReturnType<typeof
|
||||
|
||||
|
||||
|
||||
export const getListMyAssessmentResultsUrl = (params?: ListMyAssessmentResultsParams,) => {
|
||||
const normalizedParams = new URLSearchParams();
|
||||
|
||||
Object.entries(params || {}).forEach(([key, value]) => {
|
||||
|
||||
if (value !== undefined) {
|
||||
normalizedParams.append(key, value === null ? 'null' : String(value))
|
||||
}
|
||||
});
|
||||
|
||||
const stringifiedParams = normalizedParams.toString();
|
||||
|
||||
return stringifiedParams.length > 0 ? `/api/v1/me/assessment-results?${stringifiedParams}` : `/api/v1/me/assessment-results`
|
||||
}
|
||||
|
||||
/**
|
||||
* Requires a candidate session. Returns only completed root and corrective results owned by this candidate, newest first by decided_at and attempt_id. demo_express training results never appear. The cursor is opaque and bound to this candidate and listing; a malformed or foreign cursor returns 400 validation_failed.
|
||||
*
|
||||
* A v2 result includes the category decision captured when that attempt ended, including the confirmed grade then in force. Legacy v1 results omit category_decision because a later category must not be projected backward. Later policy, bank, review, or category changes do not alter either result. Employers cannot read this history; their separate projection contains only the current permitted category and no answers.
|
||||
* @summary List immutable real assessment results of the current candidate.
|
||||
*/
|
||||
export const listMyAssessmentResults = async (params?: ListMyAssessmentResultsParams, options?: Parameters<typeof apiRequest>[1]): Promise<AssessmentResultHistoryPage> => {
|
||||
|
||||
return apiRequest<AssessmentResultHistoryPage>(getListMyAssessmentResultsUrl(params),
|
||||
{
|
||||
...options,
|
||||
method: 'GET'
|
||||
|
||||
|
||||
}
|
||||
);}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
export const getListMyAssessmentResultsQueryKey = (params?: ListMyAssessmentResultsParams,) => {
|
||||
return [
|
||||
`/api/v1/me/assessment-results`, ...(params ? [params] : [])
|
||||
] as const;
|
||||
}
|
||||
|
||||
|
||||
export const getListMyAssessmentResultsQueryOptions = <TData = Awaited<ReturnType<typeof listMyAssessmentResults>>, TError = ErrorType<Problem>>(params?: ListMyAssessmentResultsParams, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof listMyAssessmentResults>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
|
||||
) => {
|
||||
|
||||
const {query: queryOptions, request: requestOptions} = options ?? {};
|
||||
|
||||
const queryKey = queryOptions?.queryKey ?? getListMyAssessmentResultsQueryKey(params);
|
||||
|
||||
|
||||
|
||||
const queryFn: QueryFunction<Awaited<ReturnType<typeof listMyAssessmentResults>>> = ({ signal }) => listMyAssessmentResults(params, { signal, ...requestOptions });
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
return { queryKey, queryFn, ...queryOptions} as UseQueryOptions<Awaited<ReturnType<typeof listMyAssessmentResults>>, TError, TData> & { queryKey: DataTag<QueryKey, TData, TError> }
|
||||
}
|
||||
|
||||
export type ListMyAssessmentResultsQueryResult = NonNullable<Awaited<ReturnType<typeof listMyAssessmentResults>>>
|
||||
export type ListMyAssessmentResultsQueryError = ErrorType<Problem>
|
||||
|
||||
|
||||
export function useListMyAssessmentResults<TData = Awaited<ReturnType<typeof listMyAssessmentResults>>, TError = ErrorType<Problem>>(
|
||||
params: undefined | ListMyAssessmentResultsParams, options: { query:Partial<UseQueryOptions<Awaited<ReturnType<typeof listMyAssessmentResults>>, TError, TData>> & Pick<
|
||||
DefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof listMyAssessmentResults>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof listMyAssessmentResults>>
|
||||
> , 'initialData'
|
||||
>, request?: SecondParameter<typeof apiRequest>}
|
||||
, queryClient?: QueryClient
|
||||
): DefinedUseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
||||
export function useListMyAssessmentResults<TData = Awaited<ReturnType<typeof listMyAssessmentResults>>, TError = ErrorType<Problem>>(
|
||||
params?: ListMyAssessmentResultsParams, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof listMyAssessmentResults>>, TError, TData>> & Pick<
|
||||
UndefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof listMyAssessmentResults>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof listMyAssessmentResults>>
|
||||
> , 'initialData'
|
||||
>, request?: SecondParameter<typeof apiRequest>}
|
||||
, queryClient?: QueryClient
|
||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
||||
export function useListMyAssessmentResults<TData = Awaited<ReturnType<typeof listMyAssessmentResults>>, TError = ErrorType<Problem>>(
|
||||
params?: ListMyAssessmentResultsParams, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof listMyAssessmentResults>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
|
||||
, queryClient?: QueryClient
|
||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
||||
/**
|
||||
* @summary List immutable real assessment results of the current candidate.
|
||||
*/
|
||||
|
||||
export function useListMyAssessmentResults<TData = Awaited<ReturnType<typeof listMyAssessmentResults>>, TError = ErrorType<Problem>>(
|
||||
params?: ListMyAssessmentResultsParams, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof listMyAssessmentResults>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
|
||||
, queryClient?: QueryClient
|
||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> } {
|
||||
|
||||
const queryOptions = getListMyAssessmentResultsQueryOptions(params,options)
|
||||
|
||||
const query = useQuery(queryOptions, queryClient) as UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||
|
||||
return withQueryKey(query, queryOptions.queryKey);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
export const getGetMyAssessmentSignalNoticeUrl = () => {
|
||||
|
||||
|
||||
|
||||
@@ -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 AssessmentCategoryDecisionView = zod.object({
|
||||
"status": zod.enum(['not_eligible', 'not_confirmed', 'assigned', 'unchanged']),
|
||||
"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()]),
|
||||
"current_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()]),
|
||||
"method": zod.union([zod.enum(['demo_basic_pass_mark']),zod.null()]),
|
||||
"source": zod.union([zod.enum(['synthetic_demo']),zod.null()]),
|
||||
"calibration_status": zod.union([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.'),zod.null()])
|
||||
}).describe('Category decision captured when this result was stored. It is absent from legacy v1 results because their current grade cannot be inferred later. It never exposes review identifiers, private answers, or the candidate\'s current category after this decision.')
|
||||
|
||||
export type AssessmentCategoryDecisionView = zod.input<typeof AssessmentCategoryDecisionView>;
|
||||
export type AssessmentCategoryDecisionViewOutput = zod.output<typeof AssessmentCategoryDecisionView>;
|
||||
@@ -72,6 +72,14 @@ export const AssessmentCorrectiveResult = zod.object({
|
||||
"not_determined_reason": zod.union([zod.enum(['expired', 'practice_incomplete', 'insufficient_bank', 'sandbox_unavailable']).describe('Why an attempt gives no decision. One root quota slot is reserved when a real root attempt starts; corrective checks in its chain do not reserve another slot.\n\n- expired: the time or session limit passed before the candidate finished the item part. Retry timing follows the recorded policy; a correction uses the existing root slot and does not reset the chain deadline or 30/90-day timers.\n- practice_incomplete: the item part was done, but the candidate did not submit the main practice before the limit. Retry timing follows the recorded policy; a correction uses the existing root slot and does not reset the chain deadline or 30/90-day timers.\n- insufficient_bank: the bank could not supply required coverage. A preflight refusal creates no attempt or root slot; a bank failure in an existing chain does not create a free new chain or another root slot.\n- sandbox_unavailable: the latest submission of a required or additional practice ended `failed` because of the sandbox infrastructure, and the limit passed before a verdict. It is a platform fault and does not create a new root slot or a free chain.'),zod.null()]).describe('The reason when `outcome` is `not_determined`, otherwise null.'),
|
||||
"confirmed_grade": zod.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Grade that this attempt confirmed, the target grade, or null when it confirmed none. Together with the specialization it forms the category.'),
|
||||
"previous_confirmed_grade": zod.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Confirmed grade of the specialization before this attempt, or null. When the attempt confirmed nothing, this grade stays in force.'),
|
||||
"category_decision": zod.object({
|
||||
"status": zod.enum(['not_eligible', 'not_confirmed', 'assigned', 'unchanged']),
|
||||
"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()]),
|
||||
"current_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()]),
|
||||
"method": zod.union([zod.enum(['demo_basic_pass_mark']),zod.null()]),
|
||||
"source": zod.union([zod.enum(['synthetic_demo']),zod.null()]),
|
||||
"calibration_status": zod.union([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.'),zod.null()])
|
||||
}).exactOptional().describe('Category decision captured when this result was stored. It is absent from legacy v1 results because their current grade cannot be inferred later. It never exposes review identifiers, private answers, or the candidate\'s current category after this decision.'),
|
||||
"strength": zod.union([zod.enum(['high', 'medium']).describe('Strength of an adaptive confirmation: `high` or `medium`, by the probability bands of the recorded policy version.'),zod.null()]).describe('Strength of an adaptive confirmation, otherwise null.'),
|
||||
"calibration_status": zod.enum(['uncalibrated', 'calibrated']).describe('Whether the thresholds of the recorded policy version are empirically calibrated. `uncalibrated` results are provisional: their thresholds come from expert judgement, and their probabilities are not claimed to be calibrated.'),
|
||||
"limitations": zod.array(zod.enum(['uncalibrated_thresholds', 'demo_bank', 'practice_not_included', 'unproctored']).describe('Known limitation of the method behind a real-assessment result, shown with the result.\n\n- uncalibrated_thresholds: the thresholds are not yet validated on a pilot.\n- demo_bank: the result comes from the small reviewed demo bank.\n- practice_not_included: the attempt had no code practice because the sandbox was not enabled.\n- unproctored: the attempt was taken online without supervision.\nAdding a value is a contract change.')).max(assessmentCorrectiveResultOneLimitationsMax),
|
||||
|
||||
@@ -72,6 +72,14 @@ export const AssessmentQualifiedResult = zod.object({
|
||||
"not_determined_reason": zod.union([zod.enum(['expired', 'practice_incomplete', 'insufficient_bank', 'sandbox_unavailable']).describe('Why an attempt gives no decision. One root quota slot is reserved when a real root attempt starts; corrective checks in its chain do not reserve another slot.\n\n- expired: the time or session limit passed before the candidate finished the item part. Retry timing follows the recorded policy; a correction uses the existing root slot and does not reset the chain deadline or 30/90-day timers.\n- practice_incomplete: the item part was done, but the candidate did not submit the main practice before the limit. Retry timing follows the recorded policy; a correction uses the existing root slot and does not reset the chain deadline or 30/90-day timers.\n- insufficient_bank: the bank could not supply required coverage. A preflight refusal creates no attempt or root slot; a bank failure in an existing chain does not create a free new chain or another root slot.\n- sandbox_unavailable: the latest submission of a required or additional practice ended `failed` because of the sandbox infrastructure, and the limit passed before a verdict. It is a platform fault and does not create a new root slot or a free chain.'),zod.null()]).describe('The reason when `outcome` is `not_determined`, otherwise null.'),
|
||||
"confirmed_grade": zod.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Grade that this attempt confirmed, the target grade, or null when it confirmed none. Together with the specialization it forms the category.'),
|
||||
"previous_confirmed_grade": zod.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Confirmed grade of the specialization before this attempt, or null. When the attempt confirmed nothing, this grade stays in force.'),
|
||||
"category_decision": zod.object({
|
||||
"status": zod.enum(['not_eligible', 'not_confirmed', 'assigned', 'unchanged']),
|
||||
"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()]),
|
||||
"current_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()]),
|
||||
"method": zod.union([zod.enum(['demo_basic_pass_mark']),zod.null()]),
|
||||
"source": zod.union([zod.enum(['synthetic_demo']),zod.null()]),
|
||||
"calibration_status": zod.union([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.'),zod.null()])
|
||||
}).exactOptional().describe('Category decision captured when this result was stored. It is absent from legacy v1 results because their current grade cannot be inferred later. It never exposes review identifiers, private answers, or the candidate\'s current category after this decision.'),
|
||||
"strength": zod.union([zod.enum(['high', 'medium']).describe('Strength of an adaptive confirmation: `high` or `medium`, by the probability bands of the recorded policy version.'),zod.null()]).describe('Strength of an adaptive confirmation, otherwise null.'),
|
||||
"calibration_status": zod.enum(['uncalibrated', 'calibrated']).describe('Whether the thresholds of the recorded policy version are empirically calibrated. `uncalibrated` results are provisional: their thresholds come from expert judgement, and their probabilities are not claimed to be calibrated.'),
|
||||
"limitations": zod.array(zod.enum(['uncalibrated_thresholds', 'demo_bank', 'practice_not_included', 'unproctored']).describe('Known limitation of the method behind a real-assessment result, shown with the result.\n\n- uncalibrated_thresholds: the thresholds are not yet validated on a pilot.\n- demo_bank: the result comes from the small reviewed demo bank.\n- practice_not_included: the attempt had no code practice because the sandbox was not enabled.\n- unproctored: the attempt was taken online without supervision.\nAdding a value is a contract change.')).max(assessmentQualifiedResultOneLimitationsMax),
|
||||
|
||||
@@ -0,0 +1,255 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
|
||||
export const assessmentRealResultOneOneVersionsBankVersionMax = 64;
|
||||
|
||||
|
||||
export const assessmentRealResultOneOneVersionsBankVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$');
|
||||
export const assessmentRealResultOneOneVersionsAlgorithmVersionMax = 64;
|
||||
|
||||
|
||||
export const assessmentRealResultOneOneVersionsAlgorithmVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$');
|
||||
export const assessmentRealResultOneOneLimitationsMax = 10;
|
||||
|
||||
export const assessmentRealResultOneOneUncertaintyOneStandardErrorMin = 0;
|
||||
|
||||
export const assessmentRealResultOneOneUncertaintyOnePGradeMin = 0;
|
||||
export const assessmentRealResultOneOneUncertaintyOnePGradeMax = 1;
|
||||
|
||||
export const assessmentRealResultOneOneBasicScoreOnePointsMin = 0;
|
||||
|
||||
|
||||
|
||||
export const assessmentRealResultOneOnePracticesItemVerdictScoreMin = 0;
|
||||
export const assessmentRealResultOneOnePracticesItemVerdictScoreMax = 3;
|
||||
|
||||
export const assessmentRealResultOneOnePracticesItemVerdictMaxScoreMin = 3;
|
||||
export const assessmentRealResultOneOnePracticesItemVerdictMaxScoreMax = 3;
|
||||
|
||||
export const assessmentRealResultOneOnePracticesItemVerdictGroupsItemGroupMax = 3;
|
||||
|
||||
export const assessmentRealResultOneOnePracticesItemVerdictGroupsMin = 3;
|
||||
export const assessmentRealResultOneOnePracticesItemVerdictGroupsMax = 3;
|
||||
|
||||
export const assessmentRealResultOneOnePracticesMax = 5;
|
||||
|
||||
export const assessmentRealResultOneOneGapsItemDomainMax = 64;
|
||||
|
||||
|
||||
export const assessmentRealResultOneOneGapsItemDomainRegExp = new RegExp('^[a-z0-9_]+$');
|
||||
export const assessmentRealResultOneOneGapsItemTitleMax = 200;
|
||||
|
||||
export const assessmentRealResultOneOneGapsMax = 20;
|
||||
|
||||
export const assessmentRealResultOneOneDurationsItemsSecondsMin = 0;
|
||||
|
||||
export const assessmentRealResultOneOneDurationsPracticeSecondsMin = 0;
|
||||
|
||||
export const assessmentRealResultOneOneNextStepsMax = 5;
|
||||
|
||||
|
||||
export const assessmentRealResultTwoOneVersionsBankVersionMax = 64;
|
||||
|
||||
|
||||
export const assessmentRealResultTwoOneVersionsBankVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$');
|
||||
export const assessmentRealResultTwoOneVersionsAlgorithmVersionMax = 64;
|
||||
|
||||
|
||||
export const assessmentRealResultTwoOneVersionsAlgorithmVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$');
|
||||
export const assessmentRealResultTwoOneLimitationsMax = 10;
|
||||
|
||||
export const assessmentRealResultTwoOneUncertaintyOneStandardErrorMin = 0;
|
||||
|
||||
export const assessmentRealResultTwoOneUncertaintyOnePGradeMin = 0;
|
||||
export const assessmentRealResultTwoOneUncertaintyOnePGradeMax = 1;
|
||||
|
||||
export const assessmentRealResultTwoOneBasicScoreOnePointsMin = 0;
|
||||
|
||||
|
||||
|
||||
export const assessmentRealResultTwoOnePracticesItemVerdictScoreMin = 0;
|
||||
export const assessmentRealResultTwoOnePracticesItemVerdictScoreMax = 3;
|
||||
|
||||
export const assessmentRealResultTwoOnePracticesItemVerdictMaxScoreMin = 3;
|
||||
export const assessmentRealResultTwoOnePracticesItemVerdictMaxScoreMax = 3;
|
||||
|
||||
export const assessmentRealResultTwoOnePracticesItemVerdictGroupsItemGroupMax = 3;
|
||||
|
||||
export const assessmentRealResultTwoOnePracticesItemVerdictGroupsMin = 3;
|
||||
export const assessmentRealResultTwoOnePracticesItemVerdictGroupsMax = 3;
|
||||
|
||||
export const assessmentRealResultTwoOnePracticesMax = 5;
|
||||
|
||||
export const assessmentRealResultTwoOneGapsItemDomainMax = 64;
|
||||
|
||||
|
||||
export const assessmentRealResultTwoOneGapsItemDomainRegExp = new RegExp('^[a-z0-9_]+$');
|
||||
export const assessmentRealResultTwoOneGapsItemTitleMax = 200;
|
||||
|
||||
export const assessmentRealResultTwoOneGapsMax = 20;
|
||||
|
||||
export const assessmentRealResultTwoOneDurationsItemsSecondsMin = 0;
|
||||
|
||||
export const assessmentRealResultTwoOneDurationsPracticeSecondsMin = 0;
|
||||
|
||||
export const assessmentRealResultTwoOneNextStepsMax = 5;
|
||||
|
||||
|
||||
export const AssessmentRealResult = zod.union([zod.object({
|
||||
"attempt_id": zod.uuid(),
|
||||
"specialization": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'),
|
||||
"target_grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),
|
||||
"root_attempt_id": zod.union([zod.uuid(),zod.null()]).describe('Root attempt of a corrective check, or null when this is not a corrective result. The corrective attempt keeps this link.'),
|
||||
"chain_deadline": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('Immutable deadline shared by a corrective chain, or null when this result is not from a corrective check.'),
|
||||
"task_language": zod.union([zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.'),zod.null()]),
|
||||
"kind": zod.enum(['root', 'corrective']),
|
||||
"mode": zod.enum(['demo_basic', 'adaptive']),
|
||||
"versions": zod.object({
|
||||
"policy_version": zod.int().min(1).describe('Number of the `product` policy version whose assessment rules apply: thresholds, stop rules, item limits, time and session limits, and retry intervals.'),
|
||||
"bank_version": zod.string().min(1).max(assessmentRealResultOneOneVersionsBankVersionMax).regex(assessmentRealResultOneOneVersionsBankVersionRegExp).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(assessmentRealResultOneOneVersionsAlgorithmVersionMax).regex(assessmentRealResultOneOneVersionsAlgorithmVersionRegExp).describe('Opaque identifier of a published version, for example `backend-demo.2026-10.1`. Clients show it as text and never parse it.')
|
||||
}).describe('Versions fixed when the attempt was created. They never change during the attempt, and a result is always reproduced from the stored answers with these versions; a later policy, bank, or algorithm version does not rewrite it.'),
|
||||
"outcome": zod.enum(['confirmed', 'not_confirmed', 'not_determined']).describe('Grade decision of the attempt.\n\n- confirmed: the target grade is confirmed by the rule of the recorded policy version.\n- not_confirmed: the evidence is below the rule, including an adaptive attempt whose probability stayed below confirmation after the additional practice, or whose additional practice was declined or not submitted in time. The previously confirmed grade, if any, stays in force.\n- not_determined: the attempt gives no decision; `not_determined_reason` says why. The previously confirmed grade stays in force.\n\nA failed, expired, or flagged attempt never lowers a confirmed grade.'),
|
||||
"not_determined_reason": zod.union([zod.enum(['expired', 'practice_incomplete', 'insufficient_bank', 'sandbox_unavailable']).describe('Why an attempt gives no decision. One root quota slot is reserved when a real root attempt starts; corrective checks in its chain do not reserve another slot.\n\n- expired: the time or session limit passed before the candidate finished the item part. Retry timing follows the recorded policy; a correction uses the existing root slot and does not reset the chain deadline or 30/90-day timers.\n- practice_incomplete: the item part was done, but the candidate did not submit the main practice before the limit. Retry timing follows the recorded policy; a correction uses the existing root slot and does not reset the chain deadline or 30/90-day timers.\n- insufficient_bank: the bank could not supply required coverage. A preflight refusal creates no attempt or root slot; a bank failure in an existing chain does not create a free new chain or another root slot.\n- sandbox_unavailable: the latest submission of a required or additional practice ended `failed` because of the sandbox infrastructure, and the limit passed before a verdict. It is a platform fault and does not create a new root slot or a free chain.'),zod.null()]).describe('The reason when `outcome` is `not_determined`, otherwise null.'),
|
||||
"confirmed_grade": zod.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Grade that this attempt confirmed, the target grade, or null when it confirmed none. Together with the specialization it forms the category.'),
|
||||
"previous_confirmed_grade": zod.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Confirmed grade of the specialization before this attempt, or null. When the attempt confirmed nothing, this grade stays in force.'),
|
||||
"category_decision": zod.object({
|
||||
"status": zod.enum(['not_eligible', 'not_confirmed', 'assigned', 'unchanged']),
|
||||
"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()]),
|
||||
"current_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()]),
|
||||
"method": zod.union([zod.enum(['demo_basic_pass_mark']),zod.null()]),
|
||||
"source": zod.union([zod.enum(['synthetic_demo']),zod.null()]),
|
||||
"calibration_status": zod.union([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.'),zod.null()])
|
||||
}).exactOptional().describe('Category decision captured when this result was stored. It is absent from legacy v1 results because their current grade cannot be inferred later. It never exposes review identifiers, private answers, or the candidate\'s current category after this decision.'),
|
||||
"strength": zod.union([zod.enum(['high', 'medium']).describe('Strength of an adaptive confirmation: `high` or `medium`, by the probability bands of the recorded policy version.'),zod.null()]).describe('Strength of an adaptive confirmation, otherwise null.'),
|
||||
"calibration_status": zod.enum(['uncalibrated', 'calibrated']).describe('Whether the thresholds of the recorded policy version are empirically calibrated. `uncalibrated` results are provisional: their thresholds come from expert judgement, and their probabilities are not claimed to be calibrated.'),
|
||||
"limitations": zod.array(zod.enum(['uncalibrated_thresholds', 'demo_bank', 'practice_not_included', 'unproctored']).describe('Known limitation of the method behind a real-assessment result, shown with the result.\n\n- uncalibrated_thresholds: the thresholds are not yet validated on a pilot.\n- demo_bank: the result comes from the small reviewed demo bank.\n- practice_not_included: the attempt had no code practice because the sandbox was not enabled.\n- unproctored: the attempt was taken online without supervision.\nAdding a value is a contract change.')).max(assessmentRealResultOneOneLimitationsMax),
|
||||
"uncertainty": zod.union([zod.object({
|
||||
"theta": zod.number(),
|
||||
"standard_error": zod.number().min(assessmentRealResultOneOneUncertaintyOneStandardErrorMin),
|
||||
"interval_95": zod.object({
|
||||
"low": zod.number(),
|
||||
"high": zod.number()
|
||||
}).describe('Interval on the ability scale.'),
|
||||
"p_grade": zod.number().min(assessmentRealResultOneOneUncertaintyOnePGradeMin).max(assessmentRealResultOneOneUncertaintyOnePGradeMax).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(assessmentRealResultOneOneBasicScoreOnePointsMin),
|
||||
"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(assessmentRealResultOneOnePracticesItemVerdictScoreMin).max(assessmentRealResultOneOnePracticesItemVerdictScoreMax),
|
||||
"max_score": zod.int().min(assessmentRealResultOneOnePracticesItemVerdictMaxScoreMin).max(assessmentRealResultOneOnePracticesItemVerdictMaxScoreMax),
|
||||
"groups": zod.array(zod.object({
|
||||
"group": zod.int().min(1).max(assessmentRealResultOneOnePracticesItemVerdictGroupsItemGroupMax),
|
||||
"passed": zod.boolean()
|
||||
}).describe('Outcome of one hidden check group. It never contains the checks themselves.')).min(assessmentRealResultOneOnePracticesItemVerdictGroupsMin).max(assessmentRealResultOneOnePracticesItemVerdictGroupsMax)
|
||||
}).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(assessmentRealResultOneOnePracticesMax).describe('Verdicts of the practices that have one, main first.'),
|
||||
"gaps": zod.array(zod.object({
|
||||
"domain": zod.string().min(1).max(assessmentRealResultOneOneGapsItemDomainMax).regex(assessmentRealResultOneOneGapsItemDomainRegExp).describe('Stable domain code of the bank blueprint.'),
|
||||
"title": zod.string().min(1).max(assessmentRealResultOneOneGapsItemTitleMax).describe('Display name in Russian. Plain text.')
|
||||
}).describe('Domain of the specialization where the evidence was weak.')).max(assessmentRealResultOneOneGapsMax).describe('Domains with weak evidence; empty when none were found or the method finds none.'),
|
||||
"durations": zod.object({
|
||||
"items_seconds": zod.int().min(assessmentRealResultOneOneDurationsItemsSecondsMin),
|
||||
"practice_seconds": zod.int().min(assessmentRealResultOneOneDurationsPracticeSecondsMin).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(assessmentRealResultOneOneNextStepsMax),
|
||||
"decided_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.')
|
||||
}).describe('Immutable result of a real assessment, visible only to its candidate. It records the method, versions, decision, uncertainty, and limitations. A corrective result also carries root_attempt_id and chain_deadline from the same chain. Later policy, bank, or algorithm versions never change it. It never contains answers, per-item correctness, keys, seeds, hidden checks, or anti-cheat signals. Fields the method does not compute are null, never zero.').and(zod.object({
|
||||
"kind": zod.enum(['root']),
|
||||
"root_attempt_id": zod.null(),
|
||||
"chain_deadline": zod.null()
|
||||
})).and(zod.object({
|
||||
"kind": zod.enum(['root'])
|
||||
})).describe('Result of a real assessment that is not a corrective attempt. The correction-chain fields are explicitly null.'),zod.object({
|
||||
"attempt_id": zod.uuid(),
|
||||
"specialization": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'),
|
||||
"target_grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),
|
||||
"root_attempt_id": zod.union([zod.uuid(),zod.null()]).describe('Root attempt of a corrective check, or null when this is not a corrective result. The corrective attempt keeps this link.'),
|
||||
"chain_deadline": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('Immutable deadline shared by a corrective chain, or null when this result is not from a corrective check.'),
|
||||
"task_language": zod.union([zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.'),zod.null()]),
|
||||
"kind": zod.enum(['root', 'corrective']),
|
||||
"mode": zod.enum(['demo_basic', 'adaptive']),
|
||||
"versions": zod.object({
|
||||
"policy_version": zod.int().min(1).describe('Number of the `product` policy version whose assessment rules apply: thresholds, stop rules, item limits, time and session limits, and retry intervals.'),
|
||||
"bank_version": zod.string().min(1).max(assessmentRealResultTwoOneVersionsBankVersionMax).regex(assessmentRealResultTwoOneVersionsBankVersionRegExp).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(assessmentRealResultTwoOneVersionsAlgorithmVersionMax).regex(assessmentRealResultTwoOneVersionsAlgorithmVersionRegExp).describe('Opaque identifier of a published version, for example `backend-demo.2026-10.1`. Clients show it as text and never parse it.')
|
||||
}).describe('Versions fixed when the attempt was created. They never change during the attempt, and a result is always reproduced from the stored answers with these versions; a later policy, bank, or algorithm version does not rewrite it.'),
|
||||
"outcome": zod.enum(['confirmed', 'not_confirmed', 'not_determined']).describe('Grade decision of the attempt.\n\n- confirmed: the target grade is confirmed by the rule of the recorded policy version.\n- not_confirmed: the evidence is below the rule, including an adaptive attempt whose probability stayed below confirmation after the additional practice, or whose additional practice was declined or not submitted in time. The previously confirmed grade, if any, stays in force.\n- not_determined: the attempt gives no decision; `not_determined_reason` says why. The previously confirmed grade stays in force.\n\nA failed, expired, or flagged attempt never lowers a confirmed grade.'),
|
||||
"not_determined_reason": zod.union([zod.enum(['expired', 'practice_incomplete', 'insufficient_bank', 'sandbox_unavailable']).describe('Why an attempt gives no decision. One root quota slot is reserved when a real root attempt starts; corrective checks in its chain do not reserve another slot.\n\n- expired: the time or session limit passed before the candidate finished the item part. Retry timing follows the recorded policy; a correction uses the existing root slot and does not reset the chain deadline or 30/90-day timers.\n- practice_incomplete: the item part was done, but the candidate did not submit the main practice before the limit. Retry timing follows the recorded policy; a correction uses the existing root slot and does not reset the chain deadline or 30/90-day timers.\n- insufficient_bank: the bank could not supply required coverage. A preflight refusal creates no attempt or root slot; a bank failure in an existing chain does not create a free new chain or another root slot.\n- sandbox_unavailable: the latest submission of a required or additional practice ended `failed` because of the sandbox infrastructure, and the limit passed before a verdict. It is a platform fault and does not create a new root slot or a free chain.'),zod.null()]).describe('The reason when `outcome` is `not_determined`, otherwise null.'),
|
||||
"confirmed_grade": zod.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Grade that this attempt confirmed, the target grade, or null when it confirmed none. Together with the specialization it forms the category.'),
|
||||
"previous_confirmed_grade": zod.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Confirmed grade of the specialization before this attempt, or null. When the attempt confirmed nothing, this grade stays in force.'),
|
||||
"category_decision": zod.object({
|
||||
"status": zod.enum(['not_eligible', 'not_confirmed', 'assigned', 'unchanged']),
|
||||
"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()]),
|
||||
"current_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()]),
|
||||
"method": zod.union([zod.enum(['demo_basic_pass_mark']),zod.null()]),
|
||||
"source": zod.union([zod.enum(['synthetic_demo']),zod.null()]),
|
||||
"calibration_status": zod.union([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.'),zod.null()])
|
||||
}).exactOptional().describe('Category decision captured when this result was stored. It is absent from legacy v1 results because their current grade cannot be inferred later. It never exposes review identifiers, private answers, or the candidate\'s current category after this decision.'),
|
||||
"strength": zod.union([zod.enum(['high', 'medium']).describe('Strength of an adaptive confirmation: `high` or `medium`, by the probability bands of the recorded policy version.'),zod.null()]).describe('Strength of an adaptive confirmation, otherwise null.'),
|
||||
"calibration_status": zod.enum(['uncalibrated', 'calibrated']).describe('Whether the thresholds of the recorded policy version are empirically calibrated. `uncalibrated` results are provisional: their thresholds come from expert judgement, and their probabilities are not claimed to be calibrated.'),
|
||||
"limitations": zod.array(zod.enum(['uncalibrated_thresholds', 'demo_bank', 'practice_not_included', 'unproctored']).describe('Known limitation of the method behind a real-assessment result, shown with the result.\n\n- uncalibrated_thresholds: the thresholds are not yet validated on a pilot.\n- demo_bank: the result comes from the small reviewed demo bank.\n- practice_not_included: the attempt had no code practice because the sandbox was not enabled.\n- unproctored: the attempt was taken online without supervision.\nAdding a value is a contract change.')).max(assessmentRealResultTwoOneLimitationsMax),
|
||||
"uncertainty": zod.union([zod.object({
|
||||
"theta": zod.number(),
|
||||
"standard_error": zod.number().min(assessmentRealResultTwoOneUncertaintyOneStandardErrorMin),
|
||||
"interval_95": zod.object({
|
||||
"low": zod.number(),
|
||||
"high": zod.number()
|
||||
}).describe('Interval on the ability scale.'),
|
||||
"p_grade": zod.number().min(assessmentRealResultTwoOneUncertaintyOnePGradeMin).max(assessmentRealResultTwoOneUncertaintyOnePGradeMax).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(assessmentRealResultTwoOneBasicScoreOnePointsMin),
|
||||
"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(assessmentRealResultTwoOnePracticesItemVerdictScoreMin).max(assessmentRealResultTwoOnePracticesItemVerdictScoreMax),
|
||||
"max_score": zod.int().min(assessmentRealResultTwoOnePracticesItemVerdictMaxScoreMin).max(assessmentRealResultTwoOnePracticesItemVerdictMaxScoreMax),
|
||||
"groups": zod.array(zod.object({
|
||||
"group": zod.int().min(1).max(assessmentRealResultTwoOnePracticesItemVerdictGroupsItemGroupMax),
|
||||
"passed": zod.boolean()
|
||||
}).describe('Outcome of one hidden check group. It never contains the checks themselves.')).min(assessmentRealResultTwoOnePracticesItemVerdictGroupsMin).max(assessmentRealResultTwoOnePracticesItemVerdictGroupsMax)
|
||||
}).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(assessmentRealResultTwoOnePracticesMax).describe('Verdicts of the practices that have one, main first.'),
|
||||
"gaps": zod.array(zod.object({
|
||||
"domain": zod.string().min(1).max(assessmentRealResultTwoOneGapsItemDomainMax).regex(assessmentRealResultTwoOneGapsItemDomainRegExp).describe('Stable domain code of the bank blueprint.'),
|
||||
"title": zod.string().min(1).max(assessmentRealResultTwoOneGapsItemTitleMax).describe('Display name in Russian. Plain text.')
|
||||
}).describe('Domain of the specialization where the evidence was weak.')).max(assessmentRealResultTwoOneGapsMax).describe('Domains with weak evidence; empty when none were found or the method finds none.'),
|
||||
"durations": zod.object({
|
||||
"items_seconds": zod.int().min(assessmentRealResultTwoOneDurationsItemsSecondsMin),
|
||||
"practice_seconds": zod.int().min(assessmentRealResultTwoOneDurationsPracticeSecondsMin).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(assessmentRealResultTwoOneNextStepsMax),
|
||||
"decided_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.')
|
||||
}).describe('Immutable result of a real assessment, visible only to its candidate. It records the method, versions, decision, uncertainty, and limitations. A corrective result also carries root_attempt_id and chain_deadline from the same chain. Later policy, bank, or algorithm versions never change it. It never contains answers, per-item correctness, keys, seeds, hidden checks, or anti-cheat signals. Fields the method does not compute are null, never zero.').and(zod.object({
|
||||
"kind": zod.enum(['corrective']),
|
||||
"root_attempt_id": zod.uuid(),
|
||||
"chain_deadline": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.')
|
||||
})).and(zod.object({
|
||||
"kind": zod.enum(['corrective'])
|
||||
})).describe('Result of a corrective real assessment. Both chain fields are present and identify the same immutable correction chain.')]).describe('A completed root or corrective result. Training-only demo_express results are excluded from qualification history.')
|
||||
|
||||
export type AssessmentRealResult = zod.input<typeof AssessmentRealResult>;
|
||||
export type AssessmentRealResultOutput = zod.output<typeof AssessmentRealResult>;
|
||||
@@ -72,6 +72,14 @@ export const AssessmentRealResultCommon = zod.object({
|
||||
"not_determined_reason": zod.union([zod.enum(['expired', 'practice_incomplete', 'insufficient_bank', 'sandbox_unavailable']).describe('Why an attempt gives no decision. One root quota slot is reserved when a real root attempt starts; corrective checks in its chain do not reserve another slot.\n\n- expired: the time or session limit passed before the candidate finished the item part. Retry timing follows the recorded policy; a correction uses the existing root slot and does not reset the chain deadline or 30/90-day timers.\n- practice_incomplete: the item part was done, but the candidate did not submit the main practice before the limit. Retry timing follows the recorded policy; a correction uses the existing root slot and does not reset the chain deadline or 30/90-day timers.\n- insufficient_bank: the bank could not supply required coverage. A preflight refusal creates no attempt or root slot; a bank failure in an existing chain does not create a free new chain or another root slot.\n- sandbox_unavailable: the latest submission of a required or additional practice ended `failed` because of the sandbox infrastructure, and the limit passed before a verdict. It is a platform fault and does not create a new root slot or a free chain.'),zod.null()]).describe('The reason when `outcome` is `not_determined`, otherwise null.'),
|
||||
"confirmed_grade": zod.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Grade that this attempt confirmed, the target grade, or null when it confirmed none. Together with the specialization it forms the category.'),
|
||||
"previous_confirmed_grade": zod.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Confirmed grade of the specialization before this attempt, or null. When the attempt confirmed nothing, this grade stays in force.'),
|
||||
"category_decision": zod.object({
|
||||
"status": zod.enum(['not_eligible', 'not_confirmed', 'assigned', 'unchanged']),
|
||||
"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()]),
|
||||
"current_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()]),
|
||||
"method": zod.union([zod.enum(['demo_basic_pass_mark']),zod.null()]),
|
||||
"source": zod.union([zod.enum(['synthetic_demo']),zod.null()]),
|
||||
"calibration_status": zod.union([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.'),zod.null()])
|
||||
}).exactOptional().describe('Category decision captured when this result was stored. It is absent from legacy v1 results because their current grade cannot be inferred later. It never exposes review identifiers, private answers, or the candidate\'s current category after this decision.'),
|
||||
"strength": zod.union([zod.enum(['high', 'medium']).describe('Strength of an adaptive confirmation: `high` or `medium`, by the probability bands of the recorded policy version.'),zod.null()]).describe('Strength of an adaptive confirmation, otherwise null.'),
|
||||
"calibration_status": zod.enum(['uncalibrated', 'calibrated']).describe('Whether the thresholds of the recorded policy version are empirically calibrated. `uncalibrated` results are provisional: their thresholds come from expert judgement, and their probabilities are not claimed to be calibrated.'),
|
||||
"limitations": zod.array(zod.enum(['uncalibrated_thresholds', 'demo_bank', 'practice_not_included', 'unproctored']).describe('Known limitation of the method behind a real-assessment result, shown with the result.\n\n- uncalibrated_thresholds: the thresholds are not yet validated on a pilot.\n- demo_bank: the result comes from the small reviewed demo bank.\n- practice_not_included: the attempt had no code practice because the sandbox was not enabled.\n- unproctored: the attempt was taken online without supervision.\nAdding a value is a contract change.')).max(assessmentRealResultCommonLimitationsMax),
|
||||
|
||||
@@ -159,6 +159,14 @@ export const AssessmentResult = zod.union([zod.object({
|
||||
"not_determined_reason": zod.union([zod.enum(['expired', 'practice_incomplete', 'insufficient_bank', 'sandbox_unavailable']).describe('Why an attempt gives no decision. One root quota slot is reserved when a real root attempt starts; corrective checks in its chain do not reserve another slot.\n\n- expired: the time or session limit passed before the candidate finished the item part. Retry timing follows the recorded policy; a correction uses the existing root slot and does not reset the chain deadline or 30/90-day timers.\n- practice_incomplete: the item part was done, but the candidate did not submit the main practice before the limit. Retry timing follows the recorded policy; a correction uses the existing root slot and does not reset the chain deadline or 30/90-day timers.\n- insufficient_bank: the bank could not supply required coverage. A preflight refusal creates no attempt or root slot; a bank failure in an existing chain does not create a free new chain or another root slot.\n- sandbox_unavailable: the latest submission of a required or additional practice ended `failed` because of the sandbox infrastructure, and the limit passed before a verdict. It is a platform fault and does not create a new root slot or a free chain.'),zod.null()]).describe('The reason when `outcome` is `not_determined`, otherwise null.'),
|
||||
"confirmed_grade": zod.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Grade that this attempt confirmed, the target grade, or null when it confirmed none. Together with the specialization it forms the category.'),
|
||||
"previous_confirmed_grade": zod.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Confirmed grade of the specialization before this attempt, or null. When the attempt confirmed nothing, this grade stays in force.'),
|
||||
"category_decision": zod.object({
|
||||
"status": zod.enum(['not_eligible', 'not_confirmed', 'assigned', 'unchanged']),
|
||||
"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()]),
|
||||
"current_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()]),
|
||||
"method": zod.union([zod.enum(['demo_basic_pass_mark']),zod.null()]),
|
||||
"source": zod.union([zod.enum(['synthetic_demo']),zod.null()]),
|
||||
"calibration_status": zod.union([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.'),zod.null()])
|
||||
}).exactOptional().describe('Category decision captured when this result was stored. It is absent from legacy v1 results because their current grade cannot be inferred later. It never exposes review identifiers, private answers, or the candidate\'s current category after this decision.'),
|
||||
"strength": zod.union([zod.enum(['high', 'medium']).describe('Strength of an adaptive confirmation: `high` or `medium`, by the probability bands of the recorded policy version.'),zod.null()]).describe('Strength of an adaptive confirmation, otherwise null.'),
|
||||
"calibration_status": zod.enum(['uncalibrated', 'calibrated']).describe('Whether the thresholds of the recorded policy version are empirically calibrated. `uncalibrated` results are provisional: their thresholds come from expert judgement, and their probabilities are not claimed to be calibrated.'),
|
||||
"limitations": zod.array(zod.enum(['uncalibrated_thresholds', 'demo_bank', 'practice_not_included', 'unproctored']).describe('Known limitation of the method behind a real-assessment result, shown with the result.\n\n- uncalibrated_thresholds: the thresholds are not yet validated on a pilot.\n- demo_bank: the result comes from the small reviewed demo bank.\n- practice_not_included: the attempt had no code practice because the sandbox was not enabled.\n- unproctored: the attempt was taken online without supervision.\nAdding a value is a contract change.')).max(assessmentResultOneOneLimitationsMax),
|
||||
@@ -225,6 +233,14 @@ export const AssessmentResult = zod.union([zod.object({
|
||||
"not_determined_reason": zod.union([zod.enum(['expired', 'practice_incomplete', 'insufficient_bank', 'sandbox_unavailable']).describe('Why an attempt gives no decision. One root quota slot is reserved when a real root attempt starts; corrective checks in its chain do not reserve another slot.\n\n- expired: the time or session limit passed before the candidate finished the item part. Retry timing follows the recorded policy; a correction uses the existing root slot and does not reset the chain deadline or 30/90-day timers.\n- practice_incomplete: the item part was done, but the candidate did not submit the main practice before the limit. Retry timing follows the recorded policy; a correction uses the existing root slot and does not reset the chain deadline or 30/90-day timers.\n- insufficient_bank: the bank could not supply required coverage. A preflight refusal creates no attempt or root slot; a bank failure in an existing chain does not create a free new chain or another root slot.\n- sandbox_unavailable: the latest submission of a required or additional practice ended `failed` because of the sandbox infrastructure, and the limit passed before a verdict. It is a platform fault and does not create a new root slot or a free chain.'),zod.null()]).describe('The reason when `outcome` is `not_determined`, otherwise null.'),
|
||||
"confirmed_grade": zod.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Grade that this attempt confirmed, the target grade, or null when it confirmed none. Together with the specialization it forms the category.'),
|
||||
"previous_confirmed_grade": zod.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Confirmed grade of the specialization before this attempt, or null. When the attempt confirmed nothing, this grade stays in force.'),
|
||||
"category_decision": zod.object({
|
||||
"status": zod.enum(['not_eligible', 'not_confirmed', 'assigned', 'unchanged']),
|
||||
"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()]),
|
||||
"current_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()]),
|
||||
"method": zod.union([zod.enum(['demo_basic_pass_mark']),zod.null()]),
|
||||
"source": zod.union([zod.enum(['synthetic_demo']),zod.null()]),
|
||||
"calibration_status": zod.union([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.'),zod.null()])
|
||||
}).exactOptional().describe('Category decision captured when this result was stored. It is absent from legacy v1 results because their current grade cannot be inferred later. It never exposes review identifiers, private answers, or the candidate\'s current category after this decision.'),
|
||||
"strength": zod.union([zod.enum(['high', 'medium']).describe('Strength of an adaptive confirmation: `high` or `medium`, by the probability bands of the recorded policy version.'),zod.null()]).describe('Strength of an adaptive confirmation, otherwise null.'),
|
||||
"calibration_status": zod.enum(['uncalibrated', 'calibrated']).describe('Whether the thresholds of the recorded policy version are empirically calibrated. `uncalibrated` results are provisional: their thresholds come from expert judgement, and their probabilities are not claimed to be calibrated.'),
|
||||
"limitations": zod.array(zod.enum(['uncalibrated_thresholds', 'demo_bank', 'practice_not_included', 'unproctored']).describe('Known limitation of the method behind a real-assessment result, shown with the result.\n\n- uncalibrated_thresholds: the thresholds are not yet validated on a pilot.\n- demo_bank: the result comes from the small reviewed demo bank.\n- practice_not_included: the attempt had no code practice because the sandbox was not enabled.\n- unproctored: the attempt was taken online without supervision.\nAdding a value is a contract change.')).max(assessmentResultTwoOneLimitationsMax),
|
||||
|
||||
@@ -0,0 +1,267 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
|
||||
export const assessmentResultHistoryPageItemsItemOneOneVersionsBankVersionMax = 64;
|
||||
|
||||
|
||||
export const assessmentResultHistoryPageItemsItemOneOneVersionsBankVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$');
|
||||
export const assessmentResultHistoryPageItemsItemOneOneVersionsAlgorithmVersionMax = 64;
|
||||
|
||||
|
||||
export const assessmentResultHistoryPageItemsItemOneOneVersionsAlgorithmVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$');
|
||||
export const assessmentResultHistoryPageItemsItemOneOneLimitationsMax = 10;
|
||||
|
||||
export const assessmentResultHistoryPageItemsItemOneOneUncertaintyOneStandardErrorMin = 0;
|
||||
|
||||
export const assessmentResultHistoryPageItemsItemOneOneUncertaintyOnePGradeMin = 0;
|
||||
export const assessmentResultHistoryPageItemsItemOneOneUncertaintyOnePGradeMax = 1;
|
||||
|
||||
export const assessmentResultHistoryPageItemsItemOneOneBasicScoreOnePointsMin = 0;
|
||||
|
||||
|
||||
|
||||
export const assessmentResultHistoryPageItemsItemOneOnePracticesItemVerdictScoreMin = 0;
|
||||
export const assessmentResultHistoryPageItemsItemOneOnePracticesItemVerdictScoreMax = 3;
|
||||
|
||||
export const assessmentResultHistoryPageItemsItemOneOnePracticesItemVerdictMaxScoreMin = 3;
|
||||
export const assessmentResultHistoryPageItemsItemOneOnePracticesItemVerdictMaxScoreMax = 3;
|
||||
|
||||
export const assessmentResultHistoryPageItemsItemOneOnePracticesItemVerdictGroupsItemGroupMax = 3;
|
||||
|
||||
export const assessmentResultHistoryPageItemsItemOneOnePracticesItemVerdictGroupsMin = 3;
|
||||
export const assessmentResultHistoryPageItemsItemOneOnePracticesItemVerdictGroupsMax = 3;
|
||||
|
||||
export const assessmentResultHistoryPageItemsItemOneOnePracticesMax = 5;
|
||||
|
||||
export const assessmentResultHistoryPageItemsItemOneOneGapsItemDomainMax = 64;
|
||||
|
||||
|
||||
export const assessmentResultHistoryPageItemsItemOneOneGapsItemDomainRegExp = new RegExp('^[a-z0-9_]+$');
|
||||
export const assessmentResultHistoryPageItemsItemOneOneGapsItemTitleMax = 200;
|
||||
|
||||
export const assessmentResultHistoryPageItemsItemOneOneGapsMax = 20;
|
||||
|
||||
export const assessmentResultHistoryPageItemsItemOneOneDurationsItemsSecondsMin = 0;
|
||||
|
||||
export const assessmentResultHistoryPageItemsItemOneOneDurationsPracticeSecondsMin = 0;
|
||||
|
||||
export const assessmentResultHistoryPageItemsItemOneOneNextStepsMax = 5;
|
||||
|
||||
|
||||
export const assessmentResultHistoryPageItemsItemTwoOneVersionsBankVersionMax = 64;
|
||||
|
||||
|
||||
export const assessmentResultHistoryPageItemsItemTwoOneVersionsBankVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$');
|
||||
export const assessmentResultHistoryPageItemsItemTwoOneVersionsAlgorithmVersionMax = 64;
|
||||
|
||||
|
||||
export const assessmentResultHistoryPageItemsItemTwoOneVersionsAlgorithmVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$');
|
||||
export const assessmentResultHistoryPageItemsItemTwoOneLimitationsMax = 10;
|
||||
|
||||
export const assessmentResultHistoryPageItemsItemTwoOneUncertaintyOneStandardErrorMin = 0;
|
||||
|
||||
export const assessmentResultHistoryPageItemsItemTwoOneUncertaintyOnePGradeMin = 0;
|
||||
export const assessmentResultHistoryPageItemsItemTwoOneUncertaintyOnePGradeMax = 1;
|
||||
|
||||
export const assessmentResultHistoryPageItemsItemTwoOneBasicScoreOnePointsMin = 0;
|
||||
|
||||
|
||||
|
||||
export const assessmentResultHistoryPageItemsItemTwoOnePracticesItemVerdictScoreMin = 0;
|
||||
export const assessmentResultHistoryPageItemsItemTwoOnePracticesItemVerdictScoreMax = 3;
|
||||
|
||||
export const assessmentResultHistoryPageItemsItemTwoOnePracticesItemVerdictMaxScoreMin = 3;
|
||||
export const assessmentResultHistoryPageItemsItemTwoOnePracticesItemVerdictMaxScoreMax = 3;
|
||||
|
||||
export const assessmentResultHistoryPageItemsItemTwoOnePracticesItemVerdictGroupsItemGroupMax = 3;
|
||||
|
||||
export const assessmentResultHistoryPageItemsItemTwoOnePracticesItemVerdictGroupsMin = 3;
|
||||
export const assessmentResultHistoryPageItemsItemTwoOnePracticesItemVerdictGroupsMax = 3;
|
||||
|
||||
export const assessmentResultHistoryPageItemsItemTwoOnePracticesMax = 5;
|
||||
|
||||
export const assessmentResultHistoryPageItemsItemTwoOneGapsItemDomainMax = 64;
|
||||
|
||||
|
||||
export const assessmentResultHistoryPageItemsItemTwoOneGapsItemDomainRegExp = new RegExp('^[a-z0-9_]+$');
|
||||
export const assessmentResultHistoryPageItemsItemTwoOneGapsItemTitleMax = 200;
|
||||
|
||||
export const assessmentResultHistoryPageItemsItemTwoOneGapsMax = 20;
|
||||
|
||||
export const assessmentResultHistoryPageItemsItemTwoOneDurationsItemsSecondsMin = 0;
|
||||
|
||||
export const assessmentResultHistoryPageItemsItemTwoOneDurationsPracticeSecondsMin = 0;
|
||||
|
||||
export const assessmentResultHistoryPageItemsItemTwoOneNextStepsMax = 5;
|
||||
|
||||
export const assessmentResultHistoryPageItemsMax = 50;
|
||||
|
||||
export const assessmentResultHistoryPagePageNextCursorMax = 512;
|
||||
|
||||
|
||||
export const assessmentResultHistoryPagePageNextCursorRegExp = new RegExp('^[A-Za-z0-9_-]+$');
|
||||
|
||||
export const AssessmentResultHistoryPage = zod.object({
|
||||
"items": zod.array(zod.union([zod.object({
|
||||
"attempt_id": zod.uuid(),
|
||||
"specialization": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'),
|
||||
"target_grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),
|
||||
"root_attempt_id": zod.union([zod.uuid(),zod.null()]).describe('Root attempt of a corrective check, or null when this is not a corrective result. The corrective attempt keeps this link.'),
|
||||
"chain_deadline": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('Immutable deadline shared by a corrective chain, or null when this result is not from a corrective check.'),
|
||||
"task_language": zod.union([zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.'),zod.null()]),
|
||||
"kind": zod.enum(['root', 'corrective']),
|
||||
"mode": zod.enum(['demo_basic', 'adaptive']),
|
||||
"versions": zod.object({
|
||||
"policy_version": zod.int().min(1).describe('Number of the `product` policy version whose assessment rules apply: thresholds, stop rules, item limits, time and session limits, and retry intervals.'),
|
||||
"bank_version": zod.string().min(1).max(assessmentResultHistoryPageItemsItemOneOneVersionsBankVersionMax).regex(assessmentResultHistoryPageItemsItemOneOneVersionsBankVersionRegExp).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(assessmentResultHistoryPageItemsItemOneOneVersionsAlgorithmVersionMax).regex(assessmentResultHistoryPageItemsItemOneOneVersionsAlgorithmVersionRegExp).describe('Opaque identifier of a published version, for example `backend-demo.2026-10.1`. Clients show it as text and never parse it.')
|
||||
}).describe('Versions fixed when the attempt was created. They never change during the attempt, and a result is always reproduced from the stored answers with these versions; a later policy, bank, or algorithm version does not rewrite it.'),
|
||||
"outcome": zod.enum(['confirmed', 'not_confirmed', 'not_determined']).describe('Grade decision of the attempt.\n\n- confirmed: the target grade is confirmed by the rule of the recorded policy version.\n- not_confirmed: the evidence is below the rule, including an adaptive attempt whose probability stayed below confirmation after the additional practice, or whose additional practice was declined or not submitted in time. The previously confirmed grade, if any, stays in force.\n- not_determined: the attempt gives no decision; `not_determined_reason` says why. The previously confirmed grade stays in force.\n\nA failed, expired, or flagged attempt never lowers a confirmed grade.'),
|
||||
"not_determined_reason": zod.union([zod.enum(['expired', 'practice_incomplete', 'insufficient_bank', 'sandbox_unavailable']).describe('Why an attempt gives no decision. One root quota slot is reserved when a real root attempt starts; corrective checks in its chain do not reserve another slot.\n\n- expired: the time or session limit passed before the candidate finished the item part. Retry timing follows the recorded policy; a correction uses the existing root slot and does not reset the chain deadline or 30/90-day timers.\n- practice_incomplete: the item part was done, but the candidate did not submit the main practice before the limit. Retry timing follows the recorded policy; a correction uses the existing root slot and does not reset the chain deadline or 30/90-day timers.\n- insufficient_bank: the bank could not supply required coverage. A preflight refusal creates no attempt or root slot; a bank failure in an existing chain does not create a free new chain or another root slot.\n- sandbox_unavailable: the latest submission of a required or additional practice ended `failed` because of the sandbox infrastructure, and the limit passed before a verdict. It is a platform fault and does not create a new root slot or a free chain.'),zod.null()]).describe('The reason when `outcome` is `not_determined`, otherwise null.'),
|
||||
"confirmed_grade": zod.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Grade that this attempt confirmed, the target grade, or null when it confirmed none. Together with the specialization it forms the category.'),
|
||||
"previous_confirmed_grade": zod.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Confirmed grade of the specialization before this attempt, or null. When the attempt confirmed nothing, this grade stays in force.'),
|
||||
"category_decision": zod.object({
|
||||
"status": zod.enum(['not_eligible', 'not_confirmed', 'assigned', 'unchanged']),
|
||||
"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()]),
|
||||
"current_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()]),
|
||||
"method": zod.union([zod.enum(['demo_basic_pass_mark']),zod.null()]),
|
||||
"source": zod.union([zod.enum(['synthetic_demo']),zod.null()]),
|
||||
"calibration_status": zod.union([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.'),zod.null()])
|
||||
}).exactOptional().describe('Category decision captured when this result was stored. It is absent from legacy v1 results because their current grade cannot be inferred later. It never exposes review identifiers, private answers, or the candidate\'s current category after this decision.'),
|
||||
"strength": zod.union([zod.enum(['high', 'medium']).describe('Strength of an adaptive confirmation: `high` or `medium`, by the probability bands of the recorded policy version.'),zod.null()]).describe('Strength of an adaptive confirmation, otherwise null.'),
|
||||
"calibration_status": zod.enum(['uncalibrated', 'calibrated']).describe('Whether the thresholds of the recorded policy version are empirically calibrated. `uncalibrated` results are provisional: their thresholds come from expert judgement, and their probabilities are not claimed to be calibrated.'),
|
||||
"limitations": zod.array(zod.enum(['uncalibrated_thresholds', 'demo_bank', 'practice_not_included', 'unproctored']).describe('Known limitation of the method behind a real-assessment result, shown with the result.\n\n- uncalibrated_thresholds: the thresholds are not yet validated on a pilot.\n- demo_bank: the result comes from the small reviewed demo bank.\n- practice_not_included: the attempt had no code practice because the sandbox was not enabled.\n- unproctored: the attempt was taken online without supervision.\nAdding a value is a contract change.')).max(assessmentResultHistoryPageItemsItemOneOneLimitationsMax),
|
||||
"uncertainty": zod.union([zod.object({
|
||||
"theta": zod.number(),
|
||||
"standard_error": zod.number().min(assessmentResultHistoryPageItemsItemOneOneUncertaintyOneStandardErrorMin),
|
||||
"interval_95": zod.object({
|
||||
"low": zod.number(),
|
||||
"high": zod.number()
|
||||
}).describe('Interval on the ability scale.'),
|
||||
"p_grade": zod.number().min(assessmentResultHistoryPageItemsItemOneOneUncertaintyOnePGradeMin).max(assessmentResultHistoryPageItemsItemOneOneUncertaintyOnePGradeMax).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(assessmentResultHistoryPageItemsItemOneOneBasicScoreOnePointsMin),
|
||||
"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(assessmentResultHistoryPageItemsItemOneOnePracticesItemVerdictScoreMin).max(assessmentResultHistoryPageItemsItemOneOnePracticesItemVerdictScoreMax),
|
||||
"max_score": zod.int().min(assessmentResultHistoryPageItemsItemOneOnePracticesItemVerdictMaxScoreMin).max(assessmentResultHistoryPageItemsItemOneOnePracticesItemVerdictMaxScoreMax),
|
||||
"groups": zod.array(zod.object({
|
||||
"group": zod.int().min(1).max(assessmentResultHistoryPageItemsItemOneOnePracticesItemVerdictGroupsItemGroupMax),
|
||||
"passed": zod.boolean()
|
||||
}).describe('Outcome of one hidden check group. It never contains the checks themselves.')).min(assessmentResultHistoryPageItemsItemOneOnePracticesItemVerdictGroupsMin).max(assessmentResultHistoryPageItemsItemOneOnePracticesItemVerdictGroupsMax)
|
||||
}).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(assessmentResultHistoryPageItemsItemOneOnePracticesMax).describe('Verdicts of the practices that have one, main first.'),
|
||||
"gaps": zod.array(zod.object({
|
||||
"domain": zod.string().min(1).max(assessmentResultHistoryPageItemsItemOneOneGapsItemDomainMax).regex(assessmentResultHistoryPageItemsItemOneOneGapsItemDomainRegExp).describe('Stable domain code of the bank blueprint.'),
|
||||
"title": zod.string().min(1).max(assessmentResultHistoryPageItemsItemOneOneGapsItemTitleMax).describe('Display name in Russian. Plain text.')
|
||||
}).describe('Domain of the specialization where the evidence was weak.')).max(assessmentResultHistoryPageItemsItemOneOneGapsMax).describe('Domains with weak evidence; empty when none were found or the method finds none.'),
|
||||
"durations": zod.object({
|
||||
"items_seconds": zod.int().min(assessmentResultHistoryPageItemsItemOneOneDurationsItemsSecondsMin),
|
||||
"practice_seconds": zod.int().min(assessmentResultHistoryPageItemsItemOneOneDurationsPracticeSecondsMin).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(assessmentResultHistoryPageItemsItemOneOneNextStepsMax),
|
||||
"decided_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.')
|
||||
}).describe('Immutable result of a real assessment, visible only to its candidate. It records the method, versions, decision, uncertainty, and limitations. A corrective result also carries root_attempt_id and chain_deadline from the same chain. Later policy, bank, or algorithm versions never change it. It never contains answers, per-item correctness, keys, seeds, hidden checks, or anti-cheat signals. Fields the method does not compute are null, never zero.').and(zod.object({
|
||||
"kind": zod.enum(['root']),
|
||||
"root_attempt_id": zod.null(),
|
||||
"chain_deadline": zod.null()
|
||||
})).and(zod.object({
|
||||
"kind": zod.enum(['root'])
|
||||
})).describe('Result of a real assessment that is not a corrective attempt. The correction-chain fields are explicitly null.'),zod.object({
|
||||
"attempt_id": zod.uuid(),
|
||||
"specialization": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'),
|
||||
"target_grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),
|
||||
"root_attempt_id": zod.union([zod.uuid(),zod.null()]).describe('Root attempt of a corrective check, or null when this is not a corrective result. The corrective attempt keeps this link.'),
|
||||
"chain_deadline": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('Immutable deadline shared by a corrective chain, or null when this result is not from a corrective check.'),
|
||||
"task_language": zod.union([zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.'),zod.null()]),
|
||||
"kind": zod.enum(['root', 'corrective']),
|
||||
"mode": zod.enum(['demo_basic', 'adaptive']),
|
||||
"versions": zod.object({
|
||||
"policy_version": zod.int().min(1).describe('Number of the `product` policy version whose assessment rules apply: thresholds, stop rules, item limits, time and session limits, and retry intervals.'),
|
||||
"bank_version": zod.string().min(1).max(assessmentResultHistoryPageItemsItemTwoOneVersionsBankVersionMax).regex(assessmentResultHistoryPageItemsItemTwoOneVersionsBankVersionRegExp).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(assessmentResultHistoryPageItemsItemTwoOneVersionsAlgorithmVersionMax).regex(assessmentResultHistoryPageItemsItemTwoOneVersionsAlgorithmVersionRegExp).describe('Opaque identifier of a published version, for example `backend-demo.2026-10.1`. Clients show it as text and never parse it.')
|
||||
}).describe('Versions fixed when the attempt was created. They never change during the attempt, and a result is always reproduced from the stored answers with these versions; a later policy, bank, or algorithm version does not rewrite it.'),
|
||||
"outcome": zod.enum(['confirmed', 'not_confirmed', 'not_determined']).describe('Grade decision of the attempt.\n\n- confirmed: the target grade is confirmed by the rule of the recorded policy version.\n- not_confirmed: the evidence is below the rule, including an adaptive attempt whose probability stayed below confirmation after the additional practice, or whose additional practice was declined or not submitted in time. The previously confirmed grade, if any, stays in force.\n- not_determined: the attempt gives no decision; `not_determined_reason` says why. The previously confirmed grade stays in force.\n\nA failed, expired, or flagged attempt never lowers a confirmed grade.'),
|
||||
"not_determined_reason": zod.union([zod.enum(['expired', 'practice_incomplete', 'insufficient_bank', 'sandbox_unavailable']).describe('Why an attempt gives no decision. One root quota slot is reserved when a real root attempt starts; corrective checks in its chain do not reserve another slot.\n\n- expired: the time or session limit passed before the candidate finished the item part. Retry timing follows the recorded policy; a correction uses the existing root slot and does not reset the chain deadline or 30/90-day timers.\n- practice_incomplete: the item part was done, but the candidate did not submit the main practice before the limit. Retry timing follows the recorded policy; a correction uses the existing root slot and does not reset the chain deadline or 30/90-day timers.\n- insufficient_bank: the bank could not supply required coverage. A preflight refusal creates no attempt or root slot; a bank failure in an existing chain does not create a free new chain or another root slot.\n- sandbox_unavailable: the latest submission of a required or additional practice ended `failed` because of the sandbox infrastructure, and the limit passed before a verdict. It is a platform fault and does not create a new root slot or a free chain.'),zod.null()]).describe('The reason when `outcome` is `not_determined`, otherwise null.'),
|
||||
"confirmed_grade": zod.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Grade that this attempt confirmed, the target grade, or null when it confirmed none. Together with the specialization it forms the category.'),
|
||||
"previous_confirmed_grade": zod.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Confirmed grade of the specialization before this attempt, or null. When the attempt confirmed nothing, this grade stays in force.'),
|
||||
"category_decision": zod.object({
|
||||
"status": zod.enum(['not_eligible', 'not_confirmed', 'assigned', 'unchanged']),
|
||||
"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()]),
|
||||
"current_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()]),
|
||||
"method": zod.union([zod.enum(['demo_basic_pass_mark']),zod.null()]),
|
||||
"source": zod.union([zod.enum(['synthetic_demo']),zod.null()]),
|
||||
"calibration_status": zod.union([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.'),zod.null()])
|
||||
}).exactOptional().describe('Category decision captured when this result was stored. It is absent from legacy v1 results because their current grade cannot be inferred later. It never exposes review identifiers, private answers, or the candidate\'s current category after this decision.'),
|
||||
"strength": zod.union([zod.enum(['high', 'medium']).describe('Strength of an adaptive confirmation: `high` or `medium`, by the probability bands of the recorded policy version.'),zod.null()]).describe('Strength of an adaptive confirmation, otherwise null.'),
|
||||
"calibration_status": zod.enum(['uncalibrated', 'calibrated']).describe('Whether the thresholds of the recorded policy version are empirically calibrated. `uncalibrated` results are provisional: their thresholds come from expert judgement, and their probabilities are not claimed to be calibrated.'),
|
||||
"limitations": zod.array(zod.enum(['uncalibrated_thresholds', 'demo_bank', 'practice_not_included', 'unproctored']).describe('Known limitation of the method behind a real-assessment result, shown with the result.\n\n- uncalibrated_thresholds: the thresholds are not yet validated on a pilot.\n- demo_bank: the result comes from the small reviewed demo bank.\n- practice_not_included: the attempt had no code practice because the sandbox was not enabled.\n- unproctored: the attempt was taken online without supervision.\nAdding a value is a contract change.')).max(assessmentResultHistoryPageItemsItemTwoOneLimitationsMax),
|
||||
"uncertainty": zod.union([zod.object({
|
||||
"theta": zod.number(),
|
||||
"standard_error": zod.number().min(assessmentResultHistoryPageItemsItemTwoOneUncertaintyOneStandardErrorMin),
|
||||
"interval_95": zod.object({
|
||||
"low": zod.number(),
|
||||
"high": zod.number()
|
||||
}).describe('Interval on the ability scale.'),
|
||||
"p_grade": zod.number().min(assessmentResultHistoryPageItemsItemTwoOneUncertaintyOnePGradeMin).max(assessmentResultHistoryPageItemsItemTwoOneUncertaintyOnePGradeMax).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(assessmentResultHistoryPageItemsItemTwoOneBasicScoreOnePointsMin),
|
||||
"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(assessmentResultHistoryPageItemsItemTwoOnePracticesItemVerdictScoreMin).max(assessmentResultHistoryPageItemsItemTwoOnePracticesItemVerdictScoreMax),
|
||||
"max_score": zod.int().min(assessmentResultHistoryPageItemsItemTwoOnePracticesItemVerdictMaxScoreMin).max(assessmentResultHistoryPageItemsItemTwoOnePracticesItemVerdictMaxScoreMax),
|
||||
"groups": zod.array(zod.object({
|
||||
"group": zod.int().min(1).max(assessmentResultHistoryPageItemsItemTwoOnePracticesItemVerdictGroupsItemGroupMax),
|
||||
"passed": zod.boolean()
|
||||
}).describe('Outcome of one hidden check group. It never contains the checks themselves.')).min(assessmentResultHistoryPageItemsItemTwoOnePracticesItemVerdictGroupsMin).max(assessmentResultHistoryPageItemsItemTwoOnePracticesItemVerdictGroupsMax)
|
||||
}).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(assessmentResultHistoryPageItemsItemTwoOnePracticesMax).describe('Verdicts of the practices that have one, main first.'),
|
||||
"gaps": zod.array(zod.object({
|
||||
"domain": zod.string().min(1).max(assessmentResultHistoryPageItemsItemTwoOneGapsItemDomainMax).regex(assessmentResultHistoryPageItemsItemTwoOneGapsItemDomainRegExp).describe('Stable domain code of the bank blueprint.'),
|
||||
"title": zod.string().min(1).max(assessmentResultHistoryPageItemsItemTwoOneGapsItemTitleMax).describe('Display name in Russian. Plain text.')
|
||||
}).describe('Domain of the specialization where the evidence was weak.')).max(assessmentResultHistoryPageItemsItemTwoOneGapsMax).describe('Domains with weak evidence; empty when none were found or the method finds none.'),
|
||||
"durations": zod.object({
|
||||
"items_seconds": zod.int().min(assessmentResultHistoryPageItemsItemTwoOneDurationsItemsSecondsMin),
|
||||
"practice_seconds": zod.int().min(assessmentResultHistoryPageItemsItemTwoOneDurationsPracticeSecondsMin).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(assessmentResultHistoryPageItemsItemTwoOneNextStepsMax),
|
||||
"decided_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.')
|
||||
}).describe('Immutable result of a real assessment, visible only to its candidate. It records the method, versions, decision, uncertainty, and limitations. A corrective result also carries root_attempt_id and chain_deadline from the same chain. Later policy, bank, or algorithm versions never change it. It never contains answers, per-item correctness, keys, seeds, hidden checks, or anti-cheat signals. Fields the method does not compute are null, never zero.').and(zod.object({
|
||||
"kind": zod.enum(['corrective']),
|
||||
"root_attempt_id": zod.uuid(),
|
||||
"chain_deadline": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.')
|
||||
})).and(zod.object({
|
||||
"kind": zod.enum(['corrective'])
|
||||
})).describe('Result of a corrective real assessment. Both chain fields are present and identify the same immutable correction chain.')]).describe('A completed root or corrective result. Training-only demo_express results are excluded from qualification history.')).max(assessmentResultHistoryPageItemsMax),
|
||||
"page": zod.object({
|
||||
"has_more": zod.boolean().describe('Whether another page follows this one.'),
|
||||
"next_cursor": zod.string().min(1).max(assessmentResultHistoryPagePageNextCursorMax).regex(assessmentResultHistoryPagePageNextCursorRegExp).nullable().describe('Opaque cursor of the next page, or null on the last page. Clients must not parse, build, or store it beyond the current listing.')
|
||||
}).describe('Cursor pagination state of a list response. Lists are ordered by a stable server-defined key. To read the next page, repeat the request with the same filters and `cursor` set to `next_cursor`.')
|
||||
}).describe('Owner-only immutable root and corrective results ordered by decided_at and attempt_id descending. Legacy v1 results omit category_decision.')
|
||||
|
||||
export type AssessmentResultHistoryPage = zod.input<typeof AssessmentResultHistoryPage>;
|
||||
export type AssessmentResultHistoryPageOutput = zod.output<typeof AssessmentResultHistoryPage>;
|
||||
@@ -16,6 +16,7 @@ export * from './assessmentAttemptSessionStart.zod';
|
||||
export * from './assessmentAttemptState.zod';
|
||||
export * from './assessmentAttemptVersion.zod';
|
||||
export * from './assessmentAvailability.zod';
|
||||
export * from './assessmentCategoryDecisionView.zod';
|
||||
export * from './assessmentClipboardSignal.zod';
|
||||
export * from './assessmentCorrectiveAttempt.zod';
|
||||
export * from './assessmentCorrectiveAttemptCreate.zod';
|
||||
@@ -49,8 +50,10 @@ export * from './assessmentQualifiedAttempt.zod';
|
||||
export * from './assessmentQualifiedAttemptCreate.zod';
|
||||
export * from './assessmentQualifiedResult.zod';
|
||||
export * from './assessmentRealMode.zod';
|
||||
export * from './assessmentRealResult.zod';
|
||||
export * from './assessmentRealResultCommon.zod';
|
||||
export * from './assessmentResult.zod';
|
||||
export * from './assessmentResultHistoryPage.zod';
|
||||
export * from './assessmentSessions.zod';
|
||||
export * from './assessmentSignalBatch.zod';
|
||||
export * from './assessmentSignalEvent.zod';
|
||||
@@ -77,6 +80,7 @@ export * from './finalizeMyAssessmentAttemptHeaders.zod';
|
||||
export * from './findErrorAnswer.zod';
|
||||
export * from './findErrorItemContent.zod';
|
||||
export * from './itemContent.zod';
|
||||
export * from './listMyAssessmentResultsParams.zod';
|
||||
export * from './numberAnswer.zod';
|
||||
export * from './numberItemContent.zod';
|
||||
export * from './orderAnswer.zod';
|
||||
|
||||
@@ -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 listMyAssessmentResultsParamsLimitDefault = 20;
|
||||
export const listMyAssessmentResultsParamsLimitMax = 50;
|
||||
|
||||
export const listMyAssessmentResultsParamsCursorMax = 512;
|
||||
|
||||
|
||||
export const listMyAssessmentResultsParamsCursorRegExp = new RegExp('^[A-Za-z0-9_-]+$');
|
||||
|
||||
export const ListMyAssessmentResultsParams = zod.object({
|
||||
"limit": zod.int().min(1).max(listMyAssessmentResultsParamsLimitMax).default(listMyAssessmentResultsParamsLimitDefault),
|
||||
"cursor": zod.string().min(1).max(listMyAssessmentResultsParamsCursorMax).regex(listMyAssessmentResultsParamsCursorRegExp).exactOptional()
|
||||
})
|
||||
|
||||
export type ListMyAssessmentResultsParams = zod.input<typeof ListMyAssessmentResultsParams>;
|
||||
export type ListMyAssessmentResultsParamsOutput = zod.output<typeof ListMyAssessmentResultsParams>;
|
||||
Reference in new issue
Block a user