feat(evidence): project skill evidence from confirmed assessments
This commit is contained in:
1 parent
4761508f13
commit
c2a8d17195
94 files changed
+10077
-151
No files matched your search
+22
-1
@@ -262,7 +262,7 @@ The signal notice (`assessment-signal-notice`) lists the signals collected durin
|
||||
Access:
|
||||
|
||||
- The candidate comes only from the session; no operation takes a candidate identifier. An employer account answers 403 `forbidden`. An attempt of another candidate answers 404 `not_found`, the same as an unknown identifier, so attempt identifiers cannot be probed.
|
||||
- No operation offers an employer answers, qualification evidence, attempt history, or anti-cheat signals. Employers will see only the current category through a separate projection.
|
||||
- No operation offers an employer answers, attempt history, or anti-cheat signals. Employers see the current category on the anonymous card and the permitted skill evidence of that card ([Skill evidence](#skill-evidence)), never a result.
|
||||
|
||||
Modes and versions:
|
||||
|
||||
@@ -697,6 +697,27 @@ Open questions for the product owner and the lawyer:
|
||||
|
||||
No new problem code is added. `TestPrivacyOperationsFollowTheConventions`, `TestPublicationAndSearchStatusAreNotConsents`, `TestAnonymousCardReachesNoProfileOrContactSchema`, `TestGeneratedPrivacyDTOsCarryNoServerOwnedFields`, `TestPrivacySchemaValidationPrecedesImplementation`, and `TestPrivacyAccessBeforeImplementation` pin the generated server and the bundle, and `frontend/src/shared/api/privacy-contract.test.ts` pins the generated Zod rules, the absence of a consent, a time, a contact, or a salary in the request and card types, and the absence of settings in the organization, invitation, need, profile, and consent files.
|
||||
|
||||
### Skill evidence
|
||||
|
||||
The tag `evidence` describes the facts that confirmed assessments leave about a candidate's skills (FR06 in the PRD). It has two read operations; the logic behind them is implemented (see [architecture](../docs/en/ARCHITECTURE.md#skill-evidence)).
|
||||
|
||||
| Method and path | operationId | Protection | Success | Specific errors |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `GET /api/v1/me/evidence` | `ListMyEvidence` | session | 200 `EvidenceFactList`, `Cache-Control: no-store` | 400, 401, 403 `forbidden` |
|
||||
| `GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}/evidence` | `GetOrganizationCandidateEvidence` | session | 200 `OrganizationEvidence`, `Cache-Control: no-store` | 400, 401, 403, 404 `not_found`, 429 |
|
||||
|
||||
Each operation also declares the problem response `default`. No new problem code is added.
|
||||
|
||||
- One event is one fact. `EvidenceFact` is a source event; `skills` are the tags of that event (a non-empty set), so a second tag never makes a second fact. `source` names the event and the immutable result (`event_id` and `result_id`, equal for an assessment because a result is keyed by its attempt; the candidate opens it at `GetMyAssessmentResult`).
|
||||
- A claim is not a measurement. `kind` is `claim` (trust 0) or `measurement` (trust 1 to 3). `EvidenceTrustLevel` is an integer from 0 to 3; an online assessment without a reliable confirmation of the identity is trust 1, and repetition never raises it. Only measurements from assessments are produced today.
|
||||
- What a fact says is `result`: the grade that was passed, the `basis` (`synthetic_demo`), and the `calibration_status` (`uncalibrated`), so the candidate never reads a demonstration category as a validated measurement. The organization projection and the preview carry both labels as well. A fact has no score, answer, item, failed attempt, or anti-cheat datum, and a failed attempt, a result without a reviewed category source, and a `demo_express` run produce no fact.
|
||||
- `ListMyEvidence` lists only the caller's facts, newest event first, hidden facts included (`visibility` `hidden`), with the shared `limit` (1 to 100, default 20) and an opaque `cursor` bound to the candidate. A malformed or foreign cursor and a limit out of range answer 400; an employer account answers 403.
|
||||
- `GetOrganizationCandidateEvidence` is a section of the anonymous card. It answers only while `GetOrganizationCandidateCard` would answer for the same handle and the card shows at least one category; every other case (unknown handle, handle of another organization, closed or revoked publication, hidden organization, minimum cohort, card without categories) is the same 404, so the answer reveals nothing the card does not. For each category of the card it returns one `OrganizationEvidenceFact`: the earliest visible assessment that passed exactly the confirmed grade, with only `skill`, `grade`, `trust`, `observed_year` (the year, UTC), and `basis` and `calibration_status` (`synthetic_demo`, `uncalibrated`; the same for every candidate, so they add no fingerprint and say the fact is a demonstration). A lower grade, a retake, the other tags, the source, the basis, the month, and every identifier stay with the candidate; at most nine facts, ordered by skill, and a hidden fact is absent. No key joins the answer to a person, but it is not unlinkable: with the other values of the card, the skill, grade, trust, and year can narrow a small pool, and the minimum cohort does not cover the year. The read consumes the card-view quota and appears in the access history with the field `categories`.
|
||||
- The preview. `CardPreview.evidence` is the same section computed for the candidate (`OrganizationEvidence`, or null exactly when `card` is null), so the candidate sees what an organization would read with the `categories` field. It applies no organization or cohort, so an organization can receive less.
|
||||
- Closed schemas and the privacy walk. Every evidence object has `additionalProperties: false` and requires all its properties. `TestNoOrganizationOperationReachesRawAssessmentData` (Go) and `test_evidence_is_closed_and_no_organization_operation_reaches_raw_assessment_data` (Python) walk every organization operation and `ListMyEvidence` through all references and fail on an assessment, signal, or review schema or on a raw answer, score, or failure property.
|
||||
|
||||
Open questions: whether the C2 consent text needs a new version now that publishing `categories` also sends one supporting assessment fact (skill, grade, trust level, year) to an organization - a decision for the owner and the lawyer, and the consent texts are not changed here; whether the evidence needs its own card field instead of the `categories` field; whether the year is the right precision for an employer; an operation for the candidate to hide or show a fact (the stored visibility exists, no operation changes it); and when claims of the profile and facts from other sources join the list.
|
||||
|
||||
### Generator checks
|
||||
|
||||
`testdata/openapi-3.2.0.yml` contains test operations that use the components above: pagination, Idempotency-Key, If-Match, ETag, and problem responses. ogen does not resolve external references, so the fixture keeps copies of the api/core components; `scripts/test_contract_copies.py` (part of `make -C api check`) checks that they, the fixture responses, and the ML `Problem` copy match api/core.
|
||||
|
||||
+22
-1
@@ -262,7 +262,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro
|
||||
Доступ:
|
||||
|
||||
- Кандидат берется только из сессии; ни одна операция не принимает идентификатор кандидата. Аккаунт работодателя получает 403 `forbidden`. Попытка другого кандидата дает 404 `not_found`, как и неизвестный идентификатор, поэтому идентификаторы попыток нельзя перебирать.
|
||||
- Ни одна операция не дает работодателю ответы, квалификационные данные, историю попыток или античит-сигналы. Работодатель будет видеть только текущую категорию через отдельную проекцию.
|
||||
- Ни одна операция не дает работодателю ответы, историю попыток или античит-сигналы. Работодатель видит текущую категорию в анонимной карточке и разрешенные доказательства навыков этой карточки ([Доказательства навыков](#доказательства-навыков)), но не результат.
|
||||
|
||||
Режимы и версии:
|
||||
|
||||
@@ -697,6 +697,27 @@ ML-сервис отвечает на ошибки той же схемой `Pro
|
||||
|
||||
Новый код problem не добавляется. `TestPrivacyOperationsFollowTheConventions`, `TestPublicationAndSearchStatusAreNotConsents`, `TestAnonymousCardReachesNoProfileOrContactSchema`, `TestGeneratedPrivacyDTOsCarryNoServerOwnedFields`, `TestPrivacySchemaValidationPrecedesImplementation` и `TestPrivacyAccessBeforeImplementation` закрепляют сгенерированный сервер и бандл, а `frontend/src/shared/api/privacy-contract.test.ts` - сгенерированные правила Zod, отсутствие согласия, времени, контакта и зарплаты в типах запросов и карточки и отсутствие настроек в файлах организации, приглашения, потребности, профиля и согласий.
|
||||
|
||||
### Доказательства навыков
|
||||
|
||||
Тег `evidence` описывает факты, которые подтвержденные оценки оставляют о навыках кандидата (FR06 в PRD). В нем две операции чтения; логика за ними реализована (см. [архитектуру](../docs/ru/ARCHITECTURE.md#доказательства-навыков)).
|
||||
|
||||
| Метод и путь | operationId | Защита | Успех | Специфичные ошибки |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `GET /api/v1/me/evidence` | `ListMyEvidence` | сессия | 200 `EvidenceFactList`, `Cache-Control: no-store` | 400, 401, 403 `forbidden` |
|
||||
| `GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}/evidence` | `GetOrganizationCandidateEvidence` | сессия | 200 `OrganizationEvidence`, `Cache-Control: no-store` | 400, 401, 403, 404 `not_found`, 429 |
|
||||
|
||||
Каждая операция также объявляет проблемный ответ `default`. Новых кодов проблем нет.
|
||||
|
||||
- Одно событие - один факт. `EvidenceFact` - это событие-источник; `skills` - теги этого события (непустое множество), поэтому второй тег не создает второй факт. `source` называет событие и неизменяемый результат (`event_id` и `result_id`, для оценки они равны, так как результат ключуется попыткой; кандидат открывает его через `GetMyAssessmentResult`).
|
||||
- Заявление не равно измерению. `kind` равен `claim` (доверие 0) или `measurement` (доверие 1-3). `EvidenceTrustLevel` - целое от 0 до 3; онлайн-оценка без надежного подтверждения личности имеет доверие 1 и повторами не растет. Сейчас создаются только измерения из оценок.
|
||||
- Что говорит факт, лежит в `result`: пройденный грейд, `basis` (`synthetic_demo`) и `calibration_status` (`uncalibrated`), поэтому кандидат не принимает демонстрационную категорию за проверенное измерение. Проекция для организации и предпросмотр тоже несут обе метки. В факте нет балла, ответа, задания, проваленной попытки и античит-данных; проваленная попытка, результат без проверенного источника категории и прогон `demo_express` фактов не создают.
|
||||
- `ListMyEvidence` возвращает только факты вызывающего, новые события первыми, включая скрытые (`visibility` `hidden`), с общим `limit` (1-100, по умолчанию 20) и непрозрачным `cursor`, привязанным к кандидату. Неверный или чужой курсор и `limit` вне диапазона дают 400; аккаунт работодателя получает 403.
|
||||
- `GetOrganizationCandidateEvidence` - раздел анонимной карточки. Он отвечает, только пока на тот же handle ответил бы `GetOrganizationCandidateCard` и карточка показывает хотя бы одну категорию; любой другой случай (неизвестный handle, handle другой организации, закрытая или отозванная публикация, скрытая организация, минимальная когорта, карточка без категорий) дает один и тот же 404, поэтому ответ не раскрывает то, чего не раскрывает карточка. На каждую категорию карточки возвращается один `OrganizationEvidenceFact`: самая ранняя видимая оценка, прошедшая ровно подтвержденный грейд, и только `skill`, `grade`, `trust`, `observed_year` (год, UTC), а также `basis` и `calibration_status` (`synthetic_demo`, `uncalibrated`; одинаковы для всех кандидатов, поэтому отпечатка не добавляют и сообщают, что факт - демонстрация). Более низкий грейд, пересдача, остальные теги, источник, основание, месяц и все идентификаторы остаются у кандидата; не более девяти фактов, по порядку навыков; скрытого факта нет. Ключа, который привязывает ответ к человеку, нет, но он не является несвязываемым: вместе с другими значениями карточки навык, грейд, доверие и год могут сузить малый пул, а минимальная когорта год не покрывает. Чтение расходует квоту просмотров карточек и попадает в историю доступа с полем `categories`.
|
||||
- Предпросмотр. `CardPreview.evidence` - тот же раздел, посчитанный для кандидата (`OrganizationEvidence`, либо null ровно тогда, когда `card` равен null), поэтому кандидат видит, что организация прочтет вместе с полем `categories`. Организация и когорта не применяются, так что организация может получить меньше.
|
||||
- Закрытые схемы и обход приватности. У каждого объекта доказательств `additionalProperties: false`, и все его свойства обязательны. `TestNoOrganizationOperationReachesRawAssessmentData` (Go) и `test_evidence_is_closed_and_no_organization_operation_reaches_raw_assessment_data` (Python) обходят все организационные операции и `ListMyEvidence` по всем ссылкам и падают на схеме оценки, сигнала или проверки и на свойстве с сырым ответом, баллом или провалом.
|
||||
|
||||
Открытые вопросы: нужна ли новая версия текста согласия C2, раз публикация `categories` теперь отправляет организации еще один подтверждающий факт оценки (навык, грейд, уровень доверия, год) - решение владельца продукта и юриста, тексты согласий здесь не меняются; нужно ли доказательствам собственное поле карточки вместо поля `categories`; подходит ли работодателю точность в один год; операция скрыть или показать факт для кандидата (сохраненная видимость есть, операции для ее изменения нет); когда в список добавятся заявления профиля и факты из других источников.
|
||||
|
||||
### Проверки генераторов
|
||||
|
||||
`testdata/openapi-3.2.0.yml` содержит тестовые операции с перечисленными компонентами: пагинацией, Idempotency-Key, If-Match, ETag и problem-ответами. ogen не разрешает внешние ссылки, поэтому фикстура хранит копии компонентов api/core; `scripts/test_contract_copies.py` (входит в `make -C api check`) проверяет, что они, ответы фикстуры и ML-копия `Problem` совпадают с api/core.
|
||||
|
||||
@@ -4385,6 +4385,14 @@ PublishedCardPreview:
|
||||
experience_band: "1_3"
|
||||
work_formats: null
|
||||
salary_compatibility: null
|
||||
evidence:
|
||||
items:
|
||||
- skill: backend
|
||||
grade: middle
|
||||
trust: 1
|
||||
basis: synthetic_demo
|
||||
calibration_status: uncalibrated
|
||||
observed_year: 2026
|
||||
generated_at: "2026-10-06T09:30:00Z"
|
||||
OrganizationAnonymousCandidateCard:
|
||||
summary: An anonymous card currently visible to one organization
|
||||
@@ -4408,6 +4416,7 @@ ClosedCardPreview:
|
||||
state: closed
|
||||
fields: []
|
||||
card: null
|
||||
evidence: null
|
||||
generated_at: "2026-10-06T09:30:00Z"
|
||||
PrivacyEventListPage:
|
||||
summary: A publication, a hiding, and a confirmed status
|
||||
@@ -4455,6 +4464,40 @@ CardAccessListPage:
|
||||
page:
|
||||
has_more: false
|
||||
next_cursor: null
|
||||
EvidenceFactListPage:
|
||||
summary: A confirmed junior backend result with one fact and two tags of the same event
|
||||
value:
|
||||
items:
|
||||
- id: 01928f7a-d1e2-7f3a-8b4c-5d6e7f8a9b01
|
||||
kind: measurement
|
||||
source:
|
||||
type: assessment_result
|
||||
event_id: 01928f7a-e1f2-7a3b-8c4d-5e6f7a8b9c01
|
||||
result_id: 01928f7a-e1f2-7a3b-8c4d-5e6f7a8b9c01
|
||||
skills:
|
||||
- backend
|
||||
- go
|
||||
result:
|
||||
grade: junior
|
||||
basis: synthetic_demo
|
||||
calibration_status: uncalibrated
|
||||
attribution: personal
|
||||
trust: 1
|
||||
occurred_at: "2026-10-08T10:15:00Z"
|
||||
visibility: visible
|
||||
page:
|
||||
has_more: false
|
||||
next_cursor: null
|
||||
OrganizationCandidateEvidence:
|
||||
summary: The one supporting assessment fact of the category on the card
|
||||
value:
|
||||
items:
|
||||
- skill: backend
|
||||
grade: junior
|
||||
trust: 1
|
||||
basis: synthetic_demo
|
||||
calibration_status: uncalibrated
|
||||
observed_year: 2026
|
||||
PrivacyStaleVersion:
|
||||
summary: The change carried a stale expected_version
|
||||
description: The setting changed, for example in another tab, after the client read it. Nothing was changed; the client reads the settings again and reapplies its edit.
|
||||
|
||||
@@ -3312,6 +3312,246 @@ ContactDisclosure:
|
||||
oneOf:
|
||||
- $ref: '#/ContactTelegramUsername'
|
||||
- type: 'null'
|
||||
EvidenceKind:
|
||||
type: string
|
||||
description: 'Whether a fact is a statement or an observation.
|
||||
|
||||
|
||||
- claim: something the candidate stated that nothing confirmed separately. Its trust is 0.
|
||||
|
||||
- measurement: a result that a system observed, such as a confirmed assessment. Its trust is 1 to 3.
|
||||
|
||||
|
||||
Assessments produce measurements only. A claim never becomes a measurement by repetition, and the two kinds are stored apart.'
|
||||
enum:
|
||||
- claim
|
||||
- measurement
|
||||
EvidenceSourceType:
|
||||
type: string
|
||||
description: 'Where the fact comes from.
|
||||
|
||||
|
||||
- assessment_result: a real (root or corrective) assessment result of this platform that confirmed a grade. An express training run (`demo_express`), a failed attempt, and a result without a reviewed category source are never a source.
|
||||
|
||||
|
||||
Adding a value is a contract change.'
|
||||
enum:
|
||||
- assessment_result
|
||||
EvidenceAttribution:
|
||||
type: string
|
||||
description: 'Whose contribution the fact is.
|
||||
|
||||
|
||||
- personal: the candidate''s own result. Every assessment fact is personal.
|
||||
|
||||
- team_role: a team result with a confirmed role of the candidate.
|
||||
|
||||
- team_unattributed: a team result without a confirmed role; it is not a personal skill.
|
||||
|
||||
|
||||
Only `personal` is produced today.'
|
||||
enum:
|
||||
- personal
|
||||
- team_role
|
||||
- team_unattributed
|
||||
EvidenceTrustLevel:
|
||||
type: integer
|
||||
format: int32
|
||||
minimum: 0
|
||||
maximum: 3
|
||||
description: 'Strength of the confirmation.
|
||||
|
||||
|
||||
- 0: stated by the person, not confirmed separately.
|
||||
|
||||
- 1: an observable online result without a reliable confirmation of the identity or the authorship. Every assessment fact has this level today, because the assessment is unproctored and the identity is not confirmed.
|
||||
|
||||
- 2: a result tied to a confirmed identity or confirmed by an independent party.
|
||||
|
||||
- 3: an in-person check with a matching confirmation.
|
||||
|
||||
|
||||
A repeated statement, a sign-in, or a repeated tag of the same event never raises the level.'
|
||||
examples:
|
||||
- 1
|
||||
EvidenceVisibility:
|
||||
type: string
|
||||
description: 'Whether the fact may take part in what an organization reads.
|
||||
|
||||
|
||||
- visible: the fact is eligible for the organization projection. It does not publish the fact: the projection also needs the published card with the `categories` field and an active C2.
|
||||
|
||||
- hidden: the candidate hid the fact. No organization reads it. Hiding never edits or deletes the confirmed result.'
|
||||
enum:
|
||||
- visible
|
||||
- hidden
|
||||
EvidenceSkillCode:
|
||||
type: string
|
||||
description: A skill tag from a closed set - the specialization codes of the catalog and the technology codes of the anonymous card. An assessment tags its fact with the specialization of the category.
|
||||
enum:
|
||||
- backend
|
||||
- frontend
|
||||
- mobile
|
||||
- network_engineer
|
||||
- devops_sre
|
||||
- data_analyst
|
||||
- ds_ml
|
||||
- information_security
|
||||
- qa
|
||||
- go
|
||||
- postgresql
|
||||
- kafka
|
||||
- docker
|
||||
EvidenceBasis:
|
||||
type: string
|
||||
description: 'What the measurement rests on.
|
||||
|
||||
|
||||
- synthetic_demo: a demonstration category from a synthetic reviewed bank. It shows the mechanics and is not a validated measurement.'
|
||||
enum:
|
||||
- synthetic_demo
|
||||
EvidenceCalibrationStatus:
|
||||
type: string
|
||||
description: 'Calibration of the method behind the result.
|
||||
|
||||
|
||||
- uncalibrated: the thresholds are initial values that no measurement has validated.'
|
||||
enum:
|
||||
- uncalibrated
|
||||
EvidenceResult:
|
||||
type: object
|
||||
description: 'What the fact says: the grade that was passed and how reliable the method is. It carries no score, answer, item, failure, or anti-cheat data.'
|
||||
additionalProperties: false
|
||||
required:
|
||||
- grade
|
||||
- basis
|
||||
- calibration_status
|
||||
properties:
|
||||
grade:
|
||||
$ref: '#/GradeCode'
|
||||
basis:
|
||||
$ref: '#/EvidenceBasis'
|
||||
calibration_status:
|
||||
$ref: '#/EvidenceCalibrationStatus'
|
||||
EvidenceSource:
|
||||
type: object
|
||||
description: Where the fact comes from. For an assessment the event is the attempt and the result is the immutable result of that attempt, which the candidate reads at `GetMyAssessmentResult`; the two identifiers are equal because a result is keyed by its attempt.
|
||||
additionalProperties: false
|
||||
required:
|
||||
- type
|
||||
- event_id
|
||||
- result_id
|
||||
properties:
|
||||
type:
|
||||
$ref: '#/EvidenceSourceType'
|
||||
event_id:
|
||||
type: string
|
||||
format: uuid
|
||||
description: Identifier of the source event. One event is one fact, however many skills it is tagged with.
|
||||
result_id:
|
||||
type: string
|
||||
format: uuid
|
||||
description: Identifier of the immutable result that produced the fact.
|
||||
EvidenceFact:
|
||||
type: object
|
||||
description: One independent fact of the current candidate. `occurred_at` is when the source event ended; for an assessment it is the time of the decision. A fact is one source event; the skills of that event are tags of the fact, so a second tag never makes a second fact. Hidden facts are listed here with their visibility, because the candidate owns them.
|
||||
additionalProperties: false
|
||||
required:
|
||||
- id
|
||||
- kind
|
||||
- source
|
||||
- skills
|
||||
- result
|
||||
- attribution
|
||||
- trust
|
||||
- occurred_at
|
||||
- visibility
|
||||
properties:
|
||||
id:
|
||||
type: string
|
||||
format: uuid
|
||||
description: Identifier of the fact.
|
||||
kind:
|
||||
$ref: '#/EvidenceKind'
|
||||
source:
|
||||
$ref: '#/EvidenceSource'
|
||||
skills:
|
||||
type: array
|
||||
minItems: 1
|
||||
maxItems: 13
|
||||
uniqueItems: true
|
||||
description: Skill tags of the event in ascending order.
|
||||
items:
|
||||
$ref: '#/EvidenceSkillCode'
|
||||
result:
|
||||
$ref: '#/EvidenceResult'
|
||||
attribution:
|
||||
$ref: '#/EvidenceAttribution'
|
||||
trust:
|
||||
$ref: '#/EvidenceTrustLevel'
|
||||
occurred_at:
|
||||
$ref: '#/Timestamp'
|
||||
visibility:
|
||||
$ref: '#/EvidenceVisibility'
|
||||
EvidenceFactList:
|
||||
type: object
|
||||
description: One page of the facts of the current candidate, newest event first.
|
||||
additionalProperties: false
|
||||
required:
|
||||
- items
|
||||
- page
|
||||
properties:
|
||||
items:
|
||||
type: array
|
||||
maxItems: 100
|
||||
description: Facts of the page.
|
||||
items:
|
||||
$ref: '#/EvidenceFact'
|
||||
page:
|
||||
$ref: '#/PageInfo'
|
||||
OrganizationEvidenceFact:
|
||||
type: object
|
||||
description: 'The one assessment fact that supports a category of the card as an organization reads it: the earliest visible measurement that passed exactly the confirmed grade of that category. A lower grade, a retake, the other tags of the event, the source, the basis, the exact time, and every identifier stay with the candidate. The fact carries no identifier of the fact, the event, the result, or the candidate, so it cannot be joined to a person by a key. It is not unlinkable: the skill, the grade, the trust level, and the year, together with the other values of the card, can narrow a small pool of candidates, and the minimum cohort of the card does not cover the year. `basis` and `calibration_status` are the same for every candidate: they say that the fact comes from a synthetic demonstration and is not calibrated, so a demonstration is never read as a validated measurement. The fact never carries an answer, score, item, failure, signal, or review band.'
|
||||
additionalProperties: false
|
||||
required:
|
||||
- skill
|
||||
- grade
|
||||
- trust
|
||||
- basis
|
||||
- calibration_status
|
||||
- observed_year
|
||||
properties:
|
||||
skill:
|
||||
$ref: '#/EvidenceSkillCode'
|
||||
grade:
|
||||
$ref: '#/GradeCode'
|
||||
trust:
|
||||
$ref: '#/EvidenceTrustLevel'
|
||||
basis:
|
||||
$ref: '#/EvidenceBasis'
|
||||
calibration_status:
|
||||
$ref: '#/EvidenceCalibrationStatus'
|
||||
observed_year:
|
||||
type: integer
|
||||
format: int32
|
||||
minimum: 2000
|
||||
maximum: 9999
|
||||
description: Year (UTC) when the assessment ended. The month, day, and time stay with the candidate.
|
||||
examples:
|
||||
- 2026
|
||||
OrganizationEvidence:
|
||||
type: object
|
||||
description: 'The permitted evidence of one candidate card, ordered by skill: at most one fact for each category of the card (at most nine). The list is empty when no visible fact supports a category of the card.'
|
||||
additionalProperties: false
|
||||
required:
|
||||
- items
|
||||
properties:
|
||||
items:
|
||||
type: array
|
||||
maxItems: 9
|
||||
description: Permitted facts, one for each supported category.
|
||||
items:
|
||||
$ref: '#/OrganizationEvidenceFact'
|
||||
HealthResponse:
|
||||
type: object
|
||||
additionalProperties: false
|
||||
@@ -6201,7 +6441,7 @@ CardField:
|
||||
description: 'A group of values of the anonymous candidate card that the candidate chooses to publish. The set is closed and has no value for the full name, a contact, or the lowest salary: the card never carries them, so no choice and no later contract change in this list can publish them by accident. Contacts leave only through the contact grant of an accepted invitation (C4), and the lowest salary never leaves.
|
||||
|
||||
|
||||
- categories: specialization and grade confirmed by an authoritative assessment result.
|
||||
- categories: specialization and grade confirmed by an authoritative assessment result. With it an organization receives the confirmed category and, with each category of the card, one supporting assessment fact: its skill, the passed grade, the trust level, the year of the assessment, and the basis and calibration that mark a synthetic, uncalibrated demonstration (`GetOrganizationCandidateEvidence`). The candidate sees the same on `GetMyCardPreview`.
|
||||
|
||||
- self_assessment: the candidate''s declared specialization and grade, separate from confirmed categories.
|
||||
|
||||
@@ -6558,12 +6798,13 @@ AnonymousCardContent:
|
||||
description: Nullable compatibility result with no salary values.
|
||||
CardPreview:
|
||||
type: object
|
||||
description: A private candidate preview computed from the current profile, publication, and consent ledger. Its pseudonym uses a separate preview context and is not an organization's alias. Organization-specific visibility filters and cohort checks can further generalize or suppress the organization-facing card. This read creates no view or history record and never reaches an organization. `card` is null while the profile is closed.
|
||||
description: A private candidate preview computed from the current profile, publication, and consent ledger. Its pseudonym uses a separate preview context and is not an organization's alias. Organization-specific visibility filters and cohort checks can further generalize or suppress the organization-facing card. This read creates no view or history record and never reaches an organization. `card` is null while the profile is closed. `evidence` is what an organization would read in the evidence section of the card, one supporting assessment fact for each category of the card, and is null exactly when `card` is null; the organization-facing section can still be generalized or suppressed.
|
||||
additionalProperties: false
|
||||
required:
|
||||
- state
|
||||
- fields
|
||||
- card
|
||||
- evidence
|
||||
- generated_at
|
||||
properties:
|
||||
state:
|
||||
@@ -6574,6 +6815,10 @@ CardPreview:
|
||||
oneOf:
|
||||
- $ref: '#/AnonymousCardContent'
|
||||
- type: 'null'
|
||||
evidence:
|
||||
oneOf:
|
||||
- $ref: '#/OrganizationEvidence'
|
||||
- type: 'null'
|
||||
generated_at:
|
||||
$ref: '#/Timestamp'
|
||||
PrivacyEventKind:
|
||||
|
||||
@@ -0,0 +1,258 @@
|
||||
schemas:
|
||||
EvidenceKind:
|
||||
type: string
|
||||
description: |-
|
||||
Whether a fact is a statement or an observation.
|
||||
|
||||
- claim: something the candidate stated that nothing confirmed separately. Its trust is 0.
|
||||
- measurement: a result that a system observed, such as a confirmed assessment. Its trust is 1 to 3.
|
||||
|
||||
Assessments produce measurements only. A claim never becomes a measurement by repetition, and the two kinds are stored apart.
|
||||
enum:
|
||||
- claim
|
||||
- measurement
|
||||
EvidenceSourceType:
|
||||
type: string
|
||||
description: |-
|
||||
Where the fact comes from.
|
||||
|
||||
- assessment_result: a real (root or corrective) assessment result of this platform that confirmed a grade. An express training run (`demo_express`), a failed attempt, and a result without a reviewed category source are never a source.
|
||||
|
||||
Adding a value is a contract change.
|
||||
enum:
|
||||
- assessment_result
|
||||
EvidenceAttribution:
|
||||
type: string
|
||||
description: |-
|
||||
Whose contribution the fact is.
|
||||
|
||||
- personal: the candidate's own result. Every assessment fact is personal.
|
||||
- team_role: a team result with a confirmed role of the candidate.
|
||||
- team_unattributed: a team result without a confirmed role; it is not a personal skill.
|
||||
|
||||
Only `personal` is produced today.
|
||||
enum:
|
||||
- personal
|
||||
- team_role
|
||||
- team_unattributed
|
||||
EvidenceTrustLevel:
|
||||
type: integer
|
||||
format: int32
|
||||
minimum: 0
|
||||
maximum: 3
|
||||
description: |-
|
||||
Strength of the confirmation.
|
||||
|
||||
- 0: stated by the person, not confirmed separately.
|
||||
- 1: an observable online result without a reliable confirmation of the identity or the authorship. Every assessment fact has this level today, because the assessment is unproctored and the identity is not confirmed.
|
||||
- 2: a result tied to a confirmed identity or confirmed by an independent party.
|
||||
- 3: an in-person check with a matching confirmation.
|
||||
|
||||
A repeated statement, a sign-in, or a repeated tag of the same event never raises the level.
|
||||
examples:
|
||||
- 1
|
||||
EvidenceVisibility:
|
||||
type: string
|
||||
description: |-
|
||||
Whether the fact may take part in what an organization reads.
|
||||
|
||||
- visible: the fact is eligible for the organization projection. It does not publish the fact: the projection also needs the published card with the `categories` field and an active C2.
|
||||
- hidden: the candidate hid the fact. No organization reads it. Hiding never edits or deletes the confirmed result.
|
||||
enum:
|
||||
- visible
|
||||
- hidden
|
||||
EvidenceSkillCode:
|
||||
type: string
|
||||
description: A skill tag from a closed set - the specialization codes of the catalog and the technology codes of the anonymous card. An assessment tags its fact with the specialization of the category.
|
||||
enum:
|
||||
- backend
|
||||
- frontend
|
||||
- mobile
|
||||
- network_engineer
|
||||
- devops_sre
|
||||
- data_analyst
|
||||
- ds_ml
|
||||
- information_security
|
||||
- qa
|
||||
- go
|
||||
- postgresql
|
||||
- kafka
|
||||
- docker
|
||||
EvidenceBasis:
|
||||
type: string
|
||||
description: |-
|
||||
What the measurement rests on.
|
||||
|
||||
- synthetic_demo: a demonstration category from a synthetic reviewed bank. It shows the mechanics and is not a validated measurement.
|
||||
enum:
|
||||
- synthetic_demo
|
||||
EvidenceCalibrationStatus:
|
||||
type: string
|
||||
description: |-
|
||||
Calibration of the method behind the result.
|
||||
|
||||
- uncalibrated: the thresholds are initial values that no measurement has validated.
|
||||
enum:
|
||||
- uncalibrated
|
||||
EvidenceResult:
|
||||
type: object
|
||||
description: >-
|
||||
What the fact says: the grade that was passed and how reliable the method
|
||||
is. It carries no score, answer, item, failure, or anti-cheat data.
|
||||
additionalProperties: false
|
||||
required:
|
||||
- grade
|
||||
- basis
|
||||
- calibration_status
|
||||
properties:
|
||||
grade:
|
||||
$ref: "./catalog_schemas.yml#/schemas/GradeCode"
|
||||
basis:
|
||||
$ref: "#/schemas/EvidenceBasis"
|
||||
calibration_status:
|
||||
$ref: "#/schemas/EvidenceCalibrationStatus"
|
||||
EvidenceSource:
|
||||
type: object
|
||||
description: >-
|
||||
Where the fact comes from. For an assessment the event is the attempt
|
||||
and the result is the immutable result of that attempt, which the
|
||||
candidate reads at `GetMyAssessmentResult`; the two identifiers are
|
||||
equal because a result is keyed by its attempt.
|
||||
additionalProperties: false
|
||||
required:
|
||||
- type
|
||||
- event_id
|
||||
- result_id
|
||||
properties:
|
||||
type:
|
||||
$ref: "#/schemas/EvidenceSourceType"
|
||||
event_id:
|
||||
type: string
|
||||
format: uuid
|
||||
description: Identifier of the source event. One event is one fact, however many skills it is tagged with.
|
||||
result_id:
|
||||
type: string
|
||||
format: uuid
|
||||
description: Identifier of the immutable result that produced the fact.
|
||||
EvidenceFact:
|
||||
type: object
|
||||
description: >-
|
||||
One independent fact of the current candidate. `occurred_at` is when
|
||||
the source event ended; for an assessment it is the time of the
|
||||
decision. A fact is one source event; the skills of that event are tags of the fact, so a second tag
|
||||
never makes a second fact. Hidden facts are listed here with their
|
||||
visibility, because the candidate owns them.
|
||||
additionalProperties: false
|
||||
required:
|
||||
- id
|
||||
- kind
|
||||
- source
|
||||
- skills
|
||||
- result
|
||||
- attribution
|
||||
- trust
|
||||
- occurred_at
|
||||
- visibility
|
||||
properties:
|
||||
id:
|
||||
type: string
|
||||
format: uuid
|
||||
description: Identifier of the fact.
|
||||
kind:
|
||||
$ref: "#/schemas/EvidenceKind"
|
||||
source:
|
||||
$ref: "#/schemas/EvidenceSource"
|
||||
skills:
|
||||
type: array
|
||||
minItems: 1
|
||||
maxItems: 13
|
||||
uniqueItems: true
|
||||
description: Skill tags of the event in ascending order.
|
||||
items:
|
||||
$ref: "#/schemas/EvidenceSkillCode"
|
||||
result:
|
||||
$ref: "#/schemas/EvidenceResult"
|
||||
attribution:
|
||||
$ref: "#/schemas/EvidenceAttribution"
|
||||
trust:
|
||||
$ref: "#/schemas/EvidenceTrustLevel"
|
||||
occurred_at:
|
||||
$ref: "./common_schemas.yml#/schemas/Timestamp"
|
||||
visibility:
|
||||
$ref: "#/schemas/EvidenceVisibility"
|
||||
EvidenceFactList:
|
||||
type: object
|
||||
description: One page of the facts of the current candidate, newest event first.
|
||||
additionalProperties: false
|
||||
required:
|
||||
- items
|
||||
- page
|
||||
properties:
|
||||
items:
|
||||
type: array
|
||||
maxItems: 100
|
||||
description: Facts of the page.
|
||||
items:
|
||||
$ref: "#/schemas/EvidenceFact"
|
||||
page:
|
||||
$ref: "./common_schemas.yml#/schemas/PageInfo"
|
||||
OrganizationEvidenceFact:
|
||||
type: object
|
||||
description: >-
|
||||
The one assessment fact that supports a category of the card as an
|
||||
organization reads it: the earliest visible measurement that passed
|
||||
exactly the confirmed grade of that category. A lower grade, a retake,
|
||||
the other tags of the event, the source, the basis, the exact time, and
|
||||
every identifier stay with the candidate. The fact carries no
|
||||
identifier of the fact, the event, the result, or the candidate, so it
|
||||
cannot be joined to a person by a key. It is not unlinkable: the skill,
|
||||
the grade, the trust level, and the year, together with the other
|
||||
values of the card, can narrow a small pool of candidates, and the
|
||||
minimum cohort of the card does not cover the year. `basis` and
|
||||
`calibration_status` are the same for every candidate: they say that
|
||||
the fact comes from a synthetic demonstration and is not calibrated,
|
||||
so a demonstration is never read as a validated measurement. The fact
|
||||
never carries an answer, score, item, failure, signal, or review band.
|
||||
additionalProperties: false
|
||||
required:
|
||||
- skill
|
||||
- grade
|
||||
- trust
|
||||
- basis
|
||||
- calibration_status
|
||||
- observed_year
|
||||
properties:
|
||||
skill:
|
||||
$ref: "#/schemas/EvidenceSkillCode"
|
||||
grade:
|
||||
$ref: "./catalog_schemas.yml#/schemas/GradeCode"
|
||||
trust:
|
||||
$ref: "#/schemas/EvidenceTrustLevel"
|
||||
basis:
|
||||
$ref: "#/schemas/EvidenceBasis"
|
||||
calibration_status:
|
||||
$ref: "#/schemas/EvidenceCalibrationStatus"
|
||||
observed_year:
|
||||
type: integer
|
||||
format: int32
|
||||
minimum: 2000
|
||||
maximum: 9999
|
||||
description: Year (UTC) when the assessment ended. The month, day, and time stay with the candidate.
|
||||
examples:
|
||||
- 2026
|
||||
OrganizationEvidence:
|
||||
type: object
|
||||
description: >-
|
||||
The permitted evidence of one candidate card, ordered by skill: at most
|
||||
one fact for each category of the card (at most nine). The list is empty
|
||||
when no visible fact supports a category of the card.
|
||||
additionalProperties: false
|
||||
required:
|
||||
- items
|
||||
properties:
|
||||
items:
|
||||
type: array
|
||||
maxItems: 9
|
||||
description: Permitted facts, one for each supported category.
|
||||
items:
|
||||
$ref: "#/schemas/OrganizationEvidenceFact"
|
||||
@@ -28,7 +28,7 @@ schemas:
|
||||
description: |-
|
||||
A group of values of the anonymous candidate card that the candidate chooses to publish. The set is closed and has no value for the full name, a contact, or the lowest salary: the card never carries them, so no choice and no later contract change in this list can publish them by accident. Contacts leave only through the contact grant of an accepted invitation (C4), and the lowest salary never leaves.
|
||||
|
||||
- categories: specialization and grade confirmed by an authoritative assessment result.
|
||||
- categories: specialization and grade confirmed by an authoritative assessment result. With it an organization receives the confirmed category and, with each category of the card, one supporting assessment fact: its skill, the passed grade, the trust level, the year of the assessment, and the basis and calibration that mark a synthetic, uncalibrated demonstration (`GetOrganizationCandidateEvidence`). The candidate sees the same on `GetMyCardPreview`.
|
||||
- self_assessment: the candidate's declared specialization and grade, separate from confirmed categories.
|
||||
- stack: only recognized technology codes from the server's closed taxonomy.
|
||||
- experience: a coarse total-experience band, without employers, periods, or descriptions.
|
||||
@@ -468,12 +468,16 @@ schemas:
|
||||
visibility filters and cohort checks can further generalize or suppress
|
||||
the organization-facing card. This read creates no view or history
|
||||
record and never reaches an organization. `card` is null while the
|
||||
profile is closed.
|
||||
profile is closed. `evidence` is what an organization would read in the
|
||||
evidence section of the card, one supporting assessment fact for each
|
||||
category of the card, and is null exactly when `card` is null; the
|
||||
organization-facing section can still be generalized or suppressed.
|
||||
additionalProperties: false
|
||||
required:
|
||||
- state
|
||||
- fields
|
||||
- card
|
||||
- evidence
|
||||
- generated_at
|
||||
properties:
|
||||
state:
|
||||
@@ -484,6 +488,10 @@ schemas:
|
||||
oneOf:
|
||||
- $ref: "#/schemas/AnonymousCardContent"
|
||||
- type: "null"
|
||||
evidence:
|
||||
oneOf:
|
||||
- $ref: "./evidence_schemas.yml#/schemas/OrganizationEvidence"
|
||||
- type: "null"
|
||||
generated_at:
|
||||
$ref: "./common_schemas.yml#/schemas/Timestamp"
|
||||
PrivacyEventKind:
|
||||
|
||||
+369
-2
@@ -25,6 +25,8 @@ tags:
|
||||
description: 'Invitations from an organization to one candidate: drafts with complete terms, immutable terms versions, sending, the candidate''s inbox, acceptance with the consent C4, structured declines, withdrawal and cancellation, and the contact grant. Contacts are readable only through an active grant, in a response separate from the terms.'
|
||||
- name: privacy
|
||||
description: 'Visibility of the current candidate: the publication of the anonymous card (a setting that refers to the C2 consent of the ledger and never replaces it), the search status that is not a consent, the organizations that the candidate hides the profile from, the preview of the card, and the history of the settings and of the accesses. Everything is closed by default, and no change makes a candidate more visible than they chose. No schema here reaches a contact, a name, or the lowest salary.'
|
||||
- name: evidence
|
||||
description: 'Skill evidence derived from confirmed assessment results: one fact per source event with its skills, trust level, attribution, date, and visibility. The candidate reads their own facts; an organization reads only the permitted projection of a currently visible card. Raw answers, failures, and anti-cheat data are never part of it.'
|
||||
- name: consent
|
||||
description: 'The consent ledger of the current account: the independent consents C1-C5 with their text versions, sources, states, and revocations. The ledger is append-only and returns only the caller''s own records.'
|
||||
- name: support
|
||||
@@ -1743,6 +1745,52 @@ paths:
|
||||
$ref: '#/components/responses/TooManyRequests'
|
||||
default:
|
||||
$ref: '#/components/responses/Problem'
|
||||
/api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}/evidence:
|
||||
get:
|
||||
operationId: GetOrganizationCandidateEvidence
|
||||
summary: Read the permitted skill evidence of one currently visible candidate card.
|
||||
description: |-
|
||||
Requires the session cookie of an employer account with an active membership in `org_id`. The organization and membership come from the current server-side session and path, never from cached search data.
|
||||
|
||||
`candidate_handle` is the organization-scoped opaque alias issued by the current anonymous-card projection. The server runs the same checks as the card read on every request: active membership, effective C2 publication, the candidate's hiding of this organization, and the minimum cohort. In addition the card must publish the `categories` field and show at least one category after the cohort rules, because the evidence explains those categories and discloses nothing beyond them. An unknown handle, a handle of another organization, a closed or revoked publication, a profile hidden from this organization, a profile suppressed by the minimum cohort, and a card without categories all answer the same 404 not_found. Closing C2 or hiding the organization blocks this read immediately, and a cached response proves nothing.
|
||||
|
||||
The response lists, for each category of the card, the one visible fact that supports its confirmed grade: the earliest assessment that passed exactly that grade, so a lower grade or a retake adds nothing. A fact the candidate hid is absent. Each fact carries only the skill, the passed grade, the trust level, the year of the assessment, and the basis and calibration of the method (`synthetic_demo`, `uncalibrated`), which are the same for every candidate and say that the fact is a demonstration, not a validated measurement. It carries no identifier of the fact, event, result, or candidate, no month or exact time, and never an answer, item, score, failed attempt, review band, or anti-cheat signal. An express training run and a failed attempt create no fact. The answer has no key that joins it to a person, but it is not unlinkable: with the other values of the card it can narrow a small pool of candidates.
|
||||
|
||||
Reading the evidence is a view of the candidate card: it consumes the organization's current card-view quota with the same distinct-card rule and is recorded in the access history with the `categories` field. When the quota is exhausted the operation answers 429 with Retry-After. The response is `Cache-Control: no-store`.
|
||||
|
||||
A missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden; an unknown organization or account without an active membership answers 404 not_found. An `org_id` that is not a UUID or a malformed candidate handle answers 400 validation_failed.
|
||||
security:
|
||||
- sessionCookie: []
|
||||
tags:
|
||||
- evidence
|
||||
parameters:
|
||||
- $ref: '#/components/parameters/OrganizationId'
|
||||
- $ref: '#/components/parameters/CandidateHandle'
|
||||
responses:
|
||||
'200':
|
||||
description: The permitted evidence of this candidate card for this organization.
|
||||
headers:
|
||||
Cache-Control:
|
||||
$ref: '#/components/headers/CacheControlNoStore'
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/OrganizationEvidence'
|
||||
examples:
|
||||
permitted:
|
||||
$ref: '#/components/examples/OrganizationCandidateEvidence'
|
||||
'400':
|
||||
$ref: '#/components/responses/ValidationFailed'
|
||||
'401':
|
||||
$ref: '#/components/responses/Unauthenticated'
|
||||
'403':
|
||||
$ref: '#/components/responses/Forbidden'
|
||||
'404':
|
||||
$ref: '#/components/responses/NotFound'
|
||||
'429':
|
||||
$ref: '#/components/responses/TooManyRequests'
|
||||
default:
|
||||
$ref: '#/components/responses/Problem'
|
||||
/api/v1/organizations/{org_id}/invitations:
|
||||
get:
|
||||
operationId: ListOrganizationInvitations
|
||||
@@ -2808,6 +2856,8 @@ paths:
|
||||
|
||||
`card` is the closed `AnonymousCardContent` projection. It reaches no private profile or contact schema and contains no name, email, phone, Telegram name, employer, salary figure, account identifier, or profile identifier. Unpublished or unknown values are null. Only allowed canonical skills and generalized experience are exposed; arbitrary profile text and imported excerpts never appear. `categories` contains only confirmed assessment results. Self-assessed grades and work formats appear only through their separate explicit publication choices, and self-assessment never becomes a confirmed category. Salary compatibility is nullable and contains no salary amount.
|
||||
|
||||
`evidence` shows what an organization would read in the evidence section of the card (`GetOrganizationCandidateEvidence`): for each category of the card, the one assessment fact that supports its confirmed grade, with its skill, the passed grade, the trust level, the year, and the basis and calibration (`synthetic_demo`, `uncalibrated`). It is null while `card` is null, and an empty list when the card shows no category or no visible fact supports one. The preview applies no organization or cohort, so an organization can still receive less.
|
||||
|
||||
A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden.
|
||||
security:
|
||||
- sessionCookie: []
|
||||
@@ -3083,6 +3133,46 @@ paths:
|
||||
$ref: '#/components/responses/Forbidden'
|
||||
default:
|
||||
$ref: '#/components/responses/Problem'
|
||||
/api/v1/me/evidence:
|
||||
get:
|
||||
operationId: ListMyEvidence
|
||||
summary: List the skill evidence of the current candidate.
|
||||
description: |-
|
||||
Requires the session cookie of a candidate account. The candidate comes from the session, so the response holds only the caller's own facts. Returns a page, newest event first with the fact identifier as the tie-breaker, with cursor pagination. The response is `Cache-Control: no-store`.
|
||||
|
||||
A fact is derived from the immutable result of a confirmed real assessment (root or corrective), in the same transaction that stores the result. Each fact names its source (the event and the result, which the candidate can open at `GetMyAssessmentResult`), the skills of the event, the grade that was passed with its basis and calibration, the attribution, the date, the visibility, and the trust level. An online assessment without a reliable confirmation of the identity has trust 1. One source event is one fact: its skills are tags of that fact, so several tags never make several facts.
|
||||
|
||||
The list never carries raw answers, items, scores, failed attempts, or anti-cheat data. A failed attempt, a result without a reviewed category source, and an express training run (`demo_express`) create no fact, so reading the list before and after an express run shows no new fact. The list includes facts the candidate hid, with `visibility` `hidden`.
|
||||
|
||||
A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account, or a candidate with an unverified email, answers 403 forbidden. A malformed `limit` or `cursor`, or a cursor of another candidate, answers 400 validation_failed.
|
||||
security:
|
||||
- sessionCookie: []
|
||||
tags:
|
||||
- evidence
|
||||
parameters:
|
||||
- $ref: '#/components/parameters/PageLimit'
|
||||
- $ref: '#/components/parameters/PageCursor'
|
||||
responses:
|
||||
'200':
|
||||
description: A page of the skill evidence of the current candidate.
|
||||
headers:
|
||||
Cache-Control:
|
||||
$ref: '#/components/headers/CacheControlNoStore'
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/EvidenceFactList'
|
||||
examples:
|
||||
page:
|
||||
$ref: '#/components/examples/EvidenceFactListPage'
|
||||
'400':
|
||||
$ref: '#/components/responses/ValidationFailed'
|
||||
'401':
|
||||
$ref: '#/components/responses/Unauthenticated'
|
||||
'403':
|
||||
$ref: '#/components/responses/Forbidden'
|
||||
default:
|
||||
$ref: '#/components/responses/Problem'
|
||||
/api/v1/me/support-cases:
|
||||
get:
|
||||
operationId: ListMySupportCases
|
||||
@@ -8953,7 +9043,7 @@ components:
|
||||
description: |-
|
||||
A group of values of the anonymous candidate card that the candidate chooses to publish. The set is closed and has no value for the full name, a contact, or the lowest salary: the card never carries them, so no choice and no later contract change in this list can publish them by accident. Contacts leave only through the contact grant of an accepted invitation (C4), and the lowest salary never leaves.
|
||||
|
||||
- categories: specialization and grade confirmed by an authoritative assessment result.
|
||||
- categories: specialization and grade confirmed by an authoritative assessment result. With it an organization receives the confirmed category and, with each category of the card, one supporting assessment fact: its skill, the passed grade, the trust level, the year of the assessment, and the basis and calibration that mark a synthetic, uncalibrated demonstration (`GetOrganizationCandidateEvidence`). The candidate sees the same on `GetMyCardPreview`.
|
||||
- self_assessment: the candidate's declared specialization and grade, separate from confirmed categories.
|
||||
- stack: only recognized technology codes from the server's closed taxonomy.
|
||||
- experience: a coarse total-experience band, without employers, periods, or descriptions.
|
||||
@@ -9257,12 +9347,13 @@ components:
|
||||
description: Nullable compatibility result with no salary values.
|
||||
CardPreview:
|
||||
type: object
|
||||
description: A private candidate preview computed from the current profile, publication, and consent ledger. Its pseudonym uses a separate preview context and is not an organization's alias. Organization-specific visibility filters and cohort checks can further generalize or suppress the organization-facing card. This read creates no view or history record and never reaches an organization. `card` is null while the profile is closed.
|
||||
description: A private candidate preview computed from the current profile, publication, and consent ledger. Its pseudonym uses a separate preview context and is not an organization's alias. Organization-specific visibility filters and cohort checks can further generalize or suppress the organization-facing card. This read creates no view or history record and never reaches an organization. `card` is null while the profile is closed. `evidence` is what an organization would read in the evidence section of the card, one supporting assessment fact for each category of the card, and is null exactly when `card` is null; the organization-facing section can still be generalized or suppressed.
|
||||
additionalProperties: false
|
||||
required:
|
||||
- state
|
||||
- fields
|
||||
- card
|
||||
- evidence
|
||||
- generated_at
|
||||
properties:
|
||||
state:
|
||||
@@ -9273,6 +9364,10 @@ components:
|
||||
oneOf:
|
||||
- $ref: '#/components/schemas/AnonymousCardContent'
|
||||
- type: 'null'
|
||||
evidence:
|
||||
oneOf:
|
||||
- $ref: '#/components/schemas/OrganizationEvidence'
|
||||
- type: 'null'
|
||||
generated_at:
|
||||
$ref: '#/components/schemas/Timestamp'
|
||||
PrivacyEventKind:
|
||||
@@ -9395,6 +9490,235 @@ components:
|
||||
$ref: '#/components/schemas/CardAccess'
|
||||
page:
|
||||
$ref: '#/components/schemas/PageInfo'
|
||||
EvidenceKind:
|
||||
type: string
|
||||
description: |-
|
||||
Whether a fact is a statement or an observation.
|
||||
|
||||
- claim: something the candidate stated that nothing confirmed separately. Its trust is 0.
|
||||
- measurement: a result that a system observed, such as a confirmed assessment. Its trust is 1 to 3.
|
||||
|
||||
Assessments produce measurements only. A claim never becomes a measurement by repetition, and the two kinds are stored apart.
|
||||
enum:
|
||||
- claim
|
||||
- measurement
|
||||
EvidenceSourceType:
|
||||
type: string
|
||||
description: |-
|
||||
Where the fact comes from.
|
||||
|
||||
- assessment_result: a real (root or corrective) assessment result of this platform that confirmed a grade. An express training run (`demo_express`), a failed attempt, and a result without a reviewed category source are never a source.
|
||||
|
||||
Adding a value is a contract change.
|
||||
enum:
|
||||
- assessment_result
|
||||
EvidenceAttribution:
|
||||
type: string
|
||||
description: |-
|
||||
Whose contribution the fact is.
|
||||
|
||||
- personal: the candidate's own result. Every assessment fact is personal.
|
||||
- team_role: a team result with a confirmed role of the candidate.
|
||||
- team_unattributed: a team result without a confirmed role; it is not a personal skill.
|
||||
|
||||
Only `personal` is produced today.
|
||||
enum:
|
||||
- personal
|
||||
- team_role
|
||||
- team_unattributed
|
||||
EvidenceTrustLevel:
|
||||
type: integer
|
||||
format: int32
|
||||
minimum: 0
|
||||
maximum: 3
|
||||
description: |-
|
||||
Strength of the confirmation.
|
||||
|
||||
- 0: stated by the person, not confirmed separately.
|
||||
- 1: an observable online result without a reliable confirmation of the identity or the authorship. Every assessment fact has this level today, because the assessment is unproctored and the identity is not confirmed.
|
||||
- 2: a result tied to a confirmed identity or confirmed by an independent party.
|
||||
- 3: an in-person check with a matching confirmation.
|
||||
|
||||
A repeated statement, a sign-in, or a repeated tag of the same event never raises the level.
|
||||
examples:
|
||||
- 1
|
||||
EvidenceVisibility:
|
||||
type: string
|
||||
description: |-
|
||||
Whether the fact may take part in what an organization reads.
|
||||
|
||||
- visible: the fact is eligible for the organization projection. It does not publish the fact: the projection also needs the published card with the `categories` field and an active C2.
|
||||
- hidden: the candidate hid the fact. No organization reads it. Hiding never edits or deletes the confirmed result.
|
||||
enum:
|
||||
- visible
|
||||
- hidden
|
||||
EvidenceSkillCode:
|
||||
type: string
|
||||
description: A skill tag from a closed set - the specialization codes of the catalog and the technology codes of the anonymous card. An assessment tags its fact with the specialization of the category.
|
||||
enum:
|
||||
- backend
|
||||
- frontend
|
||||
- mobile
|
||||
- network_engineer
|
||||
- devops_sre
|
||||
- data_analyst
|
||||
- ds_ml
|
||||
- information_security
|
||||
- qa
|
||||
- go
|
||||
- postgresql
|
||||
- kafka
|
||||
- docker
|
||||
EvidenceBasis:
|
||||
type: string
|
||||
description: |-
|
||||
What the measurement rests on.
|
||||
|
||||
- synthetic_demo: a demonstration category from a synthetic reviewed bank. It shows the mechanics and is not a validated measurement.
|
||||
enum:
|
||||
- synthetic_demo
|
||||
EvidenceCalibrationStatus:
|
||||
type: string
|
||||
description: |-
|
||||
Calibration of the method behind the result.
|
||||
|
||||
- uncalibrated: the thresholds are initial values that no measurement has validated.
|
||||
enum:
|
||||
- uncalibrated
|
||||
EvidenceResult:
|
||||
type: object
|
||||
description: 'What the fact says: the grade that was passed and how reliable the method is. It carries no score, answer, item, failure, or anti-cheat data.'
|
||||
additionalProperties: false
|
||||
required:
|
||||
- grade
|
||||
- basis
|
||||
- calibration_status
|
||||
properties:
|
||||
grade:
|
||||
$ref: '#/components/schemas/GradeCode'
|
||||
basis:
|
||||
$ref: '#/components/schemas/EvidenceBasis'
|
||||
calibration_status:
|
||||
$ref: '#/components/schemas/EvidenceCalibrationStatus'
|
||||
EvidenceSource:
|
||||
type: object
|
||||
description: Where the fact comes from. For an assessment the event is the attempt and the result is the immutable result of that attempt, which the candidate reads at `GetMyAssessmentResult`; the two identifiers are equal because a result is keyed by its attempt.
|
||||
additionalProperties: false
|
||||
required:
|
||||
- type
|
||||
- event_id
|
||||
- result_id
|
||||
properties:
|
||||
type:
|
||||
$ref: '#/components/schemas/EvidenceSourceType'
|
||||
event_id:
|
||||
type: string
|
||||
format: uuid
|
||||
description: Identifier of the source event. One event is one fact, however many skills it is tagged with.
|
||||
result_id:
|
||||
type: string
|
||||
format: uuid
|
||||
description: Identifier of the immutable result that produced the fact.
|
||||
EvidenceFact:
|
||||
type: object
|
||||
description: One independent fact of the current candidate. `occurred_at` is when the source event ended; for an assessment it is the time of the decision. A fact is one source event; the skills of that event are tags of the fact, so a second tag never makes a second fact. Hidden facts are listed here with their visibility, because the candidate owns them.
|
||||
additionalProperties: false
|
||||
required:
|
||||
- id
|
||||
- kind
|
||||
- source
|
||||
- skills
|
||||
- result
|
||||
- attribution
|
||||
- trust
|
||||
- occurred_at
|
||||
- visibility
|
||||
properties:
|
||||
id:
|
||||
type: string
|
||||
format: uuid
|
||||
description: Identifier of the fact.
|
||||
kind:
|
||||
$ref: '#/components/schemas/EvidenceKind'
|
||||
source:
|
||||
$ref: '#/components/schemas/EvidenceSource'
|
||||
skills:
|
||||
type: array
|
||||
minItems: 1
|
||||
maxItems: 13
|
||||
uniqueItems: true
|
||||
description: Skill tags of the event in ascending order.
|
||||
items:
|
||||
$ref: '#/components/schemas/EvidenceSkillCode'
|
||||
result:
|
||||
$ref: '#/components/schemas/EvidenceResult'
|
||||
attribution:
|
||||
$ref: '#/components/schemas/EvidenceAttribution'
|
||||
trust:
|
||||
$ref: '#/components/schemas/EvidenceTrustLevel'
|
||||
occurred_at:
|
||||
$ref: '#/components/schemas/Timestamp'
|
||||
visibility:
|
||||
$ref: '#/components/schemas/EvidenceVisibility'
|
||||
EvidenceFactList:
|
||||
type: object
|
||||
description: One page of the facts of the current candidate, newest event first.
|
||||
additionalProperties: false
|
||||
required:
|
||||
- items
|
||||
- page
|
||||
properties:
|
||||
items:
|
||||
type: array
|
||||
maxItems: 100
|
||||
description: Facts of the page.
|
||||
items:
|
||||
$ref: '#/components/schemas/EvidenceFact'
|
||||
page:
|
||||
$ref: '#/components/schemas/PageInfo'
|
||||
OrganizationEvidenceFact:
|
||||
type: object
|
||||
description: 'The one assessment fact that supports a category of the card as an organization reads it: the earliest visible measurement that passed exactly the confirmed grade of that category. A lower grade, a retake, the other tags of the event, the source, the basis, the exact time, and every identifier stay with the candidate. The fact carries no identifier of the fact, the event, the result, or the candidate, so it cannot be joined to a person by a key. It is not unlinkable: the skill, the grade, the trust level, and the year, together with the other values of the card, can narrow a small pool of candidates, and the minimum cohort of the card does not cover the year. `basis` and `calibration_status` are the same for every candidate: they say that the fact comes from a synthetic demonstration and is not calibrated, so a demonstration is never read as a validated measurement. The fact never carries an answer, score, item, failure, signal, or review band.'
|
||||
additionalProperties: false
|
||||
required:
|
||||
- skill
|
||||
- grade
|
||||
- trust
|
||||
- basis
|
||||
- calibration_status
|
||||
- observed_year
|
||||
properties:
|
||||
skill:
|
||||
$ref: '#/components/schemas/EvidenceSkillCode'
|
||||
grade:
|
||||
$ref: '#/components/schemas/GradeCode'
|
||||
trust:
|
||||
$ref: '#/components/schemas/EvidenceTrustLevel'
|
||||
basis:
|
||||
$ref: '#/components/schemas/EvidenceBasis'
|
||||
calibration_status:
|
||||
$ref: '#/components/schemas/EvidenceCalibrationStatus'
|
||||
observed_year:
|
||||
type: integer
|
||||
format: int32
|
||||
minimum: 2000
|
||||
maximum: 9999
|
||||
description: Year (UTC) when the assessment ended. The month, day, and time stay with the candidate.
|
||||
examples:
|
||||
- 2026
|
||||
OrganizationEvidence:
|
||||
type: object
|
||||
description: 'The permitted evidence of one candidate card, ordered by skill: at most one fact for each category of the card (at most nine). The list is empty when no visible fact supports a category of the card.'
|
||||
additionalProperties: false
|
||||
required:
|
||||
- items
|
||||
properties:
|
||||
items:
|
||||
type: array
|
||||
maxItems: 9
|
||||
description: Permitted facts, one for each supported category.
|
||||
items:
|
||||
$ref: '#/components/schemas/OrganizationEvidenceFact'
|
||||
HealthResponse:
|
||||
type: object
|
||||
additionalProperties: false
|
||||
@@ -14154,6 +14478,16 @@ components:
|
||||
experience_band: '1_3'
|
||||
work_formats: null
|
||||
salary_compatibility: null
|
||||
OrganizationCandidateEvidence:
|
||||
summary: The one supporting assessment fact of the category on the card
|
||||
value:
|
||||
items:
|
||||
- skill: backend
|
||||
grade: junior
|
||||
trust: 1
|
||||
basis: synthetic_demo
|
||||
calibration_status: uncalibrated
|
||||
observed_year: 2026
|
||||
OrganizationInvitationListPage:
|
||||
summary: The last page of the invitations of an organization
|
||||
description: The organization sees that the second invitation was declined, but not the reason or the comment.
|
||||
@@ -15565,6 +15899,14 @@ components:
|
||||
experience_band: '1_3'
|
||||
work_formats: null
|
||||
salary_compatibility: null
|
||||
evidence:
|
||||
items:
|
||||
- skill: backend
|
||||
grade: middle
|
||||
trust: 1
|
||||
basis: synthetic_demo
|
||||
calibration_status: uncalibrated
|
||||
observed_year: 2026
|
||||
generated_at: '2026-10-06T09:30:00Z'
|
||||
ClosedCardPreview:
|
||||
summary: The preview of a closed profile
|
||||
@@ -15572,6 +15914,7 @@ components:
|
||||
state: closed
|
||||
fields: []
|
||||
card: null
|
||||
evidence: null
|
||||
generated_at: '2026-10-06T09:30:00Z'
|
||||
SearchStatusUpdateLooking:
|
||||
summary: Set or confirm the status looking
|
||||
@@ -15673,6 +16016,30 @@ components:
|
||||
page:
|
||||
has_more: false
|
||||
next_cursor: null
|
||||
EvidenceFactListPage:
|
||||
summary: A confirmed junior backend result with one fact and two tags of the same event
|
||||
value:
|
||||
items:
|
||||
- id: 01928f7a-d1e2-7f3a-8b4c-5d6e7f8a9b01
|
||||
kind: measurement
|
||||
source:
|
||||
type: assessment_result
|
||||
event_id: 01928f7a-e1f2-7a3b-8c4d-5e6f7a8b9c01
|
||||
result_id: 01928f7a-e1f2-7a3b-8c4d-5e6f7a8b9c01
|
||||
skills:
|
||||
- backend
|
||||
- go
|
||||
result:
|
||||
grade: junior
|
||||
basis: synthetic_demo
|
||||
calibration_status: uncalibrated
|
||||
attribution: personal
|
||||
trust: 1
|
||||
occurred_at: '2026-10-08T10:15:00Z'
|
||||
visibility: visible
|
||||
page:
|
||||
has_more: false
|
||||
next_cursor: null
|
||||
SupportCaseListPage:
|
||||
summary: The last page of the case summaries of the current account
|
||||
value:
|
||||
|
||||
@@ -60,6 +60,13 @@ tags:
|
||||
Everything is closed by default, and no change makes a candidate more
|
||||
visible than they chose. No schema here reaches a contact, a name, or
|
||||
the lowest salary.
|
||||
- name: evidence
|
||||
description: >-
|
||||
Skill evidence derived from confirmed assessment results: one fact per
|
||||
source event with its skills, trust level, attribution, date, and
|
||||
visibility. The candidate reads their own facts; an organization reads
|
||||
only the permitted projection of a currently visible card. Raw
|
||||
answers, failures, and anti-cheat data are never part of it.
|
||||
- name: consent
|
||||
description: >-
|
||||
The consent ledger of the current account: the independent consents
|
||||
@@ -135,6 +142,8 @@ paths:
|
||||
$ref: ./routes/matches.yml
|
||||
/api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}:
|
||||
$ref: ./routes/organization_candidate_card.yml
|
||||
/api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}/evidence:
|
||||
$ref: ./routes/organization_candidate_card_evidence.yml
|
||||
/api/v1/organizations/{org_id}/invitations:
|
||||
$ref: ./routes/organization_invitations.yml
|
||||
/api/v1/organizations/{org_id}/invitations/{invitation_id}:
|
||||
@@ -183,6 +192,8 @@ paths:
|
||||
$ref: ./routes/candidate_privacy_history.yml
|
||||
/api/v1/me/privacy/access-history:
|
||||
$ref: ./routes/candidate_privacy_access_history.yml
|
||||
/api/v1/me/evidence:
|
||||
$ref: ./routes/candidate_evidence.yml
|
||||
/api/v1/me/support-cases:
|
||||
$ref: ./routes/support_cases.yml
|
||||
/api/v1/me/support-cases/{case_id}:
|
||||
@@ -871,6 +882,34 @@ components:
|
||||
$ref: ./components/schemas.yml#/CardAccess
|
||||
CardAccessList:
|
||||
$ref: ./components/schemas.yml#/CardAccessList
|
||||
EvidenceKind:
|
||||
$ref: ./components/schemas.yml#/EvidenceKind
|
||||
EvidenceSourceType:
|
||||
$ref: ./components/schemas.yml#/EvidenceSourceType
|
||||
EvidenceAttribution:
|
||||
$ref: ./components/schemas.yml#/EvidenceAttribution
|
||||
EvidenceTrustLevel:
|
||||
$ref: ./components/schemas.yml#/EvidenceTrustLevel
|
||||
EvidenceVisibility:
|
||||
$ref: ./components/schemas.yml#/EvidenceVisibility
|
||||
EvidenceSkillCode:
|
||||
$ref: ./components/schemas.yml#/EvidenceSkillCode
|
||||
EvidenceBasis:
|
||||
$ref: ./components/schemas.yml#/EvidenceBasis
|
||||
EvidenceCalibrationStatus:
|
||||
$ref: ./components/schemas.yml#/EvidenceCalibrationStatus
|
||||
EvidenceResult:
|
||||
$ref: ./components/schemas.yml#/EvidenceResult
|
||||
EvidenceSource:
|
||||
$ref: ./components/schemas.yml#/EvidenceSource
|
||||
EvidenceFact:
|
||||
$ref: ./components/schemas.yml#/EvidenceFact
|
||||
EvidenceFactList:
|
||||
$ref: ./components/schemas.yml#/EvidenceFactList
|
||||
OrganizationEvidenceFact:
|
||||
$ref: ./components/schemas.yml#/OrganizationEvidenceFact
|
||||
OrganizationEvidence:
|
||||
$ref: ./components/schemas.yml#/OrganizationEvidence
|
||||
parameters:
|
||||
IdempotencyKey:
|
||||
$ref: ./components/parameters.yml#/IdempotencyKey
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
get:
|
||||
operationId: ListMyEvidence
|
||||
summary: List the skill evidence of the current candidate.
|
||||
description: |-
|
||||
Requires the session cookie of a candidate account. The candidate comes from the session, so the response holds only the caller's own facts. Returns a page, newest event first with the fact identifier as the tie-breaker, with cursor pagination. The response is `Cache-Control: no-store`.
|
||||
|
||||
A fact is derived from the immutable result of a confirmed real assessment (root or corrective), in the same transaction that stores the result. Each fact names its source (the event and the result, which the candidate can open at `GetMyAssessmentResult`), the skills of the event, the grade that was passed with its basis and calibration, the attribution, the date, the visibility, and the trust level. An online assessment without a reliable confirmation of the identity has trust 1. One source event is one fact: its skills are tags of that fact, so several tags never make several facts.
|
||||
|
||||
The list never carries raw answers, items, scores, failed attempts, or anti-cheat data. A failed attempt, a result without a reviewed category source, and an express training run (`demo_express`) create no fact, so reading the list before and after an express run shows no new fact. The list includes facts the candidate hid, with `visibility` `hidden`.
|
||||
|
||||
A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account, or a candidate with an unverified email, answers 403 forbidden. A malformed `limit` or `cursor`, or a cursor of another candidate, answers 400 validation_failed.
|
||||
security:
|
||||
- sessionCookie: []
|
||||
tags:
|
||||
- evidence
|
||||
parameters:
|
||||
- $ref: ../components/parameters.yml#/PageLimit
|
||||
- $ref: ../components/parameters.yml#/PageCursor
|
||||
responses:
|
||||
"200":
|
||||
description: A page of the skill evidence of the current candidate.
|
||||
headers:
|
||||
Cache-Control:
|
||||
$ref: ../components/headers.yml#/CacheControlNoStore
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: ../components/schemas.yml#/EvidenceFactList
|
||||
examples:
|
||||
page:
|
||||
$ref: ../components/examples.yml#/EvidenceFactListPage
|
||||
"400":
|
||||
$ref: ../components/responses.yml#/ValidationFailed
|
||||
"401":
|
||||
$ref: ../components/responses.yml#/Unauthenticated
|
||||
"403":
|
||||
$ref: ../components/responses.yml#/Forbidden
|
||||
default:
|
||||
$ref: ../components/responses.yml#/Problem
|
||||
@@ -8,6 +8,8 @@ get:
|
||||
|
||||
`card` is the closed `AnonymousCardContent` projection. It reaches no private profile or contact schema and contains no name, email, phone, Telegram name, employer, salary figure, account identifier, or profile identifier. Unpublished or unknown values are null. Only allowed canonical skills and generalized experience are exposed; arbitrary profile text and imported excerpts never appear. `categories` contains only confirmed assessment results. Self-assessed grades and work formats appear only through their separate explicit publication choices, and self-assessment never becomes a confirmed category. Salary compatibility is nullable and contains no salary amount.
|
||||
|
||||
`evidence` shows what an organization would read in the evidence section of the card (`GetOrganizationCandidateEvidence`): for each category of the card, the one assessment fact that supports its confirmed grade, with its skill, the passed grade, the trust level, the year, and the basis and calibration (`synthetic_demo`, `uncalibrated`). It is null while `card` is null, and an empty list when the card shows no category or no visible fact supports one. The preview applies no organization or cohort, so an organization can still receive less.
|
||||
|
||||
A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden.
|
||||
security:
|
||||
- sessionCookie: []
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
get:
|
||||
operationId: GetOrganizationCandidateEvidence
|
||||
summary: Read the permitted skill evidence of one currently visible candidate card.
|
||||
description: |-
|
||||
Requires the session cookie of an employer account with an active membership in `org_id`. The organization and membership come from the current server-side session and path, never from cached search data.
|
||||
|
||||
`candidate_handle` is the organization-scoped opaque alias issued by the current anonymous-card projection. The server runs the same checks as the card read on every request: active membership, effective C2 publication, the candidate's hiding of this organization, and the minimum cohort. In addition the card must publish the `categories` field and show at least one category after the cohort rules, because the evidence explains those categories and discloses nothing beyond them. An unknown handle, a handle of another organization, a closed or revoked publication, a profile hidden from this organization, a profile suppressed by the minimum cohort, and a card without categories all answer the same 404 not_found. Closing C2 or hiding the organization blocks this read immediately, and a cached response proves nothing.
|
||||
|
||||
The response lists, for each category of the card, the one visible fact that supports its confirmed grade: the earliest assessment that passed exactly that grade, so a lower grade or a retake adds nothing. A fact the candidate hid is absent. Each fact carries only the skill, the passed grade, the trust level, the year of the assessment, and the basis and calibration of the method (`synthetic_demo`, `uncalibrated`), which are the same for every candidate and say that the fact is a demonstration, not a validated measurement. It carries no identifier of the fact, event, result, or candidate, no month or exact time, and never an answer, item, score, failed attempt, review band, or anti-cheat signal. An express training run and a failed attempt create no fact. The answer has no key that joins it to a person, but it is not unlinkable: with the other values of the card it can narrow a small pool of candidates.
|
||||
|
||||
Reading the evidence is a view of the candidate card: it consumes the organization's current card-view quota with the same distinct-card rule and is recorded in the access history with the `categories` field. When the quota is exhausted the operation answers 429 with Retry-After. The response is `Cache-Control: no-store`.
|
||||
|
||||
A missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden; an unknown organization or account without an active membership answers 404 not_found. An `org_id` that is not a UUID or a malformed candidate handle answers 400 validation_failed.
|
||||
security:
|
||||
- sessionCookie: []
|
||||
tags:
|
||||
- evidence
|
||||
parameters:
|
||||
- $ref: ../components/parameters.yml#/OrganizationId
|
||||
- $ref: ../components/parameters.yml#/CandidateHandle
|
||||
responses:
|
||||
"200":
|
||||
description: The permitted evidence of this candidate card for this organization.
|
||||
headers:
|
||||
Cache-Control:
|
||||
$ref: ../components/headers.yml#/CacheControlNoStore
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: ../components/schemas.yml#/OrganizationEvidence
|
||||
examples:
|
||||
permitted:
|
||||
$ref: ../components/examples.yml#/OrganizationCandidateEvidence
|
||||
"400":
|
||||
$ref: ../components/responses.yml#/ValidationFailed
|
||||
"401":
|
||||
$ref: ../components/responses.yml#/Unauthenticated
|
||||
"403":
|
||||
$ref: ../components/responses.yml#/Forbidden
|
||||
"404":
|
||||
$ref: ../components/responses.yml#/NotFound
|
||||
"429":
|
||||
$ref: ../components/responses.yml#/TooManyRequests
|
||||
default:
|
||||
$ref: ../components/responses.yml#/Problem
|
||||
@@ -112,4 +112,10 @@ Candidates read settings at `GET /api/v1/me/privacy`, preview at `GET /api/v1/me
|
||||
|
||||
An employer with a verified account and active membership reads a card through `GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}`. Each request rechecks membership, current C2, publication, organization hiding, and the minimum cohort; a successful view and quota use are recorded in one transaction. A closed, revoked, hidden, or suppressed card is indistinguishable from an unknown handle. Candidates can see successful card views in their access history. Contact reads and C4 grant management are not available yet; cards never contain contact details.
|
||||
|
||||
## Skill evidence
|
||||
|
||||
A confirmed real assessment result leaves one fact of skill evidence per attempt, written by the database in the same transaction that stores the result (migration 35, the trigger on `assessment_attempt_results`, and the function `skill_evidence_project_assessment_result`). The migration also projects the results that already exist. An express run, a failed attempt, and a result without a reviewed category source leave no fact. The skills of an event are tags of its fact, so several tags are still one fact, and an online assessment without a reliable identity confirmation has trust 1.
|
||||
|
||||
The candidate reads the facts at `GET /api/v1/me/evidence` (`usecase/evidence/read.go`, query `ListCandidateEvidenceFacts`); an employer reads the permitted projection at `GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}/evidence`, which runs the checks of the card read (`candidateview.Service.AuthorizeCategoriesSection`: membership, effective C2 publication, hiding, minimum cohort, quota, access audit) and then the statement `ListOrganizationVisibleEvidence` (effective publication view, `NOT EXISTS` over the hidden organizations, the `categories` field, visible measurements, one fact for each category of the card that supports its confirmed grade, an allowlist of six columns: skill, grade, trust, basis, calibration, year). The preview of the candidate (`GetMyCardPreview`) shows the same section through `ListCandidatePreviewEvidence`. The reads touch only the two evidence tables; `backend/db/evidence_queries_test.go` fails when an evidence query names a result, attempt, answer, signal, or review table. The facts, the tags, and the rules are described in [architecture](../docs/en/ARCHITECTURE.md#skill-evidence). The integration test `TestSkillEvidenceOverHTTP` runs against a real PostgreSQL and covers the fact tied to its result with trust 1, two more tags on one event, an express run and a failed attempt, paging, the organization projection with C2 granted and revoked, a hidden organization, a hidden fact, a card without categories, tags that can join a fact only in its creating transaction, the erasure of an account with facts through both cascade paths, the refusal to roll the migration back while a fact is hidden, and the rebuild after the migration is rolled back and applied again.
|
||||
|
||||
See [architecture](../docs/en/ARCHITECTURE.md) and [development](../docs/en/DEVELOPMENT.md).
|
||||
@@ -112,4 +112,10 @@
|
||||
|
||||
Работодатель с подтвержденной учетной записью и активным членством читает карточку по `GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}`. Каждый запрос заново проверяет членство, действующее C2, публикацию, скрытие для этой компании и минимальный размер группы; успешный просмотр и расход квоты записываются в одной транзакции. Закрытая, отозванная, скрытая или подавленная карточка не раскрывается и отвечает так же, как неизвестный псевдоним. Кандидат видит записи об успешных просмотрах карточки в своей истории доступа. Операция чтения контактов и управление грантами C4 пока недоступны; карточка контактов не содержит.
|
||||
|
||||
## Доказательства навыков
|
||||
|
||||
Подтвержденный настоящий результат оценки оставляет один факт доказательства на попытку; его пишет база в той же транзакции, что сохраняет результат (миграция 35, триггер на `assessment_attempt_results` и функция `skill_evidence_project_assessment_result`). Миграция также проецирует уже существующие результаты. Экспресс-прогон, проваленная попытка и результат без проверенного источника категории фактов не оставляют. Навыки события - теги его факта, поэтому несколько тегов остаются одним фактом, а у онлайн-оценки без надежного подтверждения личности доверие 1.
|
||||
|
||||
Кандидат читает факты через `GET /api/v1/me/evidence` (`usecase/evidence/read.go`, запрос `ListCandidateEvidenceFacts`); работодатель читает разрешенную проекцию через `GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}/evidence`, которая выполняет проверки чтения карточки (`candidateview.Service.AuthorizeCategoriesSection`: членство, действующая публикация с C2, скрытие, минимальная когорта, квота, аудит доступа), а затем запрос `ListOrganizationVisibleEvidence` (представление действующих публикаций, `NOT EXISTS` по скрытым организациям, поле `categories`, видимые измерения, по одному факту на каждую категорию карточки, подтверждающему ее грейд, белый список из шести колонок: навык, грейд, доверие, основание, калибровка, год). Предпросмотр кандидата (`GetMyCardPreview`) показывает тот же раздел через `ListCandidatePreviewEvidence`. Чтения трогают только две таблицы доказательств; `backend/db/evidence_queries_test.go` падает, если запрос доказательств называет таблицу результатов, попыток, ответов, сигналов или проверок. Факты, теги и правила описаны в [архитектуре](../docs/ru/ARCHITECTURE.md#доказательства-навыков). Интеграционный тест `TestSkillEvidenceOverHTTP` выполняется на настоящем PostgreSQL и проверяет: факт, связанный с результатом, с доверием 1, два дополнительных тега одного события, экспресс-прогон и проваленная попытка, постраничное чтение, проекция организации при выданном и отозванном C2, скрытая организация, скрытый факт, карточка без категорий теги, которые могут присоединиться к факту только в создавшей его транзакции, удаление аккаунта с фактами по обоим каскадным путям, отказ откатывать миграцию, пока есть скрытый факт, и перестроение после отката и повторного применения миграции.
|
||||
|
||||
Подробнее: [архитектура](../docs/ru/ARCHITECTURE.md) и [разработка](../docs/ru/DEVELOPMENT.md).
|
||||
@@ -0,0 +1,125 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var (
|
||||
evidenceTableName = regexp.MustCompile(`(?i)\bskill_evidence_(facts|skills)\b`)
|
||||
// evidenceReaders are the only queries that may name the evidence tables.
|
||||
evidenceReaders = []string{"ListCandidateEvidenceFacts", "ListCandidatePreviewEvidence", "ListOrganizationVisibleEvidence"}
|
||||
// evidenceForbiddenSources are tables whose content must never reach the
|
||||
// evidence reads: raw answers and items, results with their scores,
|
||||
// attempts, signals, and the anti-cheat review band.
|
||||
evidenceForbiddenSources = []string{
|
||||
"assessment_attempt_results", "assessment_attempt_items", "assessment_attempts",
|
||||
"assessment_attempt_reviews", "assessment_attempt_origin_marks", "assessment_answer_observations",
|
||||
"assessment_answer_fingerprint_holders", "assessment_answer_family_totals",
|
||||
"assessment_signal_events", "assessment_signal_batches", "assessment_signal_idempotency_outcomes",
|
||||
"assessment_attempt_idempotency_outcomes", "candidate_assessment_categories",
|
||||
"assessment_synthetic_category_reviews", "candidate_profile_claims", "candidate_questionnaires",
|
||||
}
|
||||
)
|
||||
|
||||
// evidenceStatements returns the statement of every query of the query files
|
||||
// by name, with comments removed.
|
||||
func evidenceStatements(t *testing.T) map[string]string {
|
||||
t.Helper()
|
||||
files, err := filepath.Glob("queries/*.sql")
|
||||
if err != nil || len(files) == 0 {
|
||||
t.Fatalf("list the query files = %v, %v", files, err)
|
||||
}
|
||||
statements := make(map[string]string)
|
||||
for _, file := range files {
|
||||
content, err := os.ReadFile(file)
|
||||
if err != nil {
|
||||
t.Fatalf("read %s: %v", file, err)
|
||||
}
|
||||
text := string(content)
|
||||
headers := queryHeaderPattern.FindAllStringSubmatchIndex(text, -1)
|
||||
for index, header := range headers {
|
||||
end := len(text)
|
||||
if index+1 < len(headers) {
|
||||
end = headers[index+1][0]
|
||||
}
|
||||
statement := lineComment.ReplaceAllString(blockComment.ReplaceAllString(text[header[1]:end], ""), "")
|
||||
statements[text[header[2]:header[3]]] = strings.ToLower(strings.Join(strings.Fields(statement), " "))
|
||||
}
|
||||
}
|
||||
return statements
|
||||
}
|
||||
|
||||
// Only the evidence reads name the projection, and the projection reads
|
||||
// reach no table of raw answers, scores, failures, or anti-cheat data.
|
||||
func TestEvidenceReadsNameOnlyTheProjection(t *testing.T) {
|
||||
statements := evidenceStatements(t)
|
||||
var found []string
|
||||
for name, statement := range statements {
|
||||
if evidenceTableName.MatchString(statement) {
|
||||
found = append(found, name)
|
||||
}
|
||||
}
|
||||
slices.Sort(found)
|
||||
want := slices.Clone(evidenceReaders)
|
||||
slices.Sort(want)
|
||||
if !slices.Equal(found, want) {
|
||||
t.Fatalf("queries that name the evidence tables = %v, want only %v", found, want)
|
||||
}
|
||||
for _, name := range evidenceReaders {
|
||||
statement := statements[name]
|
||||
for _, forbidden := range evidenceForbiddenSources {
|
||||
if regexp.MustCompile(`\b` + forbidden + `\b`).MatchString(statement) {
|
||||
t.Errorf("%s reads %s: %s", name, forbidden, statement)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The organization read goes through the effective publication view, excludes
|
||||
// the candidates that hide the organization, requires the categories field,
|
||||
// and returns an allowlist of columns with no identifier.
|
||||
func TestOrganizationEvidenceReadUsesTheVisibilityBarrier(t *testing.T) {
|
||||
statement := evidenceStatements(t)["ListOrganizationVisibleEvidence"]
|
||||
if statement == "" {
|
||||
t.Fatal("the organization evidence query is missing")
|
||||
}
|
||||
for _, required := range []string{
|
||||
"from candidate_effective_publications as effective",
|
||||
"from candidate_hidden_organizations as hidden",
|
||||
"not exists",
|
||||
"hidden.organization_id = sqlc.arg(organization_id)",
|
||||
"'categories' = any(effective.fields)",
|
||||
"fact.visibility = 'visible'",
|
||||
"effective.user_id = sqlc.arg(candidate_id)",
|
||||
"select distinct on (skill.skill_code)",
|
||||
"(skill.skill_code || '/' || fact.grade) = any(sqlc.arg(categories)::text [])",
|
||||
"fact.kind = 'measurement'",
|
||||
} {
|
||||
if !strings.Contains(statement, required) {
|
||||
t.Errorf("organization evidence query lacks %q: %s", required, statement)
|
||||
}
|
||||
}
|
||||
selected := statement[len("select"):strings.Index(statement, " from candidate_effective_publications")]
|
||||
for _, private := range []string{"fact.id", "event_id", "result_id", "candidate_id", "visibility"} {
|
||||
if strings.Contains(selected, private) {
|
||||
t.Errorf("organization evidence query selects %q: %s", private, selected)
|
||||
}
|
||||
}
|
||||
// The columns are exactly the skill, the grade, the trust level, and the
|
||||
// year, with the basis and calibration of the method: nothing else of the
|
||||
// fact leaves.
|
||||
const wantSelected = " distinct on (skill.skill_code) skill.skill_code as skill, fact.grade, fact.trust, " +
|
||||
"fact.basis, fact.calibration_status, " +
|
||||
"extract(year from fact.occurred_at at time zone 'utc')::integer as observed_year"
|
||||
if selected != wantSelected {
|
||||
t.Errorf("organization evidence query selects %q, want %q", selected, wantSelected)
|
||||
}
|
||||
if strings.Contains(statement, "candidate_publications") {
|
||||
t.Errorf("organization evidence query reads the publication table directly: %s", statement)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,314 @@
|
||||
-- +goose Up
|
||||
-- Skill evidence is a projection of immutable assessment results. One fact is
|
||||
-- one source event; the skills of that event are tags of the fact, so several
|
||||
-- tags never multiply the fact. A fact is written by the database in the same
|
||||
-- transaction as the result that qualifies it, and migration backfills the
|
||||
-- results that already exist. The projection holds no answer, score, item,
|
||||
-- failure, or anti-cheat data: reads of the evidence never touch the result,
|
||||
-- attempt, or review tables.
|
||||
|
||||
CREATE TABLE skill_evidence_facts (
|
||||
id uuid NOT NULL DEFAULT gen_random_uuid(),
|
||||
candidate_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
-- A claim is a statement that nothing confirmed separately (trust 0); a
|
||||
-- measurement is an observed result (trust 1 to 3). Only assessments feed
|
||||
-- this table today, so every stored fact is a measurement.
|
||||
kind text NOT NULL,
|
||||
source_type text NOT NULL,
|
||||
-- The source event and the immutable result of that event. For an
|
||||
-- assessment both are the attempt, because a result is keyed by its attempt.
|
||||
event_id uuid NOT NULL,
|
||||
result_id uuid NOT NULL,
|
||||
attribution text NOT NULL,
|
||||
trust smallint NOT NULL,
|
||||
-- The grade that was passed, the basis of the measurement, and its
|
||||
-- calibration, copied from the category decision of the result.
|
||||
grade text NOT NULL,
|
||||
basis text NOT NULL,
|
||||
calibration_status text NOT NULL,
|
||||
occurred_at timestamptz NOT NULL,
|
||||
-- The candidate may hide a fact; hiding never edits the result.
|
||||
visibility text NOT NULL DEFAULT 'visible',
|
||||
recorded_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
-- The transaction that created the fact. Tags are added only in that
|
||||
-- transaction, so a stored fact is never widened afterwards.
|
||||
created_txid bigint NOT NULL DEFAULT (pg_current_xact_id()::text::bigint),
|
||||
CONSTRAINT skill_evidence_facts_pkey PRIMARY KEY (id),
|
||||
CONSTRAINT skill_evidence_facts_event_key UNIQUE (source_type, event_id),
|
||||
CONSTRAINT skill_evidence_facts_result_fk FOREIGN KEY (result_id, candidate_id)
|
||||
REFERENCES assessment_attempt_results (attempt_id, user_id) ON DELETE CASCADE,
|
||||
CONSTRAINT skill_evidence_facts_kind CHECK (kind IN ('claim', 'measurement')),
|
||||
CONSTRAINT skill_evidence_facts_source CHECK (source_type IN ('assessment_result')),
|
||||
CONSTRAINT skill_evidence_facts_attribution CHECK (attribution IN ('personal', 'team_role', 'team_unattributed')),
|
||||
CONSTRAINT skill_evidence_facts_trust CHECK (
|
||||
(kind = 'claim' AND trust = 0) OR (kind = 'measurement' AND trust BETWEEN 1 AND 3)
|
||||
),
|
||||
-- An online assessment has no proctoring, so it never reaches the level of
|
||||
-- an in-person check. Level 1 is the level without a reliable identity
|
||||
-- confirmation; level 2 is reserved for a result tied to a confirmed identity.
|
||||
CONSTRAINT skill_evidence_facts_assessment_shape CHECK (
|
||||
source_type <> 'assessment_result'
|
||||
OR (kind = 'measurement' AND trust BETWEEN 1 AND 2 AND attribution = 'personal' AND event_id = result_id)
|
||||
),
|
||||
CONSTRAINT skill_evidence_facts_grade CHECK (grade IN ('intern', 'junior', 'middle', 'senior')),
|
||||
CONSTRAINT skill_evidence_facts_basis CHECK (basis IN ('synthetic_demo')),
|
||||
CONSTRAINT skill_evidence_facts_calibration CHECK (calibration_status IN ('uncalibrated')),
|
||||
CONSTRAINT skill_evidence_facts_visibility CHECK (visibility IN ('visible', 'hidden'))
|
||||
);
|
||||
|
||||
CREATE INDEX skill_evidence_facts_candidate_idx
|
||||
ON skill_evidence_facts (candidate_id, occurred_at DESC, id DESC);
|
||||
|
||||
CREATE TABLE skill_evidence_skills (
|
||||
fact_id uuid NOT NULL REFERENCES skill_evidence_facts (id) ON DELETE CASCADE,
|
||||
skill_code text NOT NULL,
|
||||
CONSTRAINT skill_evidence_skills_pkey PRIMARY KEY (fact_id, skill_code),
|
||||
-- The specialization codes of the catalog and the closed technology
|
||||
-- taxonomy of the anonymous card.
|
||||
CONSTRAINT skill_evidence_skills_code CHECK (
|
||||
skill_code IN (
|
||||
'backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre',
|
||||
'data_analyst', 'ds_ml', 'information_security', 'qa',
|
||||
'go', 'postgresql', 'kafka', 'docker'
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
-- The single rule that decides which result is qualifying evidence: a real
|
||||
-- (root or corrective) result of the basic mode, confirmed, and carried by a
|
||||
-- reviewed category decision that either assigned the grade or left a higher
|
||||
-- one in force. An express training run, a failed attempt, and a result without
|
||||
-- a reviewed source never qualify.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION skill_evidence_result_qualifies(source_result assessment_attempt_results) RETURNS boolean
|
||||
LANGUAGE sql IMMUTABLE AS $$
|
||||
SELECT source_result.schema_version = 2
|
||||
AND source_result.kind IN ('root', 'corrective')
|
||||
AND source_result.mode = 'demo_basic'
|
||||
AND source_result.outcome = 'confirmed'
|
||||
AND source_result.category_decision ->> 'status' IN ('assigned', 'unchanged')
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
-- A fact must match the immutable result it names, so no write path can store
|
||||
-- evidence for an express run, a failed attempt, or another candidate.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION skill_evidence_facts_guard_insert() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
DECLARE
|
||||
source_result assessment_attempt_results%ROWTYPE;
|
||||
BEGIN
|
||||
SELECT * INTO source_result
|
||||
FROM assessment_attempt_results
|
||||
WHERE attempt_id = NEW.result_id AND user_id = NEW.candidate_id;
|
||||
|
||||
IF NOT FOUND OR NOT skill_evidence_result_qualifies(source_result) OR
|
||||
source_result.category_decision ->> 'attempted_grade' IS DISTINCT FROM NEW.grade OR
|
||||
source_result.category_decision ->> 'source' IS DISTINCT FROM NEW.basis OR
|
||||
source_result.category_decision ->> 'calibration_status' IS DISTINCT FROM NEW.calibration_status OR
|
||||
source_result.decided_at <> NEW.occurred_at THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = '23514', CONSTRAINT = 'skill_evidence_facts_source_result',
|
||||
MESSAGE = 'skill evidence does not match a qualifying assessment result';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE TRIGGER skill_evidence_facts_guard_insert
|
||||
BEFORE INSERT ON skill_evidence_facts
|
||||
FOR EACH ROW EXECUTE FUNCTION skill_evidence_facts_guard_insert();
|
||||
|
||||
-- A stored fact never changes except its visibility, and is removed only with
|
||||
-- its owner or its result.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION skill_evidence_facts_refuse_change() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF TG_OP = 'DELETE' THEN
|
||||
IF pg_trigger_depth() > 1 THEN
|
||||
RETURN OLD;
|
||||
END IF;
|
||||
ELSIF ROW(
|
||||
NEW.id, NEW.candidate_id, NEW.kind, NEW.source_type, NEW.event_id, NEW.result_id,
|
||||
NEW.attribution, NEW.trust, NEW.grade, NEW.basis, NEW.calibration_status,
|
||||
NEW.occurred_at, NEW.recorded_at, NEW.created_txid
|
||||
) IS NOT DISTINCT FROM ROW(
|
||||
OLD.id, OLD.candidate_id, OLD.kind, OLD.source_type, OLD.event_id, OLD.result_id,
|
||||
OLD.attribution, OLD.trust, OLD.grade, OLD.basis, OLD.calibration_status,
|
||||
OLD.occurred_at, OLD.recorded_at, OLD.created_txid
|
||||
) THEN
|
||||
RETURN NEW;
|
||||
END IF;
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = '23000', CONSTRAINT = 'skill_evidence_facts_immutable',
|
||||
MESSAGE = 'skill evidence facts are immutable except for their visibility';
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE TRIGGER skill_evidence_facts_refuse_change
|
||||
BEFORE UPDATE OR DELETE ON skill_evidence_facts
|
||||
FOR EACH ROW EXECUTE FUNCTION skill_evidence_facts_refuse_change();
|
||||
|
||||
-- A fact without a skill cannot be read or matched, so the check runs at
|
||||
-- commit, after the tags of the same transaction are in place. A fact that the
|
||||
-- same transaction already removed needs no tag.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION skill_evidence_facts_require_skill() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF EXISTS (SELECT 1 FROM skill_evidence_facts WHERE id = NEW.id) AND
|
||||
NOT EXISTS (SELECT 1 FROM skill_evidence_skills WHERE fact_id = NEW.id) THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = '23514', CONSTRAINT = 'skill_evidence_facts_require_skill',
|
||||
MESSAGE = 'skill evidence fact has no skill';
|
||||
END IF;
|
||||
RETURN NULL;
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE CONSTRAINT TRIGGER skill_evidence_facts_require_skill
|
||||
AFTER INSERT ON skill_evidence_facts
|
||||
DEFERRABLE INITIALLY DEFERRED
|
||||
FOR EACH ROW EXECUTE FUNCTION skill_evidence_facts_require_skill();
|
||||
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION skill_evidence_skills_refuse_change() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF TG_OP = 'DELETE' AND pg_trigger_depth() > 1 THEN
|
||||
RETURN OLD;
|
||||
END IF;
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = '23000', CONSTRAINT = 'skill_evidence_skills_immutable',
|
||||
MESSAGE = 'skill evidence tags are immutable';
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE TRIGGER skill_evidence_skills_refuse_change
|
||||
BEFORE UPDATE OR DELETE ON skill_evidence_skills
|
||||
FOR EACH ROW EXECUTE FUNCTION skill_evidence_skills_refuse_change();
|
||||
|
||||
-- A tag joins a fact only in the transaction that created the fact: the
|
||||
-- skills of an event are fixed when the event is recorded, and a later write
|
||||
-- cannot widen what an organization may read about it.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION skill_evidence_skills_require_new_fact() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM skill_evidence_facts
|
||||
WHERE id = NEW.fact_id AND created_txid = pg_current_xact_id()::text::bigint
|
||||
) THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = '23000', CONSTRAINT = 'skill_evidence_skills_fact_sealed',
|
||||
MESSAGE = 'skills can only be added in the transaction that created the fact';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE TRIGGER skill_evidence_skills_require_new_fact
|
||||
BEFORE INSERT ON skill_evidence_skills
|
||||
FOR EACH ROW EXECUTE FUNCTION skill_evidence_skills_require_new_fact();
|
||||
|
||||
-- Projects one stored result. A result that does not qualify writes nothing,
|
||||
-- and a repeat writes nothing, so the function serves both the trigger and the
|
||||
-- backfill. Level 1 is the trust of an online result without a reliable
|
||||
-- identity confirmation.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION skill_evidence_project_assessment_result(projected_attempt_id uuid) RETURNS void
|
||||
LANGUAGE plpgsql AS $$
|
||||
DECLARE
|
||||
source_result assessment_attempt_results%ROWTYPE;
|
||||
new_fact_id uuid;
|
||||
BEGIN
|
||||
SELECT * INTO source_result
|
||||
FROM assessment_attempt_results
|
||||
WHERE attempt_id = projected_attempt_id;
|
||||
IF NOT FOUND OR NOT skill_evidence_result_qualifies(source_result) THEN
|
||||
RETURN;
|
||||
END IF;
|
||||
|
||||
INSERT INTO skill_evidence_facts (
|
||||
candidate_id, kind, source_type, event_id, result_id, attribution, trust,
|
||||
grade, basis, calibration_status, occurred_at
|
||||
) VALUES (
|
||||
source_result.user_id, 'measurement', 'assessment_result', source_result.attempt_id,
|
||||
source_result.attempt_id, 'personal', 1,
|
||||
source_result.category_decision ->> 'attempted_grade',
|
||||
source_result.category_decision ->> 'source',
|
||||
source_result.category_decision ->> 'calibration_status',
|
||||
source_result.decided_at
|
||||
)
|
||||
ON CONFLICT (source_type, event_id) DO NOTHING
|
||||
RETURNING id INTO new_fact_id;
|
||||
|
||||
IF new_fact_id IS NOT NULL THEN
|
||||
INSERT INTO skill_evidence_skills (fact_id, skill_code)
|
||||
VALUES (new_fact_id, source_result.category_decision ->> 'specialization');
|
||||
END IF;
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION skill_evidence_project_result_trigger() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
PERFORM skill_evidence_project_assessment_result(NEW.attempt_id);
|
||||
RETURN NULL;
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE TRIGGER skill_evidence_project_result
|
||||
AFTER INSERT ON assessment_attempt_results
|
||||
FOR EACH ROW EXECUTE FUNCTION skill_evidence_project_result_trigger();
|
||||
|
||||
SELECT skill_evidence_project_assessment_result(attempt_id)
|
||||
FROM assessment_attempt_results
|
||||
ORDER BY decided_at, attempt_id;
|
||||
|
||||
-- +goose Down
|
||||
-- The facts are a projection: the results they were derived from stay, and the
|
||||
-- migration projects them again when it is applied again. Hiding a fact is the
|
||||
-- candidate's own decision and cannot be derived from a result, so a rollback
|
||||
-- refuses while any such decision, or any source other than an assessment
|
||||
-- result, would be lost.
|
||||
-- +goose StatementBegin
|
||||
DO $$
|
||||
BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM skill_evidence_facts
|
||||
WHERE visibility = 'hidden' OR source_type <> 'assessment_result'
|
||||
) THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = '23000', CONSTRAINT = 'skill_evidence_retained',
|
||||
MESSAGE = 'skill evidence uses migration 00035 and must be retained';
|
||||
END IF;
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
DROP TRIGGER skill_evidence_project_result ON assessment_attempt_results;
|
||||
DROP FUNCTION skill_evidence_project_result_trigger();
|
||||
DROP FUNCTION skill_evidence_project_assessment_result(uuid);
|
||||
DROP TRIGGER skill_evidence_skills_require_new_fact ON skill_evidence_skills;
|
||||
DROP FUNCTION skill_evidence_skills_require_new_fact();
|
||||
DROP TRIGGER skill_evidence_skills_refuse_change ON skill_evidence_skills;
|
||||
DROP FUNCTION skill_evidence_skills_refuse_change();
|
||||
DROP TRIGGER skill_evidence_facts_require_skill ON skill_evidence_facts;
|
||||
DROP FUNCTION skill_evidence_facts_require_skill();
|
||||
DROP TRIGGER skill_evidence_facts_refuse_change ON skill_evidence_facts;
|
||||
DROP FUNCTION skill_evidence_facts_refuse_change();
|
||||
DROP TRIGGER skill_evidence_facts_guard_insert ON skill_evidence_facts;
|
||||
DROP FUNCTION skill_evidence_facts_guard_insert();
|
||||
DROP FUNCTION skill_evidence_result_qualifies(assessment_attempt_results);
|
||||
DROP TABLE skill_evidence_skills;
|
||||
DROP TABLE skill_evidence_facts;
|
||||
@@ -0,0 +1,105 @@
|
||||
-- Skill evidence reads. The projection tables hold no answer, score, item,
|
||||
-- failure, or anti-cheat data, and none of these statements names the result,
|
||||
-- attempt, or review tables: evidence is read from its own facts only.
|
||||
|
||||
-- The candidate's own facts, hidden ones included, newest event first. Every
|
||||
-- statement is scoped by the owner; the caller passes the continuation
|
||||
-- position of the previous page, if any, and fetches one extra row.
|
||||
-- name: ListCandidateEvidenceFacts :many
|
||||
SELECT
|
||||
fact.id,
|
||||
fact.kind,
|
||||
fact.source_type,
|
||||
fact.event_id,
|
||||
fact.result_id,
|
||||
fact.attribution,
|
||||
fact.trust,
|
||||
fact.grade,
|
||||
fact.basis,
|
||||
fact.calibration_status,
|
||||
fact.occurred_at,
|
||||
fact.visibility,
|
||||
COALESCE(
|
||||
(
|
||||
SELECT array_agg(skill.skill_code ORDER BY skill.skill_code)
|
||||
FROM skill_evidence_skills AS skill
|
||||
WHERE skill.fact_id = fact.id
|
||||
),
|
||||
'{}'::text []
|
||||
)::text [] AS skills
|
||||
FROM skill_evidence_facts AS fact
|
||||
WHERE
|
||||
fact.candidate_id = sqlc.arg(candidate_id)
|
||||
AND (
|
||||
sqlc.narg(after_occurred_at)::timestamptz IS NULL
|
||||
OR (fact.occurred_at, fact.id) < (
|
||||
sqlc.narg(after_occurred_at)::timestamptz,
|
||||
sqlc.narg(after_id)::uuid
|
||||
)
|
||||
)
|
||||
ORDER BY fact.occurred_at DESC, fact.id DESC
|
||||
LIMIT sqlc.arg(row_limit);
|
||||
|
||||
-- The evidence that one organization may read about one candidate: one fact
|
||||
-- for each category of the card, the fact that supports the confirmed grade
|
||||
-- of that category (the earliest one that passed exactly that grade, so a
|
||||
-- lower grade or a retake adds nothing). The statement selects from the
|
||||
-- effective publication view (published and backed by an unrevoked C2) and
|
||||
-- excludes the candidates that hide the reading organization, so no row means
|
||||
-- nothing to read, whatever the reason. The card must publish the categories
|
||||
-- field and only visible measurements qualify. The categories come from the
|
||||
-- caller as "specialization/grade" pairs taken from the card that was just
|
||||
-- projected, so the answer never names a skill the card does not show. The columns are
|
||||
-- an allowlist: no identifier of the fact, the event, the result, or the
|
||||
-- candidate leaves, the instant is cut to the year, and the basis and the
|
||||
-- calibration (the same for every candidate) say that the fact is a synthetic
|
||||
-- demonstration.
|
||||
-- name: ListOrganizationVisibleEvidence :many
|
||||
SELECT DISTINCT ON (skill.skill_code)
|
||||
skill.skill_code AS skill,
|
||||
fact.grade,
|
||||
fact.trust,
|
||||
fact.basis,
|
||||
fact.calibration_status,
|
||||
extract(YEAR FROM fact.occurred_at AT TIME ZONE 'UTC')::integer AS observed_year
|
||||
FROM candidate_effective_publications AS effective
|
||||
INNER JOIN skill_evidence_facts AS fact
|
||||
ON effective.user_id = fact.candidate_id
|
||||
INNER JOIN skill_evidence_skills AS skill
|
||||
ON fact.id = skill.fact_id
|
||||
WHERE
|
||||
effective.user_id = sqlc.arg(candidate_id)
|
||||
AND 'categories' = any(effective.fields)
|
||||
AND (skill.skill_code || '/' || fact.grade) = any(sqlc.arg(categories)::text [])
|
||||
AND fact.kind = 'measurement'
|
||||
AND fact.visibility = 'visible'
|
||||
AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM candidate_hidden_organizations AS hidden
|
||||
WHERE
|
||||
hidden.user_id = effective.user_id
|
||||
AND hidden.organization_id = sqlc.arg(organization_id)
|
||||
)
|
||||
ORDER BY skill.skill_code, fact.occurred_at, fact.id;
|
||||
|
||||
-- The same selection for the candidate's own card preview, so the candidate
|
||||
-- sees what an organization would read. It is scoped by the owner and runs
|
||||
-- after the caller locked the effective C2 and publication; it does not apply
|
||||
-- an organization or a cohort.
|
||||
-- name: ListCandidatePreviewEvidence :many
|
||||
SELECT DISTINCT ON (skill.skill_code)
|
||||
skill.skill_code AS skill,
|
||||
fact.grade,
|
||||
fact.trust,
|
||||
fact.basis,
|
||||
fact.calibration_status,
|
||||
extract(YEAR FROM fact.occurred_at AT TIME ZONE 'UTC')::integer AS observed_year
|
||||
FROM skill_evidence_facts AS fact
|
||||
INNER JOIN skill_evidence_skills AS skill
|
||||
ON fact.id = skill.fact_id
|
||||
WHERE
|
||||
fact.candidate_id = sqlc.arg(candidate_id)
|
||||
AND (skill.skill_code || '/' || fact.grade) = any(sqlc.arg(categories)::text [])
|
||||
AND fact.kind = 'measurement'
|
||||
AND fact.visibility = 'visible'
|
||||
ORDER BY skill.skill_code, fact.occurred_at, fact.id;
|
||||
@@ -502,6 +502,28 @@ func newAssessmentAttemptHTTPHarnessWithCategories(
|
||||
t *testing.T,
|
||||
env *testEnvironment,
|
||||
categories assessment.AssessmentCategoryDecisionSettings,
|
||||
) *assessmentAttemptHTTPHarness {
|
||||
t.Helper()
|
||||
return newAssessmentAttemptHTTPHarnessWithOptions(ctx, t, env, categories, nil)
|
||||
}
|
||||
|
||||
// assessmentHarnessParts are the shared dependencies of the attempt router, for
|
||||
// a scenario that mounts further business areas on the same router.
|
||||
type assessmentHarnessParts struct {
|
||||
pool *pgxpool.Pool
|
||||
transactor *postgresadapter.Transactor
|
||||
keyring *identity.Keyring
|
||||
clock *testClock
|
||||
}
|
||||
|
||||
// newAssessmentAttemptHTTPHarnessWithOptions builds the attempt router and adds
|
||||
// the handler options that extra returns, if any.
|
||||
func newAssessmentAttemptHTTPHarnessWithOptions(
|
||||
ctx context.Context,
|
||||
t *testing.T,
|
||||
env *testEnvironment,
|
||||
categories assessment.AssessmentCategoryDecisionSettings,
|
||||
extra func(assessmentHarnessParts) []v1.HandlerOption,
|
||||
) *assessmentAttemptHTTPHarness {
|
||||
t.Helper()
|
||||
pool := env.newPool(ctx, t)
|
||||
@@ -554,11 +576,15 @@ func newAssessmentAttemptHTTPHarnessWithCategories(
|
||||
responder := problem.NewResponder(logger)
|
||||
healthHandler := v1.NewHealthHandler(health.NewReadiness(env.Postgres), time.Second)
|
||||
identityHandler := v1.NewIdentityHandler(nil, v1.WithSessionService(sessions), v1.WithPublicOrigin(env.Config.AppPublicURL))
|
||||
handler := v1.NewHandler(healthHandler, responder,
|
||||
options := []v1.HandlerOption{
|
||||
v1.WithIdentity(identityHandler), v1.WithConsent(consentHandler),
|
||||
v1.WithQuestionnaire(questionnaireHandler), v1.WithCatalog(catalogHandler),
|
||||
v1.WithAssessment(attemptHandler), v1.WithAssessmentSignals(signalHandler),
|
||||
)
|
||||
}
|
||||
if extra != nil {
|
||||
options = append(options, extra(assessmentHarnessParts{pool: pool, transactor: transactor, keyring: keyring, clock: clock})...)
|
||||
}
|
||||
handler := v1.NewHandler(healthHandler, responder, options...)
|
||||
router, err := httpadapter.NewRouter(healthHandler, handler, identityHandler.SessionSecurity(), responder, prometheus.New(), logger, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewRouter() error = %v", err)
|
||||
|
||||
@@ -49,6 +49,7 @@ var (
|
||||
{"candidate_questionnaire_specializations"}, {"candidate_questionnaires"},
|
||||
}
|
||||
assessmentAttemptTables = []pgx.Identifier{
|
||||
{"skill_evidence_skills"}, {"skill_evidence_facts"},
|
||||
{"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"},
|
||||
|
||||
@@ -250,7 +250,8 @@ func TestPolicyVersions(t *testing.T) {
|
||||
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_synthetic_category_reviews, candidate_assessment_categories`},
|
||||
assessment_synthetic_category_reviews, candidate_assessment_categories,
|
||||
skill_evidence_facts, skill_evidence_skills`},
|
||||
}
|
||||
for _, statement := range statements {
|
||||
_, err := fixture.pool.Exec(ctx, statement.sql, statement.args...)
|
||||
|
||||
@@ -0,0 +1,887 @@
|
||||
//go:build integration
|
||||
|
||||
package integration_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
v1 "lincodex/backend/internal/adapter/primary/http/v1"
|
||||
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
|
||||
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
"lincodex/backend/internal/usecase/anonymousprofile"
|
||||
"lincodex/backend/internal/usecase/assessment"
|
||||
"lincodex/backend/internal/usecase/candidateprivacy"
|
||||
"lincodex/backend/internal/usecase/candidateview"
|
||||
"lincodex/backend/internal/usecase/companyquota"
|
||||
"lincodex/backend/internal/usecase/evidence"
|
||||
)
|
||||
|
||||
const (
|
||||
skillEvidenceHTTPTimeout = 10 * time.Minute
|
||||
// skillEvidenceMigrationVersion creates the skill evidence tables.
|
||||
skillEvidenceMigrationVersion = 35
|
||||
// evidenceCohortSize is the smallest visible group of identical cards, so
|
||||
// the cohort rules of the card leave the category in place.
|
||||
evidenceCohortSize = 5
|
||||
)
|
||||
|
||||
type skillEvidenceHarness struct {
|
||||
*assessmentAttemptHTTPHarness
|
||||
key domain.CandidateViewPseudonymKey
|
||||
}
|
||||
|
||||
func newSkillEvidenceHarness(ctx context.Context, t *testing.T, env *testEnvironment) *skillEvidenceHarness {
|
||||
t.Helper()
|
||||
var key domain.CandidateViewPseudonymKey
|
||||
harness := newAssessmentAttemptHTTPHarnessWithOptions(ctx, t, env,
|
||||
assessment.AssessmentCategoryDecisionSettings{SyntheticDemoAssignmentsEnabled: true},
|
||||
func(parts assessmentHarnessParts) []v1.HandlerOption {
|
||||
var err error
|
||||
if key, err = parts.keyring.CandidateViewPseudonymKey(); err != nil {
|
||||
t.Fatalf("CandidateViewPseudonymKey() error = %v", err)
|
||||
}
|
||||
projector := anonymousprofile.NewService(postgresadapter.NewPrivacyCohortStore(parts.pool), key, parts.clock.Now)
|
||||
quota := companyquota.NewService(parts.clock.Now)
|
||||
views, err := candidateview.NewService(candidateview.Dependencies{
|
||||
Transactor: parts.transactor, Projector: projector, PseudonymKey: key, Clock: parts.clock.Now,
|
||||
Quota: func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, candidateID uuid.UUID) (outbound.CompanyQuotaDecision, error) {
|
||||
return quota.ReserveCardView(ctx, unit, organization, candidateID)
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("candidateview.NewService() error = %v", err)
|
||||
}
|
||||
settings, err := candidateprivacy.NewService(candidateprivacy.Dependencies{Transactor: parts.transactor, Clock: parts.clock.Now})
|
||||
if err != nil {
|
||||
t.Fatalf("candidateprivacy.NewService() error = %v", err)
|
||||
}
|
||||
evidenceService, err := evidence.NewService(evidence.Dependencies{
|
||||
Transactor: parts.transactor, AuthorizeCategories: views.AuthorizeCategoriesSection,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("evidence.NewService() error = %v", err)
|
||||
}
|
||||
return []v1.HandlerOption{
|
||||
v1.WithPrivacy(v1.NewPrivacyHandler(views, settings, env.Config.AppPublicURL)),
|
||||
v1.WithEvidence(v1.NewEvidenceHandler(evidenceService)),
|
||||
}
|
||||
})
|
||||
return &skillEvidenceHarness{assessmentAttemptHTTPHarness: harness, key: key}
|
||||
}
|
||||
|
||||
// evidenceFactBody is the owner's fact as the contract declares it.
|
||||
type evidenceFactBody struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Kind string `json:"kind"`
|
||||
Source struct {
|
||||
Type string `json:"type"`
|
||||
EventID uuid.UUID `json:"event_id"`
|
||||
ResultID uuid.UUID `json:"result_id"`
|
||||
} `json:"source"`
|
||||
Skills []string `json:"skills"`
|
||||
Result struct {
|
||||
Grade string `json:"grade"`
|
||||
Basis string `json:"basis"`
|
||||
CalibrationStatus string `json:"calibration_status"`
|
||||
} `json:"result"`
|
||||
Attribution string `json:"attribution"`
|
||||
Trust int `json:"trust"`
|
||||
OccurredAt time.Time `json:"occurred_at"`
|
||||
Visibility string `json:"visibility"`
|
||||
}
|
||||
|
||||
type evidencePageBody struct {
|
||||
Items []evidenceFactBody `json:"items"`
|
||||
Page struct {
|
||||
HasMore bool `json:"has_more"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
} `json:"page"`
|
||||
}
|
||||
|
||||
func TestSkillEvidenceOverHTTP(t *testing.T) {
|
||||
env := bootstrap(t, postgresService, redisService)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), skillEvidenceHTTPTimeout)
|
||||
defer cancel()
|
||||
databaseURL := env.createIsolatedDatabase(ctx, t)
|
||||
applyMigrations(ctx, t, databaseURL)
|
||||
isolatedEnv := *env
|
||||
isolatedEnv.Config.DatabaseURL = databaseURL
|
||||
harness := newSkillEvidenceHarness(ctx, t, &isolatedEnv)
|
||||
bank := seedAssessmentCategoryHTTPBank(ctx, t, harness.pool, domain.DemoProductPolicyV2(), true)
|
||||
threshold := passPoints(int(bank.policy.Policy().Assessment.StopRule.MaxScoredItems), int(bank.policy.Policy().Assessment.Attempt.BasicPassMark))
|
||||
client := &categoryHTTPClient{harness: harness.assessmentAttemptHTTPHarness, ctx: ctx}
|
||||
transactor := postgresadapter.NewTransactor(harness.pool)
|
||||
|
||||
now := time.Now().UTC().Truncate(time.Microsecond)
|
||||
identity := identityFixture{ctx: ctx, pool: harness.pool, store: harness.store, now: now}
|
||||
organizations := organizationFixture{ctx: ctx, pool: harness.pool, identity: identity, transactor: transactor, now: now}
|
||||
privacy := candidatePrivacyFixture{
|
||||
ctx: ctx, pool: harness.pool, queries: sqlc.New(harness.pool), identity: identity,
|
||||
organizations: organizations, ledger: postgresadapter.NewConsentStore(harness.pool), now: now,
|
||||
}
|
||||
|
||||
get := func(who categoryHTTPCandidate, path string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
return harness.request(t, http.MethodGet, path, "", "", who.cookie, "", client.remote())
|
||||
}
|
||||
readOwn := func(who categoryHTTPCandidate, query string) (evidencePageBody, *httptest.ResponseRecorder) {
|
||||
t.Helper()
|
||||
response := get(who, "/api/v1/me/evidence"+query)
|
||||
var page evidencePageBody
|
||||
if response.Code == http.StatusOK {
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &page); err != nil {
|
||||
t.Fatalf("decode own evidence: %v\n%s", err, response.Body.String())
|
||||
}
|
||||
}
|
||||
return page, response
|
||||
}
|
||||
countRows := func(query string, args ...any) int {
|
||||
t.Helper()
|
||||
var count int
|
||||
if err := harness.pool.QueryRow(ctx, query, args...).Scan(&count); err != nil {
|
||||
t.Fatalf("count rows: %v", err)
|
||||
}
|
||||
return count
|
||||
}
|
||||
passingIntern := func(who categoryHTTPCandidate) attemptRun {
|
||||
t.Helper()
|
||||
run := client.run(t, who, "backend", "intern", func(int) int { return threshold })
|
||||
if run.result["outcome"] != "confirmed" || decisionOf(t, run.result)["status"] != "assigned" {
|
||||
t.Fatalf("passing run of %s = %v, want a confirmed assigned category", who.email, run.result)
|
||||
}
|
||||
return run
|
||||
}
|
||||
|
||||
// The cohort: five candidates with the same published category. A card is
|
||||
// shown only inside a group of five identical cards.
|
||||
cohort := make([]categoryHTTPCandidate, 0, evidenceCohortSize)
|
||||
runs := make(map[uuid.UUID]attemptRun, evidenceCohortSize)
|
||||
for index := range evidenceCohortSize {
|
||||
member := client.candidate(t, fmt.Sprintf("evidence-cohort-%d@example.test", index))
|
||||
runs[member.id] = passingIntern(member)
|
||||
cohort = append(cohort, member)
|
||||
}
|
||||
target := cohort[0]
|
||||
targetRun := runs[target.id]
|
||||
consents := make(map[uuid.UUID]uuid.UUID, len(cohort))
|
||||
for _, member := range cohort {
|
||||
c2 := privacy.grant(t, member.id, domain.ConsentPurposePublication, privacyC2Version, now)
|
||||
privacy.publish(t, member.id, c2.ID(), 0, domain.CardFieldCategories)
|
||||
consents[member.id] = c2.ID()
|
||||
}
|
||||
failed := client.candidate(t, "evidence-failed@example.test")
|
||||
failedRun := client.run(t, failed, "backend", "intern", func(int) int { return threshold - 1 })
|
||||
if failedRun.result["outcome"] != "not_confirmed" {
|
||||
t.Fatalf("failing run = %v, want not_confirmed", failedRun.result["outcome"])
|
||||
}
|
||||
employerAccount := client.employer(t, "evidence-employer@example.test")
|
||||
foreignAccount := client.employer(t, "evidence-foreign@example.test")
|
||||
organizationA := organizations.create(t, domain.User{ID: employerAccount.id}, organizations.completeProfile(t, "Evidence organization A"), now)
|
||||
organizationB := organizations.create(t, domain.User{ID: employerAccount.id}, organizations.completeProfile(t, "Evidence organization B"), now)
|
||||
foreignOrganization := organizations.create(t, domain.User{ID: foreignAccount.id}, organizations.completeProfile(t, "Evidence foreign organization"), now)
|
||||
// The policy and the organizations take effect when they are stored, which
|
||||
// is after the clock of the harness was read, and the card-view quota reads
|
||||
// both at the application time.
|
||||
harness.clock.Set(time.Now().UTC().Truncate(time.Microsecond))
|
||||
organizationPath := func(organizationID uuid.UUID, handle string) string {
|
||||
return fmt.Sprintf("/api/v1/organizations/%s/candidate-cards/%s/evidence", organizationID, handle)
|
||||
}
|
||||
aliasIn := func(organizationID, candidateID uuid.UUID) string {
|
||||
t.Helper()
|
||||
alias, err := harness.key.ForOrganization(organizationID, candidateID)
|
||||
if err != nil {
|
||||
t.Fatalf("ForOrganization() error = %v", err)
|
||||
}
|
||||
return alias
|
||||
}
|
||||
organizationFacts := func(organizationID, candidateID uuid.UUID, categories ...domain.CandidateViewCategory) []domain.EvidenceOrganizationFact {
|
||||
t.Helper()
|
||||
var facts []domain.EvidenceOrganizationFact
|
||||
err := transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
var err error
|
||||
facts, err = unit.Evidence().ListOrganizationFacts(ctx, organizationID, candidateID, categories)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("ListOrganizationFacts() error = %v", err)
|
||||
}
|
||||
return facts
|
||||
}
|
||||
category := func(specialization domain.SpecializationCode, grade domain.GradeCode) domain.CandidateViewCategory {
|
||||
return domain.CandidateViewCategory{Specialization: specialization, Grade: grade, Strength: domain.CandidateViewStrengthStandard}
|
||||
}
|
||||
// A source records a fact together with its tags in one transaction, the
|
||||
// only time tags can join a fact. The helper rebuilds the projection from
|
||||
// the stored results and adds the tags to the fact of one event, as such a
|
||||
// source would.
|
||||
rebuildWithTags := func(eventID uuid.UUID, skills ...string) {
|
||||
t.Helper()
|
||||
tx, err := harness.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("begin the rebuild: %v", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
if _, err := tx.Exec(ctx, `TRUNCATE skill_evidence_skills, skill_evidence_facts`); err != nil {
|
||||
t.Fatalf("empty the projection: %v", err)
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `SELECT skill_evidence_project_assessment_result(attempt_id) FROM assessment_attempt_results`); err != nil {
|
||||
t.Fatalf("project the stored results: %v", err)
|
||||
}
|
||||
for _, skill := range skills {
|
||||
if _, err := tx.Exec(ctx, `INSERT INTO skill_evidence_skills (fact_id, skill_code)
|
||||
SELECT id, $2 FROM skill_evidence_facts WHERE event_id = $1`, eventID, skill); err != nil {
|
||||
t.Fatalf("tag the event with %s: %v", skill, err)
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
t.Fatalf("commit the rebuild: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("a confirmed assessment gives one fact tied to its result with trust 1", func(t *testing.T) {
|
||||
if domain.EvidenceTrustOnlineUnconfirmed != 1 {
|
||||
t.Fatalf("the trust of an online result without identity confirmation = %d, want 1", domain.EvidenceTrustOnlineUnconfirmed)
|
||||
}
|
||||
page, response := readOwn(target, "")
|
||||
if response.Code != http.StatusOK || response.Header().Get("Cache-Control") != "no-store" || len(page.Items) != 1 ||
|
||||
page.Page.HasMore || page.Page.NextCursor != nil {
|
||||
t.Fatalf("own evidence = %d %q %s, want one no-store fact", response.Code, response.Header().Get("Cache-Control"), response.Body.String())
|
||||
}
|
||||
fact := page.Items[0]
|
||||
decidedAt, err := time.Parse(time.RFC3339Nano, targetRun.result["decided_at"].(string))
|
||||
if err != nil {
|
||||
t.Fatalf("parse decided_at: %v", err)
|
||||
}
|
||||
if fact.ID == uuid.Nil || fact.Kind != "measurement" || fact.Source.Type != "assessment_result" ||
|
||||
fact.Source.EventID != targetRun.id || fact.Source.ResultID != targetRun.id ||
|
||||
!slices.Equal(fact.Skills, []string{"backend"}) || fact.Attribution != "personal" ||
|
||||
fact.Trust != int(domain.EvidenceTrustOnlineUnconfirmed) || fact.Visibility != "visible" ||
|
||||
fact.Result.Grade != "intern" || fact.Result.Basis != "synthetic_demo" || fact.Result.CalibrationStatus != "uncalibrated" ||
|
||||
!fact.OccurredAt.Equal(decidedAt) {
|
||||
t.Fatalf("fact = %+v, want a visible online measurement of the intern result %s decided at %s", fact, targetRun.id, decidedAt)
|
||||
}
|
||||
// The same result is readable by its identifier.
|
||||
if status, _ := client.call(t, target, http.MethodGet, "/api/v1/me/assessment-attempts/"+fact.Source.ResultID.String()+"/result", "", ""); status != http.StatusOK {
|
||||
t.Fatalf("result named by the fact = %d, want 200", status)
|
||||
}
|
||||
for _, leak := range []string{"answer", "score", "points", "reference", "seed", "item_", "signal", "review", "not_confirmed"} {
|
||||
if strings.Contains(strings.ToLower(response.Body.String()), leak) {
|
||||
t.Fatalf("own evidence exposes %q: %s", leak, response.Body.String())
|
||||
}
|
||||
}
|
||||
stored := countRows(`SELECT count(*) FROM skill_evidence_facts WHERE candidate_id = $1 AND trust = 1 AND kind = 'measurement' AND result_id = $2`, target.id, targetRun.id)
|
||||
if stored != 1 {
|
||||
t.Fatalf("stored facts of the result = %d, want 1", stored)
|
||||
}
|
||||
|
||||
// Every owner reads only their own facts; a failed attempt gives none.
|
||||
for _, member := range cohort[1:] {
|
||||
memberPage, _ := readOwn(member, "")
|
||||
if len(memberPage.Items) != 1 || memberPage.Items[0].ID == fact.ID || memberPage.Items[0].Source.ResultID != runs[member.id].id {
|
||||
t.Fatalf("evidence of %s = %+v, want only their own fact", member.email, memberPage.Items)
|
||||
}
|
||||
}
|
||||
if failedPage, response := readOwn(failed, ""); response.Code != http.StatusOK || len(failedPage.Items) != 0 || failedPage.Page.HasMore {
|
||||
t.Fatalf("evidence after a failed attempt = %d %s, want no fact", response.Code, response.Body.String())
|
||||
}
|
||||
if countRows(`SELECT count(*) FROM skill_evidence_facts WHERE candidate_id = $1`, failed.id) != 0 {
|
||||
t.Fatal("a failed attempt stored a fact")
|
||||
}
|
||||
|
||||
// Access: a guest, an employer, and a malformed request are refused.
|
||||
if response := get(categoryHTTPCandidate{}, "/api/v1/me/evidence"); response.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("evidence without a session = %d, want 401", response.Code)
|
||||
}
|
||||
if response := get(employerAccount, "/api/v1/me/evidence"); response.Code != http.StatusForbidden {
|
||||
t.Fatalf("evidence of an employer account = %d, want 403", response.Code)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("several tags of one event stay one independent fact", func(t *testing.T) {
|
||||
rebuildWithTags(targetRun.id, "go", "postgresql")
|
||||
page, response := readOwn(target, "")
|
||||
if len(page.Items) != 1 || !slices.Equal(page.Items[0].Skills, []string{"backend", "go", "postgresql"}) {
|
||||
t.Fatalf("evidence after two more tags = %s, want a single fact with three tags", response.Body.String())
|
||||
}
|
||||
fact := page.Items[0]
|
||||
if facts, events := countRows(`SELECT count(*) FROM skill_evidence_facts WHERE candidate_id = $1`, target.id),
|
||||
countRows(`SELECT count(DISTINCT event_id) FROM skill_evidence_facts WHERE candidate_id = $1`, target.id); facts != 1 || events != 1 {
|
||||
t.Fatalf("independent facts = %d over %d events, want 1 over 1", facts, events)
|
||||
}
|
||||
|
||||
// One event is one fact whatever its tags, and the tags are a closed set.
|
||||
_, err := harness.pool.Exec(ctx, `
|
||||
INSERT INTO skill_evidence_facts (candidate_id, kind, source_type, event_id, result_id, attribution, trust, grade, basis, calibration_status, occurred_at)
|
||||
SELECT candidate_id, kind, source_type, event_id, result_id, attribution, trust, grade, basis, calibration_status, occurred_at
|
||||
FROM skill_evidence_facts WHERE id = $1`, fact.ID)
|
||||
assertPgError(t, "second fact for one event", err, "23505", "skill_evidence_facts_event_key")
|
||||
// A stored fact is sealed: a later transaction cannot add a tag to it.
|
||||
_, err = harness.pool.Exec(ctx, `INSERT INTO skill_evidence_skills (fact_id, skill_code) VALUES ($1, 'qa')`, fact.ID)
|
||||
assertPgError(t, "tag added to a stored fact", err, "23000", "skill_evidence_skills_fact_sealed")
|
||||
_, err = harness.pool.Exec(ctx, `UPDATE skill_evidence_skills SET skill_code = 'qa' WHERE fact_id = $1 AND skill_code = 'go'`, fact.ID)
|
||||
assertPgError(t, "rewrite of a tag", err, "23000", "skill_evidence_skills_immutable")
|
||||
_, err = harness.pool.Exec(ctx, `DELETE FROM skill_evidence_skills WHERE fact_id = $1`, fact.ID)
|
||||
assertPgError(t, "removal of tags", err, "23000", "skill_evidence_skills_immutable")
|
||||
// Inside the creating transaction the tags are still a set from the closed list.
|
||||
tx, err := harness.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("begin the tag check: %v", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
if _, err := tx.Exec(ctx, `TRUNCATE skill_evidence_skills, skill_evidence_facts`); err != nil {
|
||||
t.Fatalf("empty the projection: %v", err)
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `SELECT skill_evidence_project_assessment_result($1)`, targetRun.id); err != nil {
|
||||
t.Fatalf("project the result: %v", err)
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `SAVEPOINT repeated`); err != nil {
|
||||
t.Fatalf("savepoint: %v", err)
|
||||
}
|
||||
_, err = tx.Exec(ctx, `INSERT INTO skill_evidence_skills SELECT id, 'backend' FROM skill_evidence_facts`)
|
||||
assertPgError(t, "repeated tag", err, "23505", "skill_evidence_skills_pkey")
|
||||
if _, err := tx.Exec(ctx, `ROLLBACK TO SAVEPOINT repeated`); err != nil {
|
||||
t.Fatalf("roll back to the savepoint: %v", err)
|
||||
}
|
||||
_, err = tx.Exec(ctx, `INSERT INTO skill_evidence_skills SELECT id, 'rate-limiting' FROM skill_evidence_facts`)
|
||||
assertPgError(t, "tag outside the closed set", err, "23514", "skill_evidence_skills_code")
|
||||
})
|
||||
|
||||
t.Run("a stored fact keeps its result and trust and only its visibility changes", func(t *testing.T) {
|
||||
page, _ := readOwn(target, "")
|
||||
factID := page.Items[0].ID
|
||||
for name, test := range map[string]struct {
|
||||
sql, constraint string
|
||||
code string
|
||||
}{
|
||||
"trust": {`UPDATE skill_evidence_facts SET trust = 2 WHERE id = $1`, "skill_evidence_facts_immutable", "23000"},
|
||||
"grade": {`UPDATE skill_evidence_facts SET grade = 'senior' WHERE id = $1`, "skill_evidence_facts_immutable", "23000"},
|
||||
"attribution": {`UPDATE skill_evidence_facts SET attribution = 'team_role' WHERE id = $1`, "skill_evidence_facts_immutable", "23000"},
|
||||
"kind": {`UPDATE skill_evidence_facts SET kind = 'claim' WHERE id = $1`, "skill_evidence_facts_immutable", "23000"},
|
||||
"removal": {`DELETE FROM skill_evidence_facts WHERE id = $1`, "skill_evidence_facts_immutable", "23000"},
|
||||
"bad hiding": {`UPDATE skill_evidence_facts SET visibility = 'public' WHERE id = $1`, "skill_evidence_facts_visibility", "23514"},
|
||||
} {
|
||||
_, err := harness.pool.Exec(ctx, test.sql, factID)
|
||||
assertPgError(t, name, err, test.code, test.constraint)
|
||||
}
|
||||
// A fact is a measurement of level 1 to 3 or a claim of level 0, never both.
|
||||
for name, statement := range map[string]string{
|
||||
"claim above level 0": `INSERT INTO skill_evidence_facts (candidate_id, kind, source_type, event_id, result_id, attribution, trust, grade, basis, calibration_status, occurred_at) SELECT candidate_id, 'claim', source_type, event_id, result_id, attribution, 1, grade, basis, calibration_status, occurred_at FROM skill_evidence_facts WHERE id = $1`,
|
||||
"measurement at level 0": `INSERT INTO skill_evidence_facts (candidate_id, kind, source_type, event_id, result_id, attribution, trust, grade, basis, calibration_status, occurred_at) SELECT candidate_id, kind, source_type, event_id, result_id, attribution, 0, grade, basis, calibration_status, occurred_at FROM skill_evidence_facts WHERE id = $1`,
|
||||
"online result in person": `INSERT INTO skill_evidence_facts (candidate_id, kind, source_type, event_id, result_id, attribution, trust, grade, basis, calibration_status, occurred_at) SELECT candidate_id, kind, source_type, event_id, result_id, attribution, 3, grade, basis, calibration_status, occurred_at FROM skill_evidence_facts WHERE id = $1`,
|
||||
} {
|
||||
if _, err := harness.pool.Exec(ctx, statement, factID); err == nil {
|
||||
t.Errorf("%s was stored", name)
|
||||
}
|
||||
}
|
||||
if _, err := harness.pool.Exec(ctx, `UPDATE skill_evidence_facts SET visibility = 'hidden' WHERE id = $1`, factID); err != nil {
|
||||
t.Fatalf("hide the fact: %v", err)
|
||||
}
|
||||
hiddenPage, _ := readOwn(target, "")
|
||||
if len(hiddenPage.Items) != 1 || hiddenPage.Items[0].Visibility != "hidden" || hiddenPage.Items[0].Trust != 1 {
|
||||
t.Fatalf("own evidence after hiding = %+v, want the same fact with visibility hidden", hiddenPage.Items)
|
||||
}
|
||||
if _, err := harness.pool.Exec(ctx, `UPDATE skill_evidence_facts SET visibility = 'visible' WHERE id = $1`, factID); err != nil {
|
||||
t.Fatalf("show the fact again: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("an express run creates no qualifying evidence, category, or cohort entry", func(t *testing.T) {
|
||||
expressOnly := client.candidate(t, "evidence-express@example.test")
|
||||
beforeBody := readOwnBody(t, get, target)
|
||||
beforeFacts := countRows(`SELECT count(*) FROM skill_evidence_facts`)
|
||||
beforeCategories := countStoredCategories(t, ctx, harness.pool, target.id)
|
||||
expressIDs := make([]uuid.UUID, 0, 2)
|
||||
for _, who := range []categoryHTTPCandidate{target, expressOnly} {
|
||||
expressIDs = append(expressIDs, runPerfectExpress(t, ctx, client, harness.assessmentAttemptHTTPHarness, who))
|
||||
}
|
||||
if afterBody := readOwnBody(t, get, target); afterBody != beforeBody {
|
||||
t.Fatalf("evidence changed after an express run:\n%s\n%s", beforeBody, afterBody)
|
||||
}
|
||||
if page, _ := readOwn(expressOnly, ""); len(page.Items) != 0 {
|
||||
t.Fatalf("evidence after express only = %+v, want none", page.Items)
|
||||
}
|
||||
if afterFacts := countRows(`SELECT count(*) FROM skill_evidence_facts`); afterFacts != beforeFacts {
|
||||
t.Fatalf("facts after express = %d, want the %d before", afterFacts, beforeFacts)
|
||||
}
|
||||
if countStoredCategories(t, ctx, harness.pool, target.id) != beforeCategories || countStoredCategories(t, ctx, harness.pool, expressOnly.id) != 0 {
|
||||
t.Fatal("an express run changed a category")
|
||||
}
|
||||
// The database also refuses a fact whose source is an express result or
|
||||
// a failed attempt, even through a direct write.
|
||||
for name, source := range map[string]struct{ owner, attempt uuid.UUID }{
|
||||
"express result of the owner": {target.id, expressIDs[0]},
|
||||
"express result of an outsider": {expressOnly.id, expressIDs[1]},
|
||||
"failed attempt": {failed.id, failedRun.id},
|
||||
} {
|
||||
_, err := harness.pool.Exec(ctx, `
|
||||
INSERT INTO skill_evidence_facts (candidate_id, kind, source_type, event_id, result_id, attribution, trust, grade, basis, calibration_status, occurred_at)
|
||||
VALUES ($1, 'measurement', 'assessment_result', $2, $2, 'personal', 1, 'intern', 'synthetic_demo', 'uncalibrated', now())`, source.owner, source.attempt)
|
||||
assertPgError(t, name, err, "23514", "skill_evidence_facts_source_result")
|
||||
}
|
||||
// Neither run enters the card cohort as a confirmed category.
|
||||
consent := privacy.grant(t, expressOnly.id, domain.ConsentPurposePublication, privacyC2Version, now)
|
||||
privacy.publish(t, expressOnly.id, consent.ID(), 0, domain.CardFieldCategories)
|
||||
sources, err := postgresadapter.NewPrivacyCohortStore(harness.pool).ListVisibleCandidateViewSources(ctx, organizationA.ID())
|
||||
if err != nil {
|
||||
t.Fatalf("ListVisibleCandidateViewSources() error = %v", err)
|
||||
}
|
||||
for _, source := range sources {
|
||||
categories := source.Input("cv1_"+strings.Repeat("A", 43), now).ConfirmedCategories
|
||||
if source.CandidateID() == expressOnly.id && len(categories) != 0 {
|
||||
t.Fatalf("express-only candidate has categories %v in the cohort", categories)
|
||||
}
|
||||
}
|
||||
// Withdraw the express-only publication so that it does not join the cohort of the target.
|
||||
privacy.revokeC2(t, expressOnly.id, now.Add(time.Second))
|
||||
})
|
||||
|
||||
t.Run("the list pages by a cursor bound to its owner", func(t *testing.T) {
|
||||
pager := client.candidate(t, "evidence-pager@example.test")
|
||||
first := passingIntern(pager)
|
||||
moveFinishedAttemptBack(t, ctx, harness.pool, first.id, categoryHTTPPromotionGap)
|
||||
second := client.run(t, pager, "backend", "junior", func(int) int { return threshold })
|
||||
if second.result["outcome"] != "confirmed" {
|
||||
t.Fatalf("promotion run = %v, want confirmed", second.result["outcome"])
|
||||
}
|
||||
firstPage, response := readOwn(pager, "?limit=1")
|
||||
if response.Code != http.StatusOK || len(firstPage.Items) != 1 || !firstPage.Page.HasMore || firstPage.Page.NextCursor == nil ||
|
||||
firstPage.Items[0].Source.ResultID != second.id || firstPage.Items[0].Result.Grade != "junior" {
|
||||
t.Fatalf("first page = %d %s, want the junior fact and a cursor", response.Code, response.Body.String())
|
||||
}
|
||||
secondPage, response := readOwn(pager, "?limit=1&cursor="+url.QueryEscape(*firstPage.Page.NextCursor))
|
||||
if response.Code != http.StatusOK || len(secondPage.Items) != 1 || secondPage.Page.HasMore || secondPage.Page.NextCursor != nil ||
|
||||
secondPage.Items[0].Source.ResultID != first.id || secondPage.Items[0].Result.Grade != "intern" {
|
||||
t.Fatalf("second page = %d %s, want the intern fact and no more", response.Code, response.Body.String())
|
||||
}
|
||||
if firstPage.Items[0].ID == secondPage.Items[0].ID {
|
||||
t.Fatal("two events produced one fact")
|
||||
}
|
||||
for _, query := range []string{"?cursor=" + url.QueryEscape(*firstPage.Page.NextCursor), "?limit=0", "?limit=101", "?cursor=not-a-cursor"} {
|
||||
who := pager
|
||||
if strings.HasPrefix(query, "?cursor="+url.QueryEscape(*firstPage.Page.NextCursor)) {
|
||||
who = target // the cursor belongs to the pager
|
||||
}
|
||||
if response := get(who, "/api/v1/me/evidence"+query); response.Code != http.StatusBadRequest {
|
||||
t.Fatalf("evidence query %q = %d %s, want 400", query, response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("the preview shows the one fact for each category that an organization would read", func(t *testing.T) {
|
||||
type previewBody struct {
|
||||
Card json.RawMessage `json:"card"`
|
||||
Evidence *struct {
|
||||
Items []struct {
|
||||
Skill string `json:"skill"`
|
||||
Grade string `json:"grade"`
|
||||
Trust int `json:"trust"`
|
||||
ObservedYear int `json:"observed_year"`
|
||||
Basis string `json:"basis"`
|
||||
Calibration string `json:"calibration_status"`
|
||||
} `json:"items"`
|
||||
} `json:"evidence"`
|
||||
}
|
||||
preview := func(who categoryHTTPCandidate) previewBody {
|
||||
t.Helper()
|
||||
response := get(who, "/api/v1/me/privacy/preview")
|
||||
var body previewBody
|
||||
if response.Code != http.StatusOK || response.Header().Get("Cache-Control") != "no-store" || json.Unmarshal(response.Body.Bytes(), &body) != nil {
|
||||
t.Fatalf("preview of %s = %d %q %s", who.email, response.Code, response.Header().Get("Cache-Control"), response.Body.String())
|
||||
}
|
||||
return body
|
||||
}
|
||||
decidedAt, _ := time.Parse(time.RFC3339Nano, targetRun.result["decided_at"].(string))
|
||||
body := preview(target)
|
||||
if body.Evidence == nil || len(body.Evidence.Items) != 1 || body.Evidence.Items[0].Skill != "backend" ||
|
||||
body.Evidence.Items[0].Grade != "intern" || body.Evidence.Items[0].Trust != 1 ||
|
||||
body.Evidence.Items[0].Basis != "synthetic_demo" || body.Evidence.Items[0].Calibration != "uncalibrated" || body.Evidence.Items[0].ObservedYear != decidedAt.UTC().Year() {
|
||||
t.Fatalf("preview evidence = %+v, want the backend intern fact of %d", body.Evidence, decidedAt.UTC().Year())
|
||||
}
|
||||
// A closed profile has no card and no evidence section.
|
||||
if closed := preview(failed); string(closed.Card) != "null" || closed.Evidence != nil {
|
||||
t.Fatalf("preview of a closed profile = card %s, evidence %+v, want both null", closed.Card, closed.Evidence)
|
||||
}
|
||||
|
||||
// A candidate with a lower and a higher passed grade: one fact, the one
|
||||
// that supports the confirmed grade, whichever way it is asked for.
|
||||
pagerAccount := client.candidate(t, "evidence-supporting@example.test")
|
||||
lower := passingIntern(pagerAccount)
|
||||
moveFinishedAttemptBack(t, ctx, harness.pool, lower.id, categoryHTTPPromotionGap)
|
||||
higher := client.run(t, pagerAccount, "backend", "junior", func(int) int { return threshold })
|
||||
if higher.result["outcome"] != "confirmed" {
|
||||
t.Fatalf("promotion run = %v, want confirmed", higher.result["outcome"])
|
||||
}
|
||||
consent := privacy.grant(t, pagerAccount.id, domain.ConsentPurposePublication, privacyC2Version, now)
|
||||
privacy.publish(t, pagerAccount.id, consent.ID(), 0, domain.CardFieldCategories)
|
||||
body = preview(pagerAccount)
|
||||
if body.Evidence == nil || len(body.Evidence.Items) != 1 || body.Evidence.Items[0].Grade != "junior" {
|
||||
t.Fatalf("preview evidence with two passed grades = %+v, want only the junior fact", body.Evidence)
|
||||
}
|
||||
if facts := organizationFacts(organizationA.ID(), pagerAccount.id, category(domain.SpecializationBackend, domain.GradeJunior)); len(facts) != 1 || facts[0].Input().Grade != domain.GradeJunior {
|
||||
t.Fatalf("organization evidence for the junior category = %+v, want the junior fact", facts)
|
||||
}
|
||||
if facts := organizationFacts(organizationA.ID(), pagerAccount.id, category(domain.SpecializationBackend, domain.GradeIntern)); len(facts) != 1 || facts[0].Input().Grade != domain.GradeIntern {
|
||||
t.Fatalf("organization evidence for the intern category = %+v, want the intern fact", facts)
|
||||
}
|
||||
// A hidden fact leaves the preview as it leaves the organization.
|
||||
if _, err := harness.pool.Exec(ctx, `UPDATE skill_evidence_facts SET visibility = 'hidden' WHERE candidate_id = $1`, pagerAccount.id); err != nil {
|
||||
t.Fatalf("hide the facts: %v", err)
|
||||
}
|
||||
if body = preview(pagerAccount); body.Evidence == nil || len(body.Evidence.Items) != 0 {
|
||||
t.Fatalf("preview evidence of hidden facts = %+v, want an empty list", body.Evidence)
|
||||
}
|
||||
if facts := organizationFacts(organizationA.ID(), pagerAccount.id, category(domain.SpecializationBackend, domain.GradeJunior)); len(facts) != 0 {
|
||||
t.Fatalf("organization evidence of hidden facts = %+v, want none", facts)
|
||||
}
|
||||
if _, err := harness.pool.Exec(ctx, `UPDATE skill_evidence_facts SET visibility = 'visible' WHERE candidate_id = $1`, pagerAccount.id); err != nil {
|
||||
t.Fatalf("show the facts: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("an organization reads the permitted projection only while the card is visible", func(t *testing.T) {
|
||||
handle := aliasIn(organizationA.ID(), target.id)
|
||||
path := organizationPath(organizationA.ID(), handle)
|
||||
response := get(employerAccount, path)
|
||||
if response.Code != http.StatusOK || response.Header().Get("Cache-Control") != "no-store" {
|
||||
t.Fatalf("permitted projection = %d %q %s\n%s", response.Code, response.Header().Get("Cache-Control"), response.Body.String(), harness.logs.String())
|
||||
}
|
||||
decidedAt, _ := time.Parse(time.RFC3339Nano, targetRun.result["decided_at"].(string))
|
||||
// One fact for the one category of the card, with the skill, the grade,
|
||||
// the trust level, and the year only; the other tags stay with the candidate.
|
||||
wantBody := fmt.Sprintf(`{"items":[{"skill":"backend","grade":"intern","trust":1,"basis":"synthetic_demo","calibration_status":"uncalibrated","observed_year":%d}]}`, decidedAt.UTC().Year())
|
||||
if strings.TrimSpace(response.Body.String()) != wantBody {
|
||||
t.Fatalf("permitted projection = %s, want %s", response.Body.String(), wantBody)
|
||||
}
|
||||
for _, private := range []string{target.id.String(), targetRun.id.String(), "event_id", "result_id", "occurred_at", "observed_month", "visibility", "answer", "score", "points", "signal", "review", "not_confirmed", `"id"`} {
|
||||
if strings.Contains(response.Body.String(), private) {
|
||||
t.Fatalf("permitted projection exposes %q: %s", private, response.Body.String())
|
||||
}
|
||||
}
|
||||
// The read is a card view: the quota is used once and the candidate sees the access.
|
||||
for range 2 {
|
||||
if again := get(employerAccount, path); again.Code != http.StatusOK {
|
||||
t.Fatalf("repeated projection = %d %s", again.Code, again.Body.String())
|
||||
}
|
||||
}
|
||||
if usage := countRows(`SELECT count(*) FROM company_card_view_quota_usage WHERE candidate_id = $1 AND organization_id = $2`, target.id, organizationA.ID()); usage != 1 {
|
||||
t.Fatalf("card-view quota usage = %d, want one distinct card", usage)
|
||||
}
|
||||
if audits := countRows(`SELECT count(*) FROM candidate_card_access_events WHERE candidate_id = $1 AND organization_id = $2 AND kind = 'card_viewed' AND field_codes = ARRAY['categories']::text[]`, target.id, organizationA.ID()); audits != 3 {
|
||||
t.Fatalf("access records of the categories field = %d, want 3", audits)
|
||||
}
|
||||
|
||||
// Access: the roles and the scope of the handle.
|
||||
if response := get(target, path); response.Code != http.StatusForbidden {
|
||||
t.Fatalf("candidate account reads the projection = %d, want 403", response.Code)
|
||||
}
|
||||
if response := get(categoryHTTPCandidate{}, path); response.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("guest reads the projection = %d, want 401", response.Code)
|
||||
}
|
||||
for name, other := range map[string]string{
|
||||
"other member's organization": organizationPath(foreignOrganization.ID(), handle),
|
||||
"unknown organization": organizationPath(uuid.New(), handle),
|
||||
"alias of another organization": organizationPath(organizationB.ID(), handle),
|
||||
"unknown alias": organizationPath(organizationA.ID(), "cv1_"+strings.Repeat("A", 43)),
|
||||
} {
|
||||
if response := get(employerAccount, other); response.Code != http.StatusNotFound {
|
||||
t.Fatalf("%s = %d %s, want 404", name, response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
if response := get(employerAccount, organizationPath(organizationA.ID(), "candidate")); response.Code != http.StatusBadRequest {
|
||||
t.Fatalf("malformed handle = %d, want 400", response.Code)
|
||||
}
|
||||
if response := get(foreignAccount, path); response.Code != http.StatusNotFound {
|
||||
t.Fatalf("employer without a membership = %d, want 404", response.Code)
|
||||
}
|
||||
|
||||
// The statement itself rechecks the barrier, whatever the caller did.
|
||||
backendIntern := category(domain.SpecializationBackend, domain.GradeIntern)
|
||||
if facts := organizationFacts(organizationA.ID(), target.id, backendIntern); len(facts) != 1 ||
|
||||
facts[0].Input() != (domain.EvidenceOrganizationFactInput{
|
||||
Skill: "backend", Grade: domain.GradeIntern, Trust: 1, Basis: domain.AssessmentCategorySourceSyntheticDemo,
|
||||
CalibrationStatus: domain.AssessmentCategoryCalibrationUncalibrated, ObservedYear: int32(decidedAt.UTC().Year()),
|
||||
}) {
|
||||
t.Fatalf("repository projection = %+v, want the one backend intern fact", facts)
|
||||
}
|
||||
for name, categories := range map[string][]domain.CandidateViewCategory{
|
||||
"a specialization without a fact": {category(domain.SpecializationQA, domain.GradeIntern)},
|
||||
"a grade the candidate did not pass": {category(domain.SpecializationBackend, domain.GradeSenior)},
|
||||
"no category on the card": nil,
|
||||
} {
|
||||
if facts := organizationFacts(organizationA.ID(), target.id, categories...); len(facts) != 0 {
|
||||
t.Fatalf("repository projection for %s = %+v, want none", name, facts)
|
||||
}
|
||||
}
|
||||
if facts := organizationFacts(organizationA.ID(), uuid.New(), backendIntern); len(facts) != 0 {
|
||||
t.Fatalf("repository projection for an unknown candidate = %+v, want none", facts)
|
||||
}
|
||||
|
||||
// A hidden fact is absent from what the organization reads.
|
||||
if _, err := harness.pool.Exec(ctx, `UPDATE skill_evidence_facts SET visibility = 'hidden' WHERE candidate_id = $1`, target.id); err != nil {
|
||||
t.Fatalf("hide the fact: %v", err)
|
||||
}
|
||||
hidden := get(employerAccount, path)
|
||||
if hidden.Code != http.StatusOK || strings.TrimSpace(hidden.Body.String()) != `{"items":[]}` {
|
||||
t.Fatalf("projection of a hidden fact = %d %s, want no data", hidden.Code, hidden.Body.String())
|
||||
}
|
||||
if page, _ := readOwn(target, ""); len(page.Items) != 1 || page.Items[0].Visibility != "hidden" {
|
||||
t.Fatalf("owner after hiding = %+v, want the fact with visibility hidden", page.Items)
|
||||
}
|
||||
if _, err := harness.pool.Exec(ctx, `UPDATE skill_evidence_facts SET visibility = 'visible' WHERE candidate_id = $1`, target.id); err != nil {
|
||||
t.Fatalf("show the fact: %v", err)
|
||||
}
|
||||
|
||||
// A card that does not publish the categories field carries no evidence.
|
||||
publication := privacy.loadPublication(t, target.id)
|
||||
privacy.publish(t, target.id, consents[target.id], publication.Version(), domain.CardFieldStack)
|
||||
if response := get(employerAccount, path); response.Code != http.StatusNotFound {
|
||||
t.Fatalf("projection of a card without categories = %d %s, want 404", response.Code, response.Body.String())
|
||||
}
|
||||
if facts := organizationFacts(organizationA.ID(), target.id, backendIntern); len(facts) != 0 {
|
||||
t.Fatalf("repository projection without the categories field = %+v, want none", facts)
|
||||
}
|
||||
publication = privacy.loadPublication(t, target.id)
|
||||
privacy.publish(t, target.id, consents[target.id], publication.Version(), domain.CardFieldCategories)
|
||||
if response := get(employerAccount, path); response.Code != http.StatusOK {
|
||||
t.Fatalf("projection after publishing the categories again = %d %s", response.Code, response.Body.String())
|
||||
}
|
||||
|
||||
// Hiding the organization closes it for that organization only.
|
||||
privacy.hide(t, target.id, organizationA.ID(), now.Add(2*time.Second))
|
||||
if response := get(employerAccount, path); response.Code != http.StatusNotFound {
|
||||
t.Fatalf("projection for a hidden organization = %d %s, want 404", response.Code, response.Body.String())
|
||||
}
|
||||
if facts := organizationFacts(organizationA.ID(), target.id, backendIntern); len(facts) != 0 {
|
||||
t.Fatalf("repository projection for a hidden organization = %+v, want none", facts)
|
||||
}
|
||||
if facts := organizationFacts(organizationB.ID(), target.id, backendIntern); len(facts) != 1 {
|
||||
t.Fatalf("repository projection for another organization = %+v, want one fact", facts)
|
||||
}
|
||||
if _, err := harness.pool.Exec(ctx, `DELETE FROM candidate_hidden_organizations WHERE user_id = $1`, target.id); err != nil {
|
||||
t.Fatalf("lift the hiding: %v", err)
|
||||
}
|
||||
if response := get(employerAccount, path); response.Code != http.StatusOK {
|
||||
t.Fatalf("projection after the hiding was lifted = %d %s", response.Code, response.Body.String())
|
||||
}
|
||||
|
||||
// C2 true, then false: after the revocation there is no data, for any organization.
|
||||
privacy.revokeC2(t, target.id, now.Add(3*time.Second))
|
||||
for _, organization := range []domain.Organization{organizationA, organizationB} {
|
||||
response := get(employerAccount, organizationPath(organization.ID(), aliasIn(organization.ID(), target.id)))
|
||||
if response.Code != http.StatusNotFound || strings.Contains(response.Body.String(), "measurement") {
|
||||
t.Fatalf("projection after the C2 revocation = %d %s, want 404 without data", response.Code, response.Body.String())
|
||||
}
|
||||
if facts := organizationFacts(organization.ID(), target.id, backendIntern); len(facts) != 0 {
|
||||
t.Fatalf("repository projection after the C2 revocation = %+v, want none", facts)
|
||||
}
|
||||
}
|
||||
if page, _ := readOwn(target, ""); len(page.Items) != 1 {
|
||||
t.Fatalf("owner evidence after the C2 revocation = %+v, want the fact kept", page.Items)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("deleting the account removes its facts through both cascade paths", func(t *testing.T) {
|
||||
erased := client.candidate(t, "evidence-erased@example.test")
|
||||
run := passingIntern(erased)
|
||||
if countRows(`SELECT count(*) FROM skill_evidence_facts WHERE candidate_id = $1`, erased.id) != 1 {
|
||||
t.Fatal("the candidate to erase has no fact")
|
||||
}
|
||||
// The ledger and history guards keep a confirmed account; this fixture
|
||||
// lifts them for one transaction, as the deletion procedure will. The
|
||||
// foreign keys and the triggers of the evidence stay on.
|
||||
tx, err := harness.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("begin the erasure: %v", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
for _, statement := range []string{
|
||||
`ALTER TABLE consent_records DISABLE TRIGGER USER`,
|
||||
`ALTER TABLE users DISABLE TRIGGER USER`,
|
||||
} {
|
||||
if _, err := tx.Exec(ctx, statement); err != nil {
|
||||
t.Fatalf("lift the retention guards (%s): %v", statement, err)
|
||||
}
|
||||
}
|
||||
// Both paths lead to the fact: the owner of the fact and the result it names.
|
||||
if _, err := tx.Exec(ctx, `ALTER TABLE assessment_attempt_results DISABLE TRIGGER assessment_attempt_result_refuse_mutation`); err != nil {
|
||||
t.Fatalf("lift the result guard: %v", err)
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `ALTER TABLE candidate_assessment_categories DISABLE TRIGGER candidate_assessment_category_refuse_delete`); err != nil {
|
||||
t.Fatalf("lift the category guard: %v", err)
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `DELETE FROM consent_records WHERE subject_id = $1`, erased.id); err != nil {
|
||||
t.Fatalf("delete the consent records: %v", err)
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `DELETE FROM users WHERE id = $1`, erased.id); err != nil {
|
||||
t.Fatalf("delete the account: %v", err)
|
||||
}
|
||||
for table, column := range map[string]string{
|
||||
"skill_evidence_facts": "candidate_id", "assessment_attempt_results": "user_id",
|
||||
} {
|
||||
var remaining int
|
||||
if err := tx.QueryRow(ctx, fmt.Sprintf(`SELECT count(*) FROM %s WHERE %s = $1`, table, column), erased.id).Scan(&remaining); err != nil || remaining != 0 {
|
||||
t.Fatalf("rows of %s after the account was deleted = %d (error %v), want 0", table, remaining, err)
|
||||
}
|
||||
}
|
||||
var tags int
|
||||
if err := tx.QueryRow(ctx, `SELECT count(*) FROM skill_evidence_skills AS tag WHERE NOT EXISTS (SELECT 1 FROM skill_evidence_facts WHERE id = tag.fact_id)`).Scan(&tags); err != nil || tags != 0 {
|
||||
t.Fatalf("orphan tags = %d (error %v), want 0", tags, err)
|
||||
}
|
||||
// The guards come back before the erasure is committed.
|
||||
for _, statement := range []string{
|
||||
`ALTER TABLE consent_records ENABLE TRIGGER USER`,
|
||||
`ALTER TABLE users ENABLE TRIGGER USER`,
|
||||
`ALTER TABLE assessment_attempt_results ENABLE TRIGGER assessment_attempt_result_refuse_mutation`,
|
||||
`ALTER TABLE candidate_assessment_categories ENABLE TRIGGER candidate_assessment_category_refuse_delete`,
|
||||
} {
|
||||
if _, err := tx.Exec(ctx, statement); err != nil {
|
||||
t.Fatalf("restore the guard (%s): %v", statement, err)
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
t.Fatalf("commit the erasure: %v", err)
|
||||
}
|
||||
if countRows(`SELECT count(*) FROM pg_trigger WHERE tgenabled = 'D' AND NOT tgisinternal`) != 0 {
|
||||
t.Fatal("a trigger stayed disabled after the erasure")
|
||||
}
|
||||
if countRows(`SELECT count(*) FROM skill_evidence_facts WHERE result_id = $1`, run.id) != 0 {
|
||||
t.Fatal("a fact of the erased account remains")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("the projection is rebuilt from the results and survives the migration", func(t *testing.T) {
|
||||
qualifying := countRows(`
|
||||
SELECT count(*) FROM assessment_attempt_results
|
||||
WHERE schema_version = 2 AND kind IN ('root', 'corrective') AND outcome = 'confirmed'
|
||||
AND category_decision ->> 'status' IN ('assigned', 'unchanged')`)
|
||||
eventsBefore := evidenceEventIDs(t, ctx, harness)
|
||||
// Cohort of five, two promotions of the pager and two of the candidate of the
|
||||
// preview; nothing from the failed or express runs.
|
||||
if want := evidenceCohortSize + 4; qualifying != want || len(eventsBefore) != want {
|
||||
t.Fatalf("qualifying results = %d, facts = %d, want %d of each", qualifying, len(eventsBefore), want)
|
||||
}
|
||||
|
||||
// A fact without a skill cannot be committed.
|
||||
if _, err := harness.pool.Exec(ctx, `TRUNCATE skill_evidence_skills, skill_evidence_facts`); err != nil {
|
||||
t.Fatalf("empty the projection: %v", err)
|
||||
}
|
||||
_, err := harness.pool.Exec(ctx, `
|
||||
INSERT INTO skill_evidence_facts (candidate_id, kind, source_type, event_id, result_id, attribution, trust, grade, basis, calibration_status, occurred_at)
|
||||
SELECT user_id, 'measurement', 'assessment_result', attempt_id, attempt_id, 'personal', 1, category_decision ->> 'attempted_grade',
|
||||
category_decision ->> 'source', category_decision ->> 'calibration_status', decided_at
|
||||
FROM assessment_attempt_results WHERE attempt_id = $1`, targetRun.id)
|
||||
assertPgError(t, "fact without a skill", err, "23514", "skill_evidence_facts_require_skill")
|
||||
|
||||
if _, err := harness.pool.Exec(ctx, `SELECT skill_evidence_project_assessment_result(attempt_id) FROM assessment_attempt_results`); err != nil {
|
||||
t.Fatalf("project the stored results again: %v", err)
|
||||
}
|
||||
if eventsAfter := evidenceEventIDs(t, ctx, harness); !slices.Equal(eventsAfter, eventsBefore) {
|
||||
t.Fatalf("rebuilt events = %v, want %v", eventsAfter, eventsBefore)
|
||||
}
|
||||
if _, err := harness.pool.Exec(ctx, `SELECT skill_evidence_project_assessment_result(attempt_id) FROM assessment_attempt_results`); err != nil {
|
||||
t.Fatalf("project the stored results a second time: %v", err)
|
||||
}
|
||||
if countRows(`SELECT count(*) FROM skill_evidence_facts`) != qualifying || countRows(`SELECT count(*) FROM skill_evidence_skills`) != qualifying {
|
||||
t.Fatal("a repeated projection duplicated facts or tags")
|
||||
}
|
||||
|
||||
// Rolling the migration back removes the projection and applying it again
|
||||
// derives it once more from the results that stayed.
|
||||
migrator := newMigrator(t, databaseURL)
|
||||
// A fact that the candidate hid is a decision no result can bring back, so
|
||||
// the rollback refuses until nothing is hidden.
|
||||
if _, err := harness.pool.Exec(ctx, `UPDATE skill_evidence_facts SET visibility = 'hidden' WHERE event_id = $1`, targetRun.id); err != nil {
|
||||
t.Fatalf("hide the fact: %v", err)
|
||||
}
|
||||
_, err = migrator.DownOne(ctx)
|
||||
assertPgError(t, "rollback with a hidden fact", err, "23000", "skill_evidence_retained")
|
||||
assertTablesExist(ctx, t, harness.pool, true, "skill_evidence_facts", "skill_evidence_skills")
|
||||
if _, err := harness.pool.Exec(ctx, `UPDATE skill_evidence_facts SET visibility = 'visible' WHERE event_id = $1`, targetRun.id); err != nil {
|
||||
t.Fatalf("show the fact: %v", err)
|
||||
}
|
||||
rollBackAboveMigration(ctx, t, migrator, skillEvidenceMigrationVersion-1)
|
||||
assertTablesExist(ctx, t, harness.pool, false, "skill_evidence_facts", "skill_evidence_skills")
|
||||
assertFunctionsExist(ctx, t, harness.pool, false,
|
||||
"skill_evidence_result_qualifies(assessment_attempt_results)", "skill_evidence_project_assessment_result(uuid)")
|
||||
applyMigrations(ctx, t, databaseURL)
|
||||
if eventsAfter := evidenceEventIDs(t, ctx, harness); !slices.Equal(eventsAfter, eventsBefore) {
|
||||
t.Fatalf("events after the migration was applied again = %v, want %v", eventsAfter, eventsBefore)
|
||||
}
|
||||
if page, _ := readOwn(target, ""); len(page.Items) != 1 || page.Items[0].Trust != 1 || page.Items[0].Source.ResultID != targetRun.id {
|
||||
t.Fatalf("evidence after the migration was applied again = %+v, want the backfilled fact", page.Items)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// readOwnBody returns the raw body of the owner's evidence.
|
||||
func readOwnBody(t *testing.T, get func(categoryHTTPCandidate, string) *httptest.ResponseRecorder, who categoryHTTPCandidate) string {
|
||||
t.Helper()
|
||||
response := get(who, "/api/v1/me/evidence")
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("own evidence = %d %s", response.Code, response.Body.String())
|
||||
}
|
||||
return response.Body.String()
|
||||
}
|
||||
|
||||
// evidenceEventIDs lists the source events of the stored facts in a stable order.
|
||||
func evidenceEventIDs(t *testing.T, ctx context.Context, harness *skillEvidenceHarness) []string {
|
||||
t.Helper()
|
||||
rows, err := harness.pool.Query(ctx, `SELECT event_id::text FROM skill_evidence_facts ORDER BY event_id`)
|
||||
if err != nil {
|
||||
t.Fatalf("list evidence events: %v", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
events, err := pgx.CollectRows(rows, pgx.RowTo[string])
|
||||
if err != nil {
|
||||
t.Fatalf("read evidence events: %v", err)
|
||||
}
|
||||
return events
|
||||
}
|
||||
|
||||
// runPerfectExpress answers every item of an express training run correctly,
|
||||
// finalizes it, and returns its attempt identifier.
|
||||
func runPerfectExpress(t *testing.T, ctx context.Context, client *categoryHTTPClient, harness *assessmentAttemptHTTPHarness, who categoryHTTPCandidate) uuid.UUID {
|
||||
t.Helper()
|
||||
key := uuid.NewString()
|
||||
status, body := client.call(t, who, http.MethodPost, "/api/v1/me/assessment-attempts", `{"kind":"demo_express"}`, key+"-create")
|
||||
var attempt assessmentAnswerHTTPAttempt
|
||||
if status != http.StatusCreated || json.Unmarshal(body, &attempt) != nil || attempt.ID == uuid.Nil {
|
||||
t.Fatalf("create express attempt = %d %s", status, body)
|
||||
}
|
||||
version := attempt.Version
|
||||
for _, item := range readAssessmentAnswerHTTPItems(t, ctx, harness, attempt.ID) {
|
||||
status, body := client.call(t, who, http.MethodPost, "/api/v1/me/assessment-attempts/"+attempt.ID.String()+"/answers",
|
||||
string(assessmentAnswerHTTPBody(t, version, item)), fmt.Sprintf("%s-answer-%d", key, item.Ordinal))
|
||||
var next assessmentAnswerHTTPAttempt
|
||||
if status != http.StatusOK || json.Unmarshal(body, &next) != nil {
|
||||
t.Fatalf("answer express item %d = %d %s", item.Ordinal, status, body)
|
||||
}
|
||||
version = next.Version
|
||||
}
|
||||
finalizeBody, err := json.Marshal(map[string]int64{"expected_version": version})
|
||||
if err != nil {
|
||||
t.Fatalf("marshal finalize body: %v", err)
|
||||
}
|
||||
if status, body := client.call(t, who, http.MethodPost, "/api/v1/me/assessment-attempts/"+attempt.ID.String()+"/finalize",
|
||||
string(finalizeBody), key+"-finalize"); status != http.StatusOK {
|
||||
t.Fatalf("finalize express attempt = %d %s", status, body)
|
||||
}
|
||||
if result := client.result(t, who, attempt.ID); result["outcome"] != "demonstration" {
|
||||
t.Fatalf("express result = %v, want a demonstration", result)
|
||||
}
|
||||
return attempt.ID
|
||||
}
|
||||
@@ -4511,6 +4511,13 @@ func (s *Server) handleGetMyAssessmentSignalNoticeRequest(args [0]string, argsEs
|
||||
// formats appear only through their separate explicit publication choices, and self-assessment never
|
||||
// becomes a confirmed category. Salary compatibility is nullable and contains no salary amount.
|
||||
//
|
||||
// `evidence` shows what an organization would read in the evidence section of the card
|
||||
// (`GetOrganizationCandidateEvidence`): for each category of the card, the one assessment fact that
|
||||
// supports its confirmed grade, with its skill, the passed grade, the trust level, the year, and the
|
||||
// basis and calibration (`synthetic_demo`, `uncalibrated`). It is null while `card` is null, and an
|
||||
// empty list when the card shows no category or no visible fact supports one. The preview applies no
|
||||
// organization or cohort, so an organization can still receive less.
|
||||
//
|
||||
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account
|
||||
// answers 403 forbidden.
|
||||
//
|
||||
@@ -6379,6 +6386,243 @@ func (s *Server) handleGetOrganizationCandidateCardRequest(args [2]string, argsE
|
||||
}
|
||||
}
|
||||
|
||||
// handleGetOrganizationCandidateEvidenceRequest handles GetOrganizationCandidateEvidence operation.
|
||||
//
|
||||
// Requires the session cookie of an employer account with an active membership in `org_id`. The
|
||||
// organization and membership come from the current server-side session and path, never from cached
|
||||
// search data.
|
||||
//
|
||||
// `candidate_handle` is the organization-scoped opaque alias issued by the current anonymous-card
|
||||
// projection. The server runs the same checks as the card read on every request: active membership,
|
||||
// effective C2 publication, the candidate's hiding of this organization, and the minimum cohort. In
|
||||
// addition the card must publish the `categories` field and show at least one category after the
|
||||
// cohort rules, because the evidence explains those categories and discloses nothing beyond them. An
|
||||
// unknown handle, a handle of another organization, a closed or revoked publication, a profile hidden
|
||||
// from this organization, a profile suppressed by the minimum cohort, and a card without categories
|
||||
// all answer the same 404 not_found. Closing C2 or hiding the organization blocks this read
|
||||
// immediately, and a cached response proves nothing.
|
||||
//
|
||||
// The response lists, for each category of the card, the one visible fact that supports its confirmed
|
||||
// grade: the earliest assessment that passed exactly that grade, so a lower grade or a retake adds
|
||||
// nothing. A fact the candidate hid is absent. Each fact carries only the skill, the passed grade, the
|
||||
// trust level, the year of the assessment, and the basis and calibration of the method
|
||||
// (`synthetic_demo`, `uncalibrated`), which are the same for every candidate and say that the fact is
|
||||
// a demonstration, not a validated measurement. It carries no identifier of the fact, event, result,
|
||||
// or candidate, no month or exact time, and never an answer, item, score, failed attempt, review band,
|
||||
// or anti-cheat signal. An express training run and a failed attempt create no fact. The answer has no
|
||||
// key that joins it to a person, but it is not unlinkable: with the other values of the card it can
|
||||
// narrow a small pool of candidates.
|
||||
//
|
||||
// Reading the evidence is a view of the candidate card: it consumes the organization's current
|
||||
// card-view quota with the same distinct-card rule and is recorded in the access history with the
|
||||
// `categories` field. When the quota is exhausted the operation answers 429 with Retry-After. The
|
||||
// response is `Cache-Control: no-store`.
|
||||
//
|
||||
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account
|
||||
// answers 403 forbidden; an unknown organization or account without an active membership answers 404
|
||||
// not_found. An `org_id` that is not a UUID or a malformed candidate handle answers 400
|
||||
// validation_failed.
|
||||
//
|
||||
// GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}/evidence
|
||||
func (s *Server) handleGetOrganizationCandidateEvidenceRequest(args [2]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
|
||||
statusWriter := &codeRecorder{ResponseWriter: w}
|
||||
w = statusWriter
|
||||
otelAttrs := []attribute.KeyValue{
|
||||
otelogen.OperationID("GetOrganizationCandidateEvidence"),
|
||||
semconv.HTTPRequestMethodKey.String("GET"),
|
||||
semconv.HTTPRouteKey.String("/api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}/evidence"),
|
||||
}
|
||||
// Add attributes from config.
|
||||
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
|
||||
|
||||
// Start a span for this request.
|
||||
ctx, span := s.cfg.Tracer.Start(r.Context(), GetOrganizationCandidateEvidenceOperation,
|
||||
trace.WithAttributes(otelAttrs...),
|
||||
serverSpanKind,
|
||||
)
|
||||
defer span.End()
|
||||
|
||||
// Add Labeler to context.
|
||||
labeler := &Labeler{attrs: otelAttrs}
|
||||
ctx = contextWithLabeler(ctx, labeler)
|
||||
|
||||
// Run stopwatch.
|
||||
startTime := time.Now()
|
||||
defer func() {
|
||||
elapsedDuration := time.Since(startTime)
|
||||
|
||||
attrSet := labeler.AttributeSet()
|
||||
attrs := attrSet.ToSlice()
|
||||
code := statusWriter.status
|
||||
if code != 0 {
|
||||
codeAttr := semconv.HTTPResponseStatusCode(code)
|
||||
attrs = append(attrs, codeAttr)
|
||||
span.SetAttributes(attrs...)
|
||||
}
|
||||
attrOpt := metric.WithAttributes(attrs...)
|
||||
|
||||
// Increment request counter.
|
||||
s.requests.Add(ctx, 1, attrOpt)
|
||||
|
||||
// Use floating point division here for higher precision (instead of Millisecond method).
|
||||
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
|
||||
}()
|
||||
|
||||
var (
|
||||
recordError = func(stage string, err error) {
|
||||
span.RecordError(err)
|
||||
|
||||
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
|
||||
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
|
||||
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
|
||||
// max redirects exceeded), in which case status MUST be set to Error.
|
||||
code := statusWriter.status
|
||||
if code < 100 || code >= 500 {
|
||||
span.SetStatus(codes.Error, stage)
|
||||
}
|
||||
|
||||
attrSet := labeler.AttributeSet()
|
||||
attrs := attrSet.ToSlice()
|
||||
if code != 0 {
|
||||
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
|
||||
}
|
||||
|
||||
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
|
||||
}
|
||||
err error
|
||||
opErrContext = ogenerrors.OperationContext{
|
||||
Name: GetOrganizationCandidateEvidenceOperation,
|
||||
ID: "GetOrganizationCandidateEvidence",
|
||||
}
|
||||
)
|
||||
{
|
||||
type bitset = [1]uint8
|
||||
var satisfied bitset
|
||||
{
|
||||
sctx, ok, err := s.securitySessionCookie(ctx, GetOrganizationCandidateEvidenceOperation, r)
|
||||
if err != nil {
|
||||
err = &ogenerrors.SecurityError{
|
||||
OperationContext: opErrContext,
|
||||
Security: "SessionCookie",
|
||||
Err: err,
|
||||
}
|
||||
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
|
||||
defer recordError("Security:SessionCookie", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if ok {
|
||||
satisfied[0] |= 1 << 0
|
||||
ctx = sctx
|
||||
}
|
||||
}
|
||||
|
||||
if ok := func() bool {
|
||||
nextRequirement:
|
||||
for _, requirement := range []bitset{
|
||||
{0b00000001},
|
||||
} {
|
||||
for i, mask := range requirement {
|
||||
if satisfied[i]&mask != mask {
|
||||
continue nextRequirement
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}(); !ok {
|
||||
err = &ogenerrors.SecurityError{
|
||||
OperationContext: opErrContext,
|
||||
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
|
||||
}
|
||||
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
|
||||
defer recordError("Security", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
params, err := decodeGetOrganizationCandidateEvidenceParams(args, argsEscaped, r)
|
||||
if err != nil {
|
||||
err = &ogenerrors.DecodeParamsError{
|
||||
OperationContext: opErrContext,
|
||||
Err: err,
|
||||
}
|
||||
defer recordError("DecodeParams", err)
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
var rawBody []byte
|
||||
|
||||
var response GetOrganizationCandidateEvidenceRes
|
||||
if m := s.cfg.Middleware; m != nil {
|
||||
mreq := middleware.Request{
|
||||
Context: ctx,
|
||||
OperationName: GetOrganizationCandidateEvidenceOperation,
|
||||
OperationSummary: "Read the permitted skill evidence of one currently visible candidate card.",
|
||||
OperationID: "GetOrganizationCandidateEvidence",
|
||||
Body: nil,
|
||||
RawBody: rawBody,
|
||||
Params: middleware.Parameters{
|
||||
{
|
||||
Name: "org_id",
|
||||
In: "path",
|
||||
}: params.OrgID,
|
||||
{
|
||||
Name: "candidate_handle",
|
||||
In: "path",
|
||||
}: params.CandidateHandle,
|
||||
},
|
||||
Raw: r,
|
||||
}
|
||||
|
||||
type (
|
||||
Request = struct{}
|
||||
Params = GetOrganizationCandidateEvidenceParams
|
||||
Response = GetOrganizationCandidateEvidenceRes
|
||||
)
|
||||
response, err = middleware.HookMiddleware[
|
||||
Request,
|
||||
Params,
|
||||
Response,
|
||||
](
|
||||
m,
|
||||
mreq,
|
||||
unpackGetOrganizationCandidateEvidenceParams,
|
||||
func(ctx context.Context, request Request, params Params) (response Response, err error) {
|
||||
response, err = s.h.GetOrganizationCandidateEvidence(ctx, params)
|
||||
return response, err
|
||||
},
|
||||
)
|
||||
} else {
|
||||
response, err = s.h.GetOrganizationCandidateEvidence(ctx, params)
|
||||
}
|
||||
if err != nil {
|
||||
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
|
||||
if err := encodeErrorResponse(errRes, w, span); err != nil {
|
||||
defer recordError("Internal", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if errors.Is(err, ht.ErrNotImplemented) {
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
return
|
||||
}
|
||||
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
|
||||
defer recordError("Internal", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if err := encodeGetOrganizationCandidateEvidenceResponse(response, w, span); err != nil {
|
||||
defer recordError("EncodeResponse", err)
|
||||
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// handleGetOrganizationInvitationRequest handles GetOrganizationInvitation operation.
|
||||
//
|
||||
// Requires the session cookie of an employer account with an active membership in `org_id`. The
|
||||
@@ -8367,6 +8611,228 @@ func (s *Server) handleListMyConsentsRequest(args [0]string, argsEscaped bool, w
|
||||
}
|
||||
}
|
||||
|
||||
// handleListMyEvidenceRequest handles ListMyEvidence operation.
|
||||
//
|
||||
// Requires the session cookie of a candidate account. The candidate comes from the session, so the
|
||||
// response holds only the caller's own facts. Returns a page, newest event first with the fact
|
||||
// identifier as the tie-breaker, with cursor pagination. The response is `Cache-Control: no-store`.
|
||||
//
|
||||
// A fact is derived from the immutable result of a confirmed real assessment (root or corrective), in
|
||||
// the same transaction that stores the result. Each fact names its source (the event and the result,
|
||||
// which the candidate can open at `GetMyAssessmentResult`), the skills of the event, the grade that
|
||||
// was passed with its basis and calibration, the attribution, the date, the visibility, and the trust
|
||||
// level. An online assessment without a reliable confirmation of the identity has trust 1. One source
|
||||
// event is one fact: its skills are tags of that fact, so several tags never make several facts.
|
||||
//
|
||||
// The list never carries raw answers, items, scores, failed attempts, or anti-cheat data. A failed
|
||||
// attempt, a result without a reviewed category source, and an express training run (`demo_express`)
|
||||
// create no fact, so reading the list before and after an express run shows no new fact. The list
|
||||
// includes facts the candidate hid, with `visibility` `hidden`.
|
||||
//
|
||||
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account, or
|
||||
// a candidate with an unverified email, answers 403 forbidden. A malformed `limit` or `cursor`, or a
|
||||
// cursor of another candidate, answers 400 validation_failed.
|
||||
//
|
||||
// GET /api/v1/me/evidence
|
||||
func (s *Server) handleListMyEvidenceRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
|
||||
statusWriter := &codeRecorder{ResponseWriter: w}
|
||||
w = statusWriter
|
||||
otelAttrs := []attribute.KeyValue{
|
||||
otelogen.OperationID("ListMyEvidence"),
|
||||
semconv.HTTPRequestMethodKey.String("GET"),
|
||||
semconv.HTTPRouteKey.String("/api/v1/me/evidence"),
|
||||
}
|
||||
// Add attributes from config.
|
||||
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
|
||||
|
||||
// Start a span for this request.
|
||||
ctx, span := s.cfg.Tracer.Start(r.Context(), ListMyEvidenceOperation,
|
||||
trace.WithAttributes(otelAttrs...),
|
||||
serverSpanKind,
|
||||
)
|
||||
defer span.End()
|
||||
|
||||
// Add Labeler to context.
|
||||
labeler := &Labeler{attrs: otelAttrs}
|
||||
ctx = contextWithLabeler(ctx, labeler)
|
||||
|
||||
// Run stopwatch.
|
||||
startTime := time.Now()
|
||||
defer func() {
|
||||
elapsedDuration := time.Since(startTime)
|
||||
|
||||
attrSet := labeler.AttributeSet()
|
||||
attrs := attrSet.ToSlice()
|
||||
code := statusWriter.status
|
||||
if code != 0 {
|
||||
codeAttr := semconv.HTTPResponseStatusCode(code)
|
||||
attrs = append(attrs, codeAttr)
|
||||
span.SetAttributes(attrs...)
|
||||
}
|
||||
attrOpt := metric.WithAttributes(attrs...)
|
||||
|
||||
// Increment request counter.
|
||||
s.requests.Add(ctx, 1, attrOpt)
|
||||
|
||||
// Use floating point division here for higher precision (instead of Millisecond method).
|
||||
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
|
||||
}()
|
||||
|
||||
var (
|
||||
recordError = func(stage string, err error) {
|
||||
span.RecordError(err)
|
||||
|
||||
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
|
||||
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
|
||||
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
|
||||
// max redirects exceeded), in which case status MUST be set to Error.
|
||||
code := statusWriter.status
|
||||
if code < 100 || code >= 500 {
|
||||
span.SetStatus(codes.Error, stage)
|
||||
}
|
||||
|
||||
attrSet := labeler.AttributeSet()
|
||||
attrs := attrSet.ToSlice()
|
||||
if code != 0 {
|
||||
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
|
||||
}
|
||||
|
||||
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
|
||||
}
|
||||
err error
|
||||
opErrContext = ogenerrors.OperationContext{
|
||||
Name: ListMyEvidenceOperation,
|
||||
ID: "ListMyEvidence",
|
||||
}
|
||||
)
|
||||
{
|
||||
type bitset = [1]uint8
|
||||
var satisfied bitset
|
||||
{
|
||||
sctx, ok, err := s.securitySessionCookie(ctx, ListMyEvidenceOperation, r)
|
||||
if err != nil {
|
||||
err = &ogenerrors.SecurityError{
|
||||
OperationContext: opErrContext,
|
||||
Security: "SessionCookie",
|
||||
Err: err,
|
||||
}
|
||||
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
|
||||
defer recordError("Security:SessionCookie", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if ok {
|
||||
satisfied[0] |= 1 << 0
|
||||
ctx = sctx
|
||||
}
|
||||
}
|
||||
|
||||
if ok := func() bool {
|
||||
nextRequirement:
|
||||
for _, requirement := range []bitset{
|
||||
{0b00000001},
|
||||
} {
|
||||
for i, mask := range requirement {
|
||||
if satisfied[i]&mask != mask {
|
||||
continue nextRequirement
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}(); !ok {
|
||||
err = &ogenerrors.SecurityError{
|
||||
OperationContext: opErrContext,
|
||||
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
|
||||
}
|
||||
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
|
||||
defer recordError("Security", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
params, err := decodeListMyEvidenceParams(args, argsEscaped, r)
|
||||
if err != nil {
|
||||
err = &ogenerrors.DecodeParamsError{
|
||||
OperationContext: opErrContext,
|
||||
Err: err,
|
||||
}
|
||||
defer recordError("DecodeParams", err)
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
var rawBody []byte
|
||||
|
||||
var response ListMyEvidenceRes
|
||||
if m := s.cfg.Middleware; m != nil {
|
||||
mreq := middleware.Request{
|
||||
Context: ctx,
|
||||
OperationName: ListMyEvidenceOperation,
|
||||
OperationSummary: "List the skill evidence of the current candidate.",
|
||||
OperationID: "ListMyEvidence",
|
||||
Body: nil,
|
||||
RawBody: rawBody,
|
||||
Params: middleware.Parameters{
|
||||
{
|
||||
Name: "limit",
|
||||
In: "query",
|
||||
}: params.Limit,
|
||||
{
|
||||
Name: "cursor",
|
||||
In: "query",
|
||||
}: params.Cursor,
|
||||
},
|
||||
Raw: r,
|
||||
}
|
||||
|
||||
type (
|
||||
Request = struct{}
|
||||
Params = ListMyEvidenceParams
|
||||
Response = ListMyEvidenceRes
|
||||
)
|
||||
response, err = middleware.HookMiddleware[
|
||||
Request,
|
||||
Params,
|
||||
Response,
|
||||
](
|
||||
m,
|
||||
mreq,
|
||||
unpackListMyEvidenceParams,
|
||||
func(ctx context.Context, request Request, params Params) (response Response, err error) {
|
||||
response, err = s.h.ListMyEvidence(ctx, params)
|
||||
return response, err
|
||||
},
|
||||
)
|
||||
} else {
|
||||
response, err = s.h.ListMyEvidence(ctx, params)
|
||||
}
|
||||
if err != nil {
|
||||
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
|
||||
if err := encodeErrorResponse(errRes, w, span); err != nil {
|
||||
defer recordError("Internal", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if errors.Is(err, ht.ErrNotImplemented) {
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
return
|
||||
}
|
||||
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
|
||||
defer recordError("Internal", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if err := encodeListMyEvidenceResponse(response, w, span); err != nil {
|
||||
defer recordError("EncodeResponse", err)
|
||||
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// handleListMyHiddenOrganizationsRequest handles ListMyHiddenOrganizations operation.
|
||||
//
|
||||
// Requires the session cookie of a candidate account. The candidate comes from the session, so the
|
||||
|
||||
@@ -105,6 +105,10 @@ type GetOrganizationCandidateCardRes interface {
|
||||
getOrganizationCandidateCardRes()
|
||||
}
|
||||
|
||||
type GetOrganizationCandidateEvidenceRes interface {
|
||||
getOrganizationCandidateEvidenceRes()
|
||||
}
|
||||
|
||||
type GetOrganizationInvitationContactsRes interface {
|
||||
getOrganizationInvitationContactsRes()
|
||||
}
|
||||
@@ -141,6 +145,10 @@ type ListMyConsentsRes interface {
|
||||
listMyConsentsRes()
|
||||
}
|
||||
|
||||
type ListMyEvidenceRes interface {
|
||||
listMyEvidenceRes()
|
||||
}
|
||||
|
||||
type ListMyHiddenOrganizationsRes interface {
|
||||
listMyHiddenOrganizationsRes()
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -34,6 +34,7 @@ const (
|
||||
GetMySupportCaseOperation OperationName = "GetMySupportCase"
|
||||
GetOrganizationOperation OperationName = "GetOrganization"
|
||||
GetOrganizationCandidateCardOperation OperationName = "GetOrganizationCandidateCard"
|
||||
GetOrganizationCandidateEvidenceOperation OperationName = "GetOrganizationCandidateEvidence"
|
||||
GetOrganizationInvitationOperation OperationName = "GetOrganizationInvitation"
|
||||
GetOrganizationInvitationContactsOperation OperationName = "GetOrganizationInvitationContacts"
|
||||
GetOrganizationNeedOperation OperationName = "GetOrganizationNeed"
|
||||
@@ -43,6 +44,7 @@ const (
|
||||
ListMyAssessmentResultsOperation OperationName = "ListMyAssessmentResults"
|
||||
ListMyCardAccessHistoryOperation OperationName = "ListMyCardAccessHistory"
|
||||
ListMyConsentsOperation OperationName = "ListMyConsents"
|
||||
ListMyEvidenceOperation OperationName = "ListMyEvidence"
|
||||
ListMyHiddenOrganizationsOperation OperationName = "ListMyHiddenOrganizations"
|
||||
ListMyInvitationsOperation OperationName = "ListMyInvitations"
|
||||
ListMyOrganizationsOperation OperationName = "ListMyOrganizations"
|
||||
|
||||
@@ -1917,6 +1917,147 @@ func decodeGetOrganizationCandidateCardParams(args [2]string, argsEscaped bool,
|
||||
return params, nil
|
||||
}
|
||||
|
||||
// GetOrganizationCandidateEvidenceParams is parameters of GetOrganizationCandidateEvidence operation.
|
||||
type GetOrganizationCandidateEvidenceParams struct {
|
||||
// Identifier of an organization. Access comes only from an active membership of the session account in
|
||||
// this organization, checked by the server on every request; the identifier itself grants nothing. An
|
||||
// organization without such a membership and an unknown identifier both answer 404 not_found, so
|
||||
// organizations cannot be enumerated.
|
||||
OrgID uuid.UUID
|
||||
// Organization-scoped opaque candidate alias issued by the current visible card projection. The server
|
||||
// resolves it only for the organization in the path and rechecks current membership, publication
|
||||
// consent, and hiding on every read. Unknown, hidden, unpublished, and suppressed candidates all
|
||||
// answer the same 404.
|
||||
CandidateHandle CandidateHandle
|
||||
}
|
||||
|
||||
func unpackGetOrganizationCandidateEvidenceParams(packed middleware.Parameters) (params GetOrganizationCandidateEvidenceParams) {
|
||||
{
|
||||
key := middleware.ParameterKey{
|
||||
Name: "org_id",
|
||||
In: "path",
|
||||
}
|
||||
params.OrgID = packed[key].(uuid.UUID)
|
||||
}
|
||||
{
|
||||
key := middleware.ParameterKey{
|
||||
Name: "candidate_handle",
|
||||
In: "path",
|
||||
}
|
||||
params.CandidateHandle = packed[key].(CandidateHandle)
|
||||
}
|
||||
return params
|
||||
}
|
||||
|
||||
func decodeGetOrganizationCandidateEvidenceParams(args [2]string, argsEscaped bool, r *http.Request) (params GetOrganizationCandidateEvidenceParams, _ error) {
|
||||
// Decode path: org_id.
|
||||
if err := func() error {
|
||||
param := args[0]
|
||||
if argsEscaped {
|
||||
unescaped, err := url.PathUnescape(args[0])
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "unescape path")
|
||||
}
|
||||
param = unescaped
|
||||
}
|
||||
if len(param) > 0 {
|
||||
d := uri.NewPathDecoder(uri.PathDecoderConfig{
|
||||
Param: "org_id",
|
||||
Value: param,
|
||||
Style: uri.PathStyleSimple,
|
||||
Explode: false,
|
||||
})
|
||||
|
||||
if err := func() error {
|
||||
val, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToUUID(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
params.OrgID = c
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return validate.ErrFieldRequired
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, &ogenerrors.DecodeParamError{
|
||||
Name: "org_id",
|
||||
In: "path",
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
// Decode path: candidate_handle.
|
||||
if err := func() error {
|
||||
param := args[1]
|
||||
if argsEscaped {
|
||||
unescaped, err := url.PathUnescape(args[1])
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "unescape path")
|
||||
}
|
||||
param = unescaped
|
||||
}
|
||||
if len(param) > 0 {
|
||||
d := uri.NewPathDecoder(uri.PathDecoderConfig{
|
||||
Param: "candidate_handle",
|
||||
Value: param,
|
||||
Style: uri.PathStyleSimple,
|
||||
Explode: false,
|
||||
})
|
||||
|
||||
if err := func() error {
|
||||
var paramsDotCandidateHandleVal string
|
||||
if err := func() error {
|
||||
val, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToString(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
paramsDotCandidateHandleVal = c
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
params.CandidateHandle = CandidateHandle(paramsDotCandidateHandleVal)
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := func() error {
|
||||
if err := params.CandidateHandle.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return validate.ErrFieldRequired
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, &ogenerrors.DecodeParamError{
|
||||
Name: "candidate_handle",
|
||||
In: "path",
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
return params, nil
|
||||
}
|
||||
|
||||
// GetOrganizationInvitationParams is parameters of GetOrganizationInvitation operation.
|
||||
type GetOrganizationInvitationParams struct {
|
||||
// Identifier of an organization. Access comes only from an active membership of the session account in
|
||||
@@ -3027,6 +3168,182 @@ func decodeListMyConsentsParams(args [0]string, argsEscaped bool, r *http.Reques
|
||||
return params, nil
|
||||
}
|
||||
|
||||
// ListMyEvidenceParams is parameters of ListMyEvidence operation.
|
||||
type ListMyEvidenceParams struct {
|
||||
// Maximum number of items in the page. The server may return fewer items even when more remain; use
|
||||
// `page.has_more` to detect the end.
|
||||
Limit OptInt32 `json:",omitempty,omitzero"`
|
||||
// Opaque `page.next_cursor` value from the previous page of the same listing. Omit it to read the
|
||||
// first page. A malformed or foreign cursor returns 400 with code validation_failed.
|
||||
Cursor OptString `json:",omitempty,omitzero"`
|
||||
}
|
||||
|
||||
func unpackListMyEvidenceParams(packed middleware.Parameters) (params ListMyEvidenceParams) {
|
||||
{
|
||||
key := middleware.ParameterKey{
|
||||
Name: "limit",
|
||||
In: "query",
|
||||
}
|
||||
if v, ok := packed[key]; ok {
|
||||
params.Limit = v.(OptInt32)
|
||||
}
|
||||
}
|
||||
{
|
||||
key := middleware.ParameterKey{
|
||||
Name: "cursor",
|
||||
In: "query",
|
||||
}
|
||||
if v, ok := packed[key]; ok {
|
||||
params.Cursor = v.(OptString)
|
||||
}
|
||||
}
|
||||
return params
|
||||
}
|
||||
|
||||
func decodeListMyEvidenceParams(args [0]string, argsEscaped bool, r *http.Request) (params ListMyEvidenceParams, _ error) {
|
||||
q := uri.NewQueryDecoder(r.URL.Query())
|
||||
// Set default value for query: limit.
|
||||
{
|
||||
val := int32(20)
|
||||
params.Limit.SetTo(val)
|
||||
}
|
||||
// Decode query: limit.
|
||||
if err := func() error {
|
||||
cfg := uri.QueryParameterDecodingConfig{
|
||||
Name: "limit",
|
||||
Style: uri.QueryStyleForm,
|
||||
Explode: true,
|
||||
}
|
||||
|
||||
if err := q.HasParam(cfg); err == nil {
|
||||
if err := q.DecodeParam(cfg, func(d uri.Decoder) error {
|
||||
var paramsDotLimitVal int32
|
||||
if err := func() error {
|
||||
val, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToInt32(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
paramsDotLimitVal = c
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
params.Limit.SetTo(paramsDotLimitVal)
|
||||
return nil
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := func() error {
|
||||
if value, ok := params.Limit.Get(); ok {
|
||||
if err := func() error {
|
||||
if err := (validate.Int{
|
||||
MinSet: true,
|
||||
Min: 1,
|
||||
MaxSet: true,
|
||||
Max: 100,
|
||||
MinExclusive: false,
|
||||
MaxExclusive: false,
|
||||
MultipleOfSet: false,
|
||||
MultipleOf: 0,
|
||||
Pattern: nil,
|
||||
}).Validate(int64(value)); err != nil {
|
||||
return errors.Wrap(err, "int")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, &ogenerrors.DecodeParamError{
|
||||
Name: "limit",
|
||||
In: "query",
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
// Decode query: cursor.
|
||||
if err := func() error {
|
||||
cfg := uri.QueryParameterDecodingConfig{
|
||||
Name: "cursor",
|
||||
Style: uri.QueryStyleForm,
|
||||
Explode: true,
|
||||
}
|
||||
|
||||
if err := q.HasParam(cfg); err == nil {
|
||||
if err := q.DecodeParam(cfg, func(d uri.Decoder) error {
|
||||
var paramsDotCursorVal string
|
||||
if err := func() error {
|
||||
val, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToString(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
paramsDotCursorVal = c
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
params.Cursor.SetTo(paramsDotCursorVal)
|
||||
return nil
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := func() error {
|
||||
if value, ok := params.Cursor.Get(); ok {
|
||||
if err := func() error {
|
||||
if err := (validate.String{
|
||||
MinLength: 1,
|
||||
MinLengthSet: true,
|
||||
MaxLength: 512,
|
||||
MaxLengthSet: true,
|
||||
Email: false,
|
||||
Hostname: false,
|
||||
Regex: regexMap["^[A-Za-z0-9_-]+$"],
|
||||
MinNumeric: 0,
|
||||
MinNumericSet: false,
|
||||
MaxNumeric: 0,
|
||||
MaxNumericSet: false,
|
||||
}).Validate(string(value)); err != nil {
|
||||
return errors.Wrap(err, "string")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, &ogenerrors.DecodeParamError{
|
||||
Name: "cursor",
|
||||
In: "query",
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
return params, nil
|
||||
}
|
||||
|
||||
// ListMyHiddenOrganizationsParams is parameters of ListMyHiddenOrganizations operation.
|
||||
type ListMyHiddenOrganizationsParams struct {
|
||||
// Maximum number of items in the page. The server may return fewer items even when more remain; use
|
||||
|
||||
@@ -2472,6 +2472,121 @@ func encodeGetOrganizationCandidateCardResponse(response GetOrganizationCandidat
|
||||
}
|
||||
}
|
||||
|
||||
func encodeGetOrganizationCandidateEvidenceResponse(response GetOrganizationCandidateEvidenceRes, w http.ResponseWriter, span trace.Span) error {
|
||||
switch response := response.(type) {
|
||||
case *OrganizationEvidenceHeaders:
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
// Encoding response headers.
|
||||
{
|
||||
h := uri.NewHeaderEncoder(w.Header())
|
||||
// Encode "Cache-Control" header.
|
||||
{
|
||||
cfg := uri.HeaderParameterEncodingConfig{
|
||||
Name: "Cache-Control",
|
||||
Explode: false,
|
||||
}
|
||||
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
|
||||
return e.EncodeValue(conv.StringToString(string(response.CacheControl)))
|
||||
}); err != nil {
|
||||
return errors.Wrap(err, "encode Cache-Control header")
|
||||
}
|
||||
}
|
||||
}
|
||||
w.WriteHeader(200)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
case *GetOrganizationCandidateEvidenceBadRequest:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.WriteHeader(400)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
case *GetOrganizationCandidateEvidenceUnauthorized:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.WriteHeader(401)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
case *GetOrganizationCandidateEvidenceForbidden:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.WriteHeader(403)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
case *GetOrganizationCandidateEvidenceNotFound:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.WriteHeader(404)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
case *TooManyRequestsHeaders:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.Header().Set("Access-Control-Expose-Headers", "Retry-After")
|
||||
// Encoding response headers.
|
||||
{
|
||||
h := uri.NewHeaderEncoder(w.Header())
|
||||
// Encode "Retry-After" header.
|
||||
{
|
||||
cfg := uri.HeaderParameterEncodingConfig{
|
||||
Name: "Retry-After",
|
||||
Explode: false,
|
||||
}
|
||||
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
|
||||
if val, ok := response.RetryAfter.Get(); ok {
|
||||
return e.EncodeValue(conv.Int32ToString(val))
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return errors.Wrap(err, "encode Retry-After header")
|
||||
}
|
||||
}
|
||||
}
|
||||
w.WriteHeader(429)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
default:
|
||||
return errors.Errorf("unexpected response type: %T", response)
|
||||
}
|
||||
}
|
||||
|
||||
func encodeGetOrganizationInvitationResponse(response GetOrganizationInvitationRes, w http.ResponseWriter, span trace.Span) error {
|
||||
switch response := response.(type) {
|
||||
case *OrganizationInvitationHeaders:
|
||||
@@ -3133,6 +3248,77 @@ func encodeListMyConsentsResponse(response ListMyConsentsRes, w http.ResponseWri
|
||||
}
|
||||
}
|
||||
|
||||
func encodeListMyEvidenceResponse(response ListMyEvidenceRes, w http.ResponseWriter, span trace.Span) error {
|
||||
switch response := response.(type) {
|
||||
case *EvidenceFactListHeaders:
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
// Encoding response headers.
|
||||
{
|
||||
h := uri.NewHeaderEncoder(w.Header())
|
||||
// Encode "Cache-Control" header.
|
||||
{
|
||||
cfg := uri.HeaderParameterEncodingConfig{
|
||||
Name: "Cache-Control",
|
||||
Explode: false,
|
||||
}
|
||||
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
|
||||
return e.EncodeValue(conv.StringToString(string(response.CacheControl)))
|
||||
}); err != nil {
|
||||
return errors.Wrap(err, "encode Cache-Control header")
|
||||
}
|
||||
}
|
||||
}
|
||||
w.WriteHeader(200)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
case *ListMyEvidenceBadRequest:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.WriteHeader(400)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
case *ListMyEvidenceUnauthorized:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.WriteHeader(401)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
case *ListMyEvidenceForbidden:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.WriteHeader(403)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
default:
|
||||
return errors.Errorf("unexpected response type: %T", response)
|
||||
}
|
||||
}
|
||||
|
||||
func encodeListMyHiddenOrganizationsResponse(response ListMyHiddenOrganizationsRes, w http.ResponseWriter, span trace.Span) error {
|
||||
switch response := response.(type) {
|
||||
case *HiddenOrganizationListHeaders:
|
||||
|
||||
@@ -11,46 +11,46 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
rn72AllowedHeaders = map[string]string{
|
||||
rn74AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type",
|
||||
}
|
||||
rn9AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Origin",
|
||||
}
|
||||
rn68AllowedHeaders = map[string]string{
|
||||
rn70AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key",
|
||||
}
|
||||
rn64AllowedHeaders = map[string]string{
|
||||
rn66AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type",
|
||||
}
|
||||
rn27AllowedHeaders = map[string]string{
|
||||
"DELETE": "X-Csrf-Token",
|
||||
}
|
||||
rn70AllowedHeaders = map[string]string{
|
||||
rn72AllowedHeaders = map[string]string{
|
||||
"POST": "X-Csrf-Token",
|
||||
}
|
||||
rn11AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn83AllowedHeaders = map[string]string{
|
||||
rn85AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn22AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn82AllowedHeaders = map[string]string{
|
||||
rn84AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn67AllowedHeaders = map[string]string{
|
||||
rn69AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn5AllowedHeaders = map[string]string{
|
||||
"PUT": "Content-Type,X-Csrf-Token",
|
||||
}
|
||||
rn74AllowedHeaders = map[string]string{
|
||||
rn76AllowedHeaders = map[string]string{
|
||||
"DELETE": "X-Csrf-Token",
|
||||
}
|
||||
rn52AllowedHeaders = map[string]string{
|
||||
rn53AllowedHeaders = map[string]string{
|
||||
"DELETE": "X-Csrf-Token",
|
||||
"PUT": "Content-Type,X-Csrf-Token",
|
||||
}
|
||||
@@ -63,17 +63,17 @@ var (
|
||||
rn19AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn84AllowedHeaders = map[string]string{
|
||||
rn86AllowedHeaders = map[string]string{
|
||||
"POST": "X-Csrf-Token",
|
||||
}
|
||||
rn55AllowedHeaders = map[string]string{
|
||||
rn56AllowedHeaders = map[string]string{
|
||||
"DELETE": "X-Csrf-Token",
|
||||
"PUT": "X-Csrf-Token",
|
||||
}
|
||||
rn79AllowedHeaders = map[string]string{
|
||||
rn81AllowedHeaders = map[string]string{
|
||||
"PUT": "Content-Type,X-Csrf-Token",
|
||||
}
|
||||
rn80AllowedHeaders = map[string]string{
|
||||
rn82AllowedHeaders = map[string]string{
|
||||
"PUT": "Content-Type,X-Csrf-Token",
|
||||
}
|
||||
rn38AllowedHeaders = map[string]string{
|
||||
@@ -94,25 +94,25 @@ var (
|
||||
rn16AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn45AllowedHeaders = map[string]string{
|
||||
rn46AllowedHeaders = map[string]string{
|
||||
"PATCH": "Content-Type,X-Csrf-Token",
|
||||
}
|
||||
rn66AllowedHeaders = map[string]string{
|
||||
rn68AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn79AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn87AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn77AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn85AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn75AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,X-Csrf-Token",
|
||||
}
|
||||
rn18AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn48AllowedHeaders = map[string]string{
|
||||
rn49AllowedHeaders = map[string]string{
|
||||
"PATCH": "Content-Type,X-Csrf-Token",
|
||||
}
|
||||
)
|
||||
@@ -269,7 +269,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn72AllowedHeaders,
|
||||
allowedHeaders: rn74AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -346,7 +346,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn68AllowedHeaders,
|
||||
allowedHeaders: rn70AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -370,7 +370,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn64AllowedHeaders,
|
||||
allowedHeaders: rn66AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -450,7 +450,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn70AllowedHeaders,
|
||||
allowedHeaders: rn72AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -572,7 +572,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn83AllowedHeaders,
|
||||
allowedHeaders: rn85AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -665,7 +665,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn82AllowedHeaders,
|
||||
allowedHeaders: rn84AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -692,7 +692,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn67AllowedHeaders,
|
||||
allowedHeaders: rn69AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -903,7 +903,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "DELETE",
|
||||
allowedHeaders: rn74AllowedHeaders,
|
||||
allowedHeaders: rn76AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -937,7 +937,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "DELETE,PUT",
|
||||
allowedHeaders: rn52AllowedHeaders,
|
||||
allowedHeaders: rn53AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -950,6 +950,31 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
}
|
||||
|
||||
case 'e': // Prefix: "evidence"
|
||||
|
||||
if l := len("evidence"); len(elem) >= l && elem[0:l] == "evidence" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch r.Method {
|
||||
case "GET":
|
||||
s.handleListMyEvidenceRequest([0]string{}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "GET",
|
||||
allowedHeaders: nil,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
case 'i': // Prefix: "invitations"
|
||||
|
||||
if l := len("invitations"); len(elem) >= l && elem[0:l] == "invitations" {
|
||||
@@ -1120,7 +1145,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn84AllowedHeaders,
|
||||
allowedHeaders: rn86AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -1300,7 +1325,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "DELETE,PUT",
|
||||
allowedHeaders: rn55AllowedHeaders,
|
||||
allowedHeaders: rn56AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -1391,7 +1416,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "PUT",
|
||||
allowedHeaders: rn79AllowedHeaders,
|
||||
allowedHeaders: rn81AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -1418,7 +1443,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "PUT",
|
||||
allowedHeaders: rn80AllowedHeaders,
|
||||
allowedHeaders: rn82AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -1637,16 +1662,15 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
// Param: "candidate_handle"
|
||||
// Leaf parameter, slashes are prohibited
|
||||
// Match until "/"
|
||||
idx := strings.IndexByte(elem, '/')
|
||||
if idx >= 0 {
|
||||
break
|
||||
if idx < 0 {
|
||||
idx = len(elem)
|
||||
}
|
||||
args[1] = elem
|
||||
elem = ""
|
||||
args[1] = elem[:idx]
|
||||
elem = elem[idx:]
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch r.Method {
|
||||
case "GET":
|
||||
s.handleGetOrganizationCandidateCardRequest([2]string{
|
||||
@@ -1664,6 +1688,36 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
return
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/evidence"
|
||||
|
||||
if l := len("/evidence"); len(elem) >= l && elem[0:l] == "/evidence" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch r.Method {
|
||||
case "GET":
|
||||
s.handleGetOrganizationCandidateEvidenceRequest([2]string{
|
||||
args[0],
|
||||
args[1],
|
||||
}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "GET",
|
||||
allowedHeaders: nil,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
case 'i': // Prefix: "invitations"
|
||||
|
||||
@@ -1727,7 +1781,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "GET,PATCH",
|
||||
allowedHeaders: rn45AllowedHeaders,
|
||||
allowedHeaders: rn46AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "application/json",
|
||||
})
|
||||
@@ -1807,7 +1861,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn66AllowedHeaders,
|
||||
allowedHeaders: rn68AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -1835,7 +1889,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn77AllowedHeaders,
|
||||
allowedHeaders: rn79AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -1865,7 +1919,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn85AllowedHeaders,
|
||||
allowedHeaders: rn87AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -1898,7 +1952,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn75AllowedHeaders,
|
||||
allowedHeaders: rn77AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -1970,7 +2024,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "GET,PATCH",
|
||||
allowedHeaders: rn48AllowedHeaders,
|
||||
allowedHeaders: rn49AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "application/json",
|
||||
})
|
||||
@@ -2893,6 +2947,31 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) {
|
||||
|
||||
}
|
||||
|
||||
case 'e': // Prefix: "evidence"
|
||||
|
||||
if l := len("evidence"); len(elem) >= l && elem[0:l] == "evidence" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch method {
|
||||
case "GET":
|
||||
r.name = ListMyEvidenceOperation
|
||||
r.summary = "List the skill evidence of the current candidate."
|
||||
r.operationID = "ListMyEvidence"
|
||||
r.operationGroup = ""
|
||||
r.pathPattern = "/api/v1/me/evidence"
|
||||
r.args = args
|
||||
r.count = 0
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
case 'i': // Prefix: "invitations"
|
||||
|
||||
if l := len("invitations"); len(elem) >= l && elem[0:l] == "invitations" {
|
||||
@@ -3595,16 +3674,15 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) {
|
||||
}
|
||||
|
||||
// Param: "candidate_handle"
|
||||
// Leaf parameter, slashes are prohibited
|
||||
// Match until "/"
|
||||
idx := strings.IndexByte(elem, '/')
|
||||
if idx >= 0 {
|
||||
break
|
||||
if idx < 0 {
|
||||
idx = len(elem)
|
||||
}
|
||||
args[1] = elem
|
||||
elem = ""
|
||||
args[1] = elem[:idx]
|
||||
elem = elem[idx:]
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch method {
|
||||
case "GET":
|
||||
r.name = GetOrganizationCandidateCardOperation
|
||||
@@ -3619,6 +3697,33 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) {
|
||||
return
|
||||
}
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/evidence"
|
||||
|
||||
if l := len("/evidence"); len(elem) >= l && elem[0:l] == "/evidence" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch method {
|
||||
case "GET":
|
||||
r.name = GetOrganizationCandidateEvidenceOperation
|
||||
r.summary = "Read the permitted skill evidence of one currently visible candidate card."
|
||||
r.operationID = "GetOrganizationCandidateEvidence"
|
||||
r.operationGroup = ""
|
||||
r.pathPattern = "/api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}/evidence"
|
||||
r.args = args
|
||||
r.count = 2
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
case 'i': // Prefix: "invitations"
|
||||
|
||||
|
||||
@@ -7117,7 +7117,11 @@ func (s *CardCategoryStrength) UnmarshalText(data []byte) error {
|
||||
// leave only through the contact grant of an accepted invitation (C4), and the lowest salary never
|
||||
// leaves.
|
||||
//
|
||||
// - categories: specialization and grade confirmed by an authoritative assessment result.
|
||||
// - categories: specialization and grade confirmed by an authoritative assessment result. With it an
|
||||
// organization receives the confirmed category and, with each category of the card, one supporting
|
||||
// assessment fact: its skill, the passed grade, the trust level, the year of the assessment, and
|
||||
// the basis and calibration that mark a synthetic, uncalibrated demonstration
|
||||
// (`GetOrganizationCandidateEvidence`). The candidate sees the same on `GetMyCardPreview`.
|
||||
// - self_assessment: the candidate's declared specialization and grade, separate from confirmed
|
||||
// categories.
|
||||
// - stack: only recognized technology codes from the server's closed taxonomy.
|
||||
@@ -7231,12 +7235,15 @@ type CardFieldSet []CardField
|
||||
// pseudonym uses a separate preview context and is not an organization's alias. Organization-specific
|
||||
// visibility filters and cohort checks can further generalize or suppress the organization-facing
|
||||
// card. This read creates no view or history record and never reaches an organization. `card` is null
|
||||
// while the profile is closed.
|
||||
// while the profile is closed. `evidence` is what an organization would read in the evidence section
|
||||
// of the card, one supporting assessment fact for each category of the card, and is null exactly when
|
||||
// `card` is null; the organization-facing section can still be generalized or suppressed.
|
||||
// Ref: #/components/schemas/CardPreview
|
||||
type CardPreview struct {
|
||||
State PublicationState `json:"state"`
|
||||
Fields CardFieldSet `json:"fields"`
|
||||
Card NilAnonymousCardContent `json:"card"`
|
||||
Evidence NilOrganizationEvidence `json:"evidence"`
|
||||
GeneratedAt Timestamp `json:"generated_at"`
|
||||
}
|
||||
|
||||
@@ -7255,6 +7262,11 @@ func (s *CardPreview) GetCard() NilAnonymousCardContent {
|
||||
return s.Card
|
||||
}
|
||||
|
||||
// GetEvidence returns the value of Evidence.
|
||||
func (s *CardPreview) GetEvidence() NilOrganizationEvidence {
|
||||
return s.Evidence
|
||||
}
|
||||
|
||||
// GetGeneratedAt returns the value of GeneratedAt.
|
||||
func (s *CardPreview) GetGeneratedAt() Timestamp {
|
||||
return s.GeneratedAt
|
||||
@@ -7275,6 +7287,11 @@ func (s *CardPreview) SetCard(val NilAnonymousCardContent) {
|
||||
s.Card = val
|
||||
}
|
||||
|
||||
// SetEvidence sets the value of Evidence.
|
||||
func (s *CardPreview) SetEvidence(val NilOrganizationEvidence) {
|
||||
s.Evidence = val
|
||||
}
|
||||
|
||||
// SetGeneratedAt sets the value of GeneratedAt.
|
||||
func (s *CardPreview) SetGeneratedAt(val Timestamp) {
|
||||
s.GeneratedAt = val
|
||||
@@ -9672,6 +9689,651 @@ func (EmailVerificationResultEmailVerified) AllValues() []EmailVerificationResul
|
||||
}
|
||||
}
|
||||
|
||||
// Whose contribution the fact is.
|
||||
//
|
||||
// - personal: the candidate's own result. Every assessment fact is personal.
|
||||
// - team_role: a team result with a confirmed role of the candidate.
|
||||
// - team_unattributed: a team result without a confirmed role; it is not a personal skill.
|
||||
//
|
||||
// Only `personal` is produced today.
|
||||
// Ref: #/components/schemas/EvidenceAttribution
|
||||
type EvidenceAttribution string
|
||||
|
||||
const (
|
||||
EvidenceAttributionPersonal EvidenceAttribution = "personal"
|
||||
EvidenceAttributionTeamRole EvidenceAttribution = "team_role"
|
||||
EvidenceAttributionTeamUnattributed EvidenceAttribution = "team_unattributed"
|
||||
)
|
||||
|
||||
// AllValues returns all EvidenceAttribution values.
|
||||
func (EvidenceAttribution) AllValues() []EvidenceAttribution {
|
||||
return []EvidenceAttribution{
|
||||
EvidenceAttributionPersonal,
|
||||
EvidenceAttributionTeamRole,
|
||||
EvidenceAttributionTeamUnattributed,
|
||||
}
|
||||
}
|
||||
|
||||
// MarshalText implements encoding.TextMarshaler.
|
||||
func (s EvidenceAttribution) MarshalText() ([]byte, error) {
|
||||
switch s {
|
||||
case EvidenceAttributionPersonal:
|
||||
return []byte(s), nil
|
||||
case EvidenceAttributionTeamRole:
|
||||
return []byte(s), nil
|
||||
case EvidenceAttributionTeamUnattributed:
|
||||
return []byte(s), nil
|
||||
default:
|
||||
return nil, errors.Errorf("invalid value: %q", s)
|
||||
}
|
||||
}
|
||||
|
||||
// UnmarshalText implements encoding.TextUnmarshaler.
|
||||
func (s *EvidenceAttribution) UnmarshalText(data []byte) error {
|
||||
switch EvidenceAttribution(data) {
|
||||
case EvidenceAttributionPersonal:
|
||||
*s = EvidenceAttributionPersonal
|
||||
return nil
|
||||
case EvidenceAttributionTeamRole:
|
||||
*s = EvidenceAttributionTeamRole
|
||||
return nil
|
||||
case EvidenceAttributionTeamUnattributed:
|
||||
*s = EvidenceAttributionTeamUnattributed
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %q", data)
|
||||
}
|
||||
}
|
||||
|
||||
// What the measurement rests on.
|
||||
//
|
||||
// - synthetic_demo: a demonstration category from a synthetic reviewed bank. It shows the mechanics
|
||||
// and is not a validated measurement.
|
||||
//
|
||||
// Ref: #/components/schemas/EvidenceBasis
|
||||
type EvidenceBasis string
|
||||
|
||||
const (
|
||||
EvidenceBasisSyntheticDemo EvidenceBasis = "synthetic_demo"
|
||||
)
|
||||
|
||||
// AllValues returns all EvidenceBasis values.
|
||||
func (EvidenceBasis) AllValues() []EvidenceBasis {
|
||||
return []EvidenceBasis{
|
||||
EvidenceBasisSyntheticDemo,
|
||||
}
|
||||
}
|
||||
|
||||
// MarshalText implements encoding.TextMarshaler.
|
||||
func (s EvidenceBasis) MarshalText() ([]byte, error) {
|
||||
switch s {
|
||||
case EvidenceBasisSyntheticDemo:
|
||||
return []byte(s), nil
|
||||
default:
|
||||
return nil, errors.Errorf("invalid value: %q", s)
|
||||
}
|
||||
}
|
||||
|
||||
// UnmarshalText implements encoding.TextUnmarshaler.
|
||||
func (s *EvidenceBasis) UnmarshalText(data []byte) error {
|
||||
switch EvidenceBasis(data) {
|
||||
case EvidenceBasisSyntheticDemo:
|
||||
*s = EvidenceBasisSyntheticDemo
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %q", data)
|
||||
}
|
||||
}
|
||||
|
||||
// Calibration of the method behind the result.
|
||||
//
|
||||
// - uncalibrated: the thresholds are initial values that no measurement has validated.
|
||||
//
|
||||
// Ref: #/components/schemas/EvidenceCalibrationStatus
|
||||
type EvidenceCalibrationStatus string
|
||||
|
||||
const (
|
||||
EvidenceCalibrationStatusUncalibrated EvidenceCalibrationStatus = "uncalibrated"
|
||||
)
|
||||
|
||||
// AllValues returns all EvidenceCalibrationStatus values.
|
||||
func (EvidenceCalibrationStatus) AllValues() []EvidenceCalibrationStatus {
|
||||
return []EvidenceCalibrationStatus{
|
||||
EvidenceCalibrationStatusUncalibrated,
|
||||
}
|
||||
}
|
||||
|
||||
// MarshalText implements encoding.TextMarshaler.
|
||||
func (s EvidenceCalibrationStatus) MarshalText() ([]byte, error) {
|
||||
switch s {
|
||||
case EvidenceCalibrationStatusUncalibrated:
|
||||
return []byte(s), nil
|
||||
default:
|
||||
return nil, errors.Errorf("invalid value: %q", s)
|
||||
}
|
||||
}
|
||||
|
||||
// UnmarshalText implements encoding.TextUnmarshaler.
|
||||
func (s *EvidenceCalibrationStatus) UnmarshalText(data []byte) error {
|
||||
switch EvidenceCalibrationStatus(data) {
|
||||
case EvidenceCalibrationStatusUncalibrated:
|
||||
*s = EvidenceCalibrationStatusUncalibrated
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %q", data)
|
||||
}
|
||||
}
|
||||
|
||||
// One independent fact of the current candidate. `occurred_at` is when the source event ended; for an
|
||||
// assessment it is the time of the decision. A fact is one source event; the skills of that event are
|
||||
// tags of the fact, so a second tag never makes a second fact. Hidden facts are listed here with their
|
||||
// visibility, because the candidate owns them.
|
||||
// Ref: #/components/schemas/EvidenceFact
|
||||
type EvidenceFact struct {
|
||||
// Identifier of the fact.
|
||||
ID uuid.UUID `json:"id"`
|
||||
Kind EvidenceKind `json:"kind"`
|
||||
Source EvidenceSource `json:"source"`
|
||||
// Skill tags of the event in ascending order.
|
||||
Skills []EvidenceSkillCode `json:"skills"`
|
||||
Result EvidenceResult `json:"result"`
|
||||
Attribution EvidenceAttribution `json:"attribution"`
|
||||
Trust EvidenceTrustLevel `json:"trust"`
|
||||
OccurredAt Timestamp `json:"occurred_at"`
|
||||
Visibility EvidenceVisibility `json:"visibility"`
|
||||
}
|
||||
|
||||
// GetID returns the value of ID.
|
||||
func (s *EvidenceFact) GetID() uuid.UUID {
|
||||
return s.ID
|
||||
}
|
||||
|
||||
// GetKind returns the value of Kind.
|
||||
func (s *EvidenceFact) GetKind() EvidenceKind {
|
||||
return s.Kind
|
||||
}
|
||||
|
||||
// GetSource returns the value of Source.
|
||||
func (s *EvidenceFact) GetSource() EvidenceSource {
|
||||
return s.Source
|
||||
}
|
||||
|
||||
// GetSkills returns the value of Skills.
|
||||
func (s *EvidenceFact) GetSkills() []EvidenceSkillCode {
|
||||
return s.Skills
|
||||
}
|
||||
|
||||
// GetResult returns the value of Result.
|
||||
func (s *EvidenceFact) GetResult() EvidenceResult {
|
||||
return s.Result
|
||||
}
|
||||
|
||||
// GetAttribution returns the value of Attribution.
|
||||
func (s *EvidenceFact) GetAttribution() EvidenceAttribution {
|
||||
return s.Attribution
|
||||
}
|
||||
|
||||
// GetTrust returns the value of Trust.
|
||||
func (s *EvidenceFact) GetTrust() EvidenceTrustLevel {
|
||||
return s.Trust
|
||||
}
|
||||
|
||||
// GetOccurredAt returns the value of OccurredAt.
|
||||
func (s *EvidenceFact) GetOccurredAt() Timestamp {
|
||||
return s.OccurredAt
|
||||
}
|
||||
|
||||
// GetVisibility returns the value of Visibility.
|
||||
func (s *EvidenceFact) GetVisibility() EvidenceVisibility {
|
||||
return s.Visibility
|
||||
}
|
||||
|
||||
// SetID sets the value of ID.
|
||||
func (s *EvidenceFact) SetID(val uuid.UUID) {
|
||||
s.ID = val
|
||||
}
|
||||
|
||||
// SetKind sets the value of Kind.
|
||||
func (s *EvidenceFact) SetKind(val EvidenceKind) {
|
||||
s.Kind = val
|
||||
}
|
||||
|
||||
// SetSource sets the value of Source.
|
||||
func (s *EvidenceFact) SetSource(val EvidenceSource) {
|
||||
s.Source = val
|
||||
}
|
||||
|
||||
// SetSkills sets the value of Skills.
|
||||
func (s *EvidenceFact) SetSkills(val []EvidenceSkillCode) {
|
||||
s.Skills = val
|
||||
}
|
||||
|
||||
// SetResult sets the value of Result.
|
||||
func (s *EvidenceFact) SetResult(val EvidenceResult) {
|
||||
s.Result = val
|
||||
}
|
||||
|
||||
// SetAttribution sets the value of Attribution.
|
||||
func (s *EvidenceFact) SetAttribution(val EvidenceAttribution) {
|
||||
s.Attribution = val
|
||||
}
|
||||
|
||||
// SetTrust sets the value of Trust.
|
||||
func (s *EvidenceFact) SetTrust(val EvidenceTrustLevel) {
|
||||
s.Trust = val
|
||||
}
|
||||
|
||||
// SetOccurredAt sets the value of OccurredAt.
|
||||
func (s *EvidenceFact) SetOccurredAt(val Timestamp) {
|
||||
s.OccurredAt = val
|
||||
}
|
||||
|
||||
// SetVisibility sets the value of Visibility.
|
||||
func (s *EvidenceFact) SetVisibility(val EvidenceVisibility) {
|
||||
s.Visibility = val
|
||||
}
|
||||
|
||||
// One page of the facts of the current candidate, newest event first.
|
||||
// Ref: #/components/schemas/EvidenceFactList
|
||||
type EvidenceFactList struct {
|
||||
// Facts of the page.
|
||||
Items []EvidenceFact `json:"items"`
|
||||
Page PageInfo `json:"page"`
|
||||
}
|
||||
|
||||
// GetItems returns the value of Items.
|
||||
func (s *EvidenceFactList) GetItems() []EvidenceFact {
|
||||
return s.Items
|
||||
}
|
||||
|
||||
// GetPage returns the value of Page.
|
||||
func (s *EvidenceFactList) GetPage() PageInfo {
|
||||
return s.Page
|
||||
}
|
||||
|
||||
// SetItems sets the value of Items.
|
||||
func (s *EvidenceFactList) SetItems(val []EvidenceFact) {
|
||||
s.Items = val
|
||||
}
|
||||
|
||||
// SetPage sets the value of Page.
|
||||
func (s *EvidenceFactList) SetPage(val PageInfo) {
|
||||
s.Page = val
|
||||
}
|
||||
|
||||
// EvidenceFactListHeaders wraps EvidenceFactList with response headers.
|
||||
type EvidenceFactListHeaders struct {
|
||||
CacheControl CacheControlNoStore
|
||||
Response EvidenceFactList
|
||||
}
|
||||
|
||||
// GetCacheControl returns the value of CacheControl.
|
||||
func (s *EvidenceFactListHeaders) GetCacheControl() CacheControlNoStore {
|
||||
return s.CacheControl
|
||||
}
|
||||
|
||||
// GetResponse returns the value of Response.
|
||||
func (s *EvidenceFactListHeaders) GetResponse() EvidenceFactList {
|
||||
return s.Response
|
||||
}
|
||||
|
||||
// SetCacheControl sets the value of CacheControl.
|
||||
func (s *EvidenceFactListHeaders) SetCacheControl(val CacheControlNoStore) {
|
||||
s.CacheControl = val
|
||||
}
|
||||
|
||||
// SetResponse sets the value of Response.
|
||||
func (s *EvidenceFactListHeaders) SetResponse(val EvidenceFactList) {
|
||||
s.Response = val
|
||||
}
|
||||
|
||||
func (*EvidenceFactListHeaders) listMyEvidenceRes() {}
|
||||
|
||||
// Whether a fact is a statement or an observation.
|
||||
//
|
||||
// - claim: something the candidate stated that nothing confirmed separately. Its trust is 0.
|
||||
// - measurement: a result that a system observed, such as a confirmed assessment. Its trust is 1 to
|
||||
// 3.
|
||||
//
|
||||
// Assessments produce measurements only. A claim never becomes a measurement by repetition, and the
|
||||
// two kinds are stored apart.
|
||||
// Ref: #/components/schemas/EvidenceKind
|
||||
type EvidenceKind string
|
||||
|
||||
const (
|
||||
EvidenceKindClaim EvidenceKind = "claim"
|
||||
EvidenceKindMeasurement EvidenceKind = "measurement"
|
||||
)
|
||||
|
||||
// AllValues returns all EvidenceKind values.
|
||||
func (EvidenceKind) AllValues() []EvidenceKind {
|
||||
return []EvidenceKind{
|
||||
EvidenceKindClaim,
|
||||
EvidenceKindMeasurement,
|
||||
}
|
||||
}
|
||||
|
||||
// MarshalText implements encoding.TextMarshaler.
|
||||
func (s EvidenceKind) MarshalText() ([]byte, error) {
|
||||
switch s {
|
||||
case EvidenceKindClaim:
|
||||
return []byte(s), nil
|
||||
case EvidenceKindMeasurement:
|
||||
return []byte(s), nil
|
||||
default:
|
||||
return nil, errors.Errorf("invalid value: %q", s)
|
||||
}
|
||||
}
|
||||
|
||||
// UnmarshalText implements encoding.TextUnmarshaler.
|
||||
func (s *EvidenceKind) UnmarshalText(data []byte) error {
|
||||
switch EvidenceKind(data) {
|
||||
case EvidenceKindClaim:
|
||||
*s = EvidenceKindClaim
|
||||
return nil
|
||||
case EvidenceKindMeasurement:
|
||||
*s = EvidenceKindMeasurement
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %q", data)
|
||||
}
|
||||
}
|
||||
|
||||
// What the fact says: the grade that was passed and how reliable the method is. It carries no score,
|
||||
// answer, item, failure, or anti-cheat data.
|
||||
// Ref: #/components/schemas/EvidenceResult
|
||||
type EvidenceResult struct {
|
||||
Grade GradeCode `json:"grade"`
|
||||
Basis EvidenceBasis `json:"basis"`
|
||||
CalibrationStatus EvidenceCalibrationStatus `json:"calibration_status"`
|
||||
}
|
||||
|
||||
// GetGrade returns the value of Grade.
|
||||
func (s *EvidenceResult) GetGrade() GradeCode {
|
||||
return s.Grade
|
||||
}
|
||||
|
||||
// GetBasis returns the value of Basis.
|
||||
func (s *EvidenceResult) GetBasis() EvidenceBasis {
|
||||
return s.Basis
|
||||
}
|
||||
|
||||
// GetCalibrationStatus returns the value of CalibrationStatus.
|
||||
func (s *EvidenceResult) GetCalibrationStatus() EvidenceCalibrationStatus {
|
||||
return s.CalibrationStatus
|
||||
}
|
||||
|
||||
// SetGrade sets the value of Grade.
|
||||
func (s *EvidenceResult) SetGrade(val GradeCode) {
|
||||
s.Grade = val
|
||||
}
|
||||
|
||||
// SetBasis sets the value of Basis.
|
||||
func (s *EvidenceResult) SetBasis(val EvidenceBasis) {
|
||||
s.Basis = val
|
||||
}
|
||||
|
||||
// SetCalibrationStatus sets the value of CalibrationStatus.
|
||||
func (s *EvidenceResult) SetCalibrationStatus(val EvidenceCalibrationStatus) {
|
||||
s.CalibrationStatus = val
|
||||
}
|
||||
|
||||
// A skill tag from a closed set - the specialization codes of the catalog and the technology codes of
|
||||
// the anonymous card. An assessment tags its fact with the specialization of the category.
|
||||
// Ref: #/components/schemas/EvidenceSkillCode
|
||||
type EvidenceSkillCode string
|
||||
|
||||
const (
|
||||
EvidenceSkillCodeBackend EvidenceSkillCode = "backend"
|
||||
EvidenceSkillCodeFrontend EvidenceSkillCode = "frontend"
|
||||
EvidenceSkillCodeMobile EvidenceSkillCode = "mobile"
|
||||
EvidenceSkillCodeNetworkEngineer EvidenceSkillCode = "network_engineer"
|
||||
EvidenceSkillCodeDevopsSre EvidenceSkillCode = "devops_sre"
|
||||
EvidenceSkillCodeDataAnalyst EvidenceSkillCode = "data_analyst"
|
||||
EvidenceSkillCodeDsMl EvidenceSkillCode = "ds_ml"
|
||||
EvidenceSkillCodeInformationSecurity EvidenceSkillCode = "information_security"
|
||||
EvidenceSkillCodeQa EvidenceSkillCode = "qa"
|
||||
EvidenceSkillCodeGo EvidenceSkillCode = "go"
|
||||
EvidenceSkillCodePostgresql EvidenceSkillCode = "postgresql"
|
||||
EvidenceSkillCodeKafka EvidenceSkillCode = "kafka"
|
||||
EvidenceSkillCodeDocker EvidenceSkillCode = "docker"
|
||||
)
|
||||
|
||||
// AllValues returns all EvidenceSkillCode values.
|
||||
func (EvidenceSkillCode) AllValues() []EvidenceSkillCode {
|
||||
return []EvidenceSkillCode{
|
||||
EvidenceSkillCodeBackend,
|
||||
EvidenceSkillCodeFrontend,
|
||||
EvidenceSkillCodeMobile,
|
||||
EvidenceSkillCodeNetworkEngineer,
|
||||
EvidenceSkillCodeDevopsSre,
|
||||
EvidenceSkillCodeDataAnalyst,
|
||||
EvidenceSkillCodeDsMl,
|
||||
EvidenceSkillCodeInformationSecurity,
|
||||
EvidenceSkillCodeQa,
|
||||
EvidenceSkillCodeGo,
|
||||
EvidenceSkillCodePostgresql,
|
||||
EvidenceSkillCodeKafka,
|
||||
EvidenceSkillCodeDocker,
|
||||
}
|
||||
}
|
||||
|
||||
// MarshalText implements encoding.TextMarshaler.
|
||||
func (s EvidenceSkillCode) MarshalText() ([]byte, error) {
|
||||
switch s {
|
||||
case EvidenceSkillCodeBackend:
|
||||
return []byte(s), nil
|
||||
case EvidenceSkillCodeFrontend:
|
||||
return []byte(s), nil
|
||||
case EvidenceSkillCodeMobile:
|
||||
return []byte(s), nil
|
||||
case EvidenceSkillCodeNetworkEngineer:
|
||||
return []byte(s), nil
|
||||
case EvidenceSkillCodeDevopsSre:
|
||||
return []byte(s), nil
|
||||
case EvidenceSkillCodeDataAnalyst:
|
||||
return []byte(s), nil
|
||||
case EvidenceSkillCodeDsMl:
|
||||
return []byte(s), nil
|
||||
case EvidenceSkillCodeInformationSecurity:
|
||||
return []byte(s), nil
|
||||
case EvidenceSkillCodeQa:
|
||||
return []byte(s), nil
|
||||
case EvidenceSkillCodeGo:
|
||||
return []byte(s), nil
|
||||
case EvidenceSkillCodePostgresql:
|
||||
return []byte(s), nil
|
||||
case EvidenceSkillCodeKafka:
|
||||
return []byte(s), nil
|
||||
case EvidenceSkillCodeDocker:
|
||||
return []byte(s), nil
|
||||
default:
|
||||
return nil, errors.Errorf("invalid value: %q", s)
|
||||
}
|
||||
}
|
||||
|
||||
// UnmarshalText implements encoding.TextUnmarshaler.
|
||||
func (s *EvidenceSkillCode) UnmarshalText(data []byte) error {
|
||||
switch EvidenceSkillCode(data) {
|
||||
case EvidenceSkillCodeBackend:
|
||||
*s = EvidenceSkillCodeBackend
|
||||
return nil
|
||||
case EvidenceSkillCodeFrontend:
|
||||
*s = EvidenceSkillCodeFrontend
|
||||
return nil
|
||||
case EvidenceSkillCodeMobile:
|
||||
*s = EvidenceSkillCodeMobile
|
||||
return nil
|
||||
case EvidenceSkillCodeNetworkEngineer:
|
||||
*s = EvidenceSkillCodeNetworkEngineer
|
||||
return nil
|
||||
case EvidenceSkillCodeDevopsSre:
|
||||
*s = EvidenceSkillCodeDevopsSre
|
||||
return nil
|
||||
case EvidenceSkillCodeDataAnalyst:
|
||||
*s = EvidenceSkillCodeDataAnalyst
|
||||
return nil
|
||||
case EvidenceSkillCodeDsMl:
|
||||
*s = EvidenceSkillCodeDsMl
|
||||
return nil
|
||||
case EvidenceSkillCodeInformationSecurity:
|
||||
*s = EvidenceSkillCodeInformationSecurity
|
||||
return nil
|
||||
case EvidenceSkillCodeQa:
|
||||
*s = EvidenceSkillCodeQa
|
||||
return nil
|
||||
case EvidenceSkillCodeGo:
|
||||
*s = EvidenceSkillCodeGo
|
||||
return nil
|
||||
case EvidenceSkillCodePostgresql:
|
||||
*s = EvidenceSkillCodePostgresql
|
||||
return nil
|
||||
case EvidenceSkillCodeKafka:
|
||||
*s = EvidenceSkillCodeKafka
|
||||
return nil
|
||||
case EvidenceSkillCodeDocker:
|
||||
*s = EvidenceSkillCodeDocker
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %q", data)
|
||||
}
|
||||
}
|
||||
|
||||
// Where the fact comes from. For an assessment the event is the attempt and the result is the
|
||||
// immutable result of that attempt, which the candidate reads at `GetMyAssessmentResult`; the two
|
||||
// identifiers are equal because a result is keyed by its attempt.
|
||||
// Ref: #/components/schemas/EvidenceSource
|
||||
type EvidenceSource struct {
|
||||
Type EvidenceSourceType `json:"type"`
|
||||
// Identifier of the source event. One event is one fact, however many skills it is tagged with.
|
||||
EventID uuid.UUID `json:"event_id"`
|
||||
// Identifier of the immutable result that produced the fact.
|
||||
ResultID uuid.UUID `json:"result_id"`
|
||||
}
|
||||
|
||||
// GetType returns the value of Type.
|
||||
func (s *EvidenceSource) GetType() EvidenceSourceType {
|
||||
return s.Type
|
||||
}
|
||||
|
||||
// GetEventID returns the value of EventID.
|
||||
func (s *EvidenceSource) GetEventID() uuid.UUID {
|
||||
return s.EventID
|
||||
}
|
||||
|
||||
// GetResultID returns the value of ResultID.
|
||||
func (s *EvidenceSource) GetResultID() uuid.UUID {
|
||||
return s.ResultID
|
||||
}
|
||||
|
||||
// SetType sets the value of Type.
|
||||
func (s *EvidenceSource) SetType(val EvidenceSourceType) {
|
||||
s.Type = val
|
||||
}
|
||||
|
||||
// SetEventID sets the value of EventID.
|
||||
func (s *EvidenceSource) SetEventID(val uuid.UUID) {
|
||||
s.EventID = val
|
||||
}
|
||||
|
||||
// SetResultID sets the value of ResultID.
|
||||
func (s *EvidenceSource) SetResultID(val uuid.UUID) {
|
||||
s.ResultID = val
|
||||
}
|
||||
|
||||
// Where the fact comes from.
|
||||
//
|
||||
// - assessment_result: a real (root or corrective) assessment result of this platform that confirmed
|
||||
// a grade. An express training run (`demo_express`), a failed attempt, and a result without a
|
||||
// reviewed category source are never a source.
|
||||
//
|
||||
// Adding a value is a contract change.
|
||||
// Ref: #/components/schemas/EvidenceSourceType
|
||||
type EvidenceSourceType string
|
||||
|
||||
const (
|
||||
EvidenceSourceTypeAssessmentResult EvidenceSourceType = "assessment_result"
|
||||
)
|
||||
|
||||
// AllValues returns all EvidenceSourceType values.
|
||||
func (EvidenceSourceType) AllValues() []EvidenceSourceType {
|
||||
return []EvidenceSourceType{
|
||||
EvidenceSourceTypeAssessmentResult,
|
||||
}
|
||||
}
|
||||
|
||||
// MarshalText implements encoding.TextMarshaler.
|
||||
func (s EvidenceSourceType) MarshalText() ([]byte, error) {
|
||||
switch s {
|
||||
case EvidenceSourceTypeAssessmentResult:
|
||||
return []byte(s), nil
|
||||
default:
|
||||
return nil, errors.Errorf("invalid value: %q", s)
|
||||
}
|
||||
}
|
||||
|
||||
// UnmarshalText implements encoding.TextUnmarshaler.
|
||||
func (s *EvidenceSourceType) UnmarshalText(data []byte) error {
|
||||
switch EvidenceSourceType(data) {
|
||||
case EvidenceSourceTypeAssessmentResult:
|
||||
*s = EvidenceSourceTypeAssessmentResult
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %q", data)
|
||||
}
|
||||
}
|
||||
|
||||
type EvidenceTrustLevel int32
|
||||
|
||||
// Whether the fact may take part in what an organization reads.
|
||||
//
|
||||
// - visible: the fact is eligible for the organization projection. It does not publish the fact: the
|
||||
// projection also needs the published card with the `categories` field and an active C2.
|
||||
// - hidden: the candidate hid the fact. No organization reads it. Hiding never edits or deletes the
|
||||
// confirmed result.
|
||||
//
|
||||
// Ref: #/components/schemas/EvidenceVisibility
|
||||
type EvidenceVisibility string
|
||||
|
||||
const (
|
||||
EvidenceVisibilityVisible EvidenceVisibility = "visible"
|
||||
EvidenceVisibilityHidden EvidenceVisibility = "hidden"
|
||||
)
|
||||
|
||||
// AllValues returns all EvidenceVisibility values.
|
||||
func (EvidenceVisibility) AllValues() []EvidenceVisibility {
|
||||
return []EvidenceVisibility{
|
||||
EvidenceVisibilityVisible,
|
||||
EvidenceVisibilityHidden,
|
||||
}
|
||||
}
|
||||
|
||||
// MarshalText implements encoding.TextMarshaler.
|
||||
func (s EvidenceVisibility) MarshalText() ([]byte, error) {
|
||||
switch s {
|
||||
case EvidenceVisibilityVisible:
|
||||
return []byte(s), nil
|
||||
case EvidenceVisibilityHidden:
|
||||
return []byte(s), nil
|
||||
default:
|
||||
return nil, errors.Errorf("invalid value: %q", s)
|
||||
}
|
||||
}
|
||||
|
||||
// UnmarshalText implements encoding.TextUnmarshaler.
|
||||
func (s *EvidenceVisibility) UnmarshalText(data []byte) error {
|
||||
switch EvidenceVisibility(data) {
|
||||
case EvidenceVisibilityVisible:
|
||||
*s = EvidenceVisibilityVisible
|
||||
return nil
|
||||
case EvidenceVisibilityHidden:
|
||||
*s = EvidenceVisibilityHidden
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %q", data)
|
||||
}
|
||||
}
|
||||
|
||||
type FinalizeMyAssessmentAttemptBadRequest Problem
|
||||
|
||||
func (*FinalizeMyAssessmentAttemptBadRequest) finalizeMyAssessmentAttemptRes() {}
|
||||
@@ -10006,6 +10668,22 @@ type GetOrganizationCandidateCardUnauthorized Problem
|
||||
|
||||
func (*GetOrganizationCandidateCardUnauthorized) getOrganizationCandidateCardRes() {}
|
||||
|
||||
type GetOrganizationCandidateEvidenceBadRequest Problem
|
||||
|
||||
func (*GetOrganizationCandidateEvidenceBadRequest) getOrganizationCandidateEvidenceRes() {}
|
||||
|
||||
type GetOrganizationCandidateEvidenceForbidden Problem
|
||||
|
||||
func (*GetOrganizationCandidateEvidenceForbidden) getOrganizationCandidateEvidenceRes() {}
|
||||
|
||||
type GetOrganizationCandidateEvidenceNotFound Problem
|
||||
|
||||
func (*GetOrganizationCandidateEvidenceNotFound) getOrganizationCandidateEvidenceRes() {}
|
||||
|
||||
type GetOrganizationCandidateEvidenceUnauthorized Problem
|
||||
|
||||
func (*GetOrganizationCandidateEvidenceUnauthorized) getOrganizationCandidateEvidenceRes() {}
|
||||
|
||||
type GetOrganizationForbidden Problem
|
||||
|
||||
func (*GetOrganizationForbidden) getOrganizationRes() {}
|
||||
@@ -11911,6 +12589,18 @@ type ListMyConsentsUnauthorized Problem
|
||||
|
||||
func (*ListMyConsentsUnauthorized) listMyConsentsRes() {}
|
||||
|
||||
type ListMyEvidenceBadRequest Problem
|
||||
|
||||
func (*ListMyEvidenceBadRequest) listMyEvidenceRes() {}
|
||||
|
||||
type ListMyEvidenceForbidden Problem
|
||||
|
||||
func (*ListMyEvidenceForbidden) listMyEvidenceRes() {}
|
||||
|
||||
type ListMyEvidenceUnauthorized Problem
|
||||
|
||||
func (*ListMyEvidenceUnauthorized) listMyEvidenceRes() {}
|
||||
|
||||
type ListMyHiddenOrganizationsBadRequest Problem
|
||||
|
||||
func (*ListMyHiddenOrganizationsBadRequest) listMyHiddenOrganizationsRes() {}
|
||||
@@ -18185,6 +18875,51 @@ func (o NilOrganizationDescription) Or(d OrganizationDescription) OrganizationDe
|
||||
return d
|
||||
}
|
||||
|
||||
// NewNilOrganizationEvidence returns new NilOrganizationEvidence with value set to v.
|
||||
func NewNilOrganizationEvidence(v OrganizationEvidence) NilOrganizationEvidence {
|
||||
return NilOrganizationEvidence{
|
||||
Value: v,
|
||||
}
|
||||
}
|
||||
|
||||
// NilOrganizationEvidence is nullable OrganizationEvidence.
|
||||
type NilOrganizationEvidence struct {
|
||||
Value OrganizationEvidence
|
||||
Null bool
|
||||
}
|
||||
|
||||
// SetTo sets value to v.
|
||||
func (o *NilOrganizationEvidence) SetTo(v OrganizationEvidence) {
|
||||
o.Null = false
|
||||
o.Value = v
|
||||
}
|
||||
|
||||
// IsNull returns true if value is Null.
|
||||
func (o NilOrganizationEvidence) IsNull() bool { return o.Null }
|
||||
|
||||
// SetToNull sets value to null.
|
||||
func (o *NilOrganizationEvidence) SetToNull() {
|
||||
o.Null = true
|
||||
var v OrganizationEvidence
|
||||
o.Value = v
|
||||
}
|
||||
|
||||
// Get returns value and boolean that denotes whether value was set.
|
||||
func (o NilOrganizationEvidence) Get() (v OrganizationEvidence, ok bool) {
|
||||
if o.Null {
|
||||
return v, false
|
||||
}
|
||||
return o.Value, true
|
||||
}
|
||||
|
||||
// Or returns value if set, or given parameter if does not.
|
||||
func (o NilOrganizationEvidence) Or(d OrganizationEvidence) OrganizationEvidence {
|
||||
if v, ok := o.Get(); ok {
|
||||
return v
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
// NewNilOrganizationSphere returns new NilOrganizationSphere with value set to v.
|
||||
func NewNilOrganizationSphere(v OrganizationSphere) NilOrganizationSphere {
|
||||
return NilOrganizationSphere{
|
||||
@@ -22180,6 +22915,133 @@ func (s *OrganizationCreate) SetRepresentatives(val []OrganizationRepresentative
|
||||
|
||||
type OrganizationDescription string
|
||||
|
||||
// The permitted evidence of one candidate card, ordered by skill: at most one fact for each category
|
||||
// of the card (at most nine). The list is empty when no visible fact supports a category of the card.
|
||||
// Ref: #/components/schemas/OrganizationEvidence
|
||||
type OrganizationEvidence struct {
|
||||
// Permitted facts, one for each supported category.
|
||||
Items []OrganizationEvidenceFact `json:"items"`
|
||||
}
|
||||
|
||||
// GetItems returns the value of Items.
|
||||
func (s *OrganizationEvidence) GetItems() []OrganizationEvidenceFact {
|
||||
return s.Items
|
||||
}
|
||||
|
||||
// SetItems sets the value of Items.
|
||||
func (s *OrganizationEvidence) SetItems(val []OrganizationEvidenceFact) {
|
||||
s.Items = val
|
||||
}
|
||||
|
||||
// The one assessment fact that supports a category of the card as an organization reads it: the
|
||||
// earliest visible measurement that passed exactly the confirmed grade of that category. A lower
|
||||
// grade, a retake, the other tags of the event, the source, the basis, the exact time, and every
|
||||
// identifier stay with the candidate. The fact carries no identifier of the fact, the event, the
|
||||
// result, or the candidate, so it cannot be joined to a person by a key. It is not unlinkable: the
|
||||
// skill, the grade, the trust level, and the year, together with the other values of the card, can
|
||||
// narrow a small pool of candidates, and the minimum cohort of the card does not cover the year.
|
||||
// `basis` and `calibration_status` are the same for every candidate: they say that the fact comes from
|
||||
// a synthetic demonstration and is not calibrated, so a demonstration is never read as a validated
|
||||
// measurement. The fact never carries an answer, score, item, failure, signal, or review band.
|
||||
// Ref: #/components/schemas/OrganizationEvidenceFact
|
||||
type OrganizationEvidenceFact struct {
|
||||
Skill EvidenceSkillCode `json:"skill"`
|
||||
Grade GradeCode `json:"grade"`
|
||||
Trust EvidenceTrustLevel `json:"trust"`
|
||||
Basis EvidenceBasis `json:"basis"`
|
||||
CalibrationStatus EvidenceCalibrationStatus `json:"calibration_status"`
|
||||
// Year (UTC) when the assessment ended. The month, day, and time stay with the candidate.
|
||||
ObservedYear int32 `json:"observed_year"`
|
||||
}
|
||||
|
||||
// GetSkill returns the value of Skill.
|
||||
func (s *OrganizationEvidenceFact) GetSkill() EvidenceSkillCode {
|
||||
return s.Skill
|
||||
}
|
||||
|
||||
// GetGrade returns the value of Grade.
|
||||
func (s *OrganizationEvidenceFact) GetGrade() GradeCode {
|
||||
return s.Grade
|
||||
}
|
||||
|
||||
// GetTrust returns the value of Trust.
|
||||
func (s *OrganizationEvidenceFact) GetTrust() EvidenceTrustLevel {
|
||||
return s.Trust
|
||||
}
|
||||
|
||||
// GetBasis returns the value of Basis.
|
||||
func (s *OrganizationEvidenceFact) GetBasis() EvidenceBasis {
|
||||
return s.Basis
|
||||
}
|
||||
|
||||
// GetCalibrationStatus returns the value of CalibrationStatus.
|
||||
func (s *OrganizationEvidenceFact) GetCalibrationStatus() EvidenceCalibrationStatus {
|
||||
return s.CalibrationStatus
|
||||
}
|
||||
|
||||
// GetObservedYear returns the value of ObservedYear.
|
||||
func (s *OrganizationEvidenceFact) GetObservedYear() int32 {
|
||||
return s.ObservedYear
|
||||
}
|
||||
|
||||
// SetSkill sets the value of Skill.
|
||||
func (s *OrganizationEvidenceFact) SetSkill(val EvidenceSkillCode) {
|
||||
s.Skill = val
|
||||
}
|
||||
|
||||
// SetGrade sets the value of Grade.
|
||||
func (s *OrganizationEvidenceFact) SetGrade(val GradeCode) {
|
||||
s.Grade = val
|
||||
}
|
||||
|
||||
// SetTrust sets the value of Trust.
|
||||
func (s *OrganizationEvidenceFact) SetTrust(val EvidenceTrustLevel) {
|
||||
s.Trust = val
|
||||
}
|
||||
|
||||
// SetBasis sets the value of Basis.
|
||||
func (s *OrganizationEvidenceFact) SetBasis(val EvidenceBasis) {
|
||||
s.Basis = val
|
||||
}
|
||||
|
||||
// SetCalibrationStatus sets the value of CalibrationStatus.
|
||||
func (s *OrganizationEvidenceFact) SetCalibrationStatus(val EvidenceCalibrationStatus) {
|
||||
s.CalibrationStatus = val
|
||||
}
|
||||
|
||||
// SetObservedYear sets the value of ObservedYear.
|
||||
func (s *OrganizationEvidenceFact) SetObservedYear(val int32) {
|
||||
s.ObservedYear = val
|
||||
}
|
||||
|
||||
// OrganizationEvidenceHeaders wraps OrganizationEvidence with response headers.
|
||||
type OrganizationEvidenceHeaders struct {
|
||||
CacheControl CacheControlNoStore
|
||||
Response OrganizationEvidence
|
||||
}
|
||||
|
||||
// GetCacheControl returns the value of CacheControl.
|
||||
func (s *OrganizationEvidenceHeaders) GetCacheControl() CacheControlNoStore {
|
||||
return s.CacheControl
|
||||
}
|
||||
|
||||
// GetResponse returns the value of Response.
|
||||
func (s *OrganizationEvidenceHeaders) GetResponse() OrganizationEvidence {
|
||||
return s.Response
|
||||
}
|
||||
|
||||
// SetCacheControl sets the value of CacheControl.
|
||||
func (s *OrganizationEvidenceHeaders) SetCacheControl(val CacheControlNoStore) {
|
||||
s.CacheControl = val
|
||||
}
|
||||
|
||||
// SetResponse sets the value of Response.
|
||||
func (s *OrganizationEvidenceHeaders) SetResponse(val OrganizationEvidence) {
|
||||
s.Response = val
|
||||
}
|
||||
|
||||
func (*OrganizationEvidenceHeaders) getOrganizationCandidateEvidenceRes() {}
|
||||
|
||||
// OrganizationHeaders wraps Organization with response headers.
|
||||
type OrganizationHeaders struct {
|
||||
CacheControl CacheControlNoStore
|
||||
@@ -29642,6 +30504,7 @@ func (*TooManyRequestsHeaders) createOrganizationNeedRes() {}
|
||||
func (*TooManyRequestsHeaders) createOrganizationRes() {}
|
||||
func (*TooManyRequestsHeaders) declineMyInvitationRes() {}
|
||||
func (*TooManyRequestsHeaders) getOrganizationCandidateCardRes() {}
|
||||
func (*TooManyRequestsHeaders) getOrganizationCandidateEvidenceRes() {}
|
||||
func (*TooManyRequestsHeaders) hideOrganizationRes() {}
|
||||
func (*TooManyRequestsHeaders) loginRes() {}
|
||||
func (*TooManyRequestsHeaders) raiseOrganizationInvitationSalaryRes() {}
|
||||
|
||||
@@ -81,6 +81,7 @@ var operationRolesSessionCookie = map[string][]string{
|
||||
GetMySupportCaseOperation: []string{},
|
||||
GetOrganizationOperation: []string{},
|
||||
GetOrganizationCandidateCardOperation: []string{},
|
||||
GetOrganizationCandidateEvidenceOperation: []string{},
|
||||
GetOrganizationInvitationOperation: []string{},
|
||||
GetOrganizationInvitationContactsOperation: []string{},
|
||||
GetOrganizationNeedOperation: []string{},
|
||||
@@ -89,6 +90,7 @@ var operationRolesSessionCookie = map[string][]string{
|
||||
ListMyAssessmentResultsOperation: []string{},
|
||||
ListMyCardAccessHistoryOperation: []string{},
|
||||
ListMyConsentsOperation: []string{},
|
||||
ListMyEvidenceOperation: []string{},
|
||||
ListMyHiddenOrganizationsOperation: []string{},
|
||||
ListMyInvitationsOperation: []string{},
|
||||
ListMyOrganizationsOperation: []string{},
|
||||
|
||||
@@ -663,6 +663,13 @@ type Handler interface {
|
||||
// formats appear only through their separate explicit publication choices, and self-assessment never
|
||||
// becomes a confirmed category. Salary compatibility is nullable and contains no salary amount.
|
||||
//
|
||||
// `evidence` shows what an organization would read in the evidence section of the card
|
||||
// (`GetOrganizationCandidateEvidence`): for each category of the card, the one assessment fact that
|
||||
// supports its confirmed grade, with its skill, the passed grade, the trust level, the year, and the
|
||||
// basis and calibration (`synthetic_demo`, `uncalibrated`). It is null while `card` is null, and an
|
||||
// empty list when the card shows no category or no visible fact supports one. The preview applies no
|
||||
// organization or cohort, so an organization can still receive less.
|
||||
//
|
||||
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account
|
||||
// answers 403 forbidden.
|
||||
//
|
||||
@@ -841,6 +848,45 @@ type Handler interface {
|
||||
//
|
||||
// GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}
|
||||
GetOrganizationCandidateCard(ctx context.Context, params GetOrganizationCandidateCardParams) (GetOrganizationCandidateCardRes, error)
|
||||
// GetOrganizationCandidateEvidence implements GetOrganizationCandidateEvidence operation.
|
||||
//
|
||||
// Requires the session cookie of an employer account with an active membership in `org_id`. The
|
||||
// organization and membership come from the current server-side session and path, never from cached
|
||||
// search data.
|
||||
//
|
||||
// `candidate_handle` is the organization-scoped opaque alias issued by the current anonymous-card
|
||||
// projection. The server runs the same checks as the card read on every request: active membership,
|
||||
// effective C2 publication, the candidate's hiding of this organization, and the minimum cohort. In
|
||||
// addition the card must publish the `categories` field and show at least one category after the
|
||||
// cohort rules, because the evidence explains those categories and discloses nothing beyond them. An
|
||||
// unknown handle, a handle of another organization, a closed or revoked publication, a profile hidden
|
||||
// from this organization, a profile suppressed by the minimum cohort, and a card without categories
|
||||
// all answer the same 404 not_found. Closing C2 or hiding the organization blocks this read
|
||||
// immediately, and a cached response proves nothing.
|
||||
//
|
||||
// The response lists, for each category of the card, the one visible fact that supports its confirmed
|
||||
// grade: the earliest assessment that passed exactly that grade, so a lower grade or a retake adds
|
||||
// nothing. A fact the candidate hid is absent. Each fact carries only the skill, the passed grade, the
|
||||
// trust level, the year of the assessment, and the basis and calibration of the method
|
||||
// (`synthetic_demo`, `uncalibrated`), which are the same for every candidate and say that the fact is
|
||||
// a demonstration, not a validated measurement. It carries no identifier of the fact, event, result,
|
||||
// or candidate, no month or exact time, and never an answer, item, score, failed attempt, review band,
|
||||
// or anti-cheat signal. An express training run and a failed attempt create no fact. The answer has no
|
||||
// key that joins it to a person, but it is not unlinkable: with the other values of the card it can
|
||||
// narrow a small pool of candidates.
|
||||
//
|
||||
// Reading the evidence is a view of the candidate card: it consumes the organization's current
|
||||
// card-view quota with the same distinct-card rule and is recorded in the access history with the
|
||||
// `categories` field. When the quota is exhausted the operation answers 429 with Retry-After. The
|
||||
// response is `Cache-Control: no-store`.
|
||||
//
|
||||
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account
|
||||
// answers 403 forbidden; an unknown organization or account without an active membership answers 404
|
||||
// not_found. An `org_id` that is not a UUID or a malformed candidate handle answers 400
|
||||
// validation_failed.
|
||||
//
|
||||
// GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}/evidence
|
||||
GetOrganizationCandidateEvidence(ctx context.Context, params GetOrganizationCandidateEvidenceParams) (GetOrganizationCandidateEvidenceRes, error)
|
||||
// GetOrganizationInvitation implements GetOrganizationInvitation operation.
|
||||
//
|
||||
// Requires the session cookie of an employer account with an active membership in `org_id`. The
|
||||
@@ -1069,6 +1115,30 @@ type Handler interface {
|
||||
//
|
||||
// GET /api/v1/me/consents
|
||||
ListMyConsents(ctx context.Context, params ListMyConsentsParams) (ListMyConsentsRes, error)
|
||||
// ListMyEvidence implements ListMyEvidence operation.
|
||||
//
|
||||
// Requires the session cookie of a candidate account. The candidate comes from the session, so the
|
||||
// response holds only the caller's own facts. Returns a page, newest event first with the fact
|
||||
// identifier as the tie-breaker, with cursor pagination. The response is `Cache-Control: no-store`.
|
||||
//
|
||||
// A fact is derived from the immutable result of a confirmed real assessment (root or corrective), in
|
||||
// the same transaction that stores the result. Each fact names its source (the event and the result,
|
||||
// which the candidate can open at `GetMyAssessmentResult`), the skills of the event, the grade that
|
||||
// was passed with its basis and calibration, the attribution, the date, the visibility, and the trust
|
||||
// level. An online assessment without a reliable confirmation of the identity has trust 1. One source
|
||||
// event is one fact: its skills are tags of that fact, so several tags never make several facts.
|
||||
//
|
||||
// The list never carries raw answers, items, scores, failed attempts, or anti-cheat data. A failed
|
||||
// attempt, a result without a reviewed category source, and an express training run (`demo_express`)
|
||||
// create no fact, so reading the list before and after an express run shows no new fact. The list
|
||||
// includes facts the candidate hid, with `visibility` `hidden`.
|
||||
//
|
||||
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account, or
|
||||
// a candidate with an unverified email, answers 403 forbidden. A malformed `limit` or `cursor`, or a
|
||||
// cursor of another candidate, answers 400 validation_failed.
|
||||
//
|
||||
// GET /api/v1/me/evidence
|
||||
ListMyEvidence(ctx context.Context, params ListMyEvidenceParams) (ListMyEvidenceRes, error)
|
||||
// ListMyHiddenOrganizations implements ListMyHiddenOrganizations operation.
|
||||
//
|
||||
// Requires the session cookie of a candidate account. The candidate comes from the session, so the
|
||||
|
||||
@@ -725,6 +725,13 @@ func (UnimplementedHandler) GetMyAssessmentSignalNotice(ctx context.Context) (r
|
||||
// formats appear only through their separate explicit publication choices, and self-assessment never
|
||||
// becomes a confirmed category. Salary compatibility is nullable and contains no salary amount.
|
||||
//
|
||||
// `evidence` shows what an organization would read in the evidence section of the card
|
||||
// (`GetOrganizationCandidateEvidence`): for each category of the card, the one assessment fact that
|
||||
// supports its confirmed grade, with its skill, the passed grade, the trust level, the year, and the
|
||||
// basis and calibration (`synthetic_demo`, `uncalibrated`). It is null while `card` is null, and an
|
||||
// empty list when the card shows no category or no visible fact supports one. The preview applies no
|
||||
// organization or cohort, so an organization can still receive less.
|
||||
//
|
||||
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account
|
||||
// answers 403 forbidden.
|
||||
//
|
||||
@@ -930,6 +937,48 @@ func (UnimplementedHandler) GetOrganizationCandidateCard(ctx context.Context, pa
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// GetOrganizationCandidateEvidence implements GetOrganizationCandidateEvidence operation.
|
||||
//
|
||||
// Requires the session cookie of an employer account with an active membership in `org_id`. The
|
||||
// organization and membership come from the current server-side session and path, never from cached
|
||||
// search data.
|
||||
//
|
||||
// `candidate_handle` is the organization-scoped opaque alias issued by the current anonymous-card
|
||||
// projection. The server runs the same checks as the card read on every request: active membership,
|
||||
// effective C2 publication, the candidate's hiding of this organization, and the minimum cohort. In
|
||||
// addition the card must publish the `categories` field and show at least one category after the
|
||||
// cohort rules, because the evidence explains those categories and discloses nothing beyond them. An
|
||||
// unknown handle, a handle of another organization, a closed or revoked publication, a profile hidden
|
||||
// from this organization, a profile suppressed by the minimum cohort, and a card without categories
|
||||
// all answer the same 404 not_found. Closing C2 or hiding the organization blocks this read
|
||||
// immediately, and a cached response proves nothing.
|
||||
//
|
||||
// The response lists, for each category of the card, the one visible fact that supports its confirmed
|
||||
// grade: the earliest assessment that passed exactly that grade, so a lower grade or a retake adds
|
||||
// nothing. A fact the candidate hid is absent. Each fact carries only the skill, the passed grade, the
|
||||
// trust level, the year of the assessment, and the basis and calibration of the method
|
||||
// (`synthetic_demo`, `uncalibrated`), which are the same for every candidate and say that the fact is
|
||||
// a demonstration, not a validated measurement. It carries no identifier of the fact, event, result,
|
||||
// or candidate, no month or exact time, and never an answer, item, score, failed attempt, review band,
|
||||
// or anti-cheat signal. An express training run and a failed attempt create no fact. The answer has no
|
||||
// key that joins it to a person, but it is not unlinkable: with the other values of the card it can
|
||||
// narrow a small pool of candidates.
|
||||
//
|
||||
// Reading the evidence is a view of the candidate card: it consumes the organization's current
|
||||
// card-view quota with the same distinct-card rule and is recorded in the access history with the
|
||||
// `categories` field. When the quota is exhausted the operation answers 429 with Retry-After. The
|
||||
// response is `Cache-Control: no-store`.
|
||||
//
|
||||
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account
|
||||
// answers 403 forbidden; an unknown organization or account without an active membership answers 404
|
||||
// not_found. An `org_id` that is not a UUID or a malformed candidate handle answers 400
|
||||
// validation_failed.
|
||||
//
|
||||
// GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}/evidence
|
||||
func (UnimplementedHandler) GetOrganizationCandidateEvidence(ctx context.Context, params GetOrganizationCandidateEvidenceParams) (r GetOrganizationCandidateEvidenceRes, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// GetOrganizationInvitation implements GetOrganizationInvitation operation.
|
||||
//
|
||||
// Requires the session cookie of an employer account with an active membership in `org_id`. The
|
||||
@@ -1185,6 +1234,33 @@ func (UnimplementedHandler) ListMyConsents(ctx context.Context, params ListMyCon
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// ListMyEvidence implements ListMyEvidence operation.
|
||||
//
|
||||
// Requires the session cookie of a candidate account. The candidate comes from the session, so the
|
||||
// response holds only the caller's own facts. Returns a page, newest event first with the fact
|
||||
// identifier as the tie-breaker, with cursor pagination. The response is `Cache-Control: no-store`.
|
||||
//
|
||||
// A fact is derived from the immutable result of a confirmed real assessment (root or corrective), in
|
||||
// the same transaction that stores the result. Each fact names its source (the event and the result,
|
||||
// which the candidate can open at `GetMyAssessmentResult`), the skills of the event, the grade that
|
||||
// was passed with its basis and calibration, the attribution, the date, the visibility, and the trust
|
||||
// level. An online assessment without a reliable confirmation of the identity has trust 1. One source
|
||||
// event is one fact: its skills are tags of that fact, so several tags never make several facts.
|
||||
//
|
||||
// The list never carries raw answers, items, scores, failed attempts, or anti-cheat data. A failed
|
||||
// attempt, a result without a reviewed category source, and an express training run (`demo_express`)
|
||||
// create no fact, so reading the list before and after an express run shows no new fact. The list
|
||||
// includes facts the candidate hid, with `visibility` `hidden`.
|
||||
//
|
||||
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account, or
|
||||
// a candidate with an unverified email, answers 403 forbidden. A malformed `limit` or `cursor`, or a
|
||||
// cursor of another candidate, answers 400 validation_failed.
|
||||
//
|
||||
// GET /api/v1/me/evidence
|
||||
func (UnimplementedHandler) ListMyEvidence(ctx context.Context, params ListMyEvidenceParams) (r ListMyEvidenceRes, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// ListMyHiddenOrganizations implements ListMyHiddenOrganizations operation.
|
||||
//
|
||||
// Requires the session cookie of a candidate account. The candidate comes from the session, so the
|
||||
|
||||
@@ -6512,6 +6512,24 @@ func (s *CardPreview) Validate() error {
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if value, ok := s.Evidence.Get(); ok {
|
||||
if err := func() error {
|
||||
if err := value.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "evidence",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
@@ -8833,6 +8851,397 @@ func (s EmailVerificationResultEmailVerified) Validate() error {
|
||||
}
|
||||
}
|
||||
|
||||
func (s EvidenceAttribution) Validate() error {
|
||||
switch s {
|
||||
case "personal":
|
||||
return nil
|
||||
case "team_role":
|
||||
return nil
|
||||
case "team_unattributed":
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %v", s)
|
||||
}
|
||||
}
|
||||
|
||||
func (s EvidenceBasis) Validate() error {
|
||||
switch s {
|
||||
case "synthetic_demo":
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %v", s)
|
||||
}
|
||||
}
|
||||
|
||||
func (s EvidenceCalibrationStatus) Validate() error {
|
||||
switch s {
|
||||
case "uncalibrated":
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %v", s)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *EvidenceFact) Validate() error {
|
||||
if s == nil {
|
||||
return validate.ErrNilPointer
|
||||
}
|
||||
|
||||
var failures []validate.FieldError
|
||||
if err := func() error {
|
||||
if err := s.Kind.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "kind",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := s.Source.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "source",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if s.Skills == nil {
|
||||
return errors.New("nil is invalid value")
|
||||
}
|
||||
if err := (validate.Array{
|
||||
MinLength: 1,
|
||||
MinLengthSet: true,
|
||||
MaxLength: 13,
|
||||
MaxLengthSet: true,
|
||||
}).ValidateLength(len(s.Skills)); err != nil {
|
||||
return errors.Wrap(err, "array")
|
||||
}
|
||||
if err := validate.UniqueItems(s.Skills); err != nil {
|
||||
return errors.Wrap(err, "array")
|
||||
}
|
||||
var failures []validate.FieldError
|
||||
for i, elem := range s.Skills {
|
||||
if err := func() error {
|
||||
if err := elem.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: fmt.Sprintf("[%d]", i),
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "skills",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := s.Result.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "result",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := s.Attribution.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "attribution",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := s.Trust.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "trust",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := s.Visibility.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "visibility",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *EvidenceFactList) Validate() error {
|
||||
if s == nil {
|
||||
return validate.ErrNilPointer
|
||||
}
|
||||
|
||||
var failures []validate.FieldError
|
||||
if err := func() error {
|
||||
if s.Items == nil {
|
||||
return errors.New("nil is invalid value")
|
||||
}
|
||||
if err := (validate.Array{
|
||||
MinLength: 0,
|
||||
MinLengthSet: false,
|
||||
MaxLength: 100,
|
||||
MaxLengthSet: true,
|
||||
}).ValidateLength(len(s.Items)); err != nil {
|
||||
return errors.Wrap(err, "array")
|
||||
}
|
||||
var failures []validate.FieldError
|
||||
for i, elem := range s.Items {
|
||||
if err := func() error {
|
||||
if err := elem.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: fmt.Sprintf("[%d]", i),
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "items",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := s.Page.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "page",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *EvidenceFactListHeaders) Validate() error {
|
||||
if s == nil {
|
||||
return validate.ErrNilPointer
|
||||
}
|
||||
|
||||
var failures []validate.FieldError
|
||||
if err := func() error {
|
||||
if err := s.CacheControl.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "CacheControl",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := s.Response.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "Response",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s EvidenceKind) Validate() error {
|
||||
switch s {
|
||||
case "claim":
|
||||
return nil
|
||||
case "measurement":
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %v", s)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *EvidenceResult) Validate() error {
|
||||
if s == nil {
|
||||
return validate.ErrNilPointer
|
||||
}
|
||||
|
||||
var failures []validate.FieldError
|
||||
if err := func() error {
|
||||
if err := s.Grade.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "grade",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := s.Basis.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "basis",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := s.CalibrationStatus.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "calibration_status",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s EvidenceSkillCode) Validate() error {
|
||||
switch s {
|
||||
case "backend":
|
||||
return nil
|
||||
case "frontend":
|
||||
return nil
|
||||
case "mobile":
|
||||
return nil
|
||||
case "network_engineer":
|
||||
return nil
|
||||
case "devops_sre":
|
||||
return nil
|
||||
case "data_analyst":
|
||||
return nil
|
||||
case "ds_ml":
|
||||
return nil
|
||||
case "information_security":
|
||||
return nil
|
||||
case "qa":
|
||||
return nil
|
||||
case "go":
|
||||
return nil
|
||||
case "postgresql":
|
||||
return nil
|
||||
case "kafka":
|
||||
return nil
|
||||
case "docker":
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %v", s)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *EvidenceSource) Validate() error {
|
||||
if s == nil {
|
||||
return validate.ErrNilPointer
|
||||
}
|
||||
|
||||
var failures []validate.FieldError
|
||||
if err := func() error {
|
||||
if err := s.Type.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "type",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s EvidenceSourceType) Validate() error {
|
||||
switch s {
|
||||
case "assessment_result":
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %v", s)
|
||||
}
|
||||
}
|
||||
|
||||
func (s EvidenceTrustLevel) Validate() error {
|
||||
alias := (int32)(s)
|
||||
if err := (validate.Int{
|
||||
MinSet: true,
|
||||
Min: 0,
|
||||
MaxSet: true,
|
||||
Max: 3,
|
||||
MinExclusive: false,
|
||||
MaxExclusive: false,
|
||||
MultipleOfSet: false,
|
||||
MultipleOf: 0,
|
||||
Pattern: nil,
|
||||
}).Validate(int64(alias)); err != nil {
|
||||
return errors.Wrap(err, "int")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s EvidenceVisibility) Validate() error {
|
||||
switch s {
|
||||
case "visible":
|
||||
return nil
|
||||
case "hidden":
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %v", s)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *FinalizeMyAssessmentAttemptBadRequest) Validate() error {
|
||||
alias := (*Problem)(s)
|
||||
if err := alias.Validate(); err != nil {
|
||||
@@ -9379,6 +9788,38 @@ func (s *GetOrganizationCandidateCardUnauthorized) Validate() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *GetOrganizationCandidateEvidenceBadRequest) Validate() error {
|
||||
alias := (*Problem)(s)
|
||||
if err := alias.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *GetOrganizationCandidateEvidenceForbidden) Validate() error {
|
||||
alias := (*Problem)(s)
|
||||
if err := alias.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *GetOrganizationCandidateEvidenceNotFound) Validate() error {
|
||||
alias := (*Problem)(s)
|
||||
if err := alias.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *GetOrganizationCandidateEvidenceUnauthorized) Validate() error {
|
||||
alias := (*Problem)(s)
|
||||
if err := alias.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *GetOrganizationForbidden) Validate() error {
|
||||
alias := (*Problem)(s)
|
||||
if err := alias.Validate(); err != nil {
|
||||
@@ -10914,6 +11355,30 @@ func (s *ListMyConsentsUnauthorized) Validate() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *ListMyEvidenceBadRequest) Validate() error {
|
||||
alias := (*Problem)(s)
|
||||
if err := alias.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *ListMyEvidenceForbidden) Validate() error {
|
||||
alias := (*Problem)(s)
|
||||
if err := alias.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *ListMyEvidenceUnauthorized) Validate() error {
|
||||
alias := (*Problem)(s)
|
||||
if err := alias.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *ListMyHiddenOrganizationsBadRequest) Validate() error {
|
||||
alias := (*Problem)(s)
|
||||
if err := alias.Validate(); err != nil {
|
||||
@@ -16322,6 +16787,176 @@ func (s OrganizationDescription) Validate() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *OrganizationEvidence) Validate() error {
|
||||
if s == nil {
|
||||
return validate.ErrNilPointer
|
||||
}
|
||||
|
||||
var failures []validate.FieldError
|
||||
if err := func() error {
|
||||
if s.Items == nil {
|
||||
return errors.New("nil is invalid value")
|
||||
}
|
||||
if err := (validate.Array{
|
||||
MinLength: 0,
|
||||
MinLengthSet: false,
|
||||
MaxLength: 9,
|
||||
MaxLengthSet: true,
|
||||
}).ValidateLength(len(s.Items)); err != nil {
|
||||
return errors.Wrap(err, "array")
|
||||
}
|
||||
var failures []validate.FieldError
|
||||
for i, elem := range s.Items {
|
||||
if err := func() error {
|
||||
if err := elem.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: fmt.Sprintf("[%d]", i),
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "items",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *OrganizationEvidenceFact) Validate() error {
|
||||
if s == nil {
|
||||
return validate.ErrNilPointer
|
||||
}
|
||||
|
||||
var failures []validate.FieldError
|
||||
if err := func() error {
|
||||
if err := s.Skill.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "skill",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := s.Grade.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "grade",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := s.Trust.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "trust",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := s.Basis.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "basis",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := s.CalibrationStatus.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "calibration_status",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := (validate.Int{
|
||||
MinSet: true,
|
||||
Min: 2000,
|
||||
MaxSet: true,
|
||||
Max: 9999,
|
||||
MinExclusive: false,
|
||||
MaxExclusive: false,
|
||||
MultipleOfSet: false,
|
||||
MultipleOf: 0,
|
||||
Pattern: nil,
|
||||
}).Validate(int64(s.ObservedYear)); err != nil {
|
||||
return errors.Wrap(err, "int")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "observed_year",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *OrganizationEvidenceHeaders) Validate() error {
|
||||
if s == nil {
|
||||
return validate.ErrNilPointer
|
||||
}
|
||||
|
||||
var failures []validate.FieldError
|
||||
if err := func() error {
|
||||
if err := s.CacheControl.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "CacheControl",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := s.Response.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "Response",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *OrganizationHeaders) Validate() error {
|
||||
if s == nil {
|
||||
return validate.ErrNilPointer
|
||||
|
||||
@@ -40,6 +40,10 @@ var (
|
||||
// sharedLeafSchemas are the reusable leaves that the privacy family may
|
||||
// refer to; none of them identifies a person or carries a contact.
|
||||
sharedLeafSchemas = []string{"Timestamp", "PageInfo", "SpecializationCode", "GradeCode", "StackTag"}
|
||||
// previewEvidenceSchemas are the evidence leaves that the preview reaches
|
||||
// to show what an organization would read with the categories. They carry
|
||||
// a skill, a grade, a trust level, a year, and the demonstration labels, and no identifier.
|
||||
previewEvidenceSchemas = []string{"OrganizationEvidence", "OrganizationEvidenceFact", "EvidenceSkillCode", "EvidenceTrustLevel", "EvidenceBasis", "EvidenceCalibrationStatus"}
|
||||
)
|
||||
|
||||
func isPrivacySchema(name string) bool {
|
||||
@@ -262,11 +266,11 @@ func TestAnonymousCardReachesNoProfileOrContactSchema(t *testing.T) {
|
||||
}
|
||||
|
||||
// What the card and the preview reach is a small closed list of leaves.
|
||||
allowed := []string{
|
||||
allowed := slices.Concat([]string{
|
||||
"AnonymousCardContent", "CardCategory", "CardCategoryStrength", "CardSelfAssessment", "CardSelfAssessmentConfirmationStatus", "CandidateExperienceBand", "CandidateWorkFormat",
|
||||
"CandidateSalaryCompatibility", "CardField", "CardFieldSet", "PublicationState", "SpecializationCode",
|
||||
"GradeCode", "StackTag", "Timestamp", "CardPreview",
|
||||
}
|
||||
}, previewEvidenceSchemas)
|
||||
for _, name := range []string{"AnonymousCardContent", "CardPreview"} {
|
||||
for reached := range reachableSchemas(index, mustJSONValue(t, spec.Components.Schemas[name])) {
|
||||
if !slices.Contains(allowed, reached) {
|
||||
@@ -286,7 +290,7 @@ func TestAnonymousCardReachesNoProfileOrContactSchema(t *testing.T) {
|
||||
strings.HasPrefix(reached, "Invitation") || strings.HasPrefix(reached, "Need") || strings.HasPrefix(reached, "Consent") {
|
||||
t.Errorf("%s reaches %s", path, reached)
|
||||
}
|
||||
if !isPrivacySchema(reached) && !slices.Contains(sharedLeafSchemas, reached) && !strings.HasPrefix(reached, "Problem") &&
|
||||
if !isPrivacySchema(reached) && !slices.Contains(sharedLeafSchemas, reached) && !slices.Contains(previewEvidenceSchemas, reached) && !strings.HasPrefix(reached, "Problem") &&
|
||||
reached != "Problem" && reached != "ProblemCode" {
|
||||
t.Errorf("%s reaches %s, which is neither a privacy schema nor a shared leaf", path, reached)
|
||||
}
|
||||
|
||||
@@ -52,6 +52,7 @@ func TestCompanyContextMiddlewareFailsClosedAndExcludesOtherScopes(t *testing.T)
|
||||
// Card reads lock any active membership inside their read transaction;
|
||||
// the owner-only capability does not apply to that operation.
|
||||
apiadapter.GetOrganizationCandidateCardOperation,
|
||||
apiadapter.GetOrganizationCandidateEvidenceOperation,
|
||||
apiadapter.HideOrganizationOperation,
|
||||
apiadapter.UnhideOrganizationOperation,
|
||||
apiadapter.RevokeMyOrganizationContactConsentOperation,
|
||||
@@ -135,6 +136,7 @@ func TestCompanyContextOperationInventoryMatchesOpenAPI(t *testing.T) {
|
||||
seen := make(map[string]string, len(ownerCompanyOperations))
|
||||
seenExceptions := make(map[string]bool, len(candidateExceptions))
|
||||
seenCardRead := false
|
||||
seenEvidenceRead := false
|
||||
for path, methods := range document.Paths {
|
||||
for _, operation := range methods {
|
||||
if operation.OperationID == "" {
|
||||
@@ -161,6 +163,13 @@ func TestCompanyContextOperationInventoryMatchesOpenAPI(t *testing.T) {
|
||||
seenCardRead = true
|
||||
continue
|
||||
}
|
||||
// The evidence of a card is a section of that card: it runs the same
|
||||
// transaction-bound membership, visibility, and quota checks.
|
||||
if operation.OperationID == "GetOrganizationCandidateEvidence" &&
|
||||
path == "/api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}/evidence" {
|
||||
seenEvidenceRead = true
|
||||
continue
|
||||
}
|
||||
expectedPath, candidateOperation := candidateExceptions[operation.OperationID]
|
||||
if candidateOperation && expectedPath == path && strings.HasPrefix(path, "/api/v1/me/") {
|
||||
seenExceptions[operation.OperationID] = true
|
||||
@@ -182,6 +191,9 @@ func TestCompanyContextOperationInventoryMatchesOpenAPI(t *testing.T) {
|
||||
if !seenCardRead {
|
||||
t.Error("transaction-authorized candidate card read is absent or moved")
|
||||
}
|
||||
if !seenEvidenceRead {
|
||||
t.Error("transaction-authorized candidate evidence read is absent or moved")
|
||||
}
|
||||
}
|
||||
|
||||
type companyContextAuthenticator struct {
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
package httpadapter
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/ogen-go/ogen"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/http/api"
|
||||
)
|
||||
|
||||
const (
|
||||
evidenceOwnPath = "/api/v1/me/evidence"
|
||||
evidenceOrganizationPath = "/api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}/evidence"
|
||||
)
|
||||
|
||||
// evidenceSchemas are the schemas of the evidence family.
|
||||
var evidenceSchemas = []string{
|
||||
"EvidenceKind", "EvidenceSourceType", "EvidenceAttribution", "EvidenceTrustLevel", "EvidenceVisibility",
|
||||
"EvidenceSkillCode", "EvidenceBasis", "EvidenceCalibrationStatus", "EvidenceResult", "EvidenceSource",
|
||||
"EvidenceFact", "EvidenceFactList", "OrganizationEvidenceFact", "OrganizationEvidence",
|
||||
}
|
||||
|
||||
// rawAssessmentPropertyNames are properties that carry raw answers, failures,
|
||||
// per-item data, or anti-cheat data. No organization operation and no evidence
|
||||
// operation may declare one.
|
||||
var rawAssessmentPropertyNames = []string{
|
||||
"answer", "answers", "answer_key", "reference_answer", "raw_score", "basic_score", "pass_points", "pass_mark_basis_points",
|
||||
"scored_items", "uncertainty", "weak_domains", "practice_results", "practice", "signals", "events", "item_instance_id",
|
||||
"items_answered", "seed", "variant", "hidden_checks", "category_decision", "next_step", "not_determined_reason",
|
||||
"band", "reasons", "attempt_id",
|
||||
}
|
||||
|
||||
// Both evidence operations follow the project conventions: the session cookie
|
||||
// alone (they only read), the unauthenticated and forbidden problems, no-store
|
||||
// on the success, and the shared cursor parameters for the paged list. No new
|
||||
// problem code is needed.
|
||||
func TestEvidenceOperationsFollowTheConventions(t *testing.T) {
|
||||
spec := parsePublicContract(t)
|
||||
own := operationByID(t, spec, "ListMyEvidence")
|
||||
organization := operationByID(t, spec, "GetOrganizationCandidateEvidence")
|
||||
for _, operation := range []*ogen.Operation{own, organization} {
|
||||
if !slices.Contains(operation.Tags, "evidence") {
|
||||
t.Errorf("%s is not in the evidence tag", operation.OperationID)
|
||||
}
|
||||
if !hasSecurity(operation, "sessionCookie") || hasSecurity(operation, "sessionCsrf") {
|
||||
t.Errorf("%s security = %v, want the session cookie without a CSRF token for a read", operation.OperationID, operation.Security)
|
||||
}
|
||||
for _, status := range []string{"400", "401", "403", "default"} {
|
||||
if operation.Responses[status] == nil {
|
||||
t.Errorf("%s does not declare %s", operation.OperationID, status)
|
||||
}
|
||||
}
|
||||
if success := operation.Responses["200"]; success == nil || success.Headers["Cache-Control"] == nil {
|
||||
t.Errorf("%s does not mark its 200 response no-store", operation.OperationID)
|
||||
}
|
||||
if operation.RequestBody != nil {
|
||||
t.Errorf("%s takes a body, but it only reads", operation.OperationID)
|
||||
}
|
||||
}
|
||||
names := []string{}
|
||||
for _, parameter := range own.Parameters {
|
||||
names = append(names, parameterName(parameter))
|
||||
}
|
||||
if !slices.Contains(names, "PageLimit") || !slices.Contains(names, "PageCursor") {
|
||||
t.Errorf("ListMyEvidence parameters = %v, want the shared PageLimit and PageCursor", names)
|
||||
}
|
||||
names = names[:0]
|
||||
for _, parameter := range organization.Parameters {
|
||||
names = append(names, parameterName(parameter))
|
||||
}
|
||||
if !slices.Equal(names, []string{"OrganizationId", "CandidateHandle"}) {
|
||||
t.Errorf("GetOrganizationCandidateEvidence parameters = %v, want the organization and the candidate handle", names)
|
||||
}
|
||||
// The organization read answers an unknown, hidden, unpublished, and
|
||||
// suppressed card alike, and the quota with Retry-After.
|
||||
if organization.Responses["404"] == nil || organization.Responses["429"] == nil {
|
||||
t.Error("GetOrganizationCandidateEvidence must declare 404 and 429")
|
||||
}
|
||||
if own.Responses["404"] != nil {
|
||||
t.Error("ListMyEvidence declares 404: a list has no missing resource")
|
||||
}
|
||||
|
||||
codes := enumValues(t, resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/ProblemCode"}))
|
||||
for _, code := range []string{"validation_failed", "unauthenticated", "forbidden", "not_found", "rate_limited"} {
|
||||
if !slices.Contains(codes, code) {
|
||||
t.Errorf("ProblemCode has no %s", code)
|
||||
}
|
||||
}
|
||||
if spec.Paths[evidenceOwnPath] == nil || spec.Paths[evidenceOrganizationPath] == nil {
|
||||
t.Errorf("the contract lacks the paths %s and %s", evidenceOwnPath, evidenceOrganizationPath)
|
||||
}
|
||||
}
|
||||
|
||||
// A claim and a measurement are different kinds with different trust ranges,
|
||||
// every evidence object is closed, and the organization fact has no identifier
|
||||
// and no exact time.
|
||||
func TestEvidenceSchemasAreClosedAndSeparateClaimsFromMeasurements(t *testing.T) {
|
||||
spec := parsePublicContract(t)
|
||||
if got := enumValues(t, spec.Components.Schemas["EvidenceKind"]); !slices.Equal(got, []string{"claim", "measurement"}) {
|
||||
t.Errorf("EvidenceKind = %v, want claim and measurement", got)
|
||||
}
|
||||
trust := spec.Components.Schemas["EvidenceTrustLevel"]
|
||||
if string(trust.Minimum) != "0" || string(trust.Maximum) != "3" {
|
||||
t.Errorf("EvidenceTrustLevel range = %s..%s, want 0..3", trust.Minimum, trust.Maximum)
|
||||
}
|
||||
for _, pair := range []struct {
|
||||
name string
|
||||
want []string
|
||||
}{
|
||||
{"EvidenceFact", []string{"attribution", "id", "kind", "occurred_at", "result", "skills", "source", "trust", "visibility"}},
|
||||
{"EvidenceSource", []string{"event_id", "result_id", "type"}},
|
||||
{"EvidenceResult", []string{"basis", "calibration_status", "grade"}},
|
||||
{"EvidenceFactList", []string{"items", "page"}},
|
||||
{"OrganizationEvidenceFact", []string{"basis", "calibration_status", "grade", "observed_year", "skill", "trust"}},
|
||||
{"OrganizationEvidence", []string{"items"}},
|
||||
} {
|
||||
schema := spec.Components.Schemas[pair.name]
|
||||
if schema == nil {
|
||||
t.Fatalf("the contract has no schema %s", pair.name)
|
||||
}
|
||||
if got := propertyNames(schema); !slices.Equal(got, pair.want) {
|
||||
t.Errorf("%s properties = %v, want %v", pair.name, got, pair.want)
|
||||
}
|
||||
if schema.AdditionalProperties.Bool == nil || *schema.AdditionalProperties.Bool {
|
||||
t.Errorf("%s accepts unknown properties", pair.name)
|
||||
}
|
||||
if required := slices.Sorted(slices.Values(schema.Required)); !slices.Equal(required, pair.want) {
|
||||
t.Errorf("%s requires %v, want every property %v", pair.name, required, pair.want)
|
||||
}
|
||||
}
|
||||
assertNoJSONFields(t, api.OrganizationEvidenceFact{}, []string{"id", "event_id", "result_id", "occurred_at", "visibility", "candidate_id", "user_id"})
|
||||
for _, property := range spec.Components.Schemas["EvidenceFact"].Properties {
|
||||
if property.Name == "skills" && (!property.Schema.UniqueItems || property.Schema.MinItems == nil || *property.Schema.MinItems != 1) {
|
||||
t.Errorf("EvidenceFact.skills must be a non-empty set: one event with several tags is one fact")
|
||||
}
|
||||
}
|
||||
// An organization reads at most one fact for each category of the card.
|
||||
items := spec.Components.Schemas["OrganizationEvidence"].Properties
|
||||
for _, property := range items {
|
||||
if property.Name == "items" && (property.Schema.MaxItems == nil || *property.Schema.MaxItems != 9) {
|
||||
t.Errorf("OrganizationEvidence.items maxItems = %v, want 9: one fact for each of the nine possible categories", property.Schema.MaxItems)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// No organization operation reaches raw answers, failures, per-item data, or
|
||||
// anti-cheat data, and neither does the evidence of the candidate. The walk
|
||||
// covers every request body, response, parameter, and header through all
|
||||
// references, so a new organization operation cannot reach an assessment
|
||||
// result, attempt, or signal schema by reuse.
|
||||
func TestNoOrganizationOperationReachesRawAssessmentData(t *testing.T) {
|
||||
spec := parsePublicContract(t)
|
||||
index := componentsIndex(t, spec)
|
||||
walked := 0
|
||||
for path, item := range spec.Paths {
|
||||
organizationOperation := strings.HasPrefix(path, "/api/v1/organizations")
|
||||
if !organizationOperation && path != evidenceOwnPath {
|
||||
continue
|
||||
}
|
||||
walked++
|
||||
value := mustJSONValue(t, item)
|
||||
properties := map[string]bool{}
|
||||
declaredPropertyNames(value, properties)
|
||||
for schemaName := range reachableSchemas(index, value) {
|
||||
if strings.HasPrefix(schemaName, "Assessment") || strings.HasPrefix(schemaName, "Practice") ||
|
||||
strings.HasPrefix(schemaName, "ItemContent") || strings.Contains(schemaName, "Signal") ||
|
||||
strings.Contains(schemaName, "Review") {
|
||||
t.Errorf("%s reaches the assessment schema %s", path, schemaName)
|
||||
}
|
||||
declaredPropertyNames(mustJSONValue(t, index["#/components/schemas/"+schemaName]), properties)
|
||||
}
|
||||
if path == evidenceOwnPath && !properties["skills"] {
|
||||
t.Errorf("%s declares no skills property: the walk did not reach the schemas", path)
|
||||
}
|
||||
for _, raw := range rawAssessmentPropertyNames {
|
||||
if properties[raw] {
|
||||
t.Errorf("%s declares the raw assessment property %q", path, raw)
|
||||
}
|
||||
}
|
||||
}
|
||||
if walked < 10 {
|
||||
t.Fatalf("walked only %d organization and evidence paths, want all of them", walked)
|
||||
}
|
||||
}
|
||||
|
||||
// The walk is not vacuous: it reaches the evidence family from both
|
||||
// operations, and the family keeps the failure outcomes out of its enums.
|
||||
func TestEvidenceWalkReachesTheEvidenceFamily(t *testing.T) {
|
||||
spec := parsePublicContract(t)
|
||||
index := componentsIndex(t, spec)
|
||||
for operationID, want := range map[string][]string{
|
||||
"ListMyEvidence": {"EvidenceFact", "EvidenceSource", "EvidenceResult", "EvidenceTrustLevel"},
|
||||
"GetOrganizationCandidateEvidence": {"OrganizationEvidenceFact", "EvidenceSkillCode", "EvidenceTrustLevel"},
|
||||
} {
|
||||
reached := reachableSchemas(index, mustJSONValue(t, operationByID(t, spec, operationID)))
|
||||
for _, name := range want {
|
||||
if !reached[name] {
|
||||
t.Errorf("%s does not reach %s", operationID, name)
|
||||
}
|
||||
}
|
||||
}
|
||||
enums := map[string]bool{}
|
||||
for _, name := range evidenceSchemas {
|
||||
declaredEnumValues(mustJSONValue(t, spec.Components.Schemas[name]), enums)
|
||||
}
|
||||
for _, failure := range []string{"not_confirmed", "not_determined", "failed", "expired", "demonstration", "demo_express", "review", "attention"} {
|
||||
if enums[failure] {
|
||||
t.Errorf("the evidence family declares the enum value %q", failure)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,7 @@ type Handler struct {
|
||||
assessment *AssessmentHandler
|
||||
assessmentSignals *AssessmentSignalHandler
|
||||
privacy *PrivacyHandler
|
||||
evidence *EvidenceHandler
|
||||
problems *problem.Responder
|
||||
}
|
||||
|
||||
@@ -92,6 +93,12 @@ func WithPrivacy(privacy *PrivacyHandler) HandlerOption {
|
||||
return func(handler *Handler) { handler.privacy = privacy }
|
||||
}
|
||||
|
||||
// WithEvidence serves the skill evidence of a candidate and its permitted
|
||||
// organization projection.
|
||||
func WithEvidence(evidence *EvidenceHandler) HandlerOption {
|
||||
return func(handler *Handler) { handler.evidence = evidence }
|
||||
}
|
||||
|
||||
func NewHandler(health *HealthHandler, problems *problem.Responder, options ...HandlerOption) *Handler {
|
||||
handler := &Handler{health: health, problems: problems}
|
||||
for _, option := range options {
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/http/api"
|
||||
"lincodex/backend/internal/adapter/primary/http/problem"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
"lincodex/backend/internal/usecase/candidateview"
|
||||
"lincodex/backend/internal/usecase/evidence"
|
||||
)
|
||||
|
||||
// EvidenceOperations reads the skill evidence projection.
|
||||
type EvidenceOperations interface {
|
||||
ListMine(ctx context.Context, query outbound.EvidenceListQuery) (outbound.EvidenceFactPage, error)
|
||||
ListForOrganization(ctx context.Context, actorID, organizationID uuid.UUID, handle string) ([]domain.EvidenceOrganizationFact, error)
|
||||
}
|
||||
|
||||
// EvidenceHandler binds the evidence read use cases to the v1 API.
|
||||
type EvidenceHandler struct {
|
||||
operations EvidenceOperations
|
||||
}
|
||||
|
||||
func NewEvidenceHandler(operations EvidenceOperations) *EvidenceHandler {
|
||||
if operations == nil {
|
||||
panic("v1.NewEvidenceHandler - operations must not be nil")
|
||||
}
|
||||
return &EvidenceHandler{operations: operations}
|
||||
}
|
||||
|
||||
func (handler *Handler) ListMyEvidence(ctx context.Context, params api.ListMyEvidenceParams) (api.ListMyEvidenceRes, error) {
|
||||
if handler.evidence == nil {
|
||||
return handler.UnimplementedHandler.ListMyEvidence(ctx, params)
|
||||
}
|
||||
return handler.evidence.ListMyEvidence(ctx, params)
|
||||
}
|
||||
|
||||
func (handler *Handler) GetOrganizationCandidateEvidence(
|
||||
ctx context.Context,
|
||||
params api.GetOrganizationCandidateEvidenceParams,
|
||||
) (api.GetOrganizationCandidateEvidenceRes, error) {
|
||||
if handler.evidence == nil {
|
||||
return handler.UnimplementedHandler.GetOrganizationCandidateEvidence(ctx, params)
|
||||
}
|
||||
return handler.evidence.GetOrganizationCandidateEvidence(ctx, params)
|
||||
}
|
||||
|
||||
func (handler *EvidenceHandler) ListMyEvidence(ctx context.Context, params api.ListMyEvidenceParams) (api.ListMyEvidenceRes, error) {
|
||||
const location = "EvidenceHandler.ListMyEvidence"
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.ListMyEvidenceUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
limit, cursor, pointer := privacyPageParams(params.Limit, params.Cursor, principal.UserID, privacyCursorEvidence)
|
||||
if pointer != "" {
|
||||
return (*api.ListMyEvidenceBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationQuery, "/"+pointer).Response), nil
|
||||
}
|
||||
query := outbound.EvidenceListQuery{CandidateID: principal.UserID, Limit: limit}
|
||||
if cursor != nil {
|
||||
query.After = &outbound.EvidencePosition{OccurredAt: cursor.at, ID: cursor.id}
|
||||
}
|
||||
page, err := handler.operations.ListMine(ctx, query)
|
||||
if err != nil {
|
||||
if errors.Is(err, evidence.ErrForbidden) {
|
||||
return (*api.ListMyEvidenceForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
items := make([]api.EvidenceFact, 0, len(page.Items))
|
||||
for _, fact := range page.Items {
|
||||
items = append(items, evidenceFactResponse(fact.Snapshot()))
|
||||
}
|
||||
next, err := privacyNextCursor(page.HasMore, len(page.Items), func() (string, error) {
|
||||
last := outbound.EvidencePositionOf(page.Items[len(page.Items)-1])
|
||||
return encodePrivacyCursor(principal.UserID, privacyCursorEvidence, last.OccurredAt, last.ID)
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - encode cursor: %w", location, err)
|
||||
}
|
||||
return &api.EvidenceFactListHeaders{
|
||||
CacheControl: api.CacheControlNoStoreNoStore,
|
||||
Response: api.EvidenceFactList{Items: items, Page: api.PageInfo{HasMore: page.HasMore, NextCursor: next}},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (handler *EvidenceHandler) GetOrganizationCandidateEvidence(
|
||||
ctx context.Context,
|
||||
params api.GetOrganizationCandidateEvidenceParams,
|
||||
) (api.GetOrganizationCandidateEvidenceRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.GetOrganizationCandidateEvidenceUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
facts, err := handler.operations.ListForOrganization(ctx, principal.UserID, params.OrgID, string(params.CandidateHandle))
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, candidateview.ErrForbidden):
|
||||
return (*api.GetOrganizationCandidateEvidenceForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
case errors.Is(err, candidateview.ErrCandidateCardNotFound), errors.Is(err, outbound.ErrOrganizationNotFound):
|
||||
return (*api.GetOrganizationCandidateEvidenceNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
|
||||
case errors.Is(err, candidateview.ErrInvalidCandidateHandle):
|
||||
return (*api.GetOrganizationCandidateEvidenceBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationPath, "/candidate_handle").Response), nil
|
||||
}
|
||||
if limited, ok := candidateViewRateLimited(ctx, err); ok {
|
||||
return limited, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
evidence := organizationEvidenceResponse(facts)
|
||||
return &api.OrganizationEvidenceHeaders{
|
||||
CacheControl: api.CacheControlNoStoreNoStore,
|
||||
Response: evidence,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func evidenceFactResponse(fact domain.EvidenceFactSnapshot) api.EvidenceFact {
|
||||
return api.EvidenceFact{
|
||||
ID: fact.ID, Kind: api.EvidenceKind(fact.Kind),
|
||||
Source: api.EvidenceSource{
|
||||
Type: api.EvidenceSourceType(fact.SourceType), EventID: fact.EventID, ResultID: fact.ResultID,
|
||||
},
|
||||
Skills: evidenceSkillsResponse(fact.Skills),
|
||||
Result: evidenceResultResponse(fact.Result),
|
||||
Attribution: api.EvidenceAttribution(fact.Attribution), Trust: api.EvidenceTrustLevel(fact.Trust),
|
||||
OccurredAt: api.Timestamp(fact.OccurredAt), Visibility: api.EvidenceVisibility(fact.Visibility),
|
||||
}
|
||||
}
|
||||
|
||||
// organizationEvidenceResponse maps the allowlisted facts that an
|
||||
// organization, or the preview of the candidate, reads.
|
||||
func organizationEvidenceResponse(facts []domain.EvidenceOrganizationFact) api.OrganizationEvidence {
|
||||
items := make([]api.OrganizationEvidenceFact, 0, len(facts))
|
||||
for _, fact := range facts {
|
||||
input := fact.Input()
|
||||
items = append(items, api.OrganizationEvidenceFact{
|
||||
Skill: api.EvidenceSkillCode(input.Skill), Grade: api.GradeCode(input.Grade),
|
||||
Trust: api.EvidenceTrustLevel(input.Trust), Basis: api.EvidenceBasis(input.Basis),
|
||||
CalibrationStatus: api.EvidenceCalibrationStatus(input.CalibrationStatus), ObservedYear: input.ObservedYear,
|
||||
})
|
||||
}
|
||||
return api.OrganizationEvidence{Items: items}
|
||||
}
|
||||
|
||||
func evidenceSkillsResponse(skills []domain.EvidenceSkillCode) []api.EvidenceSkillCode {
|
||||
response := make([]api.EvidenceSkillCode, 0, len(skills))
|
||||
for _, skill := range skills {
|
||||
response = append(response, api.EvidenceSkillCode(skill))
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
func evidenceResultResponse(result domain.EvidenceResult) api.EvidenceResult {
|
||||
return api.EvidenceResult{
|
||||
Grade: api.GradeCode(result.Grade), Basis: api.EvidenceBasis(result.Basis),
|
||||
CalibrationStatus: api.EvidenceCalibrationStatus(result.CalibrationStatus),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/http/api"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
"lincodex/backend/internal/usecase/candidateview"
|
||||
"lincodex/backend/internal/usecase/evidence"
|
||||
)
|
||||
|
||||
type evidenceOperationsStub struct {
|
||||
page outbound.EvidenceFactPage
|
||||
facts []domain.EvidenceOrganizationFact
|
||||
err error
|
||||
query outbound.EvidenceListQuery
|
||||
actorID uuid.UUID
|
||||
orgID uuid.UUID
|
||||
handle string
|
||||
listCalls int
|
||||
}
|
||||
|
||||
func (stub *evidenceOperationsStub) ListMine(_ context.Context, query outbound.EvidenceListQuery) (outbound.EvidenceFactPage, error) {
|
||||
stub.query = query
|
||||
return stub.page, stub.err
|
||||
}
|
||||
|
||||
func (stub *evidenceOperationsStub) ListForOrganization(_ context.Context, actorID, organizationID uuid.UUID, handle string) ([]domain.EvidenceOrganizationFact, error) {
|
||||
stub.listCalls++
|
||||
stub.actorID, stub.orgID, stub.handle = actorID, organizationID, handle
|
||||
return stub.facts, stub.err
|
||||
}
|
||||
|
||||
func evidenceTestFact(t *testing.T, candidateID uuid.UUID, at time.Time) domain.EvidenceFact {
|
||||
t.Helper()
|
||||
attempt := uuid.New()
|
||||
fact, err := domain.RestoreEvidenceFact(domain.EvidenceFactSnapshot{
|
||||
ID: uuid.New(), CandidateID: candidateID, Kind: domain.EvidenceKindMeasurement,
|
||||
SourceType: domain.EvidenceSourceAssessmentResult, EventID: attempt, ResultID: attempt,
|
||||
Skills: []domain.EvidenceSkillCode{"go", "backend"},
|
||||
Result: domain.EvidenceResult{
|
||||
Grade: domain.GradeJunior, Basis: domain.AssessmentCategorySourceSyntheticDemo,
|
||||
CalibrationStatus: domain.AssessmentCategoryCalibrationUncalibrated,
|
||||
},
|
||||
Attribution: domain.EvidenceAttributionPersonal, Trust: domain.EvidenceTrustOnlineUnconfirmed,
|
||||
OccurredAt: at, Visibility: domain.EvidenceVisibilityVisible,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("RestoreEvidenceFact() error = %v", err)
|
||||
}
|
||||
return fact
|
||||
}
|
||||
|
||||
func TestListMyEvidenceMapsFactsAndPagesWithAnOwnerBoundCursor(t *testing.T) {
|
||||
userID := uuid.New()
|
||||
at := time.Date(2026, 10, 8, 10, 15, 0, 0, time.UTC)
|
||||
stub := &evidenceOperationsStub{page: outbound.EvidenceFactPage{
|
||||
Items: []domain.EvidenceFact{evidenceTestFact(t, userID, at)},
|
||||
HasMore: true,
|
||||
}}
|
||||
handler := NewEvidenceHandler(stub)
|
||||
ctx := privacyHTTPContext(userID, "")
|
||||
|
||||
response, err := handler.ListMyEvidence(ctx, api.ListMyEvidenceParams{Limit: api.NewOptInt32(1)})
|
||||
if err != nil {
|
||||
t.Fatalf("ListMyEvidence() error = %v", err)
|
||||
}
|
||||
page, ok := response.(*api.EvidenceFactListHeaders)
|
||||
if !ok || page.CacheControl != api.CacheControlNoStoreNoStore || len(page.Response.Items) != 1 {
|
||||
t.Fatalf("ListMyEvidence() = %#v, want a no-store page of one fact", response)
|
||||
}
|
||||
item := page.Response.Items[0]
|
||||
if item.Trust != 1 || item.Kind != api.EvidenceKindMeasurement || item.Source.EventID != item.Source.ResultID ||
|
||||
len(item.Skills) != 2 || item.Skills[0] != api.EvidenceSkillCodeBackend || item.Result.Grade != api.GradeCodeJunior ||
|
||||
item.Visibility != api.EvidenceVisibilityVisible || !time.Time(item.OccurredAt).Equal(at) {
|
||||
t.Fatalf("fact mapping = %+v", item)
|
||||
}
|
||||
if stub.query.CandidateID != userID || stub.query.Limit != 1 || stub.query.After != nil {
|
||||
t.Fatalf("query = %+v, want the session owner and the first page", stub.query)
|
||||
}
|
||||
cursor, set := page.Response.Page.NextCursor.Get()
|
||||
if !page.Response.Page.HasMore || !set || cursor == "" {
|
||||
t.Fatalf("page info = %+v, want a next cursor", page.Response.Page)
|
||||
}
|
||||
|
||||
// The cursor continues the same owner's list at the last fact of the page.
|
||||
if _, err := handler.ListMyEvidence(ctx, api.ListMyEvidenceParams{Cursor: api.NewOptString(cursor)}); err != nil {
|
||||
t.Fatalf("ListMyEvidence(cursor) error = %v", err)
|
||||
}
|
||||
if stub.query.After == nil || stub.query.After.ID != stub.page.Items[0].Snapshot().ID || !stub.query.After.OccurredAt.Equal(at) {
|
||||
t.Fatalf("continuation = %+v, want the last fact of the previous page", stub.query.After)
|
||||
}
|
||||
|
||||
// A cursor of another candidate, a cursor of another list, and a limit out of range are validation errors.
|
||||
foreign, err := encodePrivacyCursor(uuid.New(), privacyCursorEvidence, at, uuid.New())
|
||||
if err != nil {
|
||||
t.Fatalf("encodePrivacyCursor() error = %v", err)
|
||||
}
|
||||
otherList, err := encodePrivacyCursor(userID, privacyCursorAccess, at, uuid.New())
|
||||
if err != nil {
|
||||
t.Fatalf("encodePrivacyCursor() error = %v", err)
|
||||
}
|
||||
for name, params := range map[string]api.ListMyEvidenceParams{
|
||||
"foreign cursor": {Cursor: api.NewOptString(foreign)},
|
||||
"other list": {Cursor: api.NewOptString(otherList)},
|
||||
"malformed cursor": {Cursor: api.NewOptString("not-a-cursor")},
|
||||
"limit too large": {Limit: api.NewOptInt32(outbound.MaxEvidencePageSize + 1)},
|
||||
} {
|
||||
response, err := handler.ListMyEvidence(ctx, params)
|
||||
if _, bad := response.(*api.ListMyEvidenceBadRequest); err != nil || !bad {
|
||||
t.Errorf("%s = %#v, %v, want 400", name, response, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestListMyEvidenceMapsAccessFailures(t *testing.T) {
|
||||
userID := uuid.New()
|
||||
stub := &evidenceOperationsStub{err: evidence.ErrForbidden}
|
||||
handler := NewEvidenceHandler(stub)
|
||||
response, err := handler.ListMyEvidence(privacyHTTPContext(userID, ""), api.ListMyEvidenceParams{})
|
||||
if _, forbidden := response.(*api.ListMyEvidenceForbidden); err != nil || !forbidden {
|
||||
t.Fatalf("forbidden actor = %#v, %v, want 403", response, err)
|
||||
}
|
||||
unauthenticated, err := handler.ListMyEvidence(context.Background(), api.ListMyEvidenceParams{})
|
||||
if _, ok := unauthenticated.(*api.ListMyEvidenceUnauthorized); err != nil || !ok {
|
||||
t.Fatalf("no principal = %#v, %v, want 401", unauthenticated, err)
|
||||
}
|
||||
stub.err = errors.New("storage failed")
|
||||
if _, err := handler.ListMyEvidence(privacyHTTPContext(userID, ""), api.ListMyEvidenceParams{}); err == nil {
|
||||
t.Fatal("an unexpected failure was swallowed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestOrganizationEvidenceMapsOnlyTheAllowlistedShape(t *testing.T) {
|
||||
userID, organizationID := uuid.New(), uuid.New()
|
||||
handle := "cv1_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
|
||||
fact, err := domain.NewEvidenceOrganizationFact(domain.EvidenceOrganizationFactInput{
|
||||
Skill: "backend", Grade: domain.GradeJunior, Trust: domain.EvidenceTrustOnlineUnconfirmed,
|
||||
Basis: domain.AssessmentCategorySourceSyntheticDemo, CalibrationStatus: domain.AssessmentCategoryCalibrationUncalibrated, ObservedYear: 2026,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewEvidenceOrganizationFact() error = %v", err)
|
||||
}
|
||||
stub := &evidenceOperationsStub{facts: []domain.EvidenceOrganizationFact{fact}}
|
||||
handler := NewEvidenceHandler(stub)
|
||||
ctx := privacyHTTPContext(userID, "")
|
||||
params := api.GetOrganizationCandidateEvidenceParams{OrgID: organizationID, CandidateHandle: api.CandidateHandle(handle)}
|
||||
|
||||
response, err := handler.GetOrganizationCandidateEvidence(ctx, params)
|
||||
if err != nil {
|
||||
t.Fatalf("GetOrganizationCandidateEvidence() error = %v", err)
|
||||
}
|
||||
body, ok := response.(*api.OrganizationEvidenceHeaders)
|
||||
if !ok || body.CacheControl != api.CacheControlNoStoreNoStore || len(body.Response.Items) != 1 {
|
||||
t.Fatalf("response = %#v, want a no-store projection of one fact", response)
|
||||
}
|
||||
if stub.actorID != userID || stub.orgID != organizationID || stub.handle != handle {
|
||||
t.Fatalf("scope = actor %s organization %s handle %q", stub.actorID, stub.orgID, stub.handle)
|
||||
}
|
||||
encoded, err := json.Marshal(body.Response)
|
||||
if err != nil {
|
||||
t.Fatalf("encode projection: %v", err)
|
||||
}
|
||||
if want := `{"items":[{"skill":"backend","grade":"junior","trust":1,"basis":"synthetic_demo","calibration_status":"uncalibrated","observed_year":2026}]}`; string(encoded) != want {
|
||||
t.Fatalf("projection = %s, want %s", encoded, want)
|
||||
}
|
||||
for _, private := range []string{userID.String(), "event_id", "result_id", "occurred_at", "observed_month", "answer", "score", "visibility"} {
|
||||
if strings.Contains(string(encoded), private) {
|
||||
t.Fatalf("organization projection exposes %q: %s", private, encoded)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestOrganizationEvidenceMapsCardFailuresWithoutDistinction(t *testing.T) {
|
||||
userID, organizationID := uuid.New(), uuid.New()
|
||||
handle := api.CandidateHandle("cv1_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
|
||||
stub := &evidenceOperationsStub{}
|
||||
handler := NewEvidenceHandler(stub)
|
||||
ctx := privacyHTTPContext(userID, "")
|
||||
params := api.GetOrganizationCandidateEvidenceParams{OrgID: organizationID, CandidateHandle: handle}
|
||||
|
||||
for name, test := range map[string]struct {
|
||||
err error
|
||||
want string
|
||||
}{
|
||||
"candidate account": {candidateview.ErrForbidden, "forbidden"},
|
||||
"hidden or unpublished": {candidateview.ErrCandidateCardNotFound, "not_found"},
|
||||
"no membership": {outbound.ErrOrganizationNotFound, "not_found"},
|
||||
"bad handle": {candidateview.ErrInvalidCandidateHandle, "bad_request"},
|
||||
"quota": {&candidateview.RateLimitedError{RetryAt: time.Now().Add(time.Minute)}, "too_many"},
|
||||
} {
|
||||
stub.err = test.err
|
||||
response, err := handler.GetOrganizationCandidateEvidence(ctx, params)
|
||||
if err != nil {
|
||||
t.Errorf("%s: error = %v", name, err)
|
||||
continue
|
||||
}
|
||||
var got string
|
||||
switch response.(type) {
|
||||
case *api.GetOrganizationCandidateEvidenceForbidden:
|
||||
got = "forbidden"
|
||||
case *api.GetOrganizationCandidateEvidenceNotFound:
|
||||
got = "not_found"
|
||||
case *api.GetOrganizationCandidateEvidenceBadRequest:
|
||||
got = "bad_request"
|
||||
case *api.TooManyRequestsHeaders:
|
||||
got = "too_many"
|
||||
}
|
||||
if got != test.want {
|
||||
t.Errorf("%s = %T, want %s", name, response, test.want)
|
||||
}
|
||||
}
|
||||
stub.err = errors.New("storage failed")
|
||||
if _, err := handler.GetOrganizationCandidateEvidence(ctx, params); err == nil {
|
||||
t.Fatal("an unexpected failure was swallowed")
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,9 @@ const (
|
||||
privacyCursorEvents = 1
|
||||
privacyCursorHidden = 2
|
||||
privacyCursorAccess = 3
|
||||
// privacyCursorEvidence belongs to the skill evidence list, which shares the
|
||||
// owner-bound cursor of the privacy lists.
|
||||
privacyCursorEvidence = 4
|
||||
)
|
||||
|
||||
// CandidateViewOperations serves private previews, owner access history, and
|
||||
@@ -434,7 +437,7 @@ func privacyPageParams(limit api.OptInt32, cursor api.OptString, owner uuid.UUID
|
||||
func encodePrivacyCursor(owner uuid.UUID, kind byte, at time.Time, id uuid.UUID) (string, error) {
|
||||
at = at.UTC()
|
||||
seconds, nanos := at.Unix(), at.Nanosecond()
|
||||
if owner == uuid.Nil || id == uuid.Nil || kind < privacyCursorEvents || kind > privacyCursorAccess || at.IsZero() ||
|
||||
if owner == uuid.Nil || id == uuid.Nil || kind < privacyCursorEvents || kind > privacyCursorEvidence || at.IsZero() ||
|
||||
at.Year() < 1 || at.Year() > 9999 || nanos < 0 || nanos >= 1_000_000_000 || nanos%1_000 != 0 {
|
||||
return "", errors.New("privacy cursor requires an owner and valid page position")
|
||||
}
|
||||
@@ -518,7 +521,13 @@ func cardPreviewResponse(preview candidateview.PreviewResult) api.CardPreview {
|
||||
} else {
|
||||
card.SetTo(anonymousCardResponse(*preview.Card))
|
||||
}
|
||||
return api.CardPreview{State: state, Fields: fields, Card: card, GeneratedAt: api.Timestamp(preview.GeneratedAt)}
|
||||
evidence := api.NilOrganizationEvidence{}
|
||||
if preview.Card == nil {
|
||||
evidence.SetToNull()
|
||||
} else {
|
||||
evidence.SetTo(organizationEvidenceResponse(preview.Evidence))
|
||||
}
|
||||
return api.CardPreview{State: state, Fields: fields, Card: card, Evidence: evidence, GeneratedAt: api.Timestamp(preview.GeneratedAt)}
|
||||
}
|
||||
|
||||
func anonymousCardResponse(view domain.AnonymousCandidateViewDTO) api.AnonymousCardContent {
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
var _ outbound.EvidenceRepository = evidenceRepository{}
|
||||
|
||||
func (unit *UnitOfWork) Evidence() outbound.EvidenceRepository {
|
||||
return evidenceRepository{queries: unit.queries}
|
||||
}
|
||||
|
||||
type evidenceRepository struct {
|
||||
queries *sqlc.Queries
|
||||
}
|
||||
|
||||
func (repository evidenceRepository) ListCandidateFacts(
|
||||
ctx context.Context,
|
||||
query outbound.EvidenceListQuery,
|
||||
) (outbound.EvidenceFactPage, error) {
|
||||
const location = "evidenceRepository.ListCandidateFacts"
|
||||
if query.CandidateID == uuid.Nil || query.Limit < 1 || query.Limit > outbound.MaxEvidencePageSize {
|
||||
return outbound.EvidenceFactPage{}, fmt.Errorf("%s - query is invalid: %w", location, domain.ErrInvalidEvidence)
|
||||
}
|
||||
// The statement fetches one extra row to learn whether another page follows.
|
||||
params := sqlc.ListCandidateEvidenceFactsParams{CandidateID: pgUUID(query.CandidateID), RowLimit: query.Limit + 1}
|
||||
if query.After != nil {
|
||||
if query.After.ID == uuid.Nil || query.After.OccurredAt.IsZero() {
|
||||
return outbound.EvidenceFactPage{}, fmt.Errorf("%s - continuation position is invalid: %w", location, domain.ErrInvalidEvidence)
|
||||
}
|
||||
params.AfterOccurredAt = pgTime(query.After.OccurredAt)
|
||||
params.AfterID = pgUUID(query.After.ID)
|
||||
}
|
||||
rows, err := repository.queries.ListCandidateEvidenceFacts(ctx, params)
|
||||
if err != nil {
|
||||
return outbound.EvidenceFactPage{}, fmt.Errorf("%s - select facts: %w", location, markTransactionConflict(sanitizeConnectError(err)))
|
||||
}
|
||||
page := outbound.EvidenceFactPage{Items: make([]domain.EvidenceFact, 0, min(len(rows), int(query.Limit)))}
|
||||
if len(rows) > int(query.Limit) {
|
||||
page.HasMore = true
|
||||
rows = rows[:query.Limit]
|
||||
}
|
||||
for _, row := range rows {
|
||||
fact, err := restoreEvidenceFactRow(query.CandidateID, row)
|
||||
if err != nil {
|
||||
return outbound.EvidenceFactPage{}, fmt.Errorf("%s - restore fact: %w", location, err)
|
||||
}
|
||||
page.Items = append(page.Items, fact)
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func restoreEvidenceFactRow(candidateID uuid.UUID, row sqlc.ListCandidateEvidenceFactsRow) (domain.EvidenceFact, error) {
|
||||
const location = "restoreEvidenceFactRow"
|
||||
skills := make([]domain.EvidenceSkillCode, 0, len(row.Skills))
|
||||
for _, code := range row.Skills {
|
||||
skills = append(skills, domain.EvidenceSkillCode(code))
|
||||
}
|
||||
trust, err := evidenceTrust(row.Trust)
|
||||
if err != nil {
|
||||
return domain.EvidenceFact{}, fmt.Errorf("%s - %w", location, err)
|
||||
}
|
||||
fact, err := domain.RestoreEvidenceFact(domain.EvidenceFactSnapshot{
|
||||
ID: optionalUUID(row.ID), CandidateID: candidateID, Kind: domain.EvidenceKind(row.Kind),
|
||||
SourceType: domain.EvidenceSourceType(row.SourceType), EventID: optionalUUID(row.EventID),
|
||||
ResultID: optionalUUID(row.ResultID), Skills: skills,
|
||||
Result: domain.EvidenceResult{
|
||||
Grade: domain.GradeCode(row.Grade), Basis: domain.AssessmentCategorySource(row.Basis),
|
||||
CalibrationStatus: domain.AssessmentCategoryCalibrationStatus(row.CalibrationStatus),
|
||||
},
|
||||
Attribution: domain.EvidenceAttribution(row.Attribution), Trust: trust,
|
||||
OccurredAt: timeValueOrZero(row.OccurredAt), Visibility: domain.EvidenceVisibility(row.Visibility),
|
||||
})
|
||||
if err != nil {
|
||||
return domain.EvidenceFact{}, fmt.Errorf("%s - stored fact is invalid: %w", location, err)
|
||||
}
|
||||
return fact, nil
|
||||
}
|
||||
|
||||
func (repository evidenceRepository) ListOrganizationFacts(
|
||||
ctx context.Context,
|
||||
organizationID, candidateID uuid.UUID,
|
||||
categories []domain.CandidateViewCategory,
|
||||
) ([]domain.EvidenceOrganizationFact, error) {
|
||||
const location = "evidenceRepository.ListOrganizationFacts"
|
||||
if organizationID == uuid.Nil || candidateID == uuid.Nil {
|
||||
return nil, fmt.Errorf("%s - identifiers must be set: %w", location, domain.ErrInvalidEvidence)
|
||||
}
|
||||
pairs, err := evidenceCategoryPairs(categories)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - %w", location, err)
|
||||
}
|
||||
if len(pairs) == 0 {
|
||||
return []domain.EvidenceOrganizationFact{}, nil
|
||||
}
|
||||
rows, err := repository.queries.ListOrganizationVisibleEvidence(ctx, sqlc.ListOrganizationVisibleEvidenceParams{
|
||||
Categories: pairs, CandidateID: pgUUID(candidateID), OrganizationID: pgUUID(organizationID),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - select permitted facts: %w", location, markTransactionConflict(sanitizeConnectError(err)))
|
||||
}
|
||||
facts := make([]domain.EvidenceOrganizationFact, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
fact, err := restoreEvidenceOrganizationFact(row.Skill, row.Grade, row.Trust, row.Basis, row.CalibrationStatus, row.ObservedYear)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - %w", location, err)
|
||||
}
|
||||
facts = append(facts, fact)
|
||||
}
|
||||
return facts, nil
|
||||
}
|
||||
|
||||
func (repository evidenceRepository) ListPreviewFacts(
|
||||
ctx context.Context,
|
||||
candidateID uuid.UUID,
|
||||
categories []domain.CandidateViewCategory,
|
||||
) ([]domain.EvidenceOrganizationFact, error) {
|
||||
const location = "evidenceRepository.ListPreviewFacts"
|
||||
if candidateID == uuid.Nil {
|
||||
return nil, fmt.Errorf("%s - candidate ID must be set: %w", location, domain.ErrInvalidEvidence)
|
||||
}
|
||||
pairs, err := evidenceCategoryPairs(categories)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - %w", location, err)
|
||||
}
|
||||
if len(pairs) == 0 {
|
||||
return []domain.EvidenceOrganizationFact{}, nil
|
||||
}
|
||||
rows, err := repository.queries.ListCandidatePreviewEvidence(ctx, sqlc.ListCandidatePreviewEvidenceParams{
|
||||
Categories: pairs, CandidateID: pgUUID(candidateID),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - select preview facts: %w", location, markTransactionConflict(sanitizeConnectError(err)))
|
||||
}
|
||||
facts := make([]domain.EvidenceOrganizationFact, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
fact, err := restoreEvidenceOrganizationFact(row.Skill, row.Grade, row.Trust, row.Basis, row.CalibrationStatus, row.ObservedYear)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - %w", location, err)
|
||||
}
|
||||
facts = append(facts, fact)
|
||||
}
|
||||
return facts, nil
|
||||
}
|
||||
|
||||
// evidenceCategoryPairs renders the categories of a card as the
|
||||
// "specialization/grade" keys that the statements match against a fact.
|
||||
func evidenceCategoryPairs(categories []domain.CandidateViewCategory) ([]string, error) {
|
||||
pairs := make([]string, 0, len(categories))
|
||||
for _, category := range categories {
|
||||
if !category.Specialization.IsKnown() || !category.Grade.IsKnown() {
|
||||
return nil, fmt.Errorf("category is not known: %w", domain.ErrInvalidEvidence)
|
||||
}
|
||||
pairs = append(pairs, string(domain.EvidenceSkillOfSpecialization(category.Specialization))+"/"+string(category.Grade))
|
||||
}
|
||||
return pairs, nil
|
||||
}
|
||||
|
||||
func restoreEvidenceOrganizationFact(skill, grade string, trust int16, basis, calibration string, year int32) (domain.EvidenceOrganizationFact, error) {
|
||||
level, err := evidenceTrust(trust)
|
||||
if err != nil {
|
||||
return domain.EvidenceOrganizationFact{}, err
|
||||
}
|
||||
fact, err := domain.NewEvidenceOrganizationFact(domain.EvidenceOrganizationFactInput{
|
||||
Skill: domain.EvidenceSkillCode(skill), Grade: domain.GradeCode(grade), Trust: level,
|
||||
Basis: domain.AssessmentCategorySource(basis), CalibrationStatus: domain.AssessmentCategoryCalibrationStatus(calibration),
|
||||
ObservedYear: year,
|
||||
})
|
||||
if err != nil {
|
||||
return domain.EvidenceOrganizationFact{}, fmt.Errorf("restore permitted fact: %w", err)
|
||||
}
|
||||
return fact, nil
|
||||
}
|
||||
|
||||
// evidenceTrust narrows the stored smallint after checking the range that the
|
||||
// table constraint already guarantees.
|
||||
func evidenceTrust(value int16) (domain.EvidenceTrust, error) {
|
||||
if value < int16(domain.EvidenceTrustStated) || value > int16(domain.EvidenceTrustInPerson) {
|
||||
return 0, fmt.Errorf("stored trust level is out of range: %w", domain.ErrInvalidEvidence)
|
||||
}
|
||||
return domain.EvidenceTrust(value), nil
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: evidence.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const listCandidateEvidenceFacts = `-- name: ListCandidateEvidenceFacts :many
|
||||
|
||||
SELECT
|
||||
fact.id,
|
||||
fact.kind,
|
||||
fact.source_type,
|
||||
fact.event_id,
|
||||
fact.result_id,
|
||||
fact.attribution,
|
||||
fact.trust,
|
||||
fact.grade,
|
||||
fact.basis,
|
||||
fact.calibration_status,
|
||||
fact.occurred_at,
|
||||
fact.visibility,
|
||||
COALESCE(
|
||||
(
|
||||
SELECT array_agg(skill.skill_code ORDER BY skill.skill_code)
|
||||
FROM skill_evidence_skills AS skill
|
||||
WHERE skill.fact_id = fact.id
|
||||
),
|
||||
'{}'::text []
|
||||
)::text [] AS skills
|
||||
FROM skill_evidence_facts AS fact
|
||||
WHERE
|
||||
fact.candidate_id = $1
|
||||
AND (
|
||||
$2::timestamptz IS NULL
|
||||
OR (fact.occurred_at, fact.id) < (
|
||||
$2::timestamptz,
|
||||
$3::uuid
|
||||
)
|
||||
)
|
||||
ORDER BY fact.occurred_at DESC, fact.id DESC
|
||||
LIMIT $4
|
||||
`
|
||||
|
||||
type ListCandidateEvidenceFactsParams struct {
|
||||
CandidateID pgtype.UUID
|
||||
AfterOccurredAt pgtype.Timestamptz
|
||||
AfterID pgtype.UUID
|
||||
RowLimit int32
|
||||
}
|
||||
|
||||
type ListCandidateEvidenceFactsRow struct {
|
||||
ID pgtype.UUID
|
||||
Kind string
|
||||
SourceType string
|
||||
EventID pgtype.UUID
|
||||
ResultID pgtype.UUID
|
||||
Attribution string
|
||||
Trust int16
|
||||
Grade string
|
||||
Basis string
|
||||
CalibrationStatus string
|
||||
OccurredAt pgtype.Timestamptz
|
||||
Visibility string
|
||||
Skills []string
|
||||
}
|
||||
|
||||
// Skill evidence reads. The projection tables hold no answer, score, item,
|
||||
// failure, or anti-cheat data, and none of these statements names the result,
|
||||
// attempt, or review tables: evidence is read from its own facts only.
|
||||
// The candidate's own facts, hidden ones included, newest event first. Every
|
||||
// statement is scoped by the owner; the caller passes the continuation
|
||||
// position of the previous page, if any, and fetches one extra row.
|
||||
func (q *Queries) ListCandidateEvidenceFacts(ctx context.Context, arg ListCandidateEvidenceFactsParams) ([]ListCandidateEvidenceFactsRow, error) {
|
||||
rows, err := q.db.Query(ctx, listCandidateEvidenceFacts,
|
||||
arg.CandidateID,
|
||||
arg.AfterOccurredAt,
|
||||
arg.AfterID,
|
||||
arg.RowLimit,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []ListCandidateEvidenceFactsRow
|
||||
for rows.Next() {
|
||||
var i ListCandidateEvidenceFactsRow
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.Kind,
|
||||
&i.SourceType,
|
||||
&i.EventID,
|
||||
&i.ResultID,
|
||||
&i.Attribution,
|
||||
&i.Trust,
|
||||
&i.Grade,
|
||||
&i.Basis,
|
||||
&i.CalibrationStatus,
|
||||
&i.OccurredAt,
|
||||
&i.Visibility,
|
||||
&i.Skills,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listCandidatePreviewEvidence = `-- name: ListCandidatePreviewEvidence :many
|
||||
SELECT DISTINCT ON (skill.skill_code)
|
||||
skill.skill_code AS skill,
|
||||
fact.grade,
|
||||
fact.trust,
|
||||
fact.basis,
|
||||
fact.calibration_status,
|
||||
extract(YEAR FROM fact.occurred_at AT TIME ZONE 'UTC')::integer AS observed_year
|
||||
FROM skill_evidence_facts AS fact
|
||||
INNER JOIN skill_evidence_skills AS skill
|
||||
ON fact.id = skill.fact_id
|
||||
WHERE
|
||||
fact.candidate_id = $1
|
||||
AND (skill.skill_code || '/' || fact.grade) = any($2::text [])
|
||||
AND fact.kind = 'measurement'
|
||||
AND fact.visibility = 'visible'
|
||||
ORDER BY skill.skill_code, fact.occurred_at, fact.id
|
||||
`
|
||||
|
||||
type ListCandidatePreviewEvidenceParams struct {
|
||||
CandidateID pgtype.UUID
|
||||
Categories []string
|
||||
}
|
||||
|
||||
type ListCandidatePreviewEvidenceRow struct {
|
||||
Skill string
|
||||
Grade string
|
||||
Trust int16
|
||||
Basis string
|
||||
CalibrationStatus string
|
||||
ObservedYear int32
|
||||
}
|
||||
|
||||
// The same selection for the candidate's own card preview, so the candidate
|
||||
// sees what an organization would read. It is scoped by the owner and runs
|
||||
// after the caller locked the effective C2 and publication; it does not apply
|
||||
// an organization or a cohort.
|
||||
func (q *Queries) ListCandidatePreviewEvidence(ctx context.Context, arg ListCandidatePreviewEvidenceParams) ([]ListCandidatePreviewEvidenceRow, error) {
|
||||
rows, err := q.db.Query(ctx, listCandidatePreviewEvidence, arg.CandidateID, arg.Categories)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []ListCandidatePreviewEvidenceRow
|
||||
for rows.Next() {
|
||||
var i ListCandidatePreviewEvidenceRow
|
||||
if err := rows.Scan(
|
||||
&i.Skill,
|
||||
&i.Grade,
|
||||
&i.Trust,
|
||||
&i.Basis,
|
||||
&i.CalibrationStatus,
|
||||
&i.ObservedYear,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listOrganizationVisibleEvidence = `-- name: ListOrganizationVisibleEvidence :many
|
||||
SELECT DISTINCT ON (skill.skill_code)
|
||||
skill.skill_code AS skill,
|
||||
fact.grade,
|
||||
fact.trust,
|
||||
fact.basis,
|
||||
fact.calibration_status,
|
||||
extract(YEAR FROM fact.occurred_at AT TIME ZONE 'UTC')::integer AS observed_year
|
||||
FROM candidate_effective_publications AS effective
|
||||
INNER JOIN skill_evidence_facts AS fact
|
||||
ON effective.user_id = fact.candidate_id
|
||||
INNER JOIN skill_evidence_skills AS skill
|
||||
ON fact.id = skill.fact_id
|
||||
WHERE
|
||||
effective.user_id = $1
|
||||
AND 'categories' = any(effective.fields)
|
||||
AND (skill.skill_code || '/' || fact.grade) = any($2::text [])
|
||||
AND fact.kind = 'measurement'
|
||||
AND fact.visibility = 'visible'
|
||||
AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM candidate_hidden_organizations AS hidden
|
||||
WHERE
|
||||
hidden.user_id = effective.user_id
|
||||
AND hidden.organization_id = $3
|
||||
)
|
||||
ORDER BY skill.skill_code, fact.occurred_at, fact.id
|
||||
`
|
||||
|
||||
type ListOrganizationVisibleEvidenceParams struct {
|
||||
CandidateID pgtype.UUID
|
||||
Categories []string
|
||||
OrganizationID pgtype.UUID
|
||||
}
|
||||
|
||||
type ListOrganizationVisibleEvidenceRow struct {
|
||||
Skill string
|
||||
Grade string
|
||||
Trust int16
|
||||
Basis string
|
||||
CalibrationStatus string
|
||||
ObservedYear int32
|
||||
}
|
||||
|
||||
// The evidence that one organization may read about one candidate: one fact
|
||||
// for each category of the card, the fact that supports the confirmed grade
|
||||
// of that category (the earliest one that passed exactly that grade, so a
|
||||
// lower grade or a retake adds nothing). The statement selects from the
|
||||
// effective publication view (published and backed by an unrevoked C2) and
|
||||
// excludes the candidates that hide the reading organization, so no row means
|
||||
// nothing to read, whatever the reason. The card must publish the categories
|
||||
// field and only visible measurements qualify. The categories come from the
|
||||
// caller as "specialization/grade" pairs taken from the card that was just
|
||||
// projected, so the answer never names a skill the card does not show. The columns are
|
||||
// an allowlist: no identifier of the fact, the event, the result, or the
|
||||
// candidate leaves, the instant is cut to the year, and the basis and the
|
||||
// calibration (the same for every candidate) say that the fact is a synthetic
|
||||
// demonstration.
|
||||
func (q *Queries) ListOrganizationVisibleEvidence(ctx context.Context, arg ListOrganizationVisibleEvidenceParams) ([]ListOrganizationVisibleEvidenceRow, error) {
|
||||
rows, err := q.db.Query(ctx, listOrganizationVisibleEvidence, arg.CandidateID, arg.Categories, arg.OrganizationID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []ListOrganizationVisibleEvidenceRow
|
||||
for rows.Next() {
|
||||
var i ListOrganizationVisibleEvidenceRow
|
||||
if err := rows.Scan(
|
||||
&i.Skill,
|
||||
&i.Grade,
|
||||
&i.Trust,
|
||||
&i.Basis,
|
||||
&i.CalibrationStatus,
|
||||
&i.ObservedYear,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
@@ -729,6 +729,29 @@ type Session struct {
|
||||
RevokedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type SkillEvidenceFact struct {
|
||||
ID pgtype.UUID
|
||||
CandidateID pgtype.UUID
|
||||
Kind string
|
||||
SourceType string
|
||||
EventID pgtype.UUID
|
||||
ResultID pgtype.UUID
|
||||
Attribution string
|
||||
Trust int16
|
||||
Grade string
|
||||
Basis string
|
||||
CalibrationStatus string
|
||||
OccurredAt pgtype.Timestamptz
|
||||
Visibility string
|
||||
RecordedAt pgtype.Timestamptz
|
||||
CreatedTxid int64
|
||||
}
|
||||
|
||||
type SkillEvidenceSkill struct {
|
||||
FactID pgtype.UUID
|
||||
SkillCode string
|
||||
}
|
||||
|
||||
type SupportCase struct {
|
||||
ID pgtype.UUID
|
||||
CaseNumber string
|
||||
|
||||
@@ -550,11 +550,23 @@ type Querier interface {
|
||||
// read adapter resolves an organization name only through this recorded
|
||||
// access relation, which is already visible to the candidate.
|
||||
ListCandidateCardAccessEvents(ctx context.Context, arg ListCandidateCardAccessEventsParams) ([]ListCandidateCardAccessEventsRow, error)
|
||||
// Skill evidence reads. The projection tables hold no answer, score, item,
|
||||
// failure, or anti-cheat data, and none of these statements names the result,
|
||||
// attempt, or review tables: evidence is read from its own facts only.
|
||||
// The candidate's own facts, hidden ones included, newest event first. Every
|
||||
// statement is scoped by the owner; the caller passes the continuation
|
||||
// position of the previous page, if any, and fetches one extra row.
|
||||
ListCandidateEvidenceFacts(ctx context.Context, arg ListCandidateEvidenceFactsParams) ([]ListCandidateEvidenceFactsRow, error)
|
||||
// One page of the candidate's hidden organizations, newest first with the
|
||||
// organization identifier as the tie-breaker. The page continues after the
|
||||
// (hidden_at, organization_id) position of the last record of the previous
|
||||
// page.
|
||||
ListCandidateHiddenOrganizations(ctx context.Context, arg ListCandidateHiddenOrganizationsParams) ([]ListCandidateHiddenOrganizationsRow, error)
|
||||
// The same selection for the candidate's own card preview, so the candidate
|
||||
// sees what an organization would read. It is scoped by the owner and runs
|
||||
// after the caller locked the effective C2 and publication; it does not apply
|
||||
// an organization or a cohort.
|
||||
ListCandidatePreviewEvidence(ctx context.Context, arg ListCandidatePreviewEvidenceParams) ([]ListCandidatePreviewEvidenceRow, error)
|
||||
// One page of the candidate's settings history, newest first with the event
|
||||
// identifier as the tie-breaker. The organization name is resolved here, at
|
||||
// read time, and is the current name. The page continues after the
|
||||
@@ -588,6 +600,21 @@ type Querier interface {
|
||||
// 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)
|
||||
// The evidence that one organization may read about one candidate: one fact
|
||||
// for each category of the card, the fact that supports the confirmed grade
|
||||
// of that category (the earliest one that passed exactly that grade, so a
|
||||
// lower grade or a retake adds nothing). The statement selects from the
|
||||
// effective publication view (published and backed by an unrevoked C2) and
|
||||
// excludes the candidates that hide the reading organization, so no row means
|
||||
// nothing to read, whatever the reason. The card must publish the categories
|
||||
// field and only visible measurements qualify. The categories come from the
|
||||
// caller as "specialization/grade" pairs taken from the card that was just
|
||||
// projected, so the answer never names a skill the card does not show. The columns are
|
||||
// an allowlist: no identifier of the fact, the event, the result, or the
|
||||
// candidate leaves, the instant is cut to the year, and the basis and the
|
||||
// calibration (the same for every candidate) say that the fact is a synthetic
|
||||
// demonstration.
|
||||
ListOrganizationVisibleEvidence(ctx context.Context, arg ListOrganizationVisibleEvidenceParams) ([]ListOrganizationVisibleEvidenceRow, error)
|
||||
// Lists the organizations where an account has an active membership,
|
||||
// newest membership first. The page continues after the (membership
|
||||
// creation time, organization ID) position of the last item of the
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package bootstrap
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
|
||||
"lincodex/backend/config"
|
||||
v1 "lincodex/backend/internal/adapter/primary/http/v1"
|
||||
"lincodex/backend/internal/adapter/secondary/postgres"
|
||||
"lincodex/backend/internal/usecase/evidence"
|
||||
"lincodex/backend/internal/usecase/identity"
|
||||
)
|
||||
|
||||
const evidencePoolMaxConns = 4
|
||||
|
||||
func newEvidenceHandler(
|
||||
ctx context.Context,
|
||||
settings config.Config,
|
||||
logger *slog.Logger,
|
||||
keyring *identity.Keyring,
|
||||
) (*v1.EvidenceHandler, func(), error) {
|
||||
if settings.DatabaseURL == "" {
|
||||
logger.Warn("evidence operations are not served because DATABASE_URL is not set")
|
||||
return nil, func() {}, nil
|
||||
}
|
||||
key, err := keyring.CandidateViewPseudonymKey()
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("bootstrap.newEvidenceHandler - derive projection key: %w", err)
|
||||
}
|
||||
pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, evidencePoolMaxConns)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("bootstrap.newEvidenceHandler - create pool: %w", err)
|
||||
}
|
||||
transactor := postgres.NewTransactor(pool)
|
||||
views, err := newCandidateViewService(pool, transactor, key)
|
||||
if err != nil {
|
||||
pool.Close()
|
||||
return nil, nil, fmt.Errorf("bootstrap.newEvidenceHandler - create view service: %w", err)
|
||||
}
|
||||
service, err := evidence.NewService(evidence.Dependencies{
|
||||
Transactor: transactor, AuthorizeCategories: views.AuthorizeCategoriesSection,
|
||||
})
|
||||
if err != nil {
|
||||
pool.Close()
|
||||
return nil, nil, fmt.Errorf("bootstrap.newEvidenceHandler - create service: %w", err)
|
||||
}
|
||||
return v1.NewEvidenceHandler(service), pool.Close, nil
|
||||
}
|
||||
@@ -45,6 +45,7 @@ func newAPIHandler(
|
||||
assessmentHandler *v1.AssessmentHandler,
|
||||
assessmentSignalHandler *v1.AssessmentSignalHandler,
|
||||
privacyHandler *v1.PrivacyHandler,
|
||||
evidenceHandler *v1.EvidenceHandler,
|
||||
) *v1.Handler {
|
||||
return v1.NewHandler(health, problems,
|
||||
v1.WithIdentity(identityHandler),
|
||||
@@ -58,6 +59,7 @@ func newAPIHandler(
|
||||
v1.WithAssessment(assessmentHandler),
|
||||
v1.WithAssessmentSignals(assessmentSignalHandler),
|
||||
v1.WithPrivacy(privacyHandler),
|
||||
v1.WithEvidence(evidenceHandler),
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"lincodex/backend/config"
|
||||
v1 "lincodex/backend/internal/adapter/primary/http/v1"
|
||||
@@ -41,14 +42,7 @@ func newPrivacyHandler(
|
||||
return nil, nil, fmt.Errorf("bootstrap.newPrivacyHandler - create pool: %w", err)
|
||||
}
|
||||
transactor := postgres.NewTransactor(pool)
|
||||
projector := anonymousprofile.NewService(postgres.NewPrivacyCohortStore(pool), key, time.Now)
|
||||
quota := companyquota.NewService(time.Now)
|
||||
views, err := candidateview.NewService(candidateview.Dependencies{
|
||||
Transactor: transactor, Projector: projector, PseudonymKey: key, Clock: time.Now,
|
||||
Quota: func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, candidateID uuid.UUID) (outbound.CompanyQuotaDecision, error) {
|
||||
return quota.ReserveCardView(ctx, unit, organization, candidateID)
|
||||
},
|
||||
})
|
||||
views, err := newCandidateViewService(pool, transactor, key)
|
||||
if err != nil {
|
||||
pool.Close()
|
||||
return nil, nil, fmt.Errorf("bootstrap.newPrivacyHandler - create view service: %w", err)
|
||||
@@ -60,3 +54,21 @@ func newPrivacyHandler(
|
||||
}
|
||||
return v1.NewPrivacyHandler(views, privacy, settings.AppPublicURL), pool.Close, nil
|
||||
}
|
||||
|
||||
// newCandidateViewService builds the organization card checks on the given
|
||||
// pool. The privacy handler and the evidence handler each own a pool and a
|
||||
// service, so their connection use stays separate.
|
||||
func newCandidateViewService(
|
||||
pool *pgxpool.Pool,
|
||||
transactor *postgres.Transactor,
|
||||
key domain.CandidateViewPseudonymKey,
|
||||
) (*candidateview.Service, error) {
|
||||
projector := anonymousprofile.NewService(postgres.NewPrivacyCohortStore(pool), key, time.Now)
|
||||
quota := companyquota.NewService(time.Now)
|
||||
return candidateview.NewService(candidateview.Dependencies{
|
||||
Transactor: transactor, Projector: projector, PseudonymKey: key, Clock: time.Now,
|
||||
Quota: func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, candidateID uuid.UUID) (outbound.CompanyQuotaDecision, error) {
|
||||
return quota.ReserveCardView(ctx, unit, organization, candidateID)
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -57,6 +57,7 @@ func initialize(
|
||||
newAssessmentHandler,
|
||||
newAssessmentSignalHandler,
|
||||
newPrivacyHandler,
|
||||
newEvidenceHandler,
|
||||
newSessionSecurity,
|
||||
newRouter,
|
||||
newOutboxRelay,
|
||||
|
||||
@@ -184,46 +184,28 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
handler := newAPIHandler(healthHandler, responder, identityHandler, consentHandler, profileHandler, questionnaireHandler, catalogHandler, organizationHandler, needHandler, supportHandler, assessmentHandler, assessmentSignalHandler, privacyHandler)
|
||||
evidenceHandler, cleanup15, err := newEvidenceHandler(ctx, config2, logger, keyring)
|
||||
if err != nil {
|
||||
cleanup14()
|
||||
cleanup13()
|
||||
cleanup12()
|
||||
cleanup11()
|
||||
cleanup10()
|
||||
cleanup9()
|
||||
cleanup8()
|
||||
cleanup7()
|
||||
cleanup6()
|
||||
cleanup5()
|
||||
cleanup4()
|
||||
cleanup3()
|
||||
cleanup2()
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
handler := newAPIHandler(healthHandler, responder, identityHandler, consentHandler, profileHandler, questionnaireHandler, catalogHandler, organizationHandler, needHandler, supportHandler, assessmentHandler, assessmentSignalHandler, privacyHandler, evidenceHandler)
|
||||
sessionSecurity := newSessionSecurity(identityHandler)
|
||||
v := newTrustedProxies(config2)
|
||||
httpHandler, err := newRouter(healthHandler, handler, sessionSecurity, responder, metrics, logger, v, organizationHandler)
|
||||
if err != nil {
|
||||
cleanup14()
|
||||
cleanup13()
|
||||
cleanup12()
|
||||
cleanup11()
|
||||
cleanup10()
|
||||
cleanup9()
|
||||
cleanup8()
|
||||
cleanup7()
|
||||
cleanup6()
|
||||
cleanup5()
|
||||
cleanup4()
|
||||
cleanup3()
|
||||
cleanup2()
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
relay, cleanup15, err := newOutboxRelay(ctx, config2, logger, metrics)
|
||||
if err != nil {
|
||||
cleanup14()
|
||||
cleanup13()
|
||||
cleanup12()
|
||||
cleanup11()
|
||||
cleanup10()
|
||||
cleanup9()
|
||||
cleanup8()
|
||||
cleanup7()
|
||||
cleanup6()
|
||||
cleanup5()
|
||||
cleanup4()
|
||||
cleanup3()
|
||||
cleanup2()
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
bootstrapEventConsumers, cleanup16, err := newEventConsumers(ctx, config2, logger, metrics)
|
||||
if err != nil {
|
||||
cleanup15()
|
||||
cleanup14()
|
||||
@@ -242,7 +224,26 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
worker, cleanup17, err := newJobWorker(ctx, config2, logger, metrics)
|
||||
relay, cleanup16, err := newOutboxRelay(ctx, config2, logger, metrics)
|
||||
if err != nil {
|
||||
cleanup15()
|
||||
cleanup14()
|
||||
cleanup13()
|
||||
cleanup12()
|
||||
cleanup11()
|
||||
cleanup10()
|
||||
cleanup9()
|
||||
cleanup8()
|
||||
cleanup7()
|
||||
cleanup6()
|
||||
cleanup5()
|
||||
cleanup4()
|
||||
cleanup3()
|
||||
cleanup2()
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
bootstrapEventConsumers, cleanup17, err := newEventConsumers(ctx, config2, logger, metrics)
|
||||
if err != nil {
|
||||
cleanup16()
|
||||
cleanup15()
|
||||
@@ -262,7 +263,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
mailsenderWorker, cleanup18, err := newMailSenderWorker(ctx, config2, logger, metrics, mailSender)
|
||||
worker, cleanup18, err := newJobWorker(ctx, config2, logger, metrics)
|
||||
if err != nil {
|
||||
cleanup17()
|
||||
cleanup16()
|
||||
@@ -283,7 +284,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
sampler, cleanup19, err := newDeliveryMetrics(ctx, config2, logger, metrics)
|
||||
mailsenderWorker, cleanup19, err := newMailSenderWorker(ctx, config2, logger, metrics, mailSender)
|
||||
if err != nil {
|
||||
cleanup18()
|
||||
cleanup17()
|
||||
@@ -305,8 +306,32 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
sampler, cleanup20, err := newDeliveryMetrics(ctx, config2, logger, metrics)
|
||||
if err != nil {
|
||||
cleanup19()
|
||||
cleanup18()
|
||||
cleanup17()
|
||||
cleanup16()
|
||||
cleanup15()
|
||||
cleanup14()
|
||||
cleanup13()
|
||||
cleanup12()
|
||||
cleanup11()
|
||||
cleanup10()
|
||||
cleanup9()
|
||||
cleanup8()
|
||||
cleanup7()
|
||||
cleanup6()
|
||||
cleanup5()
|
||||
cleanup4()
|
||||
cleanup3()
|
||||
cleanup2()
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
application := NewApplication(config2, httpHandler, metrics, logger, mailSender, relay, bootstrapEventConsumers, worker, mailsenderWorker, sampler)
|
||||
return application, func() {
|
||||
cleanup20()
|
||||
cleanup19()
|
||||
cleanup18()
|
||||
cleanup17()
|
||||
|
||||
@@ -0,0 +1,275 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// ErrInvalidEvidence reports a skill evidence value that breaks a rule of the
|
||||
// evidence model.
|
||||
var ErrInvalidEvidence = errors.New("invalid skill evidence")
|
||||
|
||||
// EvidenceKind separates what a person stated from what a system observed. A
|
||||
// claim never becomes a measurement by repetition.
|
||||
type EvidenceKind string
|
||||
|
||||
const (
|
||||
EvidenceKindClaim EvidenceKind = "claim"
|
||||
EvidenceKindMeasurement EvidenceKind = "measurement"
|
||||
)
|
||||
|
||||
// EvidenceSourceType names where a fact comes from.
|
||||
type EvidenceSourceType string
|
||||
|
||||
// EvidenceSourceAssessmentResult is a real (root or corrective) assessment
|
||||
// result that confirmed a grade. An express training run is never a source.
|
||||
const EvidenceSourceAssessmentResult EvidenceSourceType = "assessment_result"
|
||||
|
||||
// EvidenceAttribution says whose contribution a fact is.
|
||||
type EvidenceAttribution string
|
||||
|
||||
const (
|
||||
EvidenceAttributionPersonal EvidenceAttribution = "personal"
|
||||
EvidenceAttributionTeamRole EvidenceAttribution = "team_role"
|
||||
EvidenceAttributionTeamUnattributed EvidenceAttribution = "team_unattributed"
|
||||
)
|
||||
|
||||
// EvidenceTrust is the strength of a confirmation: 0 stated, 1 an observable
|
||||
// online result without a reliable confirmation of the identity or the
|
||||
// authorship, 2 tied to a confirmed identity or an independent party, 3 an
|
||||
// in-person check.
|
||||
type EvidenceTrust uint8
|
||||
|
||||
const (
|
||||
EvidenceTrustStated EvidenceTrust = 0
|
||||
// EvidenceTrustOnlineUnconfirmed is the level of an online assessment: it
|
||||
// is unproctored and nothing confirms who answered. The database function
|
||||
// that projects a result writes this value, and a test keeps the two equal.
|
||||
EvidenceTrustOnlineUnconfirmed EvidenceTrust = 1
|
||||
EvidenceTrustIdentityTied EvidenceTrust = 2
|
||||
EvidenceTrustInPerson EvidenceTrust = 3
|
||||
)
|
||||
|
||||
// EvidenceVisibility says whether a fact may take part in what an
|
||||
// organization reads. It never publishes a fact by itself.
|
||||
type EvidenceVisibility string
|
||||
|
||||
const (
|
||||
EvidenceVisibilityVisible EvidenceVisibility = "visible"
|
||||
EvidenceVisibilityHidden EvidenceVisibility = "hidden"
|
||||
)
|
||||
|
||||
// EvidenceSkillCode is a skill tag from a closed set: the specialization codes
|
||||
// of the catalog and the technology codes of the anonymous card.
|
||||
type EvidenceSkillCode string
|
||||
|
||||
// EvidenceSkillOfSpecialization tags a fact with the specialization of a
|
||||
// category.
|
||||
func EvidenceSkillOfSpecialization(code SpecializationCode) EvidenceSkillCode {
|
||||
return EvidenceSkillCode(code)
|
||||
}
|
||||
|
||||
// IsKnown reports whether code belongs to the closed skill set.
|
||||
func (code EvidenceSkillCode) IsKnown() bool {
|
||||
return SpecializationCode(code).IsKnown() || CandidateViewSkillCode(code).IsKnown()
|
||||
}
|
||||
|
||||
// EvidenceSkillCodes returns the closed skill set in its stored order.
|
||||
func EvidenceSkillCodes() []EvidenceSkillCode {
|
||||
codes := make([]EvidenceSkillCode, 0, len(specializationCodes)+len(candidateViewSkillCodes))
|
||||
for _, code := range specializationCodes {
|
||||
codes = append(codes, EvidenceSkillCode(code))
|
||||
}
|
||||
for _, code := range candidateViewSkillCodes {
|
||||
codes = append(codes, EvidenceSkillCode(code))
|
||||
}
|
||||
return codes
|
||||
}
|
||||
|
||||
// EvidenceResult is what a fact says: the grade that was passed, the basis of
|
||||
// the measurement, and its calibration. It carries no score, answer, item,
|
||||
// failure, or anti-cheat data.
|
||||
type EvidenceResult struct {
|
||||
Grade GradeCode
|
||||
Basis AssessmentCategorySource
|
||||
CalibrationStatus AssessmentCategoryCalibrationStatus
|
||||
}
|
||||
|
||||
// EvidenceFactSnapshot is the stored shape of one fact of a candidate.
|
||||
type EvidenceFactSnapshot struct {
|
||||
ID uuid.UUID
|
||||
CandidateID uuid.UUID
|
||||
Kind EvidenceKind
|
||||
SourceType EvidenceSourceType
|
||||
// EventID is the source event and ResultID its immutable result. For an
|
||||
// assessment both are the attempt.
|
||||
EventID uuid.UUID
|
||||
ResultID uuid.UUID
|
||||
Skills []EvidenceSkillCode
|
||||
Result EvidenceResult
|
||||
Attribution EvidenceAttribution
|
||||
Trust EvidenceTrust
|
||||
OccurredAt time.Time
|
||||
Visibility EvidenceVisibility
|
||||
}
|
||||
|
||||
// EvidenceFact is one independent fact: one source event. The skills of the
|
||||
// event are tags of the fact, so adding a tag never adds a fact.
|
||||
type EvidenceFact struct {
|
||||
snapshot EvidenceFactSnapshot
|
||||
}
|
||||
|
||||
// RestoreEvidenceFact validates a stored fact against the rules of the model:
|
||||
// the trust level fits the kind, an assessment fact is a personal measurement
|
||||
// below the in-person level, and the skills are known, distinct, and ordered.
|
||||
func RestoreEvidenceFact(snapshot EvidenceFactSnapshot) (EvidenceFact, error) {
|
||||
const location = "domain.RestoreEvidenceFact"
|
||||
if snapshot.ID == uuid.Nil || snapshot.CandidateID == uuid.Nil || snapshot.EventID == uuid.Nil ||
|
||||
snapshot.ResultID == uuid.Nil || snapshot.OccurredAt.IsZero() {
|
||||
return EvidenceFact{}, fmt.Errorf("%s - identities and time are required: %w", location, ErrInvalidEvidence)
|
||||
}
|
||||
if !snapshot.Kind.valid() || !snapshot.Attribution.valid() || !snapshot.Visibility.valid() ||
|
||||
!validEvidenceTrustForKind(snapshot.Kind, snapshot.Trust) {
|
||||
return EvidenceFact{}, fmt.Errorf("%s - kind, trust, attribution, or visibility is invalid: %w", location, ErrInvalidEvidence)
|
||||
}
|
||||
if !isOnlineAssessmentEvidence(snapshot) {
|
||||
return EvidenceFact{}, fmt.Errorf("%s - an assessment fact is a personal online measurement of its own attempt: %w", location, ErrInvalidEvidence)
|
||||
}
|
||||
if err := validateEvidenceResult(snapshot.Result); err != nil {
|
||||
return EvidenceFact{}, fmt.Errorf("%s - result: %w", location, err)
|
||||
}
|
||||
skills, err := canonicalEvidenceSkills(snapshot.Skills)
|
||||
if err != nil {
|
||||
return EvidenceFact{}, fmt.Errorf("%s - skills: %w", location, err)
|
||||
}
|
||||
snapshot.Skills = skills
|
||||
snapshot.OccurredAt = snapshot.OccurredAt.UTC().Truncate(time.Microsecond)
|
||||
return EvidenceFact{snapshot: snapshot}, nil
|
||||
}
|
||||
|
||||
// isOnlineAssessmentEvidence reports whether a fact has the shape of the only
|
||||
// source that exists: a personal measurement of an assessment attempt that is
|
||||
// below the in-person level.
|
||||
func isOnlineAssessmentEvidence(snapshot EvidenceFactSnapshot) bool {
|
||||
return snapshot.SourceType == EvidenceSourceAssessmentResult && snapshot.Kind == EvidenceKindMeasurement &&
|
||||
snapshot.Attribution == EvidenceAttributionPersonal && snapshot.EventID == snapshot.ResultID &&
|
||||
snapshot.Trust <= EvidenceTrustIdentityTied
|
||||
}
|
||||
|
||||
// Snapshot returns a copy of the stored shape.
|
||||
func (fact EvidenceFact) Snapshot() EvidenceFactSnapshot {
|
||||
snapshot := fact.snapshot
|
||||
snapshot.Skills = slices.Clone(snapshot.Skills)
|
||||
return snapshot
|
||||
}
|
||||
|
||||
// IsZero reports whether the fact is the zero value.
|
||||
func (fact EvidenceFact) IsZero() bool { return fact.snapshot.ID == uuid.Nil }
|
||||
|
||||
// Bounds of the year that an organization reads, so a stored value outside a
|
||||
// sane range is refused instead of shown.
|
||||
const (
|
||||
minEvidenceObservedYear = 2000
|
||||
maxEvidenceObservedYear = 9999
|
||||
)
|
||||
|
||||
// EvidenceOrganizationFactInput is the allowlisted shape of the one fact that
|
||||
// supports a category of the card: the skill, the grade that was passed, the
|
||||
// trust level, the year of the event, and the basis and calibration of the
|
||||
// method, which are the same for every candidate. It has no identifier, no
|
||||
// exact time, and no source detail.
|
||||
type EvidenceOrganizationFactInput struct {
|
||||
Skill EvidenceSkillCode
|
||||
Grade GradeCode
|
||||
Trust EvidenceTrust
|
||||
Basis AssessmentCategorySource
|
||||
CalibrationStatus AssessmentCategoryCalibrationStatus
|
||||
ObservedYear int32
|
||||
}
|
||||
|
||||
// EvidenceOrganizationFact is one fact in the organization projection.
|
||||
type EvidenceOrganizationFact struct {
|
||||
input EvidenceOrganizationFactInput
|
||||
}
|
||||
|
||||
// NewEvidenceOrganizationFact validates the allowlisted organization shape. The
|
||||
// fact is always a measurement, so its trust is at least 1.
|
||||
func NewEvidenceOrganizationFact(input EvidenceOrganizationFactInput) (EvidenceOrganizationFact, error) {
|
||||
const location = "domain.NewEvidenceOrganizationFact"
|
||||
if !input.Skill.IsKnown() || !input.Grade.IsKnown() ||
|
||||
!validEvidenceTrustForKind(EvidenceKindMeasurement, input.Trust) {
|
||||
return EvidenceOrganizationFact{}, fmt.Errorf("%s - skill, grade, or trust is invalid: %w", location, ErrInvalidEvidence)
|
||||
}
|
||||
if err := validateEvidenceResult(EvidenceResult{Grade: input.Grade, Basis: input.Basis, CalibrationStatus: input.CalibrationStatus}); err != nil {
|
||||
return EvidenceOrganizationFact{}, fmt.Errorf("%s - result: %w", location, err)
|
||||
}
|
||||
if input.ObservedYear < minEvidenceObservedYear || input.ObservedYear > maxEvidenceObservedYear {
|
||||
return EvidenceOrganizationFact{}, fmt.Errorf("%s - observed year is out of range: %w", location, ErrInvalidEvidence)
|
||||
}
|
||||
return EvidenceOrganizationFact{input: input}, nil
|
||||
}
|
||||
|
||||
// Input returns the allowlisted shape.
|
||||
func (fact EvidenceOrganizationFact) Input() EvidenceOrganizationFactInput { return fact.input }
|
||||
|
||||
func (kind EvidenceKind) valid() bool {
|
||||
return kind == EvidenceKindClaim || kind == EvidenceKindMeasurement
|
||||
}
|
||||
|
||||
func (attribution EvidenceAttribution) valid() bool {
|
||||
switch attribution {
|
||||
case EvidenceAttributionPersonal, EvidenceAttributionTeamRole, EvidenceAttributionTeamUnattributed:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (visibility EvidenceVisibility) valid() bool {
|
||||
return visibility == EvidenceVisibilityVisible || visibility == EvidenceVisibilityHidden
|
||||
}
|
||||
|
||||
// validEvidenceTrustForKind keeps a claim at level 0 and a measurement at
|
||||
// levels 1 to 3.
|
||||
func validEvidenceTrustForKind(kind EvidenceKind, trust EvidenceTrust) bool {
|
||||
switch kind {
|
||||
case EvidenceKindClaim:
|
||||
return trust == EvidenceTrustStated
|
||||
case EvidenceKindMeasurement:
|
||||
return trust >= EvidenceTrustOnlineUnconfirmed && trust <= EvidenceTrustInPerson
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func validateEvidenceResult(result EvidenceResult) error {
|
||||
if !result.Grade.IsKnown() || result.Basis != AssessmentCategorySourceSyntheticDemo ||
|
||||
result.CalibrationStatus != AssessmentCategoryCalibrationUncalibrated {
|
||||
return fmt.Errorf("grade, basis, or calibration is not known: %w", ErrInvalidEvidence)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// canonicalEvidenceSkills returns the skills sorted, after checking that there
|
||||
// is at least one, that each is known, and that none repeats.
|
||||
func canonicalEvidenceSkills(skills []EvidenceSkillCode) ([]EvidenceSkillCode, error) {
|
||||
if len(skills) == 0 || len(skills) > len(EvidenceSkillCodes()) {
|
||||
return nil, fmt.Errorf("a fact needs between one and every known skill: %w", ErrInvalidEvidence)
|
||||
}
|
||||
ordered := slices.Clone(skills)
|
||||
slices.SortFunc(ordered, func(left, right EvidenceSkillCode) int { return strings.Compare(string(left), string(right)) })
|
||||
for index, code := range ordered {
|
||||
if !code.IsKnown() {
|
||||
return nil, fmt.Errorf("skill %q is not known: %w", string(code), ErrInvalidEvidence)
|
||||
}
|
||||
if index > 0 && ordered[index-1] == code {
|
||||
return nil, fmt.Errorf("skill %q repeats: %w", string(code), ErrInvalidEvidence)
|
||||
}
|
||||
}
|
||||
return ordered, nil
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"slices"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func validEvidenceSnapshot() EvidenceFactSnapshot {
|
||||
attempt := uuid.New()
|
||||
return EvidenceFactSnapshot{
|
||||
ID: uuid.New(), CandidateID: uuid.New(), Kind: EvidenceKindMeasurement,
|
||||
SourceType: EvidenceSourceAssessmentResult, EventID: attempt, ResultID: attempt,
|
||||
Skills: []EvidenceSkillCode{"go", "backend"},
|
||||
Result: EvidenceResult{
|
||||
Grade: GradeJunior, Basis: AssessmentCategorySourceSyntheticDemo,
|
||||
CalibrationStatus: AssessmentCategoryCalibrationUncalibrated,
|
||||
},
|
||||
Attribution: EvidenceAttributionPersonal, Trust: EvidenceTrustOnlineUnconfirmed,
|
||||
OccurredAt: time.Date(2026, 10, 8, 10, 15, 0, 123456789, time.FixedZone("test", 3*60*60)),
|
||||
Visibility: EvidenceVisibilityVisible,
|
||||
}
|
||||
}
|
||||
|
||||
func TestRestoreEvidenceFactKeepsOneFactWithOrderedTags(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
snapshot := validEvidenceSnapshot()
|
||||
fact, err := RestoreEvidenceFact(snapshot)
|
||||
if err != nil {
|
||||
t.Fatalf("RestoreEvidenceFact() error = %v", err)
|
||||
}
|
||||
got := fact.Snapshot()
|
||||
if !slices.Equal(got.Skills, []EvidenceSkillCode{"backend", "go"}) {
|
||||
t.Fatalf("Skills = %v, want the tags of one event in ascending order", got.Skills)
|
||||
}
|
||||
if got.OccurredAt.Location() != time.UTC || got.OccurredAt.Nanosecond()%1000 != 0 {
|
||||
t.Fatalf("OccurredAt = %v, want UTC at microsecond precision", got.OccurredAt)
|
||||
}
|
||||
got.Skills[0] = "qa"
|
||||
if fact.Snapshot().Skills[0] != "backend" {
|
||||
t.Fatal("Snapshot() shares its skill slice with the fact")
|
||||
}
|
||||
if EvidenceTrustOnlineUnconfirmed != 1 {
|
||||
t.Fatalf("online trust = %d, want 1", EvidenceTrustOnlineUnconfirmed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRestoreEvidenceFactRejectsBrokenModelRules(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
cases := map[string]func(*EvidenceFactSnapshot){
|
||||
"claim above level 0": func(s *EvidenceFactSnapshot) { s.Kind = EvidenceKindClaim; s.Trust = EvidenceTrustOnlineUnconfirmed },
|
||||
"measurement at level 0": func(s *EvidenceFactSnapshot) { s.Trust = EvidenceTrustStated },
|
||||
"online result at the in-person level": func(s *EvidenceFactSnapshot) { s.Trust = EvidenceTrustInPerson },
|
||||
"assessment claim": func(s *EvidenceFactSnapshot) { s.Kind = EvidenceKindClaim; s.Trust = EvidenceTrustStated },
|
||||
"team attribution": func(s *EvidenceFactSnapshot) { s.Attribution = EvidenceAttributionTeamUnattributed },
|
||||
"event differs from result": func(s *EvidenceFactSnapshot) { s.ResultID = uuid.New() },
|
||||
"unknown source": func(s *EvidenceFactSnapshot) { s.SourceType = "demo_express" },
|
||||
"no skill": func(s *EvidenceFactSnapshot) { s.Skills = nil },
|
||||
"repeated tag": func(s *EvidenceFactSnapshot) { s.Skills = []EvidenceSkillCode{"go", "go"} },
|
||||
"unknown tag": func(s *EvidenceFactSnapshot) { s.Skills = []EvidenceSkillCode{"rate-limiting"} },
|
||||
"unknown grade": func(s *EvidenceFactSnapshot) { s.Result.Grade = "principal" },
|
||||
"calibration missing": func(s *EvidenceFactSnapshot) { s.Result.CalibrationStatus = "" },
|
||||
"unknown visibility": func(s *EvidenceFactSnapshot) { s.Visibility = "public" },
|
||||
"missing candidate": func(s *EvidenceFactSnapshot) { s.CandidateID = uuid.Nil },
|
||||
"missing time": func(s *EvidenceFactSnapshot) { s.OccurredAt = time.Time{} },
|
||||
}
|
||||
for name, mutate := range cases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
snapshot := validEvidenceSnapshot()
|
||||
mutate(&snapshot)
|
||||
if _, err := RestoreEvidenceFact(snapshot); !errors.Is(err, ErrInvalidEvidence) {
|
||||
t.Fatalf("RestoreEvidenceFact() error = %v, want ErrInvalidEvidence", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestEvidenceSkillCodesAreTheSpecializationsAndTheCardTechnologies(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
codes := EvidenceSkillCodes()
|
||||
if len(codes) != len(specializationCodes)+len(CandidateViewSkillCodes()) {
|
||||
t.Fatalf("EvidenceSkillCodes() has %d codes", len(codes))
|
||||
}
|
||||
for _, code := range codes {
|
||||
if !code.IsKnown() {
|
||||
t.Errorf("%q is listed but not known", code)
|
||||
}
|
||||
}
|
||||
if EvidenceSkillCode("rate-limiting").IsKnown() || EvidenceSkillCode("").IsKnown() {
|
||||
t.Fatal("a code outside the closed set is known")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewEvidenceOrganizationFactChecksTheAllowlistedShape(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
valid := EvidenceOrganizationFactInput{
|
||||
Skill: "backend", Grade: GradeJunior, Trust: EvidenceTrustOnlineUnconfirmed,
|
||||
Basis: AssessmentCategorySourceSyntheticDemo, CalibrationStatus: AssessmentCategoryCalibrationUncalibrated, ObservedYear: 2026,
|
||||
}
|
||||
fact, err := NewEvidenceOrganizationFact(valid)
|
||||
if err != nil || fact.Input() != valid {
|
||||
t.Fatalf("NewEvidenceOrganizationFact() = %+v, %v, want the input back", fact.Input(), err)
|
||||
}
|
||||
for name, mutate := range map[string]func(*EvidenceOrganizationFactInput){
|
||||
"year before the range": func(i *EvidenceOrganizationFactInput) { i.ObservedYear = 1999 },
|
||||
"year after the range": func(i *EvidenceOrganizationFactInput) { i.ObservedYear = 10000 },
|
||||
"no year": func(i *EvidenceOrganizationFactInput) { i.ObservedYear = 0 },
|
||||
"claim level": func(i *EvidenceOrganizationFactInput) { i.Trust = EvidenceTrustStated },
|
||||
"trust above in person": func(i *EvidenceOrganizationFactInput) { i.Trust = 4 },
|
||||
"unknown skill": func(i *EvidenceOrganizationFactInput) { i.Skill = "rate-limiting" },
|
||||
"no skill": func(i *EvidenceOrganizationFactInput) { i.Skill = "" },
|
||||
"unknown grade": func(i *EvidenceOrganizationFactInput) { i.Grade = "principal" },
|
||||
"no basis": func(i *EvidenceOrganizationFactInput) { i.Basis = "" },
|
||||
"no calibration": func(i *EvidenceOrganizationFactInput) { i.CalibrationStatus = "" },
|
||||
} {
|
||||
input := valid
|
||||
mutate(&input)
|
||||
if _, err := NewEvidenceOrganizationFact(input); !errors.Is(err, ErrInvalidEvidence) {
|
||||
t.Errorf("%s: error = %v, want ErrInvalidEvidence", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package outbound
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
)
|
||||
|
||||
// MaxEvidencePageSize bounds one page of the candidate's own facts.
|
||||
const MaxEvidencePageSize = 100
|
||||
|
||||
// EvidencePosition is the descending key of the candidate's fact list.
|
||||
type EvidencePosition struct {
|
||||
OccurredAt time.Time
|
||||
ID uuid.UUID
|
||||
}
|
||||
|
||||
// EvidenceListQuery selects one owner-scoped page of facts.
|
||||
type EvidenceListQuery struct {
|
||||
CandidateID uuid.UUID
|
||||
After *EvidencePosition
|
||||
Limit int32
|
||||
}
|
||||
|
||||
// EvidenceFactPage is one page of the candidate's facts, newest event first.
|
||||
type EvidenceFactPage struct {
|
||||
Items []domain.EvidenceFact
|
||||
HasMore bool
|
||||
}
|
||||
|
||||
// EvidencePositionOf creates the continuation key for a fact.
|
||||
func EvidencePositionOf(fact domain.EvidenceFact) EvidencePosition {
|
||||
snapshot := fact.Snapshot()
|
||||
return EvidencePosition{OccurredAt: snapshot.OccurredAt, ID: snapshot.ID}
|
||||
}
|
||||
|
||||
// EvidenceRepository reads the skill evidence projection. It never reads an
|
||||
// assessment result, answer, attempt, or review: the projection is the only
|
||||
// source, so no answer, failure, or anti-cheat datum can reach a caller.
|
||||
type EvidenceRepository interface {
|
||||
// ListCandidateFacts returns one page of the facts that belong to the
|
||||
// candidate, hidden ones included.
|
||||
ListCandidateFacts(ctx context.Context, query EvidenceListQuery) (EvidenceFactPage, error)
|
||||
|
||||
// ListOrganizationFacts returns the evidence that one organization may read
|
||||
// about one candidate: for each category of the card, the one fact that
|
||||
// supports its confirmed grade. The adapter must select from
|
||||
// candidate_effective_publications, exclude the candidates that hide the
|
||||
// organization in the same statement, require the published card to carry
|
||||
// the categories field, and return only visible measurements. The caller
|
||||
// has already authorized the active organization membership and passes the
|
||||
// categories that the card just projected.
|
||||
ListOrganizationFacts(
|
||||
ctx context.Context,
|
||||
organizationID, candidateID uuid.UUID,
|
||||
categories []domain.CandidateViewCategory,
|
||||
) ([]domain.EvidenceOrganizationFact, error)
|
||||
|
||||
// ListPreviewFacts returns the same selection for the candidate's own card
|
||||
// preview. It applies no organization and no cohort, and the caller has
|
||||
// locked the effective C2 and publication.
|
||||
ListPreviewFacts(
|
||||
ctx context.Context,
|
||||
candidateID uuid.UUID,
|
||||
categories []domain.CandidateViewCategory,
|
||||
) ([]domain.EvidenceOrganizationFact, error)
|
||||
}
|
||||
@@ -62,6 +62,7 @@ type UnitOfWork interface {
|
||||
PrivacyCohort() PrivacyCohortRepository
|
||||
PrivacyView() PrivacyViewRepository
|
||||
PrivacySettings() PrivacySettingsRepository
|
||||
Evidence() EvidenceRepository
|
||||
AccountDeletionRequests() AccountDeletionRequests
|
||||
ConsentRevocationEffects() ConsentRevocationEffects
|
||||
OrganizationRepositories
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
package candidateview
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"slices"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
// categoriesProjector projects the one test source with the given categories.
|
||||
type categoriesProjector struct {
|
||||
contactAccessProjector
|
||||
|
||||
categories []domain.CandidateViewCategory
|
||||
}
|
||||
|
||||
func (projector categoriesProjector) ProjectSources(organizationID uuid.UUID, sources []domain.CandidateViewSource) ([]domain.AnonymousCandidateViewDTO, error) {
|
||||
views, err := projector.contactAccessProjector.ProjectSources(organizationID, sources)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
views[0].Categories = projector.categories
|
||||
return views, nil
|
||||
}
|
||||
|
||||
type categoriesSectionFixture struct {
|
||||
service *Service
|
||||
contact *contactAccessFixture
|
||||
actorID uuid.UUID
|
||||
organizationID uuid.UUID
|
||||
handle string
|
||||
quotaCalls int
|
||||
}
|
||||
|
||||
func newCategoriesSectionFixture(t *testing.T, categories []domain.CandidateViewCategory, allowed bool, actorScenario domain.Scenario) *categoriesSectionFixture {
|
||||
t.Helper()
|
||||
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
|
||||
actorID, candidateID := uuid.New(), uuid.New()
|
||||
organization, membership := newContactAccessOrganization(t, actorID, now)
|
||||
actor := domain.User{ID: actorID, Scenario: actorScenario, EmailVerifiedAt: &now}
|
||||
candidate := domain.User{ID: candidateID, Scenario: domain.ScenarioCandidate, EmailVerifiedAt: &now}
|
||||
publication, err := domain.NewCardFieldSet([]domain.CardField{domain.CardFieldCategories})
|
||||
if err != nil {
|
||||
t.Fatalf("NewCardFieldSet() error = %v", err)
|
||||
}
|
||||
source, err := domain.NewCandidateViewSource(candidateID, publication, domain.CandidateViewProfile{}, nil, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewCandidateViewSource() error = %v", err)
|
||||
}
|
||||
key, err := domain.NewCandidateViewPseudonymKey(bytes.Repeat([]byte("section-view-key"), 2))
|
||||
if err != nil {
|
||||
t.Fatalf("NewCandidateViewPseudonymKey() error = %v", err)
|
||||
}
|
||||
handle, err := key.ForOrganization(organization.ID(), candidateID)
|
||||
if err != nil {
|
||||
t.Fatalf("ForOrganization() error = %v", err)
|
||||
}
|
||||
fixture := &categoriesSectionFixture{
|
||||
contact: &contactAccessFixture{}, actorID: actorID, organizationID: organization.ID(), handle: handle,
|
||||
}
|
||||
unit := contactAccessUnit{
|
||||
users: contactAccessUsers{users: map[uuid.UUID]domain.User{actorID: actor, candidateID: candidate}},
|
||||
organizations: contactAccessOrganizations{organization: organization, membership: membership},
|
||||
view: contactAccessViewRepository{fixture: fixture.contact, source: source},
|
||||
}
|
||||
fixture.service, err = NewService(Dependencies{
|
||||
Transactor: contactAccessTransactor{unit: unit},
|
||||
Projector: categoriesProjector{
|
||||
contactAccessProjector: contactAccessProjector{key: key, source: source}, categories: categories,
|
||||
},
|
||||
PseudonymKey: key,
|
||||
Quota: func(context.Context, outbound.UnitOfWork, domain.Organization, uuid.UUID) (outbound.CompanyQuotaDecision, error) {
|
||||
fixture.quotaCalls++
|
||||
return outbound.CompanyQuotaDecision{Allowed: allowed, RetryAt: now.Add(time.Minute)}, nil
|
||||
},
|
||||
Clock: func() time.Time { return now },
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewService() error = %v", err)
|
||||
}
|
||||
fixture.contact.audits = nil
|
||||
return fixture
|
||||
}
|
||||
|
||||
func (fixture *categoriesSectionFixture) authorize(t *testing.T, handle string) (uuid.UUID, []domain.CandidateViewCategory, error) {
|
||||
t.Helper()
|
||||
var candidateID uuid.UUID
|
||||
var categories []domain.CandidateViewCategory
|
||||
err := fixture.service.transactor.WithinTransaction(context.Background(), func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
var err error
|
||||
candidateID, categories, err = fixture.service.AuthorizeCategoriesSection(ctx, unit, fixture.actorID, fixture.organizationID, handle)
|
||||
return err
|
||||
})
|
||||
return candidateID, categories, err
|
||||
}
|
||||
|
||||
func TestAuthorizeCategoriesSectionNamesTheCategoriesOfTheCurrentCard(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
shown := []domain.CandidateViewCategory{
|
||||
{Specialization: domain.SpecializationBackend, Grade: domain.GradeJunior, Strength: domain.CandidateViewStrengthStandard},
|
||||
{Specialization: domain.SpecializationQA, Grade: domain.GradeIntern, Strength: domain.CandidateViewStrengthStandard},
|
||||
}
|
||||
fixture := newCategoriesSectionFixture(t, shown, true, domain.ScenarioEmployer)
|
||||
|
||||
candidateID, categories, err := fixture.authorize(t, fixture.handle)
|
||||
if err != nil {
|
||||
t.Fatalf("AuthorizeCategoriesSection() error = %v", err)
|
||||
}
|
||||
if candidateID == uuid.Nil || !slices.Equal(categories, shown) {
|
||||
t.Fatalf("section = %s %v, want the candidate and the categories of the card", candidateID, categories)
|
||||
}
|
||||
if fixture.quotaCalls != 1 || len(fixture.contact.audits) != 1 ||
|
||||
fixture.contact.audits[0].Kind() != domain.CandidateCardAccessCardViewed ||
|
||||
!slices.Equal(fixture.contact.audits[0].FieldCodes(), []string{"categories"}) {
|
||||
t.Fatalf("quota calls = %d, audits = %v, want one view of the categories field", fixture.quotaCalls, fixture.contact.audits)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthorizeCategoriesSectionRefusesWithoutLeavingATrace(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
categories := []domain.CandidateViewCategory{{Specialization: domain.SpecializationBackend, Grade: domain.GradeJunior, Strength: domain.CandidateViewStrengthStandard}}
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
categories []domain.CandidateViewCategory
|
||||
allowed bool
|
||||
scenario domain.Scenario
|
||||
handle func(*categoriesSectionFixture) string
|
||||
want error
|
||||
wantQuota int
|
||||
}{
|
||||
{name: "a card without categories", allowed: true, scenario: domain.ScenarioEmployer, want: ErrCandidateCardNotFound},
|
||||
{name: "an exhausted quota", categories: categories, scenario: domain.ScenarioEmployer, want: ErrCandidateViewQuotaExceeded, wantQuota: 1},
|
||||
{name: "a candidate account", categories: categories, allowed: true, scenario: domain.ScenarioCandidate, want: ErrForbidden},
|
||||
{
|
||||
name: "a handle of another organization", categories: categories, allowed: true, scenario: domain.ScenarioEmployer,
|
||||
handle: func(*categoriesSectionFixture) string { return "cv1_" + string(bytes.Repeat([]byte("A"), 43)) },
|
||||
want: ErrCandidateCardNotFound,
|
||||
},
|
||||
{
|
||||
name: "a malformed handle", categories: categories, allowed: true, scenario: domain.ScenarioEmployer,
|
||||
handle: func(*categoriesSectionFixture) string { return "candidate" }, want: ErrInvalidCandidateHandle,
|
||||
},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
fixture := newCategoriesSectionFixture(t, test.categories, test.allowed, test.scenario)
|
||||
handle := fixture.handle
|
||||
if test.handle != nil {
|
||||
handle = test.handle(fixture)
|
||||
}
|
||||
_, _, err := fixture.authorize(t, handle)
|
||||
if !errors.Is(err, test.want) {
|
||||
t.Fatalf("AuthorizeCategoriesSection() error = %v, want %v", err, test.want)
|
||||
}
|
||||
if len(fixture.contact.audits) != 0 || fixture.quotaCalls != test.wantQuota {
|
||||
t.Fatalf("audits = %v, quota calls = %d, want no audit and %d quota calls", fixture.contact.audits, fixture.quotaCalls, test.wantQuota)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
@@ -114,23 +115,90 @@ func (service *Service) getOrganizationCardInTransaction(
|
||||
if err != nil {
|
||||
return domain.AnonymousCandidateViewDTO{}, err
|
||||
}
|
||||
decision, err := service.quota(ctx, unit, organization, candidateID)
|
||||
err = service.reserveCardView(ctx, unit, repository, organization, candidateID, location, func(at time.Time) (domain.CandidateCardAccess, error) {
|
||||
return cardViewAccessEvent(candidateID, organizationID, actorID, view, at)
|
||||
})
|
||||
if err != nil {
|
||||
return domain.AnonymousCandidateViewDTO{}, fmt.Errorf("%s - reserve card view: %w", location, err)
|
||||
}
|
||||
if !decision.Allowed {
|
||||
return domain.AnonymousCandidateViewDTO{}, &RateLimitedError{RetryAt: decision.RetryAt.UTC()}
|
||||
}
|
||||
event, err := cardViewAccessEvent(candidateID, organizationID, actorID, view, service.clock())
|
||||
if err != nil {
|
||||
return domain.AnonymousCandidateViewDTO{}, fmt.Errorf("%s - build access audit: %w", location, err)
|
||||
}
|
||||
if err := repository.RecordCandidateCardAccess(ctx, event); err != nil {
|
||||
return domain.AnonymousCandidateViewDTO{}, fmt.Errorf("%s - record access audit: %w", location, err)
|
||||
return domain.AnonymousCandidateViewDTO{}, err
|
||||
}
|
||||
return view, nil
|
||||
}
|
||||
|
||||
// reserveCardView consumes the card-view quota and appends the access audit
|
||||
// that auditFor builds. Both commit with the visibility checks that the
|
||||
// caller ran in the same transaction, so a failed read leaves neither behind.
|
||||
func (service *Service) reserveCardView(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
repository outbound.PrivacyViewRepository,
|
||||
organization domain.Organization,
|
||||
candidateID uuid.UUID,
|
||||
location string,
|
||||
auditFor func(at time.Time) (domain.CandidateCardAccess, error),
|
||||
) error {
|
||||
decision, err := service.quota(ctx, unit, organization, candidateID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - reserve card view: %w", location, err)
|
||||
}
|
||||
if !decision.Allowed {
|
||||
return &RateLimitedError{RetryAt: decision.RetryAt.UTC()}
|
||||
}
|
||||
event, err := auditFor(service.clock())
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - build access audit: %w", location, err)
|
||||
}
|
||||
if err := repository.RecordCandidateCardAccess(ctx, event); err != nil {
|
||||
return fmt.Errorf("%s - record access audit: %w", location, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// AuthorizeCategoriesSection runs the checks of an organization card read
|
||||
// inside the caller's transaction and reports which candidate, and which
|
||||
// categories (specialization and grade), the card shows. It exists for the sections
|
||||
// of a card that explain its categories, such as the permitted evidence: they
|
||||
// must not disclose more than the categories of the current card do.
|
||||
//
|
||||
// The checks are those of GetOrganizationCard: the active membership of the
|
||||
// actor, the effective C2 publication, the hiding of this organization, and
|
||||
// the minimum cohort, all under the same locks. The card must also show at
|
||||
// least one category after the cohort rules, otherwise the answer is
|
||||
// ErrCandidateCardNotFound, the same as for an unknown handle. A successful
|
||||
// call consumes the card-view quota and records the access with the
|
||||
// categories field, so the candidate sees the read in the access history. The
|
||||
// caller reads the section in the same transaction, after this returns.
|
||||
func (service *Service) AuthorizeCategoriesSection(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
actorID, organizationID uuid.UUID,
|
||||
handle string,
|
||||
) (uuid.UUID, []domain.CandidateViewCategory, error) {
|
||||
const location = "candidateview.Service.AuthorizeCategoriesSection"
|
||||
if actorID == uuid.Nil || organizationID == uuid.Nil {
|
||||
return uuid.Nil, nil, ErrForbidden
|
||||
}
|
||||
if !domain.IsCandidateViewPseudonym(handle) {
|
||||
return uuid.Nil, nil, ErrInvalidCandidateHandle
|
||||
}
|
||||
organization, repository, candidateID, view, err := service.currentOrganizationCard(ctx, unit, actorID, organizationID, handle, location)
|
||||
if err != nil {
|
||||
return uuid.Nil, nil, err
|
||||
}
|
||||
if len(view.Categories) == 0 {
|
||||
return uuid.Nil, nil, ErrCandidateCardNotFound
|
||||
}
|
||||
err = service.reserveCardView(ctx, unit, repository, organization, candidateID, location, func(at time.Time) (domain.CandidateCardAccess, error) {
|
||||
return domain.NewCandidateCardAccess(domain.CandidateCardAccessInput{
|
||||
CandidateID: candidateID, OrganizationID: organizationID, ActorID: actorID,
|
||||
Kind: domain.CandidateCardAccessCardViewed, ProjectionFields: []domain.CardField{domain.CardFieldCategories}, OccurredAt: at,
|
||||
})
|
||||
})
|
||||
if err != nil {
|
||||
return uuid.Nil, nil, err
|
||||
}
|
||||
return candidateID, slices.Clone(view.Categories), nil
|
||||
}
|
||||
|
||||
func (service *Service) currentOrganizationCard(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
@@ -216,9 +284,13 @@ func projectedViewForHandle(
|
||||
// PreviewResult contains only the candidate's own current publication state
|
||||
// and the strict anonymous-card projection.
|
||||
type PreviewResult struct {
|
||||
Published bool
|
||||
Fields domain.CardFieldSet
|
||||
Card *domain.AnonymousCandidateViewDTO
|
||||
Published bool
|
||||
Fields domain.CardFieldSet
|
||||
Card *domain.AnonymousCandidateViewDTO
|
||||
// Evidence is what an organization would read with the categories of the
|
||||
// card: for each category, the one fact that supports its confirmed grade.
|
||||
// It is empty when the card shows no category.
|
||||
Evidence []domain.EvidenceOrganizationFact
|
||||
GeneratedAt time.Time
|
||||
}
|
||||
|
||||
@@ -266,7 +338,13 @@ func (service *Service) GetMyCardPreview(ctx context.Context, actorID uuid.UUID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - build private preview: %w", location, err)
|
||||
}
|
||||
result = PreviewResult{Published: true, Fields: source.PublishedFields(), Card: &card, GeneratedAt: generatedAt}
|
||||
var facts []domain.EvidenceOrganizationFact
|
||||
if len(card.Categories) > 0 {
|
||||
if facts, err = unit.Evidence().ListPreviewFacts(ctx, actorID, card.Categories); err != nil {
|
||||
return fmt.Errorf("%s - read preview evidence: %w", location, err)
|
||||
}
|
||||
}
|
||||
result = PreviewResult{Published: true, Fields: source.PublishedFields(), Card: &card, Evidence: facts, GeneratedAt: generatedAt}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
// Package evidence reads the skill evidence projection. The candidate reads
|
||||
// their own facts; an organization reads only the permitted projection of a
|
||||
// card it is currently allowed to see. The projection holds no answers,
|
||||
// failures, or anti-cheat data, and this package has no way to reach them.
|
||||
package evidence
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrForbidden reports an actor of the wrong role or without a verified
|
||||
// email.
|
||||
ErrForbidden = errors.New("skill evidence is forbidden")
|
||||
// ErrInvalidRequest reports a page request outside the contract bounds.
|
||||
ErrInvalidRequest = errors.New("skill evidence request is invalid")
|
||||
// ErrServiceMissing reports an incomplete service wiring.
|
||||
ErrServiceMissing = errors.New("skill evidence service is unavailable")
|
||||
)
|
||||
|
||||
// AuthorizeCategoriesSection runs the shared organization card checks inside
|
||||
// the given transaction: active membership, effective C2 publication, hiding of
|
||||
// the organization, the minimum cohort, the card-view quota, and the access
|
||||
// audit. It returns the candidate and the categories that the card shows. The
|
||||
// candidateview usecase provides it; bootstrap passes it in so this package
|
||||
// does not depend on another usecase.
|
||||
type AuthorizeCategoriesSection func(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
actorID, organizationID uuid.UUID,
|
||||
handle string,
|
||||
) (uuid.UUID, []domain.CandidateViewCategory, error)
|
||||
|
||||
// Dependencies configure the read service.
|
||||
type Dependencies struct {
|
||||
Transactor outbound.Transactor
|
||||
AuthorizeCategories AuthorizeCategoriesSection
|
||||
}
|
||||
|
||||
// Service reads the evidence projection.
|
||||
type Service struct {
|
||||
transactor outbound.Transactor
|
||||
authorizeCategories AuthorizeCategoriesSection
|
||||
}
|
||||
|
||||
func NewService(deps Dependencies) (*Service, error) {
|
||||
if deps.Transactor == nil || deps.AuthorizeCategories == nil {
|
||||
return nil, fmt.Errorf("evidence.NewService - dependencies are missing: %w", ErrServiceMissing)
|
||||
}
|
||||
return &Service{transactor: deps.Transactor, authorizeCategories: deps.AuthorizeCategories}, nil
|
||||
}
|
||||
|
||||
// ListMine returns one owner-scoped page of the candidate's facts, hidden ones
|
||||
// included. The candidate comes from the session and nothing else selects the
|
||||
// owner.
|
||||
func (service *Service) ListMine(ctx context.Context, query outbound.EvidenceListQuery) (outbound.EvidenceFactPage, error) {
|
||||
const location = "evidence.Service.ListMine"
|
||||
if query.CandidateID == uuid.Nil {
|
||||
return outbound.EvidenceFactPage{}, ErrForbidden
|
||||
}
|
||||
if query.Limit < 1 || query.Limit > outbound.MaxEvidencePageSize {
|
||||
return outbound.EvidenceFactPage{}, ErrInvalidRequest
|
||||
}
|
||||
var page outbound.EvidenceFactPage
|
||||
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if err := authorizeCandidate(ctx, unit, query.CandidateID); err != nil {
|
||||
return err
|
||||
}
|
||||
var readErr error
|
||||
page, readErr = unit.Evidence().ListCandidateFacts(ctx, query)
|
||||
if readErr != nil {
|
||||
return fmt.Errorf("%s - read owner facts: %w", location, readErr)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return outbound.EvidenceFactPage{}, fmt.Errorf("%s - run transaction: %w", location, err)
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
// ListForOrganization returns the permitted facts of the card that the handle
|
||||
// names for the organization. The membership, the publication, the hiding, and
|
||||
// the cohort are rechecked by the card checks, and the repository rechecks the
|
||||
// publication and the hiding again in the statement that reads the facts, so a
|
||||
// change between the two cannot widen the answer. Nothing returned belongs to
|
||||
// a candidate that the organization may not see now.
|
||||
func (service *Service) ListForOrganization(
|
||||
ctx context.Context,
|
||||
actorID, organizationID uuid.UUID,
|
||||
handle string,
|
||||
) ([]domain.EvidenceOrganizationFact, error) {
|
||||
const location = "evidence.Service.ListForOrganization"
|
||||
var facts []domain.EvidenceOrganizationFact
|
||||
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
candidateID, categories, err := service.authorizeCategories(ctx, unit, actorID, organizationID, handle)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
facts, err = unit.Evidence().ListOrganizationFacts(ctx, organizationID, candidateID, categories)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read permitted facts: %w", location, err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - run transaction: %w", location, err)
|
||||
}
|
||||
return facts, nil
|
||||
}
|
||||
|
||||
func authorizeCandidate(ctx context.Context, unit outbound.UnitOfWork, actorID uuid.UUID) error {
|
||||
user, err := unit.Users().GetByID(ctx, actorID)
|
||||
if errors.Is(err, outbound.ErrUserNotFound) {
|
||||
return ErrForbidden
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("evidence.authorizeCandidate - read actor account: %w", err)
|
||||
}
|
||||
if !user.EmailVerified() || user.Scenario != domain.ScenarioCandidate {
|
||||
return ErrForbidden
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package evidence
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
type evidenceTestTransactor struct{ unit outbound.UnitOfWork }
|
||||
|
||||
func (transactor evidenceTestTransactor) WithinTransaction(ctx context.Context, fn func(context.Context, outbound.UnitOfWork) error) error {
|
||||
return fn(ctx, transactor.unit)
|
||||
}
|
||||
|
||||
type evidenceTestUnit struct {
|
||||
outbound.UnitOfWork
|
||||
|
||||
users outbound.UserRepository
|
||||
evidence *evidenceTestRepository
|
||||
}
|
||||
|
||||
func (unit evidenceTestUnit) Users() outbound.UserRepository { return unit.users }
|
||||
func (unit evidenceTestUnit) Evidence() outbound.EvidenceRepository { return unit.evidence }
|
||||
|
||||
type evidenceTestUsers struct {
|
||||
outbound.UserRepository
|
||||
|
||||
users map[uuid.UUID]domain.User
|
||||
}
|
||||
|
||||
func (repository evidenceTestUsers) GetByID(_ context.Context, id uuid.UUID) (domain.User, error) {
|
||||
user, ok := repository.users[id]
|
||||
if !ok {
|
||||
return domain.User{}, outbound.ErrUserNotFound
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
type evidenceTestRepository struct {
|
||||
query outbound.EvidenceListQuery
|
||||
organizationID uuid.UUID
|
||||
candidateID uuid.UUID
|
||||
categories []domain.CandidateViewCategory
|
||||
listCalls int
|
||||
organizationHit int
|
||||
}
|
||||
|
||||
func (repository *evidenceTestRepository) ListCandidateFacts(_ context.Context, query outbound.EvidenceListQuery) (outbound.EvidenceFactPage, error) {
|
||||
repository.listCalls++
|
||||
repository.query = query
|
||||
return outbound.EvidenceFactPage{}, nil
|
||||
}
|
||||
|
||||
func (repository *evidenceTestRepository) ListOrganizationFacts(
|
||||
_ context.Context,
|
||||
organizationID, candidateID uuid.UUID,
|
||||
categories []domain.CandidateViewCategory,
|
||||
) ([]domain.EvidenceOrganizationFact, error) {
|
||||
repository.organizationHit++
|
||||
repository.organizationID, repository.candidateID, repository.categories = organizationID, candidateID, categories
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (repository *evidenceTestRepository) ListPreviewFacts(context.Context, uuid.UUID, []domain.CandidateViewCategory) ([]domain.EvidenceOrganizationFact, error) {
|
||||
return nil, errors.New("the organization read must not read the preview")
|
||||
}
|
||||
|
||||
func newEvidenceTestService(t *testing.T, authorize AuthorizeCategoriesSection) (*Service, *evidenceTestRepository, domain.User, domain.User) {
|
||||
t.Helper()
|
||||
now := time.Date(2026, 10, 8, 12, 0, 0, 0, time.UTC)
|
||||
candidate := domain.User{ID: uuid.New(), Scenario: domain.ScenarioCandidate, EmailVerifiedAt: &now}
|
||||
employer := domain.User{ID: uuid.New(), Scenario: domain.ScenarioEmployer, EmailVerifiedAt: &now}
|
||||
unverified := domain.User{ID: uuid.New(), Scenario: domain.ScenarioCandidate}
|
||||
repository := &evidenceTestRepository{}
|
||||
unit := evidenceTestUnit{
|
||||
users: evidenceTestUsers{users: map[uuid.UUID]domain.User{
|
||||
candidate.ID: candidate, employer.ID: employer, unverified.ID: unverified,
|
||||
}},
|
||||
evidence: repository,
|
||||
}
|
||||
service, err := NewService(Dependencies{Transactor: evidenceTestTransactor{unit: unit}, AuthorizeCategories: authorize})
|
||||
if err != nil {
|
||||
t.Fatalf("NewService() error = %v", err)
|
||||
}
|
||||
return service, repository, candidate, unverified
|
||||
}
|
||||
|
||||
func noAuthorization(context.Context, outbound.UnitOfWork, uuid.UUID, uuid.UUID, string) (uuid.UUID, []domain.CandidateViewCategory, error) {
|
||||
return uuid.Nil, nil, errors.New("the owner read must not run the organization card checks")
|
||||
}
|
||||
|
||||
func TestNewServiceRequiresItsDependencies(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
if _, err := NewService(Dependencies{AuthorizeCategories: noAuthorization}); !errors.Is(err, ErrServiceMissing) {
|
||||
t.Fatalf("NewService(without transactor) error = %v, want ErrServiceMissing", err)
|
||||
}
|
||||
if _, err := NewService(Dependencies{Transactor: evidenceTestTransactor{}}); !errors.Is(err, ErrServiceMissing) {
|
||||
t.Fatalf("NewService(without card checks) error = %v, want ErrServiceMissing", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListMineReadsOnlyForAVerifiedCandidate(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
service, repository, candidate, unverified := newEvidenceTestService(t, noAuthorization)
|
||||
for name, test := range map[string]struct {
|
||||
query outbound.EvidenceListQuery
|
||||
want error
|
||||
}{
|
||||
"employer account": {outbound.EvidenceListQuery{CandidateID: uuid.New(), Limit: 20}, ErrForbidden},
|
||||
"unverified email": {outbound.EvidenceListQuery{CandidateID: unverified.ID, Limit: 20}, ErrForbidden},
|
||||
"no owner": {outbound.EvidenceListQuery{Limit: 20}, ErrForbidden},
|
||||
"limit below range": {outbound.EvidenceListQuery{CandidateID: candidate.ID, Limit: 0}, ErrInvalidRequest},
|
||||
"limit above range": {outbound.EvidenceListQuery{CandidateID: candidate.ID, Limit: outbound.MaxEvidencePageSize + 1}, ErrInvalidRequest},
|
||||
} {
|
||||
if _, err := service.ListMine(context.Background(), test.query); !errors.Is(err, test.want) {
|
||||
t.Errorf("%s: error = %v, want %v", name, err, test.want)
|
||||
}
|
||||
}
|
||||
if repository.listCalls != 0 {
|
||||
t.Fatalf("a refused read reached the repository %d times", repository.listCalls)
|
||||
}
|
||||
|
||||
if _, err := service.ListMine(context.Background(), outbound.EvidenceListQuery{CandidateID: candidate.ID, Limit: 20}); err != nil {
|
||||
t.Fatalf("ListMine(candidate) error = %v", err)
|
||||
}
|
||||
if repository.query.CandidateID != candidate.ID || repository.listCalls != 1 {
|
||||
t.Fatalf("repository query = %+v after %d calls, want the owner once", repository.query, repository.listCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListForOrganizationReadsOnlyWhatTheCardChecksName(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
organizationID, actorID, candidateID := uuid.New(), uuid.New(), uuid.New()
|
||||
var authorized bool
|
||||
service, repository, _, _ := newEvidenceTestService(t, func(_ context.Context, _ outbound.UnitOfWork, actor, organization uuid.UUID, handle string) (uuid.UUID, []domain.CandidateViewCategory, error) {
|
||||
authorized = actor == actorID && organization == organizationID && handle == "handle"
|
||||
return candidateID, []domain.CandidateViewCategory{{Specialization: domain.SpecializationBackend, Grade: domain.GradeIntern}}, nil
|
||||
})
|
||||
if _, err := service.ListForOrganization(context.Background(), actorID, organizationID, "handle"); err != nil {
|
||||
t.Fatalf("ListForOrganization() error = %v", err)
|
||||
}
|
||||
if !authorized || repository.organizationID != organizationID || repository.candidateID != candidateID ||
|
||||
len(repository.categories) != 1 || repository.categories[0].Specialization != domain.SpecializationBackend ||
|
||||
repository.categories[0].Grade != domain.GradeIntern {
|
||||
t.Fatalf("read scope = organization %s candidate %s categories %v", repository.organizationID, repository.candidateID, repository.categories)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListForOrganizationStopsWhenTheCardChecksRefuse(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
refusal := errors.New("card checks refused")
|
||||
service, repository, _, _ := newEvidenceTestService(t, func(context.Context, outbound.UnitOfWork, uuid.UUID, uuid.UUID, string) (uuid.UUID, []domain.CandidateViewCategory, error) {
|
||||
return uuid.Nil, nil, refusal
|
||||
})
|
||||
if _, err := service.ListForOrganization(context.Background(), uuid.New(), uuid.New(), "handle"); !errors.Is(err, refusal) {
|
||||
t.Fatalf("ListForOrganization() error = %v, want the refusal of the card checks", err)
|
||||
}
|
||||
if repository.organizationHit != 0 {
|
||||
t.Fatal("facts were read after the card checks refused")
|
||||
}
|
||||
}
|
||||
@@ -623,6 +623,24 @@ Code: migration `backend/db/migrations/00033_create_assessment_signal_review.sql
|
||||
- When and how. The review never runs in a candidate's transaction. The first accepted answer schedules the job `assessment.signal_review` with the key `<attempt>:deadline`, due one minute after the deadline of the attempt (so an answer committed right at the deadline is in its facts), and finalization schedules `<attempt>:ended`, due at once; both are inserts into `scheduled_jobs` in the transaction of the answer or the finalization, and repeats do nothing. The deadline job also covers an attempt that expires or is abandoned, however and whenever its state changes. A review is a point-in-time evaluation: it describes the facts committed when its job ran, and the job at the deadline runs it again for a finalized attempt, which picks up later matches. The job computes the review of its attempt and refreshes the review of every other attempt that has ended (terminal state or past its deadline) and shares answers with it at the attention level or above, at most 50 per job; a ring of more than 50 attempts that share answers is covered because each member runs its own deadline job and sees the others. An attempt that is still running is flagged by its own job when it ends and sees the other facts then. Writers are ordered by a transaction-scoped advisory lock per review: the job locks the review of every attempt it will write, in ascending attempt order, before it reads any fact, so the later of two jobs over one attempt waits and then reads what the earlier committed (no lost update, and no lock cycle). The times of a review come from the database clock inside the upsert and the update time never falls behind the stored times. Nothing else is locked: the facts are append-only and a job is scheduled after its facts are committed. A failure is retried by the runner with backoff and can never block or change a result; without the worker (`JOBS_ENABLED=false`) reviews wait with their jobs. The only review statement in a candidate's transaction is the insert of the job (and the two counter updates of the answer). The job logs one line with the number of reviews it wrote and its duration, and no answer, address, or candidate. Applicability bound: the share is read from the counters in constant time, but the comparison joins the answers of the attempt with the answers that hold the same values, so its cost grows with the number of holders of popular values, at most 23 items times the holders of each; it is fine for background jobs on populations of up to about 100,000 answers per family and needs sampling or a cap above that.
|
||||
- Limits. Browser signals can be forged or suppressed, so they are a hint only. A helper such as an LLM on another device is not visible. False positives are possible: a shared or changing network (mobile data, NAT), a reload, two tabs, copying the task text, and coinciding answers of a small answer space. The retention period of these facts, whether collecting them needs a separate consent beyond the notice, and who calibrates the thresholds are not decided.
|
||||
|
||||
### Skill evidence
|
||||
|
||||
Implemented as a stored projection of the immutable assessment results, with two reads: the candidate's own list and the permitted projection of a currently visible card. It feeds nothing yet: no ranking, matching, or percentile reads it.
|
||||
|
||||
Code: migration `backend/db/migrations/00035_create_skill_evidence.sql`, queries `backend/db/queries/evidence.sql`, the model in `backend/internal/domain/evidence.go`, the port `port/outbound/evidence.go` (`UnitOfWork.Evidence()`), the adapter `adapter/secondary/postgres/evidence.go`, the usecase `backend/internal/usecase/evidence/read.go`, the handler `adapter/primary/http/v1/evidence.go`, and the operations `ListMyEvidence` and `GetOrganizationCandidateEvidence` ([api/README.en.md](../../api/README.en.md#skill-evidence)).
|
||||
|
||||
- One event is one fact. `skill_evidence_facts` has one row per source event (`UNIQUE (source_type, event_id)`); `skill_evidence_skills` holds the skills of that event as tags (primary key `(fact_id, skill_code)`, a closed set of the nine specialization codes and the four technology codes of the card). A second tag adds a tag, never a fact, so repeated tags cannot multiply a contribution. A fact without a skill cannot be committed (a deferred constraint trigger), tags, once stored, are never rewritten or removed, and a tag joins a fact only in the transaction that created it (`created_txid` and the trigger `skill_evidence_skills_require_new_fact`), so a stored fact is never widened afterwards.
|
||||
- A fact keeps its source, event, result, attribution, date, visibility, and trust, and tells a claim from a measurement. `kind` is `claim` (trust 0, a statement that nothing confirmed separately) or `measurement` (trust 1 to 3, an observed result); a CHECK ties each kind to its levels. Only measurements are written today, so no claim is stored and the profile claims (trust 0) are not listed. `source_type` is `assessment_result` and the event and the result are the attempt, because a result is keyed by its attempt (`result_id` is a foreign key to `assessment_attempt_results` with the owner, and a cascade removes the fact with its result or account). `attribution` is `personal` (the team values of the PRD are reserved by the CHECK). The result part is the grade that was passed, the basis (`synthetic_demo`), and the calibration (`uncalibrated`), copied from the category decision of the result: a demonstration category is shown as one.
|
||||
- Trust 1. An online assessment is unproctored and nothing confirms who answered, so the projection writes trust 1 (the PRD level without a reliable confirmation of the identity or authorship). A CHECK allows only 1 or 2 for this source, never the in-person level 3; 2 is reserved for a result tied to a confirmed identity, which no flow produces yet. `domain.EvidenceTrustOnlineUnconfirmed` and the SQL value are kept equal by the integration test.
|
||||
- Which results qualify. One SQL predicate (`skill_evidence_result_qualifies`) says that a result is evidence: a real result (`root` or `corrective`) of the basic mode, version 2, with the outcome `confirmed`, and a category decision with the status `assigned` or `unchanged`, that is, a reviewed synthetic source. A result that passed but had no reviewed source (`not_eligible`, for example with the demonstration gate off) is not evidence, a failed attempt is not evidence and is never shown as a failure, and an express training run (`demo_express`, a version 1 result of the mode `demo_express`) is never evidence. A lower passing result under a higher category (`unchanged`) is a fact of its own: the grade was passed, and the category stays.
|
||||
- Why a stored projection written by the database, not a derivation on read. Decision: a trigger on `assessment_attempt_results` calls `skill_evidence_project_assessment_result` after the insert of a result, in the transaction that finalizes the attempt, and the migration projects the results that already exist with the same function. Reasons: the atomicity with the result and the category holds without a change to the finalization code; no write path (a command, a repair, a future import) can store a qualifying result and forget its evidence, or the reverse; a fact needs state that a derivation cannot carry (the candidate's visibility, tags from other events); and every read touches only the projection, so no query of the evidence names a result, an answer, an attempt, or a review (a test reads the query files and fails on it). The cost: the rule lives in SQL as the category guards do, the projection must be rebuilt by the function if the rule changes (the function is idempotent, and an integration test truncates the projection and rebuilds it), and the facts duplicate three values of the result. A guard trigger refuses a fact whose result does not qualify or does not match the fact, even through a direct write, and the table refuses every change but `visibility`. Rolling the migration back drops the projection, which is derived, and applying the migration again rebuilds it; but the rollback refuses (`skill_evidence_retained`) while any fact is hidden, because hiding is the candidate's decision and no result can bring it back. Known risks: a trigger failure rolls the finalization back with it, which is the intended atomicity (a result without its fact is never stored); and a real version 2 result whose specialization is outside the closed skill list would fail the backfill of the migration and the trigger, so a new specialization needs a change of the list in the same migration that admits it.
|
||||
- The candidate reads `GET /api/v1/me/evidence`: own facts only, newest first, the hidden ones with `visibility` `hidden`, a cursor bound to the candidate (the cursor of the privacy lists), `Cache-Control: no-store`. The fact names the result that the candidate can open at `GetMyAssessmentResult`.
|
||||
- The organization reads `GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}/evidence`. The evidence is a section of the card, so the read runs the checks of the card read in one transaction: verified employer, active membership, effective C2 publication, the hiding of this organization, the minimum cohort, and the card must show at least one category after the cohort rules (`candidateview.Service.AuthorizeCategoriesSection`, which returns the categories of the card, each with its grade). Then the statement `ListOrganizationVisibleEvidence` repeats the barrier: it selects from `candidate_effective_publications`, excludes the candidates that hide the organization with `NOT EXISTS`, requires the `categories` field in the published fields, and returns only visible measurements. It returns one fact for each category of the card: the earliest fact that passed exactly the confirmed grade of that category, so a lower grade or a retake adds nothing, and only the skill of the category, never the other tags. A closed or revoked publication, a hidden organization, an unknown handle, a suppressed card, and a card without categories answer one 404; a hidden fact gives an empty list, not an error. The answer is an allowlist: the skill, the passed grade, the trust level, the year of the event (`observed_year`), and the basis and calibration of the method (`synthetic_demo`, `uncalibrated`), which are the same for every candidate and tell the organization that the fact is a demonstration, not a validated measurement (they add no fingerprint). It has no identifier of the fact, the event, the result, or the candidate, no month or exact time, no source, and never an answer, score, item, failure, signal, or review band. What can and cannot be linked: no key joins the answer to a person, but it is not unlinkable. The skill, grade, trust, and year, together with the other values of the card, can narrow a small pool of candidates, and the minimum cohort of the card does not cover the year. The read consumes the card-view quota under the distinct-card rule and is recorded in the access history with the field `categories`, so the candidate sees it.
|
||||
- Scope of the consent C2. Publishing the `categories` field now sends an organization the confirmed category and one supporting assessment fact for it (skill, grade, trust level, year, and the demonstration labels). The candidate sees the same section in `GetMyCardPreview` (`evidence`), which applies no organization or cohort, so an organization can receive less. The C2 consent text was written before this section existed, and whether it needs a new version for it is a decision for the owner and the lawyer; this change does not touch the consent texts.
|
||||
- Express and failure. Reading the evidence before and after an express run shows the same list, the database refuses a fact whose result is an express run or a failed attempt, and an express run is not in the category, hence not in the card cohort. There is no percentile or ranking cohort in this release; when they appear they must read the same predicate.
|
||||
- Contract checks. `TestEvidenceOperationsFollowTheConventions`, `TestEvidenceSchemasAreClosedAndSeparateClaimsFromMeasurements`, `TestNoOrganizationOperationReachesRawAssessmentData`, and `TestEvidenceWalkReachesTheEvidenceFamily` (Go) and `test_evidence_is_closed_and_no_organization_operation_reaches_raw_assessment_data` (Python) walk every organization operation and the candidate list through all references and fail on an assessment, signal, or review schema, or on a raw answer, score, or failure property.
|
||||
- Not implemented: an operation to hide or show a fact (the column and the guard exist; no HTTP operation changes it), claims from the profile as facts, facts from FSP or other sources, revocation of a source, a trust level above 1, the use of evidence in ranking or in the Passport PDF, and retention. Whether the evidence should need its own card field instead of `categories` is open.
|
||||
|
||||
## Matching and explanations
|
||||
|
||||
Before ranking, Go applies hard filters: published profile, specialty, verified grade, required skills, and other selected criteria. A strong resume or achievement cannot compensate for a missing mandatory requirement. Distinguish an unverified skill from evidence that the skill is absent.
|
||||
|
||||
@@ -623,6 +623,24 @@ contact_grant относится к паре кандидат-компания
|
||||
- Когда и как. Проверка никогда не считается в транзакции кандидата. Первый принятый ответ планирует задание `assessment.signal_review` с ключом `<попытка>:deadline`, срок - через минуту после дедлайна попытки (чтобы ответ, зафиксированный прямо на дедлайне, попал в факты), а завершение планирует `<попытка>:ended`, срок - сразу; оба - вставки в `scheduled_jobs` в транзакции ответа или завершения, повтор ничего не делает. Задание дедлайна покрывает и попытку, которая истекает или брошена, как и когда бы ни менялось ее состояние. Проверка - оценка на момент: она описывает факты, зафиксированные к запуску ее задания, а задание на дедлайне для завершенной попытки запускает ее снова и подхватывает поздние совпадения. Задание считает проверку своей попытки и обновляет проверку каждой другой завершившейся (терминальное состояние или срок прошел) попытки с общими ответами на уровне «внимание» и выше, не более 50 за задание; кольцо больше 50 попыток с общими ответами покрыто тем, что каждый участник запускает свое задание дедлайна и видит остальных. Еще идущую попытку помечает ее собственное задание, когда она закончится и увидит остальные факты. Писатели упорядочены транзакционной advisory-блокировкой на каждую проверку: задание берет блокировки проверок всех попыток, которые будет писать, по возрастанию идентификатора, до чтения любого факта, поэтому более позднее из двух заданий по одной попытке ждет и затем читает то, что зафиксировало раннее (нет потерянного обновления и нет цикла блокировок). Время проверки берется из часов базы внутри upsert, а время обновления не отстает от сохраненного. Больше ничего не блокируется: факты только добавляются, а задание планируется после фиксации его фактов. Сбой повторяется исполнителем с задержкой и никогда не блокирует и не меняет результат; без worker (`JOBS_ENABLED=false`) проверки ждут вместе со своими заданиями. В транзакции кандидата из запросов проверки только вставка задания (и два обновления счетчиков ответа). Задание пишет в журнал одну строку с числом записанных проверок и длительностью, без ответов, адресов и кандидатов. Граница применимости: доля читается из счетчиков за постоянное время, но сравнение соединяет ответы попытки с ответами, у которых те же значения, поэтому цена растет с числом держателей популярных значений, не более 23 заданий на число держателей каждого; для фоновых заданий это нормально на совокупностях до порядка 100 000 ответов на семейство, выше нужна выборка или предел.
|
||||
- Ограничения. Браузерные сигналы можно подделать или подавить, поэтому это только подсказка. Помощь, например LLM на другом устройстве, не видна. Возможны ложные срабатывания: общая или меняющаяся сеть (мобильный интернет, NAT), перезагрузка страницы, две вкладки, копирование условия и случайные совпадения ответов из малого пространства. Срок хранения этих фактов, нужно ли для их сбора отдельное согласие сверх уведомления и кто калибрует пороги, не решено.
|
||||
|
||||
### Доказательства навыков
|
||||
|
||||
Реализовано как сохраняемая проекция неизменяемых результатов оценки с двумя чтениями: собственный список кандидата и разрешенная проекция сейчас видимой карточки. Проекцию пока никто не использует: ни ранжирование, ни подбор, ни перцентиль ее не читают.
|
||||
|
||||
Код: миграция `backend/db/migrations/00035_create_skill_evidence.sql`, запросы `backend/db/queries/evidence.sql`, модель `backend/internal/domain/evidence.go`, порт `port/outbound/evidence.go` (`UnitOfWork.Evidence()`), адаптер `adapter/secondary/postgres/evidence.go`, usecase `backend/internal/usecase/evidence/read.go`, обработчик `adapter/primary/http/v1/evidence.go` и операции `ListMyEvidence` и `GetOrganizationCandidateEvidence` ([api/README.md](../../api/README.md#доказательства-навыков)).
|
||||
|
||||
- Одно событие - один факт. В `skill_evidence_facts` одна строка на событие-источник (`UNIQUE (source_type, event_id)`); в `skill_evidence_skills` навыки этого события лежат как теги (первичный ключ `(fact_id, skill_code)`, закрытый набор из девяти кодов специализаций и четырех кодов технологий карточки). Второй тег добавляет тег, а не факт, поэтому повторные теги не умножают вклад. Факт без навыка нельзя зафиксировать (отложенный constraint-триггер), сохраненные теги не меняются и не удаляются, а тег присоединяется к факту только в транзакции, создавшей факт (`created_txid` и триггер `skill_evidence_skills_require_new_fact`), поэтому сохраненный факт потом не расширяется.
|
||||
- Факт хранит источник, событие, результат, атрибуцию, дату, видимость и доверие и отличает заявление от измерения. `kind` равен `claim` (доверие 0, утверждение без отдельного подтверждения) или `measurement` (доверие 1-3, наблюдаемый результат); CHECK связывает вид с допустимыми уровнями. Сейчас записываются только измерения, поэтому заявлений в таблице нет, а заявления профиля (доверие 0) в списке не показываются. `source_type` равен `assessment_result`, событие и результат - это попытка, так как результат ключуется попыткой (`result_id` - внешний ключ на `assessment_attempt_results` вместе с владельцем, каскад удаляет факт вместе с результатом или аккаунтом). `attribution` равна `personal` (командные значения PRD зарезервированы CHECK). Часть "результат" - пройденный грейд, основание (`synthetic_demo`) и калибровка (`uncalibrated`), скопированные из решения о категории: демонстрационная категория показывается как демонстрационная.
|
||||
- Доверие 1. Онлайн-оценка проходит без прокторинга, и ничто не подтверждает, кто отвечал, поэтому проекция пишет доверие 1 (уровень PRD без надежного подтверждения личности или авторства). CHECK допускает для этого источника только 1 или 2 и никогда не очный уровень 3; уровень 2 зарезервирован за результатом, связанным с подтвержденной личностью, - такого потока пока нет. `domain.EvidenceTrustOnlineUnconfirmed` и значение в SQL сверяет интеграционный тест.
|
||||
- Какие результаты считаются доказательством. Один SQL-предикат (`skill_evidence_result_qualifies`): настоящий результат (`root` или `corrective`) базового режима, версия 2, исход `confirmed` и решение о категории со статусом `assigned` или `unchanged`, то есть с проверенным синтетическим источником. Пройденный результат без проверенного источника (`not_eligible`, например при выключенном демонстрационном режиме) доказательством не является, проваленная попытка тоже не является и нигде не показывается как провал, а экспресс-прогон (`demo_express`, результат версии 1 режима `demo_express`) не бывает доказательством никогда. Более низкий пройденный результат при более высокой категории (`unchanged`) - отдельный факт: грейд пройден, категория остается.
|
||||
- Почему сохраняемая проекция, которую пишет база, а не вычисление при чтении. Решение: триггер на `assessment_attempt_results` после вставки результата вызывает `skill_evidence_project_assessment_result` в той же транзакции, что завершает попытку, а миграция проецирует уже существующие результаты той же функцией. Причины: атомарность с результатом и категорией без изменений в коде завершения; ни один путь записи (команда, исправление, будущий импорт) не сохранит подходящий результат без доказательства и наоборот; факту нужно состояние, которое вычисление не несет (видимость кандидата, теги от других событий); все чтения трогают только проекцию, поэтому ни один запрос доказательств не называет результат, ответ, попытку или проверку (тест читает файлы запросов и падает на этом). Цена: правило живет в SQL, как и охранники категории; при смене правила проекцию нужно перестроить функцией (она идемпотентна, интеграционный тест очищает проекцию и перестраивает ее); факт дублирует три значения результата. Охранный триггер отказывает факту, чей результат не подходит или не совпадает с фактом, даже при прямой записи, а таблица отказывает в любых изменениях, кроме `visibility`. Откат миграции удаляет проекцию, она производная, и повторное применение миграции строит ее заново; но откат отказывает (`skill_evidence_retained`), пока хоть один факт скрыт, потому что скрытие - решение кандидата, и никакой результат его не вернет. Известные риски: сбой триггера откатывает и завершение попытки, это задуманная атомарность (результат без своего факта не сохраняется); а настоящий результат версии 2 со специализацией вне закрытого списка навыков сломал бы заполнение миграции и триггер, поэтому новая специализация требует изменить список в той же миграции, которая ее допускает.
|
||||
- Кандидат читает `GET /api/v1/me/evidence`: только свои факты, новые первыми, скрытые - с `visibility` `hidden`, курсор привязан к кандидату (курсор списков приватности), `Cache-Control: no-store`. Факт называет результат, который кандидат открывает через `GetMyAssessmentResult`.
|
||||
- Организация читает `GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}/evidence`. Доказательства - раздел карточки, поэтому чтение выполняет проверки чтения карточки в одной транзакции: подтвержденный работодатель, активное членство, действующая публикация с C2, скрытие этой организации, минимальная когорта, и после правил когорты карточка должна показывать хотя бы одну категорию (`candidateview.Service.AuthorizeCategoriesSection`, он возвращает категории карточки с грейдами). Затем запрос `ListOrganizationVisibleEvidence` повторяет барьер: выбирает из `candidate_effective_publications`, исключает кандидатов, скрывших организацию, через `NOT EXISTS`, требует поле `categories` в опубликованных полях и возвращает только видимые измерения. Он возвращает по одному факту на каждую категорию карточки: самый ранний факт, который прошел ровно подтвержденный грейд этой категории, поэтому более низкий грейд и пересдача ничего не добавляют, и только навык категории, а не остальные теги. Закрытая или отозванная публикация, скрытая организация, неизвестный handle, подавленная карточка и карточка без категорий дают один и тот же 404; скрытый факт дает пустой список, а не ошибку. Ответ - белый список: навык, пройденный грейд, уровень доверия, год события (`observed_year`), а также основание и калибровка метода (`synthetic_demo`, `uncalibrated`), одинаковые для всех кандидатов: они сообщают организации, что факт - демонстрация, а не проверенное измерение (отпечатка они не добавляют). В нем нет идентификатора факта, события, результата или кандидата, нет месяца и точного времени, нет источника и никогда нет ответа, балла, задания, провала, сигнала или полосы проверки. Что можно и что нельзя связать: ключа, который привязывает ответ к человеку, нет, но ответ не является несвязываемым. Навык, грейд, доверие и год вместе с другими значениями карточки могут сузить малый пул кандидатов, а минимальная когорта карточки год не покрывает. Чтение расходует квоту просмотров карточек по правилу разных карточек и записывается в историю доступа с полем `categories`, так что кандидат его видит.
|
||||
- Область согласия C2. Публикация поля `categories` теперь отправляет организации подтвержденную категорию и один подтверждающий ее факт оценки (навык, грейд, уровень доверия, год и метки демонстрации). Кандидат видит тот же раздел в `GetMyCardPreview` (`evidence`); предпросмотр не применяет организацию и когорту, поэтому организация может получить меньше. Текст согласия C2 написан до появления этого раздела, и нужна ли для него новая версия, решают владелец продукта и юрист; это изменение тексты согласий не трогает.
|
||||
- Экспресс и провал. Чтение доказательств до и после экспресс-прогона дает один и тот же список, база отказывает факту, чей результат - экспресс-прогон или проваленная попытка, а экспресс не входит в категорию и потому в когорту карточки. Перцентиля и ранжирования в этом выпуске нет; когда они появятся, они обязаны читать тот же предикат.
|
||||
- Проверки контракта. `TestEvidenceOperationsFollowTheConventions`, `TestEvidenceSchemasAreClosedAndSeparateClaimsFromMeasurements`, `TestNoOrganizationOperationReachesRawAssessmentData` и `TestEvidenceWalkReachesTheEvidenceFamily` (Go) и `test_evidence_is_closed_and_no_organization_operation_reaches_raw_assessment_data` (Python) обходят все организационные операции и список кандидата по всем ссылкам и падают на схеме оценки, сигнала или проверки, а также на свойстве с сырым ответом, баллом или провалом.
|
||||
- Не реализовано: операция скрыть или показать факт (колонка и охранник есть, HTTP-операции для изменения нет), заявления профиля как факты, факты из ФСП и других источников, отзыв источника, уровень доверия выше 1, использование доказательств в ранжировании и в PDF "Паспорт навыков", срок хранения. Нужно ли доказательствам отдельное поле карточки вместо `categories`, остается открытым вопросом.
|
||||
|
||||
## Подбор и объяснение
|
||||
|
||||
До ранжирования Go применяет жесткие фильтры: опубликованный профиль, специализация, подтвержденный грейд, обязательные навыки и другие выбранные требования. Хорошее резюме или достижение не компенсирует отсутствующий обязательный критерий. Отсутствие подтверждения навыка нужно отличать от подтвержденного отсутствия.
|
||||
|
||||
@@ -7,6 +7,7 @@ function preview(card: NonNullable<CardPreview["card"]>): CardPreview {
|
||||
state: "published",
|
||||
fields: ["categories", "self_assessment", "stack", "experience", "work_formats"],
|
||||
card,
|
||||
evidence: { items: [] },
|
||||
generated_at: "2026-10-06T12:00:00Z",
|
||||
};
|
||||
}
|
||||
@@ -53,6 +54,7 @@ describe("candidate card presentation", () => {
|
||||
state: "closed",
|
||||
fields: [],
|
||||
card: null,
|
||||
evidence: null,
|
||||
generated_at: "2026-10-06T12:00:00Z",
|
||||
}),
|
||||
).toBeNull();
|
||||
|
||||
@@ -59,6 +59,18 @@ describe("privacy page sections", () => {
|
||||
work_formats: null,
|
||||
salary_compatibility: null,
|
||||
},
|
||||
evidence: {
|
||||
items: [
|
||||
{
|
||||
skill: "backend",
|
||||
grade: "junior",
|
||||
trust: 1,
|
||||
basis: "synthetic_demo",
|
||||
calibration_status: "uncalibrated",
|
||||
observed_year: 2026,
|
||||
},
|
||||
],
|
||||
},
|
||||
generated_at: "2026-10-03T10:00:00Z",
|
||||
};
|
||||
const markup = renderToStaticMarkup(
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import {
|
||||
faker
|
||||
} from '@faker-js/faker';
|
||||
|
||||
import {
|
||||
fakeFromPattern
|
||||
} from '../../mock-pattern';
|
||||
|
||||
import {
|
||||
HttpResponse,
|
||||
http
|
||||
} from 'msw';
|
||||
import type {
|
||||
RequestHandlerOptions
|
||||
} from 'msw';
|
||||
|
||||
import type {
|
||||
EvidenceFactList,
|
||||
OrganizationEvidence
|
||||
} from '../../schemas';
|
||||
|
||||
|
||||
export const getGetOrganizationCandidateEvidenceResponseMock = (overrideResponse: Partial<Extract<OrganizationEvidence, object>> = {}): OrganizationEvidence => ({items: Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({skill: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa','go','postgresql','kafka','docker'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), trust: faker.number.int({min: 0, max: 3}), basis: faker.helpers.arrayElement(['synthetic_demo'] as const), calibration_status: faker.helpers.arrayElement(['uncalibrated'] as const), observed_year: faker.number.int({min: 2000, max: 9999})})), ...overrideResponse})
|
||||
|
||||
export const getListMyEvidenceResponseMock = (overrideResponse: Partial<Extract<EvidenceFactList, object>> = {}): EvidenceFactList => ({items: Array.from({ length: faker.number.int({min: 1, max: 100}) }, (_, i) => i + 1).map(() => ({id: faker.string.uuid(), kind: faker.helpers.arrayElement(['claim','measurement'] as const), source: {type: faker.helpers.arrayElement(['assessment_result'] as const), event_id: faker.string.uuid(), result_id: faker.string.uuid()}, skills: faker.helpers.arrayElements(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa','go','postgresql','kafka','docker'] as const), result: {grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), basis: faker.helpers.arrayElement(['synthetic_demo'] as const), calibration_status: faker.helpers.arrayElement(['uncalibrated'] as const)}, attribution: faker.helpers.arrayElement(['personal','team_role','team_unattributed'] as const), trust: faker.number.int({min: 0, max: 3}), occurred_at: faker.date.past().toISOString().slice(0, 19) + 'Z', visibility: faker.helpers.arrayElement(['visible','hidden'] as const)})), page: {has_more: faker.datatype.boolean(), next_cursor: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 512}), null])}, ...overrideResponse})
|
||||
|
||||
|
||||
export const getGetOrganizationCandidateEvidenceMockHandler = (overrideResponse?: OrganizationEvidence | ((info: Parameters<Parameters<typeof http.get>[1]>[0]) => Promise<OrganizationEvidence> | OrganizationEvidence), options?: RequestHandlerOptions) => {
|
||||
return http.get('*/api/v1/organizations/:orgId/candidate-cards/:candidateHandle/evidence', async (info: Parameters<Parameters<typeof http.get>[1]>[0]) => {
|
||||
|
||||
|
||||
return HttpResponse.json(overrideResponse !== undefined
|
||||
? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse)
|
||||
: getGetOrganizationCandidateEvidenceResponseMock(),
|
||||
{ status: 200
|
||||
})
|
||||
}, options)
|
||||
}
|
||||
|
||||
export const getListMyEvidenceMockHandler = (overrideResponse?: EvidenceFactList | ((info: Parameters<Parameters<typeof http.get>[1]>[0]) => Promise<EvidenceFactList> | EvidenceFactList), options?: RequestHandlerOptions) => {
|
||||
return http.get('*/api/v1/me/evidence', async (info: Parameters<Parameters<typeof http.get>[1]>[0]) => {
|
||||
|
||||
|
||||
return HttpResponse.json(overrideResponse !== undefined
|
||||
? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse)
|
||||
: getListMyEvidenceResponseMock(),
|
||||
{ status: 200
|
||||
})
|
||||
}, options)
|
||||
}
|
||||
export const getEvidenceMock = () => [
|
||||
getGetOrganizationCandidateEvidenceMockHandler(),
|
||||
getListMyEvidenceMockHandler()
|
||||
]
|
||||
@@ -0,0 +1,282 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import {
|
||||
useQuery
|
||||
} from '@tanstack/react-query';
|
||||
import type {
|
||||
DataTag,
|
||||
DefinedInitialDataOptions,
|
||||
DefinedUseQueryResult,
|
||||
QueryClient,
|
||||
QueryFunction,
|
||||
QueryKey,
|
||||
UndefinedInitialDataOptions,
|
||||
UseQueryOptions,
|
||||
UseQueryResult
|
||||
} from '@tanstack/react-query';
|
||||
|
||||
import type {
|
||||
EvidenceFactList,
|
||||
ListMyEvidenceParams,
|
||||
OrganizationEvidence,
|
||||
Problem
|
||||
} from '../../schemas';
|
||||
|
||||
import { apiRequest } from '../../client';
|
||||
import type { ErrorType } from '../../client';
|
||||
|
||||
|
||||
type SecondParameter<T extends (...args: never) => unknown> = Parameters<T>[1];
|
||||
|
||||
|
||||
|
||||
const withQueryKey = <T extends object, K>(query: T, queryKey: K): T & { queryKey: K } => {
|
||||
const result = { queryKey } as T & { queryKey: K };
|
||||
for (const key of Object.keys(query)) {
|
||||
// The explicit queryKey always wins, matching the previous
|
||||
// `{ ...query, queryKey }` spread where it was set last.
|
||||
if (key === 'queryKey') continue;
|
||||
Object.defineProperty(result, key, {
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
get: () => (query as Record<string, unknown>)[key],
|
||||
});
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
export const getGetOrganizationCandidateEvidenceUrl = (orgId: string,
|
||||
candidateHandle: string,) => {
|
||||
|
||||
|
||||
|
||||
|
||||
return `/api/v1/organizations/${orgId}/candidate-cards/${candidateHandle}/evidence`
|
||||
}
|
||||
|
||||
/**
|
||||
* Requires the session cookie of an employer account with an active membership in `org_id`. The organization and membership come from the current server-side session and path, never from cached search data.
|
||||
*
|
||||
* `candidate_handle` is the organization-scoped opaque alias issued by the current anonymous-card projection. The server runs the same checks as the card read on every request: active membership, effective C2 publication, the candidate's hiding of this organization, and the minimum cohort. In addition the card must publish the `categories` field and show at least one category after the cohort rules, because the evidence explains those categories and discloses nothing beyond them. An unknown handle, a handle of another organization, a closed or revoked publication, a profile hidden from this organization, a profile suppressed by the minimum cohort, and a card without categories all answer the same 404 not_found. Closing C2 or hiding the organization blocks this read immediately, and a cached response proves nothing.
|
||||
*
|
||||
* The response lists, for each category of the card, the one visible fact that supports its confirmed grade: the earliest assessment that passed exactly that grade, so a lower grade or a retake adds nothing. A fact the candidate hid is absent. Each fact carries only the skill, the passed grade, the trust level, the year of the assessment, and the basis and calibration of the method (`synthetic_demo`, `uncalibrated`), which are the same for every candidate and say that the fact is a demonstration, not a validated measurement. It carries no identifier of the fact, event, result, or candidate, no month or exact time, and never an answer, item, score, failed attempt, review band, or anti-cheat signal. An express training run and a failed attempt create no fact. The answer has no key that joins it to a person, but it is not unlinkable: with the other values of the card it can narrow a small pool of candidates.
|
||||
*
|
||||
* Reading the evidence is a view of the candidate card: it consumes the organization's current card-view quota with the same distinct-card rule and is recorded in the access history with the `categories` field. When the quota is exhausted the operation answers 429 with Retry-After. The response is `Cache-Control: no-store`.
|
||||
*
|
||||
* A missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden; an unknown organization or account without an active membership answers 404 not_found. An `org_id` that is not a UUID or a malformed candidate handle answers 400 validation_failed.
|
||||
* @summary Read the permitted skill evidence of one currently visible candidate card.
|
||||
*/
|
||||
export const getOrganizationCandidateEvidence = async (orgId: string,
|
||||
candidateHandle: string, options?: Parameters<typeof apiRequest>[1]): Promise<OrganizationEvidence> => {
|
||||
|
||||
return apiRequest<OrganizationEvidence>(getGetOrganizationCandidateEvidenceUrl(orgId,candidateHandle),
|
||||
{
|
||||
...options,
|
||||
method: 'GET'
|
||||
|
||||
|
||||
}
|
||||
);}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
export const getGetOrganizationCandidateEvidenceQueryKey = (orgId: string,
|
||||
candidateHandle: string,) => {
|
||||
return [
|
||||
`/api/v1/organizations/${orgId}/candidate-cards/${candidateHandle}/evidence`
|
||||
] as const;
|
||||
}
|
||||
|
||||
|
||||
export const getGetOrganizationCandidateEvidenceQueryOptions = <TData = Awaited<ReturnType<typeof getOrganizationCandidateEvidence>>, TError = ErrorType<Problem>>(orgId: string,
|
||||
candidateHandle: string, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getOrganizationCandidateEvidence>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
|
||||
) => {
|
||||
|
||||
const {query: queryOptions, request: requestOptions} = options ?? {};
|
||||
|
||||
const queryKey = queryOptions?.queryKey ?? getGetOrganizationCandidateEvidenceQueryKey(orgId,candidateHandle);
|
||||
|
||||
|
||||
|
||||
const queryFn: QueryFunction<Awaited<ReturnType<typeof getOrganizationCandidateEvidence>>> = ({ signal }) => getOrganizationCandidateEvidence(orgId,candidateHandle, { signal, ...requestOptions });
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
return { queryKey, queryFn, enabled: orgId !== null && orgId !== undefined && candidateHandle !== null && candidateHandle !== undefined, ...queryOptions} as UseQueryOptions<Awaited<ReturnType<typeof getOrganizationCandidateEvidence>>, TError, TData> & { queryKey: DataTag<QueryKey, TData, TError> }
|
||||
}
|
||||
|
||||
export type GetOrganizationCandidateEvidenceQueryResult = NonNullable<Awaited<ReturnType<typeof getOrganizationCandidateEvidence>>>
|
||||
export type GetOrganizationCandidateEvidenceQueryError = ErrorType<Problem>
|
||||
|
||||
|
||||
export function useGetOrganizationCandidateEvidence<TData = Awaited<ReturnType<typeof getOrganizationCandidateEvidence>>, TError = ErrorType<Problem>>(
|
||||
orgId: string,
|
||||
candidateHandle: string, options: { query:Partial<UseQueryOptions<Awaited<ReturnType<typeof getOrganizationCandidateEvidence>>, TError, TData>> & Pick<
|
||||
DefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof getOrganizationCandidateEvidence>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof getOrganizationCandidateEvidence>>
|
||||
> , 'initialData'
|
||||
>, request?: SecondParameter<typeof apiRequest>}
|
||||
, queryClient?: QueryClient
|
||||
): DefinedUseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
||||
export function useGetOrganizationCandidateEvidence<TData = Awaited<ReturnType<typeof getOrganizationCandidateEvidence>>, TError = ErrorType<Problem>>(
|
||||
orgId: string,
|
||||
candidateHandle: string, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getOrganizationCandidateEvidence>>, TError, TData>> & Pick<
|
||||
UndefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof getOrganizationCandidateEvidence>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof getOrganizationCandidateEvidence>>
|
||||
> , 'initialData'
|
||||
>, request?: SecondParameter<typeof apiRequest>}
|
||||
, queryClient?: QueryClient
|
||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
||||
export function useGetOrganizationCandidateEvidence<TData = Awaited<ReturnType<typeof getOrganizationCandidateEvidence>>, TError = ErrorType<Problem>>(
|
||||
orgId: string,
|
||||
candidateHandle: string, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getOrganizationCandidateEvidence>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
|
||||
, queryClient?: QueryClient
|
||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
||||
/**
|
||||
* @summary Read the permitted skill evidence of one currently visible candidate card.
|
||||
*/
|
||||
|
||||
export function useGetOrganizationCandidateEvidence<TData = Awaited<ReturnType<typeof getOrganizationCandidateEvidence>>, TError = ErrorType<Problem>>(
|
||||
orgId: string,
|
||||
candidateHandle: string, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getOrganizationCandidateEvidence>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
|
||||
, queryClient?: QueryClient
|
||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> } {
|
||||
|
||||
const queryOptions = getGetOrganizationCandidateEvidenceQueryOptions(orgId,candidateHandle,options)
|
||||
|
||||
const query = useQuery(queryOptions, queryClient) as UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||
|
||||
return withQueryKey(query, queryOptions.queryKey);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
export const getListMyEvidenceUrl = (params?: ListMyEvidenceParams,) => {
|
||||
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/evidence?${stringifiedParams}` : `/api/v1/me/evidence`
|
||||
}
|
||||
|
||||
/**
|
||||
* Requires the session cookie of a candidate account. The candidate comes from the session, so the response holds only the caller's own facts. Returns a page, newest event first with the fact identifier as the tie-breaker, with cursor pagination. The response is `Cache-Control: no-store`.
|
||||
*
|
||||
* A fact is derived from the immutable result of a confirmed real assessment (root or corrective), in the same transaction that stores the result. Each fact names its source (the event and the result, which the candidate can open at `GetMyAssessmentResult`), the skills of the event, the grade that was passed with its basis and calibration, the attribution, the date, the visibility, and the trust level. An online assessment without a reliable confirmation of the identity has trust 1. One source event is one fact: its skills are tags of that fact, so several tags never make several facts.
|
||||
*
|
||||
* The list never carries raw answers, items, scores, failed attempts, or anti-cheat data. A failed attempt, a result without a reviewed category source, and an express training run (`demo_express`) create no fact, so reading the list before and after an express run shows no new fact. The list includes facts the candidate hid, with `visibility` `hidden`.
|
||||
*
|
||||
* A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account, or a candidate with an unverified email, answers 403 forbidden. A malformed `limit` or `cursor`, or a cursor of another candidate, answers 400 validation_failed.
|
||||
* @summary List the skill evidence of the current candidate.
|
||||
*/
|
||||
export const listMyEvidence = async (params?: ListMyEvidenceParams, options?: Parameters<typeof apiRequest>[1]): Promise<EvidenceFactList> => {
|
||||
|
||||
return apiRequest<EvidenceFactList>(getListMyEvidenceUrl(params),
|
||||
{
|
||||
...options,
|
||||
method: 'GET'
|
||||
|
||||
|
||||
}
|
||||
);}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
export const getListMyEvidenceQueryKey = (params?: ListMyEvidenceParams,) => {
|
||||
return [
|
||||
`/api/v1/me/evidence`, ...(params ? [params] : [])
|
||||
] as const;
|
||||
}
|
||||
|
||||
|
||||
export const getListMyEvidenceQueryOptions = <TData = Awaited<ReturnType<typeof listMyEvidence>>, TError = ErrorType<Problem>>(params?: ListMyEvidenceParams, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof listMyEvidence>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
|
||||
) => {
|
||||
|
||||
const {query: queryOptions, request: requestOptions} = options ?? {};
|
||||
|
||||
const queryKey = queryOptions?.queryKey ?? getListMyEvidenceQueryKey(params);
|
||||
|
||||
|
||||
|
||||
const queryFn: QueryFunction<Awaited<ReturnType<typeof listMyEvidence>>> = ({ signal }) => listMyEvidence(params, { signal, ...requestOptions });
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
return { queryKey, queryFn, ...queryOptions} as UseQueryOptions<Awaited<ReturnType<typeof listMyEvidence>>, TError, TData> & { queryKey: DataTag<QueryKey, TData, TError> }
|
||||
}
|
||||
|
||||
export type ListMyEvidenceQueryResult = NonNullable<Awaited<ReturnType<typeof listMyEvidence>>>
|
||||
export type ListMyEvidenceQueryError = ErrorType<Problem>
|
||||
|
||||
|
||||
export function useListMyEvidence<TData = Awaited<ReturnType<typeof listMyEvidence>>, TError = ErrorType<Problem>>(
|
||||
params: undefined | ListMyEvidenceParams, options: { query:Partial<UseQueryOptions<Awaited<ReturnType<typeof listMyEvidence>>, TError, TData>> & Pick<
|
||||
DefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof listMyEvidence>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof listMyEvidence>>
|
||||
> , 'initialData'
|
||||
>, request?: SecondParameter<typeof apiRequest>}
|
||||
, queryClient?: QueryClient
|
||||
): DefinedUseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
||||
export function useListMyEvidence<TData = Awaited<ReturnType<typeof listMyEvidence>>, TError = ErrorType<Problem>>(
|
||||
params?: ListMyEvidenceParams, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof listMyEvidence>>, TError, TData>> & Pick<
|
||||
UndefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof listMyEvidence>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof listMyEvidence>>
|
||||
> , 'initialData'
|
||||
>, request?: SecondParameter<typeof apiRequest>}
|
||||
, queryClient?: QueryClient
|
||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
||||
export function useListMyEvidence<TData = Awaited<ReturnType<typeof listMyEvidence>>, TError = ErrorType<Problem>>(
|
||||
params?: ListMyEvidenceParams, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof listMyEvidence>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
|
||||
, queryClient?: QueryClient
|
||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
||||
/**
|
||||
* @summary List the skill evidence of the current candidate.
|
||||
*/
|
||||
|
||||
export function useListMyEvidence<TData = Awaited<ReturnType<typeof listMyEvidence>>, TError = ErrorType<Problem>>(
|
||||
params?: ListMyEvidenceParams, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof listMyEvidence>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
|
||||
, queryClient?: QueryClient
|
||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> } {
|
||||
|
||||
const queryOptions = getListMyEvidenceQueryOptions(params,options)
|
||||
|
||||
const query = useQuery(queryOptions, queryClient) as UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||
|
||||
return withQueryKey(query, queryOptions.queryKey);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ export { getAssessmentMock } from './assessment/assessment.msw'
|
||||
export { getCandidateMock } from './candidate/candidate.msw'
|
||||
export { getCatalogMock } from './catalog/catalog.msw'
|
||||
export { getConsentMock } from './consent/consent.msw'
|
||||
export { getEvidenceMock } from './evidence/evidence.msw'
|
||||
export { getHealthMock } from './health/health.msw'
|
||||
export { getIdentityMock } from './identity/identity.msw'
|
||||
export { getInvitationMock } from './invitation/invitation.msw'
|
||||
|
||||
@@ -2,6 +2,7 @@ export * from './assessment/assessment';
|
||||
export * from './candidate/candidate';
|
||||
export * from './catalog/catalog';
|
||||
export * from './consent/consent';
|
||||
export * from './evidence/evidence';
|
||||
export * from './health/health';
|
||||
export * from './identity/identity';
|
||||
export * from './invitation/invitation';
|
||||
|
||||
@@ -26,6 +26,7 @@ import type {
|
||||
CardPreview,
|
||||
HiddenOrganization,
|
||||
HiddenOrganizationList,
|
||||
OrganizationEvidence,
|
||||
PrivacyEventList,
|
||||
PrivacyOrganization,
|
||||
PrivacySettings,
|
||||
@@ -42,7 +43,9 @@ export const getSetMyPublicationResponseMock = (overrideResponse: Partial<Extrac
|
||||
|
||||
export const getGetMyCardPreviewResponseAnonymousCardContentMock = (overrideResponse: Partial<AnonymousCardContent> = {}): AnonymousCardContent => ({...{pseudonym: fakeFromPattern("^cv1_[A-Za-z0-9_-]{43}$", {minLength: 47, maxLength: 47}), categories: faker.helpers.arrayElement([Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), strength: faker.helpers.arrayElement(['standard','strong'] as const)})), null]), stack: faker.helpers.arrayElement([faker.helpers.arrayElements(['go','postgresql','kafka','docker'] as const), null]), self_assessment: faker.helpers.arrayElement([Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), confirmation_status: faker.helpers.arrayElement(['confirmed','unconfirmed'] as const), declared_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,])})), null]), experience_band: faker.helpers.arrayElement([faker.helpers.arrayElement(['0_1','1_3','3_6','6_plus','0_3','3_plus'] as const),null,]), work_formats: faker.helpers.arrayElement([faker.helpers.arrayElements(['remote','office','hybrid'] as const), null]), salary_compatibility: faker.helpers.arrayElement([faker.helpers.arrayElement(['compatible','not_compatible'] as const),null,])}, ...overrideResponse});
|
||||
|
||||
export const getGetMyCardPreviewResponseMock = (overrideResponse: Partial<Extract<CardPreview, object>> = {}): CardPreview => ({state: faker.helpers.arrayElement(['closed','published'] as const), fields: faker.helpers.arrayElements(['categories','salary_compatibility','self_assessment','stack','experience','soft_skills','location','relocation','work_formats'] as const), card: faker.helpers.arrayElement([{...getGetMyCardPreviewResponseAnonymousCardContentMock()},null,]), generated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', ...overrideResponse})
|
||||
export const getGetMyCardPreviewResponseOrganizationEvidenceMock = (overrideResponse: Partial<OrganizationEvidence> = {}): OrganizationEvidence => ({...{items: Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({skill: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa','go','postgresql','kafka','docker'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), trust: faker.number.int({min: 0, max: 3}), basis: faker.helpers.arrayElement(['synthetic_demo'] as const), calibration_status: faker.helpers.arrayElement(['uncalibrated'] as const), observed_year: faker.number.int({min: 2000, max: 9999})}))}, ...overrideResponse});
|
||||
|
||||
export const getGetMyCardPreviewResponseMock = (overrideResponse: Partial<Extract<CardPreview, object>> = {}): CardPreview => ({state: faker.helpers.arrayElement(['closed','published'] as const), fields: faker.helpers.arrayElements(['categories','salary_compatibility','self_assessment','stack','experience','soft_skills','location','relocation','work_formats'] as const), card: faker.helpers.arrayElement([{...getGetMyCardPreviewResponseAnonymousCardContentMock()},null,]), evidence: faker.helpers.arrayElement([{...getGetMyCardPreviewResponseOrganizationEvidenceMock()},null,]), generated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', ...overrideResponse})
|
||||
|
||||
export const getSetMySearchStatusResponseMock = (overrideResponse: Partial<Extract<SearchStatus, object>> = {}): SearchStatus => ({value: faker.helpers.arrayElement(['looking','not_looking'] as const), lapsed: faker.datatype.boolean(), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), lapses_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), version: faker.number.int({min: 0}), ...overrideResponse})
|
||||
|
||||
|
||||
@@ -397,6 +397,8 @@ export const useSetMyPublication = <TError = ErrorType<Problem>,
|
||||
*
|
||||
* `card` is the closed `AnonymousCardContent` projection. It reaches no private profile or contact schema and contains no name, email, phone, Telegram name, employer, salary figure, account identifier, or profile identifier. Unpublished or unknown values are null. Only allowed canonical skills and generalized experience are exposed; arbitrary profile text and imported excerpts never appear. `categories` contains only confirmed assessment results. Self-assessed grades and work formats appear only through their separate explicit publication choices, and self-assessment never becomes a confirmed category. Salary compatibility is nullable and contains no salary amount.
|
||||
*
|
||||
* `evidence` shows what an organization would read in the evidence section of the card (`GetOrganizationCandidateEvidence`): for each category of the card, the one assessment fact that supports its confirmed grade, with its skill, the passed grade, the trust level, the year, and the basis and calibration (`synthetic_demo`, `uncalibrated`). It is null while `card` is null, and an empty list when the card shows no category or no visible fact supports one. The preview applies no organization or cohort, so an organization can still receive less.
|
||||
*
|
||||
* A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden.
|
||||
* @summary Preview the anonymous card that organizations would read.
|
||||
*/
|
||||
|
||||
@@ -260,14 +260,33 @@ describe("generated AnonymousCardContent", () => {
|
||||
state: "closed",
|
||||
fields: [],
|
||||
card: null,
|
||||
evidence: null,
|
||||
generated_at: "2026-10-06T09:30:00Z",
|
||||
};
|
||||
|
||||
expect(CardPreview.parse(closed)).toEqual(closed);
|
||||
expect(
|
||||
CardPreview.parse({ ...closed, state: "published", fields: ["stack"], card }),
|
||||
CardPreview.parse({
|
||||
...closed,
|
||||
state: "published",
|
||||
fields: ["stack"],
|
||||
card,
|
||||
evidence: {
|
||||
items: [
|
||||
{
|
||||
skill: "backend",
|
||||
grade: "junior",
|
||||
trust: 1,
|
||||
basis: "synthetic_demo",
|
||||
calibration_status: "uncalibrated",
|
||||
observed_year: 2026,
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
).toMatchObject({
|
||||
card: { stack: ["postgresql", "kafka"] },
|
||||
evidence: { items: [{ skill: "backend", trust: 1 }] },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
export const EvidenceAttribution = zod.enum(['personal', 'team_role', 'team_unattributed']).describe('Whose contribution the fact is.\n\n- personal: the candidate\'s own result. Every assessment fact is personal.\n- team_role: a team result with a confirmed role of the candidate.\n- team_unattributed: a team result without a confirmed role; it is not a personal skill.\n\nOnly `personal` is produced today.')
|
||||
|
||||
export type EvidenceAttribution = zod.input<typeof EvidenceAttribution>;
|
||||
export type EvidenceAttributionOutput = zod.output<typeof EvidenceAttribution>;
|
||||
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
export const evidenceFactSkillsMax = 13;
|
||||
|
||||
export const evidenceFactTrustMin = 0;
|
||||
export const evidenceFactTrustMax = 3;
|
||||
|
||||
|
||||
export const EvidenceFact = zod.object({
|
||||
"id": zod.uuid().describe('Identifier of the fact.'),
|
||||
"kind": zod.enum(['claim', 'measurement']).describe('Whether a fact is a statement or an observation.\n\n- claim: something the candidate stated that nothing confirmed separately. Its trust is 0.\n- measurement: a result that a system observed, such as a confirmed assessment. Its trust is 1 to 3.\n\nAssessments produce measurements only. A claim never becomes a measurement by repetition, and the two kinds are stored apart.'),
|
||||
"source": zod.object({
|
||||
"type": zod.enum(['assessment_result']).describe('Where the fact comes from.\n\n- assessment_result: a real (root or corrective) assessment result of this platform that confirmed a grade. An express training run (`demo_express`), a failed attempt, and a result without a reviewed category source are never a source.\n\nAdding a value is a contract change.'),
|
||||
"event_id": zod.uuid().describe('Identifier of the source event. One event is one fact, however many skills it is tagged with.'),
|
||||
"result_id": zod.uuid().describe('Identifier of the immutable result that produced the fact.')
|
||||
}).describe('Where the fact comes from. For an assessment the event is the attempt and the result is the immutable result of that attempt, which the candidate reads at `GetMyAssessmentResult`; the two identifiers are equal because a result is keyed by its attempt.'),
|
||||
"skills": zod.array(zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa', 'go', 'postgresql', 'kafka', 'docker']).describe('A skill tag from a closed set - the specialization codes of the catalog and the technology codes of the anonymous card. An assessment tags its fact with the specialization of the category.')).min(1).max(evidenceFactSkillsMax).describe('Skill tags of the event in ascending order.'),
|
||||
"result": zod.object({
|
||||
"grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),
|
||||
"basis": zod.enum(['synthetic_demo']).describe('What the measurement rests on.\n\n- synthetic_demo: a demonstration category from a synthetic reviewed bank. It shows the mechanics and is not a validated measurement.'),
|
||||
"calibration_status": zod.enum(['uncalibrated']).describe('Calibration of the method behind the result.\n\n- uncalibrated: the thresholds are initial values that no measurement has validated.')
|
||||
}).describe('What the fact says: the grade that was passed and how reliable the method is. It carries no score, answer, item, failure, or anti-cheat data.'),
|
||||
"attribution": zod.enum(['personal', 'team_role', 'team_unattributed']).describe('Whose contribution the fact is.\n\n- personal: the candidate\'s own result. Every assessment fact is personal.\n- team_role: a team result with a confirmed role of the candidate.\n- team_unattributed: a team result without a confirmed role; it is not a personal skill.\n\nOnly `personal` is produced today.'),
|
||||
"trust": zod.int().min(evidenceFactTrustMin).max(evidenceFactTrustMax).describe('Strength of the confirmation.\n\n- 0: stated by the person, not confirmed separately.\n- 1: an observable online result without a reliable confirmation of the identity or the authorship. Every assessment fact has this level today, because the assessment is unproctored and the identity is not confirmed.\n- 2: a result tied to a confirmed identity or confirmed by an independent party.\n- 3: an in-person check with a matching confirmation.\n\nA repeated statement, a sign-in, or a repeated tag of the same event never raises the level.'),
|
||||
"occurred_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.'),
|
||||
"visibility": zod.enum(['visible', 'hidden']).describe('Whether the fact may take part in what an organization reads.\n\n- visible: the fact is eligible for the organization projection. It does not publish the fact: the projection also needs the published card with the `categories` field and an active C2.\n- hidden: the candidate hid the fact. No organization reads it. Hiding never edits or deletes the confirmed result.')
|
||||
}).describe('One independent fact of the current candidate. `occurred_at` is when the source event ended; for an assessment it is the time of the decision. A fact is one source event; the skills of that event are tags of the fact, so a second tag never makes a second fact. Hidden facts are listed here with their visibility, because the candidate owns them.')
|
||||
|
||||
export type EvidenceFact = zod.input<typeof EvidenceFact>;
|
||||
export type EvidenceFactOutput = zod.output<typeof EvidenceFact>;
|
||||
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
export const evidenceFactListItemsItemSkillsMax = 13;
|
||||
|
||||
export const evidenceFactListItemsItemTrustMin = 0;
|
||||
export const evidenceFactListItemsItemTrustMax = 3;
|
||||
|
||||
export const evidenceFactListItemsMax = 100;
|
||||
|
||||
export const evidenceFactListPageNextCursorMax = 512;
|
||||
|
||||
|
||||
export const evidenceFactListPageNextCursorRegExp = new RegExp('^[A-Za-z0-9_-]+$');
|
||||
|
||||
export const EvidenceFactList = zod.object({
|
||||
"items": zod.array(zod.object({
|
||||
"id": zod.uuid().describe('Identifier of the fact.'),
|
||||
"kind": zod.enum(['claim', 'measurement']).describe('Whether a fact is a statement or an observation.\n\n- claim: something the candidate stated that nothing confirmed separately. Its trust is 0.\n- measurement: a result that a system observed, such as a confirmed assessment. Its trust is 1 to 3.\n\nAssessments produce measurements only. A claim never becomes a measurement by repetition, and the two kinds are stored apart.'),
|
||||
"source": zod.object({
|
||||
"type": zod.enum(['assessment_result']).describe('Where the fact comes from.\n\n- assessment_result: a real (root or corrective) assessment result of this platform that confirmed a grade. An express training run (`demo_express`), a failed attempt, and a result without a reviewed category source are never a source.\n\nAdding a value is a contract change.'),
|
||||
"event_id": zod.uuid().describe('Identifier of the source event. One event is one fact, however many skills it is tagged with.'),
|
||||
"result_id": zod.uuid().describe('Identifier of the immutable result that produced the fact.')
|
||||
}).describe('Where the fact comes from. For an assessment the event is the attempt and the result is the immutable result of that attempt, which the candidate reads at `GetMyAssessmentResult`; the two identifiers are equal because a result is keyed by its attempt.'),
|
||||
"skills": zod.array(zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa', 'go', 'postgresql', 'kafka', 'docker']).describe('A skill tag from a closed set - the specialization codes of the catalog and the technology codes of the anonymous card. An assessment tags its fact with the specialization of the category.')).min(1).max(evidenceFactListItemsItemSkillsMax).describe('Skill tags of the event in ascending order.'),
|
||||
"result": zod.object({
|
||||
"grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),
|
||||
"basis": zod.enum(['synthetic_demo']).describe('What the measurement rests on.\n\n- synthetic_demo: a demonstration category from a synthetic reviewed bank. It shows the mechanics and is not a validated measurement.'),
|
||||
"calibration_status": zod.enum(['uncalibrated']).describe('Calibration of the method behind the result.\n\n- uncalibrated: the thresholds are initial values that no measurement has validated.')
|
||||
}).describe('What the fact says: the grade that was passed and how reliable the method is. It carries no score, answer, item, failure, or anti-cheat data.'),
|
||||
"attribution": zod.enum(['personal', 'team_role', 'team_unattributed']).describe('Whose contribution the fact is.\n\n- personal: the candidate\'s own result. Every assessment fact is personal.\n- team_role: a team result with a confirmed role of the candidate.\n- team_unattributed: a team result without a confirmed role; it is not a personal skill.\n\nOnly `personal` is produced today.'),
|
||||
"trust": zod.int().min(evidenceFactListItemsItemTrustMin).max(evidenceFactListItemsItemTrustMax).describe('Strength of the confirmation.\n\n- 0: stated by the person, not confirmed separately.\n- 1: an observable online result without a reliable confirmation of the identity or the authorship. Every assessment fact has this level today, because the assessment is unproctored and the identity is not confirmed.\n- 2: a result tied to a confirmed identity or confirmed by an independent party.\n- 3: an in-person check with a matching confirmation.\n\nA repeated statement, a sign-in, or a repeated tag of the same event never raises the level.'),
|
||||
"occurred_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.'),
|
||||
"visibility": zod.enum(['visible', 'hidden']).describe('Whether the fact may take part in what an organization reads.\n\n- visible: the fact is eligible for the organization projection. It does not publish the fact: the projection also needs the published card with the `categories` field and an active C2.\n- hidden: the candidate hid the fact. No organization reads it. Hiding never edits or deletes the confirmed result.')
|
||||
}).describe('One independent fact of the current candidate. `occurred_at` is when the source event ended; for an assessment it is the time of the decision. A fact is one source event; the skills of that event are tags of the fact, so a second tag never makes a second fact. Hidden facts are listed here with their visibility, because the candidate owns them.')).max(evidenceFactListItemsMax).describe('Facts of the page.'),
|
||||
"page": zod.object({
|
||||
"has_more": zod.boolean().describe('Whether another page follows this one.'),
|
||||
"next_cursor": zod.string().min(1).max(evidenceFactListPageNextCursorMax).regex(evidenceFactListPageNextCursorRegExp).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('One page of the facts of the current candidate, newest event first.')
|
||||
|
||||
export type EvidenceFactList = zod.input<typeof EvidenceFactList>;
|
||||
export type EvidenceFactListOutput = zod.output<typeof EvidenceFactList>;
|
||||
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
export const EvidenceKind = zod.enum(['claim', 'measurement']).describe('Whether a fact is a statement or an observation.\n\n- claim: something the candidate stated that nothing confirmed separately. Its trust is 0.\n- measurement: a result that a system observed, such as a confirmed assessment. Its trust is 1 to 3.\n\nAssessments produce measurements only. A claim never becomes a measurement by repetition, and the two kinds are stored apart.')
|
||||
|
||||
export type EvidenceKind = zod.input<typeof EvidenceKind>;
|
||||
export type EvidenceKindOutput = zod.output<typeof EvidenceKind>;
|
||||
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
export const EvidenceResult = zod.object({
|
||||
"grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),
|
||||
"basis": zod.enum(['synthetic_demo']).describe('What the measurement rests on.\n\n- synthetic_demo: a demonstration category from a synthetic reviewed bank. It shows the mechanics and is not a validated measurement.'),
|
||||
"calibration_status": zod.enum(['uncalibrated']).describe('Calibration of the method behind the result.\n\n- uncalibrated: the thresholds are initial values that no measurement has validated.')
|
||||
}).describe('What the fact says: the grade that was passed and how reliable the method is. It carries no score, answer, item, failure, or anti-cheat data.')
|
||||
|
||||
export type EvidenceResult = zod.input<typeof EvidenceResult>;
|
||||
export type EvidenceResultOutput = zod.output<typeof EvidenceResult>;
|
||||
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
export const EvidenceSource = zod.object({
|
||||
"type": zod.enum(['assessment_result']).describe('Where the fact comes from.\n\n- assessment_result: a real (root or corrective) assessment result of this platform that confirmed a grade. An express training run (`demo_express`), a failed attempt, and a result without a reviewed category source are never a source.\n\nAdding a value is a contract change.'),
|
||||
"event_id": zod.uuid().describe('Identifier of the source event. One event is one fact, however many skills it is tagged with.'),
|
||||
"result_id": zod.uuid().describe('Identifier of the immutable result that produced the fact.')
|
||||
}).describe('Where the fact comes from. For an assessment the event is the attempt and the result is the immutable result of that attempt, which the candidate reads at `GetMyAssessmentResult`; the two identifiers are equal because a result is keyed by its attempt.')
|
||||
|
||||
export type EvidenceSource = zod.input<typeof EvidenceSource>;
|
||||
export type EvidenceSourceOutput = zod.output<typeof EvidenceSource>;
|
||||
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
export const EvidenceSourceType = zod.enum(['assessment_result']).describe('Where the fact comes from.\n\n- assessment_result: a real (root or corrective) assessment result of this platform that confirmed a grade. An express training run (`demo_express`), a failed attempt, and a result without a reviewed category source are never a source.\n\nAdding a value is a contract change.')
|
||||
|
||||
export type EvidenceSourceType = zod.input<typeof EvidenceSourceType>;
|
||||
export type EvidenceSourceTypeOutput = zod.output<typeof EvidenceSourceType>;
|
||||
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
export const EvidenceVisibility = zod.enum(['visible', 'hidden']).describe('Whether the fact may take part in what an organization reads.\n\n- visible: the fact is eligible for the organization projection. It does not publish the fact: the projection also needs the published card with the `categories` field and an active C2.\n- hidden: the candidate hid the fact. No organization reads it. Hiding never edits or deletes the confirmed result.')
|
||||
|
||||
export type EvidenceVisibility = zod.input<typeof EvidenceVisibility>;
|
||||
export type EvidenceVisibilityOutput = zod.output<typeof EvidenceVisibility>;
|
||||
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
|
||||
export * from './evidenceAttribution.zod';
|
||||
export * from './evidenceFact.zod';
|
||||
export * from './evidenceFactList.zod';
|
||||
export * from './evidenceKind.zod';
|
||||
export * from './evidenceResult.zod';
|
||||
export * from './evidenceSource.zod';
|
||||
export * from './evidenceSourceType.zod';
|
||||
export * from './evidenceVisibility.zod';
|
||||
export * from './listMyEvidenceParams.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 listMyEvidenceParamsLimitDefault = 20;
|
||||
export const listMyEvidenceParamsLimitMax = 100;
|
||||
|
||||
export const listMyEvidenceParamsCursorMax = 512;
|
||||
|
||||
|
||||
export const listMyEvidenceParamsCursorRegExp = new RegExp('^[A-Za-z0-9_-]+$');
|
||||
|
||||
export const ListMyEvidenceParams = zod.object({
|
||||
"limit": zod.int().min(1).max(listMyEvidenceParamsLimitMax).default(listMyEvidenceParamsLimitDefault),
|
||||
"cursor": zod.string().min(1).max(listMyEvidenceParamsCursorMax).regex(listMyEvidenceParamsCursorRegExp).exactOptional()
|
||||
})
|
||||
|
||||
export type ListMyEvidenceParams = zod.input<typeof ListMyEvidenceParams>;
|
||||
export type ListMyEvidenceParamsOutput = zod.output<typeof ListMyEvidenceParams>;
|
||||
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
export const EvidenceBasis = zod.enum(['synthetic_demo']).describe('What the measurement rests on.\n\n- synthetic_demo: a demonstration category from a synthetic reviewed bank. It shows the mechanics and is not a validated measurement.')
|
||||
|
||||
export type EvidenceBasis = zod.input<typeof EvidenceBasis>;
|
||||
export type EvidenceBasisOutput = zod.output<typeof EvidenceBasis>;
|
||||
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
export const EvidenceCalibrationStatus = zod.enum(['uncalibrated']).describe('Calibration of the method behind the result.\n\n- uncalibrated: the thresholds are initial values that no measurement has validated.')
|
||||
|
||||
export type EvidenceCalibrationStatus = zod.input<typeof EvidenceCalibrationStatus>;
|
||||
export type EvidenceCalibrationStatusOutput = zod.output<typeof EvidenceCalibrationStatus>;
|
||||
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
export const EvidenceSkillCode = zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa', 'go', 'postgresql', 'kafka', 'docker']).describe('A skill tag from a closed set - the specialization codes of the catalog and the technology codes of the anonymous card. An assessment tags its fact with the specialization of the category.')
|
||||
|
||||
export type EvidenceSkillCode = zod.input<typeof EvidenceSkillCode>;
|
||||
export type EvidenceSkillCodeOutput = zod.output<typeof EvidenceSkillCode>;
|
||||
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
export const EvidenceTrustLevelMin = 0;
|
||||
export const EvidenceTrustLevelMax = 3;
|
||||
|
||||
|
||||
export const EvidenceTrustLevel = zod.int().min(EvidenceTrustLevelMin).max(EvidenceTrustLevelMax).describe('Strength of the confirmation.\n\n- 0: stated by the person, not confirmed separately.\n- 1: an observable online result without a reliable confirmation of the identity or the authorship. Every assessment fact has this level today, because the assessment is unproctored and the identity is not confirmed.\n- 2: a result tied to a confirmed identity or confirmed by an independent party.\n- 3: an in-person check with a matching confirmation.\n\nA repeated statement, a sign-in, or a repeated tag of the same event never raises the level.')
|
||||
|
||||
export type EvidenceTrustLevel = zod.input<typeof EvidenceTrustLevel>;
|
||||
export type EvidenceTrustLevelOutput = zod.output<typeof EvidenceTrustLevel>;
|
||||
@@ -17,12 +17,18 @@ export * from './contactPhoneNumber.zod';
|
||||
export * from './contactTelegramUsername.zod';
|
||||
export * from './currencyCode.zod';
|
||||
export * from './emailAddress.zod';
|
||||
export * from './evidenceBasis.zod';
|
||||
export * from './evidenceCalibrationStatus.zod';
|
||||
export * from './evidenceSkillCode.zod';
|
||||
export * from './evidenceTrustLevel.zod';
|
||||
export * from './gradeCode.zod';
|
||||
export * from './invitationTermsVersion.zod';
|
||||
export * from './needLocationName.zod';
|
||||
export * from './needTaskText.zod';
|
||||
export * from './needVersion.zod';
|
||||
export * from './needVersionLabel.zod';
|
||||
export * from './organizationEvidence.zod';
|
||||
export * from './organizationEvidenceFact.zod';
|
||||
export * from './pageInfo.zod';
|
||||
export * from './problem.zod';
|
||||
export * from './problemCode.zod';
|
||||
@@ -41,6 +47,7 @@ export * from './assessment';
|
||||
export * from './candidate';
|
||||
export * from './catalog';
|
||||
export * from './consent';
|
||||
export * from './evidence';
|
||||
export * from './health';
|
||||
export * from './identity';
|
||||
export * from './invitation';
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
export const organizationEvidenceItemsItemTrustMin = 0;
|
||||
export const organizationEvidenceItemsItemTrustMax = 3;
|
||||
|
||||
export const organizationEvidenceItemsItemObservedYearMin = 2000;
|
||||
export const organizationEvidenceItemsItemObservedYearMax = 9999;
|
||||
|
||||
export const organizationEvidenceItemsMax = 9;
|
||||
|
||||
|
||||
export const OrganizationEvidence = zod.object({
|
||||
"items": zod.array(zod.object({
|
||||
"skill": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa', 'go', 'postgresql', 'kafka', 'docker']).describe('A skill tag from a closed set - the specialization codes of the catalog and the technology codes of the anonymous card. An assessment tags its fact with the specialization of the category.'),
|
||||
"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.'),
|
||||
"trust": zod.int().min(organizationEvidenceItemsItemTrustMin).max(organizationEvidenceItemsItemTrustMax).describe('Strength of the confirmation.\n\n- 0: stated by the person, not confirmed separately.\n- 1: an observable online result without a reliable confirmation of the identity or the authorship. Every assessment fact has this level today, because the assessment is unproctored and the identity is not confirmed.\n- 2: a result tied to a confirmed identity or confirmed by an independent party.\n- 3: an in-person check with a matching confirmation.\n\nA repeated statement, a sign-in, or a repeated tag of the same event never raises the level.'),
|
||||
"basis": zod.enum(['synthetic_demo']).describe('What the measurement rests on.\n\n- synthetic_demo: a demonstration category from a synthetic reviewed bank. It shows the mechanics and is not a validated measurement.'),
|
||||
"calibration_status": zod.enum(['uncalibrated']).describe('Calibration of the method behind the result.\n\n- uncalibrated: the thresholds are initial values that no measurement has validated.'),
|
||||
"observed_year": zod.int().min(organizationEvidenceItemsItemObservedYearMin).max(organizationEvidenceItemsItemObservedYearMax).describe('Year (UTC) when the assessment ended. The month, day, and time stay with the candidate.')
|
||||
}).describe('The one assessment fact that supports a category of the card as an organization reads it: the earliest visible measurement that passed exactly the confirmed grade of that category. A lower grade, a retake, the other tags of the event, the source, the basis, the exact time, and every identifier stay with the candidate. The fact carries no identifier of the fact, the event, the result, or the candidate, so it cannot be joined to a person by a key. It is not unlinkable: the skill, the grade, the trust level, and the year, together with the other values of the card, can narrow a small pool of candidates, and the minimum cohort of the card does not cover the year. `basis` and `calibration_status` are the same for every candidate: they say that the fact comes from a synthetic demonstration and is not calibrated, so a demonstration is never read as a validated measurement. The fact never carries an answer, score, item, failure, signal, or review band.')).max(organizationEvidenceItemsMax).describe('Permitted facts, one for each supported category.')
|
||||
}).describe('The permitted evidence of one candidate card, ordered by skill: at most one fact for each category of the card (at most nine). The list is empty when no visible fact supports a category of the card.')
|
||||
|
||||
export type OrganizationEvidence = zod.input<typeof OrganizationEvidence>;
|
||||
export type OrganizationEvidenceOutput = zod.output<typeof OrganizationEvidence>;
|
||||
@@ -0,0 +1,26 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
export const organizationEvidenceFactTrustMin = 0;
|
||||
export const organizationEvidenceFactTrustMax = 3;
|
||||
|
||||
export const organizationEvidenceFactObservedYearMin = 2000;
|
||||
export const organizationEvidenceFactObservedYearMax = 9999;
|
||||
|
||||
|
||||
export const OrganizationEvidenceFact = zod.object({
|
||||
"skill": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa', 'go', 'postgresql', 'kafka', 'docker']).describe('A skill tag from a closed set - the specialization codes of the catalog and the technology codes of the anonymous card. An assessment tags its fact with the specialization of the category.'),
|
||||
"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.'),
|
||||
"trust": zod.int().min(organizationEvidenceFactTrustMin).max(organizationEvidenceFactTrustMax).describe('Strength of the confirmation.\n\n- 0: stated by the person, not confirmed separately.\n- 1: an observable online result without a reliable confirmation of the identity or the authorship. Every assessment fact has this level today, because the assessment is unproctored and the identity is not confirmed.\n- 2: a result tied to a confirmed identity or confirmed by an independent party.\n- 3: an in-person check with a matching confirmation.\n\nA repeated statement, a sign-in, or a repeated tag of the same event never raises the level.'),
|
||||
"basis": zod.enum(['synthetic_demo']).describe('What the measurement rests on.\n\n- synthetic_demo: a demonstration category from a synthetic reviewed bank. It shows the mechanics and is not a validated measurement.'),
|
||||
"calibration_status": zod.enum(['uncalibrated']).describe('Calibration of the method behind the result.\n\n- uncalibrated: the thresholds are initial values that no measurement has validated.'),
|
||||
"observed_year": zod.int().min(organizationEvidenceFactObservedYearMin).max(organizationEvidenceFactObservedYearMax).describe('Year (UTC) when the assessment ended. The month, day, and time stay with the candidate.')
|
||||
}).describe('The one assessment fact that supports a category of the card as an organization reads it: the earliest visible measurement that passed exactly the confirmed grade of that category. A lower grade, a retake, the other tags of the event, the source, the basis, the exact time, and every identifier stay with the candidate. The fact carries no identifier of the fact, the event, the result, or the candidate, so it cannot be joined to a person by a key. It is not unlinkable: the skill, the grade, the trust level, and the year, together with the other values of the card, can narrow a small pool of candidates, and the minimum cohort of the card does not cover the year. `basis` and `calibration_status` are the same for every candidate: they say that the fact comes from a synthetic demonstration and is not calibrated, so a demonstration is never read as a validated measurement. The fact never carries an answer, score, item, failure, signal, or review band.')
|
||||
|
||||
export type OrganizationEvidenceFact = zod.input<typeof OrganizationEvidenceFact>;
|
||||
export type OrganizationEvidenceFactOutput = zod.output<typeof OrganizationEvidenceFact>;
|
||||
@@ -6,7 +6,7 @@
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
export const CardField = zod.enum(['categories', 'salary_compatibility', 'self_assessment', 'stack', 'experience', 'soft_skills', 'location', 'relocation', 'work_formats']).describe('A group of values of the anonymous candidate card that the candidate chooses to publish. The set is closed and has no value for the full name, a contact, or the lowest salary: the card never carries them, so no choice and no later contract change in this list can publish them by accident. Contacts leave only through the contact grant of an accepted invitation (C4), and the lowest salary never leaves.\n\n- categories: specialization and grade confirmed by an authoritative assessment result.\n- self_assessment: the candidate\'s declared specialization and grade, separate from confirmed categories.\n- stack: only recognized technology codes from the server\'s closed taxonomy.\n- experience: a coarse total-experience band, without employers, periods, or descriptions.\n- work_formats: explicitly selected work formats from the private questionnaire.\n- salary_compatibility: a nullable compatibility outcome with no salary amounts or bounds.\n- soft_skills, location, and relocation: retained only for compatibility in existing saved sets; they are not returned by the anonymous card.\n\nOnly values that the candidate confirmed ever reach the card: an unconfirmed suggestion (status `extracted`) and an unknown value never do, whatever the field set says.\n\nAdding a value is a contract change that lets a candidate publish more, and it is also a migration (the function `candidate_card_fields_are_canonical` and the CHECK constraints of the publication and event tables list the codes). A client treats an unknown value as a reason to ask for an update, and the server never adds a new value to a published set on its own.')
|
||||
export const CardField = zod.enum(['categories', 'salary_compatibility', 'self_assessment', 'stack', 'experience', 'soft_skills', 'location', 'relocation', 'work_formats']).describe('A group of values of the anonymous candidate card that the candidate chooses to publish. The set is closed and has no value for the full name, a contact, or the lowest salary: the card never carries them, so no choice and no later contract change in this list can publish them by accident. Contacts leave only through the contact grant of an accepted invitation (C4), and the lowest salary never leaves.\n\n- categories: specialization and grade confirmed by an authoritative assessment result. With it an organization receives the confirmed category and, with each category of the card, one supporting assessment fact: its skill, the passed grade, the trust level, the year of the assessment, and the basis and calibration that mark a synthetic, uncalibrated demonstration (`GetOrganizationCandidateEvidence`). The candidate sees the same on `GetMyCardPreview`.\n- self_assessment: the candidate\'s declared specialization and grade, separate from confirmed categories.\n- stack: only recognized technology codes from the server\'s closed taxonomy.\n- experience: a coarse total-experience band, without employers, periods, or descriptions.\n- work_formats: explicitly selected work formats from the private questionnaire.\n- salary_compatibility: a nullable compatibility outcome with no salary amounts or bounds.\n- soft_skills, location, and relocation: retained only for compatibility in existing saved sets; they are not returned by the anonymous card.\n\nOnly values that the candidate confirmed ever reach the card: an unconfirmed suggestion (status `extracted`) and an unknown value never do, whatever the field set says.\n\nAdding a value is a contract change that lets a candidate publish more, and it is also a migration (the function `candidate_card_fields_are_canonical` and the CHECK constraints of the publication and event tables list the codes). A client treats an unknown value as a reason to ask for an update, and the server never adds a new value to a published set on its own.')
|
||||
|
||||
export type CardField = zod.input<typeof CardField>;
|
||||
export type CardFieldOutput = zod.output<typeof CardField>;
|
||||
@@ -10,7 +10,7 @@ export const CardFieldSetMin = 0;
|
||||
export const CardFieldSetMax = 9;
|
||||
|
||||
|
||||
export const CardFieldSet = zod.array(zod.enum(['categories', 'salary_compatibility', 'self_assessment', 'stack', 'experience', 'soft_skills', 'location', 'relocation', 'work_formats']).describe('A group of values of the anonymous candidate card that the candidate chooses to publish. The set is closed and has no value for the full name, a contact, or the lowest salary: the card never carries them, so no choice and no later contract change in this list can publish them by accident. Contacts leave only through the contact grant of an accepted invitation (C4), and the lowest salary never leaves.\n\n- categories: specialization and grade confirmed by an authoritative assessment result.\n- self_assessment: the candidate\'s declared specialization and grade, separate from confirmed categories.\n- stack: only recognized technology codes from the server\'s closed taxonomy.\n- experience: a coarse total-experience band, without employers, periods, or descriptions.\n- work_formats: explicitly selected work formats from the private questionnaire.\n- salary_compatibility: a nullable compatibility outcome with no salary amounts or bounds.\n- soft_skills, location, and relocation: retained only for compatibility in existing saved sets; they are not returned by the anonymous card.\n\nOnly values that the candidate confirmed ever reach the card: an unconfirmed suggestion (status `extracted`) and an unknown value never do, whatever the field set says.\n\nAdding a value is a contract change that lets a candidate publish more, and it is also a migration (the function `candidate_card_fields_are_canonical` and the CHECK constraints of the publication and event tables list the codes). A client treats an unknown value as a reason to ask for an update, and the server never adds a new value to a published set on its own.')).min(CardFieldSetMin).max(CardFieldSetMax).describe('Distinct card fields. The server stores them in ascending order of the codes and answers them in that order, whatever order the client sent, so equal sets are equal arrays.')
|
||||
export const CardFieldSet = zod.array(zod.enum(['categories', 'salary_compatibility', 'self_assessment', 'stack', 'experience', 'soft_skills', 'location', 'relocation', 'work_formats']).describe('A group of values of the anonymous candidate card that the candidate chooses to publish. The set is closed and has no value for the full name, a contact, or the lowest salary: the card never carries them, so no choice and no later contract change in this list can publish them by accident. Contacts leave only through the contact grant of an accepted invitation (C4), and the lowest salary never leaves.\n\n- categories: specialization and grade confirmed by an authoritative assessment result. With it an organization receives the confirmed category and, with each category of the card, one supporting assessment fact: its skill, the passed grade, the trust level, the year of the assessment, and the basis and calibration that mark a synthetic, uncalibrated demonstration (`GetOrganizationCandidateEvidence`). The candidate sees the same on `GetMyCardPreview`.\n- self_assessment: the candidate\'s declared specialization and grade, separate from confirmed categories.\n- stack: only recognized technology codes from the server\'s closed taxonomy.\n- experience: a coarse total-experience band, without employers, periods, or descriptions.\n- work_formats: explicitly selected work formats from the private questionnaire.\n- salary_compatibility: a nullable compatibility outcome with no salary amounts or bounds.\n- soft_skills, location, and relocation: retained only for compatibility in existing saved sets; they are not returned by the anonymous card.\n\nOnly values that the candidate confirmed ever reach the card: an unconfirmed suggestion (status `extracted`) and an unknown value never do, whatever the field set says.\n\nAdding a value is a contract change that lets a candidate publish more, and it is also a migration (the function `candidate_card_fields_are_canonical` and the CHECK constraints of the publication and event tables list the codes). A client treats an unknown value as a reason to ask for an update, and the server never adds a new value to a published set on its own.')).min(CardFieldSetMin).max(CardFieldSetMax).describe('Distinct card fields. The server stores them in ascending order of the codes and answers them in that order, whatever order the client sent, so equal sets are equal arrays.')
|
||||
|
||||
export type CardFieldSet = zod.input<typeof CardFieldSet>;
|
||||
export type CardFieldSetOutput = zod.output<typeof CardFieldSet>;
|
||||
@@ -22,10 +22,18 @@ export const cardPreviewCardOneSelfAssessmentMax = 9;
|
||||
|
||||
export const cardPreviewCardOneWorkFormatsMax = 3;
|
||||
|
||||
export const cardPreviewEvidenceOneItemsItemTrustMin = 0;
|
||||
export const cardPreviewEvidenceOneItemsItemTrustMax = 3;
|
||||
|
||||
export const cardPreviewEvidenceOneItemsItemObservedYearMin = 2000;
|
||||
export const cardPreviewEvidenceOneItemsItemObservedYearMax = 9999;
|
||||
|
||||
export const cardPreviewEvidenceOneItemsMax = 9;
|
||||
|
||||
|
||||
export const CardPreview = zod.object({
|
||||
"state": zod.enum(['closed', 'published']).describe('Whether the candidate card can be read by organizations at all. It is computed from the stored publication and the consent ledger: a profile is closed unless the candidate published it and the C2 consent that backs the publication is still unrevoked.\n\n- closed: no organization reads the card. This is the state of every new profile and of a profile whose publication was closed or whose C2 was revoked.\n- published: organizations may read exactly the fields in `fields`, except for the organizations the candidate hid.'),
|
||||
"fields": zod.array(zod.enum(['categories', 'salary_compatibility', 'self_assessment', 'stack', 'experience', 'soft_skills', 'location', 'relocation', 'work_formats']).describe('A group of values of the anonymous candidate card that the candidate chooses to publish. The set is closed and has no value for the full name, a contact, or the lowest salary: the card never carries them, so no choice and no later contract change in this list can publish them by accident. Contacts leave only through the contact grant of an accepted invitation (C4), and the lowest salary never leaves.\n\n- categories: specialization and grade confirmed by an authoritative assessment result.\n- self_assessment: the candidate\'s declared specialization and grade, separate from confirmed categories.\n- stack: only recognized technology codes from the server\'s closed taxonomy.\n- experience: a coarse total-experience band, without employers, periods, or descriptions.\n- work_formats: explicitly selected work formats from the private questionnaire.\n- salary_compatibility: a nullable compatibility outcome with no salary amounts or bounds.\n- soft_skills, location, and relocation: retained only for compatibility in existing saved sets; they are not returned by the anonymous card.\n\nOnly values that the candidate confirmed ever reach the card: an unconfirmed suggestion (status `extracted`) and an unknown value never do, whatever the field set says.\n\nAdding a value is a contract change that lets a candidate publish more, and it is also a migration (the function `candidate_card_fields_are_canonical` and the CHECK constraints of the publication and event tables list the codes). A client treats an unknown value as a reason to ask for an update, and the server never adds a new value to a published set on its own.')).min(cardPreviewFieldsMin).max(cardPreviewFieldsMax).describe('Distinct card fields. The server stores them in ascending order of the codes and answers them in that order, whatever order the client sent, so equal sets are equal arrays.'),
|
||||
"fields": zod.array(zod.enum(['categories', 'salary_compatibility', 'self_assessment', 'stack', 'experience', 'soft_skills', 'location', 'relocation', 'work_formats']).describe('A group of values of the anonymous candidate card that the candidate chooses to publish. The set is closed and has no value for the full name, a contact, or the lowest salary: the card never carries them, so no choice and no later contract change in this list can publish them by accident. Contacts leave only through the contact grant of an accepted invitation (C4), and the lowest salary never leaves.\n\n- categories: specialization and grade confirmed by an authoritative assessment result. With it an organization receives the confirmed category and, with each category of the card, one supporting assessment fact: its skill, the passed grade, the trust level, the year of the assessment, and the basis and calibration that mark a synthetic, uncalibrated demonstration (`GetOrganizationCandidateEvidence`). The candidate sees the same on `GetMyCardPreview`.\n- self_assessment: the candidate\'s declared specialization and grade, separate from confirmed categories.\n- stack: only recognized technology codes from the server\'s closed taxonomy.\n- experience: a coarse total-experience band, without employers, periods, or descriptions.\n- work_formats: explicitly selected work formats from the private questionnaire.\n- salary_compatibility: a nullable compatibility outcome with no salary amounts or bounds.\n- soft_skills, location, and relocation: retained only for compatibility in existing saved sets; they are not returned by the anonymous card.\n\nOnly values that the candidate confirmed ever reach the card: an unconfirmed suggestion (status `extracted`) and an unknown value never do, whatever the field set says.\n\nAdding a value is a contract change that lets a candidate publish more, and it is also a migration (the function `candidate_card_fields_are_canonical` and the CHECK constraints of the publication and event tables list the codes). A client treats an unknown value as a reason to ask for an update, and the server never adds a new value to a published set on its own.')).min(cardPreviewFieldsMin).max(cardPreviewFieldsMax).describe('Distinct card fields. The server stores them in ascending order of the codes and answers them in that order, whatever order the client sent, so equal sets are equal arrays.'),
|
||||
"card": zod.union([zod.object({
|
||||
"pseudonym": zod.string().min(cardPreviewCardOnePseudonymMin).max(cardPreviewCardOnePseudonymMax).regex(cardPreviewCardOnePseudonymRegExp).describe('Stable opaque alias scoped to the reading organization. It is not an account or profile identifier and changes across organizations.'),
|
||||
"categories": zod.array(zod.object({
|
||||
@@ -43,8 +51,18 @@ export const CardPreview = zod.object({
|
||||
"work_formats": zod.array(zod.enum(['remote', 'office', 'hybrid'])).max(cardPreviewCardOneWorkFormatsMax).nullable().describe('Explicitly opted-in work formats, or null.'),
|
||||
"salary_compatibility": zod.union([zod.enum(['compatible', 'not_compatible']).describe('A coarse compatibility result only. No salary amount, minimum, range, or threshold is part of the anonymous card.'),zod.null()]).describe('Nullable compatibility result with no salary values.')
|
||||
}).describe('The anonymous candidate card as an organization reads it. Only explicitly published values reach it; unconfirmed stack suggestions and unknown values never do. Stack output uses a closed taxonomy. It carries no name, contact, resume text, employer, salary figure, account or profile identifier, and no schema of the private profile or of a contact disclosure is reachable from it; a contact reaches an organization only through the contact grant of an accepted invitation. Each property is null when its field is not published or the candidate has no value for it, so the card does not tell the two apart. The set of properties is closed, and an organization-visible card must never gain a property that identifies the candidate. The search ranking and the full card of an organization\'s search result are defined by the search contract, which reuses this content.'),zod.null()]),
|
||||
"evidence": zod.union([zod.object({
|
||||
"items": zod.array(zod.object({
|
||||
"skill": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa', 'go', 'postgresql', 'kafka', 'docker']).describe('A skill tag from a closed set - the specialization codes of the catalog and the technology codes of the anonymous card. An assessment tags its fact with the specialization of the category.'),
|
||||
"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.'),
|
||||
"trust": zod.int().min(cardPreviewEvidenceOneItemsItemTrustMin).max(cardPreviewEvidenceOneItemsItemTrustMax).describe('Strength of the confirmation.\n\n- 0: stated by the person, not confirmed separately.\n- 1: an observable online result without a reliable confirmation of the identity or the authorship. Every assessment fact has this level today, because the assessment is unproctored and the identity is not confirmed.\n- 2: a result tied to a confirmed identity or confirmed by an independent party.\n- 3: an in-person check with a matching confirmation.\n\nA repeated statement, a sign-in, or a repeated tag of the same event never raises the level.'),
|
||||
"basis": zod.enum(['synthetic_demo']).describe('What the measurement rests on.\n\n- synthetic_demo: a demonstration category from a synthetic reviewed bank. It shows the mechanics and is not a validated measurement.'),
|
||||
"calibration_status": zod.enum(['uncalibrated']).describe('Calibration of the method behind the result.\n\n- uncalibrated: the thresholds are initial values that no measurement has validated.'),
|
||||
"observed_year": zod.int().min(cardPreviewEvidenceOneItemsItemObservedYearMin).max(cardPreviewEvidenceOneItemsItemObservedYearMax).describe('Year (UTC) when the assessment ended. The month, day, and time stay with the candidate.')
|
||||
}).describe('The one assessment fact that supports a category of the card as an organization reads it: the earliest visible measurement that passed exactly the confirmed grade of that category. A lower grade, a retake, the other tags of the event, the source, the basis, the exact time, and every identifier stay with the candidate. The fact carries no identifier of the fact, the event, the result, or the candidate, so it cannot be joined to a person by a key. It is not unlinkable: the skill, the grade, the trust level, and the year, together with the other values of the card, can narrow a small pool of candidates, and the minimum cohort of the card does not cover the year. `basis` and `calibration_status` are the same for every candidate: they say that the fact comes from a synthetic demonstration and is not calibrated, so a demonstration is never read as a validated measurement. The fact never carries an answer, score, item, failure, signal, or review band.')).max(cardPreviewEvidenceOneItemsMax).describe('Permitted facts, one for each supported category.')
|
||||
}).describe('The permitted evidence of one candidate card, ordered by skill: at most one fact for each category of the card (at most nine). The list is empty when no visible fact supports a category of the card.'),zod.null()]),
|
||||
"generated_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('A private candidate preview computed from the current profile, publication, and consent ledger. Its pseudonym uses a separate preview context and is not an organization\'s alias. Organization-specific visibility filters and cohort checks can further generalize or suppress the organization-facing card. This read creates no view or history record and never reaches an organization. `card` is null while the profile is closed.')
|
||||
}).describe('A private candidate preview computed from the current profile, publication, and consent ledger. Its pseudonym uses a separate preview context and is not an organization\'s alias. Organization-specific visibility filters and cohort checks can further generalize or suppress the organization-facing card. This read creates no view or history record and never reaches an organization. `card` is null while the profile is closed. `evidence` is what an organization would read in the evidence section of the card, one supporting assessment fact for each category of the card, and is null exactly when `card` is null; the organization-facing section can still be generalized or suppressed.')
|
||||
|
||||
export type CardPreview = zod.input<typeof CardPreview>;
|
||||
export type CardPreviewOutput = zod.output<typeof CardPreview>;
|
||||
@@ -16,7 +16,7 @@ export const PrivacyEvent = zod.object({
|
||||
"id": zod.uuid().describe('Identifier of the event.'),
|
||||
"kind": zod.enum(['publication_opened', 'publication_changed', 'publication_closed', 'search_status_confirmed', 'search_status_cleared', 'organization_hidden', 'organization_unhidden']).describe('Kind of a change of the visibility settings that the history records.\n\n- publication_opened: the candidate published a closed profile.\n- publication_changed: the candidate changed the published fields of a published profile, or published it again under a new C2 record.\n- publication_closed: the candidate closed the publication. A revocation of C2 closes the card by the ledger and is read from the consent history, not recorded here.\n- search_status_confirmed: the candidate set or confirmed `looking`.\n- search_status_cleared: the candidate set `not_looking`. A lapse is not an event: it is computed.\n- organization_hidden: the candidate hid the profile from an organization.\n- organization_unhidden: the candidate lifted the hiding for an organization.'),
|
||||
"occurred_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.'),
|
||||
"fields": zod.union([zod.array(zod.enum(['categories', 'salary_compatibility', 'self_assessment', 'stack', 'experience', 'soft_skills', 'location', 'relocation', 'work_formats']).describe('A group of values of the anonymous candidate card that the candidate chooses to publish. The set is closed and has no value for the full name, a contact, or the lowest salary: the card never carries them, so no choice and no later contract change in this list can publish them by accident. Contacts leave only through the contact grant of an accepted invitation (C4), and the lowest salary never leaves.\n\n- categories: specialization and grade confirmed by an authoritative assessment result.\n- self_assessment: the candidate\'s declared specialization and grade, separate from confirmed categories.\n- stack: only recognized technology codes from the server\'s closed taxonomy.\n- experience: a coarse total-experience band, without employers, periods, or descriptions.\n- work_formats: explicitly selected work formats from the private questionnaire.\n- salary_compatibility: a nullable compatibility outcome with no salary amounts or bounds.\n- soft_skills, location, and relocation: retained only for compatibility in existing saved sets; they are not returned by the anonymous card.\n\nOnly values that the candidate confirmed ever reach the card: an unconfirmed suggestion (status `extracted`) and an unknown value never do, whatever the field set says.\n\nAdding a value is a contract change that lets a candidate publish more, and it is also a migration (the function `candidate_card_fields_are_canonical` and the CHECK constraints of the publication and event tables list the codes). A client treats an unknown value as a reason to ask for an update, and the server never adds a new value to a published set on its own.')).min(privacyEventFieldsOneMin).max(privacyEventFieldsOneMax).describe('Distinct card fields. The server stores them in ascending order of the codes and answers them in that order, whatever order the client sent, so equal sets are equal arrays.'),zod.null()]).describe('Published fields after the change for `publication_opened` and `publication_changed`, an empty set for `publication_closed`, and null for every other kind.'),
|
||||
"fields": zod.union([zod.array(zod.enum(['categories', 'salary_compatibility', 'self_assessment', 'stack', 'experience', 'soft_skills', 'location', 'relocation', 'work_formats']).describe('A group of values of the anonymous candidate card that the candidate chooses to publish. The set is closed and has no value for the full name, a contact, or the lowest salary: the card never carries them, so no choice and no later contract change in this list can publish them by accident. Contacts leave only through the contact grant of an accepted invitation (C4), and the lowest salary never leaves.\n\n- categories: specialization and grade confirmed by an authoritative assessment result. With it an organization receives the confirmed category and, with each category of the card, one supporting assessment fact: its skill, the passed grade, the trust level, the year of the assessment, and the basis and calibration that mark a synthetic, uncalibrated demonstration (`GetOrganizationCandidateEvidence`). The candidate sees the same on `GetMyCardPreview`.\n- self_assessment: the candidate\'s declared specialization and grade, separate from confirmed categories.\n- stack: only recognized technology codes from the server\'s closed taxonomy.\n- experience: a coarse total-experience band, without employers, periods, or descriptions.\n- work_formats: explicitly selected work formats from the private questionnaire.\n- salary_compatibility: a nullable compatibility outcome with no salary amounts or bounds.\n- soft_skills, location, and relocation: retained only for compatibility in existing saved sets; they are not returned by the anonymous card.\n\nOnly values that the candidate confirmed ever reach the card: an unconfirmed suggestion (status `extracted`) and an unknown value never do, whatever the field set says.\n\nAdding a value is a contract change that lets a candidate publish more, and it is also a migration (the function `candidate_card_fields_are_canonical` and the CHECK constraints of the publication and event tables list the codes). A client treats an unknown value as a reason to ask for an update, and the server never adds a new value to a published set on its own.')).min(privacyEventFieldsOneMin).max(privacyEventFieldsOneMax).describe('Distinct card fields. The server stores them in ascending order of the codes and answers them in that order, whatever order the client sent, so equal sets are equal arrays.'),zod.null()]).describe('Published fields after the change for `publication_opened` and `publication_changed`, an empty set for `publication_closed`, and null for every other kind.'),
|
||||
"consent_id": zod.union([zod.uuid(),zod.null()]).describe('C2 record that backs the publication, for `publication_opened` and `publication_changed`, or null.'),
|
||||
"organization": zod.union([zod.object({
|
||||
"id": zod.uuid().describe('Identifier of the organization.'),
|
||||
|
||||
@@ -23,7 +23,7 @@ export const PrivacyEventList = zod.object({
|
||||
"id": zod.uuid().describe('Identifier of the event.'),
|
||||
"kind": zod.enum(['publication_opened', 'publication_changed', 'publication_closed', 'search_status_confirmed', 'search_status_cleared', 'organization_hidden', 'organization_unhidden']).describe('Kind of a change of the visibility settings that the history records.\n\n- publication_opened: the candidate published a closed profile.\n- publication_changed: the candidate changed the published fields of a published profile, or published it again under a new C2 record.\n- publication_closed: the candidate closed the publication. A revocation of C2 closes the card by the ledger and is read from the consent history, not recorded here.\n- search_status_confirmed: the candidate set or confirmed `looking`.\n- search_status_cleared: the candidate set `not_looking`. A lapse is not an event: it is computed.\n- organization_hidden: the candidate hid the profile from an organization.\n- organization_unhidden: the candidate lifted the hiding for an organization.'),
|
||||
"occurred_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.'),
|
||||
"fields": zod.union([zod.array(zod.enum(['categories', 'salary_compatibility', 'self_assessment', 'stack', 'experience', 'soft_skills', 'location', 'relocation', 'work_formats']).describe('A group of values of the anonymous candidate card that the candidate chooses to publish. The set is closed and has no value for the full name, a contact, or the lowest salary: the card never carries them, so no choice and no later contract change in this list can publish them by accident. Contacts leave only through the contact grant of an accepted invitation (C4), and the lowest salary never leaves.\n\n- categories: specialization and grade confirmed by an authoritative assessment result.\n- self_assessment: the candidate\'s declared specialization and grade, separate from confirmed categories.\n- stack: only recognized technology codes from the server\'s closed taxonomy.\n- experience: a coarse total-experience band, without employers, periods, or descriptions.\n- work_formats: explicitly selected work formats from the private questionnaire.\n- salary_compatibility: a nullable compatibility outcome with no salary amounts or bounds.\n- soft_skills, location, and relocation: retained only for compatibility in existing saved sets; they are not returned by the anonymous card.\n\nOnly values that the candidate confirmed ever reach the card: an unconfirmed suggestion (status `extracted`) and an unknown value never do, whatever the field set says.\n\nAdding a value is a contract change that lets a candidate publish more, and it is also a migration (the function `candidate_card_fields_are_canonical` and the CHECK constraints of the publication and event tables list the codes). A client treats an unknown value as a reason to ask for an update, and the server never adds a new value to a published set on its own.')).min(privacyEventListItemsItemFieldsOneMin).max(privacyEventListItemsItemFieldsOneMax).describe('Distinct card fields. The server stores them in ascending order of the codes and answers them in that order, whatever order the client sent, so equal sets are equal arrays.'),zod.null()]).describe('Published fields after the change for `publication_opened` and `publication_changed`, an empty set for `publication_closed`, and null for every other kind.'),
|
||||
"fields": zod.union([zod.array(zod.enum(['categories', 'salary_compatibility', 'self_assessment', 'stack', 'experience', 'soft_skills', 'location', 'relocation', 'work_formats']).describe('A group of values of the anonymous candidate card that the candidate chooses to publish. The set is closed and has no value for the full name, a contact, or the lowest salary: the card never carries them, so no choice and no later contract change in this list can publish them by accident. Contacts leave only through the contact grant of an accepted invitation (C4), and the lowest salary never leaves.\n\n- categories: specialization and grade confirmed by an authoritative assessment result. With it an organization receives the confirmed category and, with each category of the card, one supporting assessment fact: its skill, the passed grade, the trust level, the year of the assessment, and the basis and calibration that mark a synthetic, uncalibrated demonstration (`GetOrganizationCandidateEvidence`). The candidate sees the same on `GetMyCardPreview`.\n- self_assessment: the candidate\'s declared specialization and grade, separate from confirmed categories.\n- stack: only recognized technology codes from the server\'s closed taxonomy.\n- experience: a coarse total-experience band, without employers, periods, or descriptions.\n- work_formats: explicitly selected work formats from the private questionnaire.\n- salary_compatibility: a nullable compatibility outcome with no salary amounts or bounds.\n- soft_skills, location, and relocation: retained only for compatibility in existing saved sets; they are not returned by the anonymous card.\n\nOnly values that the candidate confirmed ever reach the card: an unconfirmed suggestion (status `extracted`) and an unknown value never do, whatever the field set says.\n\nAdding a value is a contract change that lets a candidate publish more, and it is also a migration (the function `candidate_card_fields_are_canonical` and the CHECK constraints of the publication and event tables list the codes). A client treats an unknown value as a reason to ask for an update, and the server never adds a new value to a published set on its own.')).min(privacyEventListItemsItemFieldsOneMin).max(privacyEventListItemsItemFieldsOneMax).describe('Distinct card fields. The server stores them in ascending order of the codes and answers them in that order, whatever order the client sent, so equal sets are equal arrays.'),zod.null()]).describe('Published fields after the change for `publication_opened` and `publication_changed`, an empty set for `publication_closed`, and null for every other kind.'),
|
||||
"consent_id": zod.union([zod.uuid(),zod.null()]).describe('C2 record that backs the publication, for `publication_opened` and `publication_changed`, or null.'),
|
||||
"organization": zod.union([zod.object({
|
||||
"id": zod.uuid().describe('Identifier of the organization.'),
|
||||
|
||||
@@ -21,7 +21,7 @@ export const PrivacySettings = zod.object({
|
||||
"publication": zod.object({
|
||||
"state": zod.enum(['closed', 'published']).describe('Whether the candidate card can be read by organizations at all. It is computed from the stored publication and the consent ledger: a profile is closed unless the candidate published it and the C2 consent that backs the publication is still unrevoked.\n\n- closed: no organization reads the card. This is the state of every new profile and of a profile whose publication was closed or whose C2 was revoked.\n- published: organizations may read exactly the fields in `fields`, except for the organizations the candidate hid.'),
|
||||
"closed_reason": zod.union([zod.enum(['never_published', 'closed_by_candidate', 'consent_revoked']).describe('Why a closed profile is closed, shown only to the candidate.\n\n- never_published: the candidate has never published the profile.\n- closed_by_candidate: the candidate closed the publication.\n- consent_revoked: the C2 consent that backed the publication was revoked. A later C2 grant never reopens the publication; the candidate publishes again explicitly and the new publication refers to the new consent record.'),zod.null()]).describe('Why the profile is closed, or null while it is published.'),
|
||||
"fields": zod.array(zod.enum(['categories', 'salary_compatibility', 'self_assessment', 'stack', 'experience', 'soft_skills', 'location', 'relocation', 'work_formats']).describe('A group of values of the anonymous candidate card that the candidate chooses to publish. The set is closed and has no value for the full name, a contact, or the lowest salary: the card never carries them, so no choice and no later contract change in this list can publish them by accident. Contacts leave only through the contact grant of an accepted invitation (C4), and the lowest salary never leaves.\n\n- categories: specialization and grade confirmed by an authoritative assessment result.\n- self_assessment: the candidate\'s declared specialization and grade, separate from confirmed categories.\n- stack: only recognized technology codes from the server\'s closed taxonomy.\n- experience: a coarse total-experience band, without employers, periods, or descriptions.\n- work_formats: explicitly selected work formats from the private questionnaire.\n- salary_compatibility: a nullable compatibility outcome with no salary amounts or bounds.\n- soft_skills, location, and relocation: retained only for compatibility in existing saved sets; they are not returned by the anonymous card.\n\nOnly values that the candidate confirmed ever reach the card: an unconfirmed suggestion (status `extracted`) and an unknown value never do, whatever the field set says.\n\nAdding a value is a contract change that lets a candidate publish more, and it is also a migration (the function `candidate_card_fields_are_canonical` and the CHECK constraints of the publication and event tables list the codes). A client treats an unknown value as a reason to ask for an update, and the server never adds a new value to a published set on its own.')).min(privacySettingsPublicationFieldsOneMin).max(privacySettingsPublicationFieldsOneMax).describe('Distinct card fields. The server stores them in ascending order of the codes and answers them in that order, whatever order the client sent, so equal sets are equal arrays.').describe('Card fields that organizations may read. Empty exactly when `state` is `closed`.'),
|
||||
"fields": zod.array(zod.enum(['categories', 'salary_compatibility', 'self_assessment', 'stack', 'experience', 'soft_skills', 'location', 'relocation', 'work_formats']).describe('A group of values of the anonymous candidate card that the candidate chooses to publish. The set is closed and has no value for the full name, a contact, or the lowest salary: the card never carries them, so no choice and no later contract change in this list can publish them by accident. Contacts leave only through the contact grant of an accepted invitation (C4), and the lowest salary never leaves.\n\n- categories: specialization and grade confirmed by an authoritative assessment result. With it an organization receives the confirmed category and, with each category of the card, one supporting assessment fact: its skill, the passed grade, the trust level, the year of the assessment, and the basis and calibration that mark a synthetic, uncalibrated demonstration (`GetOrganizationCandidateEvidence`). The candidate sees the same on `GetMyCardPreview`.\n- self_assessment: the candidate\'s declared specialization and grade, separate from confirmed categories.\n- stack: only recognized technology codes from the server\'s closed taxonomy.\n- experience: a coarse total-experience band, without employers, periods, or descriptions.\n- work_formats: explicitly selected work formats from the private questionnaire.\n- salary_compatibility: a nullable compatibility outcome with no salary amounts or bounds.\n- soft_skills, location, and relocation: retained only for compatibility in existing saved sets; they are not returned by the anonymous card.\n\nOnly values that the candidate confirmed ever reach the card: an unconfirmed suggestion (status `extracted`) and an unknown value never do, whatever the field set says.\n\nAdding a value is a contract change that lets a candidate publish more, and it is also a migration (the function `candidate_card_fields_are_canonical` and the CHECK constraints of the publication and event tables list the codes). A client treats an unknown value as a reason to ask for an update, and the server never adds a new value to a published set on its own.')).min(privacySettingsPublicationFieldsOneMin).max(privacySettingsPublicationFieldsOneMax).describe('Distinct card fields. The server stores them in ascending order of the codes and answers them in that order, whatever order the client sent, so equal sets are equal arrays.').describe('Card fields that organizations may read. Empty exactly when `state` is `closed`.'),
|
||||
"consent_id": zod.union([zod.uuid(),zod.null()]).describe('Identifier of the C2 record of the consent ledger that backs the current or the last publication, the `id` of a `ConsentRecord` of this account, or null when the profile was never published.'),
|
||||
"published_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('Moment of the latest change that published or republished the card, or null while the profile was never published. It stays after a closing, as the time of the last publication.'),
|
||||
"version": zod.int().min(privacySettingsPublicationVersionMin).describe('Version of the publication setting of the candidate. A candidate who has never published has version 0 and the profile is closed; every change that alters the setting advances it by one. The client sends the version it read as `expected_version`. It is independent of the versions of the profile and of the search status, so a change of one never makes another stale.')
|
||||
|
||||
@@ -15,7 +15,7 @@ export const publicationVersionMin = 0;
|
||||
export const Publication = zod.object({
|
||||
"state": zod.enum(['closed', 'published']).describe('Whether the candidate card can be read by organizations at all. It is computed from the stored publication and the consent ledger: a profile is closed unless the candidate published it and the C2 consent that backs the publication is still unrevoked.\n\n- closed: no organization reads the card. This is the state of every new profile and of a profile whose publication was closed or whose C2 was revoked.\n- published: organizations may read exactly the fields in `fields`, except for the organizations the candidate hid.'),
|
||||
"closed_reason": zod.union([zod.enum(['never_published', 'closed_by_candidate', 'consent_revoked']).describe('Why a closed profile is closed, shown only to the candidate.\n\n- never_published: the candidate has never published the profile.\n- closed_by_candidate: the candidate closed the publication.\n- consent_revoked: the C2 consent that backed the publication was revoked. A later C2 grant never reopens the publication; the candidate publishes again explicitly and the new publication refers to the new consent record.'),zod.null()]).describe('Why the profile is closed, or null while it is published.'),
|
||||
"fields": zod.array(zod.enum(['categories', 'salary_compatibility', 'self_assessment', 'stack', 'experience', 'soft_skills', 'location', 'relocation', 'work_formats']).describe('A group of values of the anonymous candidate card that the candidate chooses to publish. The set is closed and has no value for the full name, a contact, or the lowest salary: the card never carries them, so no choice and no later contract change in this list can publish them by accident. Contacts leave only through the contact grant of an accepted invitation (C4), and the lowest salary never leaves.\n\n- categories: specialization and grade confirmed by an authoritative assessment result.\n- self_assessment: the candidate\'s declared specialization and grade, separate from confirmed categories.\n- stack: only recognized technology codes from the server\'s closed taxonomy.\n- experience: a coarse total-experience band, without employers, periods, or descriptions.\n- work_formats: explicitly selected work formats from the private questionnaire.\n- salary_compatibility: a nullable compatibility outcome with no salary amounts or bounds.\n- soft_skills, location, and relocation: retained only for compatibility in existing saved sets; they are not returned by the anonymous card.\n\nOnly values that the candidate confirmed ever reach the card: an unconfirmed suggestion (status `extracted`) and an unknown value never do, whatever the field set says.\n\nAdding a value is a contract change that lets a candidate publish more, and it is also a migration (the function `candidate_card_fields_are_canonical` and the CHECK constraints of the publication and event tables list the codes). A client treats an unknown value as a reason to ask for an update, and the server never adds a new value to a published set on its own.')).min(publicationFieldsOneMin).max(publicationFieldsOneMax).describe('Distinct card fields. The server stores them in ascending order of the codes and answers them in that order, whatever order the client sent, so equal sets are equal arrays.').describe('Card fields that organizations may read. Empty exactly when `state` is `closed`.'),
|
||||
"fields": zod.array(zod.enum(['categories', 'salary_compatibility', 'self_assessment', 'stack', 'experience', 'soft_skills', 'location', 'relocation', 'work_formats']).describe('A group of values of the anonymous candidate card that the candidate chooses to publish. The set is closed and has no value for the full name, a contact, or the lowest salary: the card never carries them, so no choice and no later contract change in this list can publish them by accident. Contacts leave only through the contact grant of an accepted invitation (C4), and the lowest salary never leaves.\n\n- categories: specialization and grade confirmed by an authoritative assessment result. With it an organization receives the confirmed category and, with each category of the card, one supporting assessment fact: its skill, the passed grade, the trust level, the year of the assessment, and the basis and calibration that mark a synthetic, uncalibrated demonstration (`GetOrganizationCandidateEvidence`). The candidate sees the same on `GetMyCardPreview`.\n- self_assessment: the candidate\'s declared specialization and grade, separate from confirmed categories.\n- stack: only recognized technology codes from the server\'s closed taxonomy.\n- experience: a coarse total-experience band, without employers, periods, or descriptions.\n- work_formats: explicitly selected work formats from the private questionnaire.\n- salary_compatibility: a nullable compatibility outcome with no salary amounts or bounds.\n- soft_skills, location, and relocation: retained only for compatibility in existing saved sets; they are not returned by the anonymous card.\n\nOnly values that the candidate confirmed ever reach the card: an unconfirmed suggestion (status `extracted`) and an unknown value never do, whatever the field set says.\n\nAdding a value is a contract change that lets a candidate publish more, and it is also a migration (the function `candidate_card_fields_are_canonical` and the CHECK constraints of the publication and event tables list the codes). A client treats an unknown value as a reason to ask for an update, and the server never adds a new value to a published set on its own.')).min(publicationFieldsOneMin).max(publicationFieldsOneMax).describe('Distinct card fields. The server stores them in ascending order of the codes and answers them in that order, whatever order the client sent, so equal sets are equal arrays.').describe('Card fields that organizations may read. Empty exactly when `state` is `closed`.'),
|
||||
"consent_id": zod.union([zod.uuid(),zod.null()]).describe('Identifier of the C2 record of the consent ledger that backs the current or the last publication, the `id` of a `ConsentRecord` of this account, or null when the profile was never published.'),
|
||||
"published_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('Moment of the latest change that published or republished the card, or null while the profile was never published. It stays after a closing, as the time of the last publication.'),
|
||||
"version": zod.int().min(publicationVersionMin).describe('Version of the publication setting of the candidate. A candidate who has never published has version 0 and the profile is closed; every change that alters the setting advances it by one. The client sends the version it read as `expected_version`. It is independent of the versions of the profile and of the search status, so a change of one never makes another stale.')
|
||||
|
||||
@@ -15,7 +15,7 @@ export const publicationUpdateFieldsMax = 9;
|
||||
export const PublicationUpdate = zod.object({
|
||||
"expected_version": zod.int().min(publicationUpdateExpectedVersionMin).describe('Version of the publication setting of the candidate. A candidate who has never published has version 0 and the profile is closed; every change that alters the setting advances it by one. The client sends the version it read as `expected_version`. It is independent of the versions of the profile and of the search status, so a change of one never makes another stale.'),
|
||||
"state": zod.enum(['closed', 'published']).describe('Whether the candidate card can be read by organizations at all. It is computed from the stored publication and the consent ledger: a profile is closed unless the candidate published it and the C2 consent that backs the publication is still unrevoked.\n\n- closed: no organization reads the card. This is the state of every new profile and of a profile whose publication was closed or whose C2 was revoked.\n- published: organizations may read exactly the fields in `fields`, except for the organizations the candidate hid.'),
|
||||
"fields": zod.array(zod.enum(['categories', 'salary_compatibility', 'self_assessment', 'stack', 'experience', 'soft_skills', 'location', 'relocation', 'work_formats']).describe('A group of values of the anonymous candidate card that the candidate chooses to publish. The set is closed and has no value for the full name, a contact, or the lowest salary: the card never carries them, so no choice and no later contract change in this list can publish them by accident. Contacts leave only through the contact grant of an accepted invitation (C4), and the lowest salary never leaves.\n\n- categories: specialization and grade confirmed by an authoritative assessment result.\n- self_assessment: the candidate\'s declared specialization and grade, separate from confirmed categories.\n- stack: only recognized technology codes from the server\'s closed taxonomy.\n- experience: a coarse total-experience band, without employers, periods, or descriptions.\n- work_formats: explicitly selected work formats from the private questionnaire.\n- salary_compatibility: a nullable compatibility outcome with no salary amounts or bounds.\n- soft_skills, location, and relocation: retained only for compatibility in existing saved sets; they are not returned by the anonymous card.\n\nOnly values that the candidate confirmed ever reach the card: an unconfirmed suggestion (status `extracted`) and an unknown value never do, whatever the field set says.\n\nAdding a value is a contract change that lets a candidate publish more, and it is also a migration (the function `candidate_card_fields_are_canonical` and the CHECK constraints of the publication and event tables list the codes). A client treats an unknown value as a reason to ask for an update, and the server never adds a new value to a published set on its own.')).min(publicationUpdateFieldsMin).max(publicationUpdateFieldsMax).describe('Distinct card fields. The server stores them in ascending order of the codes and answers them in that order, whatever order the client sent, so equal sets are equal arrays.')
|
||||
"fields": zod.array(zod.enum(['categories', 'salary_compatibility', 'self_assessment', 'stack', 'experience', 'soft_skills', 'location', 'relocation', 'work_formats']).describe('A group of values of the anonymous candidate card that the candidate chooses to publish. The set is closed and has no value for the full name, a contact, or the lowest salary: the card never carries them, so no choice and no later contract change in this list can publish them by accident. Contacts leave only through the contact grant of an accepted invitation (C4), and the lowest salary never leaves.\n\n- categories: specialization and grade confirmed by an authoritative assessment result. With it an organization receives the confirmed category and, with each category of the card, one supporting assessment fact: its skill, the passed grade, the trust level, the year of the assessment, and the basis and calibration that mark a synthetic, uncalibrated demonstration (`GetOrganizationCandidateEvidence`). The candidate sees the same on `GetMyCardPreview`.\n- self_assessment: the candidate\'s declared specialization and grade, separate from confirmed categories.\n- stack: only recognized technology codes from the server\'s closed taxonomy.\n- experience: a coarse total-experience band, without employers, periods, or descriptions.\n- work_formats: explicitly selected work formats from the private questionnaire.\n- salary_compatibility: a nullable compatibility outcome with no salary amounts or bounds.\n- soft_skills, location, and relocation: retained only for compatibility in existing saved sets; they are not returned by the anonymous card.\n\nOnly values that the candidate confirmed ever reach the card: an unconfirmed suggestion (status `extracted`) and an unknown value never do, whatever the field set says.\n\nAdding a value is a contract change that lets a candidate publish more, and it is also a migration (the function `candidate_card_fields_are_canonical` and the CHECK constraints of the publication and event tables list the codes). A client treats an unknown value as a reason to ask for an update, and the server never adds a new value to a published set on its own.')).min(publicationUpdateFieldsMin).max(publicationUpdateFieldsMax).describe('Distinct card fields. The server stores them in ascending order of the codes and answers them in that order, whatever order the client sent, so equal sets are equal arrays.')
|
||||
}).describe('The complete new publication setting. `published` needs a non-empty set of fields and an active C2 consent of the account; `closed` needs an empty set and never fails for a missing consent. The body names no consent: the server binds the publication to the account\'s current unrevoked C2 record, and a client can neither supply nor forge one.')
|
||||
|
||||
export type PublicationUpdate = zod.input<typeof PublicationUpdate>;
|
||||
|
||||
@@ -15,7 +15,7 @@ export const setMyPublicationBodyFieldsMax = 9;
|
||||
export const SetMyPublicationBody = zod.object({
|
||||
"expected_version": zod.int().min(setMyPublicationBodyExpectedVersionMin).describe('Version of the publication setting of the candidate. A candidate who has never published has version 0 and the profile is closed; every change that alters the setting advances it by one. The client sends the version it read as `expected_version`. It is independent of the versions of the profile and of the search status, so a change of one never makes another stale.'),
|
||||
"state": zod.enum(['closed', 'published']).describe('Whether the candidate card can be read by organizations at all. It is computed from the stored publication and the consent ledger: a profile is closed unless the candidate published it and the C2 consent that backs the publication is still unrevoked.\n\n- closed: no organization reads the card. This is the state of every new profile and of a profile whose publication was closed or whose C2 was revoked.\n- published: organizations may read exactly the fields in `fields`, except for the organizations the candidate hid.'),
|
||||
"fields": zod.array(zod.enum(['categories', 'salary_compatibility', 'self_assessment', 'stack', 'experience', 'soft_skills', 'location', 'relocation', 'work_formats']).describe('A group of values of the anonymous candidate card that the candidate chooses to publish. The set is closed and has no value for the full name, a contact, or the lowest salary: the card never carries them, so no choice and no later contract change in this list can publish them by accident. Contacts leave only through the contact grant of an accepted invitation (C4), and the lowest salary never leaves.\n\n- categories: specialization and grade confirmed by an authoritative assessment result.\n- self_assessment: the candidate\'s declared specialization and grade, separate from confirmed categories.\n- stack: only recognized technology codes from the server\'s closed taxonomy.\n- experience: a coarse total-experience band, without employers, periods, or descriptions.\n- work_formats: explicitly selected work formats from the private questionnaire.\n- salary_compatibility: a nullable compatibility outcome with no salary amounts or bounds.\n- soft_skills, location, and relocation: retained only for compatibility in existing saved sets; they are not returned by the anonymous card.\n\nOnly values that the candidate confirmed ever reach the card: an unconfirmed suggestion (status `extracted`) and an unknown value never do, whatever the field set says.\n\nAdding a value is a contract change that lets a candidate publish more, and it is also a migration (the function `candidate_card_fields_are_canonical` and the CHECK constraints of the publication and event tables list the codes). A client treats an unknown value as a reason to ask for an update, and the server never adds a new value to a published set on its own.')).min(setMyPublicationBodyFieldsMin).max(setMyPublicationBodyFieldsMax).describe('Distinct card fields. The server stores them in ascending order of the codes and answers them in that order, whatever order the client sent, so equal sets are equal arrays.')
|
||||
"fields": zod.array(zod.enum(['categories', 'salary_compatibility', 'self_assessment', 'stack', 'experience', 'soft_skills', 'location', 'relocation', 'work_formats']).describe('A group of values of the anonymous candidate card that the candidate chooses to publish. The set is closed and has no value for the full name, a contact, or the lowest salary: the card never carries them, so no choice and no later contract change in this list can publish them by accident. Contacts leave only through the contact grant of an accepted invitation (C4), and the lowest salary never leaves.\n\n- categories: specialization and grade confirmed by an authoritative assessment result. With it an organization receives the confirmed category and, with each category of the card, one supporting assessment fact: its skill, the passed grade, the trust level, the year of the assessment, and the basis and calibration that mark a synthetic, uncalibrated demonstration (`GetOrganizationCandidateEvidence`). The candidate sees the same on `GetMyCardPreview`.\n- self_assessment: the candidate\'s declared specialization and grade, separate from confirmed categories.\n- stack: only recognized technology codes from the server\'s closed taxonomy.\n- experience: a coarse total-experience band, without employers, periods, or descriptions.\n- work_formats: explicitly selected work formats from the private questionnaire.\n- salary_compatibility: a nullable compatibility outcome with no salary amounts or bounds.\n- soft_skills, location, and relocation: retained only for compatibility in existing saved sets; they are not returned by the anonymous card.\n\nOnly values that the candidate confirmed ever reach the card: an unconfirmed suggestion (status `extracted`) and an unknown value never do, whatever the field set says.\n\nAdding a value is a contract change that lets a candidate publish more, and it is also a migration (the function `candidate_card_fields_are_canonical` and the CHECK constraints of the publication and event tables list the codes). A client treats an unknown value as a reason to ask for an update, and the server never adds a new value to a published set on its own.')).min(setMyPublicationBodyFieldsMin).max(setMyPublicationBodyFieldsMax).describe('Distinct card fields. The server stores them in ascending order of the codes and answers them in that order, whatever order the client sent, so equal sets are equal arrays.')
|
||||
}).describe('The complete new publication setting. `published` needs a non-empty set of fields and an active C2 consent of the account; `closed` needs an empty set and never fails for a missing consent. The body names no consent: the server binds the publication to the account\'s current unrevoked C2 record, and a client can neither supply nor forge one.')
|
||||
|
||||
export type SetMyPublicationBody = zod.input<typeof SetMyPublicationBody>;
|
||||
|
||||
@@ -472,6 +472,96 @@ class AssessmentContractTest(unittest.TestCase):
|
||||
)
|
||||
self.assertFalse(decision.get("additionalProperties", True))
|
||||
|
||||
def test_evidence_is_closed_and_no_organization_operation_reaches_raw_assessment_data(self) -> None:
|
||||
own = self.paths["/api/v1/me/evidence"]["get"]
|
||||
organization = self.paths[
|
||||
"/api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}/evidence"
|
||||
]["get"]
|
||||
self.assertEqual(own["operationId"], "ListMyEvidence")
|
||||
self.assertEqual(organization["operationId"], "GetOrganizationCandidateEvidence")
|
||||
for operation in (own, organization):
|
||||
self.assertEqual(operation["security"], [{"sessionCookie": []}])
|
||||
self.assertEqual({"200", "400", "401", "403", "default"} - set(operation["responses"]), set())
|
||||
self.assertIn("Cache-Control", operation["responses"]["200"]["headers"])
|
||||
self.assertEqual({"404", "429"} - set(organization["responses"]), set())
|
||||
self.assertTrue(any(parameter.get("$ref", "").endswith("/PageCursor") for parameter in own["parameters"]))
|
||||
|
||||
self.assertEqual(self.schemas["EvidenceKind"]["enum"], ["claim", "measurement"])
|
||||
trust = self.schemas["EvidenceTrustLevel"]
|
||||
self.assertEqual((trust["minimum"], trust["maximum"]), (0, 3))
|
||||
for name in (
|
||||
"EvidenceFact", "EvidenceSource", "EvidenceResult", "EvidenceFactList",
|
||||
"OrganizationEvidenceFact", "OrganizationEvidence",
|
||||
):
|
||||
schema = self.schemas[name]
|
||||
self.assertFalse(schema.get("additionalProperties", True), name)
|
||||
self.assertEqual(set(schema["required"]), set(schema["properties"]), name)
|
||||
# One event is one fact: the tags are a non-empty set inside the fact.
|
||||
skills = self.schemas["EvidenceFact"]["properties"]["skills"]
|
||||
self.assertTrue(skills["uniqueItems"])
|
||||
self.assertEqual(skills["minItems"], 1)
|
||||
# An organization reads the skill, grade, trust, year, and the basis and
|
||||
# calibration of one fact for each category: no identifier, no source,
|
||||
# no exact time.
|
||||
self.assertEqual(
|
||||
set(self.schemas["OrganizationEvidenceFact"]["properties"]),
|
||||
{"skill", "grade", "trust", "basis", "calibration_status", "observed_year"},
|
||||
)
|
||||
self.assertEqual(self.schemas["OrganizationEvidence"]["properties"]["items"]["maxItems"], 9)
|
||||
|
||||
raw_properties = {
|
||||
"answer", "answers", "answer_key", "reference_answer", "raw_score", "basic_score", "pass_points",
|
||||
"scored_items", "uncertainty", "weak_domains", "practice_results", "signals", "events",
|
||||
"item_instance_id", "seed", "variant", "hidden_checks", "category_decision", "band", "reasons",
|
||||
"attempt_id",
|
||||
}
|
||||
|
||||
def reachable(value: Any, found: set[str]) -> None:
|
||||
if isinstance(value, dict):
|
||||
reference = value.get("$ref", "")
|
||||
if reference.startswith("#/components/schemas/"):
|
||||
name = reference.rsplit("/", 1)[-1]
|
||||
if name not in found:
|
||||
found.add(name)
|
||||
reachable(self.schemas[name], found)
|
||||
for child in value.values():
|
||||
reachable(child, found)
|
||||
elif isinstance(value, list):
|
||||
for child in value:
|
||||
reachable(child, found)
|
||||
|
||||
def property_names(value: Any, found: set[str]) -> None:
|
||||
if isinstance(value, dict):
|
||||
for key, child in value.items():
|
||||
if key == "properties" and isinstance(child, dict):
|
||||
found.update(child)
|
||||
property_names(child, found)
|
||||
elif isinstance(value, list):
|
||||
for child in value:
|
||||
property_names(child, found)
|
||||
|
||||
walked = 0
|
||||
for path, path_item in self.paths.items():
|
||||
if not (path.startswith("/api/v1/organizations") or path == "/api/v1/me/evidence"):
|
||||
continue
|
||||
walked += 1
|
||||
schemas: set[str] = set()
|
||||
reachable(path_item, schemas)
|
||||
names: set[str] = set()
|
||||
property_names(path_item, names)
|
||||
for schema_name in schemas:
|
||||
property_names(self.schemas[schema_name], names)
|
||||
self.assertFalse(
|
||||
schema_name.startswith(("Assessment", "Practice", "ItemContent"))
|
||||
or "Signal" in schema_name
|
||||
or "Review" in schema_name,
|
||||
f"{path} reaches the assessment schema {schema_name}",
|
||||
)
|
||||
self.assertEqual(raw_properties.intersection(names), set(), path)
|
||||
if path == "/api/v1/me/evidence":
|
||||
self.assertTrue({"EvidenceFact", "EvidenceResult"} <= schemas, "the walk must reach the evidence schemas")
|
||||
self.assertGreaterEqual(walked, 10)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user