# API contracts [Русский](README.md) | English Shared OpenAPI contracts for Go, the frontend, and ML. Contract changes come first; consumers then generate their types, server code, and clients from them. - `core/` defines the main backend's public API. - `ml/` defines the ML service's internal HTTP API. - `testdata/` contains a specification for checking tool compatibility with OpenAPI 3.2.0. Routes live in `routes/` and schemas in `components/`. The `openapi.bundle.yml` files are built automatically. Generator configuration lives in `backend/codegen/`, `frontend/codegen/`, and `ml/codegen/`. From the repository root, `make -C api check` checks contracts and `make generate` updates all generated code. ## Contract conventions `api/core/` fixes these conventions as reusable components in `openapi.yml` and the files under `components/`: schemas in `components/schemas/*_schemas.yml`, parameters in `parameters.yml`, response headers in `headers.yml`, responses in `responses.yml`, and examples in `examples.yml`. Operations reference them as they are added. Currently implemented: problem responses for errors of the Go public API and the ML service. Idempotency-Key storage, If-Match checks, and pagination are planned behavior for business operations; the declared `RegisterAccount` operation, the assessment commands, `CreateOrganization`, `CreateOrganizationNeed`, `CreateMySupportCase`, and the invitation commands require Idempotency-Key, but no operation stores keys yet. ### Errors Every error is an RFC 9457 problem with the `application/problem+json` media type and the `Problem` schema. Required fields are `type` (`urn:lincodex:problem:`), `title`, `status`, and `code`; optional ones are `detail`, `instance`, `trace_id` (equal to the `X-Request-ID` response header), and `errors`. Clients branch on `code`. Titles and details are fixed per code and never contain internal error text, stack traces, credentials, contact data, or submitted values. | Code | Status | Meaning | | --- | --- | --- | | `validation_failed` | 400 | Parameters or body do not match the contract, or the body violates a domain rule; `errors` lists the fields | | `verification_token_invalid` | 400 | The email verification token is unknown, already used, or replaced | | `verification_token_expired` | 400 | The email verification token is past its lifetime | | `unauthenticated` | 401 | No valid session | | `invalid_credentials` | 401 | Login failed; an unknown email and a wrong password are not distinguished | | `forbidden` | 403 | The caller may not perform the operation | | `email_not_verified` | 403 | Correct credentials, but the email is not verified | | `csrf_check_failed` | 403 | Missing or wrong `X-CSRF-Token`, or a disallowed `Origin` | | `not_found` | 404 | Unknown route, or an object that does not exist or is not visible | | `method_not_allowed` | 405 | Unsupported method; see `Allow` | | `idempotency_in_progress` | 409 | A request with the same Idempotency-Key is still running | | `state_conflict` | 409 | The operation is not allowed in the current state of the resource | | `version_conflict` | 412 | If-Match, or a body `expected_version`, does not match the current version | | `payload_too_large` | 413 | The body exceeds the operation limit | | `unsupported_media_type` | 415 | The request Content-Type is not accepted | | `idempotency_key_reused` | 422 | The Idempotency-Key was used with a different request | | `precondition_required` | 428 | The operation requires If-Match | | `rate_limited` | 429 | Too many requests; see `Retry-After` | | `internal` | 500 | Unexpected server error | | `not_implemented` | 501 | The operation is in the contract but not implemented | Request validation uses 400 rather than 422. The generated ogen server reports malformed and schema-invalid parameters and bodies through the same decoding errors, and for parameters it does not separate syntax from schema violations; one status keeps client handling uniform. 422 then stays free for Idempotency-Key reuse, as the IETF Idempotency-Key header draft recommends. Domain rules on the body, such as `salary_from <= salary_to`, also answer 400 `validation_failed` with body pointers to the fields involved. Each `errors` item has `in` (`body`, `query`, `path`, `header`, `cookie`), `pointer` (JSON Pointer: `/salary_from` in the body, an empty string for the whole body, `/limit` for a parameter), `code` (`required` or `invalid`; clients tolerate new values), and a fixed `message`. Body pointers follow the rules in Body pointers below. A body cut by an `http.MaxBytesReader` limit answers 413 `payload_too_large`. `state_conflict` covers business state conflicts, such as accepting an invitation that was already withdrawn. `idempotency_in_progress` is reserved for concurrent retries; the reusable responses are `StateConflict` and `IdempotencyInProgress`. Every operation declares `default: $ref: ../components/responses.yml#/Problem`; ogen then generates a single error type. An operation adds a specific response (for example `PreconditionFailed`) when clients need it in the generated types. In the Go API, unknown paths under `/api`, including paths outside `/api/v1`, answer 404 `not_found`, and a panic in an operation answers 500 `internal`; only the panic type and stack are logged. Both verification token codes use 400 because the token is request content, not the target resource: 404 and 410 describe the URI, 409 a resource state, and 422 stays reserved for Idempotency-Key reuse. A malformed token fails schema validation and answers 400 `validation_failed` with the pointer `/token`. `invalid_credentials` and `unauthenticated` share 401 but mean a failed login and a missing session respectively. `email_not_verified` is returned only after the password matched, so it tells the verification state only to someone who already proved the password. #### Body pointers The generated decoder records no path of its own. It wraps the error of each object field as `decode field ""` with go-faster/errors, and `problem.Responder` rebuilds the pointer from those wrappers, reading each link through the typed `errors.Formatter` instead of the joined error text. The rules: - A missing required field answers `required` with its own pointer at any depth, for example `/terms/communication_method` or `/terms/salary/tax_basis`. - A value that fails during decoding, such as a wrong JSON type, a malformed UUID, or an ambiguous `oneOf` value, answers `invalid` with the pointer of that value, for example `/grade` for a bare grade or `/object/id`. - A value that decodes but breaks a schema rule, such as a length, a pattern, a multiple of 1000, or an enum, answers `invalid` with its full pointer, including array indices, for example `/required_skills/2/status`; this check runs after decoding. - An unknown property answers `invalid` with the pointer of the object that contains it, for example `/terms/salary` for a `candidate_minimum` inside the range; the property name is not echoed. - A failure inside an array element during decoding answers `invalid` with the pointer of the array, for example `/required_skills`, because jx reports no element index. - The whole-body pointer `""` remains only for a malformed JSON document, a missing body, an unknown top-level property, an unknown or missing discriminator of a top-level `oneOf`, and an error chain that the responder does not recognize, which falls back safely to the whole body. `responder_test.go` covers a nested object, an array element, a `oneOf` variant field, a top-level field, and an unrecognized chain; the router tests of every contract pin the pointers through the generated server. ### Retries and Idempotency-Key A mutating command declares the `IdempotencyKey` parameter. The client generates a key (a UUID v4 is recommended) and sends it in the `Idempotency-Key` header without quotes: 1-255 characters `A-Z a-z 0-9 . _ : -`. The server scopes the key by caller and operation and fingerprints the request by method, path, and body. An anonymous operation defines its key scope and fingerprint in its own description; for `RegisterAccount` see the Identity section below. Stored for 24 hours and replayed with the same status, headers, and body: the final 2xx outcome and final deterministic 4xx business outcomes of the command, such as 404 `not_found` or 409 `state_conflict`. A replay does not repeat the side effect. Not stored, so a retry with the same key is evaluated again: 400 `validation_failed`, 413, and 415 for the request itself; 401 and 403; 409 `idempotency_in_progress`; 412 `version_conflict` and 428 `precondition_required` (nothing changed; read the resource again and retry); 422 `idempotency_key_reused`; 429; and every 5xx. The server checks in this order: 1. Authentication (401), request validation (400, 413, 415), and authorization (403). Nothing is recorded for the key. 2. A stored or running request with the same key and a different fingerprint: 422 `idempotency_key_reused`. This check comes before the in-progress check. 3. A running request with the same key and fingerprint: 409 `idempotency_in_progress`; retry later. 4. A stored outcome with the same key and fingerprint: the outcome is replayed. 5. If-Match (428, 412), then the command itself; a storable outcome is recorded. Because the replay check comes before If-Match, a retry of a completed change replays its outcome instead of failing on the version that the change itself advanced. A missing or malformed key returns 400 `validation_failed` with the pointer `/Idempotency-Key`. After 24 hours the key may be accepted as new. ### Versions: ETag and If-Match A response with a versioned resource returns a strong `ETag`, for example `"v7"`. An operation that changes such a resource says in its description that it requires `If-Match` with that value. A missing value returns 428 `precondition_required`; a value that does not equal the current ETag returns 412 `version_conflict` and changes nothing. The parameter is optional in the schema so that a missing header reaches the application, which answers 428. Weak tags, lists, and `*` fail validation with 400. The questionnaire carries its version as `expected_version` in the body instead; see Catalog and questionnaire below. ### Pagination Lists use cursor pagination: `limit` from 1 to 100 (20 by default) and an opaque `cursor` of up to 512 characters `A-Z a-z 0-9 _ -`. The response holds the items in a bounded array and `page` (`PageInfo`) with `has_more` and `next_cursor`, which is null on the last page. A malformed cursor returns 400 `validation_failed`. ### Time and money Timestamps use the `Timestamp` schema: `string`, `format: date-time`, UTC with the `Z` suffix (RFC 3339). Servers always emit UTC. ogen generates `Timestamp` as a named Go type over `time.Time`; call `.UTC()` where a value is converted to it. Money is an integer number of whole rubles (`RubAmount`, int64) with an explicit base: `SalaryRange` requires `salary_from`, `salary_to`, `currency` (`RUB`), `period` (`month`), and `tax_basis` (`net` or `gross`); see Needs below. Invitation terms reuse `SalaryRange` with the same rules. ### ML service errors The ML service answers its errors with the same `Problem` schema. Its `ProblemCode` enum keeps the public identity codes so both contracts share one shape, but the service never returns them. FastAPI request validation answers 400 `validation_failed`. An HTTP exception raised inside the service maps by status: 400, 401, 403, 404, 405, 409 (`state_conflict`), 412, 413, 415, 428, 429, and 501 to their codes, 422 to 400 `validation_failed`, any other 4xx to 400 `validation_failed`, and any other 5xx to 500 `internal`. An unhandled exception answers 500 `internal` inside the application, so Starlette does not re-raise it to uvicorn; only its type is logged. The service also routes the uvicorn loggers through its JSON log format, which keeps only the exception type of a record and never its text or traceback. ### Identity: sessions, cookie, and CSRF The `identity` tag covers registration, email verification, login, logout, and the current account. All operations are in the contract. `RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, `Login`, `GetCurrentSession`, `Logout`, and `GetCurrentAccount` are implemented in the backend. The session boundary authenticates every operation protected by the contract; its principal comes from a verified account and an active PostgreSQL session. Except for identity and the consent operations below, protected business operations currently pass the security boundary and answer 501 `not_implemented` after request validation. Frontend registration and confirmation screens remain placeholders. | Method and path | operationId | Security | Success | Specific errors | | --- | --- | --- | --- | --- | | `GET /api/v1/identity/consent-texts/{purpose}` | `GetConsentText` | public | 200 `ConsentText` | 400 `validation_failed` | | `POST /api/v1/identity/registrations` | `RegisterAccount` | public, Idempotency-Key | 202 `IdentityRequestAccepted` | 400 `validation_failed`, 403 `csrf_check_failed`, 409 `idempotency_in_progress`, 422 `idempotency_key_reused`, 429 | | `POST /api/v1/identity/email-verification-requests` | `ResendEmailVerification` | public | 202 `IdentityRequestAccepted` | 400, 403 `csrf_check_failed`, 429 | | `POST /api/v1/identity/email-verifications` | `ConfirmEmail` | public | 200 `EmailVerificationResult` | 400 `verification_token_expired`, `verification_token_invalid`, or `validation_failed`; 403 `csrf_check_failed`; 429 | | `POST /api/v1/identity/sessions` | `Login` | public | 201 `Session`, `Set-Cookie`, `Cache-Control: no-store` | 400, 401 `invalid_credentials`, 403 `email_not_verified` or `csrf_check_failed`, 429 | | `GET /api/v1/identity/sessions/current` | `GetCurrentSession` | session | 200 `Session`, `Cache-Control: no-store` | 401 `unauthenticated` | | `DELETE /api/v1/identity/sessions/current` | `Logout` | session and CSRF | 204, `Set-Cookie` clears the cookie | 401 `unauthenticated` (also clears the cookie), 403 `csrf_check_failed` | | `GET /api/v1/identity/me` | `GetCurrentAccount` | session | 200 `Account`, `Cache-Control: no-store` | 401 `unauthenticated` | Every operation also declares the `default` problem response. Registration and verification: - Accounts are not enumerated. Registration and resend answer the same neutral 202 for a new, unverified, verified, or unknown email. Login answers the same 401 `invalid_credentials` for an unknown email, a wrong password, or an invalid stored hash; unknown emails and invalid hashes also receive extra Argon2id work. A correct password for an unverified account answers 403 `email_not_verified` and creates no session. - Before the server looks up the email, it validates the whole registration body (password bounds after NFKC normalization, the password blocklist, the C1 version) and computes the Argon2id hash on every branch, so neither a 400 nor the response time depends on whether the account exists. - Registering an unverified email again never changes the password hash, scenario, or onboarding step of the account row. Every registration, the first and each repeat, stores its pending credentials (password hash, scenario, and first onboarding step) on its own verification token, replaces the C1 record, advances the registration version, and invalidates earlier verification tokens. `ConfirmEmail` requires the password chosen for that registration and checks it against the pending hash on the clicked token. In one transaction the server checks the current registration version and its C1 record, consumes the token, verifies the email, applies that token's pending credentials to the account, clears its `pending_*` fields, and records exactly one `identity.email_verified` event. Any refusal leaves the account and token unchanged. An unknown, used, replaced, or superseded token, a wrong password, or missing pending credentials answers 400 `verification_token_invalid`; an expired token answers 400 `verification_token_expired`. This prevents an address owner who clicks someone else's link from accepting that registrant's password, and vice versa. Confirmation does not create a session or cookie; sign-in is a separate endpoint and requires a verified account. - Implementation of registration, resend, and login. A verified address changes nothing and receives no message during registration (the "you already have an account" notice is not implemented). Mail limits per address (shared by registration and resend, keyed by an HMAC of the normalized address, counted whether or not an account exists): at least `VERIFICATION_MAIL_MIN_INTERVAL` (default 60 s) between messages and at most `VERIFICATION_MAIL_DAILY_LIMIT` (default 5) per 24 hours. `IDENTITY_CLIENT_HOURLY_LIMIT` (default 30 per hour, range 1 to 10000) limits registration, confirmation, resend, and login per resolved client address. `IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT` (default 10 per hour, range 1 to 10000) limits login by normalized email whether or not an account exists. `ConfirmEmail` also limits each token to 5 attempts per hour and uses the client limit. A refused request answers 429 `rate_limited` with `Retry-After`. Token replacement policy: every issue first invalidates all unused verification tokens of the account, so one link works at a time; resend changes only the token. `IDENTITY_KEY_SECRET` (at least 32 bytes, required; `IDENTITY_ALLOW_EPHEMERAL_KEY=true` allows a random one on a development stand) keys the idempotency scope, the fingerprint, the limiter keys, and session CSRF. A concurrent request with the same key waits for the first and is replayed, so `idempotency_in_progress` is not produced. Details: [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#registration-email-verification-and-resend). - Every verification token is bound to the registration version it was issued for, so a token issued before a re-registration never confirms the newer credentials. Resend issues a token for the current version with the pending credentials of that registration, invalidates the earlier ones, and changes nothing else. Planned values: tokens live 24 hours; an account that stays unverified is deleted with its consent record and tokens 7 days after its last registration. These lifetimes come from the versioned product policy (demo version 1 of the `product` family), not from configuration; see [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#product-policy-versions). - Registration requires Idempotency-Key. For this anonymous operation the key is scoped by the operation, the key, and an HMAC of the normalized email; the fingerprint is an HMAC-SHA-256 with a server secret over the canonical JSON body. The body, the password, and plain hashes of either are never stored, and the secret keeps the fingerprint from serving as an offline password check. - `ConfirmEmail` takes both `token` and the `password` selected for that registration; clients that sent only a token must be updated. The password follows `LoginPassword`: NFKC normalization and 1 to 128 code points; the registration blocklist is not applied again. `Origin` must match `APP_PUBLIC_URL`; a missing Origin, the literal value null, or a foreign Origin answers 403 `csrf_check_failed`. Confirmation attempts are limited to 5 per token per hour and also use the shared `IDENTITY_CLIENT_HOURLY_LIMIT`; a refused attempt answers 429 `rate_limited` with `Retry-After`. - The verification link is `/verify-email#token=`. The frontend confirmation screen is still a placeholder. A client page must remove the fragment with `history.replaceState`, wait for an explicit user action, and post both token and registration password; a link scanner that only opens the page does not consume the token. - An expired token answers `verification_token_expired`; an unknown, used, replaced, or superseded token, a wrong password, or missing pending credentials answers `verification_token_invalid`. The client offers a new link for either error; after confirmation the user can sign in separately. A repeated confirmation with a used token is deliberately not an idempotent 200: exactly one request succeeds per token. Consent C1 and the account: - `GetConsentText(c1)` returns the current C1 text, its `text_version`, and `published_at`. Registration sends that version in `consent_c1`; the server records it with the hash of the same stored text. A version that is no longer current answers 400 `validation_failed` with the pointer `/consent_c1/text_version`, and the client reads the text again. A dedicated code would trigger the same client action, and the field pointer already identifies it, so no new code is added. - Unknown body fields are rejected, so no other consent, including C4, can be part of registration. - Passwords are normalized to NFKC and must have 15-128 Unicode code points, without composition rules. Generated Zod validators count UTF-16 code units, so the server stays authoritative for the length. - The account has a `scenario` (`candidate` or `employer`) and a saved `onboarding_step` that the server advances; after login the client returns the user to that step. Candidate steps are `candidate_consents`, `candidate_profile`, `candidate_questionnaire`, `candidate_assessment`, and `completed`; the employer has `employer_company` and `completed`. DTOs never contain password hashes, token hashes, or session identifiers. Sessions and CSRF: - Implemented session operations: Login issues a `__Host-lincodex_session` cookie with `Path=/; Secure; HttpOnly; SameSite=Strict`, no Domain, and Expires/Max-Age at the absolute session deadline. PostgreSQL stores only the SHA-256 hash of the cookie token; the current-session GET returns the account and CSRF token after a reload. Successful login transactionally revokes an active session from the request and creates a new one; only a verified account can sign in. Logout revokes the session and clears the cookie; an expired or revoked cookie is also cleared on 401. `IDENTITY_SESSION_IDLE_TIMEOUT` defaults to `24h` (range `1m` to `30d`) and `IDENTITY_SESSION_ABSOLUTE_LIFETIME` defaults to `168h` (range `1m` to `365d`); idle cannot exceed absolute, and invalid values stop startup. Requests extend only the idle deadline. - The `sessionCsrf` scheme is the `X-CSRF-Token` header with the current session's token from `Session.csrf_token`. The backend derives it with domain-separated HMAC-SHA-256 from the cookie token and `IDENTITY_KEY_SECRET`, compares it in constant time, and does not store it in the database. All instances must share one `IDENTITY_KEY_SECRET` (at least 32 bytes), stable across restarts; changing it invalidates old CSRF values but does not revoke PostgreSQL sessions. Every unsafe operation that requires `sessionCookie` must also require `sessionCsrf`; `TestUnsafeSessionOperationsRequireCSRFToken` in the backend enforces it on the bundle. The client keeps the token in memory and restores it with `GetCurrentSession` after a reload or after 403 `csrf_check_failed`. - Every unsafe public identity operation requires exactly one `Origin` header matching `APP_PUBLIC_URL`, including `RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, and `Login`. Unsafe operations protected by a session also require the session-bound CSRF token. Origin checks do not use `Host` or forwarded headers. Public identity operations are rate-limited (429 with `Retry-After`). - Responses with a session or account carry `Cache-Control: no-store`. - The root `security` requires `sessionCookie`, so an operation that does not declare `security: []` is protected by default. How the generated server (ogen v1.24.0) evaluates the schemes, and how `v1.SessionSecurity` applies the current session boundary, are pinned by `TestGeneratedServerSecurityOrder`: - It calls `HandleSessionCookie` before `HandleSessionCsrf` and passes the context returned by a successful call on. An absent value (no cookie, empty `X-CSRF-Token`) does not call the handler, and a handler that returns `ogenerrors.ErrSkipServerSecurity` counts as unsatisfied; both continue with the next scheme, so `HandleSessionCsrf` also runs without a cookie, with the original context. - Any other handler error stops evaluation and reaches `NewError` as a `SecurityError` whose `Security` is `SessionCookie` or `SessionCsrf`. An unsatisfied requirement reaches `NewError` as a `SecurityError` with `ErrSecurityRequirementIsNotSatisfied` and no `Security` field. - Implemented mapping: `HandleSessionCookie` authenticates every operation whose contract requires `sessionCookie`; missing, unknown, expired, revoked, or unverified sessions leave the requirement unsatisfied and answer 401 `unauthenticated`. For protected unsafe operations, `HandleSessionCsrf` checks the exact Origin and the token for that same session. Without a verified principal the result is 401; with one, a missing or wrong Origin or CSRF token is 403 `csrf_check_failed`. A 401 from `Logout` also clears the cookie, while a 403 leaves a valid session intact. ### Catalog and questionnaire The `catalog` and `candidate` tags cover the specialization catalog and the candidate questionnaire (PRD FR03). The catalog is public and answers 501 `not_implemented` until its handler exists. The questionnaire is protected: a guest answers 401 `unauthenticated`, while a valid session passes the security boundary and reaches 501 `not_implemented` after request validation. Unsafe protected operations also require the session-bound CSRF token and exact Origin. | Method and path | operationId | Security | Success | Specific errors | | --- | --- | --- | --- | --- | | `GET /api/v1/specializations` | `GetSpecializationCatalog` | public | 200 `SpecializationCatalog` | none | | `GET /api/v1/me/questionnaire` | `GetMyQuestionnaire` | session | 200 `CandidateQuestionnaire`, `Cache-Control: no-store` | 401 `unauthenticated`, 403 `forbidden` | | `PUT /api/v1/me/questionnaire` | `SaveMyQuestionnaire` | session and CSRF | 200 `CandidateQuestionnaire`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `csrf_check_failed` or `forbidden`, 412 `version_conflict` | Every operation also declares the `default` problem response. Catalog: - Five directions and nine specializations: Development (`backend`, `frontend`, `mobile`), Infrastructure (`network_engineer`, `devops_sre`), Data (`data_analyst`, `ds_ml`), Security (`information_security`), Quality (`qa`). The MVP grade scale is `intern`, `junior`, `middle`, `senior`; Lead and Architect come after the MVP. The codes are enums, so adding a value is a contract change. Titles are Russian plain text. - A category is a specialization together with a confirmed grade. Task languages (`python`, `go`) and stack tags are attributes of a chosen specialization and never form a category: Backend with Go is the category `backend`. Algorithms is a shared assessment module, not a specialization. - Each specialization has `test_availability`: `status` (`available` or `in_development`), the `grades` with a published task bank, and the `task_languages` that bank offers. The MVP opens an assessment only for a category with a published bank. The server derives the values from the published banks, so they change without a contract change; the example in the contract is illustrative and says nothing about a deployed bank. - The catalog is public (`security: []`): it is the same for every caller, contains no personal data, is shown before registration, and can be cached. Questionnaire: - The candidate comes from the session; an employer account answers 403 `forbidden`. A candidate without a saved questionnaire gets 200 with `version: 0`, no specializations, and null `work_context` and `updated_at` rather than 404, so the first save reads the version the same way as later ones. - Each chosen specialization has `self_assessed_grade`, `task_languages`, `stack`, and `experience` in months or null when not stated; `work_context` holds only the acceptable work formats and no personal data. The questionnaire never contains a confirmed grade or a category, and unknown fields such as `confirmed_grade` answer 400. The self-assessed grade is the expected grade that the `candidate_assessment` onboarding step offers first; it influences where the assessment starts but adds no points, and no self-assessed grade or stack tag such as "Senior" assigns a category. A real profile stays invisible to employers until an assessment confirms a category. - The schema allows one or two specializations on save and rejects an unknown specialization, grade, task language, or work format. JSON Schema `uniqueItems` cannot compare array items by one field, so the server rejects a repeated specialization with 400 and the pointer `/specializations//specialization`. It also rejects a task language that the specialization's published bank does not offer, with the pointer of that language. A specialization whose test is `in_development` can be chosen; no assessment starts for it. - Concurrency uses `expected_version` in the body instead of If-Match, because the generated client cannot read the `ETag` header yet. The first save sends 0. A stale value answers 412 `version_conflict`, the same status and code as a failed If-Match, because the client does the same thing: it reads the questionnaire again. `version_conflict` keeps its 412 status, so `state_conflict` (409) is not used here. - PUT replaces the whole questionnaire and needs no Idempotency-Key. A body equal to the stored state changes nothing, keeps the version, and answers 200 even with an older `expected_version`, so a retry after a lost response does not fail with 412. - Order of checks for a save: session (401), CSRF and Origin (403), request validation (400), account scenario (403 `forbidden`), domain rules (400), version (412). `TestQuestionnaireSchemaValidationPrecedesImplementation` checks the schema rejections through the generated server. ### Candidate profile The `candidate` tag includes implemented `GetMyProfile` and `SaveMyProfile` operations for the private manual profile. A verified candidate reads and edits only their own profile; an employer receives 403 and a guest receives 401. PUT requires the session CSRF token and exact Origin. Data, version, overlap confirmations, history, and the step transition commit in one transaction. Without DATABASE_URL, the operations retain their 501 fallback. `confirmed_categories` is read-only: one category per specialization in catalog order, from assessment results, with `basis` (`synthetic_demo` for a demonstration category), `confirmed_at`, and `attempt_id`; no request carries it. | Method and path | operationId | Protection | Success | Specific errors | | --- | --- | --- | --- | --- | | `GET /api/v1/me/profile` | `GetMyProfile` | session | 200 `CandidateProfile`, `Cache-Control: no-store` | 401 `unauthenticated`, 403 `forbidden` | | `PUT /api/v1/me/profile` | `SaveMyProfile` | session and CSRF | 200 `CandidateProfile`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `csrf_check_failed` or `forbidden`, 412 `version_conflict` | Each operation also declares the default problem response. No new problem code is added: the contract uses `validation_failed`, `unauthenticated`, `forbidden`, `csrf_check_failed`, and `version_conflict`. `experience_overlaps` lists intersecting inclusive month ranges and their decision state. A changed save requires explicit `confirmed_parallel_periods` with indices and exact dates for that version; an earlier decision survives only for the same indices and dates. A stored unconfirmed overlap permits an exact no-op, but no other edit without a decision. History is appended only on change. A successful PUT advances only `candidate_profile` to `candidate_questionnaire`; the earlier `candidate_consents` and later steps stay unchanged. Consent-step completion has no separate operation yet. What the profile holds: - The full name and contacts (`full_name`, `contacts.email`, `contacts.phone`, `contacts.telegram`), the stack (`stack`, `StackTag` tags), roles (`roles`: a catalog specialization and a self-assessed grade), work experience (`experience`: entries with a month-precision period `YYYY-MM`, a specialization, and a description of the tasks rather than a job title), soft skills (`soft_skills`, free text), and terms (`terms`: place, readiness to relocate, and the lowest salary with its currency, period, and tax basis). This is personal data of the candidate; the description of each such schema says so, and the values never reach logs, metrics, URLs, or events. - Contacts are exactly the four kinds that the consent C4 can disclose (`ContactFieldKind`), with the same formats (E.164, the leading `@` of a Telegram name, a single line of up to 200 characters for the name), so a disclosure never converts or drops a stored value. The contact email of the profile is not the login of the account: the server sends no mail to it and does not verify it. - Acceptable work formats are not repeated in the profile: they stay only in the `WorkContext` of the questionnaire. - The profile is private: only its owner reads it, and no organization, invitation, or need schema refers to it (`$ref`). An organization sees a candidate only through the anonymous card and, after an accepted invitation, through the contact grant. The lowest salary is never disclosed to an organization; an invitation shows only a compatibility indicator that the server computes. Self-assessment and confirmed category: - The grade of a role (`roles[].self_assessed_grade`) is a claim of the candidate, the same one that the questionnaire calls `self_assessed_grade`; it adds nothing and never becomes a confirmed grade. The confirmed category is a separate list, `confirmed_categories` (specialization, grade, time, and the assessment attempt that confirmed it). It is read-only, the server derives it from assessment results, no request carries it, and the profile storage has no column for it. A request with `confirmed_grade`, `category`, or `confirmed_categories` is rejected as an unknown field. Source and confirmation: - Every value carries `status` and `source`. For a single field `status` is `confirmed`, `extracted`, or `unknown`; for `unknown` the value and the source are null, and the server fills in no default. For a list item `status` is `confirmed` or `extracted`. `source` holds `origin` (`manual`; `extracted_from_resume` and `imported` are planned and no MVP operation produces them), `trust_level`, `quote`, `extraction_version`, and `confirmed_at`. - Every claim of the profile has `trust_level` 0, whatever its source: a schema limit (`minimum` and `maximum` are 0), a CHECK in the database, and a type in the domain. Confirming a suggestion changes its status, not its level; higher levels belong to evidence (an assessment result, a confirmation by a third party), which is stored separately and never written into a claim. - A request carries a decision for each value (`value` and `status`): `confirmed` sets a manual value or confirms a stored suggestion with the same value (the source and the quote are kept), and `extracted` keeps a stored suggestion unconfirmed and is accepted only with exactly the same value. Any other use of `extracted` answers 400 with the pointer of that status, for example `/stack/1/status`, so a form submitted unchanged confirms nothing by accident, as for needs. The client never sends the source, the trust level, or the confirmation time. Version and retries: - The version starts at 0 for a candidate without a saved profile; such a candidate gets 200 with every field `unknown` and empty lists, not 404. `PUT` replaces the whole profile and a list replaces the list; a field sent as null becomes unknown and is removed. - Concurrent edits are controlled by `expected_version` in the body, as in the questionnaire: the generated client cannot read `ETag` yet. A stale value answers 412 `version_conflict` and changes nothing, and the client reads the profile again, so an edit from another tab is never lost silently. A body that changes nothing keeps the version and answers 200 even with an older version, so no Idempotency-Key is needed. Every saved change advances the version by one. - Order of checks: session (401), CSRF and Origin (403 `csrf_check_failed`), request validation (400), account scenario (403 `forbidden` for an employer), a version above the current one (412), domain rules that depend on the body alone (400), then the rules that depend on the stored claims, with the version: a decision `extracted` for something that is not a stored suggestion answers 412 on a stale version (another tab may have confirmed the value) and 400 on the current one; an unchanged body is 200; any other change over a stale version is 412. A version above the current one never existed and answers 412 even for an unchanged body. The domain rules that the schema cannot express are: a repeated tag, skill, or role specialization (without regard to letter case for tags and skills), a period that ends before it starts or lies in the future, and a decision `extracted` for something that is not a stored suggestion. The 400 response never repeats a submitted value. No file, ML, or FSP: - The profile is filled in entirely by hand. No field requires a resume, ML extraction, or an FSP account, and the migration and queries create no mandatory link to a file, ML, or FSP. Resume upload and linking an FSP ID are planned additive features; they will add their own fields and sources without changing these. Relation to the questionnaire: - The questionnaire (`/me/questionnaire`) names at most two specializations for assessment; the profile is what the candidate presents about themselves. Same-named concepts are not duplicated under different meanings: the self-assessed grade and the stack are the same claim in two places (in the questionnaire for the start of the assessment and per specialization, in the profile for display), saved separately, and the server never copies one into the other; the total months of experience in the questionnaire and the experience entries of the profile are different claims; work formats live only in the questionnaire, while place, relocation, and salary live only in the profile. The schema descriptions of both sides refer to each other. Storage (migration 00013): `candidate_profiles` (the profile row: `user_id`, `version`, times) and `candidate_profile_claims` (one row per stored claim: `kind`, `ordinal`, `value` jsonb, `status`, `origin`, `trust_level`, `quote`, `extraction_version`, `confirmed_at`). A missing row means `unknown`. Each kind of value has a CHECK for the format and bounds of the contract; `trust_level` is always 0; the tables have no file column, no FSP column, and no confirmed grade. Details are in [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#candidate-profile). Open questions for the product owner and legal: - Contact kinds: only the four C4 kinds are allowed. Whether links to GitHub, social networks, or a website are needed (the PRD hides them until an invitation is accepted); that would be a contract change in `ContactFieldKind` too. - The 152-FZ basis: which consent covers storing the profile (C1 at registration or a separate one), whether the name and the contacts need separate consents, the retention periods, and the deletion procedure. Today deleting an account cascades to its profile, and there are no retention rules. - The order of the version and the domain rules: the version is checked before the rules that depend on stored claims (a stale tab gets 412, not 400); the product owner should confirm. - Full replacement: `PUT` drops stored import suggestions that the client did not render and send back with the status `extracted`; whether that is acceptable or the server should keep suggestions that were never shown. - The minimum for the onboarding step `candidate_profile`: the current contract requires no field, so any successful PUT completes that step, including an empty no-op. Requiring fields later needs a separate product decision and contract change. - One source between the questionnaire and the profile: keep the self-assessment and the stack independent, or store one claim and show it in both places. - Soft skills: there is no taxonomy, only free text, up to 10 items of 50 characters; whether a dictionary is needed. - Experience: employer names and descriptions are personal data; how the anonymous card generalizes them (PRD: industry and size) is for the card contract, not this one. - Contact verification (confirming the phone or the email of the profile) is not provided: contacts are claims of level 0. `TestCandidateProfileOperationsFollowTheConventions`, `TestCandidateProfileSeparatesSelfAssessedGradeFromConfirmedCategory`, `TestCandidateProfileClaimsCarrySourceAndTrustLevelZero`, `TestPrivateProfileSchemasAreNotMixedWithOrganizationVisibleDTOs`, `TestGeneratedProfileDTOsCarryNoConfirmedGradeInRequests`, `TestProfileSchemaValidationPrecedesImplementation`, and `TestProfileAccessBeforeImplementation` pin the generated server and the bundle, and `frontend/src/shared/api/profile-contract.test.ts` pins the generated Zod rules, the request types without a confirmed grade, and the absence of profile fields from the organization, invitation, and need schemas. ### Assessment The `assessment` tag covers the assessment attempts of the current candidate (PRD FR04 and FR05): availability, start and resume, answers including the code practice, finalization, and the result. The operations are in the contract, but their business logic is not implemented: a guest answers 401 `unauthenticated`, and a request with a verified session reaches 501 `not_implemented` after request validation. Unsafe protected operations also require the session-bound CSRF token and exact Origin. | Method and path | operationId | Security | Success | Specific errors | | --- | --- | --- | --- | --- | | `GET /api/v1/me/assessment-availability` | `GetMyAssessmentAvailability` | session | 200 `AssessmentAvailability`, `Cache-Control: no-store` | 401 `unauthenticated`, 403 `forbidden` | | `POST /api/v1/me/assessment-attempts` | `CreateMyAssessmentAttempt` | session and CSRF, Idempotency-Key | 201 `AssessmentAttempt`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `csrf_check_failed` or `forbidden`, 409 `state_conflict` or `idempotency_in_progress`, 422 `idempotency_key_reused`, 429 | | `GET /api/v1/me/assessment-attempts/{attempt_id}` | `GetMyAssessmentAttempt` | session | 200 `AssessmentAttempt`, `Cache-Control: no-store` | 401, 403 `forbidden`, 404 `not_found` | | `POST /api/v1/me/assessment-attempts/{attempt_id}/sessions` | `StartMyAssessmentAttemptSession` | session and CSRF, Idempotency-Key | 200 `AssessmentAttempt`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict` or `idempotency_in_progress`, 412 `version_conflict`, 422, 429 | | `POST /api/v1/me/assessment-attempts/{attempt_id}/answers` | `SubmitMyAssessmentAnswer` | session and CSRF, Idempotency-Key | 200 `AssessmentAttempt`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict` or `idempotency_in_progress`, 412 `version_conflict`, 422, 429 | | `POST /api/v1/me/assessment-attempts/{attempt_id}/finalize` | `FinalizeMyAssessmentAttempt` | session and CSRF, Idempotency-Key | 200 `AssessmentAttempt`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict` or `idempotency_in_progress`, 412 `version_conflict`, 422 | | `GET /api/v1/me/assessment-attempts/{attempt_id}/result` | `GetMyAssessmentResult` | session | 200 `AssessmentResult`, `Cache-Control: no-store` | 401, 403 `forbidden`, 404 `not_found`, 409 `state_conflict` | | `GET /api/v1/me/assessment-results` | `ListMyAssessmentResults` | session | 200 `AssessmentResultHistoryPage`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `forbidden` | | `GET /api/v1/me/assessment-signal-notice` | `GetMyAssessmentSignalNotice` | session | 200 `AssessmentSignalNotice`, `Cache-Control: no-store` | 401, 403 `forbidden` | | `PUT /api/v1/me/assessment-signal-notice` | `AcknowledgeMyAssessmentSignalNotice` | session and CSRF | 200 `AssessmentSignalNotice`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `csrf_check_failed` or `forbidden`, 409 `state_conflict` | Every operation also declares the `default` problem response. The signal notice (`assessment-signal-notice`) lists the signals collected during a real attempt: browser events (focus loss, copy, paste and cut with a size, fullscreen exit; stored only while C3 is current) and server signals (response time, change of network address, parallel sessions, comparison of answer digests; only one-way keyed digests are stored, never addresses or session tokens). `GET` returns the notice version the server requires and whether the candidate acknowledged it; `PUT` stores the acknowledgement for the account and that version. The acknowledgement is a record that the candidate was informed, not a consent: it does not change C3, and the signal operation neither reads it nor refuses a batch without it. `PUT` needs no Idempotency-Key, because a repeat keeps the first time and answers 200; another version answers 409 `state_conflict`. The `demo_express` mode collects no signals and needs no acknowledgement. Access: - The candidate comes only from the session; no operation takes a candidate identifier. An employer account answers 403 `forbidden`. An attempt of another candidate answers 404 `not_found`, the same as an unknown identifier, so attempt identifiers cannot be probed. - No operation offers an employer answers, attempt history, or anti-cheat signals. Employers see the current category on the anonymous card and the permitted skill evidence of that card ([Skill evidence](#skill-evidence)), never a result. Modes and versions: - `kind` is required on creation: `root`, `corrective`, or `demo_express`. A real attempt uses `demo_basic` or `adaptive`; the server picks the mode from the published bank and the client never sends it. `demo_basic` scores a fixed form of reviewed demo items by their keys against the pass mark of the versioned basic grading policy, computes no ability estimate, and decides in one step: it never offers an additional practice. `adaptive` is the adaptive test of FR04. A candidate may explicitly request `demo_express`, a separate interactive 3 to 5 minute training run with no category, target grade, percentile, real-assessment quota, or qualification evidence. - A corrective real attempt includes `root_attempt_id`. The server allows only a strictly lower target grade not already tried in that chain. Creating the root reserves one slot in the three-root-attempts-per-180-days quota; corrections share that slot and the root's immutable `chain_deadline` (72 hours from the root start under the current policy), while keeping their own item, practice, and session limits. A correction spends no additional root slot, cannot extend the deadline, and does not reset the 30/90-day timers. A root preflight refusal creates no attempt and reserves no slot. An expired or incomplete attempt does not create a free new chain, and an insufficient bank does not grant another root slot. `demo_express` is outside correction chains and real-assessment availability. - Creation fixes `versions`: `policy_version` (the number of the `product` policy version), `bank_version`, and `algorithm_version`. The attempt and its result keep them, so a result is reproduced from the stored answers and these versions, and a later version never rewrites it. - The attempt `version` advances by exactly one with each committed change, including a verdict, an explicit session start, expiry, or automatic finalization. GET operations are projections only: they never change the state, consume session quota, or advance the version. A command or background transition commits due outcomes. Attempt lifecycle, with the commands each state accepts: | State | Meaning | Accepts | | --- | --- | --- | | `in_progress` | Items are being answered; `current_item` is the item to answer | an answer to `current_item` | | `practice_pending` | The item part is done; the main practice has no finished verdict (not submitted, `pending`, or `failed`) | a practice solution while it is `not_started` or `failed` | | `additional_practice_pending` | Adaptive only: finalize found the probability in the band below confirmation and offered one additional practice in the same attempt | the additional practice solution while it is `not_started` or `failed`; finalize in the same statuses declines the offer | | `ready_to_finalize` | Every required part is done | finalize | | `completed` | A decision was made; the result is available | only the repeat of finalize | | `expired` | The time or session limit passed before the candidate finished; the result confirms no grade | none | | `insufficient_bank` | The bank could not cover the blueprint within the limit; the result confirms no grade | none | - Additional practice (PRD FR04): with 0.50 <= P_G < 0.80 in the demo policy, the first finalize of an adaptive attempt completes nothing. It appends a practice of kind `additional` to `practices`, moves the attempt to `additional_practice_pending`, and returns the attempt. The practice continues the same attempt, keeps its time and session limits, and spends no new attempt. The next finalize after its verdict decides; P_G still below 0.80 gives `not_confirmed`. Finalizing without submitting it declines the offer with the same outcome. `practices` is a list with a `kind` rather than one more nullable field, so later practice kinds stay additive. - Finalize therefore always answers with `AssessmentAttempt`, never with a result or a `oneOf` of both. When the state is `completed`, the client reads `GetMyAssessmentResult`. One response type keeps generated clients unambiguous and leaves room for non-terminal decisions without a breaking change. - Limits: `expires_at` and `sessions` (`used`, `max`, `idle_timeout_seconds`, null when the policy defines no session limit) come from the policy version; PRD FR04 allows two sessions within 72 hours. Creation starts session 1. After an idle timeout the candidate explicitly calls `StartMyAssessmentAttemptSession` with the latest `expected_version`; it starts the next session only if quota and deadline allow. Calling it during an active session is a no-op. Session start does not extend `expires_at` or `chain_deadline`. - At the limits: a practice already `pending` is graded first. A command or background transition then finalizes `ready_to_finalize` as `completed`, declines an unsubmitted additional practice (`completed`, `not_confirmed`), or moves `in_progress` and `practice_pending` to `expired`. GET never commits these transitions. `GetMyAssessmentResult` answers 409 while a due transition has not yet been stored. - Insufficient bank is a distinct state in two places. Before a root attempt starts, `GetMyAssessmentAvailability` shows `insufficient_bank` for a grade without a published bank or enough unseen families, and `CreateMyAssessmentAttempt` answers 409 `state_conflict` without creating an attempt or reserving a root slot. A correction with an expired chain deadline or insufficient safe bank is also refused; it does not create a new chain. During an existing attempt, the terminal state `insufficient_bank` ends it without a confirmed grade instead of repeating families. - Confirmed grade. `confirmed_grade` and `confirmed_basis` of each questionnaire specialization are read together from the current category, in one snapshot. `confirmed_basis` is `synthetic_demo` for a demonstration grade and null exactly when no grade is confirmed. An attempt does not set them directly: only a category upgrade changes them. - No new problem code is added, so attempt creation gets 409 `state_conflict` plus the availability status instead of a `bank_unavailable` code. The `ProblemCode` enum is copied byte-for-byte into the ML contract (`test_contract_copies.py`), so a new code would also change the ML contract and its generated models. The availability read also tells the client why an attempt cannot start and, for `cooldown`, from when, which a fixed problem detail cannot carry. - Availability shows the limits of each grade before the start: `time_limit_seconds`, `max_sessions`, `max_items`, and `practice_required`, null when unknown. - Root-attempt quota and retry timers are separate. Only root creation reserves one of the three root slots per 180 days; corrections in that chain do not reserve another. `insufficient_bank` or an unavailable sandbox does not create a new attempt or open a free chain. After a failure, including the first test, a strictly lower grade can be tested through the same chain; lower-grade corrections do not reset the 30-day same-grade or 90-day promotion timers. Items and answers: - An item has an `id` (the instance), `sequence`, a plain-text `prompt`, and `content` (`ItemContent`) in one of the formats `choice`, `number`, `string`, `order`, `find_error`, `configuration`, and `practice`. It never contains an answer key, a correct option, a score, a family or variant identifier, a seed, or a hidden check, and seed items look like scored ones. `multiple`, `max_selections`, and `max_length` are properties of the format or the task family and never derived from the key. The variant is fixed when first served, so a reload, a retry, or a resumed session returns the same instance. - An answer (`AssessmentAnswer`) has the same seven formats and carries only the answer. Unknown fields such as `score`, `duration`, or `seed` answer 400. The server records the times and scores the answer with the key of the item instance; time never enters the grade decision. Responses never say whether an answer was correct. - The practice solution runs asynchronously in the sandbox against three hidden check groups; the client polls the attempt while it is `pending`. The verdict shows only the score 0-3 and the pass state of each group. Every outcome caused by the solution (a compilation or runtime error, a time or memory limit) is `finished` with groups not passed. `failed` (`sandbox_busy` or `sandbox_error`) means only that the infrastructure could not run it; it consumes nothing. This keeps `failed` from acting as an oracle for hidden checks and from allowing endless retries. After `finished` no other solution is accepted. - If the latest submission is still `failed` when the limit passes, the result is `not_determined` with the reason `sandbox_unavailable`. A practice never submitted gives `practice_incomplete`. - An attempt has no practice only in `demo_basic` while code practice is disabled until the sandbox isolation is verified; the result then lists the `practice_not_included` limitation. Commands, retries, and versions: - Create, start/resume session, answer, and finalize require Idempotency-Key with the 24-hour replay described above, so a repeated command returns the same outcome. Session start, answers, and finalize carry `expected_version`, the attempt `version` the client read. Creation has no version to compare and relies on the key; the single active real attempt per specialization is enforced by the state. - Each item accepts one answer. Sending the stored answer again, even with a new key or an older `expected_version`, stores nothing, keeps the version, and answers 200 with the current attempt. Equality is defined per format: sets for `option_ids` and `line_numbers`, the exact sequence for `element_ids`, numeric equality for `number`, identical text without normalization for `text` and `config`, and the same language with identical source for a practice. A different answer for an answered item answers 409 `state_conflict` with the current version; with a stale version the version check comes first and answers 412. - Exception: a practice whose latest verdict is `failed` is outside the repeat rule. A submission with the same or a different solution and the current version queues it again and advances the version. - Finalizing a `completed` attempt answers 200 with that attempt, so the result is computed once. A retry of the finalize that offered an additional practice, sent with a new key, carries the old version and answers 412, so it never declines the offer by accident. - A stale `expected_version` answers 412 `version_conflict`, not 409. This keeps the repository rule and questionnaire precedent: `version_conflict` is 412 for If-Match and for a body `expected_version` alike, because the client action is to read the resource again. 409 `state_conflict` is kept for a command that the attempt state does not allow at the current version: the work session ended, the item is not current or has another answer, the attempt is terminal or past its limits, a practice verdict is pending, or the attempt is not ready to finalize. The two codes lead to different client actions. - A premature finalize answers 409 `state_conflict` without listing the unfinished items, because `Problem` allows no extension fields. The client reads them from the attempt: `state`, `progress`, `current_item`, and `practices`. - Order of checks for a command: session (401), CSRF and Origin (403), request validation (400), account scenario (403 `forbidden`), the Idempotency-Key (422, 409 `idempotency_in_progress`, replay), attempt ownership (404), the attempt version (412 when supplied), due time or session transitions, then the command state (409 `state_conflict`) and domain rules (400 with pointers such as `/answer/option_ids/0`). An explicit session-start command returns the updated attempt when it commits a due terminal transition. Following the Idempotency-Key convention, stored 404 and 409 responses replay under the key; 400, 412, 429, and 5xx are not stored. Create and answers are rate-limited (429 with `Retry-After`), which also limits sandbox load. `TestAssessmentSchemaValidationPrecedesImplementation` checks the schema rejections through the generated server. Result: - `GetMyAssessmentResult` answers for a terminal attempt and 409 `state_conflict` for an active one, including `additional_practice_pending`. `outcome` is `confirmed`, `not_confirmed`, or `not_determined` with `not_determined_reason` (`expired`, `practice_incomplete`, `insufficient_bank`, `sandbox_unavailable`). A result never lowers a confirmed grade: `previous_confirmed_grade` stays in force when the attempt confirmed nothing. - Attempt and result responses carry the `kind` discriminator: `root`, `corrective`, or `demo_express`. Real results always include the correction-chain field pair: both are null for a root attempt, and both are populated for a corrective result. A `demo_express` result is a separate educational shape with a short summary and `demonstration_only`; it has null category, target grade, confirmed grade, strength, uncertainty, and score, and empty practices, gaps, and next steps. It cannot be used as qualification evidence and is never visible to employers. - `calibration_status` and `limitations` describe the method. Fields that the method does not compute are null, never zero: `demo_basic` has null `uncertainty` and `strength`, and `adaptive` has null `basic_score`. `uncertainty` holds `theta`, `standard_error`, `interval_95`, and `p_grade`. `practices` lists the verdicts by kind. `durations` is a separate label and never enters the decision. - `next_steps` come from the server: `retake_same_grade`, `take_lower_grade`, `accept_lower_grade` (the command is planned), and `take_higher_grade`. A first confirmation is not a promotion, so `take_higher_grade` after it has a null `available_at`; after a promotion the next one waits for the 90-day promotion interval. - The result never contains answers, per-item correctness, keys, seeds, hidden checks, or anti-cheat signals. - Category from a `demo_basic` result. A real result carries `category_decision`: `status` (`not_eligible`, `not_confirmed`, `assigned`, `unchanged`), the grade in force before and after the attempt, `method` (`demo_basic_pass_mark`), `source` (`synthetic_demo`), and `calibration_status`. The threshold comes from the accepted policy version pinned to the attempt: reaching it counts, and no request parameter sets it. A category is assigned only when `ASSESSMENT_DEMO_CATEGORIES_ENABLED` is on, the policy version is a complete demonstration policy with `demo_basic` (its threshold is its own `basic_pass_mark_bp`), and an operator attestation exists for the opening, its manifest, and the policy version; otherwise `status` is `not_eligible` and `confirmed_grade` is null even though `outcome` may be `confirmed`. `confirmed_grade` is set only when a reviewed source accepted the confirmation (`assigned` or `unchanged`). A failure, an equal grade, or a lower grade neither lowers nor changes the current category. `demo_express` never gets a `category_decision` and never creates a category. A result stored before category decisions existed has no `category_decision`: its current grade is not reconstructed afterwards. - `GET /api/v1/me/assessment-results` returns the history of the candidate only: completed `root` and `corrective` results, newest first by `decided_at` and `attempt_id`. The cursor is opaque, bound to the candidate, and uses only `[A-Za-z0-9_-]`; a foreign, altered, or malformed cursor answers 400 `validation_failed` with pointer `/cursor`. An employer account gets 403. A later change of the current policy, bank, or category changes no stored record. An employer receives only the current category (specialization, grade, the coarse strength `standard`, and the basis `basis`) through the anonymous card when the candidate published the `categories` field; the projection holds no attempt, score, version, or reason for a missing confirmation. Planned, additive: a short approach description of up to 1500 characters next to the practice, which never decides the grade (PRD FR05); the debug run operation of the practice; the server signals of the anti-cheat layer (answer time, parallel sessions, address changes), which lead to a review and an appeal, never to a public label and never to the employer (PRD FR05). ### Needs The `need` tag covers the hiring needs of an organization (PRD FR08, with the versions of FR10): requirements with their confirmation state and provenance, immutable versions, readiness, and category recommendations. The operations are in the contract, but their business logic is not implemented: a guest answers 401 `unauthenticated`, and a request with a verified session reaches 501 `not_implemented` after request validation. Unsafe protected operations also require the session-bound CSRF token and exact Origin. | Method and path | operationId | Security | Success | Specific errors | | --- | --- | --- | --- | --- | | `GET /api/v1/organizations/{org_id}/needs` | `ListOrganizationNeeds` | session | 200 `NeedList`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `forbidden`, 404 `not_found` | | `POST /api/v1/organizations/{org_id}/needs` | `CreateOrganizationNeed` | session and CSRF, Idempotency-Key | 201 `Need`, `Cache-Control: no-store` | 400, 401, 403 `csrf_check_failed` or `forbidden`, 404, 409 `idempotency_in_progress`, 422 `idempotency_key_reused`, 429 | | `GET /api/v1/organizations/{org_id}/needs/{need_id}` | `GetOrganizationNeed` | session | 200 `Need`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `forbidden`, 404 `not_found` | | `PATCH /api/v1/organizations/{org_id}/needs/{need_id}` | `UpdateOrganizationNeed` | session and CSRF | 200 `Need`, `Cache-Control: no-store` | 400, 401, 403, 404, 412 `version_conflict`, 429 | Every operation also declares the `default` problem response. A malformed `org_id` or `need_id` answers 400 with the path pointer. Access: - `org_id` in the path is the only source of the organization, and the server checks it against the active membership of the session account; no request has an organization, membership, or role field. The organization contract owns organizations and memberships and reuses the same path parameter, `parameters.yml#/OrganizationId`. - An account without an active membership in `org_id`, an unknown organization, an unknown need, and a need of another organization all answer 404 `not_found`, so identifiers cannot be probed. A candidate account answers 403 `forbidden`, and so does a member whose role does not allow the operation. - In the MVP only the owner of the organization works with needs. The other roles of the PRD FR07 matrix (recruiter, hiring manager and technical expert for assigned needs) are planned and change no field of the contract. Fields and provenance: - `requirements` (`NeedRequirementSet`) holds `specialization`, `grade`, `required_skills`, `desired_skills`, `tasks`, `domain`, `work_formats`, `location`, and `salary`. A field in a response is `{status, value, source}`; a list item has its own `status` and `source`. - `status` is `confirmed` (a member entered or confirmed the value), `extracted` (a suggestion that waits for confirmation), or `unknown` (no value). An unknown field has null `value` and `source`; the server never fills it with a default or a guess such as Senior, remote, or a zero salary. Only confirmed values feed readiness, recommendations, search, and invitations. - `source` has `origin` (`manual`, `extracted_from_text`, or the planned `imported`), `quote` (an exact excerpt of up to 300 characters, or null), `extracted_in_version`, and `extraction_version`. The quote is an excerpt of the `source_text` of `extracted_in_version`, not necessarily of the current text: a confirmed value keeps its quote after the text changes. Confirming a suggestion keeps its provenance; changing the value makes it `manual`. - A skill has `taxonomy_code`. It is null for a skill that the platform taxonomy does not know: the name stays as given, no code is guessed, and recommendations count the skill as not covered. - With `source_text`, the server extracts suggestions with deterministic rules and a dictionary before it answers, so needs work while ML is disabled. ML suggestions with quotes are planned as an asynchronous addition that creates a new version and never overwrites a confirmed value. - The text is stored as written and may contain requirements that discriminate by a protected characteristic; the extractor never turns them into a need field. The field for what a candidate must not have, with the Labor Code article 64 check, is deferred to the requirement validation feature and will be added without a breaking change. Requests, confirmation, and changes: - Every requirement field in a request is a decision `{value, status}` (`NeedSpecializationInput`, `NeedGradeInput`, `NeedDomainInput`, `NeedWorkFormatsInput`, `NeedLocationInput`, `NeedSalaryInput`), and every list item is `{name or text, status}`. `status` is `confirmed` or `extracted`. A bare value fails validation, so confirmation is always explicit. - `confirmed` with the stored suggested value confirms it and keeps its provenance; `confirmed` with another value sets a confirmed manual value. `extracted` keeps a stored suggestion open and is allowed only with exactly the stored suggested value; any other value, or a field or item without a suggestion, answers 400 with the pointer of that status, such as `/grade/status` or `/required_skills/2/status`. A client that sends back an unchanged form therefore confirms nothing by accident: it sends each suggestion with `extracted` or leaves the field out. - A need never requires a vacancy: only `title` is required, and `vacancy_id` is optional and nullable. Until vacancies exist in the contract, any vacancy identifier answers 400 with the pointer `/vacancy_id`. - On creation every decision must be `confirmed`, because a new need has no stored suggestion. An absent field is extracted from `source_text` or stays unknown. A nullable field sent as null stays unknown, and a skill or task list sent empty stays empty; neither is extracted. An empty `work_formats` value fails `minItems`. - `UpdateOrganizationNeed` uses explicit field replacement in `application/json`, not JSON Merge Patch (RFC 7396): a present field replaces that field as a whole, an absent field stays unchanged, a decision and a list are never merged, and a stored item left out of a sent list is deleted. Null removes a nullable field (it becomes `unknown`, or `vacancy_id` is unlinked); an empty skill or task list deletes every item; a list sent as null answers 400. ogen generates one optional, or optional and nullable, value per decision (`OptNilNeedGradeInput`, `OptNilNeedSalaryInput`). - A different `source_text` extracts again. New suggestions replace only the `extracted` values and items of fields not named in the body; confirmed values are never overwritten, a suggested skill whose name is already in either skill list is skipped, and a suggestion that a member deleted is not proposed again for this need. - The server also rejects a repeated skill or task and a skill in both lists, with 400 and the pointer of the later item, such as `/required_skills/1/name`. Versions and concurrency: - `version` starts at 1 and advances by exactly one with each committed change, including server-side ones. Each version is an immutable snapshot. GET always returns the latest version. - `requirements_version` is the version in which the confirmed requirements were last changed. Confirming, changing, or removing a requirement sets it to the new `version`; a change of the title, the vacancy link, the text, or suggestions only keeps it and invalidates neither the recommendations nor search results. Search runs, selection snapshots (FR10), and invitations refer to `(need_id, requirements_version)`, and only a new `requirements_version` calls for a new selection snapshot. Reading and comparing earlier versions are planned as separate operations that return `NeedRequirementSet` for a version; they add nothing to `Need`. - A change carries `expected_version`, the version the client read, in the body for the same reason as the questionnaire: the generated client cannot read `ETag` yet. A stale value answers 412 `version_conflict` and changes nothing; the repository rule keeps 412 for If-Match and a body version alike. A body that changes nothing answers 200 with the current need even with an older version, so PATCH needs no Idempotency-Key. POST needs one with the 24-hour replay; only the 201 is stored. Readiness: - `readiness.missing_fields` lists each critical field without a confirmed value: `specialization`, `grade`, `required_skills` (at least one confirmed skill), `work_formats`, `salary`, and `location` when the confirmed formats include `office` or `hybrid`. Each item has `reason` (`unknown` or `unconfirmed`) and a specific Russian `question`. - An incomplete need is saved (201 or 200), not rejected. `Problem` allows no extension fields, so the missing fields live in the resource, not in a problem. Each later operation, such as search or an invitation, states which readiness it requires. Salary: - `SalaryRange` `[A; B]` has `salary_from` and `salary_to` (`RubAmount`, whole rubles), `currency` (`RUB` only), `period` (`month` only), and `tax_basis` (`net` or `gross`); every field is required. Requests send it as `salary: {value, status}`, so its pointers are under `/salary/value`. - The schema requires bounds that are positive multiples of 1000 up to 100000000 and rejects another currency, period, or basis, for example with `/salary/value/tax_basis`. A missing field of the nested range answers `required` with its pointer, such as `/salary/value/tax_basis`. - The server checks the cross-field rules of PRD FR13 in integer arithmetic: `A < B` and a width `(B - A) / ((A + B) / 2)` from 10% to 40% inclusive, that is `20 * (B - A) >= A + B` and `5 * (B - A) <= A + B`. A violation, including equal bounds, answers 400 with the pointer `/salary/value/salary_to`. `[95000; 105000]` (exactly 10%) and `[80000; 120000]` (exactly 40%) are accepted. FR13 applies the same rules to the range of a need and of an invitation, and `docs/*/ARCHITECTURE.md` now states them for invitations instead of `0 < salary_from <= salary_to`. - Limit against probing hidden minimums (FR13, enforcement planned): setting a confirmed range, on creation or on a change, counts against a counter shared by the whole organization, every member and every need, so a new need does not reset it. At most three range settings a day; over the limit the server answers 429 with Retry-After and changes nothing. After five settings within seven days the money component is `withheld` for seven days. Repeated range changes also feed the private organization risk signals. Recommendations: - `recommendations` is computed by the server from the confirmed requirements of `requirements_version` with a versioned policy (`policy_version`, `algorithm_version`, `computed_at`). `status` is `computed`, `pending`, or `not_available` without a confirmed skill. The server may recompute them for the same `requirements_version`, for a new policy or a changed pool of candidates, without a new need version; `computed_at` and `policy_version` then change. - Each category (`specialization` and `grade`) has `score`, `skill_overlap` (weighted share with weight 2 for required and 1 for desired skills, covered and uncovered skills), `money`, and `supply` as a band: `fewer_than_5`, `from_5_to_29`, `30_or_more`. The list order is the ranking. - `money.status` is `computed`, `insufficient_data` (fewer than five candidates with a comparable known minimum), `no_salary`, or `withheld`; the last three use the neutral 0.5 and a null share. `money.share` is rounded down to a quarter (0, 0.25, 0.5, 0.75, 1): each probe of a new upper bound then tells at most which quarter of the group accepts it, and in the smallest allowed group of five a single minimum often does not move the value, while the share still separates a range that most candidates accept from one that few accept. - `score` is `0.5 * Overlap + 0.3 * Money + 0.2 * Supply`, rounded half up to two decimals, computed from the published components: the exact overlap, the quarter-rounded share or the neutral 0.5, and `Supply = min(1, active / 30)`. It is null when `supply` is `fewer_than_5`. The ranking uses Supply only at band precision below five: every group of fewer than five candidates enters it with Supply 0, so neither the score nor the order reveals the exact size of a group below five, which FR08 forbids. For five or more candidates the exact Supply is used, so the recommendation fixture (Overlap 1, Money 0.5, 15 active candidates) gives `score` 0.75. - Deviation from the PRD formula: the money share in the score and ranking is the quarter-rounded share, not the exact one, and a category with fewer than five candidates has no score. Otherwise the score with the exact share would reveal the share that `money.share` rounds, and a score with the exact Supply of a small group would reveal its size. The displayed breakdown consists of the published components. - Requests cannot set a recommendation, its score, membership, or a candidate minimum: bodies have `additionalProperties: false`, and unknown fields such as `rec_score`, `members`, `candidate_minimum`, `version`, `requirements_version`, or `recommendations` answer 400 with the whole-body pointer. `TestNeedSchemaValidationPrecedesImplementation` checks the schema rejections through the generated server, `TestNeedUpdateDecodingKeepsAbsentAndEmptyListsApart` checks the list decoding, and `frontend/src/shared/api/needs-contract.test.ts` pins the generated Zod limits, the explicit status of every decision, and the absence of these fields in the request types. Planned, additive: reading and comparing versions, exclusions, the market range hint (P25-P75) of FR08, the check plan "vacancy -> tasks", a need status for archiving, list filters, and need assignments. ### Support cases The `support` tag covers the cases of the current account (PRD FR18, with the manual assessment of FR04 and C3): questions to support, complaints, appeals of a grade or an anti-cheat decision, and manual assessment requests. The operations are implemented: a guest answers 401 `unauthenticated`, and a verified session passes request validation and the domain rules. Unsafe protected operations also require the session-bound CSRF token and exact Origin. | Method and path | operationId | Security | Success | Specific errors | | --- | --- | --- | --- | --- | | `GET /api/v1/me/support-cases` | `ListMySupportCases` | session | 200 `SupportCaseList` of `SupportCaseSummary`, `Cache-Control: no-store` | 400 `validation_failed`, 401 | | `POST /api/v1/me/support-cases` | `CreateMySupportCase` | session and CSRF, Idempotency-Key | 201 `SupportCase`, `Cache-Control: no-store` | 400, 401, 403 `csrf_check_failed` or `forbidden`, 404 `not_found`, 409 `state_conflict` or `idempotency_in_progress`, 422 `idempotency_key_reused`, 429 | | `GET /api/v1/me/support-cases/{case_id}` | `GetMySupportCase` | session | 200 `SupportCase`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 404 `not_found` | Every operation also declares the `default` problem response. Access: - The author is the account of the session; no request has a user, account, or organization field. PRD FR18 lets both candidates and company employees contact support, so `/me` serves both scenarios: an employer account opens `support` cases, and the other types answer 403 `forbidden` for it. A case belongs to the account that created it, not to an organization: other members of the same organization never see it. - Another account's case answers 404 `not_found`, the same as an unknown identifier. The contract answers 404, so identifiers cannot be probed, and the client shows the same "not found" state for a foreign and an unknown case. The author reads the case whatever happened to the object since then, so a refused test or a revoked access never hides it. - The moderation queues are separate staff operations with their own DTOs; they add nothing to these operations. Types and object references: | Type | Accounts | Object reference | Other fields | Response target | | --- | --- | --- | --- | --- | | `support` | candidate, employer | optional; `assessment_attempt` of the caller, an `organization` the caller can see, an `invitation` addressed to the caller, or another `support_case` of the caller | optional `assessment_target` | policy value | | `complaint` | candidate | required; an `organization` the caller can see or an `invitation` addressed to the caller | required `complaint_reason` | policy value | | `grade_appeal` | candidate | required; a terminal `assessment_attempt` of the caller, or a `support_case` of the caller of type `manual_assessment`, `resolved` with the outcome `assessed` | none | 10 business days | | `anticheat_appeal` | candidate | required; an `assessment_attempt` of the caller with an anti-cheat review decision | none | 10 business days | | `manual_assessment` | candidate | optional; a prior `assessment_attempt` of the caller in the same specialization | required `assessment_target`; the server fixes `rubric_version` | 5 business days | - The request is a `oneOf` of five variants selected by `type` (`SupportCaseCreateSupport`, `SupportCaseCreateComplaint`, `SupportCaseCreateGradeAppeal`, `SupportCaseCreateAnticheatAppeal`, `SupportCaseCreateManualAssessment`). Each variant restricts its reference schema, so the schema already rejects an organization in a grade appeal or a case in a complaint with the pointer `/object/type`, and a missing field of the type with its pointer, such as `/object` or `/assessment_target`. ogen selects the variant by the value of `type`. An unknown or missing type and a field of another variant such as `complaint_reason` in a support case answer 400 with the whole-body pointer `""`, because they concern the top-level variant; an `object.id` that is not a UUID answers 400 with `/object/id` (example `SupportCaseMalformedReference`). - A category assigned without an attempt is appealed too (FR18): a grade appeal may reference the caller's own manual assessment case once it is `resolved` with `assessed`. An unknown case and another account's case answer 404 `not_found`; an own case of another type, not resolved yet, or resolved with another outcome answers 409 `state_conflict`. - An organization is visible to a candidate that it invited or whose profile the organization contract shows to the candidate, and to an employer account with an active membership. The server checks every reference against the session account: an unknown object and someone else's object both answer 404 `not_found`, so a reference never reveals whether a foreign object exists. The case stores only `{type, id}`. - Invitations are in the contract (see Invitations and contact grants below) but not implemented, and anti-cheat review decisions are not in the contract yet. Until they are implemented, every `invitation` reference answers 404 and every anti-cheat appeal answers 409 `state_conflict`; the request shapes stay the same. - `offer_content` and `salary_terms_violation` complaints require an invitation; another object answers 400 with the pointer `/object/type` (a domain rule after the schema). - A failed first test or no attempt at all never blocks a manual assessment. Creating a case never grants, revokes, or changes a consent, a grade, or an attempt; a manual assessment does not depend on C3. A candidate who revoked C3 (`DELETE /api/v1/me/consents/c3`) or never gave it creates the same request, and the request neither reads nor changes the consent ledger. A retry with the same `Idempotency-Key` returns the original case; a new key (for example after a page reload) while a manual assessment of the same specialization is open answers 409 `state_conflict`, and the open case stays the only one. `rubric_version` is `null` when the target has no single current reviewed category; the server does not guess a rubric, and the case still waits for an expert with no automatic result. Content and fields the client never sets: - `description` is plain text of 1-4000 characters with at least one character that is not white space (`pattern: \S`); line breaks are allowed. ogen converts `\S` to the ECMAScript white space set, so the Go server and generated Zod both reject an empty text or one of spaces such as U+00A0 or U+3000 with the pointer `/description`. ECMAScript white space omits U+0085 (NEL), which Go `unicode.IsSpace` includes, so the implementation adds a domain check: a description whose every character is `unicode.IsSpace` or U+FEFF answers 400 with the pointer `/description`; Zod accepts it and the server stays authoritative. The server stores the text as written and never writes it to logs or notifications. - Every variant has `additionalProperties: false`. The client cannot set the status, the decision or its outcome, the priority, the response target, the rubric, the assignee, the moderator, or a contact: such fields, for example `status`, `decision`, `moderator_id`, `response_target`, `rubric_version`, or `reply_to`, answer 400 with the whole-body pointer. Case: - `number` is a human-readable number assigned on creation, `SC--` with at least six digits, for example `SC-2026-000123`. The sequence is global and never reused, so the number is unique and never changes. The API addresses a case only by its UUID `id`; the number is for letters and calls. A global sequence tells the approximate number of cases created so far, which is acceptable for the MVP. - `status` is `submitted`, `in_review`, `waiting_for_user`, `waiting_expert`, `resolved` (terminal, with `decision`), or `closed` (terminal, without a decision on the merits, for example a duplicate). Only the server changes it. `waiting_for_user` is in the enum but not set yet: it starts with the planned operation that lets the author reply. An appeal and a manual assessment move to `waiting_expert` by a `system` event in the same transaction as their creation, so the 201 already shows it; they stay there until a person decides. - `response_target` is the response deadline of FR18: `kind` `operational_goal` (a goal of the team, not a deadline set by law), `business_days`, `due_at` from the configured business calendar, `answered_at`, `late`, and `policy_version`. For `support` and `complaint` the first public reply, a decision, or a closure meets it; for the appeals and `manual_assessment` only a decision or a closure. Missing it never closes the case or changes a grade. - `decision` is null until `resolved` and then holds `outcome` (`upheld`, `partially_upheld`, `not_upheld`, `answered` for support, `assessed` for a manual assessment), the public `reason`, and `decided_at`. An upheld grade appeal never rewrites the original result; the corrected result is a separate decision of the assessment. - `history` lists every public event in order, starting with `created`: `kind` (`created`, `status_changed`, `reply`, `decision`), `actor` by kind only (`user`, `support`, `system`), `occurred_at`, the resulting `status`, and a public `message`. It is never truncated. Server invariant: a case holds at most 200 events, and the server rejects a staff reply or status change that would leave no room for the terminal event, so every case fits and can still be resolved or closed; further correspondence goes into a new case that references it as `support_case`. A truncation flag with paginated events was rejected: it would make the full case depend on a second read, while human staff cannot realistically produce 200 public events on one case. - A case never contains the identity of a moderator, an expert, or a support agent, internal notes, evidence, assessment answers, anti-cheat or risk signals, or contact data of another person. - Replies reach the user through the case. The server may also notify the verified email address of the account with the number and a link, never with the description, the reply, or assessment details; no request field names another address, so the operation cannot send mail to an address that the user typed. - `ListMySupportCases` returns `SupportCaseSummary` items, newest first, with cursor pagination: the number, type, status, object reference, category, response target, `decision_outcome`, and timestamps, without the description and the history. The full case comes only from `GetMySupportCase`. Commands and limits: - Create requires Idempotency-Key with the 24-hour replay: a retry returns the 201 snapshot stored at creation, with the same case and number, following the repository convention; the client reads the current state with `GetMySupportCase`. 404 and 409 `state_conflict` are stored and replayed; 400, 403, and 429 are not. - An attempt and a resolved manual assessment each accept at most one grade appeal, and an attempt at most one anti-cheat appeal, in any status; a disagreement with the decision goes into a support case that references the appeal as `support_case`. A specialization accepts one open manual assessment and an object one open complaint. A second one, and a grade appeal of an active attempt, answer 409 `state_conflict`. - Every create that passed authentication, validation, and the account scenario counts against a per-account limit from the product policy, including replays, 404, and 409, so the limit also bounds probing of references; over the limit the server answers 429 with `Retry-After`. - Order of checks for create: session (401), CSRF and Origin (403), request validation (400), account scenario (403 `forbidden`), the per-account case limit (429), the Idempotency-Key (422, 409 `idempotency_in_progress`, replay), domain rules (400), the object reference (404), then the state and the limits (409 `state_conflict`). The general rate limit can answer 429 before any check. - No new problem code is added: the `ProblemCode` enum is copied byte-for-byte into the ML contract. An unavailable anti-cheat appeal and a repeated appeal both use 409 `state_conflict`, and the case or the attempt tells the client why. - `TestSupportCaseSchemaValidationPrecedesImplementation` checks the schema rejections through the generated server, and `frontend/src/shared/api/support-contract.test.ts` pins the generated Zod rules, the absence of status, decision, moderator, and contact fields in the request types, and the absence of moderator identity and internal fields in the case and the summary. Open product question for manual assessment: whether repeated manual assessments of the same category follow the retest rules of FR04 (the same grade after 30 days, at most three attempts in 180 days) or their own rule. The contract only allows one open manual assessment per specialization and invents no interval. Open questions for manual assessment after a C3 refusal: whether the request needs a structured reason (for example a "C3 refused" marker) instead of the free-text `description`; whether a target with two current categories for the same specialization and grade (different task languages) should get a rubric chosen by language instead of `null`; whether a repeat with a new key should return the existing open case instead of 409. The contract invents none of these. Planned, additive (a new operation or an optional field): replies of the author, attachments, withdrawal of a case, list filters by status and type, the resulting category of a manual assessment in the decision, a next step for the author, staff queues and decisions, and the pause rules of the response target. Planned contract changes (new enum values; like the catalog codes, generated clients reject an unknown value, so each one is released with regenerated clients): object types `vacancy` and `application` for the vacancies and protected applications of FR16, and an object type for the profile analysis findings. `waiting_for_user` and `support_case` are already in the enums, so the reply operation and follow-up cases need no such change. No new event kind or actor kind is planned: an author reply is a `reply` with the actor `user`, a decision revision is another `decision` event, and experts and moderators are `support`. ### Invitations and contact grants The `invitation` tag covers invitations from an organization to one candidate (PRD FR12, with the salary rules of FR13 and the consent C4): drafts with complete terms, immutable terms versions, sending, the candidate's inbox, the view, acceptance with C4, structured declines, withdrawal, cancellation, and the contact grant. The organization side of the draft is implemented: `ListOrganizationInvitations`, `CreateOrganizationInvitation`, `GetOrganizationInvitation`, and `UpdateOrganizationInvitation` follow the rules below, except that `salary_fit` is always `not_available` and the salary limit and the withheld counter are not enforced yet ([backend](../backend/README.en.md#invitation-drafts)). `SendOrganizationInvitation` and `ListMyInvitations` are implemented as well: the send checks the owner, the key, the version, the state, the current visibility of the candidate, the pending limit of a need, and the 30-day pause after a decline, and only then charges the weekly organization quota; the pause after a no deal is not checked yet, because no operation produces that state; a success means the invitation is already in `ListMyInvitations`, and the notification and the email follow through the outbox ([architecture](../docs/en/ARCHITECTURE.md#sending-invitations)). `GetMyInvitation`, `ViewMyInvitation`, and `DeclineMyInvitation` are implemented as described below, with one limit: the cancellation is not implemented yet. A read and a view at or after the deadline first move a waiting invitation to `expired` with the reason `invitation_timeout` (the read records no view), and a late decline answers 409 `state_conflict`; a declined invitation has `contact_consent` and `contact_grant` null. `AcceptMyInvitation` is implemented as the rules below describe, but the contact read and the revocation of a grant are not implemented yet ([architecture](../docs/en/ARCHITECTURE.md#candidate-acceptance)). The business logic of the other operations is not implemented: a guest answers 401 `unauthenticated`, and a request with a verified session reaches 501 `not_implemented` after request validation. Unsafe protected operations also require the session-bound CSRF token and exact Origin. | Method and path | operationId | Security | Success | Specific errors | | --- | --- | --- | --- | --- | | `GET /api/v1/organizations/{org_id}/invitations` | `ListOrganizationInvitations` | session | 200 `OrganizationInvitationList` | 400, 401, 403 `forbidden`, 404 | | `POST /api/v1/organizations/{org_id}/invitations` | `CreateOrganizationInvitation` | session and CSRF, Idempotency-Key | 201 `OrganizationInvitation` (`draft`) | 400, 401, 403, 404, 409 `idempotency_in_progress`, 422, 429 | | `GET /api/v1/organizations/{org_id}/invitations/{invitation_id}` | `GetOrganizationInvitation` | session | 200 `OrganizationInvitation` | 400, 401, 403, 404 | | `PATCH /api/v1/organizations/{org_id}/invitations/{invitation_id}` | `UpdateOrganizationInvitation` | session and CSRF | 200 `OrganizationInvitation` | 400, 401, 403, 404, 409 `state_conflict`, 412, 429 | | `POST .../invitations/{invitation_id}/send` | `SendOrganizationInvitation` | session and CSRF, Idempotency-Key | 200 `OrganizationInvitation` (`delivered`) | 400, 401, 403, 404, 409, 412, 422, 429 | | `POST .../invitations/{invitation_id}/salary-raise` | `RaiseOrganizationInvitationSalary` | session and CSRF, Idempotency-Key | 200 `OrganizationInvitation` | 400, 401, 403, 404, 409, 412, 422, 429 | | `POST .../invitations/{invitation_id}/withdraw` | `WithdrawOrganizationInvitation` | session and CSRF, Idempotency-Key | 200 `OrganizationInvitation` (`withdrawn`) | 400, 401, 403, 404, 409, 412, 422, 429 | | `GET .../invitations/{invitation_id}/contacts` | `GetOrganizationInvitationContacts` | session | 200 `ContactDisclosure` | 400, 401, 403, 404 | | `GET /api/v1/me/invitations` | `ListMyInvitations` | session | 200 `CandidateInvitationList` | 400, 401, 403 | | `GET /api/v1/me/invitations/{invitation_id}` | `GetMyInvitation` | session | 200 `CandidateInvitation` | 400, 401, 403, 404 | | `POST /api/v1/me/invitations/{invitation_id}/view` | `ViewMyInvitation` | session and CSRF | 200 `CandidateInvitation` (`viewed`) | 400, 401, 403, 404, 429 | | `POST /api/v1/me/invitations/{invitation_id}/accept` | `AcceptMyInvitation` | session and CSRF, Idempotency-Key | 200 `CandidateInvitation` (`accepted`) | 400, 401, 403, 404, 409, 412, 422, 429 | | `POST /api/v1/me/invitations/{invitation_id}/decline` | `DeclineMyInvitation` | session and CSRF, Idempotency-Key | 200 `CandidateInvitation` (`declined`) | 400, 401, 403, 404, 409, 412, 422, 429 | | `POST /api/v1/me/invitations/{invitation_id}/cancel` | `CancelMyInvitation` | session and CSRF, Idempotency-Key | 200 `CandidateInvitation` (`cancelled_by_candidate`) | 400, 401, 403, 404, 409, 412, 422, 429 | Every success has `Cache-Control: no-store`, and every operation also declares the `default` problem response. The paths `...` start with `/api/v1/organizations/{org_id}`. 403 on an unsafe operation is `csrf_check_failed` or `forbidden`; 409 on a command is `state_conflict` or `idempotency_in_progress`; 412 is `version_conflict`; 422 is `idempotency_key_reused`. 429 on a command is the general rate limit with Retry-After, which can answer before any check; on create, update, and send it is also the salary limit or the weekly quota. The contact read and the plain reads declare no 429 of their own, like the other reads of the contract. Access: - Organization side: `org_id` in the path is the only source of the organization, checked against the active membership of the session account, as for needs. An account without the membership, an unknown organization, an unknown invitation, and an invitation of another organization all answer 404 `not_found`; a candidate account and a member whose role does not allow the operation answer 403 `forbidden`. In the MVP only the owner works with invitations; the other roles of FR07 are planned. - Candidate side: `/me/invitations` is bound to the session account. A draft, an invitation addressed to another candidate, and an unknown identifier answer 404 `not_found`; an employer account answers 403 `forbidden`. No request has a user, candidate, organization, or role field. - The candidate is named only by `candidate_handle` (`CandidateHandle` in `common_schemas.yml`, shared with the search results of FR11), never by an email address, a phone number, or an account or profile identifier. An unknown handle, a handle of another organization, and a profile that the organization may no longer see all answer 400 with the pointer `/candidate_handle`. Terms (`InvitationTerms`): - The terms are complete from the first draft and every field is required: `role_title`, `specialization`, `grade`, `offer_type` (`full_time`, `part_time`, `contract`, `internship`), `tasks`, `team`, `tech_stack`, `work_formats`, `location` (null only for a remote-only role; required for `office` or `hybrid` by a domain rule with the pointer `/terms/location`), `communication_method` (`channel` and an optional note), `salary` (`SalaryRange`), and `package`. A draft without the tax basis or the communication method therefore cannot exist: such a body answers 400 `required` with `/terms/salary/tax_basis` or `/terms/communication_method` (examples `InvitationWithoutTaxBasis` and `InvitationWithoutCommunicationMethod`). - `package` has `bonus`, `equipment`, `training`, and `health_insurance` (ДМС). Each is a `oneOf`: `{status: provided, description}` or `{status: not_provided}` ("Не предусмотрено" in the interface). "Not provided" is an explicit choice: a condition left out answers `required` with its pointer, such as `/terms/package/training`; a `provided` one without a description answers `required` at its `description`; a `not_provided` one with a description answers `invalid` at the item. Generated Zod is not strict and strips that description, so only the server rejects it. - Deliberate deviation from the wording of the acceptance criteria: the PRD package lists the work format next to the bonus, equipment, training, and ДМС, but here the format is the required `work_formats` term without a "not provided" variant, because a role always has a format and the indicator and the search compare it. This is an open question for the product owner. - The same schema is the request field and the stored snapshot, so a response can be sent back unchanged. The terms never contain data of the candidate. Versions and conflicts: - `version` advances with every committed change, including the view and the server expiry. `terms_version` advances only when the terms change: a draft change of `terms`, or the one raise of the upper bound after sending. Each terms version is immutable. - Every command except the view carries `expected_version`; `AcceptMyInvitation` also carries `terms_version`. 412 `version_conflict`: `expected_version` or, on acceptance, `terms_version` is not current (the stale terms case, example `InvitationStaleTerms`); nothing changed, nothing is stored under the key, and the client reads the invitation again. 409 `state_conflict`: the state does not allow the command, for example an acceptance of a withdrawn or expired invitation, a command at the deadline or later, a send blocked by the pending limit of a need or by the 30-day pause, a change of a sent invitation, or a second raise; it is stored under the key. The repository rule keeps 412 for any stale version, as for needs and the questionnaire. - Order: after the invitation is found and a due expiry is applied, and after the repeat check, a terminal state (`declined`, `expired`, `withdrawn`, `cancelled_by_candidate`) or, for accept and decline, a passed deadline answers 409 before the version is compared, so the client gets 409 for a withdrawn, expired, or late invitation even with stale versions and shows the final state instead of rereading and retrying. Then come the versions (412) and the remaining state rules (409). This applies to accept, decline, cancel, withdraw, and the salary raise. - Repeats return the same result: a retry with the same Idempotency-Key replays the stored outcome, and a repeated command whose transition already happened answers 200 with the current invitation even with a new key or an older version: a send of a sent invitation, a withdrawal of a withdrawn one, a decline with the same reason and comment, a cancellation of a cancelled one, the same raise, and an acceptance whose `terms_version` and fields equal those of `contact_grant`, the version and fields the candidate accepted, even when a later raise advanced the current `terms_version`. No second consent, grant, quota charge, or audit event is created. - `UpdateOrganizationInvitation` follows the convention of `UpdateOrganizationNeed`: no Idempotency-Key, explicit field replacement, and a body that changes nothing answers 200. States and the view: - `InvitationState` lists every state of the FR12 table: `draft`, `delivered`, `viewed`, `counter`, `accepted`, `interview_scheduled`, `interviewed`, `negotiation`, `terms_agreed`, `no_deal`, `declined`, `expired`, `withdrawn`, `cancelled_by_candidate`. MVP operations produce `draft`, `delivered`, `viewed`, `accepted`, `declined`, `expired`, `withdrawn`, and `cancelled_by_candidate`; the others are listed now so that generated clients accept them when the counter offer, the interview, and the sealed final arrive. The internal `SENT` step is never visible: a send answers with `delivered` after the inbox entry exists. - `expiry_reason` is `invitation_timeout` or the planned `negotiation_timeout`, non-null exactly in `expired`. - The view is an explicit command, `ViewMyInvitation`: it moves `delivered` to `viewed`, keeps the deadline, and returns the current invitation unchanged in any other state. It is idempotent by its effect, so it needs neither an Idempotency-Key nor an `expected_version`, and it never fails because the invitation changed after the client read it. `GetMyInvitation` and `ListMyInvitations` have no side effect; a read only shows a due expiry, which the server applies at the deadline anyway. The command keeps prefetches, retries, and cache refreshes from changing the state that the organization sees. - `withdrawn` is the organization's command from any unfinished state, including `draft` and `accepted`, and keeps an existing grant. `cancelled_by_candidate` is the candidate's command from any unfinished state after delivery and revokes the grant of this invitation. A decline is the structured answer before an acceptance. - The deadline is `delivered_at + response_period_days` (3, 7, or 14 days, 7 by default). A view, an email, or a raise never moves it; a command received at the deadline or later is late. Salary and the hidden minimum: - The terms reuse `SalaryRange` with the rules of the Needs section: RUB, month, `net` or `gross`, positive multiples of 1000, `A < B`, and a width of 10-40%, checked by the server with the pointer `/terms/salary/salary_to`. - The organization receives only `salary_fit`: `within_range`, `up_to_10_percent_above`, `above`, `withheld`, or `not_available` (no minimum for the offered formats, or one in the other tax basis). The exact minimum appears in no response, example, log, or problem. The server never rejects a range because of the minimum, since a rejection would reveal it. The candidate DTOs carry no indicator; the candidate compares with the own minimum in the profile. - Every change that can move the indicator is an indicator-relevant setting: the range on creation, and in a draft a change of either bound, of the tax basis, or of `work_formats`, because the indicator compares with the minimum for the offered formats. Each counts against the organization-wide limit of three settings a day, shared with the ranges of needs (429 with Retry-After), and against the withheld counter. A change that keeps the range, the basis, and the formats does not count. - `withheld`: after five indicator-relevant settings within seven days the indicator is off for seven days from the fifth. The response to the fifth setting already shows `withheld`, and so does every draft and invitation of the organization, existing ones included, until the period ends. - Switching the tax basis turns `not_available` into a band or back and so tells the organization the basis of the minimum; this is accepted, and the switch counts against the limit like any other setting. - After a send the base is fixed and the lower bound never decreases. `RaiseOrganizationInvitationSalary` raises `salary_to` once in the whole history of the invitation, creates the next terms version, and answers 409 on a second raise. It follows its own once-only rule and does not count against the daily limit, but it counts against the withheld counter because it moves the upper bound that the indicator compares. Consent C4 and the contact grant: - `GetMyInvitation` shows in `contact_consent` the C4 text for this organization and the kinds of contact that the profile holds. It is null when an acceptance is impossible: the state or the deadline does not allow it, or the profile holds no contact. In the last case the client asks the candidate to add a contact first, because a grant must cover at least one field. - `AcceptMyInvitation` sends `terms_version`, `expected_version`, and `consent_c4` (`ContactConsentAcceptance`): the shown C4 text version, `accepted: true`, and `fields`, at least one of `full_name`, `email`, `phone`, `telegram`, with no default and no preselection. A text version that is not published answers 400 `/consent_c4/text_version`, and a field the profile does not hold answers 400 `/consent_c4/fields/`. The consent is analogous to the C1 acceptance by its `text_version`, and the record matches the C4 consent ledger (purpose, text version and hash, organization, field set, source invitation). The permission to pass the data on to the organization's ATS (C4 and FR19) is planned as an additive optional flag that defaults to no transfer. - In one transaction the acceptance moves the invitation to `accepted`, records C4, creates the grant for exactly the selected fields, and writes the audit event. It never publishes the profile (C2) and never lifts a hiding. - The candidate's `contact_grant` has `status` (`active` or `revoked`), `readable`, and `blocked_by`. A grant created while the profile was not published or was hidden from the organization stays `active` with `readable: false` and `blocked_by: visibility`, so the candidate sees why the organization cannot read it (PRD FR12); it becomes readable once the candidate publishes the profile or unhides it. Any visibility change after the grant exists revokes it (`visibility_closed`), and a later publication never reopens it. - Contact values travel only in `ContactDisclosure` from `GetOrganizationInvitationContacts`, separate from the terms and the invitation. Each read checks the membership, C4, the grant and its fields, and the current visibility, without a cache. Without a readable grant the operation answers 404 `not_found`, the same as an unknown invitation. The organization's `contact_access` is `not_granted` (no grant), `available` (with the field kinds), or `closed`, which covers a revoked grant and a grant blocked from the start without saying which. This is the least revealing rule: a revocation, a hiding, and a missing publication look the same, and since every visibility change after the grant revokes it, the organization never observes a later toggle; only a grant blocked from the start can turn `available`, by the candidate's own choice. Fields that the grant does not cover are null. - Revocation: `CancelMyInvitation` revokes the grant of this invitation (`participation_cancelled`); revoking C4 for the organization closes all its grants (`consent_revoked`); revoking C2 or hiding the profile closes them (`visibility_closed`). A withdrawal, a no deal, and a negotiation timeout never revoke a grant; only a new explicit C4 creates a new one. A standalone grant revocation operation belongs to the consent contract. - Implementation: the contact read, the C4 and C2 revocations, the closing of the publication, and hiding are implemented, owner only, and close the grants as the bullet above states (architecture: [Contact reads and revocation](../docs/en/ARCHITECTURE.md#contact-reads-and-revocation)). The organization's `contact_access` is derived on every read of an invitation (`GetOrganizationInvitation`, the list, and the create, update, and send responses) with the checks of the contact read, so it shows `available` only where a read would succeed, and it never names a reason. `CancelMyInvitation` is not implemented yet. - Value formats: a single-line full name of up to 200 characters, an E.164 phone number, and a Telegram username with the leading @. The profile contract (FR02) must store contacts in the same formats, so a disclosure never converts or drops a stored value. Decline and privacy: - `DeclineMyInvitation` takes `reason` (`salary`, `tasks`, `stack`, `work_format`, `package`, `company`, `not_looking`, `other_offer`, `other`) and an optional `comment` of up to 500 characters; `other` needs no comment. The organization sees only `declined` and `responded_at`, never the reason or the comment: a reason such as `salary` would tell it that the hidden minimum is above the range. Reasons feed only aggregates with a minimum group size (planned). The candidate reads both back in `decline`. - No invitation DTO of either side carries the candidate's name, email address, phone number, Telegram username, account or profile identifier, or salary minimum; examples use synthetic data only. `TestInvitationSchemaValidationPrecedesImplementation` checks the schema rejections and pointers through the generated server, `TestInvitationDTOsCarryNoContactOrMinimum` checks the generated Go DTOs, and `frontend/src/shared/api/invitation-contract.test.ts` pins the generated Zod rules and, at the type level, the absence of contact, minimum, and decline fields. Open product questions: whether a second unfinished invitation of the same organization to the same candidate is allowed (the PRD is silent, so the contract invents no rule), the package format deviation above, the offer types, the contact kinds, and the decline reasons. Planned, additive: the counter offer and the company answer, reading earlier terms versions, interview and sealed final operations, list filters, the responsiveness metrics of the organization for the candidate, the approximate amount in the other tax basis, decline aggregates, the ATS flag of C4, and FSP fields as new contact kinds (a new enum value, released with regenerated clients). No new problem code is added: the `ProblemCode` enum is copied byte-for-byte into the ML contract, and `version_conflict` and `state_conflict` cover the stale terms and the state conflicts. ### Consents The `consent` tag covers the consent ledger of the current account (PRD FR01, FR12, and 7.3): the independent consents C1-C5 with their text versions, sources, states, and revocations. Implemented handlers provide public C1 text, current settings text and the caller's own history, settings grants of C1/C2/C3/C5, revocation of C2/C3/C5, scoped C4 revocation for one organization, and a durable C1 account-deletion request. The request does not synchronously delete the account. Protected operations require an active verified PostgreSQL session; mutations also require the session-bound CSRF token and the sole `Origin` matching `APP_PUBLIC_URL`. Guests receive 401; a disallowed account role, Origin, or CSRF token receives 403. | Method and path | operationId | Security | Success | Specific errors | | --- | --- | --- | --- | --- | | `GET /api/v1/identity/consent-texts/c1` | `GetConsentText` | public | 200 `ConsentText` | 400 `validation_failed` | | `GET /api/v1/me/consent-texts/{purpose}` | `GetMyConsentText` | session | 200 `ConsentText`, `Cache-Control: no-store` | 400, 401 | | `GET /api/v1/me/consents` | `ListMyConsents` | session | 200 `ConsentRecordList`, `Cache-Control: no-store` | 400, 401 | | `PUT /api/v1/me/consents/{purpose}` | `GrantMyConsent` | session and CSRF | 200 `ConsentRecord`, `Cache-Control: no-store` | 400, 401, 403 | | `DELETE /api/v1/me/consents/{purpose}` | `RevokeMyConsent` | session and CSRF | 204 | 401, 403 | | `DELETE /api/v1/me/consents/c4/organizations/{org_id}` | `RevokeMyOrganizationContactConsent` | session and CSRF | 204 | 400, 401, 403 | | `POST /api/v1/me/account-deletion-requests` | `RequestMyAccountDeletion` | session and CSRF | 202 `ConsentDeletionRequest`, `Cache-Control: no-store` | 401, 403 | - Purposes (`ConsentPurposeCode`): `c1` personal data processing, `c2` publication of the candidate card, `c3` automatic categorization, `c4` transfer of selected contacts to one organization, `c5` import of FSP results. Public `GetConsentText` remains C1-only. `GetMyConsentText` returns the current C1/C2/C3/C5 text before a settings grant. C4 text remains part of an invitation with its specific scope. - The subject comes from the session; no parameter names an account, so the response holds only the caller's own records. A page lists records newest grant first with cursor pagination; the optional `state` filter takes `active`, `superseded`, or `revoked`, and an unknown value answers 400 with the pointer `/state`. - A `ConsentRecord` has the purpose, the accepted `text_version`, the `source` (`registration`, `consent_settings`, or `invitation_acceptance`), `granted_at`, the computed `state`, and `revoked_at` with `revocation_source` (`consent_settings` or `support_request`). A `c4` record also names the `organization` (`ConsentOrganization`, whose `name` is the snapshot the consent text showed, so a later rename does not change it), the contact `fields` (`ContactFieldKind`), the `invitation_id`, and the `invitation_terms_version`; they are null for every other purpose. A `c2` record proves the consent to the publication text; which fields were published, and when, is evidence of the publication history ([Candidate visibility](#candidate-visibility)), and a field scope on `c2` records would be an additive change. The record never carries a contact value, the subject, or the text hash: the server stores the SHA-256 of exactly the text the subject saw, and the client never sends or receives it, as for C1 at registration. - Settings grants require explicit `accepted: true` and the current version of the text the user read. C1 is available to candidate and employer accounts; C2/C3/C5 are candidate-only. C4 is excluded from the general settings grant and is granted only when accepting a specific invitation. - The ledger is append-only. A newer text version is a new record and the earlier one becomes `superseded` without changes; revocation stamps every unrevoked record of the purpose, including earlier versions. C4 revocation is limited to one organization and takes its fields from stored records, never from request data. Repeated revocation is harmless and creates no duplicate event. - C2 revocation closes the current publication, clears its fields, appends privacy history, and writes a bounded outbox intent in one transaction. A later C2 grant does not reopen the old publication. C3 revocation does not block the manual assessment path. C5 revocation immediately closes the consent gate for future imports and writes a stop/delete intent; no external FSP adapter exists, so actual deletion at FSP is not claimed. - A C1 deletion request revokes C1 and creates or returns an active durable request plus an outbox intent in one transaction. Repeats return the same request; a later C1 grant never cancels it. The future account-deletion processor is not synchronous and is not implemented yet. - The C4 permission to pass data on to an ATS and the C4 of an application (PRD Q9) are planned as an additive flag and an additional `source` value. Open legal item: whether `c2` is a consent to the distribution of personal data under article 10.1 of 152-FZ, which requires its own consent with the categories of data. No new problem code is added: the contract uses `validation_failed`, `unauthenticated`, `forbidden`, and `csrf_check_failed`. Contract tests pin the security schemes and validation order, `TestConsentSettingsOverHTTP` exercises consent behavior with real PostgreSQL and Redis, and `frontend/src/shared/api/consent-contract.test.ts` pins generated Zod rules and the absence of hashes, subjects, and contacts from the DTOs. ### Organizations The `organization` tag includes implemented creation, reading, editing, and the current account's organization directory. A verified employer creates an organization with an active owner; organization-scoped operations require an active owner on each request. Unsafe operations require the session CSRF token and exact Origin. The common middleware also protects unimplemented need and invitation operations before their 501 fallback. See [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#organizations-and-memberships). | Method and path | operationId | Security | Success | Specific errors | | --- | --- | --- | --- | --- | | `GET /api/v1/me/organizations` | `ListMyOrganizations` | session | 200 `MyOrganizationList`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `forbidden` | | `POST /api/v1/organizations` | `CreateOrganization` | session and CSRF, Idempotency-Key | 201 `Organization`, `Cache-Control: no-store` | 400, 401, 403 `csrf_check_failed` or `forbidden`, 409 `idempotency_in_progress`, 422 `idempotency_key_reused`, 429 | | `GET /api/v1/organizations/{org_id}` | `GetOrganization` | session | 200 `Organization`, `Cache-Control: no-store` | 400, 401, 403 `forbidden`, 404 `not_found` | | `PATCH /api/v1/organizations/{org_id}` | `UpdateOrganization` | session and CSRF | 200 `Organization`, `Cache-Control: no-store` | 400, 401, 403 `csrf_check_failed` or `forbidden`, 404, 412 `version_conflict`, 429 | Every operation also declares the `default` problem response. A malformed `org_id` answers 400 with the path pointer. Active organization context: - The context is not stored on the server. Every organization-scoped operation, including the needs and invitations of this contract, names its organization in the path `org_id`, and the server checks that identifier against the active membership of the session account on every request. The identifier grants nothing; a switch between organizations is another `org_id` in the client's routes. - Reason: a session attribute would be a cache of the membership that a removal, a suspension, or a leave would have to invalidate (the next read must be closed without waiting for the browser cache to expire), it would make two tabs in two organizations fight over one value, and the path form is already the contract of needs and invitations. Organization switching clears the tenant-scoped client queries on a switch, which fits a client-side context. - `ListMyOrganizations` is the directory of contexts: the organizations where the caller has an `active` membership, newest membership first, with the caller's role and state. A client picks the context from it, may remember the last choice in the browser as a convenience, and reads the list again after a 404 from an organization path. A person with several memberships sees all of them and works in one at a time; the rights and the data of the organizations stay separate. Access: - An employer account only. A candidate account answers 403 `forbidden` on all four operations, and an account without a session answers 401. - `GetOrganization` and `UpdateOrganization` answer 404 `not_found` for an account without an active membership in `org_id` and for an unknown organization alike, and also for a `suspended`, `removed`, or `left` member, so organizations cannot be enumerated and a revoked member loses the next read at once. A member whose role does not manage the organization answers 403 `forbidden` on `GetOrganization` and `UpdateOrganization`; the FR07 matrix gives managing the company and its staff to the owner only. In the MVP every member is an owner, because the operations that add members are planned. - `CreateOrganization` creates the organization and the owner membership of the caller in one transaction (role `owner`, state `active`), so an organization never exists without an owner; the database refuses to commit one that has none. The body has no owner, role, membership, or verification field. Memberships: - A membership is `(user, organization, role, state)` and is unique per pair in any state. `OrganizationRole` has `owner`, `recruiter`, `hiring_manager`, and `technical_expert` (PRD 2.2 and Q3). `MembershipState` has `active`, `suspended` (access stopped, restorable), `removed` (ended by the owner or the platform), and `left` (ended by the member). Only `active` gives access, and the listing returns only `active` memberships; `joined_at` is the moment the membership was first created (a member who returns keeps it, and the latest activation time is a planned `activated_at` field); a membership `removed` by the platform must not be reactivated by the owner, by an invitation acceptance, or by the member management on their own, and who removed the member and why become additive fields of the member management; the other states are in the enum so that member management can show them without a contract change. Adding a role or a state is a contract change. - The role lives in the membership only. `Organization`, `OrganizationCreate`, `OrganizationUpdate`, and `CandidateOrganizationCard` have no role, owner, or member field. The caller reads their own role in `OrganizationMembership` from `ListMyOrganizations`; the DTO names no account. - There is no `invited` state: an employee joins only through an invitation to an email address (PRD 2.2), which the member-invitation tasks store as a separate record and turn into an `active` membership when the owner of the address accepts it. A person may hold independent memberships in several organizations. - Applying the full role matrix (recruiter, hiring manager, technical expert) to needs, invitations, and contacts is planned as part of role-based access control. Until then the other roles grant nothing: the operations of needs and invitations answer 403 `forbidden` for them, as their sections say. Listing and managing members, changing roles, removing members, and the rule that the last owner cannot be removed are planned as part of membership management and add operations, not fields, to this contract. Profile: - `OrganizationCreate` requires only `name`. The profile fields are `name` (1-200 characters, no surrounding whitespace or line break, because a consent record keeps a copy), `description` (1-2000 characters, nullable, line breaks allowed), `sphere` (1-100 characters, nullable, free text: the PRD has no sphere taxonomy, and a taxonomy code would be an additive field), `contacts`, and `representatives`. - `contacts` is one object with `website`, `email`, `phone`, and `telegram`, all required and nullable, so it is the request field and the stored value alike. They are public company channels: an https website without credentials, a port, or an IP address, a careers mailbox, an E.164 phone number, and a Telegram username with the leading `@`. The contract holds no personal contact of an employee, and the server cannot tell a personal address from a company one, so the owner answers for the content; a complaint about an organization goes through a support case. The server never fetches the website. - `representatives` is a list of up to ten `{name, job_title}` entries in the order the owner gave them. A representative is presentation only: not a member, with no account link, no contact, and no right, and a member does not become one by joining. The name is personal data of an employee that the owner publishes, which makes the open question below. - `UpdateOrganization` uses explicit field replacement, as `UpdateOrganizationNeed` does: a present field replaces that field as a whole, an absent field stays unchanged, and `contacts` and `representatives` are never merged. `description` and `sphere` sent as null become unset; `name`, `contacts`, and `representatives` cannot be null. ogen generates `OptNil` values for the nullable fields and a plain slice for `representatives`, where nil is absent and `[]` is an empty replacement; a handler must test it with `!= nil`, never with `len` (`TestOrganizationUpdateDecodingKeepsAbsentAndEmptyListsApart`). - Text is plain: clients show every field as text, never as HTML. Domain rules that need more than the schema, such as the host rules of the website, answer 400 with a pointer (`/contacts/website`, `/representatives/0/job_title`); the examples show the shapes. Verification level: - `OrganizationVerificationLevel` is `e0`, `e1`, `e2`, or `e3` (PRD FR07). A new organization starts at `e0` on the basis `confirmed_email`, whatever its profile looks like. The server reports a higher level only after a verification process recorded it; the processes for `e1`, `e2`, and `e3` do not exist yet (the planned verification flow adds E0/E1 with evidence, a scope, and a history), so a client treats every level but `e0` as unavailable and the contract never reports `e1`, `e2`, or `e3` as reached on its own. - No request sets or raises a level or its basis: `OrganizationCreate` and `OrganizationUpdate` are closed objects with only the profile fields, no operation of the contract changes the level, and editing the description, the contacts, or the representatives leaves it as it is. The database keeps the level and the basis in their own columns that the profile statement never writes, and a CHECK ties each level to its own bases. `OrganizationVerification` is read-only: `level`, `basis`, and `changed_at`; the scope of the check and the history of changes (PRD FR07) arrive as additive fields with the first process. - The level selects the quota tier (E0 10 invitations and 50 cards, E1 40 and 150, E2 100 and 400 in the demo policy); `domain.OrganizationVerificationLevel.QuotaTier` maps `e0` to `e2` to the tiers of the policy and has none for `e3`, which the PRD gives a separate policy. Quota enforcement is a separate planned feature. Candidate card and versions: - `Organization.candidate_card` is the card as a candidate sees it, built by the server from the profile and the level: the preview of PRD FR07. Only a candidate who received an invitation from the organization sees it; it is not a public page, and no operation shows it to anyone else until the question about the names of representatives below is decided. It repeats the profile fields and adds the level only; it has no membership, role, account, version, or basis. Its `representatives` is optional and nullable: absent or null means that they are not published, not that there are none. The invitation contract names the organization with `InvitationOrganization` and plans to return this card to the candidate additively. - `version` starts at 1 and advances with every committed change of the profile. A change carries `expected_version` in the body for the reason the needs give: the generated client cannot read `ETag` yet. A stale value answers 412 `version_conflict` and changes nothing; the repository rule keeps 412 for a stale version, as for needs. A body that changes nothing answers 200 with the current organization, so PATCH needs no Idempotency-Key. POST needs one with the 24-hour replay; only the 201 is stored. - Order of the checks of `UpdateOrganization`: session (401), CSRF and Origin (403), request validation (400), account scenario (403), membership (404) and role (403), a body that changes nothing (200), the version (412), domain rules (400). Foreign keys to organizations: `memberships` and `organization_representatives` reference `organizations(id)` now. The consent ledger, the needs, and the invitations carry an `organization_id` and reference it with a restricting foreign key in the migration that creates the invitation records, because the C4 scope needs both references at once and the consent ledger tests use synthetic organization identifiers. The application never deletes an organization. Open questions for the product owner: - Representatives: may the card show their names to every candidate before an invitation is accepted, and who answers for the right to publish an employee's name (152-FZ)? The alternative is to show representatives only in an invitation sent by their organization. - Sphere: free text now; a taxonomy for the sphere, matching the domains of needs, is a decision for the search filters. - Contacts: whether the card needs a fifth kind, such as a careers page, and whether the email must share the domain of the website. Decided by the product owner: organizations per account are not limited. The organizations of one account form a holding, and the E0 quotas (in the demo policy 10 invitations per 7 days and 50 distinct card views per 24 hours) are shared by the E0 organizations of that holding; an organization at E1 and above counts its own quotas. The contract does not change: the holding is internal and no operation exposes it. Planned, additive: member invitations, listing, role changes, and removal, the full role matrix, the verification processes and their history, the quotas by level, the card in the candidate's invitation, and a sphere code. No new problem code is added: the contract reuses `validation_failed`, `unauthenticated`, `forbidden`, `csrf_check_failed`, `not_found`, `version_conflict`, `idempotency_in_progress`, `idempotency_key_reused`, and `rate_limited`. `TestOrganizationSchemaValidationPrecedesImplementation`, `TestOrganizationAccessBeforeImplementation`, `TestOrganizationDTOsCarryNoRoleOrVerificationInTheirRequests`, `TestOrganizationUpdateDecodingKeepsAbsentAndEmptyListsApart`, and `TestOrganizationContractFollowsThePRD` pin the generated server and the bundle, and `frontend/src/shared/api/organization-contract.test.ts` pins the generated Zod rules and, at the type level, the absence of role, owner, member, and verification fields in the requests. ### Candidate visibility The tag `privacy` describes what organizations may see of the current candidate: the publication of the anonymous card, the search status, the organizations the candidate hides the profile from, a preview, and two histories (FR02 and FR12 in the PRD). The operations are in the contract but their business logic is not implemented: a guest answers 401 `unauthenticated`, and a request with a verified session reaches 501 `not_implemented` after request validation. Unsafe protected operations also require the session-bound CSRF token and exact Origin. The storage behind them exists (migration 00015, see [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#candidate-visibility)). | Method and path | operationId | Protection | Success | Specific errors | | --- | --- | --- | --- | --- | | `GET /api/v1/me/privacy` | `GetMyPrivacySettings` | session | 200 `PrivacySettings`, `Cache-Control: no-store` | 401, 403 `forbidden` | | `PUT /api/v1/me/privacy/publication` | `SetMyPublication` | session and CSRF | 200 `Publication`, `Cache-Control: no-store` | 400, 401, 403 `csrf_check_failed` or `forbidden`, 409 `state_conflict`, 412 `version_conflict` | | `GET /api/v1/me/privacy/preview` | `GetMyCardPreview` | session | 200 `CardPreview`, `Cache-Control: no-store` | 401, 403 | | `PUT /api/v1/me/privacy/search-status` | `SetMySearchStatus` | session and CSRF | 200 `SearchStatus`, `Cache-Control: no-store` | 400, 401, 403, 412 | | `GET /api/v1/me/privacy/hidden-organizations` | `ListMyHiddenOrganizations` | session | 200 `HiddenOrganizationList`, `Cache-Control: no-store` | 400, 401, 403 | | `PUT /api/v1/me/privacy/hidden-organizations/{org_id}` | `HideOrganization` | session and CSRF | 200 `HiddenOrganization`, `Cache-Control: no-store` | 400, 401, 403, 404 `not_found`, 409 `state_conflict`, 429 | | `DELETE /api/v1/me/privacy/hidden-organizations/{org_id}` | `UnhideOrganization` | session and CSRF | 204 | 400, 401, 403 | | `GET /api/v1/me/privacy/history` | `ListMyPrivacyHistory` | session | 200 `PrivacyEventList`, `Cache-Control: no-store` | 400, 401, 403 | | `GET /api/v1/me/privacy/access-history` | `ListMyCardAccessHistory` | session | 200 `CardAccessList`, `Cache-Control: no-store` | 400, 401, 403 | Each operation also declares the problem response `default`. No new problem code is added: the contract uses `validation_failed`, `unauthenticated`, `forbidden`, `csrf_check_failed`, `not_found`, `state_conflict`, `version_conflict`, and `rate_limited`. An employer account answers 403 `forbidden` on all nine operations. Closed by default and three independent settings: - A profile is closed by default. A candidate who never published reads `publication.state` `closed`, `closed_reason` `never_published`, an empty field set, and version 0; saving the profile, filling in the questionnaire, or taking an assessment never publishes it. Every setting has its own `version` (0 is "never set"), its own operation, and its own `expected_version` in the body, so a change of one never makes another stale. - The publication and C2 are separate. The consent C2 stays in the consent ledger (`ListMyConsents`) and proves that the candidate accepted the publication text. `Publication` records which fields are published and when, and refers to the C2 record behind them (`consent_id`, the `id` of a `ConsentRecord` of the same account). It does not duplicate the consent: `state` is `published` only while that record is unrevoked, so a revocation of C2 closes the card at once, and `closed_reason` says `consent_revoked`. A new C2 grant never reopens it: the candidate publishes again and the new publication binds to the new record. The body of `SetMyPublication` names no consent: the server binds the current unrevoked C2 record of the account, and without one answers 409 `state_conflict` (the candidate gives C2 first; the grant operation is planned in the consent settings). - The search status is not a consent. `SearchStatus` and `SearchStatusUpdate` have no consent, publication, or organization property, no schema of one family reaches another (a test walks the references), and `SetMySearchStatus` changes nothing but the status. A candidate whose profile is closed who sets `looking` becomes visible to no one. - Hidden organizations are records of the candidate (`HiddenOrganization`: the organization with its current name and `hidden_at`). One record per candidate and organization, at most 1000 per candidate. An organization never reads them, never learns that it is hidden, and sees a hidden candidate exactly as it sees one who is not published. Hiding and lifting a hiding change neither C2, nor the publication, nor the search status. - Hiding is a PUT of a state, so it is idempotent and takes no Idempotency-Key: hiding an organization again answers 200 with the original record and writes no history. Lifting is a DELETE that answers 204 whether the organization was hidden or not. The search status and its 30 days: - `looking` ("Ищу") stores `confirmed_at` and `lapses_at`. The interval is not a constant of the contract or the code: it is `search_status.searching_confirmation_interval_days` of the effective `product` policy version (30 in the demo version 1), read when the status is confirmed. The stored row names the policy version it used and fixes `lapses_at`, so a later policy change moves no stored time. The owner changes the interval by publishing a new policy version. - After `lapses_at` the status holds as `not_looking` with `lapsed` true. The lapse is computed on every read and never written, so it needs no job and can only narrow: it never publishes, never unhides, and never changes C2 or the hidden organizations. The candidate confirms again with `SetMySearchStatus` and `looking`, which replaces `confirmed_at` and advances the version. A reminder before the lapse is a planned notification. - A lapsed status is never "more public": the non-public `not_looking` is the only state a lapse reaches. Whether `looking` gates the appearance of a published card in search results is a search contract decision, not decided here. The anonymous card and the preview: - `CardField` is a closed set of groups of card values that the candidate chooses to publish: `categories` (the categories confirmed by assessment results), `stack`, `experience` (total months), `soft_skills`, `location`, and `relocation`. The full name, any contact, and the lowest salary have no value, so no request can publish them; contacts reach an organization only through the contact grant of an accepted invitation (C4), and the lowest salary never does. A self-assessed grade is not a category and is never published. The server stores and answers the set in ascending order of the codes. - `AnonymousCardContent` is the card as an organization reads it: a closed object of the six properties above, each null when it is not published or has no value, so the card does not tell the two apart. It has no name, email, phone, Telegram name, employer, salary figure, or account or profile identifier, and no schema of the private profile, a contact, a consent, an invitation, or an organization is reachable from it (`TestAnonymousCardReachesNoProfileOrContactSchema` walks the references). `GetMyCardPreview` returns it with the published fields, or `card` null while the profile is closed, as a private read that creates no view and no history record. The card of an organization's search result must reuse this content and cannot add a property that identifies the candidate. Versions and checks: - Both `PUT` operations of the settings follow the profile pattern: the complete new state in the body, `expected_version` in the body (the generated client cannot read the ETag yet), 412 `version_conflict` for a stale or non-existent version, and an unchanged body answers 200 with the current state even over a stale version, so no Idempotency-Key is needed. Order of checks: session (401), CSRF and Origin (403), request validation (400), account scenario (403), a version above the current one (412), an unchanged state (200), a stale version (412), then the C2 for a publication (409). A published state without a field and a closed state with a field answer 400 with the pointer `/fields`; the schema rejects an unknown or repeated card field and unknown properties such as a consent identifier or a confirmation time. `looking` always changes the stored confirmation, so it answers 412 for a stale version even as a repeat. The two 409 `state_conflict` answers are told apart by `errors`: `{in: body, pointer: /state, code: consent_required}` for a publication without an active C2, and `{in: path, pointer: /org_id, code: limit_reached}` for the 1001st hidden organization. A closing over a stored publication whose C2 was revoked is a real change (it stores the closing, records `publication_closed`, and revokes the grants); the C2 revocation path closes the stored publication and revokes the grants in its own transaction. Publishing, hiding, and the history need a verified email (a usecase requirement). `Problem.errors` is not only for `validation_failed`: a `state_conflict` carries one entry as a disambiguator (`consent_required`, `limit_reached`), so a future problem writer must not strip `errors` from non-validation responses. Only values that the candidate confirmed reach the card, a free text value that looks like a contact (email, phone, URL, Telegram link, @handle) is dropped, and adding a card field is a contract change and a migration. - 404 and anti-enumeration. `HideOrganization` answers the same 404 `not_found`, with the same body and without a different timing, for an organization that does not exist and for one that the candidate cannot see, so it is not a way to ask whether an identifier belongs to an organization. The candidate can see an organization that has sent them an invitation, and the organizations that a candidate lookup lists (planned). The identifiers are random, and the general rate limit can answer 429 with Retry-After before any check. `UnhideOrganization` reveals nothing: 204 for any well-formed identifier. A malformed `org_id` answers 400 with the pointer `/org_id`. - Contact grants. Closing the publication, and hiding an organization that holds an active contact grant, revoke that grant with the reason `visibility_closed`, in the same transaction as the change (planned together with the operations; the reason is fixed in the invitation contract). Lifting a hiding or publishing again never reopens a grant. The search status never revokes a grant. History: - `ListMyPrivacyHistory` returns the append-only history of the settings, newest first (the history stores only the organization identifier, and the current name is resolved when it is read): `publication_opened`, `publication_changed` (with the published fields and the `consent_id` behind them), `publication_closed`, `search_status_confirmed`, `search_status_cleared`, `organization_hidden`, and `organization_unhidden` (with the organization's current name). This is the evidence of the published field set and its changes with their times that the C2 record does not carry. A revocation of C2 and a lapse are computed and are not events; the consent history shows the revocation. The history holds no profile value. - `ListMyCardAccessHistory` returns the accesses of organizations to the card: `card_viewed` and `contact_read`. A view by an organization that has no invitation relation with the candidate has `organization` null; a contact read always names the organization. The entries carry no query or ranking. Its storage comes with the search and contact-read tasks, so the operation is contract-only. Open questions for the product owner and the lawyer: - The search status values: the contract has `looking` and `not_looking`. Whether the PRD needs a third status such as "open to offers" is not decided; a value is an additive change. - Whether `looking` gates the appearance of a published card in search (an organization sees only candidates who are searching) or is only a label. This decides the meaning of a lapse for visibility and belongs to the search contract. - The set of card fields. The six values are a proposal that matches the profile; the PRD card (FR11) may add, split, or drop some, for example a generalized employer industry and size instead of employers, and each is an additive contract change. - Whether publishing needs a minimum: at least one confirmed category, or a saved profile. The contract only requires one card field and an active C2. - Whether narrowing the published fields, not only closing the publication or hiding an organization, must revoke the contact grants. The invitation contract says any visibility change after a grant revokes it; this contract revokes on closing and hiding only. - How a candidate finds an organization to hide before any invitation. The contract hides by identifier and answers 404 for an organization the candidate cannot see, so hiding the current employer in advance needs an organization lookup for candidates (by name or domain), which must itself be safe against enumeration (a minimum query length, a rate limit, public data only). Without it, hiding works only for organizations that have written to the candidate. - Whether the candidate should learn the name of an organization that viewed the card without an invitation (`CardAccess.organization`), and how long accesses are kept. - The limit of hidden organizations (1000 now) and the retention of the settings and their history together with the consent evidence (152-FZ, PRD 7.3). The history references the account with `ON DELETE CASCADE`, guarded by two triggers: UPDATE is always refused, and DELETE (and the deletion of the account) is refused while the account is verified, the same condition as the consent ledger; the unverified account cleanup removes the history of an account it deletes, and the account deletion procedure extends the condition. - Free text in the card (stack tags, soft skills, location) is guarded only by `CardTextLooksLikeContact`, which errs on the side of dropping (Socket.io is dropped, a bare obfuscation can still slip through); the residual risk still requires a closed taxonomy in the card builder instead of free text. - Whether C2 is a consent to the distribution of personal data under article 10.1 of 152-FZ and needs its own field scope (see Consents); the history keeps the fields and times in the meantime. - Whether a new C2 text version requires the candidate to consent again for an existing publication. Now a publication stays effective while its C2 record is unrevoked, so a newer text version that the candidate has not accepted does not close it. - Quasi-identifiers and k-anonymity of the card: a rare combination of location, stack, and experience can identify a candidate even without a name. The generalization of rare features and a minimum group size are acceptance criteria for the card builder; the contract here only fixes the closed set of fields, the confirmed-values-only rule, and the dropping of free text that looks like a contact. - Retention and the right to erasure for the settings history. The hide and unhide records are sensitive (they say which employer a candidate avoids). The history is kept like the consent evidence and is not deletable while the account is confirmed; whether a candidate can erase it, when, and how this meets the three-year consent retention (PRD 7.3) is an open legal question. The account deletion procedure extends the delete condition of the table. No new problem code is added. `TestPrivacyOperationsFollowTheConventions`, `TestPublicationAndSearchStatusAreNotConsents`, `TestAnonymousCardReachesNoProfileOrContactSchema`, `TestGeneratedPrivacyDTOsCarryNoServerOwnedFields`, `TestPrivacySchemaValidationPrecedesImplementation`, and `TestPrivacyAccessBeforeImplementation` pin the generated server and the bundle, and `frontend/src/shared/api/privacy-contract.test.ts` pins the generated Zod rules, the absence of a consent, a time, a contact, or a salary in the request and card types, and the absence of settings in the organization, invitation, need, profile, and consent files. ### Skill evidence The tag `evidence` describes the facts that confirmed assessments leave about a candidate's skills (FR06 in the PRD). It has two read operations; the logic behind them is implemented (see [architecture](../docs/en/ARCHITECTURE.md#skill-evidence)). | Method and path | operationId | Protection | Success | Specific errors | | --- | --- | --- | --- | --- | | `GET /api/v1/me/evidence` | `ListMyEvidence` | session | 200 `EvidenceFactList`, `Cache-Control: no-store` | 400, 401, 403 `forbidden` | | `GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}/evidence` | `GetOrganizationCandidateEvidence` | session | 200 `OrganizationEvidence`, `Cache-Control: no-store` | 400, 401, 403, 404 `not_found`, 429 | Each operation also declares the problem response `default`. No new problem code is added. - One event is one fact. `EvidenceFact` is a source event; `skills` are the tags of that event (a non-empty set), so a second tag never makes a second fact. `source` names the event and the immutable result (`event_id` and `result_id`, equal for an assessment because a result is keyed by its attempt; the candidate opens it at `GetMyAssessmentResult`). - A claim is not a measurement. `kind` is `claim` (trust 0) or `measurement` (trust 1 to 3). `EvidenceTrustLevel` is an integer from 0 to 3; an online assessment without a reliable confirmation of the identity is trust 1, and repetition never raises it. Only measurements from assessments are produced today. - What a fact says is `result`: the grade that was passed, the `basis` (`synthetic_demo`), and the `calibration_status` (`uncalibrated`), so the candidate never reads a demonstration category as a validated measurement. The organization projection and the preview carry both labels as well. A fact has no score, answer, item, failed attempt, or anti-cheat datum, and a failed attempt, a result without a reviewed category source, and a `demo_express` run produce no fact. - `ListMyEvidence` lists only the caller's facts, newest event first, hidden facts included (`visibility` `hidden`), with the shared `limit` (1 to 100, default 20) and an opaque `cursor` bound to the candidate. A malformed or foreign cursor and a limit out of range answer 400; an employer account answers 403. - `GetOrganizationCandidateEvidence` is a section of the anonymous card. It answers only while `GetOrganizationCandidateCard` would answer for the same handle and the card shows at least one category; every other case (unknown handle, handle of another organization, closed or revoked publication, hidden organization, minimum cohort, card without categories) is the same 404, so the answer reveals nothing the card does not. For each category of the card it returns one `OrganizationEvidenceFact`: the earliest visible assessment that passed exactly the confirmed grade, with only `skill`, `grade`, `trust`, `observed_year` (the year, UTC), and `basis` and `calibration_status` (`synthetic_demo`, `uncalibrated`; the same for every candidate, so they add no fingerprint and say the fact is a demonstration). A lower grade, a retake, the other tags, the source, the basis, the month, and every identifier stay with the candidate; at most nine facts, ordered by skill, and a hidden fact is absent. No key joins the answer to a person, but it is not unlinkable: with the other values of the card, the skill, grade, trust, and year can narrow a small pool, and the minimum cohort does not cover the year. The read consumes the card-view quota and appears in the access history with the field `categories`. - The preview. `CardPreview.evidence` is the same section computed for the candidate (`OrganizationEvidence`, or null exactly when `card` is null), so the candidate sees what an organization would read with the `categories` field. It applies no organization or cohort, so an organization can receive less. - Closed schemas and the privacy walk. Every evidence object has `additionalProperties: false` and requires all its properties. `TestNoOrganizationOperationReachesRawAssessmentData` (Go) and `test_evidence_is_closed_and_no_organization_operation_reaches_raw_assessment_data` (Python) walk every organization operation and `ListMyEvidence` through all references and fail on an assessment, signal, or review schema or on a raw answer, score, or failure property. Open questions: whether the C2 consent text needs a new version now that publishing `categories` also sends one supporting assessment fact (skill, grade, trust level, year) to an organization - a decision for the owner and the lawyer, and the consent texts are not changed here; whether the evidence needs its own card field instead of the `categories` field; whether the year is the right precision for an employer; an operation for the candidate to hide or show a fact (the stored visibility exists, no operation changes it); and when claims of the profile and facts from other sources join the list. ### Match search The tag `organization` has one search operation for the organization-visible candidate bank (PRD FR09). It is implemented as a deterministic search without ML; the model, the groups, and the data it reads are described in [architecture](../docs/en/ARCHITECTURE.md#matching-and-explanations). | Method and path | operationId | Protection | Success | Specific errors | | --- | --- | --- | --- | --- | | `POST /api/v1/organizations/{org_id}/matches` | `SearchOrganizationMatches` | session, CSRF, `Origin`, active owner | 200 `MatchSearchResponse`, `Cache-Control: no-store` | 400, 401, 403, 404 `not_found` | The operation changes nothing and needs no Idempotency-Key; `POST` carries the body. The 200 response also declares no 429. - Access. The organization comes from the path and the active owner membership of the session account. A missing session answers 401, a candidate account, a member who is not the owner, a missing CSRF token, and a foreign `Origin` answer 403, and an unknown organization, an organization without an active membership, a need of another organization, an unknown need, or a `requirements_version` that no change of the confirmed requirements created answer 404. Hidden profiles, a revoked or missing C2 publication, the organization's own hiding, and the minimum cohort of the card are applied before any entry exists: a handle in the result is a handle that `GetOrganizationCandidateCard` opens at that moment. - Basis. `MatchSearchByNeed` searches the immutable `requirements_version` snapshot (not the general `version`), and its optional `filters` narrow it; `MatchSearchByBank` searches all organization-visible entries with explicit filters. The response `source` repeats the basis: the need reference, or the bank filters with every key present and null for a filter that was not sent (the stack is sorted). - Entries. Every entry is one candidate specialization under the organization-scoped `candidate_handle`. `main` and `near` hold confirmed categories (`near` when a required skill of the request earns less than 0.25), `unconfirmed` holds the declared specializations, sorted by Fit, then Coverage, then an internal identifier that is never returned. An unconfirmed entry has `category: null`, `strength: null`, and only `fit` and `coverage`. The groups are not one scale, and one handle can be confirmed in one specialization and unconfirmed in another. - Category basis. Each confirmed category of an entry carries `basis` (`synthetic_demo` for a demonstration category). The organization sees a demonstration as such, not as a standard confirmation; the field is required in `MatchCategory`. - Neutral and unknown values. The semantics component is 0.5 for every entry with `ml_unavailable`; `percentile` is null with `cohort_below_30` and T is 0.5 (no comparable real cohort exists, and demonstration results never form one); domain, freshness, and responsiveness are 0.5 with their flags; competition is 0 and is neither a penalty nor an unknown; a card value that is not published is `null` in `public_context` with `not_in_public_card`. - A search is charged like card reads, because an entry carries card content. The whole visible bank is ranked, and each group returns at most `max_results_per_group` entries of the policy version (demo 10, so at most 30 reveals for one search, below the 50 views per day of tier E0); no total is returned. In the order `main`, `near`, `unconfirmed`, each newly revealed candidate counts as one distinct card view of the organization (the same reservation as `GetOrganizationCandidateCard`, so a candidate already viewed inside the window costs nothing again, and repeating the search or opening the card afterwards does not charge twice) and gets one `card_viewed` entry in the access history per search with the fields actually returned. When the allowance ends, the entries already paid for are returned with `truncated: true`, nothing is written for the rest, and no error and no new problem code is returned. `truncated` is also true when a group exceeded its limit and never carries a count. The response `truncated` is required. - No contact, candidate location, salary amount or minimum, raw answer, failed attempt, or reason for withheld data is in any entry; the explanation uses the bounded `MatchEvidenceCode` and `MatchEvidenceState` values only. A deployment whose effective policy has no `matching` section answers an internal error and never ranks with defaults. Accepted residual risks: `truncated` is one bit about the size of the visible bank, and the response time grows with it; both are bounded by the group limit and carry no count. When the real comparable cohort of a category reaches the policy minimum, the percentile is still null with the reason `percentile_not_computed` and the search does not fail. A change of the visible cohort during a search repeats it up to three times; two simultaneous searches of one organization are serialized by its quota lock. Open questions: the demo value 10 of `max_results_per_group` and whether the output needs paging beyond it; whether a search should charge a candidate for a summary entry at the price of a full card view; whether the grade of a need should be an implicit filter or only an explanation; whether the PRD values should keep an online Backend result (trust 0.6 times the broad relation 0.4 gives 0.24) below the near threshold 0.25 while a stated tag (0.25) reaches it, so that a candidate whose only evidence for a required technology is an assessment of the specialization is always in `near` for it; whether the `stack` filter should require every tag (as implemented) or any; and whether the demonstration relation between specializations and technologies (Backend over Go, PostgreSQL, Kafka, and Docker; DevOps over Docker) is the taxonomy the owner wants. ### Notifications The tag `notification` describes the in-platform inbox of the current account, in the candidate cabinet and in the cabinet of one organization. It has four operations; the logic behind them is implemented, and no product module produces a real notification yet (see [architecture](../docs/en/ARCHITECTURE.md#internal-notifications)). | Method and path | operationId | Protection | Success | Specific errors | | --- | --- | --- | --- | --- | | `GET /api/v1/me/notifications` | `ListMyNotifications` | session | 200 `NotificationList`, `Cache-Control: no-store` | 400, 401, 403 `forbidden` (an employer account) | | `POST /api/v1/me/notifications/{notification_id}/read` | `MarkMyNotificationRead` | session and CSRF | 200 `NotificationReadReceipt`, `Cache-Control: no-store` | 400, 401, 403, 404 `not_found`, 429 | | `GET /api/v1/organizations/{org_id}/notifications` | `ListOrganizationNotifications` | session | 200 `NotificationList`, `Cache-Control: no-store` | 400, 401, 403 `forbidden` (a candidate account) or `email_not_verified`, 404 `not_found` | | `POST /api/v1/organizations/{org_id}/notifications/{notification_id}/read` | `MarkOrganizationNotificationRead` | session and CSRF | 200 `NotificationReadReceipt`, `Cache-Control: no-store` | 400, 401, 403, 404 `not_found`, 429 | Each operation also declares the problem response `default`. No new problem code is added. - The inbox is the delivery state inside the platform. An item exists once the event reached the platform, whether or not an email was sent, and a failed or missing email never blocks it. A repeated delivery of the same event is the same item (`id` is the event identifier). - The inbox stores references, not text. `content` is resolved from the current source for the recipient on every read and is `null` when the source is gone or the recipient may not see it now (for example the candidate hid the organization); the item stays in the list, can be marked, and a client shows a generic line, never an earlier copy. `content.link_path` is a same-origin absolute path (`^/[A-Za-z0-9/_-]{0,255}$`) or `null`. - The recipient is the session account. The organization route also needs an active membership of any role in `org_id` and lists only the caller's items of that organization. A candidate on the organization route and an employer on the candidate route get 403 `forbidden`, and an employer with an unconfirmed email gets 403 `email_not_verified` on the organization route. A missing membership, an unknown organization, an item of another account or of another organization, and an unknown identifier get the same 404 `not_found`, so identifiers cannot be enumerated. - Pagination follows the shared `limit` (1-100, default 20) and `cursor`, newest delivery first with the identifier as the tie-breaker. The cursor is bound to the account and the cabinet; a cursor of another account or cabinet gets 400. - A mark is idempotent by its effect and needs no Idempotency-Key: the first read time is stored and every repeat returns it. It reads no source and returns no content. `kind` is `invitation_delivered` (no module produces it yet) or `synthetic` (a notice with no product meaning that exercises the path). - Closed schemas and checks. Every notification object has `additionalProperties: false` and all properties required. `TestNotificationOperationsFollowTheConventions` and `TestNotificationSchemasAreClosedAndKeepTextInTheContent` (Go) check the tag, the security of reads and marks, the statuses, no-store, the parameters, and that an item carries no text, name, or contact outside `content`. ### Generator checks `testdata/openapi-3.2.0.yml` contains test operations that use the components above: pagination, Idempotency-Key, If-Match, ETag, and problem responses. ogen does not resolve external references, so the fixture keeps copies of the api/core components; `scripts/test_contract_copies.py` (part of `make -C api check`) checks that they, the fixture responses, and the ML `Problem` copy match api/core. `make -C api check-toolchain` lints the fixture and runs the three generators on it; it needs the backend Go toolchain, pnpm, and uv, so pass the same `UV` override as for `make generate`. | Target | Generator | Exercised conventions | | --- | --- | --- | | `make -C backend check-ogen-compat` | ogen | All of them: Problem, PageInfo, Timestamp, PageLimit, PageCursor, IdempotencyKey, IfMatch, ETag. Its tests check validation errors, the retry scenario, the preconditions, and the 413 body limit against the backend problem mapping | | `make -C frontend check-orval-compat` | Orval | Problem, PageInfo, Timestamp, PageLimit, PageCursor, IdempotencyKey, IfMatch. The output is type-checked with the frontend compiler settings | | `make -C ml check-pydantic-compat` | datamodel-code-generator | Problem, PageInfo, Timestamp, PageLimit, PageCursor. The models pass `mypy --strict` and a validation script | Each target writes its output to a temporary directory and removes it. Known generator limitations: - Orval 8.40 writes no Zod schema for `components/responses` but imports a `Response` type for each reference. `frontend/codegen/orval.config.ts` therefore inlines response references before generation. - Orval passes header parameters as a typed argument only with `headers: true`. With `exactOptionalPropertyTypes`, an optional header such as `If-Match` fits `RequestInit` only when Zod emits exact optional properties, so the configuration also sets `override.zod.exactOptional`. - Orval generates no type for response headers, and `apiRequest` returns only the body, so a generated client cannot read `ETag` yet. The first operation with a versioned resource must expose it, for example through the response body or the mutator. - datamodel-code-generator 0.83.0 generates models only for schemas and query and path parameters; header parameters and response headers (Idempotency-Key, If-Match, ETag) produce no Python model. - Orval does not generate `additionalOperations` methods. - ogen writes the header name in its canonical Go form (`Etag`); HTTP header names are case-insensitive. - ogen requires a `SecurityHandler` as soon as the contract has security schemes and evaluates the schemes in the order of their generated type names, so renaming a scheme can change the order; `TestGeneratedServerSecurityOrder` fails if it does. Security failures reach `NewError` without a response header, so clearing the cookie on a 401 from `Logout` needs handwritten code. - Orval does not expose security scheme values as typed arguments, so `X-CSRF-Token` is not a generated parameter; the shared API client is planned to attach it to mutating requests. Orval also generates no type for `Set-Cookie`, which the browser handles. - Orval Zod schemas ignore `uniqueItems` and do not reject unknown fields of `additionalProperties: false` objects; the server stays authoritative for both. - ogen generates an optional nullable field as `OptNil`, which tells absent (`IsSet` false), null (`IsNull`), and a value apart. An optional array that is not nullable is a plain slice instead, where nil and `[]` mean different things: an absent field decodes to nil (unchanged) and `[]` to an empty non-nil slice (delete every item), and null fails decoding. An `UpdateOrganizationNeed` handler must therefore test lists with `!= nil`, never with `len`; `TestNeedUpdateDecodingKeepsAbsentAndEmptyListsApart` pins this. - Orval clears `src/shared/api/endpoints/` and `src/shared/api/schemas/` before generation (`clean: true`), because a schema used by several tags moves from a tag directory to the schema root. - The post-Orval step `frontend/codegen/mock-patterns.ts` finds the length bounds of a patterned string by its property name and pattern, so two properties with the same name and pattern must have the same bounds. The invitation terms therefore name the technologies `tech_stack` (`SkillName`, up to 100 characters) next to the questionnaire `stack` (`StackTag`, up to 50), and a package condition carries `description` rather than `value`, which the need decisions use with other bounds. #### Format unions - Format unions such as `ItemContent` and `AssessmentAnswer` are `oneOf` without a `discriminator` object. Redocly resolves `discriminator.mapping` values as references, and `scripts/merge-schemas.py` rewrites only `$ref`, so a mapping in a split schema file cannot resolve in the merged `components/schemas.yml`. Every variant fixes `format` with a one-value enum; ogen discriminates by that value and by the fields unique to a variant and rejects a body that matches several variants, and Orval generates a Zod union. - Orval names the constants of an inline property ``, so a property name that repeats another schema name collides in `index.ts` (TS2308). The union of item formats is therefore `ItemContent`, not `AssessmentItemContent`, next to the `AssessmentItem.content` property, and the parts of `Need` are `NeedRequirementSet`, `NeedReadinessReport`, and `NeedCategoryRecommendations`, not `NeedRequirements`, `NeedReadiness`, and `NeedRecommendations`. The response target of a case is `SupportResponseTarget`, not `SupportCaseResponseTarget`, next to the `SupportCase.response_target` property. Generated Zod is not strict. A body that mixes the fields of two formats or carries an extra `score` or `seed` is accepted after unknown keys are silently stripped, and `uniqueItems` is not checked; only the server rejects such bodies. `frontend/src/shared/api/assessment-contract.test.ts` pins the accepted formats and that no answer or item DTO has a score, key, seed, or correctness field. See the [development guide](../docs/en/DEVELOPMENT.md).