From bc00d6901fa5a812515f838c02889e52e32a4c35 Mon Sep 17 00:00:00 2001
From: shira
Date: Sun, 11 Oct 2026 14:03:31 +0300
Subject: [PATCH] feat(frontend): edit projects and show semantic match
evidence
---
frontend/README.en.md | 11 +-
frontend/README.md | 11 +-
frontend/e2e/acceptance-path.spec.ts | 2 +-
frontend/e2e/candidate-home.spec.ts | 2 +-
frontend/e2e/match-search.spec.ts | 84 +++++
frontend/e2e/privacy-visibility.spec.ts | 51 ++-
frontend/e2e/profile-edit.spec.ts | 33 +-
frontend/src/entities/candidate-view/index.ts | 2 +
.../candidate-view/model/presentation.test.ts | 62 ++++
.../candidate-view/model/presentation.ts | 29 ++
.../ui/employer-card-preview.test.tsx | 33 ++
.../ui/employer-card-preview.tsx | 21 +-
frontend/src/entities/candidate/index.ts | 18 ++
.../candidate/model/profile-form.test.ts | 194 ++++++++++++
.../entities/candidate/model/profile-form.ts | 190 ++++++++++-
.../candidate/model/profile-projects.test.ts | 123 ++++++++
.../candidate/model/profile-projects.ts | 131 ++++++++
frontend/src/entities/match/index.ts | 4 +
.../src/entities/match/model/adapter.test.ts | 76 +++++
frontend/src/entities/match/model/adapter.ts | 53 +++-
.../entities/match/model/card-presentation.ts | 16 +
.../entities/match/model/explanation.test.ts | 64 +++-
.../src/entities/match/model/explanation.ts | 53 ++++
frontend/src/entities/match/model/labels.ts | 27 ++
.../entities/match/model/match.fixtures.ts | 35 +-
.../match/ui/candidate-card-details.test.tsx | 70 ++++
.../match/ui/candidate-card-details.tsx | 7 +
.../entities/match/ui/match-card.module.css | 69 ++++
frontend/src/entities/match/ui/match-card.tsx | 44 ++-
.../edit-profile/model/field-helpers.ts | 23 ++
.../edit-profile/model/profile-steps.test.ts | 2 +
.../edit-profile/model/profile-steps.ts | 5 +-
.../model/repository-recheck.test.ts | 137 ++++++++
.../edit-profile/model/repository-recheck.ts | 54 ++++
.../model/use-repository-recheck.ts | 73 +++++
.../features/edit-profile/ui/edit-profile.tsx | 39 ++-
.../features/edit-profile/ui/form-field.tsx | 56 ++++
.../edit-profile/ui/profile-form.test.tsx | 164 +++++++++-
.../features/edit-profile/ui/profile-form.tsx | 135 ++++----
.../edit-profile/ui/projects-step.module.css | 139 ++++++++
.../edit-profile/ui/projects-step.tsx | 298 ++++++++++++++++++
.../edit-profile/ui/tag-list-input.tsx | 102 ++++++
.../ui/visibility-controls.module.css | 32 ++
.../ui/visibility-controls.test.tsx | 42 +++
.../ui/visibility-controls.tsx | 33 +-
frontend/src/shared/ui/index.ts | 1 +
.../published-projects.module.css | 71 +++++
.../published-projects.test.tsx | 61 ++++
.../published-projects/published-projects.tsx | 60 ++++
.../shared/ui/status-view/describe-error.ts | 5 +
.../ui/status-view/status-view.test.tsx | 15 +
.../widgets/match-list/ui/match-list.test.tsx | 41 +++
52 files changed, 2992 insertions(+), 111 deletions(-)
create mode 100644 frontend/src/entities/candidate/model/profile-projects.test.ts
create mode 100644 frontend/src/entities/candidate/model/profile-projects.ts
create mode 100644 frontend/src/entities/match/ui/candidate-card-details.test.tsx
create mode 100644 frontend/src/features/edit-profile/model/field-helpers.ts
create mode 100644 frontend/src/features/edit-profile/model/repository-recheck.test.ts
create mode 100644 frontend/src/features/edit-profile/model/repository-recheck.ts
create mode 100644 frontend/src/features/edit-profile/model/use-repository-recheck.ts
create mode 100644 frontend/src/features/edit-profile/ui/form-field.tsx
create mode 100644 frontend/src/features/edit-profile/ui/projects-step.module.css
create mode 100644 frontend/src/features/edit-profile/ui/projects-step.tsx
create mode 100644 frontend/src/features/edit-profile/ui/tag-list-input.tsx
create mode 100644 frontend/src/shared/ui/published-projects/published-projects.module.css
create mode 100644 frontend/src/shared/ui/published-projects/published-projects.test.tsx
create mode 100644 frontend/src/shared/ui/published-projects/published-projects.tsx
diff --git a/frontend/README.en.md b/frontend/README.en.md
index 1172165..6dd12ca 100644
--- a/frontend/README.en.md
+++ b/frontend/README.en.md
@@ -39,12 +39,14 @@ Generated Orval hooks call the shared same-origin `apiRequest` client, so the `Q
`entities/candidate` holds the complete profile draft model and converts it to `CandidateProfileUpdate`. `features/edit-profile` owns the fields and saving, while `pages/profile` owns the page. Server data stays in React Query; contacts and drafts are not written to localStorage or sessionStorage.
-The form goes in steps (`Stepper`): contacts, roles with the self-assessment and the confirmed categories, experience with the confirmation of parallel periods, skills, terms, and review with saving. The server takes the whole profile with `expected_version`, so saving exists on the last step only. "Далее" validates the fields of the current step; a client or server error on save opens the step that owns the field. Inactive steps stay mounted with the hidden attribute: "Назад" keeps what was entered, and the links of fields to their hints and errors remain. A step change moves the focus to the step heading. A saved profile offers "К проверке и сохранению", and the review step leads to any step with "Изменить". A reload opens the first step with the server record; an unsaved draft is not restored.
+The form goes in steps (`Stepper`): contacts, roles with the self-assessment and the confirmed categories, experience with the confirmation of parallel periods, projects, skills, terms, and review with saving. The server takes the whole profile with `expected_version`, so saving exists on the last step only. "Далее" validates the fields of the current step; a client or server error on save opens the step that owns the field. Inactive steps stay mounted with the hidden attribute: "Назад" keeps what was entered, and the links of fields to their hints and errors remain. A step change moves the focus to the step heading. A saved profile offers "К проверке и сохранению", and the review step leads to any step with "Изменить". A reload opens the first step with the server record; an unsaved draft is not restored.
The form preserves the provenance of untouched suggestions, displays overlapping employment periods, and requires explicit confirmation of parallel work. Confirmation is bound to the current indices and dates; reordering or changing periods requires another review. Confirmed categories are displayed separately and never enter the save body. A 412 version conflict preserves the draft and offers an explicit replacement with current data.
After saving, the form reloads the session and shows the account step returned by the server. Saving a profile does not complete the consent step; that transition is not implemented yet. Independent profile editing works without ML, a file, or FSP.
+The "Проекты" step is optional: up to 10 projects, each with a title (one line, up to 100 characters), a description (up to 500), up to 10 technology tags (chips; a tag is added by Enter, a comma, the "Добавить" button, or leaving the field, and duplicates are dropped without regard to letter case), and an optional repository address. The client accepts only `https://github.com//`, as the contract and the server do: a trailing slash and `.git` are removed; other hosts, ports, credentials, paths, query strings, and fragments are rejected; one repository cannot be listed twice (letter case does not matter). An empty project row is not sent; a project without a title but with other values blocks the step. A note at the top says that the title and the description can identify the candidate and that companies never receive the repository address. The `projects` list always goes whole with `expected_version`; an untouched suggestion stays `extracted`. The repository check status comes from the latest profile response (`repository_check`) and is shown as a tag and in words: "Проверяется", "Публичный репозиторий найден", "Не найден или закрыт", "Лимит GitHub, повторим позже"; an address that the server has not stored yet reads "Проверка после сохранения". While a check is `pending`, the screen reloads the profile every 4 seconds (for at most two minutes) and leaves the draft alone. The mark only means that a public repository exists; it does not prove authorship. The "Проверить снова" button calls `RequestMyRepositoryChecks` once for all saved addresses and shows the number of scheduled checks. On a 429 the button is disabled with a countdown from `Retry-After` and the `detail` text of the server; when the server names no time there is no countdown and no time is invented.
+
## Candidate questionnaire
`pages/questionnaire` reads the specialization catalog and the current candidate's private answers through Orval. The draft stays in component state, saved answers stay in React Query, and reload restores the server record. The form offers one or two specializations, self-assessed grades, currently available task languages, stack, experience, and work formats. A specialization without a published bank is marked in development and can be saved without FSP.
@@ -98,8 +100,10 @@ On the attempt screen only the phrase "Result received" is a live message; the r
- Consents (`features/consent-management`): C1-C5 are granted and revoked separately, with the text and version shown before a grant. The block of each purpose has an anchor that the "Go to the C2 consent" button moves focus to.
- Publication (`features/profile-visibility`): step 1 shows whether C2 is active from the complete active consent history; an unknown or partly loaded state is not treated as consent, and saving stays unavailable. The step button only moves focus to the C2 block and grants nothing. The card state and fields are chosen next, and the publication is saved by a separate action (`SetMyPublication`, `expected_version` in the body). A 412 conflict keeps the draft on screen and offers an explicit reload of the current settings; a failed save does not reset the draft. Revoking C2 closes the card, and a new C2 does not reopen it.
- Closure explanation: from `closed_reason` the screen says that future reads are closed at once, that a new C2 does not reopen the card by itself, and that a former company needs a new invitation and a new C4 to read contacts. The same words appear after revoking C2, hiding an organization, unhiding it, and republishing: an earlier contact access is not restored. Hiding does not change the C4 record in the consent ledger, so next to the C4 of a hidden company a note says that the record does not bring contact access back.
+- Projects in the publication. The `projects` field is its own choice, "Проекты: название, описание и технологии". The warning stands under it at all times (assistive technology reads it with the checkbox) and turns into a caution once the field is chosen: the candidate writes the project texts and can be recognized by them, the size of a group of similar candidates does not hide them, and the repository address and its owner are never shown to companies, which see only the mark that a public repository was found.
- Search status (`SetMySearchStatus`) is its own request and its own text. It does not change the publication and grants no consent.
- Employer preview (`EmployerCardPreview` from `entities/candidate-view`) is built only from the `GET /me/privacy/preview` response. The preview alias is separate from organization aliases. Confirmed categories and self-assessment are shown apart; each specialization has its own "Grade confirmed" or "Grade not confirmed" status (the Russian labels are "Грейд подтвержден" and "Грейд не подтвержден"), told apart by the shape of the mark and by text, not by color. A candidate without a confirmed grade sees the declared level (or "Level not specified") and the not-confirmed status for each specialization separately; a confirmed Backend is not carried over to a network specialization. The evidence block shows the skill, grade, confirmation level, year, and basis (`synthetic_demo` is shown as "Результат теста", a test result; calibration is not shown in the interface). A closed card is shown as an empty state. The preview creates no access record and ignores organization filters.
+- Projects in the preview and in the employer's card are drawn by the shared `PublishedProjects` component (`shared/ui`): the title, the description (text with line breaks), the tags, and the badge "Подтвержден публичным репозиторием" for `repository_verified`, with a note that the mark does not prove authorship. There is no address or link in the data or in the markup, and all candidate text is shown as text.
- Hiding organizations: the hide button is offered only for organizations in the candidate's own access history (the server answers 404 for the rest), and only after the list of hidden organizations is fully loaded. Unhiding does not restore contact access.
- Histories: the settings history and the card access history are paginated; a partial page is never presented as complete. An access record shows the kind of access, the time, and the organization when the server names it (otherwise "Organization is not disclosed"); it carries no employees, queries, filters, or search position. An empty history and a load error are separate states.
- A link to request a manual assessment stays below.
@@ -144,7 +148,8 @@ The tests take their fixtures from the named contract examples in `api/core/open
- Specializations. An entry is one candidate under one specialization, so one alias can stand in two groups (confirmed in Backend, not confirmed in Networks). When the result holds more than one specialization a view switch appears ("Все специализации", then each one): it hides the entries of the other specializations, recomputes nothing, and carries no confirmation across. The alias is shortened for display (`entities/match/model/views.ts`); the full value is used only by requests and the invitation link.
- Entry (`entities/match`). It shows the specialization, the status "Грейд подтвержден: X" or "Грейд не подтвержден" (by icon shape and text), the confirmed category with its strength on a line apart from the grade the candidate declared, the safe card context (technologies, experience, formats, expectations), and the server's explanation of sources: every `evidence_summary` row with the state "Подтверждено", "Подтверждено частично", "Только заявлено кандидатом", or "Пробел: подтверждения нет". A `null` context value is printed as "Нет значения в карточке", because the contract does not say whether it is hidden or absent. The entry has no contact, no real identifier, and no reason why a grade is unconfirmed.
- The explanation opens with a button that carries `aria-expanded`. It is built only from the components of the response: Fit, Cov, Dom, Sem, the percentile, V, Fr, Rsp, and the final score S appear exactly as they arrived, with no rounding beyond six decimals. A neutral value (`unknown_flags`) is labelled "Нейтральное значение, не измерено" with its reason (`ml_unavailable`, `cohort_below_30`, `percentile_not_computed`, and others). A `null` percentile is printed as "Нет значения" and no number is invented. A zero competition value is called "не штраф". An entry without a confirmed grade has only Fit and Cov: the server computes no S, percentile, or category for it, and the screen draws none. Unknowns outside the scores (experience, formats, expectations, the assessment result) are listed under "Что неизвестно" with a note that they are not an absence of ability.
-- Opening a card. The "Открыть карточку" button reads `GET /organizations/{org_id}/candidate-cards/{handle}` and, when the card has categories, the evidence section as well; the server refuses the section for a card without categories, so the request is not sent. Reads are neither retried automatically nor cached after the panel leaves the screen (`gcTime: 0`, no refetch on focus), because every read is an entry in the candidate's access history. A closed panel stays mounted, and opening it again does not read the card again. A 429 shows "Квота просмотров карточек исчерпана" and the time from `Retry-After`; when the server named none, no time is invented. A 404 replaces every hidden case with one text and names no reason.
+- Matches by meaning (`semanticBlock` in `entities/match`). Inside "Почему в подборке" the block "Совпадения по смыслу" prints `semantic_evidence` in the order and within the limit the server sent: a row "requirement kind and text → item kind and title" (requirement: "Обязательный навык", "Желательный навык", "Задача"; item: "Проект", "Стек", "Роль") and a tag "Высокое сходство" or "Среднее сходство". A project shows its title and, when `repository_verified`, a "Публичный репозиторий" badge; the stack and the roles have no title, so they read "Технологии карточки" and "Специализации и грейды карточки" and get no badge. When there are no rows because the server names the `semantics` component unknown with the reason `ml_unavailable`, the block says "Совпадения по смыслу: смысловой анализ недоступен." in the same words as the explanation; an empty list without such a flag (a search over all profiles, no matches) shows no block. A repository address or owner cannot reach the breakdown: the adapter rejects a response with a field outside the contract.
+- Opening a card. The "Открыть карточку" button reads `GET /organizations/{org_id}/candidate-cards/{handle}` and, when the card has categories, the evidence section as well; the server refuses the section for a card without categories, so the request is not sent. Reads are neither retried automatically nor cached after the panel leaves the screen (`gcTime: 0`, no refetch on focus), because every read is an entry in the candidate's access history. A closed panel stays mounted, and opening it again does not read the card again. A 429 shows "Квота просмотров карточек исчерпана" and the time from `Retry-After`; when the server named none, no time is invented. A 404 replaces every hidden case with one text and names no reason. When the candidate published projects, the card panel shows them in a "Проекты" block (title, description, tags, the badge of a verified public repository) without an address.
- Invitation. Every entry has a "Пригласить" button, an unconfirmed one included. It leads to `/employer/invitations/new` with `organization_id`, `candidate_handle`, `specialization`, and, for a need search, `need_id` (see [Invitation to a candidate](#invitation-to-a-candidate)). The alias is scoped to the organization and is not a candidate identifier.
- Layout. The form sits above the result at every width: the basis of the search (a segmented control with "По потребности" and "По всем профилям"), the selects, a row of filter chips (technologies, format, salary compatibility; an applied chip is blue with a check mark), and the action; the result takes the full width. From 768 px an entry is a content column and an action column ("Пригласить", the explanation, the card); at 360 px the actions and the facts fold into one column. The "Почему в подборке" block is set in mono on a nested surface: the sign "+" (confirmed), "+/-" (partial), "?" (declared), "-" (gap) repeats the state word. A technology chip that the search asked for carries a dot and hidden text "совпадает с условием поиска". Every action works from the keyboard, focus is visible, and status is carried by text and shape, not by color.
@@ -280,6 +285,8 @@ The interface has no FSP logo. `Wordmark` is the text mark "Lincodex" with a ter
- `Tabs` (WAI-ARIA tabs pattern, arrow keys, Home and End; inactive panels stay mounted with the hidden attribute, so form state survives) and `SegmentedControl` (a native radio group drawn as capsules). `SectionSwitch` is a sub-section switch drawn as capsules but made of links to routes: it has no panels, so tabs do not fit.
- `StatusView`, `LoadingState`, `EmptyState`, `ErrorState`, `ForbiddenState`, `SavingStatus`: screen states. Each state has its own shape and text; the empty state draws a circuit trace that ends at an open node. `ErrorState` shows the code, status, server text, and request ID as plain text and offers a retry. `Skeleton`: decorative placeholder lines while loading, always next to a loading message.
- `QueryView`: maps a query result to loading, error, forbidden (401 and 403 without retry), empty, or data.
+- `describeError`: the Russian text of an error by problem code, and by HTTP status for an unknown code. The `service_unavailable` code (503, for example while a model loads) reads "Сервис пока не готов" with advice to retry in a minute; the server text stays only as a technical detail.
+- `PublishedProjects`: the projects a candidate published on the anonymous card: the title, the description, the tags, and the badge "Подтвержден публичным репозиторием". It is a purely presentational component with no repository address; the candidate's text is shown as text, never as markup.
- `TrustLevel`: an empty mark, ring, partial fill, or full mark with a visible label.
- `CircuitTrace`, `Mono`, `VisuallyHidden`, `SkipLink`, `MainRegion`.
diff --git a/frontend/README.md b/frontend/README.md
index c7e108c..6218e79 100644
--- a/frontend/README.md
+++ b/frontend/README.md
@@ -39,12 +39,14 @@ SPA на React и TypeScript со сборкой Vite и структурой FS
`entities/candidate` хранит модель полного черновика профиля и переводит ее в `CandidateProfileUpdate`. `features/edit-profile` отвечает за поля и сохранение, `pages/profile` - за страницу. Серверные данные остаются в React Query; контакты и черновик не записываются в localStorage или sessionStorage.
-Форма идет по шагам (`Stepper`): контакты, роли с самооценкой и подтвержденными категориями, опыт с подтверждением параллельных периодов, навыки, условия, проверка и сохранение. Сервер принимает профиль целиком с `expected_version`, поэтому сохранение есть только на последнем шаге. «Далее» проверяет поля текущего шага; ошибка клиента или сервера при сохранении открывает шаг, которому принадлежит поле. Неактивные шаги остаются в дереве со скрытым атрибутом: «Назад» сохраняет введенное, а связи полей с подсказками и ошибками остаются. При смене шага фокус переходит на его заголовок. У сохраненного профиля есть переход «К проверке и сохранению», а шаг проверки ведет к любому шагу кнопкой «Изменить». Перезагрузка открывает первый шаг с серверной записью; несохраненный черновик не восстанавливается.
+Форма идет по шагам (`Stepper`): контакты, роли с самооценкой и подтвержденными категориями, опыт с подтверждением параллельных периодов, проекты, навыки, условия, проверка и сохранение. Сервер принимает профиль целиком с `expected_version`, поэтому сохранение есть только на последнем шаге. «Далее» проверяет поля текущего шага; ошибка клиента или сервера при сохранении открывает шаг, которому принадлежит поле. Неактивные шаги остаются в дереве со скрытым атрибутом: «Назад» сохраняет введенное, а связи полей с подсказками и ошибками остаются. При смене шага фокус переходит на его заголовок. У сохраненного профиля есть переход «К проверке и сохранению», а шаг проверки ведет к любому шагу кнопкой «Изменить». Перезагрузка открывает первый шаг с серверной записью; несохраненный черновик не восстанавливается.
Форма сохраняет происхождение нетронутых предложений, показывает пересекающиеся периоды работы и требует явного подтверждения параллельной работы. Подтверждение связано с текущими индексами и датами; перестановка или изменение периодов требует проверки заново. Подтвержденные категории отображаются отдельно и не входят в тело сохранения. Ошибка версии 412 оставляет черновик и предлагает явно заменить его актуальными данными.
После сохранения форма перечитывает сессию и показывает шаг аккаунта, который вернул сервер. Сохранение профиля само по себе не завершает шаг согласий; переход от него пока не реализован. Независимое редактирование профиля доступно без ML, файла и ФСП.
+Шаг «Проекты» необязателен: до 10 проектов, у каждого название (одна строка, до 100 символов), описание (до 500), до 10 тегов технологий (чипы; тег добавляют Enter, запятая, кнопка «Добавить» или уход из поля, дубли без учета регистра отбрасываются) и необязательный адрес репозитория. Клиент принимает только `https://github.com/<владелец>/<репозиторий>`, как контракт и сервер: слеш в конце и `.git` убираются, другие хосты, порты, учетные данные, пути, параметры и фрагменты отклоняются, один репозиторий не указывается дважды (регистр не важен). Пустая строка проекта не отправляется; проект без названия, но с другими значениями блокирует шаг. Предупреждение сверху: название и описание могут выдать кандидата, адрес репозитория компании не получают. Список `projects` всегда уходит целиком с `expected_version`; нетронутая подсказка остается `extracted`. Статус проверки репозитория берется из последнего ответа профиля (`repository_check`) и показан тегом и словами: «Проверяется», «Публичный репозиторий найден», «Не найден или закрыт», «Лимит GitHub, повторим позже»; для адреса, которого сервер еще не хранит, написано «Проверка после сохранения». Пока есть `pending`, экран перечитывает профиль каждые 4 секунды (не дольше двух минут) и не трогает черновик. Отметка значит только, что публичный репозиторий существует; авторство она не доказывает. Кнопка «Проверить снова» вызывает `RequestMyRepositoryChecks` один раз для всех сохраненных адресов и показывает число запланированных проверок. На 429 кнопка блокируется с обратным отсчетом из `Retry-After` и текстом `detail` сервера; если сервер срок не назвал, отсчета нет и время не выдумывается.
+
## Анкета кандидата
`pages/questionnaire` получает каталог специализаций и приватные ответы текущего кандидата через Orval. Черновик остается в состоянии компонента, сохраненные ответы принадлежат React Query, а reload восстанавливает серверную запись. Форма предлагает одну или две специализации, самооценку грейда, доступные языки заданий, стек, опыт и форматы работы. Специализация без опубликованного банка отмечена как находящаяся в разработке; ее можно сохранить без ФСП.
@@ -98,8 +100,10 @@ SPA на React и TypeScript со сборкой Vite и структурой FS
- Согласия (`features/consent-management`): C1-C5 выдаются и отзываются по отдельности, текст и версия показаны до выдачи. Блок каждой цели имеет якорь, на который переводит фокус кнопка "Перейти к согласию C2".
- Публикация (`features/profile-visibility`): шаг 1 показывает, действует ли C2 по полной активной истории согласий; неизвестное или частично загруженное состояние не считается согласием, сохранение недоступно. Кнопка шага только переносит фокус к блоку C2 и ничего не выдает. Далее выбираются состояние карточки и поля, а публикация сохраняется отдельным действием (`SetMyPublication`, `expected_version` в теле). Конфликт 412 оставляет черновик на экране и предлагает явно загрузить актуальные настройки; ошибка сохранения не сбрасывает черновик. Отзыв C2 закрывает карточку, а новое C2 ее не открывает.
- Объяснение закрытия: по `closed_reason` экран говорит, что будущие чтения закрыты сразу, что новое C2 не откроет карточку само, и что бывшей компании для контактов нужны новое приглашение и новое согласие C4. Те же слова выводятся после отзыва C2, скрытия организации, снятия скрытия и повторной публикации: прежний доступ к контактам не восстанавливается. Скрытие не меняет запись C4 в журнале согласий, поэтому рядом с C4 скрытой компании выведено пояснение, что запись не возвращает доступ к контактам.
+- Проекты в публикации. Поле `projects` - отдельный выбор «Проекты: название, описание и технологии». Предупреждение стоит под ним всегда (его читает вспомогательная технология вместе с чекбоксом) и становится «предупреждающим» после выбора: тексты проектов пишет кандидат и по ним его могут узнать, размер группы похожих кандидатов их не скрывает, адрес репозитория и его владелец компаниям не показываются никогда, они видят только отметку о найденном публичном репозитории.
- Статус поиска (`SetMySearchStatus`) - отдельный запрос и отдельный текст. Он не меняет публикацию и не выдает согласие.
- Предпросмотр для работодателя (`EmployerCardPreview` из `entities/candidate-view`) строится только из ответа `GET /me/privacy/preview`. Псевдоним предпросмотра отделен от псевдонимов организаций. Подтвержденные категории и самооценка выведены раздельно; у каждой специализации свой статус "Грейд подтвержден" или "Грейд не подтвержден", различимый по форме значка и тексту, а не по цвету. Кандидат без подтвержденного грейда видит заявленный уровень (или "Уровень не указан") и статус "Грейд не подтвержден" для каждой специализации отдельно; подтвержденный Backend не переносится на сетевую специализацию. Блок подтверждающих фактов показывает навык, грейд, уровень подтверждения, год и основу (`synthetic_demo` выводится как "Результат теста"; калибровка в интерфейсе не показывается). Закрытая карточка показана пустым состоянием. Предпросмотр не создает записи доступа и не учитывает фильтры организаций.
+- Проекты в предпросмотре и в карточке работодателя показывает общий компонент `PublishedProjects` (`shared/ui`): название, описание (текст с переводами строк), теги и бейдж «Подтвержден публичным репозиторием» для `repository_verified`, с пояснением, что авторство отметка не доказывает. Адреса и ссылки нет ни в данных, ни в разметке; весь текст кандидата выводится как текст.
- Скрытие организаций: кнопка скрытия предлагается только организациям из собственной истории доступа (сервер отвечает 404 на остальные) и только после полной загрузки списка скрытых организаций. Снятие скрытия не восстанавливает контактный доступ.
- Истории: история настроек и история доступа к карточке постраничные; частичная страница не выдается за полную. Запись доступа показывает вид обращения, время и организацию, если сервер ее назвал (иначе "Организация не раскрывается"); сотрудников, запросов, фильтров и места в выдаче в ней нет. Пустая история и ошибка загрузки показаны отдельными состояниями.
- Ниже остается переход к запросу ручной оценки.
@@ -144,7 +148,8 @@ SPA на React и TypeScript со сборкой Vite и структурой FS
- Специализации. Одна запись - это кандидат в одной специализации; один псевдоним может стоять в двух группах (подтвержден в Backend, не подтвержден в сетях). Если в результате больше одной специализации, появляется переключатель представления ("Все специализации", затем каждая): он скрывает записи других специализаций, не пересчитывает ничего и не переносит подтверждение. Псевдоним показан сокращенно (`entities/match/model/views.ts`), полный нужен только запросам и ссылке на приглашение.
- Запись (`entities/match`). Показаны специализация, статус "Грейд подтвержден: X" или "Грейд не подтвержден" (форма значка и текст), подтвержденная категория и сила подтверждения отдельной строкой от заявленного кандидатом грейда, безопасный контекст карточки (технологии, опыт, форматы, ожидания) и серверное объяснение источников: каждая строка `evidence_summary` с состоянием "Подтверждено", "Подтверждено частично", "Только заявлено кандидатом" или "Пробел: подтверждения нет". Значение `null` из контекста выводится как "Нет значения в карточке": контракт не говорит, скрыто оно или отсутствует. Контактов, настоящего идентификатора и причин отсутствия подтверждения в записи нет.
- Объяснение раскрывается кнопкой с `aria-expanded`. Оно строится только из компонентов ответа: Fit, Cov, Dom, Sem, перцентиль, V, Fr, Rsp и итоговый балл S показаны ровно так, как пришли, без округления сверх шести знаков. Нейтральное значение (`unknown_flags`) подписано "Нейтральное значение, не измерено" с причиной (`ml_unavailable`, `cohort_below_30`, `percentile_not_computed` и другие). Перцентиль `null` выводится как "Нет значения", число не выдумывается. Нулевой соревновательный вклад назван "не штрафом". У записи без подтвержденного грейда есть только Fit и Cov: балла S, перцентиля и категории для нее не считают, и экран их не рисует. Неизвестное вне баллов (опыт, форматы, ожидания, результат проверки) перечислено в блоке "Что неизвестно" с пометкой, что это не отсутствие способности.
-- Открытие карточки. Кнопка "Открыть карточку" читает `GET /organizations/{org_id}/candidate-cards/{handle}`, а при наличии категорий - и раздел доказательств; без категорий сервер раздел не отдает, поэтому запрос не отправляется. Чтения не повторяются автоматически и не кешируются после ухода с экрана (`gcTime: 0`, без обновления при фокусе): каждое чтение попадает в журнал доступа кандидата. Закрытая панель остается в дереве, повторное открытие не читает карточку снова. Ответ 429 показывает "Квота просмотров карточек исчерпана" и время из `Retry-After`; если сервер его не назвал, время не выдумывается. Ответ 404 одним текстом заменяет все скрытые случаи и не называет причину.
+- Совпадения по смыслу (`semanticBlock` в `entities/match`). Внутри "Почему в подборке" блок "Совпадения по смыслу" печатает `semantic_evidence` в порядке и в пределах, которые прислал сервер: строка "тип требования и его текст → тип элемента и его название" (требование: "Обязательный навык", "Желательный навык", "Задача"; элемент: "Проект", "Стек", "Роль") и тег "Высокое сходство" или "Среднее сходство". У проекта показано название, а у проекта с `repository_verified` еще бейдж "Публичный репозиторий"; у стека и ролей названий нет, поэтому стоят подписи "Технологии карточки" и "Специализации и грейды карточки", а бейдж им не ставится. Если списка нет, потому что сервер назвал компонент `semantics` неизвестным по причине `ml_unavailable`, блок пишет "Совпадения по смыслу: смысловой анализ недоступен." теми же словами, что и объяснение; пустой список без такого флага (поиск по всем профилям, нет совпадений) блок не показывает. Адрес и владелец репозитория не могут попасть в разбор: адаптер отклоняет ответ с полем вне контракта.
+- Открытие карточки. Кнопка "Открыть карточку" читает `GET /organizations/{org_id}/candidate-cards/{handle}`, а при наличии категорий - и раздел доказательств; без категорий сервер раздел не отдает, поэтому запрос не отправляется. Чтения не повторяются автоматически и не кешируются после ухода с экрана (`gcTime: 0`, без обновления при фокусе): каждое чтение попадает в журнал доступа кандидата. Закрытая панель остается в дереве, повторное открытие не читает карточку снова. Ответ 429 показывает "Квота просмотров карточек исчерпана" и время из `Retry-After`; если сервер его не назвал, время не выдумывается. Ответ 404 одним текстом заменяет все скрытые случаи и не называет причину. Если кандидат опубликовал проекты, панель карточки показывает их блоком "Проекты" (название, описание, теги, бейдж подтвержденного публичного репозитория) без адреса.
- Приглашение. Кнопка "Пригласить" есть у каждой записи, в том числе у неподтвержденной. Она ведет на `/employer/invitations/new` с параметрами `organization_id`, `candidate_handle`, `specialization` и, для поиска по потребности, `need_id` (см. [приглашение кандидату](#приглашение-кандидату)). Псевдоним привязан к организации и не является идентификатором кандидата.
- Раскладка. Форма стоит над выдачей на всех ширинах: основание поиска (сегментный переключатель "По потребности" и "По всем профилям"), выборы, ряд фильтр-чипов (технологии, формат, совместимость ожиданий; примененный чип синий и с галочкой) и действие; выдача идет на всю ширину. Запись на 768 px и шире - колонка содержимого и колонка действий ("Пригласить", объяснение, карточка); на 360 px действия и факты складываются в один столбец. Блок "Почему в подборке" набран моно на вложенной поверхности: знак "+" (подтверждено), "+/-" (частично), "?" (заявлено), "-" (пробел) повторяет слово состояния. Чип технологии, которую запросил поиск, помечен точкой и скрытым текстом "совпадает с условием поиска". Все действия доступны с клавиатуры, фокус виден, статус кодируется текстом и формой, а не цветом.
@@ -280,6 +285,8 @@ SPA на React и TypeScript со сборкой Vite и структурой FS
- `Tabs` (шаблон вкладок WAI-ARIA, стрелки, Home и End, неактивные панели остаются в дереве со скрытым атрибутом, поэтому состояние формы сохраняется) и `SegmentedControl` (нативная группа радиокнопок в виде капсул). `SectionSwitch` - переключатель подразделов в виде капсул, но из ссылок на маршруты: у него нет панелей, поэтому вкладки не подходят.
- `StatusView`, `LoadingState`, `EmptyState`, `ErrorState`, `ForbiddenState`, `SavingStatus` - состояния экранов. У каждого состояния своя форма и текст; пустое состояние рисует дорожку платы, которая заканчивается пустым узлом. `ErrorState` показывает код, статус, текст сервера и идентификатор запроса как обычный текст и предлагает повтор. `Skeleton` - декоративные заготовки строк при загрузке, только вместе с сообщением о загрузке.
- `QueryView` - превращает результат запроса в загрузку, ошибку, отсутствие доступа (401 и 403 без повтора), пустое состояние или данные.
+- `describeError` - русский текст ошибки по коду проблемы, а для неизвестного кода по HTTP-статусу. Код `service_unavailable` (503, например пока загружается модель) показан как "Сервис пока не готов" с советом повторить через минуту; серверный текст остается только технической деталью.
+- `PublishedProjects` - проекты, которые кандидат опубликовал в анонимной карточке: название, описание, теги и бейдж "Подтвержден публичным репозиторием". Это чисто презентационный компонент без адреса репозитория; текст кандидата выводится как текст, никогда как разметка.
- `TrustLevel` - пустая метка, кольцо, частичная или полная заливка с видимой подписью.
- `CircuitTrace`, `Mono`, `VisuallyHidden`, `SkipLink`, `MainRegion`.
diff --git a/frontend/e2e/acceptance-path.spec.ts b/frontend/e2e/acceptance-path.spec.ts
index 45159a1..959208f 100644
--- a/frontend/e2e/acceptance-path.spec.ts
+++ b/frontend/e2e/acceptance-path.spec.ts
@@ -228,7 +228,7 @@ async function saveProfile(candidate: Candidate): Promise {
await page.getByLabel("Имя и фамилия").fill(candidate.fullName);
await page.getByLabel("Контактный email").fill(candidate.email);
await page.getByLabel("Телефон").fill(candidate.phone);
- for (const heading of ["Роли", "Опыт", "Навыки", "Условия", "Проверка"]) {
+ for (const heading of ["Роли", "Опыт", "Проекты", "Навыки", "Условия", "Проверка"]) {
await page.getByRole("button", { name: "Далее", exact: true }).click();
await expect(page.getByRole("heading", { name: new RegExp(`\\. ${heading}$`) })).toBeFocused();
}
diff --git a/frontend/e2e/candidate-home.spec.ts b/frontend/e2e/candidate-home.spec.ts
index cabdce4..8a415e8 100644
--- a/frontend/e2e/candidate-home.spec.ts
+++ b/frontend/e2e/candidate-home.spec.ts
@@ -160,7 +160,7 @@ test.describe("candidate home with the real backend", () => {
await expect(page.getByRole("heading", { name: "Профиль", level: 1 })).toBeVisible();
await page.getByLabel("Имя и фамилия").fill("Тестовый кандидат");
// The profile is a form in steps: walk to the review step, then save.
- for (const heading of ["Роли", "Опыт", "Навыки", "Условия", "Проверка"]) {
+ for (const heading of ["Роли", "Опыт", "Проекты", "Навыки", "Условия", "Проверка"]) {
await page.getByRole("button", { name: "Далее", exact: true }).click();
await expect(
page.getByRole("heading", { name: new RegExp(`\\. ${heading}$`) }),
diff --git a/frontend/e2e/match-search.spec.ts b/frontend/e2e/match-search.spec.ts
index 5e83f54..a5aa275 100644
--- a/frontend/e2e/match-search.spec.ts
+++ b/frontend/e2e/match-search.spec.ts
@@ -489,6 +489,25 @@ const noContext = {
salary_compatibility: null,
};
+const semanticEvidence = [
+ {
+ requirement_kind: "task",
+ requirement_text: "Разработать сервис сверки платежей",
+ item_kind: "project",
+ project_title: "Платежный шлюз",
+ repository_verified: true,
+ similarity: "high",
+ },
+ {
+ requirement_kind: "required_skill",
+ requirement_text: "Проектирование схем PostgreSQL",
+ item_kind: "stack",
+ project_title: null,
+ repository_verified: false,
+ similarity: "medium",
+ },
+];
+
function confirmedEntry(handle: string, grade: string, coverage: number, overrides = {}) {
return {
candidate_handle: handle,
@@ -899,6 +918,71 @@ test.describe("employer candidate search with a stubbed API", () => {
await expect(network.getByText("Пробел: подтверждения нет")).toBeVisible();
});
+ test("explains the matches by meaning without a repository address", async ({ page }) => {
+ const entry = confirmedEntry(handleA, "middle", 0.853333, {
+ semantic_evidence: semanticEvidence,
+ unknown_flags: [{ component: "percentile", reason: "cohort_below_30" }],
+ });
+ const card = {
+ pseudonym: handleA,
+ categories: null,
+ stack: ["go"],
+ self_assessment: null,
+ experience_band: null,
+ work_formats: null,
+ salary_compatibility: null,
+ projects: [
+ {
+ title: "Платежный шлюз",
+ description: "Проводки и сверки платежей.",
+ stack: ["Go", "PostgreSQL"],
+ repository_verified: true,
+ },
+ ],
+ };
+ await installFakeApi(page, {
+ searches: [threeGroups({ groups: { main: [entry], near: [], unconfirmed: [] } })],
+ card,
+ });
+ await openSearch(page);
+ await runSearch(page);
+
+ const confirmed = groupSection(page, "Подтвержденные").getByRole("article");
+ const why = confirmed.getByRole("region", { name: "Почему в подборке" });
+ await expect(why.getByRole("heading", { name: "Совпадения по смыслу" })).toBeVisible();
+ const rows = why.getByRole("listitem").filter({ hasText: "сходство" });
+ await expect(rows).toHaveCount(2);
+ await expect(rows.nth(0)).toContainText("Разработать сервис сверки платежей");
+ await expect(rows.nth(0)).toContainText("Проект");
+ await expect(rows.nth(0)).toContainText("Платежный шлюз");
+ await expect(rows.nth(0)).toContainText("Высокое сходство");
+ await expect(rows.nth(0)).toContainText("Публичный репозиторий");
+ await expect(rows.nth(1)).toContainText("Стек");
+ await expect(rows.nth(1)).toContainText("Среднее сходство");
+ await expect(rows.nth(1)).not.toContainText("Публичный репозиторий");
+ await expect(why.getByText("смысловой анализ недоступен")).toHaveCount(0);
+ await expect(confirmed.locator('a[href*="github"]')).toHaveCount(0);
+ await expectNoHorizontalOverflow(page);
+
+ await confirmed.getByRole("button", { name: /Открыть карточку/ }).click();
+ const panel = confirmed.getByRole("region", { name: "Карточка кандидата" });
+ await expect(panel.getByRole("heading", { name: "Проекты" })).toBeVisible();
+ await expect(panel.getByText("Подтвержден публичным репозиторием")).toBeVisible();
+ expect(await panel.innerText()).not.toMatch(/github\.com/);
+ await captureReview(page, "match-semantic-evidence");
+ });
+
+ test("keeps the unavailable wording in the meaning block when ML was down", async ({ page }) => {
+ await installFakeApi(page);
+ await openSearch(page);
+ await runSearch(page);
+
+ const why = groupSection(page, "Подтвержденные")
+ .getByRole("article")
+ .getByRole("region", { name: "Почему в подборке" });
+ await expect(why.getByText("Совпадения по смыслу: смысловой анализ недоступен.")).toBeVisible();
+ });
+
test("explains a partial output without a count", async ({ page }) => {
await installFakeApi(page, { searches: [threeGroups({ truncated: true })] });
await openSearch(page);
diff --git a/frontend/e2e/privacy-visibility.spec.ts b/frontend/e2e/privacy-visibility.spec.ts
index 6da0b65..dfde1ca 100644
--- a/frontend/e2e/privacy-visibility.spec.ts
+++ b/frontend/e2e/privacy-visibility.spec.ts
@@ -403,7 +403,7 @@ test.describe("candidate without a confirmed grade with the real backend", () =>
await page.getByLabel("Специализация").nth(1).selectOption("network_engineer");
await page.getByLabel("Моя оценка уровня").nth(0).selectOption("middle");
await page.getByLabel("Моя оценка уровня").nth(1).selectOption("junior");
- for (const heading of ["Опыт", "Навыки", "Условия", "Проверка"]) {
+ for (const heading of ["Опыт", "Проекты", "Навыки", "Условия", "Проверка"]) {
await page.getByRole("button", { name: "Далее", exact: true }).click();
await expect(
page.getByRole("heading", { name: new RegExp(`\\. ${heading}$`) }),
@@ -598,7 +598,17 @@ function previewFor(state: FakeState): Record {
experience_band: null,
work_formats: null,
salary_compatibility: null,
- projects: null,
+ projects: fields.includes("projects")
+ ? [
+ {
+ title: "Платежный шлюз",
+ description: "Проводки и сверки платежей.",
+ stack: ["Go", "PostgreSQL"],
+ repository_verified: true,
+ },
+ { title: "Каталог", description: null, stack: [], repository_verified: false },
+ ]
+ : null,
},
evidence: fields.includes("categories")
? {
@@ -795,6 +805,43 @@ test.describe("candidate visibility states with a stubbed API", () => {
await expectNoHorizontalOverflow(page);
});
+ test("warns before the projects are published and shows them in the preview without an address", async ({
+ page,
+ }) => {
+ const state = freshState({
+ publication: {
+ state: "published",
+ closed_reason: null,
+ fields: ["categories", "projects"],
+ consent_id: c2RecordId,
+ published_at: "2026-10-08T10:00:00Z",
+ version: 1,
+ },
+ });
+ await installFakeApi(page, state);
+ await page.goto("/candidate/privacy");
+
+ const publication = page.getByRole("region", { name: "Публикация карточки", exact: true });
+ const projects = publication.getByRole("checkbox", {
+ name: "Проекты: название, описание и технологии",
+ });
+ await expect(projects).toBeChecked();
+ await expect(publication.getByText(/по ним вас могут узнать/)).toBeVisible();
+ await expect(
+ publication.getByText(/Адрес репозитория и его владелец компаниям не показываются никогда/),
+ ).toBeVisible();
+
+ const preview = previewSection(page);
+ await expect(preview.getByRole("heading", { name: "Проекты" })).toBeVisible();
+ await expect(preview.getByText("Платежный шлюз")).toBeVisible();
+ await expect(preview.getByText("PostgreSQL", { exact: true })).toBeVisible();
+ await expect(preview.getByText("Подтвержден публичным репозиторием")).toHaveCount(1);
+ await expect(preview.locator('a[href*="github"]')).toHaveCount(0);
+ await expect(preview.getByText(/github\.com/)).toHaveCount(0);
+ await captureReview(page, "privacy-projects");
+ await expectNoHorizontalOverflow(page);
+ });
+
test("a changed search status never publishes the card", async ({ page }) => {
const state = freshState();
await installFakeApi(page, state);
diff --git a/frontend/e2e/profile-edit.spec.ts b/frontend/e2e/profile-edit.spec.ts
index 8aca735..a2a5b35 100644
--- a/frontend/e2e/profile-edit.spec.ts
+++ b/frontend/e2e/profile-edit.spec.ts
@@ -130,7 +130,7 @@ test.describe("candidate profile", () => {
await expect(page.getByRole("heading", { name: /\. Проверка$/ })).toBeFocused();
return;
}
- for (const heading of ["Роли", "Опыт", "Навыки", "Условия", "Проверка"]) {
+ for (const heading of ["Роли", "Опыт", "Проекты", "Навыки", "Условия", "Проверка"]) {
if (await save.isVisible()) break;
await nextStep(page, heading);
}
@@ -201,6 +201,7 @@ test.describe("candidate profile", () => {
}) => {
const suffix = crypto.randomUUID().slice(0, 8);
const name = `Тестовый профиль ${suffix}`;
+ const projectTitle = `Платежный шлюз ${suffix}`;
const contactEmail = `contact-${suffix}@example.test`;
const { email } = await registerCandidate(page);
@@ -211,7 +212,7 @@ test.describe("candidate profile", () => {
await page.getByLabel("Телефон").fill("+79990000000");
await page.getByLabel("Telegram").fill("@candidate_123");
- await expect(page.getByText("Шаг 1 из 6", { exact: true })).toBeVisible();
+ await expect(page.getByText("Шаг 1 из 7", { exact: true })).toBeVisible();
await nextStep(page, "Роли");
await page.getByRole("button", { name: "Добавить специализацию" }).click();
await page.getByLabel("Специализация").selectOption("backend");
@@ -236,6 +237,23 @@ test.describe("candidate profile", () => {
).toBeFocused();
await page.getByRole("checkbox", { name: /Подтверждаю, что места работы 1 и 2/ }).check();
+ await nextStep(page, "Проекты");
+ await page.getByRole("button", { name: "Добавить проект" }).click();
+ await page.getByLabel("Название", { exact: true }).fill(projectTitle);
+ await page.getByLabel("Что делает проект и что делали вы").fill("Проводки и сверки платежей.");
+ const projectTags = page.getByLabel("Технологии проекта");
+ await projectTags.fill("Go");
+ await projectTags.press("Enter");
+ await projectTags.fill("PostgreSQL, Kafka");
+ await projectTags.press("Enter");
+ await expect(page.getByRole("button", { name: /Убрать технологию Kafka/ })).toBeVisible();
+ // A wrong repository address stops the step and names the field.
+ await page.getByLabel("Репозиторий на GitHub, необязательно").fill("https://gitlab.com/a/b");
+ await page.getByRole("button", { name: "Далее", exact: true }).click();
+ await expect(page.getByRole("alert").filter({ hasText: "Проекты, проект 1" })).toBeFocused();
+ await expect(page.getByText(/Нужен адрес вида https:\/\/github\.com/).first()).toBeVisible();
+ await page.getByLabel("Репозиторий на GitHub, необязательно").fill("");
+
await nextStep(page, "Навыки");
await page.getByRole("button", { name: "Добавить навык" }).click();
await page.getByLabel("Навык 1", { exact: true }).fill("Go");
@@ -307,6 +325,17 @@ test.describe("candidate profile", () => {
await expect(page.getByText("Сохраненный шаг аккаунта: Согласия.")).toBeVisible();
await expectResponsiveKeyboardFlow(page);
+ // The saved project comes back with its tags.
+ await openReview(page);
+ await editStep(page, "проекты", "Проекты");
+ await expect(page.getByLabel("Название", { exact: true })).toHaveValue(projectTitle);
+ await expect(page.getByLabel("Что делает проект и что делали вы")).toHaveValue(
+ "Проводки и сверки платежей.",
+ );
+ await expect(page.getByRole("button", { name: /Убрать технологию PostgreSQL/ })).toBeVisible();
+ await page.reload();
+ await expect(page.getByLabel("Имя и фамилия")).toHaveValue(name);
+
const secondContext = await browser.newContext({
baseURL: e2eBaseUrl(),
locale: "ru-RU",
diff --git a/frontend/src/entities/candidate-view/index.ts b/frontend/src/entities/candidate-view/index.ts
index b868da6..037b34c 100644
--- a/frontend/src/entities/candidate-view/index.ts
+++ b/frontend/src/entities/candidate-view/index.ts
@@ -16,6 +16,7 @@ export {
presentCandidatePreview,
publicationDraftFromSettings,
privacyEventLabels,
+ projectsPublicationWarning,
publishableCardFields,
specializationLabels,
} from "./model/presentation";
@@ -24,6 +25,7 @@ export { EmployerCardPreview } from "./ui/employer-card-preview";
export type {
C2State,
CandidateViewPresentation,
+ CardProjectPresentation,
EvidencePresentation,
PublicationClosureNotice,
SelfAssessmentPresentation,
diff --git a/frontend/src/entities/candidate-view/model/presentation.test.ts b/frontend/src/entities/candidate-view/model/presentation.test.ts
index 8dc4189..caa9f59 100644
--- a/frontend/src/entities/candidate-view/model/presentation.test.ts
+++ b/frontend/src/entities/candidate-view/model/presentation.test.ts
@@ -180,6 +180,62 @@ describe("candidate card presentation", () => {
});
});
+describe("published projects", () => {
+ const card = {
+ pseudonym: `cv1_${"c".repeat(43)}`,
+ categories: null,
+ stack: null,
+ self_assessment: null,
+ experience_band: null,
+ work_formats: null,
+ salary_compatibility: null,
+ };
+
+ it("presents the title, the description, the tags, and the verification, in the published order", () => {
+ const result = presentCandidatePreview(
+ preview({
+ ...card,
+ projects: [
+ {
+ title: "Платежный шлюз",
+ description: "Проводки и сверки.",
+ stack: ["Go", "PostgreSQL"],
+ repository_verified: true,
+ },
+ { title: "Каталог", description: null, stack: [], repository_verified: false },
+ ],
+ }),
+ );
+
+ expect(result?.projects).toEqual([
+ {
+ title: "Платежный шлюз",
+ description: "Проводки и сверки.",
+ stack: ["Go", "PostgreSQL"],
+ repositoryVerified: true,
+ },
+ { title: "Каталог", description: null, stack: [], repositoryVerified: false },
+ ]);
+ });
+
+ it("keeps an unpublished field null, so the card does not tell it from no value", () => {
+ expect(presentCandidatePreview(preview({ ...card, projects: null }))?.projects).toBeNull();
+ });
+
+ it("carries no repository address even if a response sent one", () => {
+ const withAddress = {
+ title: "Каталог",
+ description: null,
+ stack: [],
+ repository_verified: true,
+ repository_url: "https://github.com/example-org/catalog",
+ };
+ const result = presentCandidatePreview(preview({ ...card, projects: [withAddress] }));
+
+ expect(JSON.stringify(result)).not.toContain("github.com");
+ });
+});
+
describe("editable card fields", () => {
it("exposes only safe groups supported by the anonymous-card contract", () => {
const stored: CardField[] = [
@@ -197,8 +253,14 @@ describe("editable card fields", () => {
"experience",
"work_formats",
"salary_compatibility",
+ "projects",
]);
expect(editableCardFields(stored)).toEqual(["categories", "work_formats"]);
+ expect(editableCardFields([...stored, "projects"])).toEqual([
+ "categories",
+ "work_formats",
+ "projects",
+ ]);
});
});
diff --git a/frontend/src/entities/candidate-view/model/presentation.ts b/frontend/src/entities/candidate-view/model/presentation.ts
index ab21b62..407bf15 100644
--- a/frontend/src/entities/candidate-view/model/presentation.ts
+++ b/frontend/src/entities/candidate-view/model/presentation.ts
@@ -26,6 +26,7 @@ export const publishableCardFields = [
"experience",
"work_formats",
"salary_compatibility",
+ "projects",
] as const satisfies readonly CardField[];
export type PublishableCardField = (typeof publishableCardFields)[number];
@@ -144,8 +145,20 @@ export const cardFieldLabels: Readonly> = {
experience: "Общий опыт",
work_formats: "Форматы работы",
salary_compatibility: "Совместимость по зарплатным ожиданиям",
+ projects: "Проекты: название, описание и технологии",
};
+/**
+ * What publishing the projects reveals. It is shown beside the choice, before
+ * the candidate makes it, and again in the card preview.
+ */
+export const projectsPublicationWarning = {
+ identify:
+ "Название и описание проектов пишете вы, и по ним вас могут узнать. Не публикуйте проект, если в тексте есть имя, контакт или название работодателя. Размер группы похожих кандидатов эти тексты не скрывает: карточка с проектами может быть единственной в своем роде.",
+ repository:
+ "Адрес репозитория и его владелец компаниям не показываются никогда. Они видят только отметку, что публичный репозиторий проекта найден.",
+} as const;
+
export const specializationLabels = {
backend: "Backend",
frontend: "Frontend",
@@ -215,6 +228,13 @@ export type EvidencePresentation = {
basisLabel: string;
};
+export type CardProjectPresentation = {
+ title: string;
+ description: string | null;
+ stack: readonly string[];
+ repositoryVerified: boolean;
+};
+
export type CandidateViewPresentation = {
pseudonym: string;
categories: readonly CategoryPresentation[] | null;
@@ -223,6 +243,8 @@ export type CandidateViewPresentation = {
experience: string | null;
workFormats: readonly string[] | null;
salaryCompatibility: string | null;
+ /** Published projects in the candidate's order; null when the field is not published. */
+ projects: readonly CardProjectPresentation[] | null;
/**
* Supporting assessment facts as an organization reads them. Null while the
* card is closed; an empty list when no visible fact supports a category.
@@ -302,6 +324,13 @@ export function presentCandidatePreview(preview: CardPreview): CandidateViewPres
salaryCompatibility: card.salary_compatibility
? salaryCompatibilityLabels[card.salary_compatibility]
: null,
+ projects:
+ card.projects?.map((project) => ({
+ title: project.title,
+ description: project.description,
+ stack: [...project.stack],
+ repositoryVerified: project.repository_verified,
+ })) ?? null,
evidence: preview.evidence ? preview.evidence.items.map(evidencePresentation) : null,
};
}
diff --git a/frontend/src/entities/candidate-view/ui/employer-card-preview.test.tsx b/frontend/src/entities/candidate-view/ui/employer-card-preview.test.tsx
index 8435a8b..556647c 100644
--- a/frontend/src/entities/candidate-view/ui/employer-card-preview.test.tsx
+++ b/frontend/src/entities/candidate-view/ui/employer-card-preview.test.tsx
@@ -135,6 +135,39 @@ describe("employer card preview", () => {
expect(markup).toContain("2026");
});
+ it("shows published projects with their tags, a badge for a verified repository, and no address", () => {
+ const base = published();
+ const markup = render({
+ ...base,
+ fields: ["projects"],
+ card: {
+ ...(base.card as NonNullable),
+ projects: [
+ {
+ title: "Платежный шлюз",
+ description: "Проводки и сверки.",
+ stack: ["Go", "PostgreSQL"],
+ repository_verified: true,
+ },
+ { title: "Каталог", description: null, stack: ["Django"], repository_verified: false },
+ ],
+ },
+ });
+
+ expect(markup).toContain(">Проекты");
+ expect(markup).toContain("Платежный шлюз");
+ expect(markup).toContain("Проводки и сверки.");
+ expect(markup).toContain(">PostgreSQL<");
+ expect(markup.match(/Подтвержден публичным репозиторием/g)).toHaveLength(1);
+ expect(markup).toContain("Адрес репозитория и его владелец ей не показываются");
+ expect(markup).not.toContain("github.com");
+ expect(markup).not.toContain("href=");
+ });
+
+ it("shows no projects block while the field is not published", () => {
+ expect(render(published())).not.toContain(">Проекты");
+ });
+
it("explains a closed card without offering to open it", () => {
const markup = render({
state: "closed",
diff --git a/frontend/src/entities/candidate-view/ui/employer-card-preview.tsx b/frontend/src/entities/candidate-view/ui/employer-card-preview.tsx
index 1ec276e..e069809 100644
--- a/frontend/src/entities/candidate-view/ui/employer-card-preview.tsx
+++ b/frontend/src/entities/candidate-view/ui/employer-card-preview.tsx
@@ -1,5 +1,11 @@
import type { CardPreview } from "../../../shared/api/schemas";
-import { EmptyState, ErrorState, LoadingState, TrustLevel } from "../../../shared/ui";
+import {
+ EmptyState,
+ ErrorState,
+ LoadingState,
+ PublishedProjects,
+ TrustLevel,
+} from "../../../shared/ui";
import {
presentCandidatePreview,
type CandidateViewPresentation,
@@ -169,6 +175,19 @@ export function EmployerCardPreview({
)}
) : null}
+ {card.projects ? (
+
+
Проекты
+ {card.projects.length > 0 ? (
+
+ ) : (
+
Опубликованных проектов в карточке нет.
+ )}
+
+ Так проекты видит компания. Адрес репозитория и его владелец ей не показываются.
+
+
+ ) : null}
diff --git a/frontend/src/entities/candidate/index.ts b/frontend/src/entities/candidate/index.ts
index 6b1f251..3ad0ec6 100644
--- a/frontend/src/entities/candidate/index.ts
+++ b/frontend/src/entities/candidate/index.ts
@@ -1,11 +1,13 @@
export {
addExperience,
+ addProject,
addRole,
addSoftSkill,
addStack,
buildCandidateProfileUpdate,
mapProfileServerErrors,
moveExperience,
+ moveProject,
profilePointerField,
removeExperience,
removeItem,
@@ -14,6 +16,7 @@ export {
toCandidateProfileDraft,
updateExperienceDraft,
updateFieldDraft,
+ updateProjectDraft,
updateRoleDraft,
updateSalaryDraft,
updateSoftSkillDraft,
@@ -21,11 +24,26 @@ export {
type CandidateProfileDraft,
type ExperienceDraft,
type FieldDraft,
+ type ProjectDraft,
type ProfileFormIssue,
type RoleDraft,
type SoftSkillDraft,
type StackDraft,
} from "./model/profile-form";
+export {
+ describeRepositoryStatus,
+ hasPendingRepositoryChecks,
+ maxProjectDescription,
+ maxProjectStack,
+ maxProjectStackTag,
+ maxProjectTitle,
+ maxProjects,
+ normalizeRepositoryUrl,
+ parseGitHubRepository,
+ repositoryChecksOf,
+ repositoryKey,
+ type RepositoryStatusView,
+} from "./model/profile-projects";
export {
buildCandidateJourney,
onboardingStepLabels,
diff --git a/frontend/src/entities/candidate/model/profile-form.test.ts b/frontend/src/entities/candidate/model/profile-form.test.ts
index 2c019a2..772d908 100644
--- a/frontend/src/entities/candidate/model/profile-form.test.ts
+++ b/frontend/src/entities/candidate/model/profile-form.test.ts
@@ -2,14 +2,18 @@ import { describe, expect, it } from "vitest";
import type { CandidateProfile } from "../../../shared/api/schemas";
import {
addExperience,
+ addProject,
buildCandidateProfileUpdate,
mapProfileServerErrors,
moveExperience,
+ moveProject,
+ removeItem,
reviewExperienceOverlaps,
setParallelAcknowledgement,
toCandidateProfileDraft,
updateExperienceDraft,
updateFieldDraft,
+ updateProjectDraft,
} from "./profile-form";
const unknownClaim = { status: "unknown", value: null, source: null } as const;
@@ -233,3 +237,193 @@ describe("candidate profile draft mapping", () => {
]);
});
});
+
+describe("candidate profile projects", () => {
+ const now = new Date("2026-06-15T00:00:00Z");
+
+ function withProject(
+ patch: Partial[2]> = {},
+ id = "new",
+ draft = toCandidateProfileDraft(blankProfile()),
+ ) {
+ return updateProjectDraft(addProject(draft, id), id, {
+ title: "Платежный шлюз",
+ description: "Проводки и сверки.",
+ stack: ["Go", "PostgreSQL"],
+ repository_url: "https://github.com/example-org/payments-ledger",
+ ...patch,
+ });
+ }
+
+ it("always sends the list, so a saved profile never loses its projects", () => {
+ const result = buildCandidateProfileUpdate(toCandidateProfileDraft(blankProfile()), now);
+
+ expect(result.data?.projects).toEqual([]);
+ });
+
+ it("sends a typed project as confirmed with the canonical repository address", () => {
+ const result = buildCandidateProfileUpdate(
+ withProject({
+ title: " Платежный шлюз ",
+ repository_url: " https://github.com/example-org/ledger.git ",
+ }),
+ now,
+ );
+
+ expect(result.issues).toEqual([]);
+ expect(result.data?.projects).toEqual([
+ {
+ title: "Платежный шлюз",
+ description: "Проводки и сверки.",
+ stack: ["Go", "PostgreSQL"],
+ repository_url: "https://github.com/example-org/ledger",
+ status: "confirmed",
+ },
+ ]);
+ });
+
+ it("sends an empty description and an empty address as null", () => {
+ const result = buildCandidateProfileUpdate(
+ withProject({ description: " ", repository_url: "", stack: [] }),
+ now,
+ );
+
+ expect(result.data?.projects).toEqual([
+ {
+ title: "Платежный шлюз",
+ description: null,
+ stack: [],
+ repository_url: null,
+ status: "confirmed",
+ },
+ ]);
+ });
+
+ it("drops a row without any value and keeps the order of the others", () => {
+ let draft = withProject({}, "first");
+ draft = addProject(draft, "blank");
+ draft = withProject({ title: "Второй", repository_url: "" }, "second", draft);
+
+ const result = buildCandidateProfileUpdate(draft, now);
+
+ expect(result.data?.projects?.map((item) => item.title)).toEqual(["Платежный шлюз", "Второй"]);
+ expect(moveProject(draft, 0, 1).projects[1]?.id).toBe("first");
+ expect(moveProject(draft, 0, -1)).toBe(draft);
+ expect(removeItem(draft, "projects", "blank").projects).toHaveLength(2);
+ });
+
+ it("requires a title once any other value is given", () => {
+ const result = buildCandidateProfileUpdate(withProject({ title: "" }), now);
+
+ expect(result.data).toBeNull();
+ expect(result.issues).toEqual([
+ { field: "projects.0.title", message: "Укажите название проекта." },
+ ]);
+ });
+
+ it("rejects an address that is not a GitHub repository and names the field", () => {
+ for (const address of [
+ "https://gitlab.com/example-org/ledger",
+ "https://github.com/example-org",
+ "https://github.com/example-org/ledger?tab=readme",
+ ]) {
+ const result = buildCandidateProfileUpdate(withProject({ repository_url: address }), now);
+ expect(result.data).toBeNull();
+ expect(result.issues.map((issue) => issue.field)).toEqual(["projects.0.repository_url"]);
+ }
+ });
+
+ it("rejects a repeated repository, also in another letter case or with .git", () => {
+ let draft = withProject({}, "first");
+ draft = withProject(
+ { title: "Копия", repository_url: "https://github.com/Example-Org/Payments-Ledger.git" },
+ "second",
+ draft,
+ );
+
+ const result = buildCandidateProfileUpdate(draft, now);
+
+ expect(result.data).toBeNull();
+ expect(result.issues).toEqual([
+ {
+ field: "projects.1.repository_url",
+ message: "Этот репозиторий уже указан в проекте 1.",
+ },
+ ]);
+ });
+
+ it("rejects a repeated stack tag without regard to letter case and an oversized tag", () => {
+ expect(buildCandidateProfileUpdate(withProject({ stack: ["Go", "go"] }), now).issues).toEqual([
+ { field: "projects.0.stack", message: "Технология повторяется." },
+ ]);
+ expect(
+ buildCandidateProfileUpdate(withProject({ stack: ["a".repeat(51)] }), now).issues[0]?.field,
+ ).toBe("projects.0.stack");
+ expect(
+ buildCandidateProfileUpdate(
+ withProject({ stack: Array.from({ length: 11 }, (_, index) => `tag${index}`) }),
+ now,
+ ).issues[0]?.field,
+ ).toBe("projects.0.stack");
+ });
+
+ it("limits the text and the number of projects like the contract", () => {
+ expect(
+ buildCandidateProfileUpdate(withProject({ description: "я".repeat(501) }), now).issues[0]
+ ?.field,
+ ).toBe("projects.0.description");
+ expect(
+ buildCandidateProfileUpdate(withProject({ title: "я".repeat(101) }), now).issues[0]?.field,
+ ).toBe("projects.0.title");
+
+ let draft = toCandidateProfileDraft(blankProfile());
+ for (let index = 0; index < 11; index += 1) {
+ draft = withProject({ title: `Проект ${index}`, repository_url: "" }, `p${index}`, draft);
+ }
+ expect(buildCandidateProfileUpdate(draft, now).data).toBeNull();
+ });
+
+ it("keeps an untouched suggestion unconfirmed and confirms an edited one", () => {
+ const profile: CandidateProfile = {
+ ...blankProfile(),
+ version: 2,
+ projects: [
+ {
+ title: "Каталог",
+ description: null,
+ stack: ["Django"],
+ repository_url: "https://github.com/example-org/catalog",
+ repository_check: { state: "verified", checked_at: "2026-10-05T09:30:00Z" },
+ status: "extracted",
+ source: suggestion,
+ },
+ ],
+ };
+ let draft = toCandidateProfileDraft(profile);
+
+ expect(buildCandidateProfileUpdate(draft, now).data?.projects).toEqual([
+ {
+ title: "Каталог",
+ description: null,
+ stack: ["Django"],
+ repository_url: "https://github.com/example-org/catalog",
+ status: "extracted",
+ },
+ ]);
+
+ draft = updateProjectDraft(draft, "project-0", { description: "Витрина товаров." });
+ expect(buildCandidateProfileUpdate(draft, now).data?.projects?.[0]?.status).toBe("confirmed");
+ // The expected version of the draft travels with the projects.
+ expect(buildCandidateProfileUpdate(draft, now).data?.expected_version).toBe(2);
+ });
+
+ it("maps server pointers of a project to the field of the form", () => {
+ expect(
+ mapProfileServerErrors([
+ { pointer: "/projects/1/repository_url" },
+ { pointer: "/projects/0/stack/2" },
+ { pointer: "/projects/3/title" },
+ ]).map((issue) => issue.field),
+ ).toEqual(["projects.1.repository_url", "projects.0.stack", "projects.3.title"]);
+ });
+});
diff --git a/frontend/src/entities/candidate/model/profile-form.ts b/frontend/src/entities/candidate/model/profile-form.ts
index 0d26860..2c5ac1b 100644
--- a/frontend/src/entities/candidate/model/profile-form.ts
+++ b/frontend/src/entities/candidate/model/profile-form.ts
@@ -3,6 +3,15 @@ import {
type CandidateProfile,
type CandidateProfileUpdate,
} from "../../../shared/api/schemas";
+import {
+ maxProjectDescription,
+ maxProjectStack,
+ maxProjectStackTag,
+ maxProjectTitle,
+ maxProjects,
+ normalizeRepositoryUrl,
+ repositoryKey,
+} from "./profile-projects";
type ClaimStatus = CandidateProfile["full_name"]["status"];
type DecisionStatus = Exclude;
@@ -39,11 +48,19 @@ type ExperienceValue = Omit<
> & { specialization: CandidateProfile["experience"][number]["specialization"] | "" };
type SoftSkillValue = Pick;
type SalaryValue = CandidateProfile["terms"]["salary_minimum"]["value"];
+/** A project as the form edits it: an empty string stands for no description or repository. */
+type ProjectValue = {
+ title: string;
+ description: string;
+ stack: string[];
+ repository_url: string;
+};
export type StackDraft = StackValue & ItemMetadata;
export type RoleDraft = RoleValue & ItemMetadata;
export type ExperienceDraft = ExperienceValue & ItemMetadata;
export type SoftSkillDraft = SoftSkillValue & ItemMetadata;
+export type ProjectDraft = ProjectValue & ItemMetadata;
export type SalaryDraft = {
amount: string;
@@ -66,6 +83,7 @@ export type CandidateProfileDraft = {
roles: RoleDraft[];
experience: ExperienceDraft[];
softSkills: SoftSkillDraft[];
+ projects: ProjectDraft[];
terms: {
location: FieldDraft;
relocation: FieldDraft;
@@ -164,6 +182,14 @@ export function toCandidateProfileDraft(profile: CandidateProfile): CandidatePro
softSkills: profile.soft_skills.map((item, index) =>
itemDraft(`soft-skill-${index}`, index, item, { skill: item.skill }),
),
+ projects: profile.projects.map((item, index) =>
+ itemDraft(`project-${index}`, index, item, {
+ title: item.title,
+ description: item.description ?? "",
+ stack: [...item.stack],
+ repository_url: item.repository_url ?? "",
+ }),
+ ),
terms: {
location: textFieldDraft(profile.terms.location),
relocation: valueFieldDraft(profile.terms.relocation),
@@ -219,6 +245,14 @@ export function updateExperienceDraft(
return dateChanged ? { ...updated, parallelAcknowledgements: {} } : updated;
}
+export function updateProjectDraft(
+ draft: CandidateProfileDraft,
+ id: string,
+ patch: Partial,
+): CandidateProfileDraft {
+ return updateItem(draft, "projects", id, patch);
+}
+
export function updateSalaryDraft(
draft: CandidateProfileDraft,
patch: Partial>,
@@ -258,7 +292,7 @@ export function updateSoftSkillDraft(
}
function updateItem<
- Key extends "stack" | "roles" | "experience" | "softSkills",
+ Key extends "stack" | "roles" | "experience" | "softSkills" | "projects",
Item extends CandidateProfileDraft[Key][number],
Patch extends Partial>>,
>(draft: CandidateProfileDraft, key: Key, id: string, patch: Patch): CandidateProfileDraft {
@@ -484,7 +518,40 @@ export function addSoftSkill(draft: CandidateProfileDraft, id: string): Candidat
};
}
-export function removeItem(
+export function addProject(draft: CandidateProfileDraft, id: string): CandidateProfileDraft {
+ return {
+ ...draft,
+ projects: [
+ ...draft.projects,
+ {
+ id,
+ originalIndex: null,
+ title: "",
+ description: "",
+ stack: [],
+ repository_url: "",
+ status: "confirmed",
+ originalStatus: null,
+ originalValue: null,
+ source: null,
+ },
+ ],
+ };
+}
+
+export function moveProject(
+ draft: CandidateProfileDraft,
+ index: number,
+ direction: -1 | 1,
+): CandidateProfileDraft {
+ const targetIndex = index + direction;
+ if (targetIndex < 0 || targetIndex >= draft.projects.length) return draft;
+ const projects = [...draft.projects];
+ [projects[index], projects[targetIndex]] = [projects[targetIndex]!, projects[index]!];
+ return { ...draft, projects };
+}
+
+export function removeItem(
draft: CandidateProfileDraft,
key: Key,
id: string,
@@ -516,6 +583,40 @@ function itemDecision(
};
}
+function isBlankProject(item: ProjectDraft): boolean {
+ return (
+ !item.title.trim() &&
+ !item.description.trim() &&
+ item.stack.every((tag) => !tag.trim()) &&
+ !item.repository_url.trim()
+ );
+}
+
+/** The value of a project as the request sends it: trimmed, with the canonical repository address. */
+function projectRequestValue(item: ProjectDraft) {
+ const repositoryUrl = item.repository_url.trim();
+ return {
+ title: item.title.trim(),
+ description: item.description.replaceAll("\r\n", "\n").trim() || null,
+ stack: item.stack.map((tag) => tag.trim()).filter(Boolean),
+ repository_url: repositoryUrl ? (normalizeRepositoryUrl(repositoryUrl) ?? repositoryUrl) : null,
+ };
+}
+
+function projectDecision(item: ProjectDraft) {
+ const value = projectRequestValue(item);
+ const original = item.originalValue
+ ? {
+ title: item.originalValue.title,
+ description: item.originalValue.description || null,
+ stack: item.originalValue.stack,
+ repository_url: item.originalValue.repository_url || null,
+ }
+ : null;
+ const extracted = item.status === "extracted" && original !== null && sameValue(value, original);
+ return { ...value, status: extracted ? "extracted" : "confirmed" };
+}
+
function escapePointerSegment(value: string | number): string {
return String(value).replaceAll("~", "~0").replaceAll("/", "~1");
}
@@ -534,6 +635,7 @@ function fieldForPointer(pointer: string): string {
if (root === "experience" && index !== undefined)
return `experience.${index}.${property ?? "started_on"}`;
if (root === "soft_skills" && index !== undefined) return `softSkills.${index}.skill`;
+ if (root === "projects" && index !== undefined) return `projects.${index}.${property ?? "title"}`;
if (root === "terms" && index) {
if (index === "salary_minimum") {
return property === "value"
@@ -558,6 +660,76 @@ function monthIsFuture(value: string, now: Date): boolean {
return month > current;
}
+/**
+ * Client checks of the projects that the server repeats: the title, the text
+ * limits, the stack tags, the GitHub address, and the repeat rules. A project
+ * row without any value is dropped on save and is not an issue.
+ */
+function projectIssues(draft: CandidateProfileDraft): ProfileFormIssue[] {
+ const issues: ProfileFormIssue[] = [];
+ const add = (index: number, property: string, message: string) =>
+ issues.push({ field: `projects.${index}.${property}`, message });
+ const repositories = new Map();
+ const projects = new Map();
+ const used = draft.projects.filter((item) => !isBlankProject(item));
+ if (used.length > maxProjects) {
+ issues.push({
+ field: "projects.0.title",
+ message: `Можно добавить не больше ${maxProjects} проектов.`,
+ });
+ }
+ draft.projects.forEach((item, index) => {
+ if (isBlankProject(item)) return;
+ const value = projectRequestValue(item);
+ if (!value.title) add(index, "title", "Укажите название проекта.");
+ else if (value.title.length > maxProjectTitle || /[\r\n]/.test(value.title)) {
+ add(index, "title", `Название: одна строка, не длиннее ${maxProjectTitle} символов.`);
+ }
+ if ((value.description ?? "").length > maxProjectDescription) {
+ add(index, "description", `Описание не длиннее ${maxProjectDescription} символов.`);
+ }
+ if (value.stack.length > maxProjectStack) {
+ add(index, "stack", `Не больше ${maxProjectStack} технологий в проекте.`);
+ }
+ const tags = new Set();
+ for (const tag of value.stack) {
+ const key = tag.toLocaleLowerCase("ru");
+ if (tag.length > maxProjectStackTag || /[\r\n]/.test(tag)) {
+ add(index, "stack", `Технология: одна строка, не длиннее ${maxProjectStackTag} символов.`);
+ break;
+ }
+ if (tags.has(key)) {
+ add(index, "stack", "Технология повторяется.");
+ break;
+ }
+ tags.add(key);
+ }
+ if (item.repository_url.trim()) {
+ const key = repositoryKey(item.repository_url);
+ if (!key) {
+ add(
+ index,
+ "repository_url",
+ "Нужен адрес вида https://github.com/владелец/репозиторий, без параметров и других сайтов.",
+ );
+ } else if (repositories.has(key)) {
+ add(
+ index,
+ "repository_url",
+ `Этот репозиторий уже указан в проекте ${(repositories.get(key) ?? 0) + 1}.`,
+ );
+ } else {
+ repositories.set(key, index);
+ }
+ } else {
+ const key = JSON.stringify([value.title, value.description, value.stack]);
+ if (projects.has(key)) add(index, "title", "Такой проект уже добавлен.");
+ else projects.set(key, index);
+ }
+ });
+ return issues;
+}
+
function customValidationIssues(draft: CandidateProfileDraft, now: Date): ProfileFormIssue[] {
const issues: ProfileFormIssue[] = [];
const duplicates = (
@@ -612,6 +784,7 @@ function customValidationIssues(draft: CandidateProfileDraft, now: Date): Profil
});
}
});
+ issues.push(...projectIssues(draft));
if (draft.terms.salaryMinimum.amount.trim() && !draft.terms.salaryMinimum.tax_basis) {
issues.push({
field: "terms.salaryMinimum.tax_basis",
@@ -673,6 +846,7 @@ export function buildCandidateProfileUpdate(
second_period: overlap.secondPeriod,
})),
soft_skills: draft.softSkills.filter((item) => item.skill.trim()).map(itemDecision),
+ projects: draft.projects.filter((item) => !isBlankProject(item)).map(projectDecision),
terms: {
location: fieldDecision(draft.terms.location, draft.terms.location.value.trim()),
relocation: fieldDecision(draft.terms.relocation),
@@ -692,11 +866,15 @@ export function buildCandidateProfileUpdate(
const issues = customValidationIssues(draft, now);
const parsed = CandidateProfileUpdateSchema.safeParse(data);
if (!parsed.success) {
+ // The schema repeats what a specific check already said about a field.
+ const reported = new Set(issues.map((issue) => issue.field));
issues.push(
- ...parsed.error.issues.map((issue) => ({
- field: fieldForPointer(zodPointer(issue.path)),
- message: "Проверьте значение и формат этого поля.",
- })),
+ ...parsed.error.issues
+ .map((issue) => ({
+ field: fieldForPointer(zodPointer(issue.path)),
+ message: "Проверьте значение и формат этого поля.",
+ }))
+ .filter((issue) => !reported.has(issue.field)),
);
}
return {
diff --git a/frontend/src/entities/candidate/model/profile-projects.test.ts b/frontend/src/entities/candidate/model/profile-projects.test.ts
new file mode 100644
index 0000000..7fd86f8
--- /dev/null
+++ b/frontend/src/entities/candidate/model/profile-projects.test.ts
@@ -0,0 +1,123 @@
+import { describe, expect, it } from "vitest";
+import type { CandidateProfile } from "../../../shared/api/schemas";
+import {
+ describeRepositoryStatus,
+ hasPendingRepositoryChecks,
+ normalizeRepositoryUrl,
+ parseGitHubRepository,
+ repositoryChecksOf,
+ repositoryKey,
+} from "./profile-projects";
+
+const source = {
+ origin: "manual",
+ trust_level: 0,
+ quote: null,
+ extraction_version: null,
+ confirmed_at: "2026-10-05T09:30:00Z",
+} as const;
+
+function projects(
+ ...items: Array<[string | null, "pending" | "verified" | "not_found" | "unavailable" | null]>
+): Pick {
+ return {
+ projects: items.map(([url, state], index) => ({
+ title: `Проект ${index}`,
+ description: null,
+ stack: [],
+ repository_url: url,
+ repository_check: state ? { state, checked_at: null } : null,
+ status: "confirmed" as const,
+ source,
+ })),
+ };
+}
+
+describe("GitHub repository address", () => {
+ it("accepts only https://github.com// and canonicalizes it", () => {
+ expect(normalizeRepositoryUrl("https://github.com/example-org/payments-ledger")).toBe(
+ "https://github.com/example-org/payments-ledger",
+ );
+ expect(normalizeRepositoryUrl(" https://github.com/Example-Org/Ledger.git ")).toBe(
+ "https://github.com/Example-Org/Ledger",
+ );
+ expect(normalizeRepositoryUrl("https://github.com/example-org/ledger/")).toBe(
+ "https://github.com/example-org/ledger",
+ );
+ expect(parseGitHubRepository("https://github.com/a/b.c_d-e")).toEqual({
+ owner: "a",
+ name: "b.c_d-e",
+ });
+ });
+
+ it.each([
+ "",
+ "github.com/example-org/ledger",
+ "http://github.com/example-org/ledger",
+ "https://www.github.com/example-org/ledger",
+ "https://gitlab.com/example-org/ledger",
+ "https://github.com.evil.example/example-org/ledger",
+ "https://user:token@github.com/example-org/ledger",
+ "https://github.com:8443/example-org/ledger",
+ "https://github.com/example-org",
+ "https://github.com/example-org/ledger/tree/main",
+ "https://github.com/example-org/ledger?tab=readme",
+ "https://github.com/example-org/ledger#readme",
+ "https://github.com/-owner/ledger",
+ "https://github.com/own--er/ledger",
+ "https://github.com/example-org/..",
+ "https://github.com/example-org/led ger",
+ ])("rejects %j", (value) => {
+ expect(normalizeRepositoryUrl(value)).toBeNull();
+ });
+
+ it("treats letter case and a .git suffix as the same repository", () => {
+ expect(repositoryKey("https://github.com/Example-Org/Ledger.git")).toBe(
+ repositoryKey("https://github.com/example-org/ledger/"),
+ );
+ expect(repositoryKey("https://github.com/example-org/ledger")).toBe("example-org/ledger");
+ });
+});
+
+describe("repository checks of saved projects", () => {
+ it("indexes the checks by repository identity and skips projects without one", () => {
+ const checks = repositoryChecksOf(
+ projects(
+ ["https://github.com/example-org/ledger", "verified"],
+ [null, null],
+ ["https://github.com/example-org/other", null],
+ ),
+ );
+
+ expect([...checks.keys()]).toEqual(["example-org/ledger"]);
+ expect(checks.get("example-org/ledger")?.state).toBe("verified");
+ });
+
+ it("reports a pending check so the screen keeps reloading the statuses", () => {
+ expect(
+ hasPendingRepositoryChecks(projects(["https://github.com/example-org/a", "pending"])),
+ ).toBe(true);
+ expect(
+ hasPendingRepositoryChecks(projects(["https://github.com/example-org/a", "verified"])),
+ ).toBe(false);
+ expect(hasPendingRepositoryChecks(undefined)).toBe(false);
+ });
+
+ it("describes every state in words and never as a proof of authorship", () => {
+ const states = ["pending", "verified", "not_found", "unavailable"] as const;
+ const views = states.map((state) => describeRepositoryStatus({ state, checked_at: null }));
+
+ expect(views.map((view) => view.label)).toEqual([
+ "Проверяется",
+ "Публичный репозиторий найден",
+ "Не найден или закрыт",
+ "Лимит GitHub, повторим позже",
+ ]);
+ expect(views.map((view) => view.tone)).toEqual(["neutral", "success", "danger", "neutral"]);
+ expect(views[1]?.note).toContain("Авторство не проверяется");
+ expect(describeRepositoryStatus(undefined)).toMatchObject({
+ state: "unsaved",
+ label: "Проверка после сохранения",
+ });
+ });
+});
diff --git a/frontend/src/entities/candidate/model/profile-projects.ts b/frontend/src/entities/candidate/model/profile-projects.ts
new file mode 100644
index 0000000..8e629fd
--- /dev/null
+++ b/frontend/src/entities/candidate/model/profile-projects.ts
@@ -0,0 +1,131 @@
+import type { CandidateProfile, ProfileRepositoryCheck } from "../../../shared/api/schemas";
+
+/*
+ * Project rules of the profile form. They mirror the contract and the server
+ * so a bad value is caught before the request: the same host, the same owner
+ * and repository patterns, and the same repeat rules.
+ */
+
+export const maxProjects = 10;
+export const maxProjectTitle = 100;
+export const maxProjectDescription = 500;
+export const maxProjectStack = 10;
+export const maxProjectStackTag = 50;
+
+const repositoryPrefix = "https://github.com/";
+const ownerPattern = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/;
+const namePattern = /^[A-Za-z0-9._-]{1,100}$/;
+
+export type GitHubRepository = { owner: string; name: string };
+
+/**
+ * Parses https://github.com// with an optional trailing
+ * slash or `.git` suffix. Any other host, scheme, port, credentials, query,
+ * fragment, or extra path segment is rejected, as the server does.
+ */
+export function parseGitHubRepository(raw: string): GitHubRepository | null {
+ const value = raw.trim();
+ if (value.length > 160 || !value.startsWith(repositoryPrefix)) return null;
+ const path = value.slice(repositoryPrefix.length).replace(/\/$/, "");
+ const parts = path.split("/");
+ if (parts.length !== 2) return null;
+ const owner = parts[0] ?? "";
+ const name = (parts[1] ?? "").replace(/\.git$/, "");
+ if (!ownerPattern.test(owner) || owner.includes("--")) return null;
+ if (!namePattern.test(name) || name === "." || name === "..") return null;
+ return { owner, name };
+}
+
+/** The canonical address the server stores, or null for an invalid address. */
+export function normalizeRepositoryUrl(raw: string): string | null {
+ const repository = parseGitHubRepository(raw);
+ return repository ? `${repositoryPrefix}${repository.owner}/${repository.name}` : null;
+}
+
+/** The identity of a repository: GitHub treats letter case as the same repository. */
+export function repositoryKey(raw: string): string | null {
+ const repository = parseGitHubRepository(raw);
+ return repository ? `${repository.owner}/${repository.name}`.toLowerCase() : null;
+}
+
+/** Latest server checks of the saved repositories, by repository identity. */
+export function repositoryChecksOf(
+ profile: Pick,
+): ReadonlyMap {
+ const checks = new Map();
+ for (const project of profile.projects) {
+ if (!project.repository_url || !project.repository_check) continue;
+ const key = repositoryKey(project.repository_url);
+ if (key) checks.set(key, project.repository_check);
+ }
+ return checks;
+}
+
+/** True while at least one saved repository waits for its check. */
+export function hasPendingRepositoryChecks(
+ profile: Pick | undefined,
+): boolean {
+ return Boolean(
+ profile?.projects.some((project) => project.repository_check?.state === "pending"),
+ );
+}
+
+export type RepositoryStatusView = {
+ state: ProfileRepositoryCheck["state"] | "unsaved";
+ tone: "neutral" | "success" | "danger";
+ label: string;
+ note: string;
+ checkedAt: string | null;
+};
+
+/**
+ * Words for the check of one repository. `unsaved` stands for an address that
+ * the server has not stored yet, so no check exists for it.
+ */
+export function describeRepositoryStatus(
+ check: ProfileRepositoryCheck | undefined,
+): RepositoryStatusView {
+ if (!check) {
+ return {
+ state: "unsaved",
+ tone: "neutral",
+ label: "Проверка после сохранения",
+ note: "Адрес проверится в фоне, когда вы сохраните профиль.",
+ checkedAt: null,
+ };
+ }
+ switch (check.state) {
+ case "pending":
+ return {
+ state: "pending",
+ tone: "neutral",
+ label: "Проверяется",
+ note: "Проверка идет в фоне. Статус обновится сам.",
+ checkedAt: check.checked_at,
+ };
+ case "verified":
+ return {
+ state: "verified",
+ tone: "success",
+ label: "Публичный репозиторий найден",
+ note: "Это значит только, что репозиторий существует и открыт. Авторство не проверяется.",
+ checkedAt: check.checked_at,
+ };
+ case "not_found":
+ return {
+ state: "not_found",
+ tone: "danger",
+ label: "Не найден или закрыт",
+ note: "GitHub не нашел публичный репозиторий: он может быть закрытым, переименованным или удаленным. Проект остается в профиле без отметки о репозитории.",
+ checkedAt: check.checked_at,
+ };
+ case "unavailable":
+ return {
+ state: "unavailable",
+ tone: "neutral",
+ label: "Лимит GitHub, повторим позже",
+ note: "GitHub сейчас не ответил, например из-за лимита запросов. Сервер повторит проверку сам.",
+ checkedAt: check.checked_at,
+ };
+ }
+}
diff --git a/frontend/src/entities/match/index.ts b/frontend/src/entities/match/index.ts
index 2a54a75..822c686 100644
--- a/frontend/src/entities/match/index.ts
+++ b/frontend/src/entities/match/index.ts
@@ -15,6 +15,7 @@ export type {
MatchConfirmedComponentsModel,
MatchGroup,
MatchSearchModel,
+ MatchSemanticEvidenceModel,
MatchSearchSourceModel,
MatchUnconfirmedCardModel,
} from "./model/adapter";
@@ -37,8 +38,11 @@ export {
evidenceRows,
formatScore,
otherUnknowns,
+ semanticBlock,
type ComponentRow,
type EvidenceRow,
+ type SemanticBlock,
+ type SemanticRow,
} from "./model/explanation";
export {
gradeCodes,
diff --git a/frontend/src/entities/match/model/adapter.test.ts b/frontend/src/entities/match/model/adapter.test.ts
index 4bae197..f89dd7b 100644
--- a/frontend/src/entities/match/model/adapter.test.ts
+++ b/frontend/src/entities/match/model/adapter.test.ts
@@ -203,6 +203,82 @@ describe("match response adapter", () => {
expect(matchSearchFromTransport(roundTrip)).toEqual(model);
});
+ it("round-trips the semantic evidence of an entry in the server order", () => {
+ const response = matchResponseFixture();
+ const [candidate] = response.groups.main;
+ if (!candidate) throw new Error("Fixture main card is missing.");
+ const evidence = [
+ {
+ requirement_kind: "task" as const,
+ requirement_text: "Разработать сервис сверки платежей",
+ item_kind: "project" as const,
+ project_title: "Платежный шлюз",
+ repository_verified: true,
+ similarity: "high" as const,
+ },
+ {
+ requirement_kind: "required_skill" as const,
+ requirement_text: "PostgreSQL",
+ item_kind: "stack" as const,
+ project_title: null,
+ repository_verified: false,
+ similarity: "medium" as const,
+ },
+ ];
+ const withEvidence = {
+ ...response,
+ groups: { ...response.groups, main: [{ ...candidate, semantic_evidence: evidence }] },
+ };
+
+ const model = matchSearchFromTransport(withEvidence);
+
+ expect(model.cards[0]?.semanticEvidence).toEqual([
+ {
+ requirementKind: "task",
+ requirementText: "Разработать сервис сверки платежей",
+ itemKind: "project",
+ projectTitle: "Платежный шлюз",
+ repositoryVerified: true,
+ similarity: "high",
+ },
+ {
+ requirementKind: "required_skill",
+ requirementText: "PostgreSQL",
+ itemKind: "stack",
+ projectTitle: null,
+ repositoryVerified: false,
+ similarity: "medium",
+ },
+ ]);
+ expect(matchSearchToTransport(model)).toEqual(withEvidence);
+ });
+
+ it("rejects evidence that carries a repository address or an owner", () => {
+ const response = matchResponseFixture();
+ const [candidate] = response.groups.main;
+ if (!candidate) throw new Error("Fixture main card is missing.");
+ const item = {
+ requirement_kind: "task",
+ requirement_text: "Разработать сервис сверки платежей",
+ item_kind: "project",
+ project_title: "Платежный шлюз",
+ repository_verified: true,
+ similarity: "high",
+ };
+ for (const extra of [
+ { repository_url: "https://github.com/example-org/payments-ledger" },
+ { repository_owner: "example-org" },
+ ]) {
+ expectInvalidResponse({
+ ...response,
+ groups: {
+ ...response.groups,
+ main: [{ ...candidate, semantic_evidence: [{ ...item, ...extra }] }],
+ },
+ });
+ }
+ });
+
it("keeps the truncation flag, which carries no count", () => {
const response = { ...matchResponseFixture(), truncated: true };
const model = matchSearchFromTransport(response);
diff --git a/frontend/src/entities/match/model/adapter.ts b/frontend/src/entities/match/model/adapter.ts
index 7ee6f7a..7f3d7c3 100644
--- a/frontend/src/entities/match/model/adapter.ts
+++ b/frontend/src/entities/match/model/adapter.ts
@@ -43,10 +43,26 @@ type MatchPublicContext = {
};
type MatchEvidence = ConfirmedCandidate["evidence_summary"][number];
+type MatchSemanticEvidenceTransport = ConfirmedCandidate["semantic_evidence"][number];
type MatchUnknownFlag = ConfirmedCandidate["unknown_flags"][number];
type ConfirmedComponents = ConfirmedCandidate["components"];
type UnconfirmedComponents = UnconfirmedCandidate["components"];
+/**
+ * Why a requirement of the need matched a published card item. The server
+ * computes it from stored vectors; it carries only public card values, so it
+ * has no repository address and no owner.
+ */
+export type MatchSemanticEvidenceModel = {
+ readonly requirementKind: MatchSemanticEvidenceTransport["requirement_kind"];
+ readonly requirementText: string;
+ readonly itemKind: MatchSemanticEvidenceTransport["item_kind"];
+ /** Published project title for a project item, otherwise null. */
+ readonly projectTitle: string | null;
+ readonly repositoryVerified: boolean;
+ readonly similarity: MatchSemanticEvidenceTransport["similarity"];
+};
+
export type MatchConfirmedComponentsModel = Omit & {
readonly rankScore: ConfirmedComponents["rank_score"];
};
@@ -61,6 +77,8 @@ export type MatchConfirmedCardModel = {
readonly strength: ConfirmedCandidate["strength"];
readonly publicContext: MatchPublicContext;
readonly evidenceSummary: readonly MatchEvidence[];
+ /** In the order the server sent: strongest similarity first. */
+ readonly semanticEvidence: readonly MatchSemanticEvidenceModel[];
readonly components: MatchConfirmedComponentsModel;
readonly unknownFlags: readonly MatchUnknownFlag[];
};
@@ -75,6 +93,7 @@ export type MatchUnconfirmedCardModel = {
readonly strength: null;
readonly publicContext: MatchPublicContext;
readonly evidenceSummary: readonly MatchEvidence[];
+ readonly semanticEvidence: readonly MatchSemanticEvidenceModel[];
readonly components: UnconfirmedComponents;
readonly unknownFlags: readonly MatchUnknownFlag[];
};
@@ -215,6 +234,32 @@ function publicContextToTransport(
};
}
+function semanticEvidenceFromTransport(
+ items: readonly MatchSemanticEvidenceTransport[],
+): MatchSemanticEvidenceModel[] {
+ return items.map((item) => ({
+ requirementKind: item.requirement_kind,
+ requirementText: item.requirement_text,
+ itemKind: item.item_kind,
+ projectTitle: item.project_title,
+ repositoryVerified: item.repository_verified,
+ similarity: item.similarity,
+ }));
+}
+
+function semanticEvidenceToTransport(
+ items: readonly MatchSemanticEvidenceModel[],
+): MatchSemanticEvidenceTransport[] {
+ return items.map((item) => ({
+ requirement_kind: item.requirementKind,
+ requirement_text: item.requirementText,
+ item_kind: item.itemKind,
+ project_title: item.projectTitle,
+ repository_verified: item.repositoryVerified,
+ similarity: item.similarity,
+ }));
+}
+
function confirmedFromTransport(
group: "main" | "near",
candidate: ConfirmedCandidate,
@@ -230,6 +275,7 @@ function confirmedFromTransport(
strength: candidate.strength,
publicContext: publicContextFromTransport(candidate.public_context),
evidenceSummary: candidate.evidence_summary.map(({ code, state }) => ({ code, state })),
+ semanticEvidence: semanticEvidenceFromTransport(candidate.semantic_evidence),
components: { ...components, rankScore },
unknownFlags: candidate.unknown_flags.map(({ component, reason }) => ({ component, reason })),
};
@@ -246,6 +292,7 @@ function unconfirmedFromTransport(candidate: UnconfirmedCandidate): MatchUnconfi
strength: null,
publicContext: publicContextFromTransport(candidate.public_context),
evidenceSummary: candidate.evidence_summary.map(({ code, state }) => ({ code, state })),
+ semanticEvidence: semanticEvidenceFromTransport(candidate.semantic_evidence),
components: { fit: candidate.components.fit, coverage: candidate.components.coverage },
unknownFlags: candidate.unknown_flags.map(({ component, reason }) => ({ component, reason })),
};
@@ -275,8 +322,7 @@ function confirmedToTransport(candidate: MatchConfirmedCardModel): ConfirmedCand
strength: candidate.strength,
public_context: publicContextToTransport(candidate.publicContext),
evidence_summary: candidate.evidenceSummary.map(({ code, state }) => ({ code, state })),
- // The card model does not carry the semantic explanation yet.
- semantic_evidence: [],
+ semantic_evidence: semanticEvidenceToTransport(candidate.semanticEvidence),
components: { ...components, rank_score: rankScore },
unknown_flags: candidate.unknownFlags.map(({ component, reason }) => ({ component, reason })),
};
@@ -292,8 +338,7 @@ function unconfirmedToTransport(candidate: MatchUnconfirmedCardModel): Unconfirm
strength: null,
public_context: publicContextToTransport(candidate.publicContext),
evidence_summary: candidate.evidenceSummary.map(({ code, state }) => ({ code, state })),
- // The card model does not carry the semantic explanation yet.
- semantic_evidence: [],
+ semantic_evidence: semanticEvidenceToTransport(candidate.semanticEvidence),
components: { fit: candidate.components.fit, coverage: candidate.components.coverage },
unknown_flags: candidate.unknownFlags.map(({ component, reason }) => ({ component, reason })),
};
diff --git a/frontend/src/entities/match/model/card-presentation.ts b/frontend/src/entities/match/model/card-presentation.ts
index f25b8d6..f1663a0 100644
--- a/frontend/src/entities/match/model/card-presentation.ts
+++ b/frontend/src/entities/match/model/card-presentation.ts
@@ -27,6 +27,15 @@ export type CardDetails = {
experience: string | null;
workFormats: readonly string[] | null;
salaryCompatibility: string | null;
+ /** Published projects in the candidate's order; null when the card has none to show. */
+ projects:
+ | readonly {
+ title: string;
+ description: string | null;
+ stack: readonly string[];
+ repositoryVerified: boolean;
+ }[]
+ | null;
};
/**
@@ -54,6 +63,13 @@ export function presentCard(card: AnonymousCardContent): CardDetails {
salaryCompatibility: card.salary_compatibility
? salaryCompatibilityLabels[card.salary_compatibility]
: null,
+ projects:
+ card.projects?.map((project) => ({
+ title: project.title,
+ description: project.description,
+ stack: [...project.stack],
+ repositoryVerified: project.repository_verified,
+ })) ?? null,
};
}
diff --git a/frontend/src/entities/match/model/explanation.test.ts b/frontend/src/entities/match/model/explanation.test.ts
index 60bbcb4..28bb686 100644
--- a/frontend/src/entities/match/model/explanation.test.ts
+++ b/frontend/src/entities/match/model/explanation.test.ts
@@ -1,5 +1,11 @@
import { describe, expect, it } from "vitest";
-import { componentRows, evidenceRows, formatScore, otherUnknowns } from "./explanation";
+import {
+ componentRows,
+ evidenceRows,
+ formatScore,
+ otherUnknowns,
+ semanticBlock,
+} from "./explanation";
import { matchModelFixture } from "./match.fixtures";
function cardAt(index: number) {
@@ -79,3 +85,59 @@ describe("match explanation", () => {
]);
});
});
+
+describe("semantic evidence block", () => {
+ it("lists the rows in the order the server sent, with kind, label, and band", () => {
+ const block = semanticBlock(cardAt(1));
+
+ expect(block?.kind).toBe("evidence");
+ if (block?.kind !== "evidence") throw new Error("Expected evidence rows.");
+ expect(
+ block.rows.map((row) => [
+ row.requirementLabel,
+ row.itemKindLabel,
+ row.itemLabel,
+ row.similarityLabel,
+ ]),
+ ).toEqual([
+ ["Задача", "Проект", "Платежный шлюз", "Высокое сходство"],
+ ["Обязательный навык", "Стек", "Технологии карточки", "Среднее сходство"],
+ ["Желательный навык", "Проект", "Внутренняя витрина", "Среднее сходство"],
+ ["Задача", "Роль", "Специализации и грейды карточки", "Среднее сходство"],
+ ]);
+ });
+
+ it("marks only a verified project as backed by a public repository", () => {
+ const block = semanticBlock(cardAt(1));
+ if (block?.kind !== "evidence") throw new Error("Expected evidence rows.");
+
+ expect(block.rows.map((row) => row.repositoryVerified)).toEqual([true, false, false, false]);
+ });
+
+ it("never marks a stack or roles item, even if a verified flag came with it", () => {
+ const card = cardAt(1);
+ const forged = {
+ ...card,
+ semanticEvidence: card.semanticEvidence.map((item) => ({
+ ...item,
+ repositoryVerified: true,
+ })),
+ };
+ const block = semanticBlock(forged);
+ if (block?.kind !== "evidence") throw new Error("Expected evidence rows.");
+
+ expect(block.rows.map((row) => row.repositoryVerified)).toEqual([true, false, true, false]);
+ });
+
+ it("keeps the unavailable wording when the semantic component is unknown for lack of ML", () => {
+ expect(semanticBlock(cardAt(0))).toEqual({
+ kind: "unavailable",
+ text: "смысловой анализ недоступен",
+ });
+ });
+
+ it("shows no block when there is nothing to say", () => {
+ // An unconfirmed entry without evidence and without a semantics flag.
+ expect(semanticBlock(cardAt(3))).toBeNull();
+ });
+});
diff --git a/frontend/src/entities/match/model/explanation.ts b/frontend/src/entities/match/model/explanation.ts
index 3d32f8f..7ae9073 100644
--- a/frontend/src/entities/match/model/explanation.ts
+++ b/frontend/src/entities/match/model/explanation.ts
@@ -3,6 +3,10 @@ import type { MatchCardModel } from "./adapter";
import {
evidenceCodeLabels,
evidenceStateLabels,
+ semanticItemKindLabels,
+ semanticItemPlainLabels,
+ semanticRequirementLabels,
+ semanticSimilarityLabels,
unknownComponentLabels,
unknownReasonLabels,
} from "./labels";
@@ -157,3 +161,52 @@ export function evidenceRows(card: MatchCardModel): EvidenceRow[] {
stateLabel: evidenceStateLabels[item.state],
}));
}
+
+export type SemanticRow = {
+ key: string;
+ requirementLabel: string;
+ requirementText: string;
+ itemKindLabel: string;
+ /** The title of a published project, or a plain label of the stack or the roles. */
+ itemLabel: string;
+ /** True only for a project whose linked repository the server found public. */
+ repositoryVerified: boolean;
+ similarity: "high" | "medium";
+ similarityLabel: string;
+};
+
+export type SemanticBlock =
+ { kind: "evidence"; rows: SemanticRow[] } | { kind: "unavailable"; text: string };
+
+/**
+ * The "matches by meaning" block of one entry. The rows keep the order and
+ * the limit that the server sent. With no rows the block appears only when
+ * the server names the semantic component unknown because ML was down, with
+ * the same words as the explanation; an empty list from a bank search or from
+ * a need without a match shows no block at all.
+ */
+export function semanticBlock(card: MatchCardModel): SemanticBlock | null {
+ if (card.semanticEvidence.length > 0) {
+ return {
+ kind: "evidence",
+ rows: card.semanticEvidence.map((item, index) => ({
+ key: `${index}:${item.requirementKind}:${item.requirementText}`,
+ requirementLabel: semanticRequirementLabels[item.requirementKind],
+ requirementText: item.requirementText,
+ itemKindLabel: semanticItemKindLabels[item.itemKind],
+ itemLabel:
+ item.itemKind === "project"
+ ? (item.projectTitle ?? semanticItemKindLabels.project)
+ : semanticItemPlainLabels[item.itemKind],
+ repositoryVerified: item.itemKind === "project" && item.repositoryVerified,
+ similarity: item.similarity,
+ similarityLabel: semanticSimilarityLabels[item.similarity],
+ })),
+ };
+ }
+ const flag = flagFor(card, "semantics");
+ if (flag?.reason === "ml_unavailable") {
+ return { kind: "unavailable", text: describeUnknownReason(flag) };
+ }
+ return null;
+}
diff --git a/frontend/src/entities/match/model/labels.ts b/frontend/src/entities/match/model/labels.ts
index 838ccac..809a99b 100644
--- a/frontend/src/entities/match/model/labels.ts
+++ b/frontend/src/entities/match/model/labels.ts
@@ -5,6 +5,7 @@ import type {
MatchEvidenceCode,
MatchEvidenceState,
MatchSearchStackTag,
+ MatchSemanticItemKind,
MatchStrength,
MatchUnknownComponent,
MatchUnknownReason,
@@ -154,3 +155,29 @@ export const unknownReasonLabels: Readonly> =
no_response_history: "нет истории ответов",
percentile_not_computed: "перцентиль пока не рассчитывается",
};
+
+export const semanticRequirementLabels = {
+ required_skill: "Обязательный навык",
+ desired_skill: "Желательный навык",
+ task: "Задача",
+} as const;
+
+export const semanticItemKindLabels: Readonly> = {
+ project: "Проект",
+ stack: "Стек",
+ roles: "Роль",
+};
+
+/**
+ * Public labels of the card items that carry no title of their own: the
+ * stack and the roles are shown as the card shows them to the organization.
+ */
+export const semanticItemPlainLabels: Readonly> = {
+ stack: "Технологии карточки",
+ roles: "Специализации и грейды карточки",
+};
+
+export const semanticSimilarityLabels = {
+ high: "Высокое сходство",
+ medium: "Среднее сходство",
+} as const;
diff --git a/frontend/src/entities/match/model/match.fixtures.ts b/frontend/src/entities/match/model/match.fixtures.ts
index 17dbefd..9384a50 100644
--- a/frontend/src/entities/match/model/match.fixtures.ts
+++ b/frontend/src/entities/match/model/match.fixtures.ts
@@ -89,7 +89,40 @@ export function matchResponseFixture(
{ code: "confirmed_category", state: "supports" },
{ code: "required_skill_evidence", state: "partial" },
],
- semantic_evidence: [],
+ semantic_evidence: [
+ {
+ requirement_kind: "task",
+ requirement_text: "Разработать сервис сверки платежей",
+ item_kind: "project",
+ project_title: "Платежный шлюз",
+ repository_verified: true,
+ similarity: "high",
+ },
+ {
+ requirement_kind: "required_skill",
+ requirement_text: "Проектирование схем PostgreSQL",
+ item_kind: "stack",
+ project_title: null,
+ repository_verified: false,
+ similarity: "medium",
+ },
+ {
+ requirement_kind: "desired_skill",
+ requirement_text: "Наставничество в команде",
+ item_kind: "project",
+ project_title: "Внутренняя витрина",
+ repository_verified: false,
+ similarity: "medium",
+ },
+ {
+ requirement_kind: "task",
+ requirement_text: "Поддерживать сервисы доставки",
+ item_kind: "roles",
+ project_title: null,
+ repository_verified: false,
+ similarity: "medium",
+ },
+ ],
components: {
fit: 0.4,
coverage: 0.18,
diff --git a/frontend/src/entities/match/ui/candidate-card-details.test.tsx b/frontend/src/entities/match/ui/candidate-card-details.test.tsx
new file mode 100644
index 0000000..3e0a296
--- /dev/null
+++ b/frontend/src/entities/match/ui/candidate-card-details.test.tsx
@@ -0,0 +1,70 @@
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { renderToString } from "react-dom/server";
+import { describe, expect, it } from "vitest";
+import type { AnonymousCardContent } from "../../../shared/api/schemas";
+import { matchCardQueryKeys } from "../api/card";
+import { CandidateCardDetails } from "./candidate-card-details";
+
+const accountId = "11111111-1111-4111-8111-111111111111";
+const organizationId = "22222222-2222-4222-8222-222222222222";
+const handle = "cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
+
+const card: AnonymousCardContent = {
+ pseudonym: handle,
+ categories: null,
+ stack: ["go"],
+ self_assessment: null,
+ experience_band: "3_6",
+ work_formats: null,
+ salary_compatibility: null,
+ projects: [
+ {
+ title: "Платежный шлюз",
+ description: "Проводки и сверки.\nВыплаты по расписанию.",
+ stack: ["Go", "PostgreSQL"],
+ repository_verified: true,
+ },
+ { title: "Каталог", description: null, stack: [], repository_verified: false },
+ ],
+};
+
+function render(content: AnonymousCardContent): string {
+ const client = new QueryClient();
+ client.setQueryData(matchCardQueryKeys.card(accountId, organizationId, handle), content);
+ return renderToString(
+
+
+ ,
+ ).replaceAll("", "");
+}
+
+describe("candidate card details", () => {
+ it("lists the published projects with tags and a badge for a verified repository", () => {
+ const html = render(card);
+
+ expect(html).toContain(">Проекты");
+ expect(html).toContain("Платежный шлюз");
+ expect(html).toContain("Выплаты по расписанию.");
+ expect(html).toContain(">PostgreSQL<");
+ expect(html.match(/Подтвержден публичным репозиторием/g)).toHaveLength(1);
+ expect(html).toContain("Каталог");
+ });
+
+ it("shows no address or link of a repository", () => {
+ const html = render(card);
+
+ expect(html).not.toContain("github");
+ expect(html).not.toMatch(/href="https?:/);
+ });
+
+ it("shows no projects block while the card carries none", () => {
+ expect(render({ ...card, projects: null })).not.toContain(">Проекты");
+ expect(render({ ...card, projects: [] })).not.toContain(">Проекты");
+ });
+});
diff --git a/frontend/src/entities/match/ui/candidate-card-details.tsx b/frontend/src/entities/match/ui/candidate-card-details.tsx
index 938536c..a9ecbc2 100644
--- a/frontend/src/entities/match/ui/candidate-card-details.tsx
+++ b/frontend/src/entities/match/ui/candidate-card-details.tsx
@@ -4,6 +4,7 @@ import {
ForbiddenState,
isAccessDenied,
LoadingState,
+ PublishedProjects,
StatusView,
TrustLevel,
} from "../../../shared/ui";
@@ -155,6 +156,12 @@ export function CandidateCardDetails({
Зарплатные ожидания
{details.salaryCompatibility ?? "Нет значения в карточке"}
+ );
+}
+
+type ProjectsStepProps = {
+ draft: CandidateProfileDraft;
+ issues: readonly ProfileFormIssue[];
+ isSaving: boolean;
+ /** Ids of the fields, built by the form so every step shares one prefix. */
+ fieldId: (field: string) => string;
+ newRowId: (kind: string) => string;
+ /** Latest server checks of the saved repositories. */
+ checks: ReadonlyMap;
+ recheck: RepositoryRecheck;
+ onDraftChange: (draft: CandidateProfileDraft) => void;
+};
+
+/** The "Проекты" step: up to ten projects with an optional GitHub repository each. */
+export function ProjectsStep({
+ draft,
+ issues,
+ isSaving,
+ fieldId,
+ newRowId,
+ checks,
+ recheck,
+ onDraftChange,
+}: ProjectsStepProps) {
+ const issue = (field: string) => errorFor(issues, field);
+ const hasRepository = draft.projects.some((item) => item.repository_url.trim() !== "");
+ const hasSavedRepository = draft.projects.some((item) => {
+ const key = repositoryKey(item.repository_url);
+ return key !== null && checks.has(key);
+ });
+ const waiting = recheck.cooldown > 0;
+
+ return (
+ <>
+
+
+ Название и описание могут выдать вас, если вы отдельно опубликуете проекты в карточке. Не
+ пишите в них имя, контакты и адрес репозитория. Адрес репозитория компании не получают
+ никогда.
+
+ Сервер читает только публичные данные на GitHub и отмечает, что репозиторий существует и
+ открыт. Это не доказывает авторство. Проверяются сохраненные адреса; сделали репозиторий
+ публичным - проверьте снова.
+
+
+
+ {recheck.isPending ? "Запрашиваем проверку..." : "Проверить снова"}
+
+ {waiting ? (
+
+ Следующий запрос можно отправить через {formatCountdown(recheck.cooldown)}.
+
+ ) : null}
+ {!hasSavedRepository ? (
+ Сначала сохраните профиль с адресом.
+ ) : null}
+
+ {recheck.failure ? (
+
+
+ {recheck.failure.detail ?
{recheck.failure.detail}
: null}
+
+
+ ) : null}
+ {recheck.message ? (
+
+ {recheck.message}
+
+ ) : null}
+
+ ) : null}
+ >
+ );
+}
diff --git a/frontend/src/features/edit-profile/ui/tag-list-input.tsx b/frontend/src/features/edit-profile/ui/tag-list-input.tsx
new file mode 100644
index 0000000..6d0c245
--- /dev/null
+++ b/frontend/src/features/edit-profile/ui/tag-list-input.tsx
@@ -0,0 +1,102 @@
+import { useState, type KeyboardEvent } from "react";
+import { Button, Tag } from "../../../shared/ui";
+import styles from "./projects-step.module.css";
+
+type TagListInputProps = {
+ id: string;
+ tags: readonly string[];
+ maxTags: number;
+ maxLength: number;
+ disabled: boolean;
+ invalid: boolean;
+ describedBy: string | undefined;
+ /** Accessible name of the button that removes one tag. */
+ removeLabel: (tag: string) => string;
+ onChange: (tags: string[]) => void;
+};
+
+/**
+ * Technology tags of one project: the tags added so far as removable chips and
+ * one field for the next tag. Enter, a comma, the add button, and leaving the
+ * field all add the typed text, so a tag typed before "Далее" is never lost.
+ * Tags compare without regard to letter case, as the server does.
+ */
+export function TagListInput({
+ id,
+ tags,
+ maxTags,
+ maxLength,
+ disabled,
+ invalid,
+ describedBy,
+ removeLabel,
+ onChange,
+}: TagListInputProps) {
+ const [text, setText] = useState("");
+ const full = tags.length >= maxTags;
+
+ function commit() {
+ const next = [...tags];
+ for (const part of text.split(/[,\n]/)) {
+ const tag = part.trim();
+ if (!tag || next.length >= maxTags) continue;
+ if (
+ next.some((existing) => existing.toLocaleLowerCase("ru") === tag.toLocaleLowerCase("ru"))
+ ) {
+ continue;
+ }
+ next.push(tag.slice(0, maxLength));
+ }
+ setText("");
+ if (next.length !== tags.length) onChange(next);
+ }
+
+ function handleKeyDown(event: KeyboardEvent) {
+ // Enter belongs to this field: it must not submit the surrounding step.
+ if (event.key === "Enter" || event.key === ",") {
+ event.preventDefault();
+ commit();
+ }
+ }
+
+ return (
+
+ Отметка значит только, что публичный репозиторий проекта существует. Авторство она не
+ доказывает, а адрес репозитория компаниям не показывается.
+
+ ) : null}
+
+ );
+}
diff --git a/frontend/src/shared/ui/status-view/describe-error.ts b/frontend/src/shared/ui/status-view/describe-error.ts
index 1280ea0..a9cc39a 100644
--- a/frontend/src/shared/ui/status-view/describe-error.ts
+++ b/frontend/src/shared/ui/status-view/describe-error.ts
@@ -80,6 +80,11 @@ const codeMessages: Partial> = {
title: "Запрос не прошел проверку",
description: "Проверьте введенные данные и повторите попытку.",
},
+ service_unavailable: {
+ title: "Сервис пока не готов",
+ description:
+ "Он загружается или временно перегружен. Ничего не потеряно: повторите попытку через минуту.",
+ },
not_implemented: {
title: "Функция еще не реализована",
description: "Этот раздел появится в одной из следующих версий.",
diff --git a/frontend/src/shared/ui/status-view/status-view.test.tsx b/frontend/src/shared/ui/status-view/status-view.test.tsx
index 0c49bac..4f06d4c 100644
--- a/frontend/src/shared/ui/status-view/status-view.test.tsx
+++ b/frontend/src/shared/ui/status-view/status-view.test.tsx
@@ -113,6 +113,21 @@ describe("describeError", () => {
});
});
+ it("names the service_unavailable code as a service that is not ready yet", () => {
+ const error = new ApiRequestError({
+ status: 503,
+ code: "service_unavailable",
+ title: "Service unavailable",
+ });
+ const html = renderToStaticMarkup( undefined} />);
+
+ expect(describeError(error)).toMatchObject({
+ title: "Сервис пока не готов",
+ technical: { code: "service_unavailable", status: 503 },
+ });
+ expect(text(html)).toContain("Повторить");
+ });
+
it("treats a CSRF rejection as an error, not as missing access", () => {
const error = new ApiRequestError({ status: 403, code: "csrf_check_failed", title: "csrf" });
const html = renderToStaticMarkup( undefined} />);
diff --git a/frontend/src/widgets/match-list/ui/match-list.test.tsx b/frontend/src/widgets/match-list/ui/match-list.test.tsx
index 51b7837..b10de73 100644
--- a/frontend/src/widgets/match-list/ui/match-list.test.tsx
+++ b/frontend/src/widgets/match-list/ui/match-list.test.tsx
@@ -172,6 +172,47 @@ describe("match list", () => {
expect(html).toMatch(/>Заявлено: [^<]+);
});
+ describe("matches by meaning", () => {
+ // The shared helper strips the markers that server rendering puts between text nodes.
+ const text = (html: string) => html.replaceAll("", "");
+
+ it("prints each requirement, the matched card item, and the similarity band", () => {
+ const html = text(render(matchModelFixture()));
+
+ expect(html).toContain("Совпадения по смыслу");
+ expect(html).toContain("Разработать сервис сверки платежей");
+ expect(html).toContain("Платежный шлюз");
+ expect(html).toContain("Высокое сходство");
+ expect(html).toContain("Среднее сходство");
+ expect(html).toContain(">Проект<");
+ expect(html).toContain(">Стек<");
+ expect(html).toContain(">Роль<");
+ expect(html).toContain("Обязательный навык");
+ expect(html).toContain("Желательный навык");
+ });
+
+ it("marks a verified project with the public repository badge, and no other row", () => {
+ const html = text(render(matchModelFixture()));
+
+ expect(html.match(/Публичный репозиторий/g)).toHaveLength(1);
+ });
+
+ it("shows no repository address, owner, or link in the evidence", () => {
+ const html = text(render(matchModelFixture()));
+
+ expect(html).not.toContain("github");
+ expect(html).not.toMatch(/href="https?:/);
+ });
+
+ it("keeps the unavailable wording where ML was down and shows nothing for a plain empty list", () => {
+ const html = text(render(matchModelFixture()));
+
+ expect(html).toContain("Совпадения по смыслу: смысловой анализ недоступен.");
+ // Only the near entry carries rows and only the first one the unavailable text.
+ expect(html.match(/Совпадения по смыслу<\/h6>/g)).toHaveLength(2);
+ });
+ });
+
it("marks the technologies that the search asked for, in words as well as a dot", () => {
const plain = render(matchModelFixture());
// A need result does not echo its filters, so the request's own are used.