fix(assessment): return confirmed categories with their basis and label demonstration categories

This commit is contained in:
shira committed 2026-10-09 21:24:24 +03:00
1 parent 623d41b969
commit d4903a3796
77 files changed
+1441 -288

No files matched your search

+14 -3
View File
@@ -702,14 +702,25 @@ Code: migration `backend/db/migrations/00035_create_skill_evidence.sql`, queries
- 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 the Passport PDF, and retention. Whether the evidence should need its own card field instead of `categories` is open.
### Assessment availability and the confirmed grade
`GET /api/v1/me/assessment-availability` (`GetMyAssessmentAvailability`) only reads. The usecase `backend/internal/usecase/assessment/availability.go` reads the policy, the bank, the questionnaire, the attempts, the quota, and the current categories in one repeatable-read snapshot. For each questionnaire specialization, `confirmed_grade` and its basis `confirmed_basis` come from the current `candidate_assessment_categories` row through the `ListCandidateCategories` port, not from the results. The grade and its basis are therefore read together, and `confirmed_basis` is null exactly when no grade is confirmed. A category of a specialization that the questionnaire no longer lists does not appear in the availability, but the profile shows it.
The profile (`GetMyProfile`, `SaveMyProfile`) reads the same rows in its own transaction. `confirmed_categories` holds one category per specialization in catalog order, with its `basis`, its assignment time (`confirmed_at`), and the `attempt_id` of the attempt whose result assigned it. An empty list means that no result has confirmed a category.
A category changes only by a strict grade upgrade (the database trigger and the domain): a result with a higher pass replaces the row, a pass at an equal or lower grade leaves it as it is and the decision gets the status `unchanged`. A failed attempt does not change the category. The domain has no category revocation; the row leaves only through the cascade of an account deletion.
`basis` is the same value as the `source` of the category decision. Today it is always `synthetic_demo`: the database accepts only the demonstration source and `calibration_status = uncalibrated`. The candidate card and the organization search therefore show such a category as a demonstration, not as a validated measurement. The basis is required in every category object, so a category without a basis cannot look like a standard confirmation.
## Matching and explanations
Implemented as a deterministic search without ML: `POST /api/v1/organizations/{org_id}/matches` (`SearchOrganizationMatches`, [api/README.en.md](../../api/README.en.md#match-search)). Code: the usecase `backend/internal/usecase/matching/` (`search.go` the flow, `filter.go` the filters, `score.go` the integer scoring, `explain.go` the explanation), the card list `candidateview.Service.ListVisibleCards`, the policy section `domain.MatchingPolicy` (`policy_matching.go`), the skill relations `domain.RelateEvidenceSkill` (`evidence_relation.go`), the handler `adapter/primary/http/v1/matches.go`, and the wiring `bootstrap/matches.go`. There is no new table, migration, or query file: the search reuses the barrier queries that the card and the evidence already use, so there is one copy of the visibility rule.
- Access before ranking. The search is one transaction. The owner role is checked under the membership lock before any card is read. `ListVisibleCards` then runs the checks of a card read: verified employer, then `ListVisibleCandidateViewSources`, which selects from `candidate_effective_publications` (published and backed by an unrevoked C2) and excludes the candidates that hide the reading organization with `NOT EXISTS` over `candidate_hidden_organizations`; then the account, C2, and publication locks, and the anonymous projection with its minimum cohort of five. The list is therefore exactly the set of handles that `GetOrganizationCandidateCard` opens at that moment: a card that the cohort rules suppress is not searched, a revoked C2, a closed publication, or a hidden organization takes effect on the next request, and nothing is cached or stored. The permitted evidence is read only through the organization-safe batch query `ListOrganizationVisibleEvidenceBatch` (one statement for the whole candidate set, with the barriers of the single read: the effective publication view, `NOT EXISTS` over the hiding, the `categories` field, visible measurements), and only when the request names skills. The locks are those of the card read and nothing else is locked; the writes of the search are limited to the candidates it returns.
- Owner only. For the MVP milestone the active owner of the organization searches. The HTTP boundary refuses every other role (`ownerCompanyOperations`), and the usecase repeats the role check under the membership lock, so a membership alone grants nothing. The full role and assignment matrix is later work and must not widen rights by one membership.
- Charged like card reads. A search returns card content (the confirmed category with its strength, the declared grade, the stack, the experience band, the work formats, and the explanation), so it passes through the same allowance as a card read. The whole visible bank is ranked, and then each group is cut to `max_results_per_group` of the policy version (demo value 10, so at most 30 reveals for one search, below the 50 distinct card views per day of tier E0); no total is returned. Walking the output in the order `main`, `near`, `unconfirmed`, each newly revealed candidate is reserved through the company quota port (`candidateview.SearchViews.Reserve`, the same `ReserveCardView` as a card read: idempotent per organization and candidate inside the window, so repeating the search or opening the card afterwards does not charge twice), and the candidate's access history gets one `card_viewed` entry per search with the fields actually returned (`SearchViews.Record`), all in the transaction of the search. When the allowance ends, the output stops at the first refusal: the entries already paid for are returned, `truncated` is true, nothing is written for the rest, and there is no error. `truncated` is also true when a group exceeded its limit; it carries no count. Opening a card is still the read for the full card.
- Charged like card reads. A search returns card content (the confirmed category with its strength and basis, the declared grade, the stack, the experience band, the work formats, and the explanation), so it passes through the same allowance as a card read. The whole visible bank is ranked, and then each group is cut to `max_results_per_group` of the policy version (demo value 10, so at most 30 reveals for one search, below the 50 distinct card views per day of tier E0); no total is returned. Walking the output in the order `main`, `near`, `unconfirmed`, each newly revealed candidate is reserved through the company quota port (`candidateview.SearchViews.Reserve`, the same `ReserveCardView` as a card read: idempotent per organization and candidate inside the window, so repeating the search or opening the card afterwards does not charge twice), and the candidate's access history gets one `card_viewed` entry per search with the fields actually returned (`SearchViews.Record`), all in the transaction of the search. When the allowance ends, the output stops at the first refusal: the entries already paid for are returned, `truncated` is true, nothing is written for the rest, and there is no error. `truncated` is also true when a group exceeded its limit; it carries no count. Opening a card is still the read for the full card.
- One entry per candidate specialization, built from the card the organization is allowed to see. A specialization is confirmed only when the card shows its category (`categories` published and not generalized away); a role that the self-assessment lists as unconfirmed is an unconfirmed entry; a role marked confirmed whose category the card does not show gives no entry, because a result cannot claim a confirmation the candidate did not publish. The same handle can therefore be confirmed in Backend and unconfirmed in Networks, and a Backend confirmation never changes the Networks entry. The status of an entry follows the specialization of the request: a need with a confirmed specialization and a `specialization` filter both restrict it, and two different values leave nothing. A need without a confirmed specialization searches all of them and returns each specialization separately.
- Category basis. Each confirmed category of an entry carries `basis` from the same stored row as the card. Today it is `synthetic_demo`, a demonstration that is not a validated measurement. The organization reads it as a demonstration confirmation; the field is required in `MatchCategory`, so a category without a basis cannot exist.
- Filters, all applied before scoring. `confirmed_grade`, `confirmed_category`, and `confirmation_status: confirmed` keep only confirmed entries; a declared grade never satisfies them. `declared_grade` is a separate claim. `stack` requires every named tag in the card and also counts as a required skill of the request. `conditions.work_formats` needs one common format, and `conditions.salary_compatibility` needs the same value; an unknown card value never satisfies a condition. An unconfirmed category alone hides nothing: without a confirmed filter the declared specializations are listed.
- Requested skills. The skills of the Cov come from the confirmed required (weight 2) and desired (weight 1) skills of the need snapshot, with the tags of the `stack` filter as required. A code is counted once however often it is repeated. A skill without a taxonomy code has no reviewed mapping, matches nothing, and is a gap. An empty request uses the neutral Cov 0.5 instead of dividing by zero. The need is read by `requirements_version` (`GetVersion`); a general version that only changed the title is not a requirements snapshot and answers 404, and the snapshot of an older requirements version stays searchable and unchanged.
- Evidence of a skill. Each requested skill takes the best product of the trust, attribution, and relation coefficients over the permitted evidence, not their sum. The evidence is the stated stack tags of the card (trust 0, a claim) and, for a confirmed entry, the one assessment fact that supports its category (trust 1, personal). The relation is exact for the same code, broader for a specialization over a technology, and narrower the other way, by the `skill_taxonomy` of the policy version (demo: `backend` over `docker`, `go`, `kafka`, `postgresql`; `devops_sre` over `docker`); a version without a taxonomy relates only equal codes, so the version fully determines the result. The taxonomy is a demonstration mapping, not a measured one. An online Backend result is worth 0.6 * 1.0 * 0.4 = 0.24 for a requested Go and a stated Go tag 0.25; the near threshold is 0.25, so a candidate whose only evidence for a required technology is a Backend assessment is always in `near` for it, and a stated tag alone is enough to be in `main`. That consequence of the PRD values is an owner question. Repeating a tag or a skill adds nothing.
@@ -908,7 +919,7 @@ Own `GetMyProfile` and `SaveMyProfile` operations are implemented through `backe
Migration `00020_create_candidate_profile_history.sql` adds overlapping-period confirmations and version history. `experience_overlaps` lists intersections of inclusive calendar months. An explicit confirmation binds two indices to their exact dates in the current request and its `expected_version`; an earlier confirmation carries forward only for the same indices and dates. Editing an employer or description alone does not invalidate the confirmed periods. A stored unconfirmed overlap permits only an exact no-op; a changed profile requires confirmation or corrected dates.
The changed version, complete claim set, period confirmations, and private history snapshot commit in one transaction. Each snapshot is bounded to 256 KiB; a trigger refuses history UPDATE, and deleting the profile cascades to its history. There is no automatic retention expiry. A no-op creates no history. A successful save, including a no-op, advances only `candidate_profile` to `candidate_questionnaire`, leaving later steps unchanged. Confirmed categories currently remain empty until assessment-result reading is implemented and are never written by the profile form.
The changed version, complete claim set, period confirmations, and private history snapshot commit in one transaction. Each snapshot is bounded to 256 KiB; a trigger refuses history UPDATE, and deleting the profile cascades to its history. There is no automatic retention expiry. A no-op creates no history. A successful save, including a no-op, advances only `candidate_profile` to `candidate_questionnaire`, leaving later steps unchanged. Confirmed categories are read in the same transaction as the profile (`GetMyProfile`, `SaveMyProfile`): one per specialization in catalog order, from `candidate_assessment_categories`. The profile form never writes them.
Tables:
@@ -919,7 +930,7 @@ Decisions:
- Claims, not columns. Every value has a status, a source, and a confirmation time, so one claims table replaces fifty columns; jsonb holds the shape of the value (a string, a boolean, or an object), and each kind has its own CHECK for the format and bounds of the contract (E.164 for the phone, the `@` of a Telegram name, a multiple of 1000 for the salary, `YYYY-MM` and the order of the period for experience, the known specialization and grade codes). The domain validates a value in full before it is written, and `RestoreCandidateProfileContent` applies the same rules on read, so a row changed outside the application is rejected.
- Trust level 0 in the schema. `trust_level` is stored in a column with `CHECK (trust_level = 0)`, and the insert statement supplies 0 itself and takes no level from the caller. A confirmed value requires `confirmed_at`, an unconfirmed suggestion does not and is always an import (`extraction_version` is not NULL); a manual value is always confirmed and carries no quote. Raising trust is a property of evidence, which is not stored here.
- No confirmed category. The tables have no column for a confirmed grade or a category, and the value of a role admits only the keys `specialization` and `self_assessed_grade`, so neither a form nor an import can write a confirmed category; it is derived from assessment results when read (`confirmed_categories`).
- No confirmed category. The tables have no column for a confirmed grade or a category, and the value of a role admits only the keys `specialization` and `self_assessed_grade`, so neither a form nor an import can write a confirmed category; it is read from the `candidate_assessment_categories` rows, which only an assessment result writes (`confirmed_categories`, with its `basis`).
- No mandatory link to a file, ML, or FSP. The tables have no column or foreign key to a resume file, the object storage, ML, or an FSP account, and the only foreign keys point at `users` and `candidate_profiles`. A profile typed by hand is complete; a future import adds its own columns or tables additively (`TestCandidateProfileStorage` checks the set of columns and foreign keys).
- Version. `AdvanceCandidateProfileVersion` is one statement that advances the version only when the stored one equals the one the caller read; for a stale version no row returns, and the caller answers 412 `version_conflict`. The update time is `GREATEST(stored, application clock)`, so an instance clock that runs behind never violates the CHECK `candidate_profiles_updated_after_creation` (which would be a 500). Version monotonicity is enforced by these queries only: there is no trigger, so no other code may write `version`. `InsertCandidateProfile` with `ON CONFLICT DO NOTHING` tells a lost first save apart (concurrent first saves: one wins, the rest get a version conflict). Replacing the set of claims (delete all, insert the new ones) runs in one transaction with the version advance. `domain.CandidateProfile.Replace(input, expectedVersion, at)` fixes the order: a version above the current one is a conflict; body rules are 400; a decision `extracted` that depends on the stored claims, against a stale version, is `ErrCandidateProfileVersionConflict` rather than 400; a body that changes nothing does not advance the version; any other change over a stale version is a conflict.
- Consistent read. `ReadCandidateProfile` reads the profile row and every claim in one statement (a LEFT JOIN), that is, from one snapshot; two separate queries could return version N with the claims of N+1 when a save commits between them. The adapter must use only this query and never replace it with two; a write reads the profile in the same transaction as the replacement, and the version condition protects against a lost edit.
+14 -3
View File
@@ -702,14 +702,25 @@ contact_grant относится к паре кандидат-компания
- Проверки контракта. `TestEvidenceOperationsFollowTheConventions`, `TestEvidenceSchemasAreClosedAndSeparateClaimsFromMeasurements`, `TestNoOrganizationOperationReachesRawAssessmentData` и `TestEvidenceWalkReachesTheEvidenceFamily` (Go) и `test_evidence_is_closed_and_no_organization_operation_reaches_raw_assessment_data` (Python) обходят все организационные операции и список кандидата по всем ссылкам и падают на схеме оценки, сигнала или проверки, а также на свойстве с сырым ответом, баллом или провалом.
- Не реализовано: операция скрыть или показать факт (колонка и охранник есть, HTTP-операции для изменения нет), заявления профиля как факты, факты из ФСП и других источников, отзыв источника, уровень доверия выше 1, использование доказательств в PDF "Паспорт навыков", срок хранения. Нужно ли доказательствам отдельное поле карточки вместо `categories`, остается открытым вопросом.
### Доступность оценки и подтвержденный грейд
`GET /api/v1/me/assessment-availability` (`GetMyAssessmentAvailability`) только читает. Usecase `backend/internal/usecase/assessment/availability.go` читает политику, банк, анкету, попытки, квоту и текущие категории одним снимком repeatable read. Для каждой специализации анкеты `confirmed_grade` и основание `confirmed_basis` берутся из текущей строки `candidate_assessment_categories` через порт `ListCandidateCategories`, а не из результатов. Поэтому грейд и основание читаются вместе, а `confirmed_basis` равен null ровно тогда, когда грейда нет. Категория специализации, которой нет в анкете, в доступности не появляется, но профиль ее показывает.
Профиль (`GetMyProfile`, `SaveMyProfile`) читает те же строки в своей транзакции. `confirmed_categories` содержит одну категорию на специализацию в порядке каталога с `basis`, временем назначения (`confirmed_at`) и `attempt_id` попытки, чей результат ее назначил. Пустой список означает, что ни один результат категорию не подтвердил.
Замена категории - только строгое повышение грейда (триггер базы и домен): результат с более высоким проходом заменяет строку, а проход на равный или более низкий грейд оставляет ее прежней, и решение получает статус `unchanged`. Неудачная попытка категорию не меняет. Отзыва категории домен не предусматривает; строка уходит только каскадом при удалении аккаунта.
`basis` - то же значение, что `source` решения о категории. Сейчас оно всегда `synthetic_demo`: база принимает только демонстрационный источник и `calibration_status = uncalibrated`. Поэтому карточки кандидата и подбор организаций показывают такую категорию как демонстрационную, а не как проверенное измерение. Основание обязательно в каждом объекте категории, поэтому категория без основания не может выглядеть стандартным подтверждением.
## Подбор и объяснение
Реализован как детерминированный поиск без ML: `POST /api/v1/organizations/{org_id}/matches` (`SearchOrganizationMatches`, [api/README.md](../../api/README.md#подбор)). Код: usecase `backend/internal/usecase/matching/` (`search.go` - порядок работы, `filter.go` - фильтры, `score.go` - целочисленный расчет, `explain.go` - объяснение), список карточек `candidateview.Service.ListVisibleCards`, раздел политики `domain.MatchingPolicy` (`policy_matching.go`), связи навыков `domain.RelateEvidenceSkill` (`evidence_relation.go`), обработчик `adapter/primary/http/v1/matches.go` и сборка `bootstrap/matches.go`. Новых таблиц, миграций и файлов запросов нет: поиск использует барьерные запросы, которыми уже пользуются карточка и доказательства, поэтому правило видимости существует в одном экземпляре.
- Доступ до ранжирования. Поиск выполняется в одной транзакции. Роль владельца проверяется под блокировкой членства до чтения любых карточек. Затем `ListVisibleCards` проводит проверки чтения карточки: подтвержденный работодатель, затем `ListVisibleCandidateViewSources`, который выбирает из `candidate_effective_publications` (опубликовано и подкреплено неотозванным C2) и исключает кандидатов, скрывших читающую организацию, через `NOT EXISTS` по `candidate_hidden_organizations`; затем блокировки аккаунта, C2 и публикации и анонимная проекция с минимальной когортой из пяти. Поэтому список - это ровно те handle, которые в этот момент открывает `GetOrganizationCandidateCard`: карточка, скрытая правилами когорты, не ищется, отзыв C2, закрытая публикация или скрытая организация действуют со следующего запроса, ничего не кешируется и не хранится. Разрешенные доказательства читаются только организационно безопасным пакетным запросом `ListOrganizationVisibleEvidenceBatch` (один запрос на весь набор кандидатов с барьерами одиночного чтения: представление действующих публикаций, `NOT EXISTS` по скрытию, поле `categories`, видимые измерения) и только если запрос называет навыки. Блокировки - те же, что у чтения карточки, ничего больше не блокируется; записи поиска ограничены кандидатами, которых он возвращает.
- Только владелец. Для MVP ищет действующий владелец организации. HTTP-граница отклоняет любую другую роль (`ownerCompanyOperations`), а usecase повторяет проверку роли под блокировкой членства, поэтому само членство ничего не дает. Полная матрица ролей и назначений - более поздняя работа и не должна расширять права по одному членству.
- Оплата как чтение карточек. Поиск возвращает содержимое карточки (подтвержденную категорию с силой, заявленный грейд, стек, диапазон стажа, форматы работы и объяснение), поэтому проходит через тот же лимит, что чтение карточки. Ранжируется весь видимый банк, затем каждая группа обрезается до `max_results_per_group` версии политики (демо 10, то есть не более 30 показов за один поиск, меньше 50 уникальных просмотров в сутки уровня E0); итог не возвращается. В порядке `main`, `near`, `unconfirmed` каждый впервые показанный кандидат резервируется через порт квоты компании (`candidateview.SearchViews.Reserve`, тот же `ReserveCardView`, что у чтения карточки: идемпотентно на организацию и кандидата внутри окна, поэтому повтор поиска или открытие карточки после него не списывает дважды), а в истории доступа кандидата появляется по одной записи `card_viewed` за поиск с фактически возвращенными полями (`SearchViews.Record`); все это в транзакции поиска. Когда лимит заканчивается, вывод останавливается на первом отказе: возвращаются уже оплаченные записи, `truncated` истинно, для остальных ничего не пишется, ошибки нет. `truncated` истинно и когда группа превысила предел; числа оно не несет. Полная карточка по-прежнему открывается своим чтением.
- Оплата как чтение карточек. Поиск возвращает содержимое карточки (подтвержденную категорию с силой и основанием, заявленный грейд, стек, диапазон стажа, форматы работы и объяснение), поэтому проходит через тот же лимит, что чтение карточки. Ранжируется весь видимый банк, затем каждая группа обрезается до `max_results_per_group` версии политики (демо 10, то есть не более 30 показов за один поиск, меньше 50 уникальных просмотров в сутки уровня E0); итог не возвращается. В порядке `main`, `near`, `unconfirmed` каждый впервые показанный кандидат резервируется через порт квоты компании (`candidateview.SearchViews.Reserve`, тот же `ReserveCardView`, что у чтения карточки: идемпотентно на организацию и кандидата внутри окна, поэтому повтор поиска или открытие карточки после него не списывает дважды), а в истории доступа кандидата появляется по одной записи `card_viewed` за поиск с фактически возвращенными полями (`SearchViews.Record`); все это в транзакции поиска. Когда лимит заканчивается, вывод останавливается на первом отказе: возвращаются уже оплаченные записи, `truncated` истинно, для остальных ничего не пишется, ошибки нет. `truncated` истинно и когда группа превысила предел; числа оно не несет. Полная карточка по-прежнему открывается своим чтением.
- Одна запись на специализацию кандидата, из карточки, которую организации разрешено видеть. Специализация подтверждена, только когда карточка показывает ее категорию (`categories` опубликованы и не обобщены до пустоты); роль, помеченная в самооценке как неподтвержденная, - неподтвержденная запись; роль, помеченная подтвержденной, чью категорию карточка не показывает, записи не дает, потому что результат не может заявлять подтверждение, которое кандидат не опубликовал. Один и тот же handle может быть подтвержден по Backend и не подтвержден по сетям, и подтверждение Backend никогда не меняет запись по сетям. Статус записи следует специализации запроса: подтвержденная специализация потребности и фильтр `specialization` оба ограничивают поиск, а два разных значения не оставляют ничего. Потребность без подтвержденной специализации ищет по всем и возвращает каждую специализацию отдельно.
- Основание категории. Каждая подтвержденная категория записи несет `basis` из той же строки, что и карточка. Сейчас это `synthetic_demo`: демонстрация, которая не является проверенным измерением. Организация видит ее как демонстрационное подтверждение; поле обязательно в `MatchCategory`, поэтому категория без основания невозможна.
- Фильтры, все до расчета. `confirmed_grade`, `confirmed_category` и `confirmation_status: confirmed` оставляют только подтвержденные записи; заявленный грейд их не удовлетворяет. `declared_grade` - отдельное заявление. `stack` требует каждый названный тег в карточке и одновременно считается обязательным навыком запроса. `conditions.work_formats` требует один общий формат, `conditions.salary_compatibility` - то же значение; неизвестное значение карточки условие не удовлетворяет. Одна неподтвержденная категория ничего не скрывает: без подтвержденного фильтра заявленные специализации выводятся.
- Запрошенные навыки. Навыки для Cov берутся из подтвержденных обязательных (вес 2) и желательных (вес 1) навыков снимка потребности, теги фильтра `stack` считаются обязательными. Код считается один раз, сколько бы раз он ни повторялся. Навык без таксономического кода не имеет проверенного соответствия, ничему не соответствует и остается пробелом. Пустой запрос использует нейтральное Cov 0.5 вместо деления на ноль. Потребность читается по `requirements_version` (`GetVersion`); общая версия, изменившая только название, не является снимком требований и дает 404, а снимок прежней версии требований остается доступным и неизменным.
- Доказательство навыка. Для каждого запрошенного навыка берется лучшее произведение коэффициентов доверия, атрибуции и связи среди разрешенных доказательств, а не их сумма. Доказательства - заявленные теги стека карточки (доверие 0, заявление) и для подтвержденной записи единственный факт оценки, подтверждающий ее категорию (доверие 1, личный). Связь точная для того же кода, широкая для специализации над технологией и узкая в обратную сторону, по `skill_taxonomy` версии политики (демо: `backend` над `docker`, `go`, `kafka`, `postgresql`; `devops_sre` над `docker`); версия без таксономии связывает только равные коды, так что версия политики полностью определяет результат. Таксономия - демонстрационное соответствие, а не измеренное. Онлайн-результат Backend стоит 0.6 * 1.0 * 0.4 = 0.24 для запрошенного Go, заявленный тег Go - 0.25; порог близости 0.25, поэтому кандидат, у которого единственное доказательство обязательной технологии - оценка Backend, для нее всегда в `near`, а одного заявленного тега достаточно для `main`. Это следствие значений PRD - вопрос владельцу продукта. Повтор тега или навыка ничего не добавляет.
@@ -908,7 +919,7 @@ Middleware `backend/internal/adapter/primary/http/company_context.go` прове
Миграция `00020_create_candidate_profile_history.sql` добавляет подтверждения пересекающихся периодов и историю версий. `experience_overlaps` перечисляет пересечения включительных календарных месяцев. Явное подтверждение связывает два индекса с точными датами в текущем запросе и его `expected_version`; прежнее подтверждение переносится только при тех же индексах и датах. Изменение работодателя или описания само по себе не меняет подтвержденные периоды. Сохраненный неподтвержденный overlap допускает только точный no-op; перед изменением профиля его надо подтвердить или исправить даты.
Измененная версия, полный набор заявлений, подтверждения периодов и закрытый снимок истории записываются одной транзакцией. Каждый снимок ограничен 256 KiB; UPDATE истории запрещен триггером, удаление профиля каскадно удаляет историю. Автоматического срока очистки нет. No-op не создает историю. Успешное сохранение, включая no-op, переводит только шаг `candidate_profile` в `candidate_questionnaire`; поздний шаг не меняется. Подтвержденные категории пока возвращаются пустыми до реализации чтения результатов оценки и никогда не записываются формой профиля.
Измененная версия, полный набор заявлений, подтверждения периодов и закрытый снимок истории записываются одной транзакцией. Каждый снимок ограничен 256 KiB; UPDATE истории запрещен триггером, удаление профиля каскадно удаляет историю. Автоматического срока очистки нет. No-op не создает историю. Успешное сохранение, включая no-op, переводит только шаг `candidate_profile` в `candidate_questionnaire`; поздний шаг не меняется. Подтвержденные категории читаются в той же транзакции, что и профиль (`GetMyProfile`, `SaveMyProfile`): по одной на специализацию в порядке каталога, из строк `candidate_assessment_categories`. Форма профиля их никогда не записывает.
Таблицы:
@@ -919,7 +930,7 @@ Middleware `backend/internal/adapter/primary/http/company_context.go` прове
- Заявления, а не столбцы. У каждого значения есть статус, источник и время подтверждения, поэтому одна таблица заявлений вместо пятидесяти столбцов; форму значения (строка, булево или объект) держит jsonb, а у каждого вида есть свой CHECK формата и границ контракта (E.164 для телефона, `@` у Telegram, кратность 1000 у зарплаты, `YYYY-MM` и порядок периода у опыта, известные коды специализации и грейда). Домен проверяет значение полностью до записи, а `RestoreCandidateProfileContent` повторяет те же правила при чтении, поэтому строка, измененная вне приложения, отклоняется.
- Доверие 0 в схеме. `trust_level` хранится в столбце с `CHECK (trust_level = 0)`, а оператор вставки подставляет 0 сам и не принимает уровень от вызывающего. Подтвержденное значение требует `confirmed_at`, неподтвержденное предложение - нет и обязательно является импортом (`extraction_version` не NULL); ручное значение всегда подтверждено и не несет цитаты. Повышение доверия - свойство доказательств, которые хранятся не здесь.
- Нет подтвержденной категории. В таблицах нет столбца подтвержденного грейда или категории, а значение роли допускает только ключи `specialization` и `self_assessed_grade`, поэтому ни форма, ни импорт не могут записать подтвержденную категорию; она выводится из результатов оценки при чтении (`confirmed_categories`).
- Нет подтвержденной категории. В таблицах нет столбца подтвержденного грейда или категории, а значение роли допускает только ключи `specialization` и `self_assessed_grade`, поэтому ни форма, ни импорт не могут записать подтвержденную категорию; она читается из строк `candidate_assessment_categories`, которые пишет только результат оценки (`confirmed_categories`, вместе с основанием `basis`).
- Нет обязательной связи с файлом, ML или ФСП. В таблицах нет столбцов и внешних ключей к файлу резюме, хранилищу объектов, ML или аккаунту ФСП, а единственные внешние ключи - на `users` и на `candidate_profiles`. Профиль, набранный вручную, полон; будущий импорт добавит свои столбцы или таблицы аддитивно (`TestCandidateProfileStorage` проверяет набор столбцов и внешних ключей).
- Версия. `AdvanceCandidateProfileVersion` - один оператор, который увеличивает версию только когда сохраненная равна прочитанной вызывающим; для устаревшей версии строка не возвращается, и вызывающий отвечает 412 `version_conflict`. Время обновления считается как `GREATEST(сохраненное, текущее время приложения)`, поэтому отставшие часы экземпляра не нарушают CHECK `candidate_profiles_updated_after_creation` (иначе был бы 500). Монотонность версии обеспечивают только эти запросы: триггера нет, поэтому никакой другой код не должен писать `version`. `InsertCandidateProfile` с `ON CONFLICT DO NOTHING` отличает проигранное первое сохранение (параллельные первые сохранения: одно выигрывает, остальные - конфликт версии). Замена набора заявлений (удалить все и вставить новые) идет в одной транзакции вместе с продвижением версии. `domain.CandidateProfile.Replace(input, expectedVersion, at)` задает порядок: версия выше текущей - конфликт; правила тела - 400; решение `extracted`, зависящее от сохраненных заявлений, при устаревшей версии - `ErrCandidateProfileVersionConflict`, а не 400; тело без изменений - без продвижения версии; иное изменение по устаревшей версии - конфликт.
- Согласованное чтение. `ReadCandidateProfile` читает строку профиля и все заявления одним оператором (LEFT JOIN), то есть из одного снимка; два отдельных запроса могли бы вернуть версию N с заявлениями N+1 при сохранении между ними. Адаптер обязан использовать только этот запрос и не заменять его двумя; запись читает профиль в той же транзакции, что и замена, а защиту от потерянной правки дает условие версии.