From 8e7ce8d71c413fad2412f12e26a04c0463d9aa90 Mon Sep 17 00:00:00 2001 From: TakuyaYagam1 Date: Wed, 7 Oct 2026 01:38:49 +0300 Subject: [PATCH] chore: remove backlog references from code and documentation --- .agents/workflows/development.md | 2 + api/README.en.md | 114 +++++++-------- api/README.md | 114 +++++++-------- api/core/components/schemas.yml | 34 ++--- .../components/schemas/common_schemas.yml | 2 +- .../components/schemas/consent_schemas.yml | 4 +- .../schemas/contact_grant_schemas.yml | 6 +- .../components/schemas/invitation_schemas.yml | 2 +- api/core/components/schemas/need_schemas.yml | 4 +- .../schemas/organization_schemas.yml | 4 +- .../components/schemas/privacy_schemas.yml | 4 +- .../components/schemas/support_schemas.yml | 8 +- api/core/openapi.bundle.yml | 70 +++++----- .../routes/candidate_invitation_accept.yml | 6 +- .../routes/candidate_invitation_cancel.yml | 2 +- api/core/routes/candidate_invitation_view.yml | 2 +- .../candidate_privacy_access_history.yml | 2 +- .../routes/candidate_privacy_publication.yml | 2 +- api/core/routes/consents.yml | 4 +- api/core/routes/organization_invitation.yml | 2 +- .../organization_invitation_contacts.yml | 4 +- .../routes/organization_invitation_send.yml | 4 +- api/core/routes/organization_invitations.yml | 2 +- api/core/routes/organization_need.yml | 2 +- api/core/routes/organization_needs.yml | 2 +- api/core/routes/support_case.yml | 2 +- api/core/routes/support_cases.yml | 2 +- .../migrations/00012_add_delivery_sending.sql | 6 +- .../00013_create_candidate_profiles.sql | 2 +- .../00015_create_candidate_privacy.sql | 2 +- backend/db/queries/candidate.sql | 2 +- backend/db/queries/privacy.sql | 4 +- backend/integration_test/mail_sender_test.go | 2 +- .../primary/http/api/oas_handlers_gen.go | 111 ++++++++------- .../primary/http/api/oas_schemas_gen.go | 59 ++++---- .../primary/http/api/oas_server_gen.go | 111 ++++++++------- .../primary/http/api/oas_unimplemented_gen.go | 111 ++++++++------- .../http/candidate_privacy_contract_test.go | 2 +- .../adapter/primary/http/router_test.go | 2 +- .../adapter/primary/http/v1/security.go | 2 +- .../secondary/postgres/delivery_statistics.go | 2 +- .../secondary/postgres/sqlc/candidate.sql.go | 2 +- .../secondary/postgres/sqlc/privacy.sql.go | 4 +- .../secondary/postgres/sqlc/querier.go | 6 +- backend/internal/domain/mail_content.go | 2 +- backend/internal/domain/organization.go | 2 +- backend/internal/domain/policy.go | 4 +- backend/internal/domain/visibility.go | 15 +- backend/internal/port/outbound/consents.go | 2 +- .../port/outbound/delivery_statistics.go | 2 +- backend/internal/port/outbound/identity.go | 2 +- backend/internal/port/outbound/password.go | 2 +- backend/internal/usecase/consent/service.go | 6 +- backend/internal/usecase/files/namespace.go | 4 +- backend/internal/usecase/files/store.go | 2 +- .../internal/usecase/identity/credentials.go | 2 +- backend/internal/usecase/identity/register.go | 2 +- .../usecase/notification/mail_request.go | 2 +- .../internal/usecase/notification/quota.go | 4 +- .../usecase/notification/send_retry.go | 2 +- docs/en/ARCHITECTURE.md | 132 +++++++++--------- docs/en/DEPLOY.md | 12 +- docs/en/DEVELOPMENT.md | 4 +- docs/en/TESTING.md | 4 +- docs/ru/ARCHITECTURE.md | 132 +++++++++--------- docs/ru/DEPLOY.md | 12 +- docs/ru/DEVELOPMENT.md | 4 +- docs/ru/TESTING.md | 4 +- .../src/entities/need/model/need-form.test.ts | 2 +- .../src/shared/api/consent-contract.test.ts | 2 +- .../shared/api/endpoints/consent/consent.ts | 4 +- .../api/endpoints/invitation/invitation.ts | 22 +-- .../src/shared/api/endpoints/need/need.ts | 4 +- .../shared/api/endpoints/privacy/privacy.ts | 4 +- .../shared/api/endpoints/support/support.ts | 4 +- .../shared/api/organization-contract.test.ts | 2 +- .../src/shared/api/privacy-contract.test.ts | 15 +- .../src/shared/api/profile-contract.test.ts | 2 +- .../schemas/consent/consentPurposeCode.zod.ts | 2 +- .../api/schemas/consent/consentRecord.zod.ts | 6 +- .../schemas/consent/consentRecordList.zod.ts | 6 +- .../api/schemas/consent/consentSource.zod.ts | 2 +- .../api/schemas/contactFieldKind.zod.ts | 2 +- .../invitation/acceptMyInvitationBody.zod.ts | 2 +- .../schemas/invitation/candidateHandle.zod.ts | 2 +- .../invitation/candidateInvitation.zod.ts | 6 +- .../contactConsentAcceptance.zod.ts | 2 +- .../invitation/contactConsentOffer.zod.ts | 4 +- .../invitation/contactConsentText.zod.ts | 2 +- .../invitation/contactDisclosure.zod.ts | 4 +- .../schemas/invitation/contactGrant.zod.ts | 2 +- .../createOrganizationInvitationBody.zod.ts | 2 +- .../invitation/invitationAcceptance.zod.ts | 2 +- .../invitation/invitationContactAccess.zod.ts | 2 +- .../invitation/invitationSalaryFit.zod.ts | 2 +- .../invitation/organizationInvitation.zod.ts | 6 +- .../organizationInvitationCreate.zod.ts | 2 +- .../organizationInvitationList.zod.ts | 4 +- .../organizationInvitationSummary.zod.ts | 4 +- .../need/createOrganizationNeedBody.zod.ts | 2 +- .../src/shared/api/schemas/need/need.zod.ts | 4 +- .../need/needCategoryRecommendation.zod.ts | 2 +- .../need/needCategoryRecommendations.zod.ts | 2 +- .../shared/api/schemas/need/needCreate.zod.ts | 2 +- .../api/schemas/need/needMoneyFit.zod.ts | 2 +- .../api/schemas/need/needMoneyStatus.zod.ts | 2 +- .../api/schemas/need/needSourceText.zod.ts | 2 +- .../shared/api/schemas/need/needUpdate.zod.ts | 2 +- .../need/updateOrganizationNeedBody.zod.ts | 2 +- .../organization/membershipState.zod.ts | 2 +- .../organization/myOrganization.zod.ts | 4 +- .../organization/myOrganizationList.zod.ts | 4 +- .../organizationMembership.zod.ts | 4 +- .../privacy/anonymousCardContent.zod.ts | 2 +- .../api/schemas/privacy/cardPreview.zod.ts | 2 +- .../support/createMySupportCaseBody.zod.ts | 2 +- .../api/schemas/support/supportCase.zod.ts | 6 +- .../support/supportCaseActorKind.zod.ts | 2 +- .../schemas/support/supportCaseCreate.zod.ts | 2 +- .../support/supportCaseCreateSupport.zod.ts | 2 +- .../schemas/support/supportCaseEvent.zod.ts | 4 +- .../support/supportCaseEventKind.zod.ts | 2 +- .../schemas/support/supportCaseList.zod.ts | 2 +- .../support/supportCaseObjectReference.zod.ts | 2 +- .../support/supportCaseObjectType.zod.ts | 2 +- .../schemas/support/supportCaseSummary.zod.ts | 2 +- .../grafana/dashboards/lincodex-product.json | 2 +- observability/prometheus/rules/lincodex.yml | 4 +- .../scripts/verify-product-metrics.sh | 4 +- 129 files changed, 699 insertions(+), 701 deletions(-) diff --git a/.agents/workflows/development.md b/.agents/workflows/development.md index 0735593..7d4a7c0 100644 --- a/.agents/workflows/development.md +++ b/.agents/workflows/development.md @@ -8,4 +8,6 @@ Preserve concurrent edits. If ownership is unclear or a collision appears, stop Use Make targets instead of maintaining duplicate shell command lists. Generate derived output from its source. Validate the affected boundary, then hand off the exact files changed and evidence collected. +Keep planning identifiers and progress reports inside the local PRD directory. Describe behavior and rationale in code comments, documentation, and commit messages without referring to numbered backlog items. Never stage or commit PRD. Use the configured human Git identity and do not add assistant authorship or coauthor trailers. + Keep ignore rules in the component that owns the artifacts. Each service has its own .gitignore; the root .gitignore covers only files at the repository root. Do not collect service caches and build outputs in one root ignore file. diff --git a/api/README.en.md b/api/README.en.md index 59a1508..0fb9f1c 100644 --- a/api/README.en.md +++ b/api/README.en.md @@ -102,7 +102,7 @@ The ML service answers its errors with the same `Problem` schema. Its `ProblemCo ### 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` and `ResendEmailVerification` are implemented (TASK-053); the other public operations still answer 501 `not_implemented` after request validation, and the backend's `v1.DenyAllSecurity` rejects every session, so operations that require one answer 401 `unauthenticated`. Values marked as planned come from configuration in TASK-054 to TASK-056. +The `identity` tag covers registration, email verification, login, logout, and the current account. All operations are in the contract. `RegisterAccount` and `ResendEmailVerification` are implemented; the other public operations still answer 501 `not_implemented` after request validation, and the backend's `v1.DenyAllSecurity` rejects every session, so operations that require one answer 401 `unauthenticated`. Values marked as planned come from the planned email confirmation, login, and session configuration. | Method and path | operationId | Security | Success | Specific errors | | --- | --- | --- | --- | --- | @@ -121,8 +121,8 @@ Registration and verification: - Accounts are not enumerated. Registration and resend answer the same neutral 202 for a new, unverified, verified, or unknown email, and login answers 401 `invalid_credentials` for both an unknown email and a wrong password. - 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, the scenario, or the onboarding step of the account row. Every registration, the first and each repeat, stores its own pending credentials (password hash and scenario) on its own verification token, replaces the C1 record, advances the registration version, and invalidates every earlier verification token. Confirming a token (`ConfirmEmail`, TASK-054) must apply the pending credentials of that token only, and must require the password of that registration to confirm a token that carries pending credentials; the current `EmailVerificationRequest` has no password field, so TASK-054 changes the contract. This stops a pre-registration with someone else's password from being adopted by the address owner who clicks the attacker's link, and the reverse. The account row of an unverified account cannot be used to sign in: login (TASK-055) refuses every unverified account and never compares a password with the row or the pending credentials of an unverified account. For a verified email nothing changes; the server sends nothing. -- Implementation of registration and resend (TASK-053). Verified address: nothing changes and nothing is sent (the "you already have an account" notice is not implemented). 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; per client: `IDENTITY_CLIENT_HOURLY_LIMIT` (default 30 per hour). A refused request answers 429 `rate_limited` with `Retry-After` in whole seconds and issues no token. 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, and the limiter keys. 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-and-verification-resend). +- Registering an unverified email again never changes the password hash, the scenario, or the onboarding step of the account row. Every registration, the first and each repeat, stores its own pending credentials (password hash and scenario) on its own verification token, replaces the C1 record, advances the registration version, and invalidates every earlier verification token. Confirming a token (`ConfirmEmail`) must apply the pending credentials of that token only, and must require the password of that registration to confirm a token that carries pending credentials; the current `EmailVerificationRequest` has no password field, so email confirmation requires a contract change. This stops a pre-registration with someone else's password from being adopted by the address owner who clicks the attacker's link, and the reverse. The account row of an unverified account cannot be used to sign in: login refuses every unverified account and never compares a password with the row or the pending credentials of an unverified account. For a verified email nothing changes; the server sends nothing. +- Implementation of registration and resend. Verified address: nothing changes and nothing is sent (the "you already have an account" notice is not implemented). 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; per client: `IDENTITY_CLIENT_HOURLY_LIMIT` (default 30 per hour). A refused request answers 429 `rate_limited` with `Retry-After` in whole seconds and issues no token. 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, and the limiter keys. 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-and-verification-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. - The verification link is `/verify-email#token=`. The page removes the fragment with `history.replaceState` and posts the token only after an explicit user action, so the token stays out of server logs and Referer headers and a link scanner does not consume it. Verification does not start a session. @@ -139,11 +139,11 @@ Sessions and CSRF: - The `sessionCookie` scheme is the cookie `__Host-lincodex_session` with `Path=/; Secure; HttpOnly; SameSite=Strict` and no Domain. The server keeps sessions in PostgreSQL and takes the caller only from the session. Only a verified account gets a session. Login revokes the session the request carried and issues a new identifier and CSRF token; logout revokes the session server-side. Planned timeouts: 24 hours idle and 7 days absolute; activity extends only the idle deadline. Both come from the versioned product policy, not from configuration. - The `sessionCsrf` scheme is the `X-CSRF-Token` header with the session-bound token from `Session.csrf_token`. 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 request, including the public ones, must carry an `Origin` from the configured allowlist, otherwise 403 `csrf_check_failed` (planned, TASK-056; see the [development guide](../docs/en/DEVELOPMENT.md#sessions-on-local-http)). Public identity operations are rate-limited (429 with `Retry-After`). +- Every unsafe request, including the public ones, must carry an `Origin` from the configured allowlist, otherwise 403 `csrf_check_failed` (planned; see the [development guide](../docs/en/DEVELOPMENT.md#sessions-on-local-http)). 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 the mapping planned for TASK-056, are documented on `v1.DenyAllSecurity` and pinned by `TestGeneratedServerSecurityOrder`: +How the generated server (ogen v1.24.0) evaluates the schemes, and the mapping planned for session authentication, are documented on `v1.DenyAllSecurity` and 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. @@ -179,7 +179,7 @@ Questionnaire: ### Candidate profile -The `candidate` tag also describes the private candidate profile that the candidate fills in by hand (FR02 in the PRD, TASK-066). The operations are in the contract and the business logic is not implemented yet, so each answers 401 `unauthenticated` while there are no sessions (`v1.DenyAllSecurity`), and 501 `not_implemented` once a session is accepted and the schema is valid. +The `candidate` tag also describes the private candidate profile that the candidate fills in by hand (FR02 in the PRD). The operations are in the contract and the business logic is not implemented yet, so each answers 401 `unauthenticated` while there are no sessions (`v1.DenyAllSecurity`), and 501 `not_implemented` once a session is accepted and the schema is valid. | Method and path | operationId | Protection | Success | Specific errors | | --- | --- | --- | --- | --- | @@ -215,11 +215,11 @@ 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 (TASK-150): +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, TASK-066): `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). +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: @@ -230,7 +230,7 @@ Open questions for the product owner and legal: - The minimum for the onboarding step `candidate_profile`: the contract requires no field; which fields complete the step is the product owner's decision. - 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 (TASK-185), not this one. +- 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. @@ -278,7 +278,7 @@ Attempt lifecycle, with the commands each state accepts: - 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. A read or command on the active attempt after `idle_timeout_seconds` without one starts the next session; one beyond `max` starts none, and the attempt becomes `expired`. Reading a terminal attempt or a result never starts a session. - At the limits: a practice already `pending` is graded first. Then `ready_to_finalize` is finalized by the server and becomes `completed`, an unsubmitted additional practice is declined (`completed`, `not_confirmed`), and `in_progress` and `practice_pending` become `expired`. A finalize after that answers 200 with the `completed` attempt; any other command answers 409 `state_conflict`. - Insufficient bank is a distinct state in two places. Before the start, `GetMyAssessmentAvailability` shows `insufficient_bank` for a grade without a published bank or without enough families that this candidate has not seen, and `CreateMyAssessmentAttempt` answers 409 `state_conflict` without creating anything. During an attempt, the terminal state `insufficient_bank` ends it without a confirmed grade instead of repeating families. -- No new problem code is added, so TASK-157 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. +- 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. - Counting against the retry rules (3 attempts per 180 days, the 30-day same-grade interval): an attempt that ends `not_determined` with the reason `expired` or `practice_incomplete` is the candidate's attempt and counts. `insufficient_bank` and `sandbox_unavailable` are platform faults: they never count and start no interval. After a failure, including the first test, a lower grade can be tested at once. @@ -296,7 +296,7 @@ Commands, retries, and versions: - 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 deviates from the wording of the TASK-155 test step and of TASK-152, which say 409. It keeps the repository rule above and the questionnaire precedent: `version_conflict` is 412 for If-Match and for a body `expected_version` alike, because the client action is the same, 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 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 therefore lead to different client actions. +- A stale `expected_version` answers 412 `version_conflict`, not 409. It keeps the repository rule above and the questionnaire precedent: `version_conflict` is 412 for If-Match and for a body `expected_version` alike, because the client action is the same, 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 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 therefore 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), the attempt (404, after any due transition), the repeat of a stored answer or of finalize on a completed attempt (200), the version (412), the state (409 `state_conflict`), then domain rules (400 with pointers such as `/answer/option_ids/0`). Following the Idempotency-Key convention, 404 and 409 `state_conflict` are stored under the key and replayed, while 400, including domain rules, 412, 429, and 5xx are not. Create and answers are rate-limited (429 with `Retry-After`), which also limits sandbox load. `TestAssessmentSchemaValidationPrecedesImplementation` checks the schema rejections through the generated server. @@ -324,7 +324,7 @@ Every operation also declares the `default` problem response. A malformed `org_i 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 (TASK-077) owns organizations and memberships and reuses the same path parameter, `parameters.yml#/OrganizationId`. +- `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. @@ -335,7 +335,7 @@ Fields and provenance: - `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 TASK-182 and will be added without a breaking change. +- 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: @@ -350,8 +350,8 @@ Requests, confirmation, and changes: 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, TASK-193), 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; TASK-179 says 409, but 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. +- `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: @@ -363,18 +363,18 @@ 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, planned in TASK-211): 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 risk signals of TASK-319. +- 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 TASK-183 fixture (Overlap 1, Money 0.5, 15 active candidates) gives `score` 0.75. -- Deviation from the PRD formula and from TASK-183 and TASK-457: 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 breakdown that TASK-457 shows consists of the published components. +- `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 (TASK-182), the market range hint (P25-P75) of FR08, the check plan "vacancy -> tasks", a need status for archiving, list filters, and need assignments. +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 @@ -391,8 +391,8 @@ 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. TASK-314 says "forbidden" for a foreign case URL; the contract answers 404 instead, 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 of TASK-316 are separate staff operations with their own DTOs; they add nothing to these operations. +- 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: @@ -406,10 +406,10 @@ Types and object references: - 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 (TASK-077) 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}`. +- 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; how a manual assessment relates to the C3 consent is decided by TASK-064 and TASK-315. +- 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; how a manual assessment relates to the C3 consent is defined by consent revocation and manual assessment. Content and fields the client never sets: @@ -436,11 +436,11 @@ Commands and limits: - 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 TASK-315: 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 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. -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 (TASK-322), staff queues and decisions (TASK-316, TASK-317, TASK-323), and the pause rules of the response target. +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 findings of TASK-272. `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 (TASK-317) is another `decision` event, and experts and moderators are `support`. +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 @@ -467,9 +467,9 @@ Every success has `Cache-Control: no-store`, and every operation also declares t 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 (TASK-463). +- 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, TASK-185), 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`. +- 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`): @@ -481,7 +481,7 @@ Terms (`InvitationTerms`): 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. TASK-197, TASK-201, and TASK-204 say 409 for stale terms; the repository rule keeps 412 for any stale version, as for needs and the questionnaire. +- 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. @@ -490,7 +490,7 @@ 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. TASK-200 describes the view as a GET; the command keeps prefetches, retries, and cache refreshes from changing the state that the organization sees. +- 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. @@ -498,7 +498,7 @@ 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, TASK-211), and against the withheld counter. A change that keeps the range, the basis, and the formats does not count. +- 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. @@ -506,12 +506,12 @@ Salary and the hidden minimum: 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 ledger of TASK-062 (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 (TASK-201). It never publishes the profile (C2) and never lifts a hiding. +- `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`, TASK-064); 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 (TASK-064, TASK-202). -- 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, TASK-066) must store contacts in the same formats, so a disclosure never converts or drops a stored value. +- 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. +- 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: @@ -526,7 +526,7 @@ No new problem code is added: the `ProblemCode` enum is copied byte-for-byte int ### 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. The read operation is in the contract; its handler is not implemented yet, so it answers 401 `unauthenticated` until sessions exist (`v1.DenyAllSecurity`). The storage behind it exists (TASK-062, see [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#consent-ledger)). +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. The read operation is in the contract; its handler is not implemented yet, so it answers 401 `unauthenticated` until sessions exist (`v1.DenyAllSecurity`). The storage behind it exists (see [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#consent-ledger)). | Method and path | operationId | Security | Success | Specific errors | | --- | --- | --- | --- | --- | @@ -534,9 +534,9 @@ The `consent` tag covers the consent ledger of the current account (PRD FR01, FR - 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. `ConsentPurpose` stays the subset whose text is public before registration (`c1`), so `GetConsentText` does not widen. - 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), TASK-088), 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. +- 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. - The ledger is append-only. A newer text version of a purpose is a new record and the earlier one becomes `superseded` without any change; a revocation stamps the unrevoked records of the purpose, and for `c4` of one organization, once; a later grant is a new record, and a revoked `c4` of an invitation never comes back. Purposes are independent. -- Planned, additive: granting C1, C2, C3, and C5 in the consent settings (TASK-063) and revoking any purpose with its consequences (TASK-064), as new operations of this tag; C1 at registration and C4 in `AcceptMyInvitation` already have their own operations. 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. +- Planned, additive: granting C1, C2, C3, and C5 in the consent settings and revoking any purpose with its consequences, as new operations of this tag; C1 at registration and C4 in `AcceptMyInvitation` already have their own operations. 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. @@ -544,7 +544,7 @@ No new problem code is added: the contract reuses `validation_failed` and `unaut ### Organizations -The `organization` tag covers the organizations of employer accounts and the memberships that give an account its role in them (PRD FR07, 2.2, and 6.4): the profile with its public contacts and representatives, the verification level that only the server sets, and the active organization context. The operations are in the contract; their business logic is not implemented yet, so every one answers 401 `unauthenticated` until sessions exist (`v1.DenyAllSecurity`). The storage behind them exists (TASK-077, see [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#organizations-and-memberships)); creating, editing, and the membership checks of the other operations are planned in TASK-078 and TASK-079. +The `organization` tag covers the organizations of employer accounts and the memberships that give an account its role in them (PRD FR07, 2.2, and 6.4): the profile with its public contacts and representatives, the verification level that only the server sets, and the active organization context. The operations are in the contract; their business logic is not implemented yet, so every one answers 401 `unauthenticated` until sessions exist (`v1.DenyAllSecurity`). The storage behind them exists (see [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#organizations-and-memberships)); creating, editing, and the membership checks of the other operations are planned as part of organization management and access control. | Method and path | operationId | Security | Success | Specific errors | | --- | --- | --- | --- | --- | @@ -555,10 +555,10 @@ The `organization` tag covers the organizations of employer accounts and the mem Every operation also declares the `default` problem response. A malformed `org_id` answers 400 with the path pointer. -Active organization context (decision of TASK-077): +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 (TASK-079 wants the next read closed, not the browser cache expired), it would make two tabs in two organizations fight over one value, and the path form is already the contract of needs and invitations. TASK-085 clears the tenant-scoped client queries on a switch, which fits a client-side context. +- 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: @@ -569,10 +569,10 @@ Access: 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` of TASK-082); 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 (TASK-082, TASK-084), 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. +- 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 (TASK-081 and TASK-082). 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 in TASK-083 and TASK-463. 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 in TASK-084 and TASK-085 and add operations, not fields, to this contract. +- 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: @@ -584,9 +584,9 @@ Profile: 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 (TASK-086 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. +- `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. The quotas themselves are TASK-087. +- 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: @@ -594,22 +594,22 @@ Candidate card and versions: - `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 (TASK-198), because the C4 scope needs both references at once and the ledger tests of TASK-062 and TASK-063 use synthetic organization identifiers. The application never deletes an organization. +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. -- Organizations per account (blocking for TASK-078 and TASK-087): the PRD sets no limit, and FR07 says that quotas belong to the organization as a whole and never grow on their own, but nothing stops one account from creating many organizations, each at `e0` with its own quota, which multiplies the quotas. This contract invents no number. The mechanism is ready: a cap would answer 409 `state_conflict` on `CreateOrganization` without a change of the schema, and the anti-abuse signals are TASK-319. The owner must decide the limit, or accept the risk explicitly, before the quotas of TASK-087 are enforced and before `CreateOrganization` is opened to users. +- Organizations per account (blocking for organization creation and quota enforcement): the PRD sets no limit, and FR07 says that quotas belong to the organization as a whole and never grow on their own, but nothing stops one account from creating many organizations, each at `e0` with its own quota, which multiplies the quotas. This contract invents no number. The mechanism is ready: a cap would answer 409 `state_conflict` on `CreateOrganization` without a change of the schema, and the anti-abuse signals belong to organization risk assessment. The owner must decide the limit, or accept the risk explicitly, before the organization quotas are enforced and before `CreateOrganization` is opened to users. - 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. -Planned, additive: member invitations, listing, role changes, and removal (TASK-081 to TASK-085), the full role matrix (TASK-463), the verification processes and their history (TASK-086), the quotas by level (TASK-087), the card in the candidate's invitation, the number-of-organizations cap, and a sphere code. +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, the number-of-organizations cap, 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, TASK-088). The operations are in the contract but their business logic is not implemented, so each answers 401 `unauthenticated` while there are no sessions (`v1.DenyAllSecurity`), and 501 `not_implemented` after an accepted session and a valid request. The storage behind them exists (migration 00015, see [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#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, so each answers 401 `unauthenticated` while there are no sessions (`v1.DenyAllSecurity`), and 501 `not_implemented` after an accepted session and a valid request. The storage behind them exists (migration 00015, see [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#candidate-visibility)). | Method and path | operationId | Protection | Success | Specific errors | | --- | --- | --- | --- | --- | @@ -628,7 +628,7 @@ Each operation also declares the problem response `default`. No new problem code 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, TASK-063). +- 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. @@ -637,16 +637,16 @@ 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 (TASK-185), not decided here. +- 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 (TASK-185) must reuse this content and cannot add a property that identifies the candidate. +- `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 (TASK-064) 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. +- 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. @@ -658,17 +658,17 @@ History: 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 (TASK-185). +- 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 is closed by TASK-089 with a closed taxonomy instead of free text. +- 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 of TASK-089, which builds the card; 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. +- 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. diff --git a/api/README.md b/api/README.md index aea1d35..cd0f619 100644 --- a/api/README.md +++ b/api/README.md @@ -102,7 +102,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro ### Identity: сессии, cookie и CSRF -Тег `identity` описывает регистрацию, подтверждение email, вход, выход и текущий аккаунт. Все операции есть в контракте. `RegisterAccount` и `ResendEmailVerification` реализованы (TASK-053); остальные публичные операции после валидации запроса по-прежнему отвечают 501 `not_implemented`, а `v1.DenyAllSecurity` в backend отклоняет любую сессию, поэтому операции, которым она нужна, отвечают 401 `unauthenticated`. Значения, отмеченные как запланированные, задаются конфигурацией в TASK-054 - TASK-056. +Тег `identity` описывает регистрацию, подтверждение email, вход, выход и текущий аккаунт. Все операции есть в контракте. `RegisterAccount` и `ResendEmailVerification` реализованы; остальные публичные операции после валидации запроса по-прежнему отвечают 501 `not_implemented`, а `v1.DenyAllSecurity` в backend отклоняет любую сессию, поэтому операции, которым она нужна, отвечают 401 `unauthenticated`. Значения, отмеченные как запланированные, задаются конфигурацией подтверждения почты, входа и сессий. | Метод и путь | operationId | Защита | Успех | Конкретные ошибки | | --- | --- | --- | --- | --- | @@ -121,8 +121,8 @@ ML-сервис отвечает на ошибки той же схемой `Pro - Аккаунты не перечисляются. Регистрация и повторная отправка отвечают одинаковым нейтральным 202 для нового, неподтвержденного, подтвержденного и неизвестного email, а вход отвечает 401 `invalid_credentials` и для неизвестного email, и для неверного пароля. - До поиска email сервер проверяет все тело регистрации (длину пароля после нормализации NFKC, blocklist паролей, версию C1) и в каждой ветке вычисляет хеш Argon2id, поэтому ни 400, ни время ответа не зависят от существования аккаунта. -- Повторная регистрация неподтвержденного email никогда не меняет хеш пароля, сценарий и шаг онбординга строки аккаунта. Каждая регистрация, первая и каждая повторная, хранит свои отложенные учетные данные (хеш пароля и сценарий) на своем токене подтверждения, заменяет запись C1, увеличивает версию регистрации и аннулирует все прежние токены подтверждения. Подтверждение токена (`ConfirmEmail`, TASK-054) обязано применять отложенные данные только этого токена и требовать пароль этой регистрации, чтобы подтвердить токен с отложенными данными; в текущем `EmailVerificationRequest` поля пароля нет, поэтому TASK-054 меняет контракт. Это не дает владельцу адреса, перешедшему по ссылке злоумышленника, принять предрегистрацию с чужим паролем, и наоборот. Строкой неподтвержденного аккаунта нельзя войти: вход (TASK-055) отклоняет любой неподтвержденный аккаунт и никогда не сравнивает пароль со строкой или с отложенными данными неподтвержденного аккаунта. Для подтвержденного email ничего не меняется; сервер ничего не отправляет. -- Реализация регистрации и повторной отправки (TASK-053). Подтвержденный адрес: ничего не меняется и ничего не отправляется (уведомление "у вас уже есть аккаунт" не реализовано). Лимиты на адрес (общие для регистрации и повторной отправки, ключ - HMAC нормализованного адреса, считаются независимо от наличия аккаунта): не реже `VERIFICATION_MAIL_MIN_INTERVAL` (по умолчанию 60 с) между письмами и не больше `VERIFICATION_MAIL_DAILY_LIMIT` (по умолчанию 5) за 24 часа; на клиента: `IDENTITY_CLIENT_HOURLY_LIMIT` (по умолчанию 30 в час). Отклоненный запрос дает 429 `rate_limited` с `Retry-After` в целых секундах и не выпускает токен. Политика замены токена: каждый выпуск сначала аннулирует все неиспользованные токены подтверждения аккаунта, поэтому работает одна ссылка; повторная отправка меняет только токен. `IDENTITY_KEY_SECRET` (не меньше 32 байт, обязателен; `IDENTITY_ALLOW_EPHEMERAL_KEY=true` разрешает случайный на стенде разработки) ключует область идемпотентности, отпечаток и ключи лимитера. Параллельный запрос с тем же ключом ждет первый и воспроизводится, поэтому `idempotency_in_progress` не возникает. Подробности: [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#регистрация-и-повторная-отправка-подтверждения). +- Повторная регистрация неподтвержденного email никогда не меняет хеш пароля, сценарий и шаг онбординга строки аккаунта. Каждая регистрация, первая и каждая повторная, хранит свои отложенные учетные данные (хеш пароля и сценарий) на своем токене подтверждения, заменяет запись C1, увеличивает версию регистрации и аннулирует все прежние токены подтверждения. Подтверждение токена (`ConfirmEmail`) обязано применять отложенные данные только этого токена и требовать пароль этой регистрации, чтобы подтвердить токен с отложенными данными; в текущем `EmailVerificationRequest` поля пароля нет, поэтому подтверждение почты требует изменения контракта. Это не дает владельцу адреса, перешедшему по ссылке злоумышленника, принять предрегистрацию с чужим паролем, и наоборот. Строкой неподтвержденного аккаунта нельзя войти: вход отклоняет любой неподтвержденный аккаунт и никогда не сравнивает пароль со строкой или с отложенными данными неподтвержденного аккаунта. Для подтвержденного email ничего не меняется; сервер ничего не отправляет. +- Реализация регистрации и повторной отправки. Подтвержденный адрес: ничего не меняется и ничего не отправляется (уведомление "у вас уже есть аккаунт" не реализовано). Лимиты на адрес (общие для регистрации и повторной отправки, ключ - HMAC нормализованного адреса, считаются независимо от наличия аккаунта): не реже `VERIFICATION_MAIL_MIN_INTERVAL` (по умолчанию 60 с) между письмами и не больше `VERIFICATION_MAIL_DAILY_LIMIT` (по умолчанию 5) за 24 часа; на клиента: `IDENTITY_CLIENT_HOURLY_LIMIT` (по умолчанию 30 в час). Отклоненный запрос дает 429 `rate_limited` с `Retry-After` в целых секундах и не выпускает токен. Политика замены токена: каждый выпуск сначала аннулирует все неиспользованные токены подтверждения аккаунта, поэтому работает одна ссылка; повторная отправка меняет только токен. `IDENTITY_KEY_SECRET` (не меньше 32 байт, обязателен; `IDENTITY_ALLOW_EPHEMERAL_KEY=true` разрешает случайный на стенде разработки) ключует область идемпотентности, отпечаток и ключи лимитера. Параллельный запрос с тем же ключом ждет первый и воспроизводится, поэтому `idempotency_in_progress` не возникает. Подробности: [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#регистрация-и-повторная-отправка-подтверждения). - Каждый токен подтверждения привязан к версии регистрации, для которой выпущен, поэтому токен, выпущенный до повторной регистрации, никогда не подтверждает новые учетные данные. Повторная отправка выпускает токен для текущей версии с отложенными данными этой регистрации, аннулирует прежние и больше ничего не меняет. Запланированные значения: токен живет 24 часа; аккаунт, оставшийся неподтвержденным, удаляется вместе с записью согласия и токенами через 7 дней после последней регистрации. Эти сроки берутся из версионированной продуктовой политики (демонстрационная версия 1 семейства `product`), а не из конфигурации; см. [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#версии-продуктовой-политики). - Регистрация требует Idempotency-Key. Для этой анонимной операции ключ ограничивается операцией, самим ключом и HMAC нормализованного email; отпечаток - HMAC-SHA-256 с серверным секретом над каноническим JSON тела. Тело, пароль и их простые хеши не хранятся, а секрет не дает использовать отпечаток для офлайн-проверки пароля. - Ссылка подтверждения имеет вид `/verify-email#token=`. Страница удаляет фрагмент через `history.replaceState` и отправляет токен только после явного действия пользователя, поэтому токен не попадает в логи сервера и заголовок Referer, а сканер ссылок его не расходует. Подтверждение не создает сессию. @@ -139,11 +139,11 @@ ML-сервис отвечает на ошибки той же схемой `Pro - Схема `sessionCookie` - cookie `__Host-lincodex_session` с `Path=/; Secure; HttpOnly; SameSite=Strict` и без Domain. Сервер хранит сессии в PostgreSQL и берет вызывающего только из сессии. Сессию получает только подтвержденный аккаунт. Вход отзывает сессию, пришедшую с запросом, и выдает новый идентификатор и CSRF-токен; выход отзывает сессию на сервере. Запланированные тайм-ауты: 24 часа простоя и 7 дней абсолютного срока; активность продлевает только срок простоя. Оба значения берутся из версионированной продуктовой политики, а не из конфигурации. - Схема `sessionCsrf` - заголовок `X-CSRF-Token` с привязанным к сессии токеном из `Session.csrf_token`. Любая небезопасная операция, требующая `sessionCookie`, обязана требовать и `sessionCsrf`; это проверяет `TestUnsafeSessionOperationsRequireCSRFToken` в backend по bundle. Клиент хранит токен только в памяти и восстанавливает его через `GetCurrentSession` после перезагрузки страницы или после 403 `csrf_check_failed`. -- Любой небезопасный запрос, включая публичные, должен нести `Origin` из настроенного allowlist, иначе 403 `csrf_check_failed` (запланировано, TASK-056; см. [руководство по разработке](../docs/ru/DEVELOPMENT.md#сессии-на-локальном-http)). Публичные операции identity ограничены по частоте (429 с `Retry-After`). +- Любой небезопасный запрос, включая публичные, должен нести `Origin` из настроенного allowlist, иначе 403 `csrf_check_failed` (запланировано; см. [руководство по разработке](../docs/ru/DEVELOPMENT.md#сессии-на-локальном-http)). Публичные операции identity ограничены по частоте (429 с `Retry-After`). - Ответы с сессией или аккаунтом несут `Cache-Control: no-store`. - Корневой `security` требует `sessionCookie`, поэтому операция без явного `security: []` защищена по умолчанию. -Как сгенерированный сервер (ogen v1.24.0) проверяет схемы и какое отображение запланировано для TASK-056, описано в `v1.DenyAllSecurity` и закреплено тестом `TestGeneratedServerSecurityOrder`: +Как сгенерированный сервер (ogen v1.24.0) проверяет схемы и какое отображение запланировано для аутентификации сессий, описано в `v1.DenyAllSecurity` и закреплено тестом `TestGeneratedServerSecurityOrder`: - Он вызывает `HandleSessionCookie` раньше `HandleSessionCsrf` и передает дальше контекст, возвращенный успешным вызовом. Отсутствующее значение (нет cookie, пустой `X-CSRF-Token`) не вызывает обработчик, а обработчик, вернувший `ogenerrors.ErrSkipServerSecurity`, считается невыполненным; в обоих случаях проверка продолжается со следующей схемы, поэтому `HandleSessionCsrf` вызывается и без cookie, с исходным контекстом. - Любая другая ошибка обработчика останавливает проверку и попадает в `NewError` как `SecurityError` с `Security`, равным `SessionCookie` или `SessionCsrf`. Невыполненное требование попадает в `NewError` как `SecurityError` с `ErrSecurityRequirementIsNotSatisfied` и без поля `Security`. @@ -179,7 +179,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro ### Профиль кандидата -Тег `candidate` описывает и приватный профиль кандидата, который кандидат заполняет вручную (FR02 в PRD, TASK-066). Операции есть в контракте, бизнес-логика еще не реализована, поэтому каждая отвечает 401 `unauthenticated`, пока сессий нет (`v1.DenyAllSecurity`), а после принятой сессии и валидной схемы - 501 `not_implemented`. +Тег `candidate` описывает и приватный профиль кандидата, который кандидат заполняет вручную (FR02 в PRD). Операции есть в контракте, бизнес-логика еще не реализована, поэтому каждая отвечает 401 `unauthenticated`, пока сессий нет (`v1.DenyAllSecurity`), а после принятой сессии и валидной схемы - 501 `not_implemented`. | Метод и путь | operationId | Защита | Успех | Конкретные ошибки | | --- | --- | --- | --- | --- | @@ -215,11 +215,11 @@ ML-сервис отвечает на ошибки той же схемой `Pro - Профиль полностью заполняется вручную. Ни одно поле не требует резюме, извлечения ML или аккаунта ФСП, а миграция и запросы не создают обязательной связи с файлом, ML или ФСП. Загрузка резюме и привязка ФСП ID - запланированные аддитивные возможности; они добавят свои поля и источники, не меняя этих. -Связь с анкетой (TASK-150): +Связь с анкетой: - Анкета (`/me/questionnaire`) задает не более двух специализаций для оценки; профиль - то, что кандидат показывает о себе. Одноименные понятия не дублируются под разным смыслом: самооценка грейда и стек - одно и то же заявление в двух местах (в анкете для старта оценки и по специализации, в профиле для показа), сохраняются раздельно, и сервер не копирует одно в другое; общий опыт в месяцах в анкете и записи опыта в профиле - разные заявления; форматы работы живут только в анкете, а место, переезд и зарплата - только в профиле. Описания схем обеих сторон ссылаются друг на друга. -Хранение (миграция 00013, TASK-066): `candidate_profiles` (строка профиля: `user_id`, `version`, времена) и `candidate_profile_claims` (по строке на сохраненное заявление: `kind`, `ordinal`, `value` jsonb, `status`, `origin`, `trust_level`, `quote`, `extraction_version`, `confirmed_at`). Отсутствие строки значит `unknown`. Для каждого вида значения есть CHECK формата и границ контракта; `trust_level` всегда 0; в таблицах нет ни столбца файла, ни столбца ФСП, ни подтвержденного грейда. Подробности - в [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#профиль-кандидата). +Хранение (миграция 00013): `candidate_profiles` (строка профиля: `user_id`, `version`, времена) и `candidate_profile_claims` (по строке на сохраненное заявление: `kind`, `ordinal`, `value` jsonb, `status`, `origin`, `trust_level`, `quote`, `extraction_version`, `confirmed_at`). Отсутствие строки значит `unknown`. Для каждого вида значения есть CHECK формата и границ контракта; `trust_level` всегда 0; в таблицах нет ни столбца файла, ни столбца ФСП, ни подтвержденного грейда. Подробности - в [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#профиль-кандидата). Открытые вопросы к владельцу продукта и юристу: @@ -230,7 +230,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro - Минимум для шага онбординга `candidate_profile`: контракт не требует ни одного поля; какие поля нужны, чтобы шаг считался пройденным, решает владелец продукта. - Единый источник между анкетой и профилем: оставить самооценку и стек независимыми или хранить одно заявление и показывать в обоих местах. - Софт-скиллы: таксономии нет, свободный текст до 10 штук по 50 символов; нужен ли справочник. -- Опыт: названия работодателей и описания - ПДн; как анонимная карточка их обобщает (PRD: отрасль и размер), решает контракт карточки (TASK-185), а не этот. +- Опыт: названия работодателей и описания - ПДн; как анонимная карточка их обобщает (PRD: отрасль и размер), решает контракт карточки, а не этот. - Проверка контактов (подтверждение телефона или email профиля) не предусмотрена: контакты - заявления уровня 0. `TestCandidateProfileOperationsFollowTheConventions`, `TestCandidateProfileSeparatesSelfAssessedGradeFromConfirmedCategory`, `TestCandidateProfileClaimsCarrySourceAndTrustLevelZero`, `TestPrivateProfileSchemasAreNotMixedWithOrganizationVisibleDTOs`, `TestGeneratedProfileDTOsCarryNoConfirmedGradeInRequests`, `TestProfileSchemaValidationPrecedesImplementation` и `TestProfileAccessBeforeImplementation` закрепляют сгенерированный сервер и бандл, а `frontend/src/shared/api/profile-contract.test.ts` - сгенерированные правила Zod, типы запросов без подтвержденного грейда и отсутствие полей профиля в схемах организации, приглашения и потребности. @@ -278,7 +278,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro - Лимиты: `expires_at` и `sessions` (`used`, `max`, `idle_timeout_seconds`; null, если политика не задает лимит сессий) берутся из версии политики; FR04 в PRD допускает две сессии в пределах 72 часов. Создание начинает сессию 1. Чтение или команда по активной попытке после `idle_timeout_seconds` без них начинает следующую сессию; сессия сверх `max` не начинается, и попытка становится `expired`. Чтение терминальной попытки или результата сессию не начинает. - При достижении лимитов практика в статусе `pending` сначала оценивается. Затем сервер сам завершает `ready_to_finalize` и переводит в `completed`, неотправленная дополнительная практика считается отклоненной (`completed`, `not_confirmed`), а `in_progress` и `practice_pending` становятся `expired`. Завершение после этого дает 200 с попыткой в `completed`; любая другая команда дает 409 `state_conflict`. - Недостаточный банк - отдельное состояние в двух местах. До старта `GetMyAssessmentAvailability` показывает `insufficient_bank` для грейда без опубликованного банка или без достаточного числа семейств, которых кандидат еще не видел, а `CreateMyAssessmentAttempt` отвечает 409 `state_conflict` и ничего не создает. Во время попытки терминальное состояние `insufficient_bank` завершает ее без подтвержденного грейда вместо повтора семейств. -- Новый код проблемы не добавлен, поэтому TASK-157 получает 409 `state_conflict` и статус доступности вместо кода `bank_unavailable`. Перечисление `ProblemCode` побайтно скопировано в ML-контракт (`test_contract_copies.py`), поэтому новый код изменил бы и ML-контракт, и его сгенерированные модели. Чтение доступности к тому же объясняет клиенту, почему попытка не может начаться, и для `cooldown` - с какого момента; фиксированный detail проблемы этого передать не может. +- Новый код проблемы не добавлен, поэтому создание попытки получает 409 `state_conflict` и статус доступности вместо кода `bank_unavailable`. Перечисление `ProblemCode` побайтно скопировано в ML-контракт (`test_contract_copies.py`), поэтому новый код изменил бы и ML-контракт, и его сгенерированные модели. Чтение доступности к тому же объясняет клиенту, почему попытка не может начаться, и для `cooldown` - с какого момента; фиксированный detail проблемы этого передать не может. - Доступность показывает лимиты каждого грейда до старта: `time_limit_seconds`, `max_sessions`, `max_items` и `practice_required`; null, если значение неизвестно. - Учет в правилах повтора (3 попытки за 180 дней, 30 дней до повтора того же грейда): попытка с итогом `not_determined` по причине `expired` или `practice_incomplete` - попытка кандидата и учитывается. `insufficient_bank` и `sandbox_unavailable` - сбои платформы: они не учитываются и не запускают интервал. После неудачи, включая первый тест, меньший грейд можно проверить сразу. @@ -296,7 +296,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro - Каждое задание принимает один ответ. Повторная отправка сохраненного ответа, даже с новым ключом или старым `expected_version`, ничего не сохраняет, не меняет версию и дает 200 с текущей попыткой. Равенство определено для каждого формата: множества для `option_ids` и `line_numbers`, точная последовательность для `element_ids`, числовое равенство для `number`, совпадение текста без нормализации для `text` и `config`, тот же язык и совпадающий исходный код для практики. Другой ответ на уже отвеченное задание дает 409 `state_conflict` при текущей версии; при устаревшей версии ее проверка идет раньше и дает 412. - Исключение: практика, последний вердикт которой `failed`, не подпадает под правило повтора. Отправка того же или другого решения с текущей версией снова ставит его в очередь и увеличивает версию. - Завершение попытки в `completed` дает 200 с этой попыткой, поэтому результат вычисляется один раз. Повтор завершения, которое предложило дополнительную практику, с новым ключом несет старую версию и получает 412, поэтому он не может случайно отклонить предложение. -- Устаревший `expected_version` дает 412 `version_conflict`, а не 409. Это отступление от формулировки шага проверки TASK-155 и TASK-152, где указан 409. Так сохраняется правило репозитория выше и прецедент анкеты: `version_conflict` - это 412 и для If-Match, и для `expected_version` в теле, потому что действие клиента одно - прочитать ресурс снова. 409 `state_conflict` оставлен для команды, которую состояние попытки не допускает при текущей версии: задание не текущее или уже имеет другой ответ, попытка терминальная или вышла за лимиты, вердикт практики еще не готов или попытка не готова к завершению. Поэтому два кода ведут к разным действиям клиента. +- Устаревший `expected_version` дает 412 `version_conflict`, а не 409. Так сохраняется правило репозитория выше и прецедент анкеты: `version_conflict` - это 412 и для If-Match, и для `expected_version` в теле, потому что действие клиента одно - прочитать ресурс снова. 409 `state_conflict` оставлен для команды, которую состояние попытки не допускает при текущей версии: задание не текущее или уже имеет другой ответ, попытка терминальная или вышла за лимиты, вердикт практики еще не готов или попытка не готова к завершению. Поэтому два кода ведут к разным действиям клиента. - Преждевременное завершение дает 409 `state_conflict` без перечня незавершенных заданий, потому что `Problem` не допускает дополнительных полей. Клиент берет их из попытки: `state`, `progress`, `current_item` и `practices`. - Порядок проверок команды: сессия (401), CSRF и Origin (403), валидация запроса (400), сценарий аккаунта (403 `forbidden`), Idempotency-Key (422, 409 `idempotency_in_progress`, повтор), попытка (404, после всех назревших переходов), повтор сохраненного ответа или завершения завершенной попытки (200), версия (412), состояние (409 `state_conflict`), затем доменные правила (400 с pointer вроде `/answer/option_ids/0`). По соглашению об Idempotency-Key 404 и 409 `state_conflict` сохраняются под ключом и повторяются, а 400 (включая доменные правила), 412, 429 и 5xx - нет. Создание и ответы ограничены по частоте (429 с `Retry-After`), что ограничивает и нагрузку на песочницу. `TestAssessmentSchemaValidationPrecedesImplementation` проверяет отказы схемы через сгенерированный сервер. @@ -324,7 +324,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro Доступ: -- `org_id` в пути - единственный источник организации, и сервер сверяет его с действующим членством аккаунта сессии; ни один запрос не содержит поля организации, членства или роли. Организации и членства принадлежат контракту организации (TASK-077), который переиспользует тот же параметр пути `parameters.yml#/OrganizationId`. +- `org_id` в пути - единственный источник организации, и сервер сверяет его с действующим членством аккаунта сессии; ни один запрос не содержит поля организации, членства или роли. Организации и членства принадлежат контракту организации, который переиспользует тот же параметр пути `parameters.yml#/OrganizationId`. - Аккаунт без действующего членства в `org_id`, неизвестная организация, неизвестная потребность и потребность другой организации одинаково дают 404 `not_found`, поэтому идентификаторы нельзя перебрать. Аккаунт кандидата получает 403 `forbidden`, как и участник, чья роль не разрешает операцию. - В MVP с потребностями работает только владелец организации. Остальные роли матрицы FR07 в PRD (рекрутер, нанимающий менеджер и техэксперт для назначенных потребностей) запланированы и не меняют ни одного поля контракта. @@ -335,7 +335,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro - `source` содержит `origin` (`manual`, `extracted_from_text` или запланированный `imported`), `quote` (точный фрагмент до 300 знаков или null), `extracted_in_version` и `extraction_version`. Цитата - фрагмент `source_text` версии `extracted_in_version`, а не обязательно текущего текста: подтвержденное значение сохраняет цитату после изменения текста. Подтверждение предложения сохраняет его происхождение; изменение значения делает его `manual`. - У навыка есть `taxonomy_code`. Он равен null для навыка, которого нет в таксономии платформы: название остается как указано, код не угадывается, а рекомендации считают навык непокрытым. - При наличии `source_text` сервер до ответа извлекает предложения детерминированными правилами и словарем, поэтому потребности работают при выключенном ML. ML-предложения с цитатами запланированы как асинхронное дополнение, которое создает новую версию и никогда не перезаписывает подтвержденное значение. -- Текст хранится как написан и может содержать дискриминирующие требования по защищенным признакам; извлечение никогда не превращает их в поле потребности. Поле того, чего не должно быть у кандидата, с проверкой по ст. 64 ТК РФ отложено до TASK-182 и добавится без ломающих изменений. +- Текст хранится как написан и может содержать дискриминирующие требования по защищенным признакам; извлечение никогда не превращает их в поле потребности. Поле того, чего не должно быть у кандидата, с проверкой по ст. 64 ТК РФ отложено до реализации проверки требований и добавится без ломающих изменений. Запросы, подтверждение и изменения: @@ -350,8 +350,8 @@ ML-сервис отвечает на ошибки той же схемой `Pro Версии и конкурентность: - `version` начинается с 1 и растет ровно на единицу с каждым зафиксированным изменением, включая серверные. Каждая версия - неизменяемый снимок. GET всегда возвращает последнюю версию. -- `requirements_version` - версия, в которой подтвержденные требования менялись последний раз. Подтверждение, изменение или удаление требования делает ее равной новой `version`; изменение названия, привязки вакансии, текста или только предложений ее сохраняет и не обесценивает ни рекомендации, ни результаты поиска. Запуски поиска, снимки подборки (FR10, TASK-193) и приглашения ссылаются на `(need_id, requirements_version)`, и новый снимок подборки нужен только при новой `requirements_version`. Чтение и сравнение прежних версий запланированы отдельными операциями, которые возвращают `NeedRequirementSet` для версии; в `Need` они ничего не добавляют. -- Изменение передает `expected_version` - прочитанную клиентом версию - в теле по той же причине, что и анкета: сгенерированный клиент пока не читает `ETag`. Устаревшее значение дает 412 `version_conflict` и ничего не меняет; в TASK-179 указан 409, но правило репозитория сохраняет 412 и для If-Match, и для версии в теле. Тело, которое ничего не меняет, дает 200 с текущей потребностью даже со старой версией, поэтому PATCH не нужен Idempotency-Key. POST требует его с повтором в течение 24 часов; сохраняется только 201. +- `requirements_version` - версия, в которой подтвержденные требования менялись последний раз. Подтверждение, изменение или удаление требования делает ее равной новой `version`; изменение названия, привязки вакансии, текста или только предложений ее сохраняет и не обесценивает ни рекомендации, ни результаты поиска. Запуски поиска, снимки подборки (FR10) и приглашения ссылаются на `(need_id, requirements_version)`, и новый снимок подборки нужен только при новой `requirements_version`. Чтение и сравнение прежних версий запланированы отдельными операциями, которые возвращают `NeedRequirementSet` для версии; в `Need` они ничего не добавляют. +- Изменение передает `expected_version` - прочитанную клиентом версию - в теле по той же причине, что и анкета: сгенерированный клиент пока не читает `ETag`. Устаревшее значение дает 412 `version_conflict` и ничего не меняет; правило репозитория сохраняет 412 и для If-Match, и для версии в теле. Тело, которое ничего не меняет, дает 200 с текущей потребностью даже со старой версией, поэтому PATCH не нужен Idempotency-Key. POST требует его с повтором в течение 24 часов; сохраняется только 201. Готовность: @@ -363,18 +363,18 @@ ML-сервис отвечает на ошибки той же схемой `Pro - `SalaryRange` `[A; B]` содержит `salary_from` и `salary_to` (`RubAmount`, целые рубли), `currency` (только `RUB`), `period` (только `month`) и `tax_basis` (`net` или `gross`); все поля обязательны. Запрос передает ее как `salary: {value, status}`, поэтому ее pointer начинаются с `/salary/value`. - Схема требует положительных границ, кратных 1000, до 100000000 и отклоняет другую валюту, период или базу, например с `/salary/value/tax_basis`. Отсутствующее поле вложенной вилки дает `required` со своим pointer, например `/salary/value/tax_basis`. - Межполевые правила FR13 в PRD сервер проверяет в целочисленной арифметике: `A < B` и ширина `(B - A) / ((A + B) / 2)` от 10% до 40% включительно, то есть `20 * (B - A) >= A + B` и `5 * (B - A) <= A + B`. Нарушение, включая равные границы, дает 400 с pointer `/salary/value/salary_to`. `[95000; 105000]` (ровно 10%) и `[80000; 120000]` (ровно 40%) принимаются. FR13 применяет одни правила к вилке потребности и приглашения, и `docs/*/ARCHITECTURE.md` теперь указывает их для приглашений вместо `0 < salary_from <= salary_to`. -- Ограничение против подбора скрытых минимумов (FR13, запланировано в TASK-211): задание подтвержденной вилки при создании или изменении учитывается в счетчике, общем для всей организации, всех участников и всех потребностей, поэтому новая потребность его не обнуляет. Не больше трех заданий вилки в сутки; сверх лимита сервер отвечает 429 с Retry-After и ничего не меняет. После пяти заданий за семь дней денежная компонента получает статус `withheld` на семь дней. Повторные изменения вилки также питают приватные сигналы риска TASK-319. +- Ограничение против подбора скрытых минимумов (FR13, применение запланировано): задание подтвержденной вилки при создании или изменении учитывается в счетчике, общем для всей организации, всех участников и всех потребностей, поэтому новая потребность его не обнуляет. Не больше трех заданий вилки в сутки; сверх лимита сервер отвечает 429 с Retry-After и ничего не меняет. После пяти заданий за семь дней денежная компонента получает статус `withheld` на семь дней. Повторные изменения вилки также питают приватные сигналы риска организации. Рекомендации: - `recommendations` вычисляет сервер по подтвержденным требованиям версии `requirements_version` с версионируемой политикой (`policy_version`, `algorithm_version`, `computed_at`). `status` - `computed`, `pending` или `not_available` без подтвержденного навыка. Сервер может пересчитать их для той же `requirements_version` при новой политике или изменившемся пуле кандидатов без новой версии потребности; тогда меняются `computed_at` и `policy_version`. - У каждой категории (`specialization` и `grade`) есть `score`, `skill_overlap` (взвешенная доля с весом 2 для обязательных и 1 для желательных навыков, покрытые и непокрытые навыки), `money` и `supply` диапазоном: `fewer_than_5`, `from_5_to_29`, `30_or_more`. Порядок списка задает ранжирование. - `money.status` - `computed`, `insufficient_data` (меньше пяти кандидатов с известным сопоставимым минимумом), `no_salary` или `withheld`; последние три используют нейтральное 0,5 и null в доле. `money.share` округляется вниз до четверти (0, 0.25, 0.5, 0.75, 1): каждая проба новой верхней границы говорит не больше того, какая четверть группы ее принимает, а в наименьшей допустимой группе из пяти один минимум часто не сдвигает значение; при этом доля по-прежнему отличает вилку, которую принимает большинство, от той, которую принимают немногие. -- `score` равен `0.5 * Overlap + 0.3 * Money + 0.2 * Supply` с округлением половины вверх до двух знаков и вычисляется по опубликованным компонентам: точному покрытию, доле с округлением до четверти или нейтральному 0,5 и `Supply = min(1, active / 30)`. Он равен null, когда `supply` - `fewer_than_5`. Ниже пяти ранжирование использует Supply только с точностью диапазона: каждая группа меньше пяти кандидатов входит в него с Supply 0, поэтому ни балл, ни порядок не раскрывают точный размер группы меньше пяти, что запрещает FR08. Для пяти и более кандидатов используется точный Supply, поэтому фикстура TASK-183 (Overlap 1, Money 0,5, 15 активных кандидатов) дает `score` 0.75. -- Отступление от формулы PRD, TASK-183 и TASK-457: в балле и ранжировании используется доля денег, округленная до четверти, а не точная, и у категории меньше чем с пятью кандидатами балла нет. Иначе балл с точной долей раскрыл бы долю, которую округляет `money.share`, а балл с точным Supply малой группы - ее размер. Разложение, которое показывает TASK-457, состоит из опубликованных компонент. +- `score` равен `0.5 * Overlap + 0.3 * Money + 0.2 * Supply` с округлением половины вверх до двух знаков и вычисляется по опубликованным компонентам: точному покрытию, доле с округлением до четверти или нейтральному 0,5 и `Supply = min(1, active / 30)`. Он равен null, когда `supply` - `fewer_than_5`. Ниже пяти ранжирование использует Supply только с точностью диапазона: каждая группа меньше пяти кандидатов входит в него с Supply 0, поэтому ни балл, ни порядок не раскрывают точный размер группы меньше пяти, что запрещает FR08. Для пяти и более кандидатов используется точный Supply, поэтому фикстура рекомендаций (Overlap 1, Money 0,5, 15 активных кандидатов) дает `score` 0.75. +- Отступление от формулы PRD: в балле и ранжировании используется доля денег, округленная до четверти, а не точная, и у категории меньше чем с пятью кандидатами балла нет. Иначе балл с точной долей раскрыл бы долю, которую округляет `money.share`, а балл с точным Supply малой группы - ее размер. Отображаемое разложение, состоит из опубликованных компонент. - Запрос не может задать рекомендацию, ее балл, членство или минимум кандидата: у тел `additionalProperties: false`, и неизвестные поля, например `rec_score`, `members`, `candidate_minimum`, `version`, `requirements_version` или `recommendations`, дают 400 с pointer на все тело. `TestNeedSchemaValidationPrecedesImplementation` проверяет отказы схемы через сгенерированный сервер, `TestNeedUpdateDecodingKeepsAbsentAndEmptyListsApart` - декодирование списков, а `frontend/src/shared/api/needs-contract.test.ts` закрепляет ограничения сгенерированного Zod, явный статус каждого решения и отсутствие этих полей в типах запросов. -Запланировано, добавляется без ломающих изменений: чтение и сравнение версий, исключения (TASK-182), подсказка рыночной вилки (P25-P75) из FR08, план проверки "вакансия -> задания", статус потребности для архивации, фильтры списка и назначения на потребность. +Запланировано, добавляется без ломающих изменений: чтение и сравнение версий, исключения, подсказка рыночной вилки (P25-P75) из FR08, план проверки "вакансия -> задания", статус потребности для архивации, фильтры списка и назначения на потребность. ### Обращения @@ -391,8 +391,8 @@ ML-сервис отвечает на ошибки той же схемой `Pro Доступ: - Автор - аккаунт сессии; ни один запрос не содержит поля пользователя, аккаунта или организации. FR18 в PRD позволяет обращаться в поддержку и кандидату, и сотруднику компании, поэтому `/me` обслуживает оба сценария: аккаунт работодателя открывает обращения типа `support`, а остальные типы дают ему 403 `forbidden`. Обращение принадлежит создавшему его аккаунту, а не организации: другие участники той же организации его не видят. -- Обращение другого аккаунта дает 404 `not_found`, как и неизвестный идентификатор. TASK-314 говорит о "forbidden" для URL чужого обращения; контракт вместо этого отвечает 404, чтобы идентификаторы нельзя было перебрать, и клиент показывает одно и то же состояние "не найдено" для чужого и неизвестного обращения. Автор читает обращение независимо от того, что потом стало с объектом, поэтому отказ в тесте или отозванный доступ его не скрывают. -- Очереди модерации из TASK-316 - отдельные служебные операции со своими DTO; к этим операциям они ничего не добавляют. +- Обращение другого аккаунта дает 404 `not_found`, как и неизвестный идентификатор. Контракт отвечает 404, чтобы идентификаторы нельзя было перебрать, и клиент показывает одно и то же состояние "не найдено" для чужого и неизвестного обращения. Автор читает обращение независимо от того, что потом стало с объектом, поэтому отказ в тесте или отозванный доступ его не скрывают. +- Очереди модерации - отдельные служебные операции со своими DTO; к этим операциям они ничего не добавляют. Типы и ссылки на объекты: @@ -406,10 +406,10 @@ ML-сервис отвечает на ошибки той же схемой `Pro - Запрос - `oneOf` из пяти вариантов, выбираемых по `type` (`SupportCaseCreateSupport`, `SupportCaseCreateComplaint`, `SupportCaseCreateGradeAppeal`, `SupportCaseCreateAnticheatAppeal`, `SupportCaseCreateManualAssessment`). Каждый вариант сужает схему своей ссылки, поэтому уже схема отклоняет организацию в апелляции грейда или обращение в жалобе с pointer `/object/type`, а отсутствующее поле типа - с его pointer, например `/object` или `/assessment_target`. ogen выбирает вариант по значению `type`. Неизвестный или отсутствующий тип и поле другого варианта, например `complaint_reason` в обращении в поддержку, дают 400 с pointer на все тело `""`, потому что относятся к варианту верхнего уровня; `object.id`, который не является UUID, дает 400 с `/object/id` (пример `SupportCaseMalformedReference`). - Категорию, присвоенную без попытки, тоже можно оспорить (FR18): апелляция грейда может ссылаться на собственное обращение ручной оценки, когда оно `resolved` с `assessed`. Неизвестное обращение и обращение другого аккаунта дают 404 `not_found`; собственное обращение другого типа, еще не решенное или решенное с другим исходом дает 409 `state_conflict`. -- Организацию видит кандидат, которого она пригласила или которому контракт организации (TASK-077) показывает ее профиль, и аккаунт работодателя с действующим членством в ней. Сервер сверяет каждую ссылку с аккаунтом сессии: неизвестный и чужой объект одинаково дают 404 `not_found`, поэтому ссылка не раскрывает, существует ли чужой объект. Обращение хранит только `{type, id}`. +- Организацию видит кандидат, которого она пригласила или которому контракт организации показывает ее профиль, и аккаунт работодателя с действующим членством в ней. Сервер сверяет каждую ссылку с аккаунтом сессии: неизвестный и чужой объект одинаково дают 404 `not_found`, поэтому ссылка не раскрывает, существует ли чужой объект. Обращение хранит только `{type, id}`. - Приглашения есть в контракте (см. раздел Приглашения и контактные разрешения ниже), но не реализованы, а решений античит-проверки в контракте пока нет. До их реализации любая ссылка `invitation` дает 404, а любая античит-апелляция - 409 `state_conflict`; форма запроса не меняется. - Жалобы `offer_content` и `salary_terms_violation` требуют приглашения; другой объект дает 400 с pointer `/object/type` (доменное правило после схемы). -- Неудачный первый тест или отсутствие попыток не блокируют ручную оценку. Создание обращения не дает, не отзывает и не меняет согласие, грейд или попытку; связь ручной оценки с согласием C3 решают TASK-064 и TASK-315. +- Неудачный первый тест или отсутствие попыток не блокируют ручную оценку. Создание обращения не дает, не отзывает и не меняет согласие, грейд или попытку; связь ручной оценки с согласием C3 определяют отзыв согласия и ручная оценка. Содержание и поля, которые клиент не задает: @@ -436,11 +436,11 @@ ML-сервис отвечает на ошибки той же схемой `Pro - Новый problem-код не добавляется: перечисление `ProblemCode` побайтно копируется в ML-контракт. Недоступная античит-апелляция и повторная апелляция используют 409 `state_conflict`, а причину клиент узнает из обращения или попытки. - `TestSupportCaseSchemaValidationPrecedesImplementation` проверяет отказы схемы через сгенерированный сервер, а `frontend/src/shared/api/support-contract.test.ts` закрепляет правила сгенерированного Zod, отсутствие полей статуса, решения, модератора и контактов в типах запроса и отсутствие личности модератора и внутренних полей в обращении и в сводке. -Открытый продуктовый вопрос к TASK-315: подчиняются ли повторные ручные оценки той же категории правилам пересдачи из FR04 (тот же грейд через 30 дней, не больше трех попыток за 180 дней) или собственному правилу. Контракт разрешает только одну открытую ручную оценку на специализацию и интервал не придумывает. +Открытый продуктовый вопрос для ручной оценки: подчиняются ли повторные ручные оценки той же категории правилам пересдачи из FR04 (тот же грейд через 30 дней, не больше трех попыток за 180 дней) или собственному правилу. Контракт разрешает только одну открытую ручную оценку на специализацию и интервал не придумывает. -Запланировано, добавляется без ломающих изменений (новая операция или необязательное поле): ответы автора, вложения, отзыв обращения, фильтры списка по статусу и типу, итоговая категория ручной оценки в решении, следующий шаг для автора (TASK-322), служебные очереди и решения (TASK-316, TASK-317, TASK-323) и правила паузы срока ответа. +Запланировано, добавляется без ломающих изменений (новая операция или необязательное поле): ответы автора, вложения, отзыв обращения, фильтры списка по статусу и типу, итоговая категория ручной оценки в решении, следующий шаг для автора, служебные очереди и решения и правила паузы срока ответа. -Запланированные изменения контракта (новые значения перечислений; как и коды каталога, сгенерированные клиенты отклоняют неизвестное значение, поэтому каждое выходит вместе с перегенерированными клиентами): типы объектов `vacancy` и `application` для вакансий и защищенных откликов из FR16 и тип объекта для замечаний к профилю из TASK-272. `waiting_for_user` и `support_case` уже есть в перечислениях, поэтому операции ответа и последующим обращениям такое изменение не нужно. Новых видов событий и участников не планируется: ответ автора - это `reply` с участником `user`, пересмотр решения (TASK-317) - еще одно событие `decision`, а эксперты и модераторы - это `support`. +Запланированные изменения контракта (новые значения перечислений; как и коды каталога, сгенерированные клиенты отклоняют неизвестное значение, поэтому каждое выходит вместе с перегенерированными клиентами): типы объектов `vacancy` и `application` для вакансий и защищенных откликов из FR16 и тип объекта для замечаний из анализа профиля. `waiting_for_user` и `support_case` уже есть в перечислениях, поэтому операции ответа и последующим обращениям такое изменение не нужно. Новых видов событий и участников не планируется: ответ автора - это `reply` с участником `user`, пересмотр решения - еще одно событие `decision`, а эксперты и модераторы - это `support`. ### Приглашения и контактные разрешения @@ -467,9 +467,9 @@ ML-сервис отвечает на ошибки той же схемой `Pro Доступ: -- Сторона организации: `org_id` в пути - единственный источник организации, сервер сверяет его с действующим членством аккаунта сессии, как для потребностей. Аккаунт без членства, неизвестная организация, неизвестное приглашение и приглашение другой организации одинаково дают 404 `not_found`; аккаунт кандидата и участник, чья роль не разрешает операцию, получают 403 `forbidden`. В MVP с приглашениями работает только владелец; остальные роли FR07 запланированы (TASK-463). +- Сторона организации: `org_id` в пути - единственный источник организации, сервер сверяет его с действующим членством аккаунта сессии, как для потребностей. Аккаунт без членства, неизвестная организация, неизвестное приглашение и приглашение другой организации одинаково дают 404 `not_found`; аккаунт кандидата и участник, чья роль не разрешает операцию, получают 403 `forbidden`. В MVP с приглашениями работает только владелец; остальные роли FR07 запланированы. - Сторона кандидата: `/me/invitations` привязаны к аккаунту сессии. Черновик, приглашение другому кандидату и неизвестный идентификатор дают 404 `not_found`; аккаунт работодателя получает 403 `forbidden`. Ни в одном запросе нет поля пользователя, кандидата, организации или роли. -- Кандидат указывается только через `candidate_handle` (`CandidateHandle` в `common_schemas.yml`, общий с результатами поиска FR11, TASK-185), никогда через email, телефон или идентификатор аккаунта либо профиля. Неизвестный handle, handle другой организации и профиль, который организация больше не может видеть, одинаково дают 400 с pointer `/candidate_handle`. +- Кандидат указывается только через `candidate_handle` (`CandidateHandle` в `common_schemas.yml`, общий с результатами поиска FR11), никогда через email, телефон или идентификатор аккаунта либо профиля. Неизвестный handle, handle другой организации и профиль, который организация больше не может видеть, одинаково дают 400 с pointer `/candidate_handle`. Условия (`InvitationTerms`): @@ -481,7 +481,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro Версии и конфликты: - `version` растет с каждым зафиксированным изменением, включая просмотр и серверное истечение срока. `terms_version` растет только при изменении условий: изменении `terms` в черновике или единственном повышении верхней границы после отправки. Каждая версия условий неизменяема. -- Каждая команда, кроме просмотра, передает `expected_version`; `AcceptMyInvitation` передает еще `terms_version`. 412 `version_conflict`: `expected_version` или, при принятии, `terms_version` не текущие (случай устаревших условий, пример `InvitationStaleTerms`); ничего не изменено, под ключом ничего не сохраняется, клиент перечитывает приглашение. 409 `state_conflict`: состояние не допускает команду, например принятие отозванного или истекшего приглашения, команда в момент дедлайна или позже, отправка, заблокированная лимитом ожидающих по потребности или 30-дневной паузой, изменение отправленного приглашения или второе повышение; такой ответ сохраняется под ключом. TASK-197, TASK-201 и TASK-204 называют 409 для устаревших условий; правило репозитория оставляет 412 для любой устаревшей версии, как для потребностей и анкеты. +- Каждая команда, кроме просмотра, передает `expected_version`; `AcceptMyInvitation` передает еще `terms_version`. 412 `version_conflict`: `expected_version` или, при принятии, `terms_version` не текущие (случай устаревших условий, пример `InvitationStaleTerms`); ничего не изменено, под ключом ничего не сохраняется, клиент перечитывает приглашение. 409 `state_conflict`: состояние не допускает команду, например принятие отозванного или истекшего приглашения, команда в момент дедлайна или позже, отправка, заблокированная лимитом ожидающих по потребности или 30-дневной паузой, изменение отправленного приглашения или второе повышение; такой ответ сохраняется под ключом. Правило репозитория оставляет 412 для любой устаревшей версии, как для потребностей и анкеты. - Порядок: после того как приглашение найдено и наступивший срок применен, и после проверки повтора терминальное состояние (`declined`, `expired`, `withdrawn`, `cancelled_by_candidate`) или, для принятия и отказа, прошедший дедлайн дает 409 до сравнения версий. Поэтому клиент получает 409 для отозванного, истекшего или опоздавшего приглашения даже с устаревшими версиями и показывает итоговое состояние, а не перечитывает и повторяет. Затем идут версии (412) и остальные правила состояния (409). Это относится к принятию, отказу, отмене, отзыву и повышению вилки. - Повторы возвращают прежний результат: повтор с тем же Idempotency-Key воспроизводит сохраненный исход, а повтор команды, чей переход уже произошел, отвечает 200 с текущим приглашением даже с новым ключом или старой версией: отправка отправленного, отзыв отозванного, отказ с той же причиной и комментарием, отмена отмененного, то же повышение и принятие, чьи `terms_version` и поля совпадают с `contact_grant` - версией и полями, которые кандидат принял, даже если позднее повышение увеличило текущую `terms_version`. Второе согласие, grant, списание квоты или событие аудита не создаются. - `UpdateOrganizationInvitation` следует соглашению `UpdateOrganizationNeed`: без Idempotency-Key, с явной заменой полей, а тело, которое ничего не меняет, дает 200. @@ -490,7 +490,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro - `InvitationState` перечисляет все состояния таблицы FR12: `draft`, `delivered`, `viewed`, `counter`, `accepted`, `interview_scheduled`, `interviewed`, `negotiation`, `terms_agreed`, `no_deal`, `declined`, `expired`, `withdrawn`, `cancelled_by_candidate`. Операции MVP производят `draft`, `delivered`, `viewed`, `accepted`, `declined`, `expired`, `withdrawn` и `cancelled_by_candidate`; остальные перечислены заранее, чтобы сгенерированные клиенты принимали их, когда появятся встречное предложение, интервью и закрытый финал. Внутренний этап `SENT` не виден: отправка отвечает `delivered` после создания входящей записи. - `expiry_reason` - `invitation_timeout` или запланированный `negotiation_timeout`, не null ровно в `expired`. -- Просмотр - явная команда `ViewMyInvitation`: она переводит `delivered` в `viewed`, сохраняет дедлайн и в любом другом состоянии возвращает текущее приглашение без изменений. Команда идемпотентна по эффекту, поэтому ей не нужны ни Idempotency-Key, ни `expected_version`, и она никогда не падает из-за того, что приглашение изменилось после чтения клиентом. `GetMyInvitation` и `ListMyInvitations` побочных эффектов не имеют; чтение лишь показывает наступивший срок, который сервер применяет в момент дедлайна в любом случае. TASK-200 описывает просмотр как GET; команда не дает предзагрузке, повтору или обновлению кеша менять состояние, которое видит организация. +- Просмотр - явная команда `ViewMyInvitation`: она переводит `delivered` в `viewed`, сохраняет дедлайн и в любом другом состоянии возвращает текущее приглашение без изменений. Команда идемпотентна по эффекту, поэтому ей не нужны ни Idempotency-Key, ни `expected_version`, и она никогда не падает из-за того, что приглашение изменилось после чтения клиентом. `GetMyInvitation` и `ListMyInvitations` побочных эффектов не имеют; чтение лишь показывает наступивший срок, который сервер применяет в момент дедлайна в любом случае. Команда не дает предзагрузке, повтору или обновлению кеша менять состояние, которое видит организация. - `withdrawn` - команда организации из любого незавершенного состояния, включая `draft` и `accepted`; существующий grant она сохраняет. `cancelled_by_candidate` - команда кандидата из любого незавершенного состояния после доставки; она отзывает grant этого приглашения. Отказ - структурированный ответ до принятия. - Дедлайн равен `delivered_at + response_period_days` (3, 7 или 14 дней, по умолчанию 7). Просмотр, письмо или повышение вилки его не сдвигают; команда, принятая в момент дедлайна или позже, опоздала. @@ -498,7 +498,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro - Условия переиспользуют `SalaryRange` с правилами раздела Потребности: RUB, месяц, `net` или `gross`, положительные границы, кратные 1000, `A < B` и ширина 10-40%, которую сервер проверяет с pointer `/terms/salary/salary_to`. - Организация получает только `salary_fit`: `within_range`, `up_to_10_percent_above`, `above`, `withheld` или `not_available` (нет минимума для предложенных форматов или он в другой базе). Точный минимум не появляется ни в ответе, ни в примере, ни в логе, ни в problem. Сервер никогда не отклоняет вилку из-за минимума, потому что отказ сам раскрыл бы его. В DTO кандидата индикатора нет; кандидат сравнивает с собственным минимумом из профиля. -- Каждое изменение, которое может сдвинуть индикатор, считается установкой: вилка при создании, а в черновике изменение любой границы, базы или `work_formats`, потому что индикатор сравнивает с минимумом для предложенных форматов. Каждая установка учитывается в общем лимите организации - три в день вместе с вилками потребностей (429 с Retry-After, TASK-211) - и в счетчике `withheld`. Изменение, которое сохраняет вилку, базу и форматы, не учитывается. +- Каждое изменение, которое может сдвинуть индикатор, считается установкой: вилка при создании, а в черновике изменение любой границы, базы или `work_formats`, потому что индикатор сравнивает с минимумом для предложенных форматов. Каждая установка учитывается в общем лимите организации - три в день вместе с вилками потребностей (429 с Retry-After) - и в счетчике `withheld`. Изменение, которое сохраняет вилку, базу и форматы, не учитывается. - `withheld`: после пяти установок за семь дней индикатор выключается на семь дней с пятой. Ответ на пятую установку уже показывает `withheld`, как и каждый черновик и каждое приглашение организации, включая существующие, до конца периода. - Переключение базы превращает `not_available` в диапазон или обратно и тем сообщает организации базу минимума; это принято, а переключение учитывается в лимите как любая установка. - После отправки база фиксирована, а нижняя граница не снижается. `RaiseOrganizationInvitationSalary` поднимает `salary_to` один раз за всю историю приглашения, создает следующую версию условий и отвечает 409 на второе повышение. Оно подчиняется своему однократному правилу и не входит в дневной лимит, но учитывается в счетчике `withheld`, потому что сдвигает верхнюю границу, с которой сравнивает индикатор. @@ -506,12 +506,12 @@ ML-сервис отвечает на ошибки той же схемой `Pro Согласие C4 и контактное разрешение: - `GetMyInvitation` показывает в `contact_consent` текст C4 для этой организации и виды контактов, которые есть в профиле. Поле равно null, когда принять приглашение нельзя: этого не допускает состояние или дедлайн либо в профиле нет контактов. В последнем случае клиент просит кандидата сначала добавить контакт, потому что grant должен покрывать хотя бы одно поле. -- `AcceptMyInvitation` передает `terms_version`, `expected_version` и `consent_c4` (`ContactConsentAcceptance`): показанную версию текста C4, `accepted: true` и `fields` - хотя бы одно из `full_name`, `email`, `phone`, `telegram`, без значения по умолчанию и без предвыбора. Неопубликованная версия текста дает 400 `/consent_c4/text_version`, а поле, которого нет в профиле, - 400 `/consent_c4/fields/`. Согласие аналогично принятию C1 по `text_version`, а запись совпадает с реестром C4 из TASK-062 (цель, версия и хэш текста, организация, набор полей, приглашение-источник). Разрешение передавать данные в ATS организации (C4 и FR19) запланировано как дополнительный необязательный флаг, по умолчанию без передачи. -- В одной транзакции принятие переводит приглашение в `accepted`, записывает C4, создает grant ровно на выбранные поля и пишет событие аудита (TASK-201). Оно не публикует профиль (C2) и не снимает скрытие. +- `AcceptMyInvitation` передает `terms_version`, `expected_version` и `consent_c4` (`ContactConsentAcceptance`): показанную версию текста C4, `accepted: true` и `fields` - хотя бы одно из `full_name`, `email`, `phone`, `telegram`, без значения по умолчанию и без предвыбора. Неопубликованная версия текста дает 400 `/consent_c4/text_version`, а поле, которого нет в профиле, - 400 `/consent_c4/fields/`. Согласие аналогично принятию C1 по `text_version`, а запись совпадает с реестром согласий C4 (цель, версия и хэш текста, организация, набор полей, приглашение-источник). Разрешение передавать данные в ATS организации (C4 и FR19) запланировано как дополнительный необязательный флаг, по умолчанию без передачи. +- В одной транзакции принятие переводит приглашение в `accepted`, записывает C4, создает grant ровно на выбранные поля и пишет событие аудита. Оно не публикует профиль (C2) и не снимает скрытие. - У `contact_grant` кандидата есть `status` (`active` или `revoked`), `readable` и `blocked_by`. Grant, созданный, когда профиль не был опубликован или был скрыт от организации, остается `active` с `readable: false` и `blocked_by: visibility`, чтобы кандидат видел, почему организация не может его прочитать (FR12 в PRD); он станет читаемым, когда кандидат опубликует профиль или снимет скрытие. Любое изменение видимости после появления grant отзывает его (`visibility_closed`), и повторная публикация его не открывает. - Значения контактов передаются только в `ContactDisclosure` из `GetOrganizationInvitationContacts`, отдельно от условий и приглашения. Каждое чтение проверяет членство, C4, grant и его поля и текущую видимость без кеша. Без читаемого grant операция отвечает 404 `not_found`, как для неизвестного приглашения. `contact_access` организации - `not_granted` (grant нет), `available` (с видами полей) или `closed`, что покрывает и отозванный grant, и grant, заблокированный с самого начала, не говоря, какой из них. Это наименее раскрывающее правило: отзыв, скрытие и отсутствие публикации выглядят одинаково, а поскольку любое изменение видимости после появления grant его отзывает, организация не наблюдает последующих переключений; стать `available` может только grant, заблокированный с начала, и лишь по собственному выбору кандидата. Поля вне grant равны null. -- Отзыв: `CancelMyInvitation` отзывает grant этого приглашения (`participation_cancelled`); отзыв C4 для организации закрывает все ее grants (`consent_revoked`, TASK-064); отзыв C2 или скрытие профиля закрывает их (`visibility_closed`). Отзыв приглашения, `no_deal` и таймаут финала grant не отзывают; новый grant создает только новое явное C4. Отдельная операция отзыва grant относится к контракту согласий (TASK-064, TASK-202). -- Форматы значений: ФИО одной строкой до 200 символов, телефон в формате E.164 и имя пользователя Telegram с ведущим @. Контракт профиля (FR02, TASK-066) должен хранить контакты в тех же форматах, чтобы раскрытие не преобразовывало и не отбрасывало сохраненное значение. +- Отзыв: `CancelMyInvitation` отзывает grant этого приглашения (`participation_cancelled`); отзыв C4 для организации закрывает все ее grants (`consent_revoked`); отзыв C2 или скрытие профиля закрывает их (`visibility_closed`). Отзыв приглашения, `no_deal` и таймаут финала grant не отзывают; новый grant создает только новое явное C4. Отдельная операция отзыва grant относится к контракту согласий. +- Форматы значений: ФИО одной строкой до 200 символов, телефон в формате E.164 и имя пользователя Telegram с ведущим @. Контракт профиля (FR02) должен хранить контакты в тех же форматах, чтобы раскрытие не преобразовывало и не отбрасывало сохраненное значение. Отказ и приватность: @@ -526,7 +526,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro ### Согласия -Тег `consent` описывает журнал согласий текущего аккаунта (FR01, FR12 и 7.3 в PRD): независимые согласия C1-C5 с версиями текстов, источниками, состояниями и отзывами. Операция чтения есть в контракте, но ее обработчик еще не реализован, поэтому до появления сессий она отвечает 401 `unauthenticated` (`v1.DenyAllSecurity`). Хранение за ней уже есть (TASK-062, см. [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#журнал-согласий)). +Тег `consent` описывает журнал согласий текущего аккаунта (FR01, FR12 и 7.3 в PRD): независимые согласия C1-C5 с версиями текстов, источниками, состояниями и отзывами. Операция чтения есть в контракте, но ее обработчик еще не реализован, поэтому до появления сессий она отвечает 401 `unauthenticated` (`v1.DenyAllSecurity`). Хранение за ней уже есть (см. [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#журнал-согласий)). | Метод и путь | operationId | Защита | Успех | Конкретные ошибки | | --- | --- | --- | --- | --- | @@ -534,9 +534,9 @@ ML-сервис отвечает на ошибки той же схемой `Pro - Цели (`ConsentPurposeCode`): `c1` - обработка персональных данных, `c2` - публикация карточки кандидата, `c3` - автоматическая категоризация, `c4` - передача выбранных контактов одной организации, `c5` - импорт результатов ФСП. `ConsentPurpose` остается подмножеством, текст которого доступен до регистрации (`c1`), поэтому `GetConsentText` не расширяется. - Субъект берется из сессии; ни один параметр не называет аккаунт, поэтому ответ содержит только собственные записи вызывающего. Страница перечисляет записи от новой выдачи к старой с курсорной пагинацией; необязательный фильтр `state` принимает `active`, `superseded` или `revoked`, а неизвестное значение отвечает 400 с указателем `/state`. -- `ConsentRecord` содержит цель, принятую `text_version`, `source` (`registration`, `consent_settings` или `invitation_acceptance`), `granted_at`, вычисленное `state`, а также `revoked_at` и `revocation_source` (`consent_settings` или `support_request`). Запись `c4` дополнительно называет `organization` (`ConsentOrganization`, где `name` - снимок названия из текста согласия, поэтому последующее переименование его не меняет), поля контакта `fields` (`ContactFieldKind`), `invitation_id` и `invitation_terms_version`; для остальных целей они равны null. Запись `c2` доказывает согласие с текстом публикации; какие поля и когда опубликованы - доказательства истории публикации ([Видимость кандидата](#видимость-кандидата), TASK-088), а scope полей в записях `c2` был бы аддитивным изменением. Запись никогда не содержит значения контакта, субъекта или хэш текста: сервер хранит SHA-256 ровно того текста, который видел субъект, а клиент его не отправляет и не получает, как и для C1 при регистрации. +- `ConsentRecord` содержит цель, принятую `text_version`, `source` (`registration`, `consent_settings` или `invitation_acceptance`), `granted_at`, вычисленное `state`, а также `revoked_at` и `revocation_source` (`consent_settings` или `support_request`). Запись `c4` дополнительно называет `organization` (`ConsentOrganization`, где `name` - снимок названия из текста согласия, поэтому последующее переименование его не меняет), поля контакта `fields` (`ContactFieldKind`), `invitation_id` и `invitation_terms_version`; для остальных целей они равны null. Запись `c2` доказывает согласие с текстом публикации; какие поля и когда опубликованы - доказательства истории публикации ([Видимость кандидата](#видимость-кандидата)), а scope полей в записях `c2` был бы аддитивным изменением. Запись никогда не содержит значения контакта, субъекта или хэш текста: сервер хранит SHA-256 ровно того текста, который видел субъект, а клиент его не отправляет и не получает, как и для C1 при регистрации. - Журнал только дополняется. Новая версия текста цели - новая запись, а прежняя становится `superseded` без изменений; отзыв один раз ставит отметку на неотозванные записи цели, а для `c4` - одной организации; последующая выдача - новая запись, и отозванное `c4` приглашения не возвращается. Цели независимы. -- Запланировано, аддитивно: выдача C1, C2, C3 и C5 в настройках согласий (TASK-063) и отзыв любой цели с последствиями (TASK-064) новыми операциями этого тега; у C1 при регистрации и C4 в `AcceptMyInvitation` уже есть свои операции. Разрешение C4 на передачу данных в ATS и C4 при отклике (Q9 в PRD) запланированы как аддитивный флаг и дополнительное значение `source`. +- Запланировано, аддитивно: выдача C1, C2, C3 и C5 в настройках согласий и отзыв любой цели с последствиями новыми операциями этого тега; у C1 при регистрации и C4 в `AcceptMyInvitation` уже есть свои операции. Разрешение C4 на передачу данных в ATS и C4 при отклике (Q9 в PRD) запланированы как аддитивный флаг и дополнительное значение `source`. Открытый юридический вопрос: является ли `c2` согласием на распространение персональных данных по статье 10.1 152-ФЗ, которое требует отдельного согласия с категориями данных. @@ -544,7 +544,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro ### Организации -Тег `organization` описывает организации аккаунтов работодателя и членства, которые дают аккаунту роль в них (FR07, 2.2 и 6.4 в PRD): профиль с публичными контактами и представителями, уровень проверки, который задает только сервер, и активный контекст организации. Операции есть в контракте, но их бизнес-логика еще не реализована, поэтому до появления сессий каждая отвечает 401 `unauthenticated` (`v1.DenyAllSecurity`). Хранение за ними уже есть (TASK-077, см. [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#организации-и-членства)); создание, редактирование и проверки членства в остальных операциях запланированы в TASK-078 и TASK-079. +Тег `organization` описывает организации аккаунтов работодателя и членства, которые дают аккаунту роль в них (FR07, 2.2 и 6.4 в PRD): профиль с публичными контактами и представителями, уровень проверки, который задает только сервер, и активный контекст организации. Операции есть в контракте, но их бизнес-логика еще не реализована, поэтому до появления сессий каждая отвечает 401 `unauthenticated` (`v1.DenyAllSecurity`). Хранение за ними уже есть (см. [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#организации-и-членства)); создание, редактирование и проверки членства в остальных операциях запланированы в управлении организациями и контроле доступа. | Метод и путь | operationId | Защита | Успех | Конкретные ошибки | | --- | --- | --- | --- | --- | @@ -555,10 +555,10 @@ ML-сервис отвечает на ошибки той же схемой `Pro Каждая операция также объявляет problem-ответ `default`. Некорректный `org_id` отвечает 400 с указателем пути. -Активный контекст организации (решение TASK-077): +Активный контекст организации: - Контекст не хранится на сервере. Каждая операция в области организации, включая потребности и приглашения этого контракта, называет организацию в пути `org_id`, а сервер на каждом запросе проверяет этот идентификатор по активному членству аккаунта сессии. Сам идентификатор ничего не дает; переключение между организациями - это другой `org_id` в маршрутах клиента. -- Причина: атрибут сессии был бы кешем членства, который пришлось бы сбрасывать при удалении, приостановке или выходе (TASK-079 требует закрыть следующее чтение, а не ждать истечения кеша браузера), две вкладки в двух организациях спорили бы за одно значение, а форма с путем уже является контрактом потребностей и приглашений. TASK-085 очищает клиентские запросы с областью организации при переключении, что согласуется с клиентским контекстом. +- Причина: атрибут сессии был бы кешем членства, который пришлось бы сбрасывать при удалении, приостановке или выходе (нужно закрыть следующее чтение, а не ждать истечения кеша браузера), две вкладки в двух организациях спорили бы за одно значение, а форма с путем уже является контрактом потребностей и приглашений. Переключение организации очищает клиентские запросы с ее областью, что согласуется с клиентским контекстом. - `ListMyOrganizations` - справочник контекстов: организации, где у вызывающего `active` членство, от нового членства к старому, с ролью и состоянием вызывающего. Клиент выбирает контекст из него, может помнить последний выбор в браузере для удобства и перечитывает список после 404 по пути организации. Человек с несколькими членствами видит все и работает в одной за раз; права и данные организаций остаются раздельными. Доступ: @@ -569,10 +569,10 @@ ML-сервис отвечает на ошибки той же схемой `Pro Членства: -- Членство - это `(пользователь, организация, роль, состояние)`, уникальное для пары в любом состоянии. `OrganizationRole` содержит `owner`, `recruiter`, `hiring_manager` и `technical_expert` (2.2 и Q3 в PRD). `MembershipState` содержит `active`, `suspended` (доступ остановлен, можно вернуть), `removed` (завершено владельцем или платформой) и `left` (завершено участником). Доступ дает только `active`, и список возвращает только `active` членства; `joined_at` - момент первого создания членства (вернувшийся участник сохраняет его, а время последней активации - запланированное поле `activated_at` в TASK-082); членство `removed` по решению платформы не должно само возвращаться в работу по решению владельца, принятию приглашения или управлению участниками (TASK-082, TASK-084), а кто и почему удалил участника - аддитивные поля управления участниками; остальные состояния есть в enum, чтобы управление участниками могло их показывать без изменения контракта. Добавление роли или состояния - изменение контракта. +- Членство - это `(пользователь, организация, роль, состояние)`, уникальное для пары в любом состоянии. `OrganizationRole` содержит `owner`, `recruiter`, `hiring_manager` и `technical_expert` (2.2 и Q3 в PRD). `MembershipState` содержит `active`, `suspended` (доступ остановлен, можно вернуть), `removed` (завершено владельцем или платформой) и `left` (завершено участником). Доступ дает только `active`, и список возвращает только `active` членства; `joined_at` - момент первого создания членства (вернувшийся участник сохраняет его, а время последней активации - запланированное поле `activated_at`); членство `removed` по решению платформы не должно само возвращаться в работу по решению владельца, принятию приглашения или управлению участниками, а кто и почему удалил участника - аддитивные поля управления участниками; остальные состояния есть в enum, чтобы управление участниками могло их показывать без изменения контракта. Добавление роли или состояния - изменение контракта. - Роль живет только в членстве. В `Organization`, `OrganizationCreate`, `OrganizationUpdate` и `CandidateOrganizationCard` нет поля роли, владельца или участника. Свою роль вызывающий читает в `OrganizationMembership` из `ListMyOrganizations`; DTO не называет аккаунт. -- Состояния `invited` нет: сотрудник попадает в организацию только по приглашению на email (2.2 в PRD), которое задачи приглашения сотрудников хранят отдельной записью и превращают в `active` членство, когда владелец адреса его принимает (TASK-081 и TASK-082). Человек может иметь независимые членства в нескольких организациях. -- Применение полной матрицы ролей (рекрутер, нанимающий менеджер, техэксперт) к потребностям, приглашениям и контактам запланировано в TASK-083 и TASK-463. До этого остальные роли ничего не дают: операции потребностей и приглашений отвечают им 403 `forbidden`, как сказано в их разделах. Список и управление участниками, смена ролей, удаление участников и правило, что последнего владельца удалить нельзя, запланированы в TASK-084 и TASK-085 и добавляют в контракт операции, а не поля. +- Состояния `invited` нет: сотрудник попадает в организацию только по приглашению на email (2.2 в PRD), которое задачи приглашения сотрудников хранят отдельной записью и превращают в `active` членство, когда владелец адреса его принимает. Человек может иметь независимые членства в нескольких организациях. +- Применение полной матрицы ролей (рекрутер, нанимающий менеджер, техэксперт) к потребностям, приглашениям и контактам запланировано в ролевом контроле доступа. До этого остальные роли ничего не дают: операции потребностей и приглашений отвечают им 403 `forbidden`, как сказано в их разделах. Список и управление участниками, смена ролей, удаление участников и правило, что последнего владельца удалить нельзя, запланированы в управлении участниками и добавляют в контракт операции, а не поля. Профиль: @@ -584,9 +584,9 @@ ML-сервис отвечает на ошибки той же схемой `Pro Уровень проверки: -- `OrganizationVerificationLevel` - `e0`, `e1`, `e2` или `e3` (FR07 в PRD). Новая организация начинает с `e0` на основании `confirmed_email`, как бы ни выглядел ее профиль. Более высокий уровень сервер сообщает только после того, как его записал процесс проверки; процессов для `e1`, `e2` и `e3` еще нет (TASK-086 добавляет E0/E1 с доказательствами, областью действия и историей), поэтому клиент считает любой уровень, кроме `e0`, недоступным, а контракт никогда не сообщает `e1`, `e2` или `e3` достигнутыми сами по себе. +- `OrganizationVerificationLevel` - `e0`, `e1`, `e2` или `e3` (FR07 в PRD). Новая организация начинает с `e0` на основании `confirmed_email`, как бы ни выглядел ее профиль. Более высокий уровень сервер сообщает только после того, как его записал процесс проверки; процессов для `e1`, `e2` и `e3` еще нет (запланированный процесс проверки добавляет E0/E1 с доказательствами, областью действия и историей), поэтому клиент считает любой уровень, кроме `e0`, недоступным, а контракт никогда не сообщает `e1`, `e2` или `e3` достигнутыми сами по себе. - Ни один запрос не задает и не повышает уровень или его основание: `OrganizationCreate` и `OrganizationUpdate` - закрытые объекты только с полями профиля, ни одна операция контракта не меняет уровень, а правка описания, контактов или представителей оставляет его как есть. База держит уровень и основание в отдельных столбцах, которые оператор обновления профиля никогда не пишет, а CHECK связывает каждый уровень с его основаниями. `OrganizationVerification` только для чтения: `level`, `basis` и `changed_at`; область проверки и история изменений (FR07 в PRD) придут аддитивными полями с первым процессом. -- Уровень выбирает ступень квот (E0 10 приглашений и 50 карточек, E1 40 и 150, E2 100 и 400 в демо-политике); `domain.OrganizationVerificationLevel.QuotaTier` сопоставляет `e0`-`e2` ступеням политики и не имеет ступени для `e3`, которому PRD отводит отдельную политику. Сами квоты - TASK-087. +- Уровень выбирает ступень квот (E0 10 приглашений и 50 карточек, E1 40 и 150, E2 100 и 400 в демо-политике); `domain.OrganizationVerificationLevel.QuotaTier` сопоставляет `e0`-`e2` ступеням политики и не имеет ступени для `e3`, которому PRD отводит отдельную политику. Применение квот - отдельная запланированная функция. Карточка кандидата и версии: @@ -594,22 +594,22 @@ ML-сервис отвечает на ошибки той же схемой `Pro - `version` начинается с 1 и растет с каждым зафиксированным изменением профиля. Изменение несет `expected_version` в теле по той же причине, что и потребности: сгенерированный клиент пока не читает `ETag`. Устаревшее значение отвечает 412 `version_conflict` и ничего не меняет; правило репозитория сохраняет 412 для устаревшей версии, как и для потребностей. Тело без изменений отвечает 200 с текущей организацией, поэтому PATCH не нужен Idempotency-Key. POST нужен ключ с повтором на 24 часа; сохраняется только 201. - Порядок проверок `UpdateOrganization`: сессия (401), CSRF и Origin (403), валидация запроса (400), сценарий аккаунта (403), членство (404) и роль (403), тело без изменений (200), версия (412), доменные правила (400). -Внешние ключи на организации: `memberships` и `organization_representatives` ссылаются на `organizations(id)` уже сейчас. Журнал согласий, потребности и приглашения несут `organization_id` и ссылаются на него ограничивающим внешним ключом в миграции, создающей записи приглашений (TASK-198), потому что для области C4 нужны сразу обе ссылки, а тесты журнала TASK-062 и TASK-063 используют синтетические идентификаторы организаций. Приложение никогда не удаляет организацию. +Внешние ключи на организации: `memberships` и `organization_representatives` ссылаются на `organizations(id)` уже сейчас. Журнал согласий, потребности и приглашения несут `organization_id` и ссылаются на него ограничивающим внешним ключом в миграции, создающей записи приглашений, потому что для области C4 нужны сразу обе ссылки, а тесты журнала согласий используют синтетические идентификаторы организаций. Приложение никогда не удаляет организацию. Открытые вопросы к владельцу продукта: - Представители: может ли карточка показывать их имена любому кандидату до принятия приглашения и кто отвечает за право публиковать имя сотрудника (152-ФЗ)? Альтернатива - показывать представителей только в приглашении, отправленном их организацией. -- Организаций на аккаунт (блокирует TASK-078 и TASK-087): в PRD лимита нет, а FR07 говорит, что квоты принадлежат организации целиком и сами не растут, но ничто не мешает одному аккаунту создать много организаций, каждая из которых начинает с `e0` со своей квотой, что умножает квоты. Этот контракт не придумывает число. Механизм готов: ограничение отвечало бы 409 `state_conflict` на `CreateOrganization` без изменения схемы, а сигналы против злоупотреблений - TASK-319. Владелец продукта должен решить лимит или явно принять риск до того, как квоты TASK-087 начнут применяться и до того, как `CreateOrganization` откроют пользователям. +- Организаций на аккаунт (блокирует создание организаций и применение квот): в PRD лимита нет, а FR07 говорит, что квоты принадлежат организации целиком и сами не растут, но ничто не мешает одному аккаунту создать много организаций, каждая из которых начинает с `e0` со своей квотой, что умножает квоты. Этот контракт не придумывает число. Механизм готов: ограничение отвечало бы 409 `state_conflict` на `CreateOrganization` без изменения схемы, а сигналы против злоупотреблений относятся к оценке риска организации. Владелец продукта должен решить лимит или явно принять риск до того, как квоты организации начнут применяться и до того, как `CreateOrganization` откроют пользователям. - Сфера: пока свободный текст; таксономия сферы, согласованная с доменами потребностей, - решение для поисковых фильтров. - Контакты: нужен ли в карточке пятый вид, например страница вакансий, и должна ли почта совпадать с доменом сайта. -Запланировано, аддитивно: приглашения участников, список, смена ролей и удаление (TASK-081 - TASK-085), полная матрица ролей (TASK-463), процессы проверки и их история (TASK-086), квоты по уровню (TASK-087), карточка в приглашении кандидата, ограничение числа организаций и код сферы. +Запланировано, аддитивно: приглашения участников, список, смена ролей и удаление, полная матрица ролей, процессы проверки и их история, квоты по уровню, карточка в приглашении кандидата, ограничение числа организаций и код сферы. Новый код problem не добавляется: контракт использует `validation_failed`, `unauthenticated`, `forbidden`, `csrf_check_failed`, `not_found`, `version_conflict`, `idempotency_in_progress`, `idempotency_key_reused` и `rate_limited`. `TestOrganizationSchemaValidationPrecedesImplementation`, `TestOrganizationAccessBeforeImplementation`, `TestOrganizationDTOsCarryNoRoleOrVerificationInTheirRequests`, `TestOrganizationUpdateDecodingKeepsAbsentAndEmptyListsApart` и `TestOrganizationContractFollowsThePRD` закрепляют сгенерированный сервер и бандл, а `frontend/src/shared/api/organization-contract.test.ts` - сгенерированные правила Zod и, на уровне типов, отсутствие полей роли, владельца, участников и уровня проверки в запросах. ### Видимость кандидата -Тег `privacy` описывает, что организации могут видеть о текущем кандидате: публикацию анонимной карточки, статус поиска, организации, от которых кандидат скрывает профиль, предпросмотр и две истории (FR02 и FR12 в PRD, TASK-088). Операции есть в контракте, но их бизнес-логика еще не реализована, поэтому каждая отвечает 401 `unauthenticated`, пока сессий нет (`v1.DenyAllSecurity`), а после принятой сессии и валидного запроса - 501 `not_implemented`. Хранение за ними уже есть (миграция 00015, см. [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#видимость-кандидата)). +Тег `privacy` описывает, что организации могут видеть о текущем кандидате: публикацию анонимной карточки, статус поиска, организации, от которых кандидат скрывает профиль, предпросмотр и две истории (FR02 и FR12 в PRD). Операции есть в контракте, но их бизнес-логика еще не реализована, поэтому каждая отвечает 401 `unauthenticated`, пока сессий нет (`v1.DenyAllSecurity`), а после принятой сессии и валидного запроса - 501 `not_implemented`. Хранение за ними уже есть (миграция 00015, см. [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#видимость-кандидата)). | Метод и путь | operationId | Защита | Успех | Конкретные ошибки | | --- | --- | --- | --- | --- | @@ -628,7 +628,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro Закрыто по умолчанию и три независимые настройки: - Профиль закрыт по умолчанию. Кандидат, который никогда не публиковал, читает `publication.state` `closed`, `closed_reason` `never_published`, пустой набор полей и версию 0; сохранение профиля, заполнение анкеты и оценка его не публикуют. У каждой настройки своя `version` (0 - "никогда не задавалась"), своя операция и свой `expected_version` в теле, поэтому изменение одной никогда не делает устаревшей другую. -- Публикация и C2 разделены. Согласие C2 остается в журнале согласий (`ListMyConsents`) и доказывает, что кандидат принял текст публикации. `Publication` хранит, какие поля опубликованы и когда, и ссылается на запись C2 за ними (`consent_id` - `id` записи `ConsentRecord` того же аккаунта). Она не дублирует согласие: `state` равен `published`, только пока эта запись не отозвана, поэтому отзыв C2 закрывает карточку сразу, а `closed_reason` показывает `consent_revoked`. Новая выдача C2 карточку не открывает: кандидат публикует заново, и новая публикация привязывается к новой записи. Тело `SetMyPublication` не называет согласие: сервер привязывает текущую неотозванную запись C2 аккаунта, а без нее отвечает 409 `state_conflict` (кандидат сначала дает C2; операция выдачи запланирована в настройках согласий, TASK-063). +- Публикация и C2 разделены. Согласие C2 остается в журнале согласий (`ListMyConsents`) и доказывает, что кандидат принял текст публикации. `Publication` хранит, какие поля опубликованы и когда, и ссылается на запись C2 за ними (`consent_id` - `id` записи `ConsentRecord` того же аккаунта). Она не дублирует согласие: `state` равен `published`, только пока эта запись не отозвана, поэтому отзыв C2 закрывает карточку сразу, а `closed_reason` показывает `consent_revoked`. Новая выдача C2 карточку не открывает: кандидат публикует заново, и новая публикация привязывается к новой записи. Тело `SetMyPublication` не называет согласие: сервер привязывает текущую неотозванную запись C2 аккаунта, а без нее отвечает 409 `state_conflict` (кандидат сначала дает C2; операция выдачи запланирована в настройках согласий). - Статус поиска - не согласие. В `SearchStatus` и `SearchStatusUpdate` нет свойств согласия, публикации или организации, схемы одного семейства не достигают другого (тест обходит ссылки), а `SetMySearchStatus` не меняет ничего, кроме статуса. Кандидат с закрытым профилем, который задал `looking`, не становится видимым никому. - Скрытые организации - записи кандидата (`HiddenOrganization`: организация с ее текущим названием и `hidden_at`). Одна запись на кандидата и организацию, не более 1000 на кандидата. Организация их не читает, не узнает, что скрыта, и видит скрывшего кандидата так же, как неопубликованного. Скрытие и его снятие не меняют ни C2, ни публикацию, ни статус поиска. - Скрытие - это PUT состояния, поэтому оно идемпотентно и не требует Idempotency-Key: повторное скрытие отвечает 200 с исходной записью и не пишет историю. Снятие - DELETE, который отвечает 204, была организация скрыта или нет. @@ -637,16 +637,16 @@ ML-сервис отвечает на ошибки той же схемой `Pro - `looking` ("Ищу") хранит `confirmed_at` и `lapses_at`. Срок - не константа контракта или кода: это `search_status.searching_confirmation_interval_days` действующей версии политики `product` (в демо-версии 1 - 30), прочитанное при подтверждении статуса. Строка называет версию политики, которой воспользовалась, и фиксирует `lapses_at`, поэтому последующее изменение политики не сдвигает сохраненные времена. Владелец меняет срок публикацией новой версии политики. - После `lapses_at` статус действует как `not_looking` с `lapsed` true. Истечение вычисляется при каждом чтении и нигде не записывается, поэтому не требует задачи и может только сужать: оно никогда не публикует, не снимает скрытие и не меняет C2 или скрытые организации. Кандидат подтверждает снова через `SetMySearchStatus` со значением `looking`, которое заменяет `confirmed_at` и увеличивает версию. Напоминание до истечения - запланированное уведомление. -- Истекший статус никогда не становится "более публичным": единственное состояние, до которого доходит истечение, - непубличное `not_looking`. Влияет ли `looking` на появление опубликованной карточки в выдаче поиска - решение контракта поиска (TASK-185), здесь не принято. +- Истекший статус никогда не становится "более публичным": единственное состояние, до которого доходит истечение, - непубличное `not_looking`. Влияет ли `looking` на появление опубликованной карточки в выдаче поиска - решение контракта поиска, здесь не принято. Анонимная карточка и предпросмотр: - `CardField` - закрытый набор групп значений карточки, которые кандидат выбирает публиковать: `categories` (категории, подтвержденные результатами оценки), `stack`, `experience` (суммарно в месяцах), `soft_skills`, `location` и `relocation`. У полного имени, любого контакта и минимальной зарплаты значения нет, поэтому ни один запрос не может их опубликовать; контакты доходят до организации только через контактное разрешение принятого приглашения (C4), а минимальная зарплата не доходит никогда. Самооценка грейда не категория и никогда не публикуется. Сервер хранит и отдает набор в порядке возрастания кодов. -- `AnonymousCardContent` - карточка так, как ее читает организация: закрытый объект из шести свойств выше, каждое равно null, если не опубликовано или значения нет, поэтому карточка не различает эти случаи. В ней нет имени, email, телефона, имени в Telegram, работодателя, суммы зарплаты, идентификатора аккаунта или профиля, и из нее недостижима ни одна схема приватного профиля, контакта, согласия, приглашения или организации (`TestAnonymousCardReachesNoProfileOrContactSchema` обходит ссылки). `GetMyCardPreview` возвращает ее с опубликованными полями или `card` null, пока профиль закрыт, как приватное чтение, которое не создает просмотра и записи в истории. Карточка результата поиска организации (TASK-185) должна использовать это содержимое и не вправе добавлять свойство, идентифицирующее кандидата. +- `AnonymousCardContent` - карточка так, как ее читает организация: закрытый объект из шести свойств выше, каждое равно null, если не опубликовано или значения нет, поэтому карточка не различает эти случаи. В ней нет имени, email, телефона, имени в Telegram, работодателя, суммы зарплаты, идентификатора аккаунта или профиля, и из нее недостижима ни одна схема приватного профиля, контакта, согласия, приглашения или организации (`TestAnonymousCardReachesNoProfileOrContactSchema` обходит ссылки). `GetMyCardPreview` возвращает ее с опубликованными полями или `card` null, пока профиль закрыт, как приватное чтение, которое не создает просмотра и записи в истории. Карточка результата поиска организации должна использовать это содержимое и не вправе добавлять свойство, идентифицирующее кандидата. Версии и проверки: -- Обе операции `PUT` настроек следуют образцу профиля: полное новое состояние в теле, `expected_version` в теле (сгенерированный клиент пока не читает ETag), 412 `version_conflict` для устаревшей или несуществующей версии, а тело без изменений отвечает 200 с текущим состоянием даже при устаревшей версии, поэтому Idempotency-Key не нужен. Порядок проверок: сессия (401), CSRF и Origin (403), валидация запроса (400), сценарий аккаунта (403), версия выше текущей (412), неизмененное состояние (200), устаревшая версия (412), затем C2 для публикации (409). Состояние `published` без поля и `closed` с полем отвечают 400 с указателем `/fields`; схема отклоняет неизвестное или повторное поле карточки и неизвестные свойства, например идентификатор согласия или время подтверждения. `looking` всегда меняет сохраненное подтверждение, поэтому при устаревшей версии отвечает 412 даже как повтор. Два вида 409 `state_conflict` различаются через `errors`: `{in: body, pointer: /state, code: consent_required}` для публикации без действующей C2 и `{in: path, pointer: /org_id, code: limit_reached}` для 1001-й скрытой организации. Закрытие поверх сохраненной публикации с отозванной C2 - настоящее изменение (сохраняет закрытие, пишет `publication_closed` и отзывает разрешения); путь отзыва C2 (TASK-064) сам закрывает сохраненную публикацию и отзывает разрешения в своей транзакции. Публикации, скрытию и истории нужен подтвержденный email (требование юзкейса). `Problem.errors` не только для `validation_failed`: `state_conflict` несет одну запись как уточнение (`consent_required`, `limit_reached`), поэтому будущий писатель problem не должен вырезать `errors` из ответов, не связанных с валидацией. В карточку попадают только подтвержденные значения, свободный текст, похожий на контакт (email, телефон, URL, ссылка Telegram, @handle), отбрасывается, а новое поле карточки - это изменение контракта и миграция. +- Обе операции `PUT` настроек следуют образцу профиля: полное новое состояние в теле, `expected_version` в теле (сгенерированный клиент пока не читает ETag), 412 `version_conflict` для устаревшей или несуществующей версии, а тело без изменений отвечает 200 с текущим состоянием даже при устаревшей версии, поэтому Idempotency-Key не нужен. Порядок проверок: сессия (401), CSRF и Origin (403), валидация запроса (400), сценарий аккаунта (403), версия выше текущей (412), неизмененное состояние (200), устаревшая версия (412), затем C2 для публикации (409). Состояние `published` без поля и `closed` с полем отвечают 400 с указателем `/fields`; схема отклоняет неизвестное или повторное поле карточки и неизвестные свойства, например идентификатор согласия или время подтверждения. `looking` всегда меняет сохраненное подтверждение, поэтому при устаревшей версии отвечает 412 даже как повтор. Два вида 409 `state_conflict` различаются через `errors`: `{in: body, pointer: /state, code: consent_required}` для публикации без действующей C2 и `{in: path, pointer: /org_id, code: limit_reached}` для 1001-й скрытой организации. Закрытие поверх сохраненной публикации с отозванной C2 - настоящее изменение (сохраняет закрытие, пишет `publication_closed` и отзывает разрешения); путь отзыва C2 сам закрывает сохраненную публикацию и отзывает разрешения в своей транзакции. Публикации, скрытию и истории нужен подтвержденный email (требование юзкейса). `Problem.errors` не только для `validation_failed`: `state_conflict` несет одну запись как уточнение (`consent_required`, `limit_reached`), поэтому будущий писатель problem не должен вырезать `errors` из ответов, не связанных с валидацией. В карточку попадают только подтвержденные значения, свободный текст, похожий на контакт (email, телефон, URL, ссылка Telegram, @handle), отбрасывается, а новое поле карточки - это изменение контракта и миграция. - 404 и защита от перебора. `HideOrganization` отвечает одинаковым 404 `not_found`, с тем же телом и без другого времени ответа, и для несуществующей организации, и для той, которую кандидат не видит, поэтому операция не позволяет спросить, принадлежит ли идентификатор организации. Кандидат видит организацию, приславшую ему приглашение, и организации, которые покажет поиск организаций для кандидата (запланирован). Идентификаторы случайные, а общий лимит запросов может ответить 429 с Retry-After до любой проверки. `UnhideOrganization` ничего не раскрывает: 204 на любой корректный идентификатор. Некорректный `org_id` отвечает 400 с указателем `/org_id`. - Контактные разрешения. Закрытие публикации и скрытие организации, у которой есть активное контактное разрешение, отзывают его с причиной `visibility_closed` в той же транзакции, что и изменение (запланировано вместе с операциями; причину задает контракт приглашений). Снятие скрытия и повторная публикация разрешение не возвращают. Статус поиска разрешение никогда не отзывает. @@ -658,17 +658,17 @@ ML-сервис отвечает на ошибки той же схемой `Pro Открытые вопросы к владельцу продукта и юристу: - Значения статуса поиска: в контракте `looking` и `not_looking`. Нужен ли по PRD третий статус, например "открыт к предложениям", не решено; значение - аддитивное изменение. -- Влияет ли `looking` на появление опубликованной карточки в поиске (организация видит только ищущих) или это только метка. Это определяет смысл истечения для видимости и относится к контракту поиска (TASK-185). +- Влияет ли `looking` на появление опубликованной карточки в поиске (организация видит только ищущих) или это только метка. Это определяет смысл истечения для видимости и относится к контракту поиска. - Набор полей карточки. Шесть значений - предложение, согласованное с профилем; карточка в PRD (FR11) может добавить, разделить или убрать часть, например обобщенную отрасль и размер работодателя вместо работодателей, и каждое изменение аддитивно для контракта. - Нужен ли для публикации минимум: хотя бы одна подтвержденная категория или сохраненный профиль. Контракт требует только одно поле карточки и действующую C2. - Должно ли сужение опубликованных полей, а не только закрытие публикации или скрытие организации, отзывать контактные разрешения. Контракт приглашений говорит, что любое изменение видимости после разрешения его отзывает; этот контракт отзывает только при закрытии и скрытии. - Как кандидат находит организацию, чтобы скрыть ее до любого приглашения. Контракт скрывает по идентификатору и отвечает 404 на организацию, которую кандидат не видит, поэтому заранее скрыть текущего работодателя можно только при поиске организаций для кандидата (по названию или домену), который сам должен быть защищен от перебора (минимальная длина запроса, лимит, только публичные данные). Без него скрытие работает только для организаций, которые уже написали кандидату. - Должен ли кандидат узнавать название организации, которая смотрела карточку без приглашения (`CardAccess.organization`), и сколько хранятся обращения. - Предел скрытых организаций (сейчас 1000) и срок хранения настроек и их истории вместе с доказательствами согласий (152-ФЗ, PRD 7.3). История ссылается на аккаунт с `ON DELETE CASCADE` под защитой двух триггеров: UPDATE запрещен всегда, а DELETE (и удаление аккаунта) запрещен, пока аккаунт подтвержден, как у журнала согласий; очистка неподтвержденных аккаунтов удаляет историю удаляемого аккаунта, а процедура удаления аккаунта расширит условие. -- Свободный текст в карточке (теги стека, софт-скиллы, место) защищает только `CardTextLooksLikeContact`, который ошибается в сторону отбрасывания (Socket.io отбрасывается, а простая обфускация все же может пройти); остаточный риск закрывает TASK-089 закрытой таксономией вместо свободного текста. +- Свободный текст в карточке (теги стека, софт-скиллы, место) защищает только `CardTextLooksLikeContact`, который ошибается в сторону отбрасывания (Socket.io отбрасывается, а простая обфускация все же может пройти); для устранения остаточного риска построителю карточки еще нужна закрытая таксономия вместо свободного текста. - Является ли C2 согласием на распространение персональных данных по статье 10.1 152-ФЗ и нужна ли ей собственная область полей (см. Согласия); пока поля и времена хранит история. - Требует ли новая версия текста C2 повторного согласия кандидата для уже существующей публикации. Сейчас публикация действует, пока ее запись C2 не отозвана, поэтому более новая версия текста, которую кандидат не принимал, ее не закрывает. -- Квазиидентификаторы и k-анонимность карточки: редкое сочетание места, стека и опыта может идентифицировать кандидата и без имени. Обобщение редких признаков и минимальный размер группы - критерии приемки TASK-089, который строит карточку; здесь контракт фиксирует только закрытый набор полей, правило "только подтвержденные значения" и отбрасывание свободного текста, похожего на контакт. +- Квазиидентификаторы и k-анонимность карточки: редкое сочетание места, стека и опыта может идентифицировать кандидата и без имени. Обобщение редких признаков и минимальный размер группы - критерии приемки построителя карточки; здесь контракт фиксирует только закрытый набор полей, правило "только подтвержденные значения" и отбрасывание свободного текста, похожего на контакт. - Хранение и право на удаление истории настроек. Записи о скрытии и снятии скрытия чувствительны (они говорят, каких работодателей кандидат избегает). История хранится как доказательства согласий и не удаляется, пока аккаунт подтвержден; может ли кандидат стереть ее, когда и как это согласуется с трехлетним хранением согласий (PRD 7.3) - открытый юридический вопрос. Процедура удаления аккаунта расширит условие удаления таблицы. Новый код problem не добавляется. `TestPrivacyOperationsFollowTheConventions`, `TestPublicationAndSearchStatusAreNotConsents`, `TestAnonymousCardReachesNoProfileOrContactSchema`, `TestGeneratedPrivacyDTOsCarryNoServerOwnedFields`, `TestPrivacySchemaValidationPrecedesImplementation` и `TestPrivacyAccessBeforeImplementation` закрепляют сгенерированный сервер и бандл, а `frontend/src/shared/api/privacy-contract.test.ts` - сгенерированные правила Zod, отсутствие согласия, времени, контакта и зарплаты в типах запросов и карточки и отсутствие настроек в файлах организации, приглашения, потребности, профиля и согласий. diff --git a/api/core/components/schemas.yml b/api/core/components/schemas.yml index 3084456..c35779e 100644 --- a/api/core/components/schemas.yml +++ b/api/core/components/schemas.yml @@ -28,7 +28,7 @@ CandidateHandle: minLength: 1 maxLength: 128 pattern: ^[A-Za-z0-9_-]+$ - description: Opaque reference to a candidate as one organization sees it, taken from a search result card of that organization. It is not the candidate's account or profile identifier, it never contains an email address or a phone number, and it means nothing to another organization. The server resolves it only for the organization in the path. Clients never parse it. It is shared by the invitations of FR12 and the search results of FR11 (TASK-185), which issue it. + description: Opaque reference to a candidate as one organization sees it, taken from a search result card of that organization. It is not the candidate's account or profile identifier, it never contains an email address or a phone number, and it means nothing to another organization. The server resolves it only for the organization in the path. Clients never parse it. It is shared by the invitations of FR12 and the search results of FR11, which issue it. examples: - cand_7Qm2xVb9Lr4Kp0Zt AssessmentMode: @@ -2127,7 +2127,7 @@ ConsentPurposeCode: - c1: processing of personal data, given at registration. - - c2: publication of the candidate card. The record proves the consent to the published text; which fields were published and when is evidence of the publication history (TASK-088), not of this record. Adding a field scope to c2 records later is an additive change. + - c2: publication of the candidate card. The record proves the consent to the published text; which fields were published and when is evidence of the publication history, not of this record. Adding a field scope to c2 records later is an additive change. - c3: automatic categorization. Without it the candidate can request a manual assessment by the same rubric. @@ -2164,7 +2164,7 @@ ConsentSource: - registration: the c1 acceptance of RegisterAccount. - - consent_settings: the consent settings of the account, for c1, c2, c3, and c5 (planned, TASK-063 and TASK-064). + - consent_settings: the consent settings of the account, for c1, c2, c3, and c5 (planned). - invitation_acceptance: the c4 acceptance of AcceptMyInvitation. @@ -2302,7 +2302,7 @@ ContactFieldKind: - telegram: the Telegram username from the profile. - The value formats are those of ContactDisclosure: 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, TASK-066) must store contacts in the same formats, so a disclosure never has to convert or drop a stored value. The FSP results of FR14, which need their own explicit permission, are planned as additional kinds. Adding a value is a contract change.' + The value formats are those of ContactDisclosure: 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 has to convert or drop a stored value. The FSP results of FR14, which need their own explicit permission, are planned as additional kinds. Adding a value is a contract change.' enum: - full_name - email @@ -2310,7 +2310,7 @@ ContactFieldKind: - telegram ContactConsentText: type: object - description: Currently published text of the consent C4 for this invitation. The server stores an acceptance with `text_version` and the hash of exactly this text, together with the organization, the selected fields, the invitation, and its terms version (the ledger of TASK-062). + description: Currently published text of the consent C4 for this invitation. The server stores an acceptance with `text_version` and the hash of exactly this text, together with the organization, the selected fields, the invitation, and its terms version (the consent ledger). additionalProperties: false required: - text_version @@ -2479,7 +2479,7 @@ ContactFullName: description: Full name as the candidate wrote it in the profile. Plain text without line breaks; clients show it as text, never as HTML. ContactDisclosure: type: object - description: Contacts of the candidate that the organization may read through an active grant of this invitation. This is the only response that carries contact values, and it is separate from the terms and from the invitation. Each field the grant does not cover is null, and so is a covered field that the profile no longer holds. The response is never cached or stored by the server for later reads, so a revocation closes the next read at once. The value formats depend on the profile contract (FR02, TASK-066), which must store the same formats; see ContactFieldKind. + description: Contacts of the candidate that the organization may read through an active grant of this invitation. This is the only response that carries contact values, and it is separate from the terms and from the invitation. Each field the grant does not cover is null, and so is a covered field that the profile no longer holds. The response is never cached or stored by the server for later reads, so a revocation closes the next read at once. The value formats depend on the profile contract (FR02), which must store the same formats; see ContactFieldKind. additionalProperties: false required: - invitation_id @@ -3055,7 +3055,7 @@ InvitationSalaryFit: - above: the minimum is more than 10% above `B`. - - withheld: the organization made five indicator-relevant settings within seven days, so the indicator is off for seven days from the fifth (the limit of TASK-211). The response to the fifth setting already carries `withheld`, and so does every draft and invitation of the organization, existing ones included, until the period ends. + - withheld: the organization made five indicator-relevant settings within seven days, so the indicator is off for seven days from the fifth. The response to the fifth setting already carries `withheld`, and so does every draft and invitation of the organization, existing ones included, until the period ends. - not_available: the candidate set no minimum for the offered formats, or set it in the other tax basis. @@ -3584,7 +3584,7 @@ NeedSourceText: type: string minLength: 1 maxLength: 10000 - description: 'Free description of the team''s tasks as the employer wrote or pasted it. The server extracts proposed requirements from it; the text itself is never a requirement. It may contain line breaks. Plain text; clients show it as text, never as HTML. It describes the job and must not contain personal data of candidates. The server stores it as written: it may contain requirements that discriminate by a protected characteristic, and the extractor never turns such a requirement into a need field. Exclusions, the requirements that a candidate must not meet, are planned as a separate additive field with the Labor Code article 64 check (TASK-182).' + description: 'Free description of the team''s tasks as the employer wrote or pasted it. The server extracts proposed requirements from it; the text itself is never a requirement. It may contain line breaks. Plain text; clients show it as text, never as HTML. It describes the job and must not contain personal data of candidates. The server stores it as written: it may contain requirements that discriminate by a protected characteristic, and the extractor never turns such a requirement into a need field. Exclusions, the requirements that a candidate must not meet, are planned as a separate additive field with the Labor Code article 64 check.' NeedValueStatus: type: string description: 'Confirmation state of one need field. @@ -4147,7 +4147,7 @@ NeedMoneyStatus: - no_salary: the need has no confirmed salary range; the policy uses the neutral value 0.5 and `share` is null. - - withheld: the organization changed salary ranges five times within seven days, so salary aggregates are withheld for seven days (PRD FR13, planned in TASK-211); the policy uses the neutral value 0.5 and `share` is null. + - withheld: the organization changed salary ranges five times within seven days, so salary aggregates are withheld for seven days (PRD FR13, enforcement planned); the policy uses the neutral value 0.5 and `share` is null. An unknown candidate minimum never counts as zero.' @@ -4796,7 +4796,7 @@ MembershipState: - suspended: access is stopped, and the owner or the platform may restore it. - - removed: the owner or the platform ended the membership. A removal by the platform is not undone by the owner or by an invitation: the acceptance of an employee invitation and the member management (TASK-082, TASK-084) must not reactivate it on their own. Who removed the member and why become additive fields of the member management. + - removed: the owner or the platform ended the membership. A removal by the platform is not undone by the owner or by an invitation: the acceptance of an employee invitation and the member management must not reactivate it on their own. Who removed the member and why become additive fields of the member management. - left: the member ended the membership. @@ -4826,7 +4826,7 @@ OrganizationMembership: state: $ref: '#/MembershipState' joined_at: - description: Moment the membership was first created. A member who left and returns keeps the same value, because the pair has one membership; the moment of the latest activation is a planned additive field (`activated_at`, TASK-082). + description: Moment the membership was first created. A member who left and returns keeps the same value, because the pair has one membership; the moment of the latest activation is a planned additive field (`activated_at`). allOf: - $ref: '#/Timestamp' OrganizationSummary: @@ -5131,8 +5131,8 @@ CardCategory: $ref: '#/GradeCode' AnonymousCardContent: type: object - description: The anonymous candidate card as an organization reads it. Only values that the candidate confirmed reach it; an unconfirmed suggestion and an unknown value never do. A free text value (a stack tag, a soft skill, the location) that looks like a contact (an email address, a phone number, a URL or domain, a Telegram link, an @handle) is dropped by the builder (TASK-089) and never published. It carries no name, contact, resume text, employer, salary figure, account or profile identifier, and no schema of the private profile or of a contact disclosure is reachable from it; a contact reaches an organization only through the contact grant of an accepted invitation. Each property is null when its field is not published or the candidate has no value for it, so the card does not tell the two apart. The set of properties is closed, and an organization-visible card must never gain a property that identifies the candidate. The search ranking and the full card of an organization's search - result are defined by the search contract (TASK-185), which reuses this content. + description: The anonymous candidate card as an organization reads it. Only values that the candidate confirmed reach it; an unconfirmed suggestion and an unknown value never do. A free text value (a stack tag, a soft skill, the location) that looks like a contact (an email address, a phone number, a URL or domain, a Telegram link, an @handle) is dropped by the builder and never published. It carries no name, contact, resume text, employer, salary figure, account or profile identifier, and no schema of the private profile or of a contact disclosure is reachable from it; a contact reaches an organization only through the contact grant of an accepted invitation. Each property is null when its field is not published or the candidate has no value for it, so the card does not tell the two apart. The set of properties is closed, and an organization-visible card must never gain a property that identifies the candidate. The search ranking and the full card of an organization's search result are + defined by the search contract, which reuses this content. additionalProperties: false required: - categories @@ -5678,14 +5678,14 @@ SupportCaseStatus: - closed SupportCaseObjectType: type: string - description: 'Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a contract change: generated clients reject an unknown value. Planned values: `vacancy` and `application` with the vacancies and protected applications of PRD FR16, and a profile finding with TASK-272. + description: 'Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a contract change: generated clients reject an unknown value. Planned values: `vacancy` and `application` with the vacancies and protected applications of PRD FR16, and a profile finding with profile analysis. - assessment_attempt: an assessment attempt of the caller. - organization: an organization that the caller can see. - - invitation: an invitation addressed to the caller. Invitations are in the contract (TASK-196) but not implemented yet; until they are, every invitation reference answers 404 not_found. + - invitation: an invitation addressed to the caller. Invitations are in the contract but not implemented yet; until they are, every invitation reference answers 404 not_found. - support_case: another case of the caller, for example the resolved manual assessment that a grade appeal disputes.' enum: @@ -5977,7 +5977,7 @@ SupportCaseDecision: $ref: '#/Timestamp' SupportCaseActorKind: type: string - description: 'Who caused an event, by kind only. A case never names or identifies a moderator, an expert, or a support agent; experts and moderators of TASK-316 and TASK-323 are `support` too. Adding a value is a contract change. + description: 'Who caused an event, by kind only. A case never names or identifies a moderator, an expert, or a support agent; assessment experts and appeal moderators are `support` too. Adding a value is a contract change. - user: the author of the case. @@ -5991,7 +5991,7 @@ SupportCaseActorKind: - system SupportCaseEventKind: type: string - description: 'Kind of a public history event. Adding a value is a contract change. A reply of the author, planned with `waiting_for_user`, is a `reply` with the actor `user`, and a later revision of a decision (TASK-317) is another `decision` event, so neither needs a new value. + description: 'Kind of a public history event. Adding a value is a contract change. A reply of the author, planned with `waiting_for_user`, is a `reply` with the actor `user`, and a later revision of a decision is another `decision` event, so neither needs a new value. - created: the case was created; `status` is `submitted`. For an appeal or a manual assessment, a `status_changed` event of the actor `system` to `waiting_expert` follows in the same transaction. diff --git a/api/core/components/schemas/common_schemas.yml b/api/core/components/schemas/common_schemas.yml index b340ecc..92c4821 100644 --- a/api/core/components/schemas/common_schemas.yml +++ b/api/core/components/schemas/common_schemas.yml @@ -44,6 +44,6 @@ schemas: address or a phone number, and it means nothing to another organization. The server resolves it only for the organization in the path. Clients never parse it. It is shared by the invitations of - FR12 and the search results of FR11 (TASK-185), which issue it. + FR12 and the search results of FR11, which issue it. examples: - cand_7Qm2xVb9Lr4Kp0Zt diff --git a/api/core/components/schemas/consent_schemas.yml b/api/core/components/schemas/consent_schemas.yml index f8b7ce2..e9c12e3 100644 --- a/api/core/components/schemas/consent_schemas.yml +++ b/api/core/components/schemas/consent_schemas.yml @@ -5,7 +5,7 @@ schemas: One of the independent consents of PRD FR01. A grant or a revocation of one purpose never changes another. - c1: processing of personal data, given at registration. - - c2: publication of the candidate card. The record proves the consent to the published text; which fields were published and when is evidence of the publication history (TASK-088), not of this record. Adding a field scope to c2 records later is an additive change. + - c2: publication of the candidate card. The record proves the consent to the published text; which fields were published and when is evidence of the publication history, not of this record. Adding a field scope to c2 records later is an additive change. - c3: automatic categorization. Without it the candidate can request a manual assessment by the same rubric. - c4: transfer of the selected contact data to one organization, currently given only in an invitation acceptance. - c5: import of FSP results. @@ -35,7 +35,7 @@ schemas: Where the subject gave the consent. - registration: the c1 acceptance of RegisterAccount. - - consent_settings: the consent settings of the account, for c1, c2, c3, and c5 (planned, TASK-063 and TASK-064). + - consent_settings: the consent settings of the account, for c1, c2, c3, and c5 (planned). - invitation_acceptance: the c4 acceptance of AcceptMyInvitation. A c4 given when sending an application (PRD Q9) is planned as an additional value. diff --git a/api/core/components/schemas/contact_grant_schemas.yml b/api/core/components/schemas/contact_grant_schemas.yml index c0935ae..8646ae9 100644 --- a/api/core/components/schemas/contact_grant_schemas.yml +++ b/api/core/components/schemas/contact_grant_schemas.yml @@ -9,7 +9,7 @@ schemas: - phone: the contact phone number from the profile. - telegram: the Telegram username from the profile. - The value formats are those of ContactDisclosure: 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, TASK-066) must store contacts in the same formats, so a disclosure never has to convert or drop a stored value. The FSP results of FR14, which need their own explicit permission, are planned as additional kinds. Adding a value is a contract change. + The value formats are those of ContactDisclosure: 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 has to convert or drop a stored value. The FSP results of FR14, which need their own explicit permission, are planned as additional kinds. Adding a value is a contract change. enum: - full_name - email @@ -21,7 +21,7 @@ schemas: Currently published text of the consent C4 for this invitation. The server stores an acceptance with `text_version` and the hash of exactly this text, together with the organization, the selected - fields, the invitation, and its terms version (the ledger of TASK-062). + fields, the invitation, and its terms version (the consent ledger). additionalProperties: false required: - text_version @@ -230,7 +230,7 @@ schemas: is a covered field that the profile no longer holds. The response is never cached or stored by the server for later reads, so a revocation closes the next read at once. The value formats depend on - the profile contract (FR02, TASK-066), which must store the same + the profile contract (FR02), which must store the same formats; see ContactFieldKind. additionalProperties: false required: diff --git a/api/core/components/schemas/invitation_schemas.yml b/api/core/components/schemas/invitation_schemas.yml index f6b2506..440932f 100644 --- a/api/core/components/schemas/invitation_schemas.yml +++ b/api/core/components/schemas/invitation_schemas.yml @@ -354,7 +354,7 @@ schemas: - within_range: the minimum is not above `B`. - up_to_10_percent_above: the minimum is above `B` by at most 10%, that is `10 * minimum <= 11 * B`. - above: the minimum is more than 10% above `B`. - - withheld: the organization made five indicator-relevant settings within seven days, so the indicator is off for seven days from the fifth (the limit of TASK-211). The response to the fifth setting already carries `withheld`, and so does every draft and invitation of the organization, existing ones included, until the period ends. + - withheld: the organization made five indicator-relevant settings within seven days, so the indicator is off for seven days from the fifth. The response to the fifth setting already carries `withheld`, and so does every draft and invitation of the organization, existing ones included, until the period ends. - not_available: the candidate set no minimum for the offered formats, or set it in the other tax basis. Every change that can move this indicator is an indicator-relevant setting: the range set on creation, and in a draft a change of either bound, of the tax basis, or of `work_formats`, since the minimum depends on the format. Each counts against the organization-wide limit of three settings a day (429) and against the withheld counter of five settings within seven days, together with the ranges of needs. The one raise of the upper bound of a sent invitation counts against the withheld counter but not against the daily limit, because FR13 gives it its own once-only rule. 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. diff --git a/api/core/components/schemas/need_schemas.yml b/api/core/components/schemas/need_schemas.yml index e11ac57..8236f02 100644 --- a/api/core/components/schemas/need_schemas.yml +++ b/api/core/components/schemas/need_schemas.yml @@ -36,7 +36,7 @@ schemas: characteristic, and the extractor never turns such a requirement into a need field. Exclusions, the requirements that a candidate must not meet, are planned as a separate additive field with the Labor Code - article 64 check (TASK-182). + article 64 check. NeedValueStatus: type: string description: |- @@ -738,7 +738,7 @@ schemas: - computed: at least five available candidates of the category have a known minimum comparable with the confirmed range; `share` is given. - insufficient_data: fewer than five such candidates; the policy uses the neutral value 0.5 and `share` is null. - no_salary: the need has no confirmed salary range; the policy uses the neutral value 0.5 and `share` is null. - - withheld: the organization changed salary ranges five times within seven days, so salary aggregates are withheld for seven days (PRD FR13, planned in TASK-211); the policy uses the neutral value 0.5 and `share` is null. + - withheld: the organization changed salary ranges five times within seven days, so salary aggregates are withheld for seven days (PRD FR13, enforcement planned); the policy uses the neutral value 0.5 and `share` is null. An unknown candidate minimum never counts as zero. enum: diff --git a/api/core/components/schemas/organization_schemas.yml b/api/core/components/schemas/organization_schemas.yml index a38a673..7aff4c2 100644 --- a/api/core/components/schemas/organization_schemas.yml +++ b/api/core/components/schemas/organization_schemas.yml @@ -407,7 +407,7 @@ schemas: - active: the member works in the organization with the role. - suspended: access is stopped, and the owner or the platform may restore it. - - removed: the owner or the platform ended the membership. A removal by the platform is not undone by the owner or by an invitation: the acceptance of an employee invitation and the member management (TASK-082, TASK-084) must not reactivate it on their own. Who removed the member and why become additive fields of the member management. + - removed: the owner or the platform ended the membership. A removal by the platform is not undone by the owner or by an invitation: the acceptance of an employee invitation and the member management must not reactivate it on their own. Who removed the member and why become additive fields of the member management. - left: the member ended the membership. One account has at most one membership per organization, so a former member who returns gets the same membership back in `active`, and the history of the pair is the history of its audit events (planned). The listing of this contract returns only `active` memberships; the other states are listed now so that generated clients accept them when the member management reads them. Adding a state is a contract change. @@ -444,7 +444,7 @@ schemas: Moment the membership was first created. A member who left and returns keeps the same value, because the pair has one membership; the moment of the latest activation is a planned additive field - (`activated_at`, TASK-082). + (`activated_at`). allOf: - $ref: "./common_schemas.yml#/schemas/Timestamp" OrganizationSummary: diff --git a/api/core/components/schemas/privacy_schemas.yml b/api/core/components/schemas/privacy_schemas.yml index e6f6fb3..c68922b 100644 --- a/api/core/components/schemas/privacy_schemas.yml +++ b/api/core/components/schemas/privacy_schemas.yml @@ -329,7 +329,7 @@ schemas: unknown value never do. A free text value (a stack tag, a soft skill, the location) that looks like a contact (an email address, a phone number, a URL or domain, a Telegram link, an @handle) is dropped by the builder - (TASK-089) and never published. It carries + and never published. It carries no name, contact, resume text, employer, salary figure, account or profile identifier, and no schema of the private profile or of a contact disclosure is reachable from it; a contact reaches an @@ -339,7 +339,7 @@ schemas: apart. The set of properties is closed, and an organization-visible card must never gain a property that identifies the candidate. The search ranking and the full card of an organization's search result - are defined by the search contract (TASK-185), which reuses this + are defined by the search contract, which reuses this content. additionalProperties: false required: diff --git a/api/core/components/schemas/support_schemas.yml b/api/core/components/schemas/support_schemas.yml index 6c0972a..5917216 100644 --- a/api/core/components/schemas/support_schemas.yml +++ b/api/core/components/schemas/support_schemas.yml @@ -51,11 +51,11 @@ schemas: SupportCaseObjectType: type: string description: |- - Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a contract change: generated clients reject an unknown value. Planned values: `vacancy` and `application` with the vacancies and protected applications of PRD FR16, and a profile finding with TASK-272. + Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a contract change: generated clients reject an unknown value. Planned values: `vacancy` and `application` with the vacancies and protected applications of PRD FR16, and a profile finding with profile analysis. - assessment_attempt: an assessment attempt of the caller. - organization: an organization that the caller can see. - - invitation: an invitation addressed to the caller. Invitations are in the contract (TASK-196) but not implemented yet; until they are, every invitation reference answers 404 not_found. + - invitation: an invitation addressed to the caller. Invitations are in the contract but not implemented yet; until they are, every invitation reference answers 404 not_found. - support_case: another case of the caller, for example the resolved manual assessment that a grade appeal disputes. enum: - assessment_attempt @@ -411,7 +411,7 @@ schemas: SupportCaseActorKind: type: string description: |- - Who caused an event, by kind only. A case never names or identifies a moderator, an expert, or a support agent; experts and moderators of TASK-316 and TASK-323 are `support` too. Adding a value is a contract change. + Who caused an event, by kind only. A case never names or identifies a moderator, an expert, or a support agent; assessment experts and appeal moderators are `support` too. Adding a value is a contract change. - user: the author of the case. - support: a person of the support, moderation, or expert staff. @@ -423,7 +423,7 @@ schemas: SupportCaseEventKind: type: string description: |- - Kind of a public history event. Adding a value is a contract change. A reply of the author, planned with `waiting_for_user`, is a `reply` with the actor `user`, and a later revision of a decision (TASK-317) is another `decision` event, so neither needs a new value. + Kind of a public history event. Adding a value is a contract change. A reply of the author, planned with `waiting_for_user`, is a `reply` with the actor `user`, and a later revision of a decision is another `decision` event, so neither needs a new value. - created: the case was created; `status` is `submitted`. For an appeal or a manual assessment, a `status_changed` event of the actor `system` to `waiting_expert` follows in the same transaction. - status_changed: the status changed; `status` is the new status, and `message` may explain a closure. diff --git a/api/core/openapi.bundle.yml b/api/core/openapi.bundle.yml index 93f426c..73f12ed 100644 --- a/api/core/openapi.bundle.yml +++ b/api/core/openapi.bundle.yml @@ -1172,7 +1172,7 @@ paths: The need is saved even when critical fields are missing: the response is 201 with version 1, and `readiness.missing_fields` names each critical field without a confirmed value with a specific question. `recommendations` is computed by the server from the confirmed requirements only; the request cannot set a recommendation, its score, or its components. Creating a need never contacts a candidate or sends an invitation. - Salary limit: setting a salary range counts against a limit shared by the whole organization, every member and every need, on creation as on a change: at most three range settings a day (PRD FR13, planned in TASK-211). Over the limit the server answers 429 with Retry-After and creates nothing. After five settings within seven days the money component of the recommendations is `withheld` for seven days. The limit keeps an organization from probing hidden candidate minimums with new needs instead of edits; repeated range changes also feed the private risk signals of TASK-319. + Salary limit: setting a salary range counts against a limit shared by the whole organization, every member and every need, on creation as on a change: at most three range settings a day (PRD FR13, enforcement planned). Over the limit the server answers 429 with Retry-After and creates nothing. After five settings within seven days the money component of the recommendations is `withheld` for seven days. The limit keeps an organization from probing hidden candidate minimums with new needs instead of edits; repeated range changes also feed the private organization risk signals. Idempotency: a retry with the same key and body within 24 hours replays the stored 201 and creates nothing, so a lost response never creates a second need. A different body with the same key answers 422 idempotency_key_reused. 400 is never stored, so a corrected retry is evaluated again. @@ -1292,7 +1292,7 @@ paths: The operation needs no Idempotency-Key: a body that changes nothing when applied to the current version, such as a retry of a change that already succeeded, keeps the version and answers 200 with the current need even when `expected_version` is older. An incomplete need is a valid result; `readiness.missing_fields` tells what remains. - Salary limit: the recommendations aggregate candidates' minimums against the upper bound, so setting or changing a confirmed salary range counts against a limit shared by the whole organization, every member and every need, together with ranges set on creation: at most three a day (PRD FR13, planned in TASK-211). 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 risk signals of TASK-319. + Salary limit: the recommendations aggregate candidates' minimums against the upper bound, so setting or changing a confirmed salary range counts against a limit shared by the whole organization, every member and every need, together with ranges set on creation: at most three a day (PRD FR13, enforcement planned). 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. Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for a candidate), membership (404 not_found) and role (403 forbidden), the need (404 not_found), a body that changes nothing (200), the version (412), domain rules (400 with a pointer such as `/salary/value/salary_to` for a range whose lower bound is not below the upper one or whose width is outside 10-40%, `/desired_skills/0/name` for a skill that is also in the required list, `/grade/status` or `/required_skills/2/status` for `extracted` with a value that is not the stored suggestion, or `/vacancy_id`), then the salary change limit (429). The schema rejects a missing or non-positive `expected_version`, unknown fields such as `rec_score`, `members`, `candidate_minimum`, or `version`, a field sent as a bare value instead of `{value, status}`, a list sent as null, a salary bound that is not a positive multiple of 1000, and an unknown currency, period, or tax basis. security: @@ -1390,7 +1390,7 @@ paths: The terms are complete from the start (PRD FR12): the role, the specialization and the grade, the offer type, the tasks, the team, the technology stack, the work formats and the place of work, the communication method, the salary range in RUB with its tax basis, and the package. Each package condition is either `provided` with a description or explicitly `not_provided`; leaving one out fails validation. A draft without the tax basis or the communication method therefore cannot exist. The draft is created as version 1 with terms version 1, and the candidate does not see it until SendOrganizationInvitation. - Salary: SalaryRange applies the same rules as for a need: whole rubles, positive multiples of 1000, `salary_from < salary_to`, and a width from 10% to 40% of the midpoint, checked by the server in integer arithmetic. The response carries `salary_fit`, the coarse indicator of PRD FR13 against the candidate's hidden minimum; the exact minimum appears in no response. The server never rejects a range because of the minimum, since a rejection would reveal it. Creating a draft is an indicator-relevant setting: it counts against the limit shared by the whole organization with the ranges of needs, at most three settings a day, and against the withheld counter, after five settings within seven days the indicator is `withheld` for seven days from the fifth, on every draft and invitation of the organization (PRD FR13, planned in TASK-211; see InvitationSalaryFit). Over the limit the server answers 429 with Retry-After and creates nothing. + Salary: SalaryRange applies the same rules as for a need: whole rubles, positive multiples of 1000, `salary_from < salary_to`, and a width from 10% to 40% of the midpoint, checked by the server in integer arithmetic. The response carries `salary_fit`, the coarse indicator of PRD FR13 against the candidate's hidden minimum; the exact minimum appears in no response. The server never rejects a range because of the minimum, since a rejection would reveal it. Creating a draft is an indicator-relevant setting: it counts against the limit shared by the whole organization with the ranges of needs, at most three settings a day, and against the withheld counter, after five settings within seven days the indicator is `withheld` for seven days from the fifth, on every draft and invitation of the organization (PRD FR13, enforcement planned; see InvitationSalaryFit). Over the limit the server answers 429 with Retry-After and creates nothing. Idempotency: a retry with the same key and body within 24 hours replays the stored 201 and creates nothing, so a lost response never creates a second draft. A different body with the same key answers 422 idempotency_key_reused. 400 and 429 are never stored. @@ -1497,7 +1497,7 @@ paths: Versions: every committed change creates version `expected_version + 1`; a change of the terms also creates the next terms version, an immutable snapshot, and a change of anything else keeps the terms version. `expected_version` is the `version` the client read; when it is not current, the server answers 412 version_conflict and changes nothing, and the client reads the invitation again. The version travels in the body because the generated client cannot read the ETag response header yet. The operation needs no Idempotency-Key: a body that changes nothing when applied to the current version, such as a retry of a change that already succeeded, keeps the version and answers 200 with the current invitation even when `expected_version` is older. - Salary limit: every change that can move `salary_fit` is an indicator-relevant setting: a change of either salary bound, of the tax basis, or of `work_formats`, because the indicator compares with the candidate's minimum for the offered formats, and switching formats or the basis would otherwise probe the minimum for free. Such a change counts against the limit shared by the organization with needs and other drafts, at most three settings a day, and against the withheld counter, which withholds `salary_fit` for seven days from the fifth setting within seven days (PRD FR13, planned in TASK-211; see InvitationSalaryFit). Over the limit the server answers 429 with Retry-After and changes nothing. A change that keeps the range, the basis, and the formats does not count. The operation follows the convention of UpdateOrganizationNeed: no Idempotency-Key, and a body that changes nothing answers 200. + Salary limit: every change that can move `salary_fit` is an indicator-relevant setting: a change of either salary bound, of the tax basis, or of `work_formats`, because the indicator compares with the candidate's minimum for the offered formats, and switching formats or the basis would otherwise probe the minimum for free. Such a change counts against the limit shared by the organization with needs and other drafts, at most three settings a day, and against the withheld counter, which withholds `salary_fit` for seven days from the fifth setting within seven days (PRD FR13, enforcement planned; see InvitationSalaryFit). Over the limit the server answers 429 with Retry-After and changes nothing. A change that keeps the range, the basis, and the formats does not count. The operation follows the convention of UpdateOrganizationNeed: no Idempotency-Key, and a body that changes nothing answers 200. Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for a candidate), membership (404 not_found) and role (403 forbidden), the invitation (404 not_found), a body that changes nothing (200), the version (412), the state (409 state_conflict), domain rules (400 with the pointers of CreateOrganizationInvitation), then the salary limit (429). security: @@ -1553,9 +1553,9 @@ paths: description: |- Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. In the MVP only the owner of the organization sends invitations. - Sends the current terms version of a `draft`. Sending is internal and never visible as a state: in one transaction the server records the delivery, creates the candidate's inbox entry, starts the deadline `response_deadline_at = delivered_at + response_period_days`, spends one invitation of the weekly organization quota, and writes the outbox event for the notification (TASK-199), then answers 200 with the state `delivered`. A successful answer therefore means the candidate can already read the invitation; an email is a separate notification that never blocks or delays it, and its retries never move the deadline. No contact of the candidate is disclosed by sending. + Sends the current terms version of a `draft`. Sending is internal and never visible as a state: in one transaction the server records the delivery, creates the candidate's inbox entry, starts the deadline `response_deadline_at = delivered_at + response_period_days`, spends one invitation of the weekly organization quota, and writes the outbox event for the notification, then answers 200 with the state `delivered`. A successful answer therefore means the candidate can already read the invitation; an email is a separate notification that never blocks or delays it, and its retries never move the deadline. No contact of the candidate is disclosed by sending. - The server checks again that the candidate is still visible to the organization: a revoked publication C2 or a profile hidden from the organization answers 409 state_conflict without telling which. It also enforces the limits of the product policy: at most 20 invitations waiting for an answer per need (`delivered`, `viewed`, `counter`) and the 30-day pause for the pair of the organization and the candidate after a decline or a no deal, regardless of the member or the need, both with 409 state_conflict; and the rolling weekly quota of the organization (TASK-087), with 429 and Retry-After. The pending limit and the quota are planned in TASK-205 and TASK-087. + The server checks again that the candidate is still visible to the organization: a revoked publication C2 or a profile hidden from the organization answers 409 state_conflict without telling which. It also enforces the limits of the product policy: at most 20 invitations waiting for an answer per need (`delivered`, `viewed`, `counter`) and the 30-day pause for the pair of the organization and the candidate after a decline or a no deal, regardless of the member or the need, both with 409 state_conflict; and the rolling weekly quota of the organization, with 429 and Retry-After. Enforcement of the pending limit and the organization quota is planned. Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, and a send of an invitation that was already sent answers 200 with the invitation in its current state even with a new key or an older `expected_version`; the quota is spent once. A stale `expected_version` on a draft answers 412 version_conflict, so the organization never sends terms it did not read. @@ -1740,13 +1740,13 @@ paths: operationId: GetOrganizationInvitationContacts summary: Read the contacts that the candidate disclosed to the organization. description: |- - Requires the session cookie of an employer account with an active membership in `org_id`. In the MVP only the owner of the organization reads contacts (TASK-202); the other roles of PRD FR07 are planned. + Requires the session cookie of an employer account with an active membership in `org_id`. In the MVP only the owner of the organization reads contacts; the other roles of PRD FR07 are planned. This is the only operation that returns contact values, and its response is separate from the terms and from the invitation. It answers only while a grant created by the acceptance of this invitation is active and the read is allowed now: on every request the server checks the membership, the consent C4 for this organization, the grant and its fields, and the current visibility of the profile (C2 and the organizations the candidate hid the profile from), with no cache in between, so a revocation closes the next read at once. The response holds exactly the fields that the grant covers; every other field is null. A grant of organization A never answers for organization B. Without such a grant the contacts do not exist for the caller, and the operation answers 404 not_found, the same as for an unknown invitation: before an acceptance, after a decline or an expiry, after the candidate revoked C4 or cancelled the participation, after the candidate closed the visibility, and while a grant created when the profile was not published or was hidden from the organization stays blocked. The answer does not tell which applies; `contact_access` of GetOrganizationInvitation tells the organization whether access is `not_granted`, `available`, or `closed`, without the reason, and the candidate sees `readable` and `blocked_by` on the grant. Withdrawing the invitation keeps an existing grant. A later publication of the profile never reopens a closed grant; only a new explicit C4 creates a new one. - Every successful read is recorded in the access audit (planned in TASK-090 and TASK-202), and the response has `Cache-Control: no-store`. + Every successful read is recorded in the access audit (planned with the contact access history), and the response has `Cache-Control: no-store`. Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden; an account without an active membership in the organization, an unknown organization, an unknown invitation, an invitation of another organization, and an invitation without an active readable grant all answer 404 not_found; a member whose role does not allow reading contacts answers 403 forbidden. An `org_id` or `invitation_id` that is not a UUID answers 400 validation_failed with the path pointer. security: @@ -1871,7 +1871,7 @@ paths: description: |- Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The candidate comes from the session. The request has no body. - The view transition of PRD FR12 (TASK-200) is an explicit command, so reading the invitation with GetMyInvitation stays free of side effects. The client sends it when the candidate opens the terms screen. For a `delivered` invitation the server moves it to `viewed`, sets `viewed_at`, advances `version`, and keeps the deadline. In any other state, including `viewed`, `accepted`, and the terminal states, it changes nothing and answers 200 with the current invitation. A view never reopens, extends, or answers an invitation, and the organization sees only the state `viewed` and `viewed_at`. + The view transition of PRD FR12 is an explicit command, so reading the invitation with GetMyInvitation stays free of side effects. The client sends it when the candidate opens the terms screen. For a `delivered` invitation the server moves it to `viewed`, sets `viewed_at`, advances `version`, and keeps the deadline. In any other state, including `viewed`, `accepted`, and the terminal states, it changes nothing and answers 200 with the current invitation. A view never reopens, extends, or answers an invitation, and the organization sees only the state `viewed` and `viewed_at`. The command is idempotent by its effect: the first view wins and every repeat returns the current invitation. It therefore needs no Idempotency-Key and no `expected_version`: a view must never fail because the invitation changed after the client read it, for example after a salary raise. A view at the deadline or later first applies the due expiry and answers 200 with `expired`. @@ -1919,11 +1919,11 @@ paths: Only an acceptance of the current terms version with the consent C4 creates access to contacts (PRD FR12). The body names the `terms_version` the candidate read and accepts, the `expected_version` of the invitation, and `consent_c4`: the C4 text version that the candidate saw, `accepted: true`, and the contact fields the candidate selected. At least one field is required and nothing is preselected or defaulted, so a grant never covers a field the candidate did not choose. The fields come only from the candidate's profile; the request never carries contact values. - Allowed in `delivered` and `viewed` before `response_deadline_at`; accepting directly from `delivered` is allowed, as in the PRD FR12 transition table. In one transaction the server moves the invitation to `accepted`, records the consent C4 in the consent ledger with the organization, the fields, the invitation, the terms version, and the text version and its hash (TASK-062), creates the contact grant for exactly those fields, and writes the audit event (TASK-201). The response is the invitation with `contact_grant`. The acceptance never publishes the profile (C2) and never bypasses a profile hidden from the organization: the grant alone does not guarantee a read, and the organization reads only while the visibility allows it. + Allowed in `delivered` and `viewed` before `response_deadline_at`; accepting directly from `delivered` is allowed, as in the PRD FR12 transition table. In one transaction the server moves the invitation to `accepted`, records the consent C4 in the consent ledger with the organization, the fields, the invitation, the terms version, and the text version and its hash, creates the contact grant for exactly those fields, and writes the audit event. The response is the invitation with `contact_grant`. The acceptance never publishes the profile (C2) and never bypasses a profile hidden from the organization: the grant alone does not guarantee a read, and the organization reads only while the visibility allows it. - 412 or 409: a `terms_version` or `expected_version` that is not current answers 412 version_conflict, the repository status for a stale version, and records nothing; this is the stale terms case, for example after the organization raised the salary, and the client reads the invitation again and shows the new terms for a new decision. A state that does not allow an acceptance answers 409 state_conflict: `withdrawn`, `expired`, `declined`, `cancelled_by_candidate`, the planned `counter`, or a command received at the deadline or later, which is late. A terminal state and a passed deadline are checked before the versions: the server first applies the due expiry, and the client then gets 409 for a withdrawn, expired, or late invitation even when its versions are stale, so it shows the final state instead of rereading and retrying. TASK-197, TASK-201, and TASK-204 say 409 for stale terms; the repository rule keeps 412 for any stale version, so clients branch on `version_conflict` to reread and on `state_conflict` to show the final state. + 412 or 409: a `terms_version` or `expected_version` that is not current answers 412 version_conflict, the repository status for a stale version, and records nothing; this is the stale terms case, for example after the organization raised the salary, and the client reads the invitation again and shows the new terms for a new decision. A state that does not allow an acceptance answers 409 state_conflict: `withdrawn`, `expired`, `declined`, `cancelled_by_candidate`, the planned `counter`, or a command received at the deadline or later, which is late. A terminal state and a passed deadline are checked before the versions: the server first applies the due expiry, and the client then gets 409 for a withdrawn, expired, or late invitation even when its versions are stale, so it shows the final state instead of rereading and retrying. The repository rule keeps 412 for any stale version, so clients branch on `version_conflict` to reread and on `state_conflict` to show the final state. - Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, and an acceptance of an invitation that is already `accepted` whose `terms_version` and set of fields equal those of its `contact_grant`, the terms version and fields that the candidate accepted, answers 200 with it even with a new key, an older `expected_version`, or a current `terms_version` that a later raise advanced; no second consent, grant, or audit event is created. A different terms version or field set on an accepted invitation answers 409 state_conflict; changing the disclosed fields is a matter of the consent operations (TASK-064). Of two concurrent acceptances only one makes the transition. + Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, and an acceptance of an invitation that is already `accepted` whose `terms_version` and set of fields equal those of its `contact_grant`, the terms version and fields that the candidate accepted, answers 200 with it even with a new key, an older `expected_version`, or a current `terms_version` that a later raise advanced; no second consent, grant, or audit event is created. A different terms version or field set on an accepted invitation answers 409 state_conflict; changing the disclosed fields is a matter of the consent operations. Of two concurrent acceptances only one makes the transition. Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for an employer), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the invitation (404 not_found, after any due expiry), the repeat on an accepted invitation (200), a terminal state or a passed deadline (409 state_conflict, whatever the versions), the versions (412), any other state that does not allow an acceptance (409 state_conflict), then the consent rules (400 with the pointer `/consent_c4/text_version` for a text version that is not the published one, or `/consent_c4/fields/0` for a field that the profile does not hold). The schema rejects a missing `terms_version`, an empty or repeated field list, an unknown field kind, `accepted` other than true, and unknown fields such as `email` or `phone`. The general rate limit can answer 429 with Retry-After before any check. 404 and 409 state_conflict are stored under the key; 400, 412, and 429 are not. security: @@ -2049,7 +2049,7 @@ paths: description: |- Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The candidate comes from the session. - Moves an unfinished invitation to the terminal state `cancelled_by_candidate` (PRD FR12): `delivered`, `viewed`, `accepted`, and the planned stages up to `negotiation`. The process closes. In the same transaction the server revokes the contact grant that the acceptance of this invitation created, with the reason `participation_cancelled`, so the next contact read of the organization answers 404. Grants of other invitations or applications stay; revoking the consent C4 for the organization as a whole, which closes all of them, belongs to the consent operations (TASK-064). + Moves an unfinished invitation to the terminal state `cancelled_by_candidate` (PRD FR12): `delivered`, `viewed`, `accepted`, and the planned stages up to `negotiation`. The process closes. In the same transaction the server revokes the contact grant that the acceptance of this invitation created, with the reason `participation_cancelled`, so the next contact read of the organization answers 404. Grants of other invitations or applications stay; revoking the consent C4 for the organization as a whole, which closes all of them, belongs to the consent operations. Cancel differs from decline and withdraw: a decline is the structured answer before an acceptance and counts as a response; a cancellation leaves the process at any unfinished stage, mostly after an acceptance, and carries no reason; a withdrawal is the organization's command and keeps the grant. Before an answer the client offers the decline. @@ -2113,9 +2113,9 @@ paths: The ledger is append-only. Every grant is a record with its purpose, the accepted text version, the source, and the grant time; the server also stores the hash of exactly the text the subject saw. A newer text version of the same purpose is a new record, and the earlier one becomes `superseded` without any change. A revocation stamps every unrevoked record of the purpose, and for c4 of one organization, once; a later grant is a new record. Purposes are independent. - Without `state` the page lists the whole history; `state=active` lists the consents that hold now, one per purpose for c1, c2, c3, and c5 and one per accepted invitation for c4. A c4 record names the organization with the name its consent text showed (a snapshot that a later rename does not change), the selected contact fields, and the invitation with its terms version; it never carries a contact value. A c2 record proves the consent to the publication text; the published field set and its changes are evidence of the publication history (TASK-088). + Without `state` the page lists the whole history; `state=active` lists the consents that hold now, one per purpose for c1, c2, c3, and c5 and one per accepted invitation for c4. A c4 record names the organization with the name its consent text showed (a snapshot that a later rename does not change), the selected contact fields, and the invitation with its terms version; it never carries a contact value. A c2 record proves the consent to the publication text; the published field set and its changes are evidence of the publication history. - Granting c1, c2, c3, and c5 in the consent settings and revoking any purpose are planned operations of this tag (TASK-063 and TASK-064); c1 is given at registration and c4 only in AcceptMyInvitation. + Granting c1, c2, c3, and c5 in the consent settings and revoking any purpose are planned operations of this tag; c1 is given at registration and c4 only in AcceptMyInvitation. Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated. A malformed `limit`, `cursor`, or `state` answers 400 validation_failed. security: @@ -2192,7 +2192,7 @@ paths: description: |- Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The body is the complete new publication setting: `state` `published` with the non-empty set of card fields, or `closed` with an empty set. It changes only the publication; the search status and the hidden organizations stay as they were. - Publication is not a consent and does not duplicate one. The consent C2 lives in the consent ledger (`ListMyConsents`); this setting refers to it. Publishing requires an active, unrevoked C2 record of the account and binds the publication to that record, so a client sends no consent identifier and cannot forge one. Without one the server answers 409 state_conflict with the entry `{in: body, pointer: /state, code: consent_required}` in `errors`, which tells it apart from every other conflict, and changes nothing: the client gives C2 first (planned in the consent settings, TASK-063) and then publishes. The server takes the C2 record under a share lock in the transaction that writes the publication, so a revocation that races with a publication either commits first (the publication is refused) or closes the card right after. A revocation of C2 closes the card at once, because `state` is computed from the unrevoked record; a later C2 grant never reopens it, and the candidate publishes again under the new record. The revocation path itself (TASK-064) closes the stored publication and revokes the contact grants in its own transaction. A closing sent over a stored publication whose C2 was revoked is a real change: it stores the closing, records `publication_closed`, and revokes the grants as any closing does. Publishing, like every visibility change, needs a verified email (a usecase requirement; the unverified account cleanup deletes only accounts without such records). Publishing never adds a field that the body did not name, and a new `CardField` value is never published for a candidate who did not choose it. + Publication is not a consent and does not duplicate one. The consent C2 lives in the consent ledger (`ListMyConsents`); this setting refers to it. Publishing requires an active, unrevoked C2 record of the account and binds the publication to that record, so a client sends no consent identifier and cannot forge one. Without one the server answers 409 state_conflict with the entry `{in: body, pointer: /state, code: consent_required}` in `errors`, which tells it apart from every other conflict, and changes nothing: the client gives C2 first (planned in the consent settings) and then publishes. The server takes the C2 record under a share lock in the transaction that writes the publication, so a revocation that races with a publication either commits first (the publication is refused) or closes the card right after. A revocation of C2 closes the card at once, because `state` is computed from the unrevoked record; a later C2 grant never reopens it, and the candidate publishes again under the new record. The revocation path itself closes the stored publication and revokes the contact grants in its own transaction. A closing sent over a stored publication whose C2 was revoked is a real change: it stores the closing, records `publication_closed`, and revokes the grants as any closing does. Publishing, like every visibility change, needs a verified email (a usecase requirement; the unverified account cleanup deletes only accounts without such records). Publishing never adds a field that the body did not name, and a new `CardField` value is never published for a candidate who did not choose it. The field set contains only the groups of `CardField`. The full name, contacts, and the lowest salary have no value there, so no body can publish them. Only values that the candidate confirmed ever reach the card. Contacts reach an organization only through the contact grant (C4), and a profile that is published or closed changes none of the grants that exist; closing the publication, and hiding an organization that holds a grant, revoke the contact grants concerned with the reason `visibility_closed` in the same transaction as the change (planned together with the operations, see the invitation contract). @@ -2493,7 +2493,7 @@ paths: An access is a view of the anonymous card by an organization (`card_viewed`) or a read of the contacts through an active contact grant (`contact_read`). Reading the history is not an access and writes nothing. A view of the card by an organization that has no invitation relation with the candidate carries `organization` null, so the candidate sees that the card was viewed without learning a company that they cannot otherwise see; a contact read always names the organization, because the candidate accepted its invitation. The entries carry no search query, filter, or ranking of the organization, and no organization the candidate hides ever appears as a viewer, because a hidden organization cannot read the card. - The storage of accesses is planned with the card and contact operations of the organization side (TASK-185 and the contact read of the invitation contract); until then the operation answers 501 not_implemented after the session and request checks. + The storage of accesses is planned with the card and contact operations of the organization side (anonymous card reads and contact reads under the invitation contract); until then the operation answers 501 not_implemented after the session and request checks. A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. A malformed `limit` or `cursor` answers 400 validation_failed. security: @@ -2576,7 +2576,7 @@ paths: | `anticheat_appeal` | candidate | required; `assessment_attempt` of the caller with an anti-cheat review decision | none | | `manual_assessment` | candidate | optional; a prior `assessment_attempt` of the caller in the same specialization | required `assessment_target` | - An organization is visible to a candidate when it sent the candidate an invitation or when the organization contract (TASK-077) shows the candidate its profile, and to an employer account when the account has an active membership in it. Invitations are in the contract (TASK-196) but not implemented yet, so until they are, every `invitation` reference answers 404 not_found; anti-cheat review decisions are not either, so until TASK-173 every anti-cheat appeal answers 409 state_conflict. The schema rejects an object type that the case type does not accept, for example an organization in a grade appeal. + An organization is visible to a candidate when it sent the candidate an invitation or when the organization contract shows the candidate its profile, and to an employer account when the account has an active membership in it. Invitations are in the contract but not implemented yet, so until they are, every `invitation` reference answers 404 not_found; anti-cheat review decisions are not either, so until review decisions are implemented, every anti-cheat appeal answers 409 state_conflict. The schema rejects an object type that the case type does not accept, for example an organization in a grade appeal. Ownership of the reference: the server checks the object against the session account on every create. An unknown object and an object of someone else, such as another candidate's attempt, another account's case, or an invitation addressed to another person, both answer 404 not_found, so a reference never reveals whether a foreign object exists. An own case that a grade appeal cannot dispute, because it is not a manual assessment, is not resolved yet, or was resolved with another outcome, answers 409 state_conflict. An identifier that is not a UUID fails validation with the pointer `/object/id`. The case stores only the type and the identifier of the object. @@ -2655,7 +2655,7 @@ paths: The history lists every public event and is never truncated: the server keeps a case within 200 events by rejecting a staff event that would leave no room for the terminal one. - The case must belong to the account of the session: a case of another account, including another member of the same organization, answers 404 not_found, the same as an unknown identifier, so identifiers cannot be probed. TASK-314 says forbidden for a foreign case URL; the contract answers 404 instead, so the client shows the same "not found" state for a foreign and an unknown case. A malformed `case_id` answers 400 validation_failed with the path pointer. + The case must belong to the account of the session: a case of another account, including another member of the same organization, answers 404 not_found, the same as an unknown identifier, so identifiers cannot be probed. The contract answers 404, so the client shows the same "not found" state for a foreign and an unknown case. A malformed `case_id` answers 400 validation_failed with the path pointer. security: - sessionCookie: [] tags: @@ -5256,7 +5256,7 @@ components: type: string minLength: 1 maxLength: 10000 - description: 'Free description of the team''s tasks as the employer wrote or pasted it. The server extracts proposed requirements from it; the text itself is never a requirement. It may contain line breaks. Plain text; clients show it as text, never as HTML. It describes the job and must not contain personal data of candidates. The server stores it as written: it may contain requirements that discriminate by a protected characteristic, and the extractor never turns such a requirement into a need field. Exclusions, the requirements that a candidate must not meet, are planned as a separate additive field with the Labor Code article 64 check (TASK-182).' + description: 'Free description of the team''s tasks as the employer wrote or pasted it. The server extracts proposed requirements from it; the text itself is never a requirement. It may contain line breaks. Plain text; clients show it as text, never as HTML. It describes the job and must not contain personal data of candidates. The server stores it as written: it may contain requirements that discriminate by a protected characteristic, and the extractor never turns such a requirement into a need field. Exclusions, the requirements that a candidate must not meet, are planned as a separate additive field with the Labor Code article 64 check.' NeedValueStatus: type: string description: |- @@ -5809,7 +5809,7 @@ components: - computed: at least five available candidates of the category have a known minimum comparable with the confirmed range; `share` is given. - insufficient_data: fewer than five such candidates; the policy uses the neutral value 0.5 and `share` is null. - no_salary: the need has no confirmed salary range; the policy uses the neutral value 0.5 and `share` is null. - - withheld: the organization changed salary ranges five times within seven days, so salary aggregates are withheld for seven days (PRD FR13, planned in TASK-211); the policy uses the neutral value 0.5 and `share` is null. + - withheld: the organization changed salary ranges five times within seven days, so salary aggregates are withheld for seven days (PRD FR13, enforcement planned); the policy uses the neutral value 0.5 and `share` is null. An unknown candidate minimum never counts as zero. enum: @@ -6184,11 +6184,11 @@ components: SupportCaseObjectType: type: string description: |- - Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a contract change: generated clients reject an unknown value. Planned values: `vacancy` and `application` with the vacancies and protected applications of PRD FR16, and a profile finding with TASK-272. + Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a contract change: generated clients reject an unknown value. Planned values: `vacancy` and `application` with the vacancies and protected applications of PRD FR16, and a profile finding with profile analysis. - assessment_attempt: an assessment attempt of the caller. - organization: an organization that the caller can see. - - invitation: an invitation addressed to the caller. Invitations are in the contract (TASK-196) but not implemented yet; until they are, every invitation reference answers 404 not_found. + - invitation: an invitation addressed to the caller. Invitations are in the contract but not implemented yet; until they are, every invitation reference answers 404 not_found. - support_case: another case of the caller, for example the resolved manual assessment that a grade appeal disputes. enum: - assessment_attempt @@ -6471,7 +6471,7 @@ components: SupportCaseActorKind: type: string description: |- - Who caused an event, by kind only. A case never names or identifies a moderator, an expert, or a support agent; experts and moderators of TASK-316 and TASK-323 are `support` too. Adding a value is a contract change. + Who caused an event, by kind only. A case never names or identifies a moderator, an expert, or a support agent; assessment experts and appeal moderators are `support` too. Adding a value is a contract change. - user: the author of the case. - support: a person of the support, moderation, or expert staff. @@ -6483,7 +6483,7 @@ components: SupportCaseEventKind: type: string description: |- - Kind of a public history event. Adding a value is a contract change. A reply of the author, planned with `waiting_for_user`, is a `reply` with the actor `user`, and a later revision of a decision (TASK-317) is another `decision` event, so neither needs a new value. + Kind of a public history event. Adding a value is a contract change. A reply of the author, planned with `waiting_for_user`, is a `reply` with the actor `user`, and a later revision of a decision is another `decision` event, so neither needs a new value. - created: the case was created; `status` is `submitted`. For an appeal or a manual assessment, a `status_changed` event of the actor `system` to `waiting_expert` follows in the same transaction. - status_changed: the status changed; `status` is the new status, and `message` may explain a closure. @@ -6733,7 +6733,7 @@ components: minLength: 1 maxLength: 128 pattern: ^[A-Za-z0-9_-]+$ - description: Opaque reference to a candidate as one organization sees it, taken from a search result card of that organization. It is not the candidate's account or profile identifier, it never contains an email address or a phone number, and it means nothing to another organization. The server resolves it only for the organization in the path. Clients never parse it. It is shared by the invitations of FR12 and the search results of FR11 (TASK-185), which issue it. + description: Opaque reference to a candidate as one organization sees it, taken from a search result card of that organization. It is not the candidate's account or profile identifier, it never contains an email address or a phone number, and it means nothing to another organization. The server resolves it only for the organization in the path. Clients never parse it. It is shared by the invitations of FR12 and the search results of FR11, which issue it. examples: - cand_7Qm2xVb9Lr4Kp0Zt InvitationRoleTitle: @@ -6941,7 +6941,7 @@ components: - within_range: the minimum is not above `B`. - up_to_10_percent_above: the minimum is above `B` by at most 10%, that is `10 * minimum <= 11 * B`. - above: the minimum is more than 10% above `B`. - - withheld: the organization made five indicator-relevant settings within seven days, so the indicator is off for seven days from the fifth (the limit of TASK-211). The response to the fifth setting already carries `withheld`, and so does every draft and invitation of the organization, existing ones included, until the period ends. + - withheld: the organization made five indicator-relevant settings within seven days, so the indicator is off for seven days from the fifth. The response to the fifth setting already carries `withheld`, and so does every draft and invitation of the organization, existing ones included, until the period ends. - not_available: the candidate set no minimum for the offered formats, or set it in the other tax basis. Every change that can move this indicator is an indicator-relevant setting: the range set on creation, and in a draft a change of either bound, of the tax basis, or of `work_formats`, since the minimum depends on the format. Each counts against the organization-wide limit of three settings a day (429) and against the withheld counter of five settings within seven days, together with the ranges of needs. The one raise of the upper bound of a sent invitation counts against the withheld counter but not against the daily limit, because FR13 gives it its own once-only rule. 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. @@ -7449,7 +7449,7 @@ components: - phone: the contact phone number from the profile. - telegram: the Telegram username from the profile. - The value formats are those of ContactDisclosure: 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, TASK-066) must store contacts in the same formats, so a disclosure never has to convert or drop a stored value. The FSP results of FR14, which need their own explicit permission, are planned as additional kinds. Adding a value is a contract change. + The value formats are those of ContactDisclosure: 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 has to convert or drop a stored value. The FSP results of FR14, which need their own explicit permission, are planned as additional kinds. Adding a value is a contract change. enum: - full_name - email @@ -7457,7 +7457,7 @@ components: - telegram ContactConsentText: type: object - description: Currently published text of the consent C4 for this invitation. The server stores an acceptance with `text_version` and the hash of exactly this text, together with the organization, the selected fields, the invitation, and its terms version (the ledger of TASK-062). + description: Currently published text of the consent C4 for this invitation. The server stores an acceptance with `text_version` and the hash of exactly this text, together with the organization, the selected fields, the invitation, and its terms version (the consent ledger). additionalProperties: false required: - text_version @@ -7622,7 +7622,7 @@ components: description: Full name as the candidate wrote it in the profile. Plain text without line breaks; clients show it as text, never as HTML. ContactDisclosure: type: object - description: Contacts of the candidate that the organization may read through an active grant of this invitation. This is the only response that carries contact values, and it is separate from the terms and from the invitation. Each field the grant does not cover is null, and so is a covered field that the profile no longer holds. The response is never cached or stored by the server for later reads, so a revocation closes the next read at once. The value formats depend on the profile contract (FR02, TASK-066), which must store the same formats; see ContactFieldKind. + description: Contacts of the candidate that the organization may read through an active grant of this invitation. This is the only response that carries contact values, and it is separate from the terms and from the invitation. Each field the grant does not cover is null, and so is a covered field that the profile no longer holds. The response is never cached or stored by the server for later reads, so a revocation closes the next read at once. The value formats depend on the profile contract (FR02), which must store the same formats; see ContactFieldKind. additionalProperties: false required: - invitation_id @@ -7674,7 +7674,7 @@ components: One of the independent consents of PRD FR01. A grant or a revocation of one purpose never changes another. - c1: processing of personal data, given at registration. - - c2: publication of the candidate card. The record proves the consent to the published text; which fields were published and when is evidence of the publication history (TASK-088), not of this record. Adding a field scope to c2 records later is an additive change. + - c2: publication of the candidate card. The record proves the consent to the published text; which fields were published and when is evidence of the publication history, not of this record. Adding a field scope to c2 records later is an additive change. - c3: automatic categorization. Without it the candidate can request a manual assessment by the same rubric. - c4: transfer of the selected contact data to one organization, currently given only in an invitation acceptance. - c5: import of FSP results. @@ -7704,7 +7704,7 @@ components: Where the subject gave the consent. - registration: the c1 acceptance of RegisterAccount. - - consent_settings: the consent settings of the account, for c1, c2, c3, and c5 (planned, TASK-063 and TASK-064). + - consent_settings: the consent settings of the account, for c1, c2, c3, and c5 (planned). - invitation_acceptance: the c4 acceptance of AcceptMyInvitation. A c4 given when sending an application (PRD Q9) is planned as an additional value. @@ -8127,7 +8127,7 @@ components: - active: the member works in the organization with the role. - suspended: access is stopped, and the owner or the platform may restore it. - - removed: the owner or the platform ended the membership. A removal by the platform is not undone by the owner or by an invitation: the acceptance of an employee invitation and the member management (TASK-082, TASK-084) must not reactivate it on their own. Who removed the member and why become additive fields of the member management. + - removed: the owner or the platform ended the membership. A removal by the platform is not undone by the owner or by an invitation: the acceptance of an employee invitation and the member management must not reactivate it on their own. Who removed the member and why become additive fields of the member management. - left: the member ended the membership. One account has at most one membership per organization, so a former member who returns gets the same membership back in `active`, and the history of the pair is the history of its audit events (planned). The listing of this contract returns only `active` memberships; the other states are listed now so that generated clients accept them when the member management reads them. Adding a state is a contract change. @@ -8155,7 +8155,7 @@ components: state: $ref: '#/components/schemas/MembershipState' joined_at: - description: Moment the membership was first created. A member who left and returns keeps the same value, because the pair has one membership; the moment of the latest activation is a planned additive field (`activated_at`, TASK-082). + description: Moment the membership was first created. A member who left and returns keeps the same value, because the pair has one membership; the moment of the latest activation is a planned additive field (`activated_at`). allOf: - $ref: '#/components/schemas/Timestamp' OrganizationSummary: @@ -8449,7 +8449,7 @@ components: $ref: '#/components/schemas/GradeCode' AnonymousCardContent: type: object - description: The anonymous candidate card as an organization reads it. Only values that the candidate confirmed reach it; an unconfirmed suggestion and an unknown value never do. A free text value (a stack tag, a soft skill, the location) that looks like a contact (an email address, a phone number, a URL or domain, a Telegram link, an @handle) is dropped by the builder (TASK-089) and never published. It carries no name, contact, resume text, employer, salary figure, account or profile identifier, and no schema of the private profile or of a contact disclosure is reachable from it; a contact reaches an organization only through the contact grant of an accepted invitation. Each property is null when its field is not published or the candidate has no value for it, so the card does not tell the two apart. The set of properties is closed, and an organization-visible card must never gain a property that identifies the candidate. The search ranking and the full card of an organization's search result are defined by the search contract (TASK-185), which reuses this content. + description: The anonymous candidate card as an organization reads it. Only values that the candidate confirmed reach it; an unconfirmed suggestion and an unknown value never do. A free text value (a stack tag, a soft skill, the location) that looks like a contact (an email address, a phone number, a URL or domain, a Telegram link, an @handle) is dropped by the builder and never published. It carries no name, contact, resume text, employer, salary figure, account or profile identifier, and no schema of the private profile or of a contact disclosure is reachable from it; a contact reaches an organization only through the contact grant of an accepted invitation. Each property is null when its field is not published or the candidate has no value for it, so the card does not tell the two apart. The set of properties is closed, and an organization-visible card must never gain a property that identifies the candidate. The search ranking and the full card of an organization's search result are defined by the search contract, which reuses this content. additionalProperties: false required: - categories diff --git a/api/core/routes/candidate_invitation_accept.yml b/api/core/routes/candidate_invitation_accept.yml index fd2d179..18df52e 100644 --- a/api/core/routes/candidate_invitation_accept.yml +++ b/api/core/routes/candidate_invitation_accept.yml @@ -6,11 +6,11 @@ post: Only an acceptance of the current terms version with the consent C4 creates access to contacts (PRD FR12). The body names the `terms_version` the candidate read and accepts, the `expected_version` of the invitation, and `consent_c4`: the C4 text version that the candidate saw, `accepted: true`, and the contact fields the candidate selected. At least one field is required and nothing is preselected or defaulted, so a grant never covers a field the candidate did not choose. The fields come only from the candidate's profile; the request never carries contact values. - Allowed in `delivered` and `viewed` before `response_deadline_at`; accepting directly from `delivered` is allowed, as in the PRD FR12 transition table. In one transaction the server moves the invitation to `accepted`, records the consent C4 in the consent ledger with the organization, the fields, the invitation, the terms version, and the text version and its hash (TASK-062), creates the contact grant for exactly those fields, and writes the audit event (TASK-201). The response is the invitation with `contact_grant`. The acceptance never publishes the profile (C2) and never bypasses a profile hidden from the organization: the grant alone does not guarantee a read, and the organization reads only while the visibility allows it. + Allowed in `delivered` and `viewed` before `response_deadline_at`; accepting directly from `delivered` is allowed, as in the PRD FR12 transition table. In one transaction the server moves the invitation to `accepted`, records the consent C4 in the consent ledger with the organization, the fields, the invitation, the terms version, and the text version and its hash, creates the contact grant for exactly those fields, and writes the audit event. The response is the invitation with `contact_grant`. The acceptance never publishes the profile (C2) and never bypasses a profile hidden from the organization: the grant alone does not guarantee a read, and the organization reads only while the visibility allows it. - 412 or 409: a `terms_version` or `expected_version` that is not current answers 412 version_conflict, the repository status for a stale version, and records nothing; this is the stale terms case, for example after the organization raised the salary, and the client reads the invitation again and shows the new terms for a new decision. A state that does not allow an acceptance answers 409 state_conflict: `withdrawn`, `expired`, `declined`, `cancelled_by_candidate`, the planned `counter`, or a command received at the deadline or later, which is late. A terminal state and a passed deadline are checked before the versions: the server first applies the due expiry, and the client then gets 409 for a withdrawn, expired, or late invitation even when its versions are stale, so it shows the final state instead of rereading and retrying. TASK-197, TASK-201, and TASK-204 say 409 for stale terms; the repository rule keeps 412 for any stale version, so clients branch on `version_conflict` to reread and on `state_conflict` to show the final state. + 412 or 409: a `terms_version` or `expected_version` that is not current answers 412 version_conflict, the repository status for a stale version, and records nothing; this is the stale terms case, for example after the organization raised the salary, and the client reads the invitation again and shows the new terms for a new decision. A state that does not allow an acceptance answers 409 state_conflict: `withdrawn`, `expired`, `declined`, `cancelled_by_candidate`, the planned `counter`, or a command received at the deadline or later, which is late. A terminal state and a passed deadline are checked before the versions: the server first applies the due expiry, and the client then gets 409 for a withdrawn, expired, or late invitation even when its versions are stale, so it shows the final state instead of rereading and retrying. The repository rule keeps 412 for any stale version, so clients branch on `version_conflict` to reread and on `state_conflict` to show the final state. - Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, and an acceptance of an invitation that is already `accepted` whose `terms_version` and set of fields equal those of its `contact_grant`, the terms version and fields that the candidate accepted, answers 200 with it even with a new key, an older `expected_version`, or a current `terms_version` that a later raise advanced; no second consent, grant, or audit event is created. A different terms version or field set on an accepted invitation answers 409 state_conflict; changing the disclosed fields is a matter of the consent operations (TASK-064). Of two concurrent acceptances only one makes the transition. + Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, and an acceptance of an invitation that is already `accepted` whose `terms_version` and set of fields equal those of its `contact_grant`, the terms version and fields that the candidate accepted, answers 200 with it even with a new key, an older `expected_version`, or a current `terms_version` that a later raise advanced; no second consent, grant, or audit event is created. A different terms version or field set on an accepted invitation answers 409 state_conflict; changing the disclosed fields is a matter of the consent operations. Of two concurrent acceptances only one makes the transition. Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for an employer), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the invitation (404 not_found, after any due expiry), the repeat on an accepted invitation (200), a terminal state or a passed deadline (409 state_conflict, whatever the versions), the versions (412), any other state that does not allow an acceptance (409 state_conflict), then the consent rules (400 with the pointer `/consent_c4/text_version` for a text version that is not the published one, or `/consent_c4/fields/0` for a field that the profile does not hold). The schema rejects a missing `terms_version`, an empty or repeated field list, an unknown field kind, `accepted` other than true, and unknown fields such as `email` or `phone`. The general rate limit can answer 429 with Retry-After before any check. 404 and 409 state_conflict are stored under the key; 400, 412, and 429 are not. security: diff --git a/api/core/routes/candidate_invitation_cancel.yml b/api/core/routes/candidate_invitation_cancel.yml index 07a2804..4714c88 100644 --- a/api/core/routes/candidate_invitation_cancel.yml +++ b/api/core/routes/candidate_invitation_cancel.yml @@ -4,7 +4,7 @@ post: description: |- Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The candidate comes from the session. - Moves an unfinished invitation to the terminal state `cancelled_by_candidate` (PRD FR12): `delivered`, `viewed`, `accepted`, and the planned stages up to `negotiation`. The process closes. In the same transaction the server revokes the contact grant that the acceptance of this invitation created, with the reason `participation_cancelled`, so the next contact read of the organization answers 404. Grants of other invitations or applications stay; revoking the consent C4 for the organization as a whole, which closes all of them, belongs to the consent operations (TASK-064). + Moves an unfinished invitation to the terminal state `cancelled_by_candidate` (PRD FR12): `delivered`, `viewed`, `accepted`, and the planned stages up to `negotiation`. The process closes. In the same transaction the server revokes the contact grant that the acceptance of this invitation created, with the reason `participation_cancelled`, so the next contact read of the organization answers 404. Grants of other invitations or applications stay; revoking the consent C4 for the organization as a whole, which closes all of them, belongs to the consent operations. Cancel differs from decline and withdraw: a decline is the structured answer before an acceptance and counts as a response; a cancellation leaves the process at any unfinished stage, mostly after an acceptance, and carries no reason; a withdrawal is the organization's command and keeps the grant. Before an answer the client offers the decline. diff --git a/api/core/routes/candidate_invitation_view.yml b/api/core/routes/candidate_invitation_view.yml index 0fa90d4..294ab87 100644 --- a/api/core/routes/candidate_invitation_view.yml +++ b/api/core/routes/candidate_invitation_view.yml @@ -4,7 +4,7 @@ post: description: |- Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The candidate comes from the session. The request has no body. - The view transition of PRD FR12 (TASK-200) is an explicit command, so reading the invitation with GetMyInvitation stays free of side effects. The client sends it when the candidate opens the terms screen. For a `delivered` invitation the server moves it to `viewed`, sets `viewed_at`, advances `version`, and keeps the deadline. In any other state, including `viewed`, `accepted`, and the terminal states, it changes nothing and answers 200 with the current invitation. A view never reopens, extends, or answers an invitation, and the organization sees only the state `viewed` and `viewed_at`. + The view transition of PRD FR12 is an explicit command, so reading the invitation with GetMyInvitation stays free of side effects. The client sends it when the candidate opens the terms screen. For a `delivered` invitation the server moves it to `viewed`, sets `viewed_at`, advances `version`, and keeps the deadline. In any other state, including `viewed`, `accepted`, and the terminal states, it changes nothing and answers 200 with the current invitation. A view never reopens, extends, or answers an invitation, and the organization sees only the state `viewed` and `viewed_at`. The command is idempotent by its effect: the first view wins and every repeat returns the current invitation. It therefore needs no Idempotency-Key and no `expected_version`: a view must never fail because the invitation changed after the client read it, for example after a salary raise. A view at the deadline or later first applies the due expiry and answers 200 with `expired`. diff --git a/api/core/routes/candidate_privacy_access_history.yml b/api/core/routes/candidate_privacy_access_history.yml index 36d988d..878be37 100644 --- a/api/core/routes/candidate_privacy_access_history.yml +++ b/api/core/routes/candidate_privacy_access_history.yml @@ -6,7 +6,7 @@ get: An access is a view of the anonymous card by an organization (`card_viewed`) or a read of the contacts through an active contact grant (`contact_read`). Reading the history is not an access and writes nothing. A view of the card by an organization that has no invitation relation with the candidate carries `organization` null, so the candidate sees that the card was viewed without learning a company that they cannot otherwise see; a contact read always names the organization, because the candidate accepted its invitation. The entries carry no search query, filter, or ranking of the organization, and no organization the candidate hides ever appears as a viewer, because a hidden organization cannot read the card. - The storage of accesses is planned with the card and contact operations of the organization side (TASK-185 and the contact read of the invitation contract); until then the operation answers 501 not_implemented after the session and request checks. + The storage of accesses is planned with the card and contact operations of the organization side (anonymous card reads and contact reads under the invitation contract); until then the operation answers 501 not_implemented after the session and request checks. A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. A malformed `limit` or `cursor` answers 400 validation_failed. security: diff --git a/api/core/routes/candidate_privacy_publication.yml b/api/core/routes/candidate_privacy_publication.yml index 938e593..3178058 100644 --- a/api/core/routes/candidate_privacy_publication.yml +++ b/api/core/routes/candidate_privacy_publication.yml @@ -4,7 +4,7 @@ put: description: |- Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The body is the complete new publication setting: `state` `published` with the non-empty set of card fields, or `closed` with an empty set. It changes only the publication; the search status and the hidden organizations stay as they were. - Publication is not a consent and does not duplicate one. The consent C2 lives in the consent ledger (`ListMyConsents`); this setting refers to it. Publishing requires an active, unrevoked C2 record of the account and binds the publication to that record, so a client sends no consent identifier and cannot forge one. Without one the server answers 409 state_conflict with the entry `{in: body, pointer: /state, code: consent_required}` in `errors`, which tells it apart from every other conflict, and changes nothing: the client gives C2 first (planned in the consent settings, TASK-063) and then publishes. The server takes the C2 record under a share lock in the transaction that writes the publication, so a revocation that races with a publication either commits first (the publication is refused) or closes the card right after. A revocation of C2 closes the card at once, because `state` is computed from the unrevoked record; a later C2 grant never reopens it, and the candidate publishes again under the new record. The revocation path itself (TASK-064) closes the stored publication and revokes the contact grants in its own transaction. A closing sent over a stored publication whose C2 was revoked is a real change: it stores the closing, records `publication_closed`, and revokes the grants as any closing does. Publishing, like every visibility change, needs a verified email (a usecase requirement; the unverified account cleanup deletes only accounts without such records). Publishing never adds a field that the body did not name, and a new `CardField` value is never published for a candidate who did not choose it. + Publication is not a consent and does not duplicate one. The consent C2 lives in the consent ledger (`ListMyConsents`); this setting refers to it. Publishing requires an active, unrevoked C2 record of the account and binds the publication to that record, so a client sends no consent identifier and cannot forge one. Without one the server answers 409 state_conflict with the entry `{in: body, pointer: /state, code: consent_required}` in `errors`, which tells it apart from every other conflict, and changes nothing: the client gives C2 first (planned in the consent settings) and then publishes. The server takes the C2 record under a share lock in the transaction that writes the publication, so a revocation that races with a publication either commits first (the publication is refused) or closes the card right after. A revocation of C2 closes the card at once, because `state` is computed from the unrevoked record; a later C2 grant never reopens it, and the candidate publishes again under the new record. The revocation path itself closes the stored publication and revokes the contact grants in its own transaction. A closing sent over a stored publication whose C2 was revoked is a real change: it stores the closing, records `publication_closed`, and revokes the grants as any closing does. Publishing, like every visibility change, needs a verified email (a usecase requirement; the unverified account cleanup deletes only accounts without such records). Publishing never adds a field that the body did not name, and a new `CardField` value is never published for a candidate who did not choose it. The field set contains only the groups of `CardField`. The full name, contacts, and the lowest salary have no value there, so no body can publish them. Only values that the candidate confirmed ever reach the card. Contacts reach an organization only through the contact grant (C4), and a profile that is published or closed changes none of the grants that exist; closing the publication, and hiding an organization that holds a grant, revoke the contact grants concerned with the reason `visibility_closed` in the same transaction as the change (planned together with the operations, see the invitation contract). diff --git a/api/core/routes/consents.yml b/api/core/routes/consents.yml index 9bdfdae..cbaeb15 100644 --- a/api/core/routes/consents.yml +++ b/api/core/routes/consents.yml @@ -6,9 +6,9 @@ get: The ledger is append-only. Every grant is a record with its purpose, the accepted text version, the source, and the grant time; the server also stores the hash of exactly the text the subject saw. A newer text version of the same purpose is a new record, and the earlier one becomes `superseded` without any change. A revocation stamps every unrevoked record of the purpose, and for c4 of one organization, once; a later grant is a new record. Purposes are independent. - Without `state` the page lists the whole history; `state=active` lists the consents that hold now, one per purpose for c1, c2, c3, and c5 and one per accepted invitation for c4. A c4 record names the organization with the name its consent text showed (a snapshot that a later rename does not change), the selected contact fields, and the invitation with its terms version; it never carries a contact value. A c2 record proves the consent to the publication text; the published field set and its changes are evidence of the publication history (TASK-088). + Without `state` the page lists the whole history; `state=active` lists the consents that hold now, one per purpose for c1, c2, c3, and c5 and one per accepted invitation for c4. A c4 record names the organization with the name its consent text showed (a snapshot that a later rename does not change), the selected contact fields, and the invitation with its terms version; it never carries a contact value. A c2 record proves the consent to the publication text; the published field set and its changes are evidence of the publication history. - Granting c1, c2, c3, and c5 in the consent settings and revoking any purpose are planned operations of this tag (TASK-063 and TASK-064); c1 is given at registration and c4 only in AcceptMyInvitation. + Granting c1, c2, c3, and c5 in the consent settings and revoking any purpose are planned operations of this tag; c1 is given at registration and c4 only in AcceptMyInvitation. Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated. A malformed `limit`, `cursor`, or `state` answers 400 validation_failed. security: diff --git a/api/core/routes/organization_invitation.yml b/api/core/routes/organization_invitation.yml index 672d4bd..f925302 100644 --- a/api/core/routes/organization_invitation.yml +++ b/api/core/routes/organization_invitation.yml @@ -53,7 +53,7 @@ patch: Versions: every committed change creates version `expected_version + 1`; a change of the terms also creates the next terms version, an immutable snapshot, and a change of anything else keeps the terms version. `expected_version` is the `version` the client read; when it is not current, the server answers 412 version_conflict and changes nothing, and the client reads the invitation again. The version travels in the body because the generated client cannot read the ETag response header yet. The operation needs no Idempotency-Key: a body that changes nothing when applied to the current version, such as a retry of a change that already succeeded, keeps the version and answers 200 with the current invitation even when `expected_version` is older. - Salary limit: every change that can move `salary_fit` is an indicator-relevant setting: a change of either salary bound, of the tax basis, or of `work_formats`, because the indicator compares with the candidate's minimum for the offered formats, and switching formats or the basis would otherwise probe the minimum for free. Such a change counts against the limit shared by the organization with needs and other drafts, at most three settings a day, and against the withheld counter, which withholds `salary_fit` for seven days from the fifth setting within seven days (PRD FR13, planned in TASK-211; see InvitationSalaryFit). Over the limit the server answers 429 with Retry-After and changes nothing. A change that keeps the range, the basis, and the formats does not count. The operation follows the convention of UpdateOrganizationNeed: no Idempotency-Key, and a body that changes nothing answers 200. + Salary limit: every change that can move `salary_fit` is an indicator-relevant setting: a change of either salary bound, of the tax basis, or of `work_formats`, because the indicator compares with the candidate's minimum for the offered formats, and switching formats or the basis would otherwise probe the minimum for free. Such a change counts against the limit shared by the organization with needs and other drafts, at most three settings a day, and against the withheld counter, which withholds `salary_fit` for seven days from the fifth setting within seven days (PRD FR13, enforcement planned; see InvitationSalaryFit). Over the limit the server answers 429 with Retry-After and changes nothing. A change that keeps the range, the basis, and the formats does not count. The operation follows the convention of UpdateOrganizationNeed: no Idempotency-Key, and a body that changes nothing answers 200. Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for a candidate), membership (404 not_found) and role (403 forbidden), the invitation (404 not_found), a body that changes nothing (200), the version (412), the state (409 state_conflict), domain rules (400 with the pointers of CreateOrganizationInvitation), then the salary limit (429). security: diff --git a/api/core/routes/organization_invitation_contacts.yml b/api/core/routes/organization_invitation_contacts.yml index f052fe6..9fdd29f 100644 --- a/api/core/routes/organization_invitation_contacts.yml +++ b/api/core/routes/organization_invitation_contacts.yml @@ -2,13 +2,13 @@ get: operationId: GetOrganizationInvitationContacts summary: Read the contacts that the candidate disclosed to the organization. description: |- - Requires the session cookie of an employer account with an active membership in `org_id`. In the MVP only the owner of the organization reads contacts (TASK-202); the other roles of PRD FR07 are planned. + Requires the session cookie of an employer account with an active membership in `org_id`. In the MVP only the owner of the organization reads contacts; the other roles of PRD FR07 are planned. This is the only operation that returns contact values, and its response is separate from the terms and from the invitation. It answers only while a grant created by the acceptance of this invitation is active and the read is allowed now: on every request the server checks the membership, the consent C4 for this organization, the grant and its fields, and the current visibility of the profile (C2 and the organizations the candidate hid the profile from), with no cache in between, so a revocation closes the next read at once. The response holds exactly the fields that the grant covers; every other field is null. A grant of organization A never answers for organization B. Without such a grant the contacts do not exist for the caller, and the operation answers 404 not_found, the same as for an unknown invitation: before an acceptance, after a decline or an expiry, after the candidate revoked C4 or cancelled the participation, after the candidate closed the visibility, and while a grant created when the profile was not published or was hidden from the organization stays blocked. The answer does not tell which applies; `contact_access` of GetOrganizationInvitation tells the organization whether access is `not_granted`, `available`, or `closed`, without the reason, and the candidate sees `readable` and `blocked_by` on the grant. Withdrawing the invitation keeps an existing grant. A later publication of the profile never reopens a closed grant; only a new explicit C4 creates a new one. - Every successful read is recorded in the access audit (planned in TASK-090 and TASK-202), and the response has `Cache-Control: no-store`. + Every successful read is recorded in the access audit (planned with the contact access history), and the response has `Cache-Control: no-store`. Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden; an account without an active membership in the organization, an unknown organization, an unknown invitation, an invitation of another organization, and an invitation without an active readable grant all answer 404 not_found; a member whose role does not allow reading contacts answers 403 forbidden. An `org_id` or `invitation_id` that is not a UUID answers 400 validation_failed with the path pointer. security: diff --git a/api/core/routes/organization_invitation_send.yml b/api/core/routes/organization_invitation_send.yml index e735882..b08c8b6 100644 --- a/api/core/routes/organization_invitation_send.yml +++ b/api/core/routes/organization_invitation_send.yml @@ -4,9 +4,9 @@ post: description: |- Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. In the MVP only the owner of the organization sends invitations. - Sends the current terms version of a `draft`. Sending is internal and never visible as a state: in one transaction the server records the delivery, creates the candidate's inbox entry, starts the deadline `response_deadline_at = delivered_at + response_period_days`, spends one invitation of the weekly organization quota, and writes the outbox event for the notification (TASK-199), then answers 200 with the state `delivered`. A successful answer therefore means the candidate can already read the invitation; an email is a separate notification that never blocks or delays it, and its retries never move the deadline. No contact of the candidate is disclosed by sending. + Sends the current terms version of a `draft`. Sending is internal and never visible as a state: in one transaction the server records the delivery, creates the candidate's inbox entry, starts the deadline `response_deadline_at = delivered_at + response_period_days`, spends one invitation of the weekly organization quota, and writes the outbox event for the notification, then answers 200 with the state `delivered`. A successful answer therefore means the candidate can already read the invitation; an email is a separate notification that never blocks or delays it, and its retries never move the deadline. No contact of the candidate is disclosed by sending. - The server checks again that the candidate is still visible to the organization: a revoked publication C2 or a profile hidden from the organization answers 409 state_conflict without telling which. It also enforces the limits of the product policy: at most 20 invitations waiting for an answer per need (`delivered`, `viewed`, `counter`) and the 30-day pause for the pair of the organization and the candidate after a decline or a no deal, regardless of the member or the need, both with 409 state_conflict; and the rolling weekly quota of the organization (TASK-087), with 429 and Retry-After. The pending limit and the quota are planned in TASK-205 and TASK-087. + The server checks again that the candidate is still visible to the organization: a revoked publication C2 or a profile hidden from the organization answers 409 state_conflict without telling which. It also enforces the limits of the product policy: at most 20 invitations waiting for an answer per need (`delivered`, `viewed`, `counter`) and the 30-day pause for the pair of the organization and the candidate after a decline or a no deal, regardless of the member or the need, both with 409 state_conflict; and the rolling weekly quota of the organization, with 429 and Retry-After. Enforcement of the pending limit and the organization quota is planned. Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, and a send of an invitation that was already sent answers 200 with the invitation in its current state even with a new key or an older `expected_version`; the quota is spent once. A stale `expected_version` on a draft answers 412 version_conflict, so the organization never sends terms it did not read. diff --git a/api/core/routes/organization_invitations.yml b/api/core/routes/organization_invitations.yml index 58641eb..d960691 100644 --- a/api/core/routes/organization_invitations.yml +++ b/api/core/routes/organization_invitations.yml @@ -48,7 +48,7 @@ post: The terms are complete from the start (PRD FR12): the role, the specialization and the grade, the offer type, the tasks, the team, the technology stack, the work formats and the place of work, the communication method, the salary range in RUB with its tax basis, and the package. Each package condition is either `provided` with a description or explicitly `not_provided`; leaving one out fails validation. A draft without the tax basis or the communication method therefore cannot exist. The draft is created as version 1 with terms version 1, and the candidate does not see it until SendOrganizationInvitation. - Salary: SalaryRange applies the same rules as for a need: whole rubles, positive multiples of 1000, `salary_from < salary_to`, and a width from 10% to 40% of the midpoint, checked by the server in integer arithmetic. The response carries `salary_fit`, the coarse indicator of PRD FR13 against the candidate's hidden minimum; the exact minimum appears in no response. The server never rejects a range because of the minimum, since a rejection would reveal it. Creating a draft is an indicator-relevant setting: it counts against the limit shared by the whole organization with the ranges of needs, at most three settings a day, and against the withheld counter, after five settings within seven days the indicator is `withheld` for seven days from the fifth, on every draft and invitation of the organization (PRD FR13, planned in TASK-211; see InvitationSalaryFit). Over the limit the server answers 429 with Retry-After and creates nothing. + Salary: SalaryRange applies the same rules as for a need: whole rubles, positive multiples of 1000, `salary_from < salary_to`, and a width from 10% to 40% of the midpoint, checked by the server in integer arithmetic. The response carries `salary_fit`, the coarse indicator of PRD FR13 against the candidate's hidden minimum; the exact minimum appears in no response. The server never rejects a range because of the minimum, since a rejection would reveal it. Creating a draft is an indicator-relevant setting: it counts against the limit shared by the whole organization with the ranges of needs, at most three settings a day, and against the withheld counter, after five settings within seven days the indicator is `withheld` for seven days from the fifth, on every draft and invitation of the organization (PRD FR13, enforcement planned; see InvitationSalaryFit). Over the limit the server answers 429 with Retry-After and creates nothing. Idempotency: a retry with the same key and body within 24 hours replays the stored 201 and creates nothing, so a lost response never creates a second draft. A different body with the same key answers 422 idempotency_key_reused. 400 and 429 are never stored. diff --git a/api/core/routes/organization_need.yml b/api/core/routes/organization_need.yml index aec1add..c64260c 100644 --- a/api/core/routes/organization_need.yml +++ b/api/core/routes/organization_need.yml @@ -62,7 +62,7 @@ patch: The operation needs no Idempotency-Key: a body that changes nothing when applied to the current version, such as a retry of a change that already succeeded, keeps the version and answers 200 with the current need even when `expected_version` is older. An incomplete need is a valid result; `readiness.missing_fields` tells what remains. - Salary limit: the recommendations aggregate candidates' minimums against the upper bound, so setting or changing a confirmed salary range counts against a limit shared by the whole organization, every member and every need, together with ranges set on creation: at most three a day (PRD FR13, planned in TASK-211). 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 risk signals of TASK-319. + Salary limit: the recommendations aggregate candidates' minimums against the upper bound, so setting or changing a confirmed salary range counts against a limit shared by the whole organization, every member and every need, together with ranges set on creation: at most three a day (PRD FR13, enforcement planned). 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. Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for a candidate), membership (404 not_found) and role (403 forbidden), the need (404 not_found), a body that changes nothing (200), the version (412), domain rules (400 with a pointer such as `/salary/value/salary_to` for a range whose lower bound is not below the upper one or whose width is outside 10-40%, `/desired_skills/0/name` for a skill that is also in the required list, `/grade/status` or `/required_skills/2/status` for `extracted` with a value that is not the stored suggestion, or `/vacancy_id`), then the salary change limit (429). The schema rejects a missing or non-positive `expected_version`, unknown fields such as `rec_score`, `members`, `candidate_minimum`, or `version`, a field sent as a bare value instead of `{value, status}`, a list sent as null, a salary bound that is not a positive multiple of 1000, and an unknown currency, period, or tax basis. security: diff --git a/api/core/routes/organization_needs.yml b/api/core/routes/organization_needs.yml index afe693a..1d84d87 100644 --- a/api/core/routes/organization_needs.yml +++ b/api/core/routes/organization_needs.yml @@ -50,7 +50,7 @@ post: The need is saved even when critical fields are missing: the response is 201 with version 1, and `readiness.missing_fields` names each critical field without a confirmed value with a specific question. `recommendations` is computed by the server from the confirmed requirements only; the request cannot set a recommendation, its score, or its components. Creating a need never contacts a candidate or sends an invitation. - Salary limit: setting a salary range counts against a limit shared by the whole organization, every member and every need, on creation as on a change: at most three range settings a day (PRD FR13, planned in TASK-211). Over the limit the server answers 429 with Retry-After and creates nothing. After five settings within seven days the money component of the recommendations is `withheld` for seven days. The limit keeps an organization from probing hidden candidate minimums with new needs instead of edits; repeated range changes also feed the private risk signals of TASK-319. + Salary limit: setting a salary range counts against a limit shared by the whole organization, every member and every need, on creation as on a change: at most three range settings a day (PRD FR13, enforcement planned). Over the limit the server answers 429 with Retry-After and creates nothing. After five settings within seven days the money component of the recommendations is `withheld` for seven days. The limit keeps an organization from probing hidden candidate minimums with new needs instead of edits; repeated range changes also feed the private organization risk signals. Idempotency: a retry with the same key and body within 24 hours replays the stored 201 and creates nothing, so a lost response never creates a second need. A different body with the same key answers 422 idempotency_key_reused. 400 is never stored, so a corrected retry is evaluated again. diff --git a/api/core/routes/support_case.yml b/api/core/routes/support_case.yml index 2998471..cb5b4ad 100644 --- a/api/core/routes/support_case.yml +++ b/api/core/routes/support_case.yml @@ -8,7 +8,7 @@ get: The history lists every public event and is never truncated: the server keeps a case within 200 events by rejecting a staff event that would leave no room for the terminal one. - The case must belong to the account of the session: a case of another account, including another member of the same organization, answers 404 not_found, the same as an unknown identifier, so identifiers cannot be probed. TASK-314 says forbidden for a foreign case URL; the contract answers 404 instead, so the client shows the same "not found" state for a foreign and an unknown case. A malformed `case_id` answers 400 validation_failed with the path pointer. + The case must belong to the account of the session: a case of another account, including another member of the same organization, answers 404 not_found, the same as an unknown identifier, so identifiers cannot be probed. The contract answers 404, so the client shows the same "not found" state for a foreign and an unknown case. A malformed `case_id` answers 400 validation_failed with the path pointer. security: - sessionCookie: [] tags: diff --git a/api/core/routes/support_cases.yml b/api/core/routes/support_cases.yml index 508d30f..a599be1 100644 --- a/api/core/routes/support_cases.yml +++ b/api/core/routes/support_cases.yml @@ -49,7 +49,7 @@ post: | `anticheat_appeal` | candidate | required; `assessment_attempt` of the caller with an anti-cheat review decision | none | | `manual_assessment` | candidate | optional; a prior `assessment_attempt` of the caller in the same specialization | required `assessment_target` | - An organization is visible to a candidate when it sent the candidate an invitation or when the organization contract (TASK-077) shows the candidate its profile, and to an employer account when the account has an active membership in it. Invitations are in the contract (TASK-196) but not implemented yet, so until they are, every `invitation` reference answers 404 not_found; anti-cheat review decisions are not either, so until TASK-173 every anti-cheat appeal answers 409 state_conflict. The schema rejects an object type that the case type does not accept, for example an organization in a grade appeal. + An organization is visible to a candidate when it sent the candidate an invitation or when the organization contract shows the candidate its profile, and to an employer account when the account has an active membership in it. Invitations are in the contract but not implemented yet, so until they are, every `invitation` reference answers 404 not_found; anti-cheat review decisions are not either, so until review decisions are implemented, every anti-cheat appeal answers 409 state_conflict. The schema rejects an object type that the case type does not accept, for example an organization in a grade appeal. Ownership of the reference: the server checks the object against the session account on every create. An unknown object and an object of someone else, such as another candidate's attempt, another account's case, or an invitation addressed to another person, both answer 404 not_found, so a reference never reveals whether a foreign object exists. An own case that a grade appeal cannot dispute, because it is not a manual assessment, is not resolved yet, or was resolved with another outcome, answers 409 state_conflict. An identifier that is not a UUID fails validation with the pointer `/object/id`. The case stores only the type and the identifier of the object. diff --git a/backend/db/migrations/00012_add_delivery_sending.sql b/backend/db/migrations/00012_add_delivery_sending.sql index a80ecad..104338f 100644 --- a/backend/db/migrations/00012_add_delivery_sending.sql +++ b/backend/db/migrations/00012_add_delivery_sending.sql @@ -1,5 +1,5 @@ -- +goose Up --- Sending of service identity mail (TASK-016). The sending worker claims a +-- Sending of service identity mail. The sending worker claims a -- due delivery under a lease, checks that the token and the account behind -- it are still current, and ends a delivery that must not be sent in a -- terminal non-sent status with a reason. @@ -112,8 +112,8 @@ ALTER TABLE deliveries ADD CONSTRAINT deliveries_body_present CHECK ( ); -- Serves the claim of due service mail. The predicate names the kinds the --- sending worker handles, so rows of other kinds (notifications, which wait --- for TASK-462) never enter the index and an idle poll does not scan them. +-- sending worker handles, so rows of other kinds (product notifications) +-- never enter the index and an idle poll does not scan them. -- The claim query repeats the kind literals so the planner can use it. CREATE INDEX deliveries_due_idx ON deliveries (next_attempt_at, id) diff --git a/backend/db/migrations/00013_create_candidate_profiles.sql b/backend/db/migrations/00013_create_candidate_profiles.sql index 383c0cb..eed7c09 100644 --- a/backend/db/migrations/00013_create_candidate_profiles.sql +++ b/backend/db/migrations/00013_create_candidate_profiles.sql @@ -1,5 +1,5 @@ -- +goose Up --- The manual candidate profile (PRD FR02, TASK-066): full name and contacts, +-- The manual candidate profile (PRD FR02): full name and contacts, -- stack, roles, work experience, soft skills, and desired terms, each value -- with its confirmation state and provenance. Enum-like columns are text with -- CHECK constraints, as in the identity tables. diff --git a/backend/db/migrations/00015_create_candidate_privacy.sql b/backend/db/migrations/00015_create_candidate_privacy.sql index dbf76c7..04d61d7 100644 --- a/backend/db/migrations/00015_create_candidate_privacy.sql +++ b/backend/db/migrations/00015_create_candidate_privacy.sql @@ -1,5 +1,5 @@ -- +goose Up --- Visibility of the candidate card (PRD FR02 and FR12, TASK-088): the +-- Visibility of the candidate card (PRD FR02 and FR12): the -- publication, the search status, the organizations the candidate hides the -- profile from, and the history of these settings. Enum-like columns are text -- with CHECK constraints, as in the other tables. diff --git a/backend/db/queries/candidate.sql b/backend/db/queries/candidate.sql index 17e12c7..18fc7bf 100644 --- a/backend/db/queries/candidate.sql +++ b/backend/db/queries/candidate.sql @@ -1,4 +1,4 @@ --- Queries of the manual candidate profile (TASK-066). The profile is personal +-- Queries of the manual candidate profile. The profile is personal -- data of the account that owns it: every statement is scoped by user_id, and -- no statement selects another account's row. None of them names a file, the -- ML service, or an FSP account, because the profile needs none. diff --git a/backend/db/queries/privacy.sql b/backend/db/queries/privacy.sql index 331961f..71e7a8a 100644 --- a/backend/db/queries/privacy.sql +++ b/backend/db/queries/privacy.sql @@ -1,4 +1,4 @@ --- Queries of the candidate visibility settings (TASK-088): the publication of +-- Queries of the candidate visibility settings: the publication of -- the card, the search status, the hidden organizations, and the history of -- these settings. Every statement is scoped by the candidate's user_id, and -- no statement selects another account's row. No statement reads or writes a @@ -285,7 +285,7 @@ FOR SHARE; -- organization. No row means the organization reads nothing, whichever of -- the reasons applies, so it cannot tell a hidden candidate from an -- unpublished one. Every organization-facing read of a publication starts --- from this shape (TASK-185, TASK-089, TASK-090). +-- from this shape. -- name: ReadPublicationVisibleToOrganization :one SELECT effective.user_id, diff --git a/backend/integration_test/mail_sender_test.go b/backend/integration_test/mail_sender_test.go index c8a4123..4b412f3 100644 --- a/backend/integration_test/mail_sender_test.go +++ b/backend/integration_test/mail_sender_test.go @@ -1016,7 +1016,7 @@ func TestServiceMailSending(t *testing.T) { } sender := harness.newSender(t, harness.transactor, 100, 3000) if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassIdle || len(fixture.Requests()[calls:]) != 0 { - t.Fatalf("pass = %+v with %d provider calls, want idle and none: notifications belong to TASK-462", result, len(fixture.Requests()[calls:])) + t.Fatalf("pass = %+v with %d provider calls, want idle and none: product notification sending is not implemented", result, len(fixture.Requests()[calls:])) } if got := harness.delivery(ctx, t, delivery.ID()); got.Status() != domain.DeliveryStatusPending || got.AttemptCount() != 0 { t.Fatalf("the notification is %s with %d attempts, want it untouched", got.Status(), got.AttemptCount()) diff --git a/backend/internal/adapter/primary/http/api/oas_handlers_gen.go b/backend/internal/adapter/primary/http/api/oas_handlers_gen.go index 960c680..4119481 100644 --- a/backend/internal/adapter/primary/http/api/oas_handlers_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_handlers_gen.go @@ -48,11 +48,11 @@ func (c *codeRecorder) Unwrap() http.ResponseWriter { // Allowed in `delivered` and `viewed` before `response_deadline_at`; accepting directly from // `delivered` is allowed, as in the PRD FR12 transition table. In one transaction the server moves the // invitation to `accepted`, records the consent C4 in the consent ledger with the organization, the -// fields, the invitation, the terms version, and the text version and its hash (TASK-062), creates the -// contact grant for exactly those fields, and writes the audit event (TASK-201). The response is the -// invitation with `contact_grant`. The acceptance never publishes the profile (C2) and never bypasses -// a profile hidden from the organization: the grant alone does not guarantee a read, and the -// organization reads only while the visibility allows it. +// fields, the invitation, the terms version, and the text version and its hash, creates the contact +// grant for exactly those fields, and writes the audit event. The response is the invitation with +// `contact_grant`. The acceptance never publishes the profile (C2) and never bypasses a profile hidden +// from the organization: the grant alone does not guarantee a read, and the organization reads only +// while the visibility allows it. // // 412 or 409: a `terms_version` or `expected_version` that is not current answers 412 // version_conflict, the repository status for a stale version, and records nothing; this is the stale @@ -62,9 +62,9 @@ func (c *codeRecorder) Unwrap() http.ResponseWriter { // the planned `counter`, or a command received at the deadline or later, which is late. A terminal // state and a passed deadline are checked before the versions: the server first applies the due // expiry, and the client then gets 409 for a withdrawn, expired, or late invitation even when its -// versions are stale, so it shows the final state instead of rereading and retrying. TASK-197, -// TASK-201, and TASK-204 say 409 for stale terms; the repository rule keeps 412 for any stale version, -// so clients branch on `version_conflict` to reread and on `state_conflict` to show the final state. +// versions are stale, so it shows the final state instead of rereading and retrying. The repository +// rule keeps 412 for any stale version, so clients branch on `version_conflict` to reread and on +// `state_conflict` to show the final state. // // Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, // and an acceptance of an invitation that is already `accepted` whose `terms_version` and set of @@ -72,8 +72,8 @@ func (c *codeRecorder) Unwrap() http.ResponseWriter { // answers 200 with it even with a new key, an older `expected_version`, or a current `terms_version` // that a later raise advanced; no second consent, grant, or audit event is created. A different terms // version or field set on an accepted invitation answers 409 state_conflict; changing the disclosed -// fields is a matter of the consent operations (TASK-064). Of two concurrent acceptances only one -// makes the transition. +// fields is a matter of the consent operations. Of two concurrent acceptances only one makes the +// transition. // // Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), // account scenario (403 forbidden for an employer), the Idempotency-Key (422, 409 @@ -330,7 +330,7 @@ func (s *Server) handleAcceptMyInvitationRequest(args [1]string, argsEscaped boo // In the same transaction the server revokes the contact grant that the acceptance of this invitation // created, with the reason `participation_cancelled`, so the next contact read of the organization // answers 404. Grants of other invitations or applications stay; revoking the consent C4 for the -// organization as a whole, which closes all of them, belongs to the consent operations (TASK-064). +// organization as a whole, which closes all of them, belongs to the consent operations. // // Cancel differs from decline and withdraw: a decline is the structured answer before an acceptance // and counts as a response; a cancellation leaves the process at any unfinished stage, mostly after an @@ -1048,10 +1048,10 @@ func (s *Server) handleCreateMyAssessmentAttemptRequest(args [0]string, argsEsca // `manual_assessment` | candidate | optional; a prior `assessment_attempt` of the caller in the same specialization | required `assessment_target` // // An organization is visible to a candidate when it sent the candidate an invitation or when the -// organization contract (TASK-077) shows the candidate its profile, and to an employer account when -// the account has an active membership in it. Invitations are in the contract (TASK-196) but not -// implemented yet, so until they are, every `invitation` reference answers 404 not_found; anti-cheat -// review decisions are not either, so until TASK-173 every anti-cheat appeal answers 409 +// organization contract shows the candidate its profile, and to an employer account when the account +// has an active membership in it. Invitations are in the contract but not implemented yet, so until +// they are, every `invitation` reference answers 404 not_found; anti-cheat review decisions are not +// either, so until review decisions are implemented, every anti-cheat appeal answers 409 // state_conflict. The schema rejects an object type that the case type does not accept, for example an // organization in a grade appeal. // @@ -1631,7 +1631,7 @@ func (s *Server) handleCreateOrganizationRequest(args [0]string, argsEscaped boo // indicator-relevant setting: it counts against the limit shared by the whole organization with the // ranges of needs, at most three settings a day, and against the withheld counter, after five settings // within seven days the indicator is `withheld` for seven days from the fifth, on every draft and -// invitation of the organization (PRD FR13, planned in TASK-211; see InvitationSalaryFit). Over the +// invitation of the organization (PRD FR13, enforcement planned; see InvitationSalaryFit). Over the // limit the server answers 429 with Retry-After and creates nothing. // // Idempotency: a retry with the same key and body within 24 hours replays the stored 201 and creates @@ -1913,10 +1913,10 @@ func (s *Server) handleCreateOrganizationInvitationRequest(args [1]string, argsE // // Salary limit: setting a salary range counts against a limit shared by the whole organization, every // member and every need, on creation as on a change: at most three range settings a day (PRD FR13, -// planned in TASK-211). Over the limit the server answers 429 with Retry-After and creates nothing. +// enforcement planned). Over the limit the server answers 429 with Retry-After and creates nothing. // After five settings within seven days the money component of the recommendations is `withheld` for // seven days. The limit keeps an organization from probing hidden candidate minimums with new needs -// instead of edits; repeated range changes also feed the private risk signals of TASK-319. +// instead of edits; repeated range changes also feed the private organization risk signals. // // Idempotency: a retry with the same key and body within 24 hours replays the stored 201 and creates // nothing, so a lost response never creates a second need. A different body with the same key answers @@ -5051,9 +5051,9 @@ func (s *Server) handleGetMyQuestionnaireRequest(args [0]string, argsEscaped boo // // The case must belong to the account of the session: a case of another account, including another // member of the same organization, answers 404 not_found, the same as an unknown identifier, so -// identifiers cannot be probed. TASK-314 says forbidden for a foreign case URL; the contract answers -// 404 instead, so the client shows the same "not found" state for a foreign and an unknown case. A -// malformed `case_id` answers 400 validation_failed with the path pointer. +// identifiers cannot be probed. The contract answers 404, so the client shows the same "not found" +// state for a foreign and an unknown case. A malformed `case_id` answers 400 validation_failed with +// the path pointer. // // GET /api/v1/me/support-cases/{case_id} func (s *Server) handleGetMySupportCaseRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { @@ -5693,8 +5693,7 @@ func (s *Server) handleGetOrganizationInvitationRequest(args [2]string, argsEsca // handleGetOrganizationInvitationContactsRequest handles GetOrganizationInvitationContacts operation. // // Requires the session cookie of an employer account with an active membership in `org_id`. In the MVP -// only the owner of the organization reads contacts (TASK-202); the other roles of PRD FR07 are -// planned. +// only the owner of the organization reads contacts; the other roles of PRD FR07 are planned. // // This is the only operation that returns contact values, and its response is separate from the terms // and from the invitation. It answers only while a grant created by the acceptance of this invitation @@ -5714,8 +5713,8 @@ func (s *Server) handleGetOrganizationInvitationRequest(args [2]string, argsEsca // Withdrawing the invitation keeps an existing grant. A later publication of the profile never reopens // a closed grant; only a new explicit C4 creates a new one. // -// Every successful read is recorded in the access audit (planned in TASK-090 and TASK-202), and the -// response has `Cache-Control: no-store`. +// Every successful read is recorded in the access audit (planned with the contact access history), and +// the response has `Cache-Control: no-store`. // // Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate // account answers 403 forbidden; an account without an active membership in the organization, an @@ -6566,8 +6565,8 @@ func (s *Server) handleHideOrganizationRequest(args [1]string, argsEscaped bool, // hidden organization cannot read the card. // // The storage of accesses is planned with the card and contact operations of the organization side -// (TASK-185 and the contact read of the invitation contract); until then the operation answers 501 -// not_implemented after the session and request checks. +// (anonymous card reads and contact reads under the invitation contract); until then the operation +// answers 501 not_implemented after the session and request checks. // // A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account // answers 403 forbidden. A malformed `limit` or `cursor` answers 400 validation_failed. @@ -6791,10 +6790,10 @@ func (s *Server) handleListMyCardAccessHistoryRequest(args [0]string, argsEscape // organization with the name its consent text showed (a snapshot that a later rename does not change), // the selected contact fields, and the invitation with its terms version; it never carries a contact // value. A c2 record proves the consent to the publication text; the published field set and its -// changes are evidence of the publication history (TASK-088). +// changes are evidence of the publication history. // // Granting c1, c2, c3, and c5 in the consent settings and revoking any purpose are planned operations -// of this tag (TASK-063 and TASK-064); c1 is given at registration and c4 only in AcceptMyInvitation. +// of this tag; c1 is given at registration and c4 only in AcceptMyInvitation. // // Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated. A malformed // `limit`, `cursor`, or `state` answers 400 validation_failed. @@ -10080,9 +10079,9 @@ func (s *Server) handleSaveMyQuestionnaireRequest(args [0]string, argsEscaped bo // Sends the current terms version of a `draft`. Sending is internal and never visible as a state: in // one transaction the server records the delivery, creates the candidate's inbox entry, starts the // deadline `response_deadline_at = delivered_at + response_period_days`, spends one invitation of the -// weekly organization quota, and writes the outbox event for the notification (TASK-199), then answers -// 200 with the state `delivered`. A successful answer therefore means the candidate can already read -// the invitation; an email is a separate notification that never blocks or delays it, and its retries +// weekly organization quota, and writes the outbox event for the notification, then answers 200 with +// the state `delivered`. A successful answer therefore means the candidate can already read the +// invitation; an email is a separate notification that never blocks or delays it, and its retries // never move the deadline. No contact of the candidate is disclosed by sending. // // The server checks again that the candidate is still visible to the organization: a revoked @@ -10090,8 +10089,8 @@ func (s *Server) handleSaveMyQuestionnaireRequest(args [0]string, argsEscaped bo // which. It also enforces the limits of the product policy: at most 20 invitations waiting for an // answer per need (`delivered`, `viewed`, `counter`) and the 30-day pause for the pair of the // organization and the candidate after a decline or a no deal, regardless of the member or the need, -// both with 409 state_conflict; and the rolling weekly quota of the organization (TASK-087), with 429 -// and Retry-After. The pending limit and the quota are planned in TASK-205 and TASK-087. +// both with 409 state_conflict; and the rolling weekly quota of the organization, with 429 and +// Retry-After. Enforcement of the pending limit and the organization quota is planned. // // Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, // and a send of an invitation that was already sent answers 200 with the invitation in its current @@ -10355,18 +10354,18 @@ func (s *Server) handleSendOrganizationInvitationRequest(args [2]string, argsEsc // the account and binds the publication to that record, so a client sends no consent identifier and // cannot forge one. Without one the server answers 409 state_conflict with the entry // `{in: body, pointer: /state, code: consent_required}` in `errors`, which tells it apart from every -// other conflict, and changes nothing: the client gives C2 first (planned in the consent settings, -// TASK-063) and then publishes. The server takes the C2 record under a share lock in the transaction -// that writes the publication, so a revocation that races with a publication either commits first (the -// publication is refused) or closes the card right after. A revocation of C2 closes the card at once, -// because `state` is computed from the unrevoked record; a later C2 grant never reopens it, and the -// candidate publishes again under the new record. The revocation path itself (TASK-064) closes the -// stored publication and revokes the contact grants in its own transaction. A closing sent over a -// stored publication whose C2 was revoked is a real change: it stores the closing, records -// `publication_closed`, and revokes the grants as any closing does. Publishing, like every visibility -// change, needs a verified email (a usecase requirement; the unverified account cleanup deletes only -// accounts without such records). Publishing never adds a field that the body did not name, and a new -// `CardField` value is never published for a candidate who did not choose it. +// other conflict, and changes nothing: the client gives C2 first (planned in the consent settings) and +// then publishes. The server takes the C2 record under a share lock in the transaction that writes the +// publication, so a revocation that races with a publication either commits first (the publication is +// refused) or closes the card right after. A revocation of C2 closes the card at once, because `state` +// is computed from the unrevoked record; a later C2 grant never reopens it, and the candidate +// publishes again under the new record. The revocation path itself closes the stored publication and +// revokes the contact grants in its own transaction. A closing sent over a stored publication whose C2 +// was revoked is a real change: it stores the closing, records `publication_closed`, and revokes the +// grants as any closing does. Publishing, like every visibility change, needs a verified email (a +// usecase requirement; the unverified account cleanup deletes only accounts without such records). +// Publishing never adds a field that the body did not name, and a new `CardField` value is never +// published for a candidate who did not choose it. // // The field set contains only the groups of `CardField`. The full name, contacts, and the lowest // salary have no value there, so no body can publish them. Only values that the candidate confirmed @@ -11662,11 +11661,11 @@ func (s *Server) handleUpdateOrganizationRequest(args [1]string, argsEscaped boo // candidate's minimum for the offered formats, and switching formats or the basis would otherwise // probe the minimum for free. Such a change counts against the limit shared by the organization with // needs and other drafts, at most three settings a day, and against the withheld counter, which -// withholds `salary_fit` for seven days from the fifth setting within seven days (PRD FR13, planned in -// TASK-211; see InvitationSalaryFit). Over the limit the server answers 429 with Retry-After and -// changes nothing. A change that keeps the range, the basis, and the formats does not count. The -// operation follows the convention of UpdateOrganizationNeed: no Idempotency-Key, and a body that -// changes nothing answers 200. +// withholds `salary_fit` for seven days from the fifth setting within seven days (PRD FR13, +// enforcement planned; see InvitationSalaryFit). Over the limit the server answers 429 with +// Retry-After and changes nothing. A change that keeps the range, the basis, and the formats does not +// count. The operation follows the convention of UpdateOrganizationNeed: no Idempotency-Key, and a +// body that changes nothing answers 200. // // Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), // account scenario (403 forbidden for a candidate), membership (404 not_found) and role (403 @@ -11955,10 +11954,10 @@ func (s *Server) handleUpdateOrganizationInvitationRequest(args [2]string, argsE // // Salary limit: the recommendations aggregate candidates' minimums against the upper bound, so setting // or changing a confirmed salary range counts against a limit shared by the whole organization, every -// member and every need, together with ranges set on creation: at most three a day (PRD FR13, planned -// in TASK-211). 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 risk signals of TASK-319. +// member and every need, together with ranges set on creation: at most three a day (PRD FR13, +// enforcement planned). 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. // // Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), // account scenario (403 forbidden for a candidate), membership (404 not_found) and role (403 @@ -12210,7 +12209,7 @@ func (s *Server) handleUpdateOrganizationNeedRequest(args [2]string, argsEscaped // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, // and an allowed Origin. The candidate comes from the session. The request has no body. // -// The view transition of PRD FR12 (TASK-200) is an explicit command, so reading the invitation with +// The view transition of PRD FR12 is an explicit command, so reading the invitation with // GetMyInvitation stays free of side effects. The client sends it when the candidate opens the terms // screen. For a `delivered` invitation the server moves it to `viewed`, sets `viewed_at`, advances // `version`, and keeps the deadline. In any other state, including `viewed`, `accepted`, and the diff --git a/backend/internal/adapter/primary/http/api/oas_schemas_gen.go b/backend/internal/adapter/primary/http/api/oas_schemas_gen.go index 5ff774c..c295b56 100644 --- a/backend/internal/adapter/primary/http/api/oas_schemas_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_schemas_gen.go @@ -193,14 +193,14 @@ func (s *AccountScenario) UnmarshalText(data []byte) error { // The anonymous candidate card as an organization reads it. Only values that the candidate confirmed // reach it; an unconfirmed suggestion and an unknown value never do. A free text value (a stack tag, a // soft skill, the location) that looks like a contact (an email address, a phone number, a URL or -// domain, a Telegram link, an @handle) is dropped by the builder (TASK-089) and never published. It -// carries no name, contact, resume text, employer, salary figure, account or profile identifier, and -// no schema of the private profile or of a contact disclosure is reachable from it; a contact reaches -// an organization only through the contact grant of an accepted invitation. Each property is null when +// domain, a Telegram link, an @handle) is dropped by the builder and never published. It carries no +// name, contact, resume text, employer, salary figure, account or profile identifier, and no schema of +// the private profile or of a contact disclosure is reachable from it; a contact reaches an +// organization only through the contact grant of an accepted invitation. Each property is null when // its field is not published or the candidate has no value for it, so the card does not tell the two // apart. The set of properties is closed, and an organization-visible card must never gain a property // that identifies the candidate. The search ranking and the full card of an organization's search -// result are defined by the search contract (TASK-185), which reuses this content. +// result are defined by the search contract, which reuses this content. // Ref: #/components/schemas/AnonymousCardContent type AnonymousCardContent struct { // Categories confirmed by assessment results, or null. @@ -4245,8 +4245,8 @@ func (s *ConsentPurpose) UnmarshalText(data []byte) error { // // - c1: processing of personal data, given at registration. // - c2: publication of the candidate card. The record proves the consent to the published text; which -// fields were published and when is evidence of the publication history (TASK-088), not of this -// record. Adding a field scope to c2 records later is an additive change. +// fields were published and when is evidence of the publication history, not of this record. Adding +// a field scope to c2 records later is an additive change. // - c3: automatic categorization. Without it the candidate can request a manual assessment by the // same rubric. // - c4: transfer of the selected contact data to one organization, currently given only in an @@ -4574,8 +4574,7 @@ func (s *ConsentRevocationSource) UnmarshalText(data []byte) error { // Where the subject gave the consent. // // - registration: the c1 acceptance of RegisterAccount. -// - consent_settings: the consent settings of the account, for c1, c2, c3, and c5 (planned, TASK-063 -// and TASK-064). +// - consent_settings: the consent settings of the account, for c1, c2, c3, and c5 (planned). // - invitation_acceptance: the c4 acceptance of AcceptMyInvitation. // // A c4 given when sending an application (PRD Q9) is planned as an additional value. @@ -4878,7 +4877,7 @@ func (s *ContactConsentOffer) SetAvailableFields(val []ContactFieldKind) { // Currently published text of the consent C4 for this invitation. The server stores an acceptance with // `text_version` and the hash of exactly this text, together with the organization, the selected -// fields, the invitation, and its terms version (the ledger of TASK-062). +// fields, the invitation, and its terms version (the consent ledger). // Ref: #/components/schemas/ContactConsentText type ContactConsentText struct { TextVersion ConsentTextVersion `json:"text_version"` @@ -4911,8 +4910,8 @@ func (s *ContactConsentText) SetText(val string) { // This is the only response that carries contact values, and it is separate from the terms and from // the invitation. Each field the grant does not cover is null, and so is a covered field that the // profile no longer holds. The response is never cached or stored by the server for later reads, so a -// revocation closes the next read at once. The value formats depend on the profile contract (FR02, -// TASK-066), which must store the same formats; see ContactFieldKind. +// revocation closes the next read at once. The value formats depend on the profile contract (FR02), +// which must store the same formats; see ContactFieldKind. // Ref: #/components/schemas/ContactDisclosure type ContactDisclosure struct { // Invitation whose acceptance created the grant. @@ -5045,10 +5044,10 @@ func (*ContactDisclosureHeaders) getOrganizationInvitationContactsRes() {} // - telegram: the Telegram username from the profile. // // The value formats are those of ContactDisclosure: 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, -// TASK-066) must store contacts in the same formats, so a disclosure never has to convert or drop a -// stored value. The FSP results of FR14, which need their own explicit permission, are planned as -// additional kinds. Adding a value is a contract change. +// 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 has to convert or drop a stored value. The +// FSP results of FR14, which need their own explicit permission, are planned as additional kinds. +// Adding a value is a contract change. // Ref: #/components/schemas/ContactFieldKind type ContactFieldKind string @@ -7244,9 +7243,9 @@ type InvitationRoleTitle string // `10 * minimum <= 11 * B`. // - above: the minimum is more than 10% above `B`. // - withheld: the organization made five indicator-relevant settings within seven days, so the -// indicator is off for seven days from the fifth (the limit of TASK-211). The response to the fifth -// setting already carries `withheld`, and so does every draft and invitation of the organization, -// existing ones included, until the period ends. +// indicator is off for seven days from the fifth. The response to the fifth setting already carries +// `withheld`, and so does every draft and invitation of the organization, existing ones included, +// until the period ends. // - not_available: the candidate set no minimum for the offered formats, or set it in the other tax // basis. // @@ -8031,8 +8030,8 @@ func (*LogoutNoContent) logoutRes() {} // - suspended: access is stopped, and the owner or the platform may restore it. // - removed: the owner or the platform ended the membership. A removal by the platform is not undone // by the owner or by an invitation: the acceptance of an employee invitation and the member -// management (TASK-082, TASK-084) must not reactivate it on their own. Who removed the member and -// why become additive fields of the member management. +// management must not reactivate it on their own. Who removed the member and why become additive +// fields of the member management. // - left: the member ended the membership. // // One account has at most one membership per organization, so a former member who returns gets the @@ -9194,7 +9193,7 @@ func (s *NeedMoneyFit) SetShare(val NilFloat64) { // - no_salary: the need has no confirmed salary range; the policy uses the neutral value 0.5 and // `share` is null. // - withheld: the organization changed salary ranges five times within seven days, so salary -// aggregates are withheld for seven days (PRD FR13, planned in TASK-211); the policy uses the +// aggregates are withheld for seven days (PRD FR13, enforcement planned); the policy uses the // neutral value 0.5 and `share` is null. // // An unknown candidate minimum never counts as zero. @@ -16289,7 +16288,7 @@ type OrganizationMembership struct { State MembershipState `json:"state"` // Moment the membership was first created. A member who left and returns keeps the same value, because // the pair has one membership; the moment of the latest activation is a planned additive field - // (`activated_at`, TASK-082). + // (`activated_at`). JoinedAt Timestamp `json:"joined_at"` } @@ -20913,8 +20912,8 @@ func (s *SupportCase) SetUpdatedAt(val Timestamp) { } // Who caused an event, by kind only. A case never names or identifies a moderator, an expert, or a -// support agent; experts and moderators of TASK-316 and TASK-323 are `support` too. Adding a value is -// a contract change. +// support agent; assessment experts and appeal moderators are `support` too. Adding a value is a +// contract change. // // - user: the author of the case. // - support: a person of the support, moderation, or expert staff. @@ -21949,8 +21948,8 @@ func (s *SupportCaseEvent) SetMessage(val NilSupportCasePublicText) { } // Kind of a public history event. Adding a value is a contract change. A reply of the author, planned -// with `waiting_for_user`, is a `reply` with the actor `user`, and a later revision of a decision -// (TASK-317) is another `decision` event, so neither needs a new value. +// with `waiting_for_user`, is a `reply` with the actor `user`, and a later revision of a decision is +// another `decision` event, so neither needs a new value. // // - created: the case was created; `status` is `submitted`. For an appeal or a manual assessment, a // `status_changed` event of the actor `system` to `waiting_expert` follows in the same transaction. @@ -22208,12 +22207,12 @@ func (s *SupportCaseObjectReference) SetID(val uuid.UUID) { // Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a // contract change: generated clients reject an unknown value. Planned values: `vacancy` and // `application` with the vacancies and protected applications of PRD FR16, and a profile finding with -// TASK-272. +// profile analysis. // // - assessment_attempt: an assessment attempt of the caller. // - organization: an organization that the caller can see. -// - invitation: an invitation addressed to the caller. Invitations are in the contract (TASK-196) but -// not implemented yet; until they are, every invitation reference answers 404 not_found. +// - invitation: an invitation addressed to the caller. Invitations are in the contract but not +// implemented yet; until they are, every invitation reference answers 404 not_found. // - support_case: another case of the caller, for example the resolved manual assessment that a grade // appeal disputes. // diff --git a/backend/internal/adapter/primary/http/api/oas_server_gen.go b/backend/internal/adapter/primary/http/api/oas_server_gen.go index 5ed9a02..46721f7 100644 --- a/backend/internal/adapter/primary/http/api/oas_server_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_server_gen.go @@ -23,11 +23,11 @@ type Handler interface { // Allowed in `delivered` and `viewed` before `response_deadline_at`; accepting directly from // `delivered` is allowed, as in the PRD FR12 transition table. In one transaction the server moves the // invitation to `accepted`, records the consent C4 in the consent ledger with the organization, the - // fields, the invitation, the terms version, and the text version and its hash (TASK-062), creates the - // contact grant for exactly those fields, and writes the audit event (TASK-201). The response is the - // invitation with `contact_grant`. The acceptance never publishes the profile (C2) and never bypasses - // a profile hidden from the organization: the grant alone does not guarantee a read, and the - // organization reads only while the visibility allows it. + // fields, the invitation, the terms version, and the text version and its hash, creates the contact + // grant for exactly those fields, and writes the audit event. The response is the invitation with + // `contact_grant`. The acceptance never publishes the profile (C2) and never bypasses a profile hidden + // from the organization: the grant alone does not guarantee a read, and the organization reads only + // while the visibility allows it. // // 412 or 409: a `terms_version` or `expected_version` that is not current answers 412 // version_conflict, the repository status for a stale version, and records nothing; this is the stale @@ -37,9 +37,9 @@ type Handler interface { // the planned `counter`, or a command received at the deadline or later, which is late. A terminal // state and a passed deadline are checked before the versions: the server first applies the due // expiry, and the client then gets 409 for a withdrawn, expired, or late invitation even when its - // versions are stale, so it shows the final state instead of rereading and retrying. TASK-197, - // TASK-201, and TASK-204 say 409 for stale terms; the repository rule keeps 412 for any stale version, - // so clients branch on `version_conflict` to reread and on `state_conflict` to show the final state. + // versions are stale, so it shows the final state instead of rereading and retrying. The repository + // rule keeps 412 for any stale version, so clients branch on `version_conflict` to reread and on + // `state_conflict` to show the final state. // // Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, // and an acceptance of an invitation that is already `accepted` whose `terms_version` and set of @@ -47,8 +47,8 @@ type Handler interface { // answers 200 with it even with a new key, an older `expected_version`, or a current `terms_version` // that a later raise advanced; no second consent, grant, or audit event is created. A different terms // version or field set on an accepted invitation answers 409 state_conflict; changing the disclosed - // fields is a matter of the consent operations (TASK-064). Of two concurrent acceptances only one - // makes the transition. + // fields is a matter of the consent operations. Of two concurrent acceptances only one makes the + // transition. // // Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), // account scenario (403 forbidden for an employer), the Idempotency-Key (422, 409 @@ -74,7 +74,7 @@ type Handler interface { // In the same transaction the server revokes the contact grant that the acceptance of this invitation // created, with the reason `participation_cancelled`, so the next contact read of the organization // answers 404. Grants of other invitations or applications stay; revoking the consent C4 for the - // organization as a whole, which closes all of them, belongs to the consent operations (TASK-064). + // organization as a whole, which closes all of them, belongs to the consent operations. // // Cancel differs from decline and withdraw: a decline is the structured answer before an acceptance // and counts as a response; a cancellation leaves the process at any unfinished stage, mostly after an @@ -186,10 +186,10 @@ type Handler interface { // `manual_assessment` | candidate | optional; a prior `assessment_attempt` of the caller in the same specialization | required `assessment_target` // // An organization is visible to a candidate when it sent the candidate an invitation or when the - // organization contract (TASK-077) shows the candidate its profile, and to an employer account when - // the account has an active membership in it. Invitations are in the contract (TASK-196) but not - // implemented yet, so until they are, every `invitation` reference answers 404 not_found; anti-cheat - // review decisions are not either, so until TASK-173 every anti-cheat appeal answers 409 + // organization contract shows the candidate its profile, and to an employer account when the account + // has an active membership in it. Invitations are in the contract but not implemented yet, so until + // they are, every `invitation` reference answers 404 not_found; anti-cheat review decisions are not + // either, so until review decisions are implemented, every anti-cheat appeal answers 409 // state_conflict. The schema rejects an object type that the case type does not accept, for example an // organization in a grade appeal. // @@ -315,7 +315,7 @@ type Handler interface { // indicator-relevant setting: it counts against the limit shared by the whole organization with the // ranges of needs, at most three settings a day, and against the withheld counter, after five settings // within seven days the indicator is `withheld` for seven days from the fifth, on every draft and - // invitation of the organization (PRD FR13, planned in TASK-211; see InvitationSalaryFit). Over the + // invitation of the organization (PRD FR13, enforcement planned; see InvitationSalaryFit). Over the // limit the server answers 429 with Retry-After and creates nothing. // // Idempotency: a retry with the same key and body within 24 hours replays the stored 201 and creates @@ -366,10 +366,10 @@ type Handler interface { // // Salary limit: setting a salary range counts against a limit shared by the whole organization, every // member and every need, on creation as on a change: at most three range settings a day (PRD FR13, - // planned in TASK-211). Over the limit the server answers 429 with Retry-After and creates nothing. + // enforcement planned). Over the limit the server answers 429 with Retry-After and creates nothing. // After five settings within seven days the money component of the recommendations is `withheld` for // seven days. The limit keeps an organization from probing hidden candidate minimums with new needs - // instead of edits; repeated range changes also feed the private risk signals of TASK-319. + // instead of edits; repeated range changes also feed the private organization risk signals. // // Idempotency: a retry with the same key and body within 24 hours replays the stored 201 and creates // nothing, so a lost response never creates a second need. A different body with the same key answers @@ -699,9 +699,9 @@ type Handler interface { // // The case must belong to the account of the session: a case of another account, including another // member of the same organization, answers 404 not_found, the same as an unknown identifier, so - // identifiers cannot be probed. TASK-314 says forbidden for a foreign case URL; the contract answers - // 404 instead, so the client shows the same "not found" state for a foreign and an unknown case. A - // malformed `case_id` answers 400 validation_failed with the path pointer. + // identifiers cannot be probed. The contract answers 404, so the client shows the same "not found" + // state for a foreign and an unknown case. A malformed `case_id` answers 400 validation_failed with + // the path pointer. // // GET /api/v1/me/support-cases/{case_id} GetMySupportCase(ctx context.Context, params GetMySupportCaseParams) (GetMySupportCaseRes, error) @@ -755,8 +755,7 @@ type Handler interface { // GetOrganizationInvitationContacts implements GetOrganizationInvitationContacts operation. // // Requires the session cookie of an employer account with an active membership in `org_id`. In the MVP - // only the owner of the organization reads contacts (TASK-202); the other roles of PRD FR07 are - // planned. + // only the owner of the organization reads contacts; the other roles of PRD FR07 are planned. // // This is the only operation that returns contact values, and its response is separate from the terms // and from the invitation. It answers only while a grant created by the acceptance of this invitation @@ -776,8 +775,8 @@ type Handler interface { // Withdrawing the invitation keeps an existing grant. A later publication of the profile never reopens // a closed grant; only a new explicit C4 creates a new one. // - // Every successful read is recorded in the access audit (planned in TASK-090 and TASK-202), and the - // response has `Cache-Control: no-store`. + // Every successful read is recorded in the access audit (planned with the contact access history), and + // the response has `Cache-Control: no-store`. // // Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate // account answers 403 forbidden; an account without an active membership in the organization, an @@ -891,8 +890,8 @@ type Handler interface { // hidden organization cannot read the card. // // The storage of accesses is planned with the card and contact operations of the organization side - // (TASK-185 and the contact read of the invitation contract); until then the operation answers 501 - // not_implemented after the session and request checks. + // (anonymous card reads and contact reads under the invitation contract); until then the operation + // answers 501 not_implemented after the session and request checks. // // A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account // answers 403 forbidden. A malformed `limit` or `cursor` answers 400 validation_failed. @@ -918,10 +917,10 @@ type Handler interface { // organization with the name its consent text showed (a snapshot that a later rename does not change), // the selected contact fields, and the invitation with its terms version; it never carries a contact // value. A c2 record proves the consent to the publication text; the published field set and its - // changes are evidence of the publication history (TASK-088). + // changes are evidence of the publication history. // // Granting c1, c2, c3, and c5 in the consent settings and revoking any purpose are planned operations - // of this tag (TASK-063 and TASK-064); c1 is given at registration and c4 only in AcceptMyInvitation. + // of this tag; c1 is given at registration and c4 only in AcceptMyInvitation. // // Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated. A malformed // `limit`, `cursor`, or `state` answers 400 validation_failed. @@ -1296,9 +1295,9 @@ type Handler interface { // Sends the current terms version of a `draft`. Sending is internal and never visible as a state: in // one transaction the server records the delivery, creates the candidate's inbox entry, starts the // deadline `response_deadline_at = delivered_at + response_period_days`, spends one invitation of the - // weekly organization quota, and writes the outbox event for the notification (TASK-199), then answers - // 200 with the state `delivered`. A successful answer therefore means the candidate can already read - // the invitation; an email is a separate notification that never blocks or delays it, and its retries + // weekly organization quota, and writes the outbox event for the notification, then answers 200 with + // the state `delivered`. A successful answer therefore means the candidate can already read the + // invitation; an email is a separate notification that never blocks or delays it, and its retries // never move the deadline. No contact of the candidate is disclosed by sending. // // The server checks again that the candidate is still visible to the organization: a revoked @@ -1306,8 +1305,8 @@ type Handler interface { // which. It also enforces the limits of the product policy: at most 20 invitations waiting for an // answer per need (`delivered`, `viewed`, `counter`) and the 30-day pause for the pair of the // organization and the candidate after a decline or a no deal, regardless of the member or the need, - // both with 409 state_conflict; and the rolling weekly quota of the organization (TASK-087), with 429 - // and Retry-After. The pending limit and the quota are planned in TASK-205 and TASK-087. + // both with 409 state_conflict; and the rolling weekly quota of the organization, with 429 and + // Retry-After. Enforcement of the pending limit and the organization quota is planned. // // Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, // and a send of an invitation that was already sent answers 200 with the invitation in its current @@ -1336,18 +1335,18 @@ type Handler interface { // the account and binds the publication to that record, so a client sends no consent identifier and // cannot forge one. Without one the server answers 409 state_conflict with the entry // `{in: body, pointer: /state, code: consent_required}` in `errors`, which tells it apart from every - // other conflict, and changes nothing: the client gives C2 first (planned in the consent settings, - // TASK-063) and then publishes. The server takes the C2 record under a share lock in the transaction - // that writes the publication, so a revocation that races with a publication either commits first (the - // publication is refused) or closes the card right after. A revocation of C2 closes the card at once, - // because `state` is computed from the unrevoked record; a later C2 grant never reopens it, and the - // candidate publishes again under the new record. The revocation path itself (TASK-064) closes the - // stored publication and revokes the contact grants in its own transaction. A closing sent over a - // stored publication whose C2 was revoked is a real change: it stores the closing, records - // `publication_closed`, and revokes the grants as any closing does. Publishing, like every visibility - // change, needs a verified email (a usecase requirement; the unverified account cleanup deletes only - // accounts without such records). Publishing never adds a field that the body did not name, and a new - // `CardField` value is never published for a candidate who did not choose it. + // other conflict, and changes nothing: the client gives C2 first (planned in the consent settings) and + // then publishes. The server takes the C2 record under a share lock in the transaction that writes the + // publication, so a revocation that races with a publication either commits first (the publication is + // refused) or closes the card right after. A revocation of C2 closes the card at once, because `state` + // is computed from the unrevoked record; a later C2 grant never reopens it, and the candidate + // publishes again under the new record. The revocation path itself closes the stored publication and + // revokes the contact grants in its own transaction. A closing sent over a stored publication whose C2 + // was revoked is a real change: it stores the closing, records `publication_closed`, and revokes the + // grants as any closing does. Publishing, like every visibility change, needs a verified email (a + // usecase requirement; the unverified account cleanup deletes only accounts without such records). + // Publishing never adds a field that the body did not name, and a new `CardField` value is never + // published for a candidate who did not choose it. // // The field set contains only the groups of `CardField`. The full name, contacts, and the lowest // salary have no value there, so no body can publish them. Only values that the candidate confirmed @@ -1549,11 +1548,11 @@ type Handler interface { // candidate's minimum for the offered formats, and switching formats or the basis would otherwise // probe the minimum for free. Such a change counts against the limit shared by the organization with // needs and other drafts, at most three settings a day, and against the withheld counter, which - // withholds `salary_fit` for seven days from the fifth setting within seven days (PRD FR13, planned in - // TASK-211; see InvitationSalaryFit). Over the limit the server answers 429 with Retry-After and - // changes nothing. A change that keeps the range, the basis, and the formats does not count. The - // operation follows the convention of UpdateOrganizationNeed: no Idempotency-Key, and a body that - // changes nothing answers 200. + // withholds `salary_fit` for seven days from the fifth setting within seven days (PRD FR13, + // enforcement planned; see InvitationSalaryFit). Over the limit the server answers 429 with + // Retry-After and changes nothing. A change that keeps the range, the basis, and the formats does not + // count. The operation follows the convention of UpdateOrganizationNeed: no Idempotency-Key, and a + // body that changes nothing answers 200. // // Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), // account scenario (403 forbidden for a candidate), membership (404 not_found) and role (403 @@ -1611,10 +1610,10 @@ type Handler interface { // // Salary limit: the recommendations aggregate candidates' minimums against the upper bound, so setting // or changing a confirmed salary range counts against a limit shared by the whole organization, every - // member and every need, together with ranges set on creation: at most three a day (PRD FR13, planned - // in TASK-211). 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 risk signals of TASK-319. + // member and every need, together with ranges set on creation: at most three a day (PRD FR13, + // enforcement planned). 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. // // Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), // account scenario (403 forbidden for a candidate), membership (404 not_found) and role (403 @@ -1635,7 +1634,7 @@ type Handler interface { // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, // and an allowed Origin. The candidate comes from the session. The request has no body. // - // The view transition of PRD FR12 (TASK-200) is an explicit command, so reading the invitation with + // The view transition of PRD FR12 is an explicit command, so reading the invitation with // GetMyInvitation stays free of side effects. The client sends it when the candidate opens the terms // screen. For a `delivered` invitation the server moves it to `viewed`, sets `viewed_at`, advances // `version`, and keeps the deadline. In any other state, including `viewed`, `accepted`, and the diff --git a/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go b/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go index d12d841..69cc614 100644 --- a/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go @@ -28,11 +28,11 @@ var _ Handler = UnimplementedHandler{} // Allowed in `delivered` and `viewed` before `response_deadline_at`; accepting directly from // `delivered` is allowed, as in the PRD FR12 transition table. In one transaction the server moves the // invitation to `accepted`, records the consent C4 in the consent ledger with the organization, the -// fields, the invitation, the terms version, and the text version and its hash (TASK-062), creates the -// contact grant for exactly those fields, and writes the audit event (TASK-201). The response is the -// invitation with `contact_grant`. The acceptance never publishes the profile (C2) and never bypasses -// a profile hidden from the organization: the grant alone does not guarantee a read, and the -// organization reads only while the visibility allows it. +// fields, the invitation, the terms version, and the text version and its hash, creates the contact +// grant for exactly those fields, and writes the audit event. The response is the invitation with +// `contact_grant`. The acceptance never publishes the profile (C2) and never bypasses a profile hidden +// from the organization: the grant alone does not guarantee a read, and the organization reads only +// while the visibility allows it. // // 412 or 409: a `terms_version` or `expected_version` that is not current answers 412 // version_conflict, the repository status for a stale version, and records nothing; this is the stale @@ -42,9 +42,9 @@ var _ Handler = UnimplementedHandler{} // the planned `counter`, or a command received at the deadline or later, which is late. A terminal // state and a passed deadline are checked before the versions: the server first applies the due // expiry, and the client then gets 409 for a withdrawn, expired, or late invitation even when its -// versions are stale, so it shows the final state instead of rereading and retrying. TASK-197, -// TASK-201, and TASK-204 say 409 for stale terms; the repository rule keeps 412 for any stale version, -// so clients branch on `version_conflict` to reread and on `state_conflict` to show the final state. +// versions are stale, so it shows the final state instead of rereading and retrying. The repository +// rule keeps 412 for any stale version, so clients branch on `version_conflict` to reread and on +// `state_conflict` to show the final state. // // Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, // and an acceptance of an invitation that is already `accepted` whose `terms_version` and set of @@ -52,8 +52,8 @@ var _ Handler = UnimplementedHandler{} // answers 200 with it even with a new key, an older `expected_version`, or a current `terms_version` // that a later raise advanced; no second consent, grant, or audit event is created. A different terms // version or field set on an accepted invitation answers 409 state_conflict; changing the disclosed -// fields is a matter of the consent operations (TASK-064). Of two concurrent acceptances only one -// makes the transition. +// fields is a matter of the consent operations. Of two concurrent acceptances only one makes the +// transition. // // Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), // account scenario (403 forbidden for an employer), the Idempotency-Key (422, 409 @@ -82,7 +82,7 @@ func (UnimplementedHandler) AcceptMyInvitation(ctx context.Context, req *Invitat // In the same transaction the server revokes the contact grant that the acceptance of this invitation // created, with the reason `participation_cancelled`, so the next contact read of the organization // answers 404. Grants of other invitations or applications stay; revoking the consent C4 for the -// organization as a whole, which closes all of them, belongs to the consent operations (TASK-064). +// organization as a whole, which closes all of them, belongs to the consent operations. // // Cancel differs from decline and withdraw: a decline is the structured answer before an acceptance // and counts as a response; a cancellation leaves the process at any unfinished stage, mostly after an @@ -203,10 +203,10 @@ func (UnimplementedHandler) CreateMyAssessmentAttempt(ctx context.Context, req * // `manual_assessment` | candidate | optional; a prior `assessment_attempt` of the caller in the same specialization | required `assessment_target` // // An organization is visible to a candidate when it sent the candidate an invitation or when the -// organization contract (TASK-077) shows the candidate its profile, and to an employer account when -// the account has an active membership in it. Invitations are in the contract (TASK-196) but not -// implemented yet, so until they are, every `invitation` reference answers 404 not_found; anti-cheat -// review decisions are not either, so until TASK-173 every anti-cheat appeal answers 409 +// organization contract shows the candidate its profile, and to an employer account when the account +// has an active membership in it. Invitations are in the contract but not implemented yet, so until +// they are, every `invitation` reference answers 404 not_found; anti-cheat review decisions are not +// either, so until review decisions are implemented, every anti-cheat appeal answers 409 // state_conflict. The schema rejects an object type that the case type does not accept, for example an // organization in a grade appeal. // @@ -338,7 +338,7 @@ func (UnimplementedHandler) CreateOrganization(ctx context.Context, req *Organiz // indicator-relevant setting: it counts against the limit shared by the whole organization with the // ranges of needs, at most three settings a day, and against the withheld counter, after five settings // within seven days the indicator is `withheld` for seven days from the fifth, on every draft and -// invitation of the organization (PRD FR13, planned in TASK-211; see InvitationSalaryFit). Over the +// invitation of the organization (PRD FR13, enforcement planned; see InvitationSalaryFit). Over the // limit the server answers 429 with Retry-After and creates nothing. // // Idempotency: a retry with the same key and body within 24 hours replays the stored 201 and creates @@ -392,10 +392,10 @@ func (UnimplementedHandler) CreateOrganizationInvitation(ctx context.Context, re // // Salary limit: setting a salary range counts against a limit shared by the whole organization, every // member and every need, on creation as on a change: at most three range settings a day (PRD FR13, -// planned in TASK-211). Over the limit the server answers 429 with Retry-After and creates nothing. +// enforcement planned). Over the limit the server answers 429 with Retry-After and creates nothing. // After five settings within seven days the money component of the recommendations is `withheld` for // seven days. The limit keeps an organization from probing hidden candidate minimums with new needs -// instead of edits; repeated range changes also feed the private risk signals of TASK-319. +// instead of edits; repeated range changes also feed the private organization risk signals. // // Idempotency: a retry with the same key and body within 24 hours replays the stored 201 and creates // nothing, so a lost response never creates a second need. A different body with the same key answers @@ -770,9 +770,9 @@ func (UnimplementedHandler) GetMyQuestionnaire(ctx context.Context) (r GetMyQues // // The case must belong to the account of the session: a case of another account, including another // member of the same organization, answers 404 not_found, the same as an unknown identifier, so -// identifiers cannot be probed. TASK-314 says forbidden for a foreign case URL; the contract answers -// 404 instead, so the client shows the same "not found" state for a foreign and an unknown case. A -// malformed `case_id` answers 400 validation_failed with the path pointer. +// identifiers cannot be probed. The contract answers 404, so the client shows the same "not found" +// state for a foreign and an unknown case. A malformed `case_id` answers 400 validation_failed with +// the path pointer. // // GET /api/v1/me/support-cases/{case_id} func (UnimplementedHandler) GetMySupportCase(ctx context.Context, params GetMySupportCaseParams) (r GetMySupportCaseRes, _ error) { @@ -835,8 +835,7 @@ func (UnimplementedHandler) GetOrganizationInvitation(ctx context.Context, param // GetOrganizationInvitationContacts implements GetOrganizationInvitationContacts operation. // // Requires the session cookie of an employer account with an active membership in `org_id`. In the MVP -// only the owner of the organization reads contacts (TASK-202); the other roles of PRD FR07 are -// planned. +// only the owner of the organization reads contacts; the other roles of PRD FR07 are planned. // // This is the only operation that returns contact values, and its response is separate from the terms // and from the invitation. It answers only while a grant created by the acceptance of this invitation @@ -856,8 +855,8 @@ func (UnimplementedHandler) GetOrganizationInvitation(ctx context.Context, param // Withdrawing the invitation keeps an existing grant. A later publication of the profile never reopens // a closed grant; only a new explicit C4 creates a new one. // -// Every successful read is recorded in the access audit (planned in TASK-090 and TASK-202), and the -// response has `Cache-Control: no-store`. +// Every successful read is recorded in the access audit (planned with the contact access history), and +// the response has `Cache-Control: no-store`. // // Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate // account answers 403 forbidden; an account without an active membership in the organization, an @@ -983,8 +982,8 @@ func (UnimplementedHandler) HideOrganization(ctx context.Context, params HideOrg // hidden organization cannot read the card. // // The storage of accesses is planned with the card and contact operations of the organization side -// (TASK-185 and the contact read of the invitation contract); until then the operation answers 501 -// not_implemented after the session and request checks. +// (anonymous card reads and contact reads under the invitation contract); until then the operation +// answers 501 not_implemented after the session and request checks. // // A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account // answers 403 forbidden. A malformed `limit` or `cursor` answers 400 validation_failed. @@ -1013,10 +1012,10 @@ func (UnimplementedHandler) ListMyCardAccessHistory(ctx context.Context, params // organization with the name its consent text showed (a snapshot that a later rename does not change), // the selected contact fields, and the invitation with its terms version; it never carries a contact // value. A c2 record proves the consent to the publication text; the published field set and its -// changes are evidence of the publication history (TASK-088). +// changes are evidence of the publication history. // // Granting c1, c2, c3, and c5 in the consent settings and revoking any purpose are planned operations -// of this tag (TASK-063 and TASK-064); c1 is given at registration and c4 only in AcceptMyInvitation. +// of this tag; c1 is given at registration and c4 only in AcceptMyInvitation. // // Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated. A malformed // `limit`, `cursor`, or `state` answers 400 validation_failed. @@ -1436,9 +1435,9 @@ func (UnimplementedHandler) SaveMyQuestionnaire(ctx context.Context, req *Candid // Sends the current terms version of a `draft`. Sending is internal and never visible as a state: in // one transaction the server records the delivery, creates the candidate's inbox entry, starts the // deadline `response_deadline_at = delivered_at + response_period_days`, spends one invitation of the -// weekly organization quota, and writes the outbox event for the notification (TASK-199), then answers -// 200 with the state `delivered`. A successful answer therefore means the candidate can already read -// the invitation; an email is a separate notification that never blocks or delays it, and its retries +// weekly organization quota, and writes the outbox event for the notification, then answers 200 with +// the state `delivered`. A successful answer therefore means the candidate can already read the +// invitation; an email is a separate notification that never blocks or delays it, and its retries // never move the deadline. No contact of the candidate is disclosed by sending. // // The server checks again that the candidate is still visible to the organization: a revoked @@ -1446,8 +1445,8 @@ func (UnimplementedHandler) SaveMyQuestionnaire(ctx context.Context, req *Candid // which. It also enforces the limits of the product policy: at most 20 invitations waiting for an // answer per need (`delivered`, `viewed`, `counter`) and the 30-day pause for the pair of the // organization and the candidate after a decline or a no deal, regardless of the member or the need, -// both with 409 state_conflict; and the rolling weekly quota of the organization (TASK-087), with 429 -// and Retry-After. The pending limit and the quota are planned in TASK-205 and TASK-087. +// both with 409 state_conflict; and the rolling weekly quota of the organization, with 429 and +// Retry-After. Enforcement of the pending limit and the organization quota is planned. // // Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, // and a send of an invitation that was already sent answers 200 with the invitation in its current @@ -1479,18 +1478,18 @@ func (UnimplementedHandler) SendOrganizationInvitation(ctx context.Context, req // the account and binds the publication to that record, so a client sends no consent identifier and // cannot forge one. Without one the server answers 409 state_conflict with the entry // `{in: body, pointer: /state, code: consent_required}` in `errors`, which tells it apart from every -// other conflict, and changes nothing: the client gives C2 first (planned in the consent settings, -// TASK-063) and then publishes. The server takes the C2 record under a share lock in the transaction -// that writes the publication, so a revocation that races with a publication either commits first (the -// publication is refused) or closes the card right after. A revocation of C2 closes the card at once, -// because `state` is computed from the unrevoked record; a later C2 grant never reopens it, and the -// candidate publishes again under the new record. The revocation path itself (TASK-064) closes the -// stored publication and revokes the contact grants in its own transaction. A closing sent over a -// stored publication whose C2 was revoked is a real change: it stores the closing, records -// `publication_closed`, and revokes the grants as any closing does. Publishing, like every visibility -// change, needs a verified email (a usecase requirement; the unverified account cleanup deletes only -// accounts without such records). Publishing never adds a field that the body did not name, and a new -// `CardField` value is never published for a candidate who did not choose it. +// other conflict, and changes nothing: the client gives C2 first (planned in the consent settings) and +// then publishes. The server takes the C2 record under a share lock in the transaction that writes the +// publication, so a revocation that races with a publication either commits first (the publication is +// refused) or closes the card right after. A revocation of C2 closes the card at once, because `state` +// is computed from the unrevoked record; a later C2 grant never reopens it, and the candidate +// publishes again under the new record. The revocation path itself closes the stored publication and +// revokes the contact grants in its own transaction. A closing sent over a stored publication whose C2 +// was revoked is a real change: it stores the closing, records `publication_closed`, and revokes the +// grants as any closing does. Publishing, like every visibility change, needs a verified email (a +// usecase requirement; the unverified account cleanup deletes only accounts without such records). +// Publishing never adds a field that the body did not name, and a new `CardField` value is never +// published for a candidate who did not choose it. // // The field set contains only the groups of `CardField`. The full name, contacts, and the lowest // salary have no value there, so no body can publish them. Only values that the candidate confirmed @@ -1707,11 +1706,11 @@ func (UnimplementedHandler) UpdateOrganization(ctx context.Context, req *Organiz // candidate's minimum for the offered formats, and switching formats or the basis would otherwise // probe the minimum for free. Such a change counts against the limit shared by the organization with // needs and other drafts, at most three settings a day, and against the withheld counter, which -// withholds `salary_fit` for seven days from the fifth setting within seven days (PRD FR13, planned in -// TASK-211; see InvitationSalaryFit). Over the limit the server answers 429 with Retry-After and -// changes nothing. A change that keeps the range, the basis, and the formats does not count. The -// operation follows the convention of UpdateOrganizationNeed: no Idempotency-Key, and a body that -// changes nothing answers 200. +// withholds `salary_fit` for seven days from the fifth setting within seven days (PRD FR13, +// enforcement planned; see InvitationSalaryFit). Over the limit the server answers 429 with +// Retry-After and changes nothing. A change that keeps the range, the basis, and the formats does not +// count. The operation follows the convention of UpdateOrganizationNeed: no Idempotency-Key, and a +// body that changes nothing answers 200. // // Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), // account scenario (403 forbidden for a candidate), membership (404 not_found) and role (403 @@ -1772,10 +1771,10 @@ func (UnimplementedHandler) UpdateOrganizationInvitation(ctx context.Context, re // // Salary limit: the recommendations aggregate candidates' minimums against the upper bound, so setting // or changing a confirmed salary range counts against a limit shared by the whole organization, every -// member and every need, together with ranges set on creation: at most three a day (PRD FR13, planned -// in TASK-211). 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 risk signals of TASK-319. +// member and every need, together with ranges set on creation: at most three a day (PRD FR13, +// enforcement planned). 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. // // Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), // account scenario (403 forbidden for a candidate), membership (404 not_found) and role (403 @@ -1799,7 +1798,7 @@ func (UnimplementedHandler) UpdateOrganizationNeed(ctx context.Context, req *Nee // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, // and an allowed Origin. The candidate comes from the session. The request has no body. // -// The view transition of PRD FR12 (TASK-200) is an explicit command, so reading the invitation with +// The view transition of PRD FR12 is an explicit command, so reading the invitation with // GetMyInvitation stays free of side effects. The client sends it when the candidate opens the terms // screen. For a `delivered` invitation the server moves it to `viewed`, sets `viewed_at`, advances // `version`, and keeps the deadline. In any other state, including `viewed`, `accepted`, and the diff --git a/backend/internal/adapter/primary/http/candidate_privacy_contract_test.go b/backend/internal/adapter/primary/http/candidate_privacy_contract_test.go index a2cbd08..ca3c35d 100644 --- a/backend/internal/adapter/primary/http/candidate_privacy_contract_test.go +++ b/backend/internal/adapter/primary/http/candidate_privacy_contract_test.go @@ -280,7 +280,7 @@ func TestAnonymousCardReachesNoProfileOrContactSchema(t *testing.T) { // The reverse: the private profile family does not reach the card or any // visibility schema, and an organization path reaches no setting of a // candidate. The card content stays the only privacy schema meant for - // organization-visible operations later (TASK-185). + // organization-visible operations later. for name, schema := range spec.Components.Schemas { if isPrivacySchema(name) { continue diff --git a/backend/internal/adapter/primary/http/router_test.go b/backend/internal/adapter/primary/http/router_test.go index 0ad31cd..043e726 100644 --- a/backend/internal/adapter/primary/http/router_test.go +++ b/backend/internal/adapter/primary/http/router_test.go @@ -355,7 +355,7 @@ func (security *recordingSecurity) HandleSessionCsrf(ctx context.Context, _ api. return ctx, nil } -// The session-bound CSRF check of TASK-056 relies on the generated server +// The session-bound CSRF check relies on the generated server // calling HandleSessionCookie before HandleSessionCsrf and passing the // returned context on. ogen orders the calls by scheme name, so renaming a // scheme or upgrading ogen must keep this test green. diff --git a/backend/internal/adapter/primary/http/v1/security.go b/backend/internal/adapter/primary/http/v1/security.go index a568529..61f8a4a 100644 --- a/backend/internal/adapter/primary/http/v1/security.go +++ b/backend/internal/adapter/primary/http/v1/security.go @@ -19,7 +19,7 @@ var errSessionsNotImplemented = errors.New("v1.DenyAllSecurity - sessions are no // call it and keep their own behavior, which is 501 not_implemented until // their business logic exists. // -// TASK-056 replaces it. The generated server (ogen v1.24.0) evaluates the +// Session authentication will replace it. The generated server (ogen v1.24.0) evaluates the // schemes of an operation as follows; TestGeneratedServerSecurityOrder pins // the order and the context propagation: // diff --git a/backend/internal/adapter/secondary/postgres/delivery_statistics.go b/backend/internal/adapter/secondary/postgres/delivery_statistics.go index 37e8649..9ad71ea 100644 --- a/backend/internal/adapter/secondary/postgres/delivery_statistics.go +++ b/backend/internal/adapter/secondary/postgres/delivery_statistics.go @@ -37,7 +37,7 @@ func (store *DeliveryStatisticsStore) DeliveryStatistics(ctx context.Context) (o statistics.Counts = append(statistics.Counts, count) earliest := row.EarliestPendingAttemptAt // Only service mail is picked up by a worker; a due notification - // waits for TASK-462 and must not count as overdue. + // awaits product notification sending and must not count as overdue. if !count.Kind.IsServiceMail() { continue } diff --git a/backend/internal/adapter/secondary/postgres/sqlc/candidate.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/candidate.sql.go index 2bd3ba2..6a4f942 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/candidate.sql.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/candidate.sql.go @@ -81,7 +81,7 @@ type InsertCandidateProfileParams struct { At pgtype.Timestamptz } -// Queries of the manual candidate profile (TASK-066). The profile is personal +// Queries of the manual candidate profile. The profile is personal // data of the account that owns it: every statement is scoped by user_id, and // no statement selects another account's row. None of them names a file, the // ML service, or an FSP account, because the profile needs none. diff --git a/backend/internal/adapter/secondary/postgres/sqlc/privacy.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/privacy.sql.go index 05d91be..b23a813 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/privacy.sql.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/privacy.sql.go @@ -480,7 +480,7 @@ type ReadCandidatePublicationRow struct { ConsentRevokedAt pgtype.Timestamptz } -// Queries of the candidate visibility settings (TASK-088): the publication of +// Queries of the candidate visibility settings: the publication of // the card, the search status, the hidden organizations, and the history of // these settings. Every statement is scoped by the candidate's user_id, and // no statement selects another account's row. No statement reads or writes a @@ -574,7 +574,7 @@ type ReadPublicationVisibleToOrganizationRow struct { // organization. No row means the organization reads nothing, whichever of // the reasons applies, so it cannot tell a hidden candidate from an // unpublished one. Every organization-facing read of a publication starts -// from this shape (TASK-185, TASK-089, TASK-090). +// from this shape. func (q *Queries) ReadPublicationVisibleToOrganization(ctx context.Context, arg ReadPublicationVisibleToOrganizationParams) (ReadPublicationVisibleToOrganizationRow, error) { row := q.db.QueryRow(ctx, readPublicationVisibleToOrganization, arg.UserID, arg.OrganizationID) var i ReadPublicationVisibleToOrganizationRow diff --git a/backend/internal/adapter/secondary/postgres/sqlc/querier.go b/backend/internal/adapter/secondary/postgres/sqlc/querier.go index 7361fdb..236969b 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/querier.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/querier.go @@ -243,7 +243,7 @@ type Querier interface { // field codes, and times, never a name; the caller // writes it in the transaction of the change it records. InsertCandidatePrivacyEvent(ctx context.Context, arg InsertCandidatePrivacyEventParams) error - // Queries of the manual candidate profile (TASK-066). The profile is personal + // Queries of the manual candidate profile. The profile is personal // data of the account that owns it: every statement is scoped by user_id, and // no statement selects another account's row. None of them names a file, the // ML service, or an FSP account, because the profile needs none. @@ -434,7 +434,7 @@ type Querier interface { // 0). Claims come in a stable order: single fields by kind, list items by // position. Never replace this with two statements. ReadCandidateProfile(ctx context.Context, userID pgtype.UUID) ([]ReadCandidateProfileRow, error) - // Queries of the candidate visibility settings (TASK-088): the publication of + // Queries of the candidate visibility settings: the publication of // the card, the search status, the hidden organizations, and the history of // these settings. Every statement is scoped by the candidate's user_id, and // no statement selects another account's row. No statement reads or writes a @@ -455,7 +455,7 @@ type Querier interface { // organization. No row means the organization reads nothing, whichever of // the reasons applies, so it cannot tell a hidden candidate from an // unpublished one. Every organization-facing read of a publication starts - // from this shape (TASK-185, TASK-089, TASK-090). + // from this shape. ReadPublicationVisibleToOrganization(ctx context.Context, arg ReadPublicationVisibleToOrganizationParams) (ReadPublicationVisibleToOrganizationRow, error) // Advances a delivery past one attempt and appends the attempt in one // statement, so both happen or neither does, inside or outside a diff --git a/backend/internal/domain/mail_content.go b/backend/internal/domain/mail_content.go index 0c5e39c..68af518 100644 --- a/backend/internal/domain/mail_content.go +++ b/backend/internal/domain/mail_content.go @@ -59,7 +59,7 @@ func ParseMailKind(value string) (MailKind, error) { // ServiceMailKinds lists the kinds of service identity mail, the kinds the // sending worker claims and sends. Notifications are not among them until -// their sending is connected (TASK-462). The delivery metrics of due mail, +// their sending is connected. The delivery metrics of due mail, // the sending worker, and the due index of the deliveries table follow this // list; changing it changes the predicate of deliveries_due_idx too. func ServiceMailKinds() []MailKind { diff --git a/backend/internal/domain/organization.go b/backend/internal/domain/organization.go index bb1f20c..b4c36ca 100644 --- a/backend/internal/domain/organization.go +++ b/backend/internal/domain/organization.go @@ -100,7 +100,7 @@ func (level OrganizationVerificationLevel) QuotaTier() (OrganizationTier, bool) return OrganizationTierE2, true case OrganizationVerificationE3: // The PRD gives E3 a separate policy, not a quota tier. A caller that - // reads quotas (TASK-087) must fail closed on false: grant no quota + // reads quotas must fail closed on false: grant no quota // and refuse the action, never fall back to a lower or a default tier. return "", false default: diff --git a/backend/internal/domain/policy.go b/backend/internal/domain/policy.go index 79d9f85..86a151b 100644 --- a/backend/internal/domain/policy.go +++ b/backend/internal/domain/policy.go @@ -278,8 +278,8 @@ type AssessmentPolicy struct { SameGradeRetryAfter CalendarDays // MaxAttemptsPerWindow limits attempts in any AttemptWindow. Whether the // limit counts per grade, per specialty, or across all assessments of a - // candidate is an open question for the attempt tasks (TASK-157 and - // TASK-158); the policy stores only the number. + // candidate is an open question for attempt accounting; + // the policy stores only the number. MaxAttemptsPerWindow int32 AttemptWindow CalendarDays // PromotionMinInterval is the minimum time between grade promotions. diff --git a/backend/internal/domain/visibility.go b/backend/internal/domain/visibility.go index a3df88d..7526303 100644 --- a/backend/internal/domain/visibility.go +++ b/backend/internal/domain/visibility.go @@ -14,8 +14,8 @@ import ( "golang.org/x/text/unicode/norm" ) -// This file holds the visibility settings of a candidate (PRD FR02 and FR12, -// TASK-088): the publication of the anonymous card, the search status, and the +// This file holds the visibility settings of a candidate (PRD FR02 and FR12): +// the publication of the anonymous card, the search status, and the // organizations the candidate hides the profile from. // // The rules that shape every type here: @@ -757,8 +757,7 @@ func (event PrivacyEvent) LogValue() slog.Value { ) } -// Rules for the content of an anonymous card (TASK-089 builds it; these are -// the hard requirements of this task): +// Rules for the content of an anonymous card: // - Only confirmed profile values ever reach the card. A suggestion that // the candidate did not confirm (status extracted) and an unknown value // never do. @@ -768,8 +767,8 @@ func (event PrivacyEvent) LogValue() slog.Value { // check the builder must apply to every free text before it enters the // card; it errs on the side of dropping. // - Quasi-identifiers (a rare combination of location, stack, and -// experience) and the generalization of rare features are an acceptance -// criterion of TASK-089, not decided here. +// experience) and the generalization of rare features must be handled +// by the card builder; they are not decided here. const ( // cardWordStart and cardWordEnd are Unicode word boundaries. Go's \b is @@ -813,8 +812,8 @@ var ( // with NFKC first, so fullwidth and compatibility forms of @, +, and digits // count, and every Unicode decimal digit counts toward a phone number. A card // builder drops such a value instead of publishing it. The check errs on the -// side of dropping; it is the barrier for free text until TASK-089 replaces -// free text by a closed taxonomy, which closes the residual risk. +// side of dropping; a closed taxonomy in the card builder is still needed +// to replace free text and address the residual risk. func CardTextLooksLikeContact(text string) bool { normalized := norm.NFKC.String(text) lowered := strings.ToLower(normalized) diff --git a/backend/internal/port/outbound/consents.go b/backend/internal/port/outbound/consents.go index d312579..ce8d7a5 100644 --- a/backend/internal/port/outbound/consents.go +++ b/backend/internal/port/outbound/consents.go @@ -81,7 +81,7 @@ type ConsentLedger interface { // Superseded is decided by granted_at, then the record ID: the // unrevoked record granted last is active, whatever its text version, // so Grant accepts any published version. The usecase consent.Service - // (TASK-063) is the path that checks that the version is the current + // is the path that checks that the version is the current // text of the purpose, ConsentTexts().Current at the grant time, before // it calls Grant; business code grants through it, not directly. // diff --git a/backend/internal/port/outbound/delivery_statistics.go b/backend/internal/port/outbound/delivery_statistics.go index f6f0cbd..fb1156f 100644 --- a/backend/internal/port/outbound/delivery_statistics.go +++ b/backend/internal/port/outbound/delivery_statistics.go @@ -23,7 +23,7 @@ type DeliveryStatistics struct { // EarliestPendingAttemptAt is the earliest NextAttemptAt of a pending // service mail delivery (domain.ServiceMailKinds, the kinds a worker // sends), by the application clock that wrote it; zero without one. A - // notification waits for its sending to be connected (TASK-462) and is + // notification waits for its sending to be connected and is // not counted, so it never looks overdue. EarliestPendingAttemptAt time.Time } diff --git a/backend/internal/port/outbound/identity.go b/backend/internal/port/outbound/identity.go index f625923..981f2b6 100644 --- a/backend/internal/port/outbound/identity.go +++ b/backend/internal/port/outbound/identity.go @@ -93,7 +93,7 @@ type UserRepository interface { // The same statement deletes the C1 records with the source // registration that the earlier registration of this account stored, // because the earlier registrant's consent must never stand for the new - // one. The registration usecase (TASK-053) must record the new C1 with + // one. The registration usecase must record the new C1 with // ConsentLedger().Grant in the same transaction; a version conflict // deletes nothing. UpdateRegistration(ctx context.Context, user domain.User) (domain.User, error) diff --git a/backend/internal/port/outbound/password.go b/backend/internal/port/outbound/password.go index 4848448..b9655ee 100644 --- a/backend/internal/port/outbound/password.go +++ b/backend/internal/port/outbound/password.go @@ -33,7 +33,7 @@ var ( // concurrent hashing; a context that ends while waiting returns the context // error and computes nothing. Errors never contain the password or the hash. // -// Login (TASK-055) must answer invalid_credentials for an unknown email, a +// Login must answer invalid_credentials for an unknown email, a // wrong password, and a stored hash that is invalid // (domain.ErrInvalidPasswordHash, from the repository or from Verify). For // an invalid hash it must also log an error and call VerifyDummy, because a diff --git a/backend/internal/usecase/consent/service.go b/backend/internal/usecase/consent/service.go index 5dc6bfe..ba43035 100644 --- a/backend/internal/usecase/consent/service.go +++ b/backend/internal/usecase/consent/service.go @@ -11,7 +11,7 @@ // // Revocation is not part of this package. Its downstream effects (closing // publication and grants, the deletion request, the manual path, stopping -// the import) belong to TASK-064, which calls ConsentLedger().Revoke. +// the import) belong to consent revocation, which calls ConsentLedger().Revoke. package consent import ( @@ -110,7 +110,7 @@ type SettingsGrantInput struct { // *StaleConsentTextError: an older one, one that is scheduled but not yet // published, and one that never existed. // -// The registration (TASK-053) must call it with C1 and the submitted version +// The registration must call it with C1 and the submitted version // before it branches on a new or an existing email. A stale version then // fails the same way for both, so the answer does not reveal whether the // account exists; GrantAtRegistration repeats the check inside the @@ -300,7 +300,7 @@ type ContactGrantInput struct { // It checks that TextVersion is the current C4 text like GrantInSettings does, and // the ledger checks that the hash is the hash of that text with the // organization name filled in. It is meant for the transaction of the -// acceptance (TASK-201), next to the invitation state change and the audit +// acceptance, next to the invitation state change and the audit // event. When the invitation already has a C4 record of the same subject, // the result has Created false and holds that record, revoked or not; the // caller compares its scope with the input to tell a repeat from a conflict. diff --git a/backend/internal/usecase/files/namespace.go b/backend/internal/usecase/files/namespace.go index 8fa31f8..aaa1c7f 100644 --- a/backend/internal/usecase/files/namespace.go +++ b/backend/internal/usecase/files/namespace.go @@ -7,11 +7,11 @@ package files type Namespace string const ( - // NamespaceResume holds uploaded resume files (TASK-070). + // NamespaceResume holds uploaded resume files. NamespaceResume Namespace = "resume" // NamespaceProfilePDF holds generated standard profile PDFs (FR02). NamespaceProfilePDF Namespace = "profile-pdf" - // NamespaceAccountExport holds personal data exports (TASK-093, TASK-458). + // NamespaceAccountExport holds personal data exports. NamespaceAccountExport Namespace = "account-export" ) diff --git a/backend/internal/usecase/files/store.go b/backend/internal/usecase/files/store.go index 3921f09..b40b050 100644 --- a/backend/internal/usecase/files/store.go +++ b/backend/internal/usecase/files/store.go @@ -61,7 +61,7 @@ func NewStore(storage outbound.ObjectStorage) *Store { // object. One race remains: when the whole body was sent before the caller // canceled, the server may still commit after the cleanup Delete returned. // Such an orphan has no Record, so a planned namespace sweeper that removes -// keys without a record (with backups, TASK-030 and TASK-458) is the final +// keys without a record (with backups) is the final // cleanup. See Record for the caller's order of operations. func (store *Store) Put(ctx context.Context, policy Policy, upload Upload) (Record, error) { if !policy.valid() { diff --git a/backend/internal/usecase/identity/credentials.go b/backend/internal/usecase/identity/credentials.go index c0a2680..ca978bb 100644 --- a/backend/internal/usecase/identity/credentials.go +++ b/backend/internal/usecase/identity/credentials.go @@ -23,7 +23,7 @@ func NewCredentials(hasher outbound.PasswordHasher) *Credentials { // HashNewPassword applies the registration password policy to raw and hashes // the normalized password. A password outside the policy returns an error // wrapping domain.ErrInvalidPassword without calling the hasher. Errors -// never contain raw. Registration (TASK-053, not implemented yet) must call +// never contain raw. Registration must call // it on every branch before it looks up the email, so that neither the // outcome nor the time depends on whether the account exists. func (credentials *Credentials) HashNewPassword(ctx context.Context, raw string) (domain.PasswordHash, error) { diff --git a/backend/internal/usecase/identity/register.go b/backend/internal/usecase/identity/register.go index e9122ac..8af78d2 100644 --- a/backend/internal/usecase/identity/register.go +++ b/backend/internal/usecase/identity/register.go @@ -332,7 +332,7 @@ func (registration *Registration) createAccount(ctx context.Context, unit outbou // reRegister starts a new registration of an unverified address. It never // changes the credentials, scenario, or onboarding step of the account row: // the new registration carries its own on its verification token, and -// confirming a token applies only the credentials of that token (TASK-054). +// confirming a token applies only the credentials of that token. // So neither the first nor the latest registrant of an address can make its // owner adopt a password the owner did not choose. The lock order of the // identity repositories applies: tokens first, then the account. diff --git a/backend/internal/usecase/notification/mail_request.go b/backend/internal/usecase/notification/mail_request.go index fe7f957..5968207 100644 --- a/backend/internal/usecase/notification/mail_request.go +++ b/backend/internal/usecase/notification/mail_request.go @@ -7,7 +7,7 @@ // consumer's dedup marker, reads the request, resolves the recipient address // from the account, renders the current template version once, stores the // Delivery, and deletes the request. Sending notifications is planned -// (TASK-462); no worker claims them yet. +// ; no worker claims them yet. // // Service mail of the account flows (email verification and password reset) // takes a shorter path: ServiceMailer stores its delivery directly in the diff --git a/backend/internal/usecase/notification/quota.go b/backend/internal/usecase/notification/quota.go index dbe1185..24b6d7a 100644 --- a/backend/internal/usecase/notification/quota.go +++ b/backend/internal/usecase/notification/quota.go @@ -40,7 +40,7 @@ var ( // is used up: the delivery waits for the reset in waiting_quota, and an // operator may decide otherwise. // -// The sending worker (ServiceMailSender, TASK-016) uses it in two +// The sending worker (ServiceMailSender) uses it in two // transactions around one transport call: // // 1. PrepareSend in the transaction that claims a due delivery. It either @@ -124,7 +124,7 @@ func (decision SendDecision) Proceed() bool { return !decision.Permit.IsZero() } // NextAttemptAt at the reset, which is what an operator and the user's // status view (DeliveryStatusReader) read; // - an unknown delivery is returned unchanged with ResetAt: its retry -// belongs to the retry policy (TASK-017), and parking it would hide that +// belongs to the retry policy, and parking it would hide that // an earlier attempt may have been accepted. // // The caller chooses which deliveries are due. A delivery pinned to another diff --git a/backend/internal/usecase/notification/send_retry.go b/backend/internal/usecase/notification/send_retry.go index 51a4249..d84e412 100644 --- a/backend/internal/usecase/notification/send_retry.go +++ b/backend/internal/usecase/notification/send_retry.go @@ -15,7 +15,7 @@ const jitterShare = 5 // (temporary or rate_limited), and of a delivery on which the sending worker // itself failed. It is the minimum that the delivery state machine needs, // because a pending delivery must say when it is due; the attempt limit, the -// unknown outcome policy, and manual retries belong to TASK-017. +// unknown outcome policy, and manual retries are part of the planned delivery retry policy. // // There is no limit on provider refusals on purpose: service mail carries a // token that expires, and the sending worker cancels the delivery with the diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md index 51d29b0..26e5c37 100644 --- a/docs/en/ARCHITECTURE.md +++ b/docs/en/ARCHITECTURE.md @@ -54,7 +54,7 @@ The MVP does not add a separate vector database, Kubernetes, or a search microse ### HTTP perimeter and client address -Implemented (TASK-042). The frontend Nginx is the only public HTTP entry. It serves the SPA, proxies `/api/v1/` to Go, and proxies the restricted `/telemetry`; every other path, including `/metrics`, `/readyz`, and administration paths of other services, is refused with 404. Security headers, a strict same-origin CSP, a 1 MB default body limit that answers 413 in the contract's problem format, and coarse per-client `limit_req`/`limit_conn` (429 with `Retry-After`) are set there; the limits are far above normal use and do not replace the domain quotas, which stay in the backend. The details and the checks are in [DEPLOY.md](DEPLOY.md#public-perimeter-and-client-address). +Implemented. The frontend Nginx is the only public HTTP entry. It serves the SPA, proxies `/api/v1/` to Go, and proxies the restricted `/telemetry`; every other path, including `/metrics`, `/readyz`, and administration paths of other services, is refused with 404. Security headers, a strict same-origin CSP, a 1 MB default body limit that answers 413 in the contract's problem format, and coarse per-client `limit_req`/`limit_conn` (429 with `Retry-After`) are set there; the limits are far above normal use and do not replace the domain quotas, which stay in the backend. The details and the checks are in [DEPLOY.md](DEPLOY.md#public-perimeter-and-client-address). The client address is derived only through trusted proxies. The edge replaces `X-Forwarded-For`; the app Nginx trusts the edge tunnel address and passes the backend one resolved entry; `middleware.ClientIP` (`backend/internal/adapter/primary/http/middleware/clientip.go`) trusts `X-Forwarded-For` only from `TRUSTED_PROXY_CIDRS` (by default only the pinned frontend container address) and reads it from the right, so an entry a client puts to the left of the first untrusted hop never counts. Usecases and handlers that need the address for a limiter read it with `middleware.ClientAddr(ctx)` and key the limiter with `middleware.LimiterKey` (IPv6 reduced to /64). The address is never logged or stored beyond the limiter window; the request log and metrics have no field for it. The first consumer is the registration and resend limits (see Registration and verification resend); the router mounts `ClientIP`. @@ -64,7 +64,7 @@ The client address is derived only through trusted proxies. The edge replaces `X - Keys have the form `/<32 hex characters>` from 128 random bits. Only the validated policy namespace comes from code; file names and other client input never become part of a key. `Open` and `Delete` accept only keys of their policy's namespace and format, so a client-shaped key, a traversal path, or another feature's key is rejected before storage is called. - Writes take the exact size. A declared size above the policy limit is rejected before any request. The stream passes through an `io.LimitReader` guard that withholds the last chunk until the source has ended, so a longer or shorter source aborts the request before storage receives a complete body. Any failure after the write started deletes the key, also after caller cancellation. Sources of unknown length are not buffered; a feature that needs them must spool to a bounded temporary file or add multipart upload. The source needs its own deadline, such as `http.ResponseController.SetReadDeadline` on a request body: `Put` waits for a blocked read, and canceling the context does not interrupt it. -- `Put` returns a `Record`: the key, the bare media type, the size, the SHA-256 digest computed while streaming, and the sanitized original name. The layer keeps no index and adds no tables. Callers follow one order: `Put`, then persist the record with their ownership data in a database transaction, then `Delete` the key if that transaction fails. One race remains: when the whole body was sent before the caller canceled, the server may commit after the cleanup `Delete` returned. Such orphans have no record and no request reaches them; a namespace sweeper that removes keys without a record is planned together with backups and exports (TASK-030, TASK-458) and does not exist yet. The original name is display metadata only: it is not stored in SeaweedFS and is never used in keys or logs, but it may still contain personal data. Sanitizing removes path elements, control, format, separator, and private-use characters and does not normalize Unicode. The content type is declared by the caller; detection by content belongs to the document parser. +- `Put` returns a `Record`: the key, the bare media type, the size, the SHA-256 digest computed while streaming, and the sanitized original name. The layer keeps no index and adds no tables. Callers follow one order: `Put`, then persist the record with their ownership data in a database transaction, then `Delete` the key if that transaction fails. One race remains: when the whole body was sent before the caller canceled, the server may commit after the cleanup `Delete` returned. Such orphans have no record and no request reaches them; a namespace sweeper that removes keys without a record is planned together with backups and exports and does not exist yet. The original name is display metadata only: it is not stored in SeaweedFS and is never used in keys or logs, but it may still contain personal data. Sanitizing removes path elements, control, format, separator, and private-use characters and does not normalize Unicode. The content type is declared by the caller; detection by content belongs to the document parser. - `Open` checks that the stored object still fits the policy and closes the response on every rejection. The caller closes the returned `File`; reading fails when the body differs from the stored size. The adapter's `SEAWEEDFS_TIMEOUT` bounds connection setup, the TLS handshake, and the wait for response headers, not the body transfer of `Put` and `Get`, so the caller's context is the only bound on a long or slow stream. `Delete` is idempotent, and absence maps to `files.ErrNotFound`. - There are no public URLs. The layer creates no public, permanent, or presigned URLs, and the bucket has no public policy or anonymous ACL. A browser download must go through an authenticated backend endpoint that checks current access and streams `File` with `Content-Disposition: attachment` and `X-Content-Type-Options: nosniff`, so a stored file is never rendered as a page of the application origin. The key, bucket, and storage URL never reach clients. @@ -99,7 +99,7 @@ The relay that publishes these rows is described in [Outbox relay](#outbox-relay ### Outbox relay -Implemented (TASK-009): the relay loop in `backend/internal/worker/outboxrelay/`, the `outbound.OutboxRelayStore` and `outbound.EventPublisher` ports (`backend/internal/port/outbound/outbox_relay.go`), the PostgreSQL store (`adapter/secondary/postgres/outbox_relay.go`), and the franz-go producer (`adapter/secondary/kafka/`). Bootstrap starts the relay together with the HTTP servers in the same process and stops it on shutdown. The relay has its own PostgreSQL pool of at most two connections, one for the claim transaction and one for the backlog read, so it never takes connections from request handling. It does not run when `RELAY_ENABLED=false` or `DATABASE_URL` is unset; the outbox then keeps the events. Settings are listed in [DEPLOY.md](DEPLOY.md#outbox-relay). +Implemented: the relay loop in `backend/internal/worker/outboxrelay/`, the `outbound.OutboxRelayStore` and `outbound.EventPublisher` ports (`backend/internal/port/outbound/outbox_relay.go`), the PostgreSQL store (`adapter/secondary/postgres/outbox_relay.go`), and the franz-go producer (`adapter/secondary/kafka/`). Bootstrap starts the relay together with the HTTP servers in the same process and stops it on shutdown. The relay has its own PostgreSQL pool of at most two connections, one for the claim transaction and one for the backlog read, so it never takes connections from request handling. It does not run when `RELAY_ENABLED=false` or `DATABASE_URL` is unset; the outbox then keeps the events. Settings are listed in [DEPLOY.md](DEPLOY.md#outbox-relay). One pass is one READ COMMITTED transaction: @@ -134,7 +134,7 @@ The metric `lincodex_outbox_relay_events_total{outcome}` counts published and fa ### Event consumers -Implemented (TASK-010): the consumer runtime in `backend/internal/worker/eventconsumer/`, the handler port `inbound.EventHandler` (`backend/internal/port/inbound/event_handler.go`), the `outbound.EventSource` and `outbound.EventConsumerStore` ports (`backend/internal/port/outbound/event_consumer.go`), the franz-go consumer group member (`adapter/secondary/kafka/consumer.go`), the PostgreSQL store (`adapter/secondary/postgres/event_consumer.go`), and migration `00005_create_event_consumer_tables.sql` with the `consumer_processed_events` and `consumer_dead_letters` tables. One product handler is registered (TASK-015): `eventHandlers()` in `backend/internal/bootstrap/consumers.go` returns the mail delivery handler `notification_delivery` described in [Mail deliveries](#mail-deliveries), so a backend with `CONSUMER_ENABLED` and `DATABASE_URL` runs one consumer in the group `.notification_delivery`. The runtime integration tests use a test-only handler that writes into a table the test creates. A product module adds its handler to that list. Settings are listed in [DEPLOY.md](DEPLOY.md#event-consumers). +Implemented: the consumer runtime in `backend/internal/worker/eventconsumer/`, the handler port `inbound.EventHandler` (`backend/internal/port/inbound/event_handler.go`), the `outbound.EventSource` and `outbound.EventConsumerStore` ports (`backend/internal/port/outbound/event_consumer.go`), the franz-go consumer group member (`adapter/secondary/kafka/consumer.go`), the PostgreSQL store (`adapter/secondary/postgres/event_consumer.go`), and migration `00005_create_event_consumer_tables.sql` with the `consumer_processed_events` and `consumer_dead_letters` tables. One product handler is registered: `eventHandlers()` in `backend/internal/bootstrap/consumers.go` returns the mail delivery handler `notification_delivery` described in [Mail deliveries](#mail-deliveries), so a backend with `CONSUMER_ENABLED` and `DATABASE_URL` runs one consumer in the group `.notification_delivery`. The runtime integration tests use a test-only handler that writes into a table the test creates. A product module adds its handler to that list. Settings are listed in [DEPLOY.md](DEPLOY.md#event-consumers). A handler implements three methods: @@ -174,7 +174,7 @@ The metric `lincodex_event_consumer_records_total{consumer,outcome}` counts fini ### Scheduled jobs -Implemented (TASK-035): durable jobs that run once when they fall due, such as a response deadline. The runtime is in `backend/internal/worker/jobrunner/`, the handler port `inbound.JobHandler` in `backend/internal/port/inbound/job_handler.go`, the `outbound.JobScheduler` and `outbound.JobStore` ports in `backend/internal/port/outbound/scheduled_job.go`, the validated `domain.ScheduledJob` in `backend/internal/domain/scheduled_job.go`, the PostgreSQL store and scheduler in `adapter/secondary/postgres/scheduled_job.go`, and migration `00008_create_scheduled_jobs.sql` with the `scheduled_jobs` table. No product handler is registered yet: `jobHandlers()` in `backend/internal/bootstrap/jobs.go` returns an empty list, so the backend logs `no scheduled job kind is registered` and starts no worker. The tests use a test-only kind. The first planned product kind is the invitation response deadline (TASK-205). Settings are in [DEPLOY.md](DEPLOY.md#scheduled-jobs). +Implemented: durable jobs that run once when they fall due, such as a response deadline. The runtime is in `backend/internal/worker/jobrunner/`, the handler port `inbound.JobHandler` in `backend/internal/port/inbound/job_handler.go`, the `outbound.JobScheduler` and `outbound.JobStore` ports in `backend/internal/port/outbound/scheduled_job.go`, the validated `domain.ScheduledJob` in `backend/internal/domain/scheduled_job.go`, the PostgreSQL store and scheduler in `adapter/secondary/postgres/scheduled_job.go`, and migration `00008_create_scheduled_jobs.sql` with the `scheduled_jobs` table. No product handler is registered yet: `jobHandlers()` in `backend/internal/bootstrap/jobs.go` returns an empty list, so the backend logs `no scheduled job kind is registered` and starts no worker. The tests use a test-only kind. The first planned product kind is the invitation response deadline. Settings are in [DEPLOY.md](DEPLOY.md#scheduled-jobs). Scheduling. A usecase calls `unit.ScheduledJobs().Schedule(ctx, job)` in its business transaction, so the job exists exactly when the change that needs it committed, and `Cancel(ctx, kind, key)` stops a job that has not finished. A job has a kind (the handler name, a lowercase dotted name), a key that identifies the logical job within its kind (for example an aggregate ID), a due time from the application clock, an optional attempt limit, and a payload: a flat JSON object of identifiers of at most 2 KiB. Neither the key nor the payload may contain personal data; the handler reads everything else from the source tables when it runs. `(kind, key)` is unique and the first schedule wins: a repeat inserts nothing (`INSERT ... ON CONFLICT DO NOTHING`) and reports `false`, also after the job ran or was canceled. This is insert-or-ignore rather than an upsert on purpose: a repeated command cannot move a deadline that must not be reset, and a stale writer cannot revive a finished job. A new occurrence needs a new key, for example `:`. @@ -196,7 +196,7 @@ Metrics: `lincodex_scheduled_jobs_total{kind,outcome}` counts claimed jobs by `d ### Mail transport -Implemented: the outbound `MailSender` port (`backend/internal/port/outbound/mail.go`), the `disabled` transport (`adapter/secondary/mail/disabled/`), the Resend transport (`adapter/secondary/mail/resend/`, the primary provider for the working stand), and the transport selection in bootstrap. Usecases, templates, and domain events depend only on the port; `EMAIL_PROVIDER` selects exactly one transport (`resend`, `smtp`, or `disabled`), and bootstrap binds the port to it before migrations run. There is no fallback between transports: an unusable selection stops startup. Planned: an SMTP relay transport (`mail/smtp/`, TASK-014, outside the MVP); until it exists, `smtp` fails startup after its settings are validated. The only caller is the sending worker for service identity mail (TASK-016, see [Sending service mail](#sending-service-mail)); product notifications are stored as deliveries but not sent until TASK-462. Settings are described in [DEPLOY.md](DEPLOY.md#mail). +Implemented: the outbound `MailSender` port (`backend/internal/port/outbound/mail.go`), the `disabled` transport (`adapter/secondary/mail/disabled/`), the Resend transport (`adapter/secondary/mail/resend/`, the primary provider for the working stand), and the transport selection in bootstrap. Usecases, templates, and domain events depend only on the port; `EMAIL_PROVIDER` selects exactly one transport (`resend`, `smtp`, or `disabled`), and bootstrap binds the port to it before migrations run. There is no fallback between transports: an unusable selection stops startup. Planned: an SMTP relay transport (`mail/smtp/`, outside the MVP); until it exists, `smtp` fails startup after its settings are validated. The only caller is the sending worker for service identity mail (see [Sending service mail](#sending-service-mail)); product notifications are stored as deliveries but not sent until product notification sending is implemented. Settings are described in [DEPLOY.md](DEPLOY.md#mail). `Send(ctx, OutgoingMail)` makes exactly one attempt. `OutgoingMail` carries the recipient, subject, text and HTML bodies, and an idempotency key that stays the same for one logical delivery across retries (1 to 256 printable ASCII characters, the Resend limit, without personal data); the sender comes from `EMAIL_FROM`. With a nil error the result is one of: @@ -206,7 +206,7 @@ Implemented: the outbound `MailSender` port (`backend/internal/port/outbound/mai `rejected` and `unknown` may carry `RetryAfter`, the provider's wait hint or a wait the transport derived from documented provider rules, and `ProviderCode`, the provider's error name. A `quota_exhausted` rejection also names the exhausted window in `QuotaPeriod` (`day` or `month`) when the provider said which; it is empty otherwise. A transport sets `ProviderCode` only from its fixed list of documented names and leaves it empty otherwise, so it never carries provider text and is safe to log and store. -A non-nil error means the message certainly did not leave the process: `ErrMailChannelUnavailable` in `disabled` mode, `ErrInvalidOutgoingMail` for an invalid message, or the context error when the caller's context ended before the request was written. A failure before the request was written while the context is still active is `rejected`/`temporary`, not an error. Retries, backoff, and recording outcomes belong to a single planned delivery layer, not to the transport. The verification flows (TASK-053, TASK-054) must treat `ErrMailChannelUnavailable` as not sent: it never confirms an address or replaces an account check. `OutgoingMail` redacts itself in `fmt` and `slog` output, and transport errors and logs never contain recipients, subjects, bodies, credentials, or raw provider responses. +A non-nil error means the message certainly did not leave the process: `ErrMailChannelUnavailable` in `disabled` mode, `ErrInvalidOutgoingMail` for an invalid message, or the context error when the caller's context ended before the request was written. A failure before the request was written while the context is still active is `rejected`/`temporary`, not an error. Retries, backoff, and recording outcomes belong to a single planned delivery layer, not to the transport. The verification flows must treat `ErrMailChannelUnavailable` as not sent: it never confirms an address or replaces an account check. `OutgoingMail` redacts itself in `fmt` and `slog` output, and transport errors and logs never contain recipients, subjects, bodies, credentials, or raw provider responses. The Resend transport uses `net/http` without an SDK. One `Send` is one `POST https://api.resend.com/emails` with `from` (`EMAIL_FROM`), `to` (one recipient), `subject`, `text`, and `html` (a blank part is omitted), an `Authorization: Bearer` key, a `User-Agent`, and `Idempotency-Key` set to the message's key. Resend keeps a key for 24 hours and answers the same key and body with the original result without sending again, so a retry must repeat the stored body under the same key; a changed body under an old key is a conflict, not a reason to make a new key. `EMAIL_TIMEOUT` bounds the whole attempt. The client follows no redirects, uses HTTP/1.1, and opens a fresh connection for every send: a kept-alive connection that the server closed while idle would fail after the request was handed to it and turn a message Resend never saw into a false `unknown`. The request also has no `GetBody`, because `net/http` treats a POST with `Idempotency-Key` as replayable on a broken reused connection. The adapter has no retry loop and does not log. An answer is read up to 64 KiB; only the message ID and the error `name` are parsed, and the provider's message and body are not kept. @@ -230,11 +230,11 @@ The Resend transport uses `net/http` without an SDK. One `Send` is one `POST htt | Failure before the request was written: DNS, connect, TLS, or the attempt timeout | `rejected`, `temporary`: no complete request reached Resend | | The caller's context ended before the request was written | the context error; nothing was sent | -Every `rejected` or `unknown` answer with a known error name sets `ProviderCode` to that name, for example `invalid_idempotent_request`, `invalid_api_key`, or `daily_quota_exceeded`. Known names are those on the Resend errors page plus the older names that the official Node SDK still lists (`invalid_api_key`, `invalid_from_address`, `invalid_access`, `invalid_region`, `security_error`, `internal_server_error`); any other name counts as no name. `RetryAfter` is capped at 24 hours. Rate-limit pacing and the attempt limit belong to the retry policy (TASK-017), the sending worker applies only the minimum schedule described in [Sending service mail](#sending-service-mail), and the stop at the end of the 24-hour key window is the sending worker's rule for an attempt whose worker was lost; waiting for a quota reset is decided by the quota gate described in [Mail quotas](#mail-quotas). +Every `rejected` or `unknown` answer with a known error name sets `ProviderCode` to that name, for example `invalid_idempotent_request`, `invalid_api_key`, or `daily_quota_exceeded`. Known names are those on the Resend errors page plus the older names that the official Node SDK still lists (`invalid_api_key`, `invalid_from_address`, `invalid_access`, `invalid_region`, `security_error`, `internal_server_error`); any other name counts as no name. `RetryAfter` is capped at 24 hours. Rate-limit pacing and the attempt limit belong to the retry policy, the sending worker applies only the minimum schedule described in [Sending service mail](#sending-service-mail), and the stop at the end of the 24-hour key window is the sending worker's rule for an attempt whose worker was lost; waiting for a quota reset is decided by the quota gate described in [Mail quotas](#mail-quotas). ### Mail deliveries -Implemented (TASK-015): the `domain.Delivery` aggregate, `domain.MailContent`, and `domain.MailRequest` (`backend/internal/domain/delivery.go`, `mail_content.go`, `mail_request.go`), the `outbound.DeliveryRepository` and `outbound.MailRequestRepository` ports (`port/outbound/delivery.go`) through `UnitOfWork.Deliveries()`, `UnitOfWork.MailRequests()`, and `postgres.DeliveryStore`, migration `00006_create_deliveries.sql` with the `mail_requests`, `deliveries`, and `delivery_attempts` tables, the queries in `backend/db/queries/delivery.sql`, and in `backend/internal/usecase/notification/` the request usecase `MailRequester` and the consumer `DeliveryHandler`. The quota gate that admits or defers a send is implemented with TASK-018; see [Mail quotas](#mail-quotas). Implemented (TASK-016): the worker that claims due service mail, checks its token and account, passes it through the quota gate, and calls `MailSender`, with migration `00012_add_delivery_sending.sql`; see [Sending service mail](#sending-service-mail). Planned: retries and the unknown outcome policy (TASK-017), and sending product notifications with the permission check before a send (TASK-462). The delivery state gauges are implemented with TASK-022; see [Metrics, telemetry, and alerts](#metrics-telemetry-and-alerts). No product flow calls `MailRequester` yet, and no identity flow calls `ServiceMailer` yet (registration and reset are separate tasks), so a stored notification waits and no service mail exists outside the tests. +Implemented: the `domain.Delivery` aggregate, `domain.MailContent`, and `domain.MailRequest` (`backend/internal/domain/delivery.go`, `mail_content.go`, `mail_request.go`), the `outbound.DeliveryRepository` and `outbound.MailRequestRepository` ports (`port/outbound/delivery.go`) through `UnitOfWork.Deliveries()`, `UnitOfWork.MailRequests()`, and `postgres.DeliveryStore`, migration `00006_create_deliveries.sql` with the `mail_requests`, `deliveries`, and `delivery_attempts` tables, the queries in `backend/db/queries/delivery.sql`, and in `backend/internal/usecase/notification/` the request usecase `MailRequester` and the consumer `DeliveryHandler`. The quota gate that admits or defers a send is implemented; see [Mail quotas](#mail-quotas). Implemented: the worker that claims due service mail, checks its token and account, passes it through the quota gate, and calls `MailSender`, with migration `00012_add_delivery_sending.sql`; see [Sending service mail](#sending-service-mail). Planned: retries and the unknown outcome policy, and sending product notifications with the permission check before a send. The delivery state gauges are implemented; see [Metrics, telemetry, and alerts](#metrics-telemetry-and-alerts). No product flow calls `MailRequester` yet, and no identity flow calls `ServiceMailer` yet (registration and reset are separate tasks), so a stored notification waits and no service mail exists outside the tests. A delivery is the durable state of sending one message to one recipient. A `deliveries` row holds: @@ -254,7 +254,7 @@ Creation path: Why the event carries only a reference. Events stay in `outbox_events` and in Kafka for the topic retention, and the domain event rule allows only identifiers and minimal facts. FR19 also requires that a queue does not keep revoked data available. The text therefore lives in `mail_requests`, which the account's deletion removes by cascade, and only as long as needed: the handler deletes the row in the transaction that stores the rendered delivery. After that the text exists only in the delivery, under the same retention and access rules. The address is read from the account in the handler transaction, so it is the address current at creation. -Token mail. Verification and password reset bodies carry a one-time bearer token, which must never enter an event or a request row, and storage keeps only its SHA-256. `mail_requests` and schema version 1 therefore allow only kind `notification`. Token mail deliveries are created by the identity flows directly in the transaction that issues the token, through `ServiceMailer` (TASK-016), which uses `domain.NewDelivery` and `DeliveryRepository.Create` and binds the delivery to the token; the identity flows that call it (registration, resend, reset) are separate tasks. +Token mail. Verification and password reset bodies carry a one-time bearer token, which must never enter an event or a request row, and storage keeps only its SHA-256. `mail_requests` and schema version 1 therefore allow only kind `notification`. Token mail deliveries are created by the identity flows directly in the transaction that issues the token, through `ServiceMailer`, which uses `domain.NewDelivery` and `DeliveryRepository.Create` and binds the delivery to the token; the identity flows that call it (registration, resend, reset) are separate tasks. Immutable content. A delivery stores the rendered body and never renders it again. Rendering at send time would need the raw token, which exists only in memory when it is issued, and a retry under the same idempotency key must repeat exactly the same body: Resend treats a changed body under an old key as a conflict. The domain recomputes the content hash on every read and fails with `domain.ErrMailContentIntegrity` on a mismatch. The trigger `deliveries_refuse_content_change` refuses an UPDATE that changes the recipient, content, idempotency key, source event, or creation time (SQLSTATE 23000, constraint `deliveries_content_immutable`, mapped to `outbound.ErrDeliveryContentImmutable`). A new template version therefore applies to new deliveries only; old template files are not needed to send a stored delivery. @@ -263,7 +263,7 @@ Personal data at rest. A delivery row holds the recipient address and the bodies - Queries for operations select metadata columns (ID, kind, status, attempts, times, provider) and never the bodies, the request text, or the address; see [DEPLOY.md](DEPLOY.md#mail-deliveries). - Deleting an account deletes its mail requests, deliveries, and their attempts by cascade. The unverified account cleanup locks them with `FOR UPDATE SKIP LOCKED` like tokens and sessions, so it never waits for the delivery consumer or a worker that holds a row. - The bodies of a token mail are cleared when the delivery reaches `accepted`, `rejected`, or `cancelled` (`body_redacted_at`, see [Sending service mail](#sending-service-mail)), so a database dump or backup holds no token of a finished mail; a retention rule that deletes other terminal deliveries after a bounded period is not implemented yet, and until it exists those rows stay. Encryption of the bodies at rest is not implemented either. -- `Delivery`, `MailContent`, `MailRequest`, `NotificationText`, and `EmailAddress` redact themselves in `fmt` and `slog` output: a delivery logs its ID, kind, status, and provider. Handler errors name the broken rule and never quote the payload, and the adapter replaces PostgreSQL error text with its SQLSTATE and constraint. The delivery metrics (TASK-022) carry only the kind, status, provider, and quota window labels, never the address, a user or delivery ID, the provider account label, or the subject. +- `Delivery`, `MailContent`, `MailRequest`, `NotificationText`, and `EmailAddress` redact themselves in `fmt` and `slog` output: a delivery logs its ID, kind, status, and provider. Handler errors name the broken rule and never quote the payload, and the adapter replaces PostgreSQL error text with its SQLSTATE and constraint. The delivery metrics carry only the kind, status, provider, and quota window labels, never the address, a user or delivery ID, the provider account label, or the subject. Statuses. The values follow the `MailSender` outcomes: @@ -279,25 +279,25 @@ Statuses. The values follow the `MailSender` outcomes: Transitions: - `Delivery.RecordAttempt` takes the result of one transport attempt and appends an attempt row. `pending`, `waiting_quota`, and `unknown` accept an attempt: `accepted` gives `accepted`, a `permanent` or `invalid_request` rejection gives `rejected`, `temporary` or `rate_limited` gives `pending`, `quota_exhausted` gives `waiting_quota`, and `unknown` gives `unknown`. `accepted`, `rejected`, and `cancelled` refuse any further attempt with `domain.ErrDeliveryTransition`. -- `Delivery.WaitForQuota(at, until)` parks a `pending` or `waiting_quota` delivery in `waiting_quota` without an attempt, for the case where TASK-018's local quota defers a send before the transport is called; a zero `until` means the reset is unknown. It refuses `unknown`, whose earlier attempt may have been accepted and whose retry belongs to the retry policy, and the terminal statuses. `DeliveryRepository.WaitForQuota` stores it. +- `Delivery.WaitForQuota(at, until)` parks a `pending` or `waiting_quota` delivery in `waiting_quota` without an attempt, for the case where the local mail quota defers a send before the transport is called; a zero `until` means the reset is unknown. It refuses `unknown`, whose earlier attempt may have been accepted and whose retry belongs to the retry policy, and the terminal statuses. `DeliveryRepository.WaitForQuota` stores it. - `Delivery.Cancel(at, reason)` ends a `pending` or `waiting_quota` delivery in `cancelled` without an attempt; the reason is one of `token_missing`, `token_purpose_mismatch`, `token_owner_mismatch`, `token_consumed`, `token_revoked`, `token_expired`, `account_not_current`, `recipient_mismatch`, `content_invalid`, or `processing_failed`. It refuses `unknown`, like `WaitForQuota`: an earlier attempt may have been accepted, so it is never reported as not sent. `DeliveryRepository.Cancel` stores it. - `Delivery.Rebind(at, account)` moves a delivery that has no attempt yet to another provider account; see below. `DeliveryRepository.Rebind` stores it. -Every change advances `version`, and the store applies it only over the previous version. The next attempt time comes from the caller's retry policy (TASK-017) and must fit the target status; the CHECK `deliveries_next_attempt_matches_status` repeats the rule, and `deliveries_provider_message_id_when_accepted` requires the provider ID exactly for `accepted`. +Every change advances `version`, and the store applies it only over the previous version. The next attempt time comes from the caller's retry policy and must fit the target status; the CHECK `deliveries_next_attempt_matches_status` repeats the rule, and `deliveries_provider_message_id_when_accepted` requires the provider ID exactly for `accepted`. Attempts. The current state sits in counters on `deliveries`, so a worker reads one row, and every attempt is a row in `delivery_attempts`: number, time, outcome, rejection, provider code, provider message ID, wait hint, resulting status, and next attempt time. The history is what an operator needs to judge an unknown outcome, what the end of the 24-hour key window counts from (the first attempt), and what an audit of a manual decision refers to. The wait hint is stored exactly as the Go `time.Duration` in nanoseconds (`retry_after_ns`), so a round trip never changes it. `RecordAttempt` stores the delivery and the attempt in one statement: a data-modifying CTE updates the delivery only while its version is still the one before the attempt and appends the attempt only if that update matched. A second writer of the same attempt gets `outbound.ErrDeliveryVersionConflict` and writes nothing. A trigger refuses an UPDATE of an attempt. Quota accounting is not derived from this history: the cascade from an account deletes its deliveries and attempts, so counting sends from `delivery_attempts` would lose sends of deleted accounts and let the provider quota be exceeded. The quota therefore has its own counter that does not cascade, keyed by provider, provider account, and UTC day or month; see [Mail quotas](#mail-quotas). -Provider account. Each delivery is pinned to the transport and account configured when it was created. Providers and accounts share no idempotency keys, so FR19 forbids moving an uncertain delivery to another one; a configuration change applies to new deliveries only, and the sending worker must use the pinned account. `EMAIL_ACCOUNT` names the account (`default` unless set); change it whenever `RESEND_API_KEY` moves to another Resend account. The account may change only while the delivery has no attempt, because before the first attempt no provider has seen the key: `Delivery.Rebind` refuses a delivery with an attempt or in a terminal status, and the trigger refuses a provider change after an attempt (constraint `deliveries_provider_pinned`, mapped to `outbound.ErrDeliveryProviderPinned`). TASK-016 uses it for deliveries created while `EMAIL_PROVIDER=disabled` once the stand enables a transport; whether it rebinds them automatically or on an operator's request is its decision. +Provider account. Each delivery is pinned to the transport and account configured when it was created. Providers and accounts share no idempotency keys, so FR19 forbids moving an uncertain delivery to another one; a configuration change applies to new deliveries only, and the sending worker must use the pinned account. `EMAIL_ACCOUNT` names the account (`default` unless set); change it whenever `RESEND_API_KEY` moves to another Resend account. The account may change only while the delivery has no attempt, because before the first attempt no provider has seen the key: `Delivery.Rebind` refuses a delivery with an attempt or in a terminal status, and the trigger refuses a provider change after an attempt (constraint `deliveries_provider_pinned`, mapped to `outbound.ErrDeliveryProviderPinned`). The service mail worker uses it for deliveries created while `EMAIL_PROVIDER=disabled` once the stand enables a transport; whether it rebinds them automatically or on an operator's request is its decision. -Migration `00012_add_delivery_sending.sql` (TASK-016) is additive; existing rows stay valid. It adds to `deliveries`: `email_token_id` (a nullable foreign key to `email_tokens.id` for token mail, immutable like the rest of the content, NULL for notifications), `cancel_reason` (set exactly when the status is `cancelled`, CHECK-limited to the reasons above), the lease columns `claim_owner` and `claimed_until` (both or neither; only a delivery the worker may still send holds one), `first_send_started_at` (when the first request started, by the database clock), `failure_count` (consecutive failures of the worker on the row), `body_redacted_at` (the bodies of a token mail were cleared), the status `cancelled` with its CHECKs, and two partial indexes: `deliveries_due_idx` on `(next_attempt_at, id)` whose predicate names the service kinds and the statuses that are picked up again, so notification rows never enter it and an idle poll does not scan them, and one on `email_token_id`. The trigger `deliveries_refuse_content_change` also allows exactly one change of the bodies: a terminal token mail may have both set to empty together with `body_redacted_at`, once. It adds the `password_reset` token purpose to `email_tokens`. The down migration turns cancelled deliveries into rejected ones and deletes reset tokens. Planned: a cancelled delivery for a revoked permission (TASK-462). +Migration `00012_add_delivery_sending.sql` is additive; existing rows stay valid. It adds to `deliveries`: `email_token_id` (a nullable foreign key to `email_tokens.id` for token mail, immutable like the rest of the content, NULL for notifications), `cancel_reason` (set exactly when the status is `cancelled`, CHECK-limited to the reasons above), the lease columns `claim_owner` and `claimed_until` (both or neither; only a delivery the worker may still send holds one), `first_send_started_at` (when the first request started, by the database clock), `failure_count` (consecutive failures of the worker on the row), `body_redacted_at` (the bodies of a token mail were cleared), the status `cancelled` with its CHECKs, and two partial indexes: `deliveries_due_idx` on `(next_attempt_at, id)` whose predicate names the service kinds and the statuses that are picked up again, so notification rows never enter it and an idle poll does not scan them, and one on `email_token_id`. The trigger `deliveries_refuse_content_change` also allows exactly one change of the bodies: a terminal token mail may have both set to empty together with `body_redacted_at`, once. It adds the `password_reset` token purpose to `email_tokens`. The down migration turns cancelled deliveries into rejected ones and deletes reset tokens. Planned: a cancelled delivery for a revoked permission. The store provides `Get`, `ListAttempts`, the version-checked `RecordAttempt`, `WaitForQuota`, `Cancel`, and `Rebind`, and for the sending worker `ClaimDue`, `ReleaseClaim`, and `ServiceMailState`. ### Mail quotas -Implemented (TASK-018): quota windows and limits in `backend/internal/domain/mail_quota.go`; the `outbound.MailQuotaRepository` port (`port/outbound/mail_quota.go`), whose writes go through `UnitOfWork.MailQuotas()` and whose reads also go through `postgres.MailQuotaStore`; migration `00007_create_mail_quota_usage.sql` with the `mail_quota_usage` and `mail_quota_reservations` tables; the queries in `backend/db/queries/mail_quota.sql`; in `backend/internal/usecase/notification/`, `QuotaGate` with `PrepareSend` and `SettleSend` (`quota.go`), the startup report `ReportQuotaUsage`, and the user status reader `DeliveryStatusReader` (`delivery_status.go`); `SendResult.QuotaPeriod` in the mail port, filled by the Resend adapter; and the startup report in bootstrap (`bootstrap/mail_quota.go`). The sending worker (TASK-016) calls the gate around `MailSender.Send` and `bootstrap/mail_sender.go` builds it from configuration with `resend.IdempotencyWindow` or zero for SMTP; see [Sending service mail](#sending-service-mail). Planned: the API or identity flow that shows the status reader's result. Only service identity mail counts against the quota while TASK-462 is open. +Implemented: quota windows and limits in `backend/internal/domain/mail_quota.go`; the `outbound.MailQuotaRepository` port (`port/outbound/mail_quota.go`), whose writes go through `UnitOfWork.MailQuotas()` and whose reads also go through `postgres.MailQuotaStore`; migration `00007_create_mail_quota_usage.sql` with the `mail_quota_usage` and `mail_quota_reservations` tables; the queries in `backend/db/queries/mail_quota.sql`; in `backend/internal/usecase/notification/`, `QuotaGate` with `PrepareSend` and `SettleSend` (`quota.go`), the startup report `ReportQuotaUsage`, and the user status reader `DeliveryStatusReader` (`delivery_status.go`); `SendResult.QuotaPeriod` in the mail port, filled by the Resend adapter; and the startup report in bootstrap (`bootstrap/mail_quota.go`). The sending worker calls the gate around `MailSender.Send` and `bootstrap/mail_sender.go` builds it from configuration with `resend.IdempotencyWindow` or zero for SMTP; see [Sending service mail](#sending-service-mail). Planned: the API or identity flow that shows the status reader's result. Only service identity mail counts against the quota until product notification sending is implemented. Limits. `EMAIL_QUOTA_DAILY` and `EMAIL_QUOTA_MONTHLY` limit the recipients sent through the configured provider account (`EMAIL_PROVIDER` and `EMAIL_ACCOUNT`) per UTC day, from 00:00 to 00:00 UTC, and per UTC calendar month. Every recipient counts, as Resend counts them; a delivery has one recipient. The defaults are the Resend Free limits checked on 2026-10-05, 100 and 3000; they apply to `resend` and to `disabled`, which sends nothing. `smtp` has no default and does not start without both values, because a relay's limits are not Resend's. Values range from 1 to 1000000000, and the daily limit must not exceed the monthly one. No value turns the quota off, so no provider runs without the gate. Limits are configuration, not domain constants, and are not stored: a changed limit applies from the next reservation, and a limit lowered below the current usage defers every new send until the window resets. @@ -311,9 +311,9 @@ Lock order. Every write first creates and locks all the usage rows it will touch Reservation. `QuotaGate.PrepareSend(ctx, unit, delivery)` runs in the caller's transaction: 1. A delivery pinned to a provider account other than the configured one fails with `notification.ErrQuotaNotConfigured`: no limits are known for it, and an account without a quota is never "unlimited". An `accepted` or `rejected` delivery fails with `domain.ErrDeliveryTransition`. -2. A retry inside the provider's idempotency window reuses an open reservation of the same delivery (the earlier attempt was `unknown`, or its process stopped before settling) and proceeds without counting again: the provider answers a repeated key with the original result instead of sending twice. The window is a gate parameter: `resend.IdempotencyWindow`, 24 hours per the Resend API documentation, or zero for SMTP, which has no provider-side deduplication, so every SMTP retry counts again. After the window a retry counts again; whether it may run at all is the retry policy's decision (TASK-017). +2. A retry inside the provider's idempotency window reuses an open reservation of the same delivery (the earlier attempt was `unknown`, or its process stopped before settling) and proceeds without counting again: the provider answers a repeated key with the original result instead of sending twice. The window is a gate parameter: `resend.IdempotencyWindow`, 24 hours per the Resend API documentation, or zero for SMTP, which has no provider-side deduplication, so every SMTP retry counts again. After the window a retry counts again; whether it may run at all is the retry policy's decision. 3. Otherwise the repository locks the day and month rows, adds one recipient to both only when it fits both limits, and journals the reservation. If it does not fit, nothing changes and the result says which limit would be exceeded. The reservation is all-or-nothing across both windows. -4. When the send is admitted, the decision carries a permit and the delivery is unchanged. Otherwise the delivery waits for the reset of the full window: the next 00:00 UTC for the day, the first day of the next month for the month; when both are full, the month reset wins. A `pending` or `waiting_quota` delivery is stored as `waiting_quota` with `next_attempt_at` at that time through `Delivery.WaitForQuota`. The change time is the later of the clock and the delivery's last change, and the reset is not earlier than that, so an instance whose clock runs a few milliseconds behind the one that last wrote the delivery can still park it. An `unknown` delivery is returned unchanged with the reset time: its retry belongs to the retry policy (TASK-017), and parking it would hide that an earlier attempt may have been accepted. +4. When the send is admitted, the decision carries a permit and the delivery is unchanged. Otherwise the delivery waits for the reset of the full window: the next 00:00 UTC for the day, the first day of the next month for the month; when both are full, the month reset wins. A `pending` or `waiting_quota` delivery is stored as `waiting_quota` with `next_attempt_at` at that time through `Delivery.WaitForQuota`. The change time is the later of the clock and the delivery's last change, and the reset is not earlier than that, so an instance whose clock runs a few milliseconds behind the one that last wrote the delivery can still park it. An `unknown` delivery is returned unchanged with the reset time: its retry belongs to the retry policy, and parking it would hide that an earlier attempt may have been accepted. The row locks last until the caller's transaction ends, so the worker must commit before it calls the transport; the cost is that sends of one account reserve one after another. @@ -338,11 +338,11 @@ What the user sees. `notification.DeliveryStatusReader.LatestForUser(ctx, userID | `rejected` | Your email could not be sent | | `cancelled` | Your email was not sent because the link in it is no longer valid; request a new one | -Operators read the same rows with the queries in [DEPLOY.md](DEPLOY.md#mail-quotas). The gate logs `mail quota is used up; the delivery waits for the reset` at info level and `the mail provider reported its quota used up; local sending stops until the reset` at warn level, with only the delivery ID, provider, period, and reset time. The quota gauges (TASK-022) come from `MailQuotaUsageReader.Usage` for the configured account, with the labels provider and window only; see [Metrics, telemetry, and alerts](#metrics-telemetry-and-alerts). +Operators read the same rows with the queries in [DEPLOY.md](DEPLOY.md#mail-quotas). The gate logs `mail quota is used up; the delivery waits for the reset` at info level and `the mail provider reported its quota used up; local sending stops until the reset` at warn level, with only the delivery ID, provider, period, and reset time. The quota gauges come from `MailQuotaUsageReader.Usage` for the configured account, with the labels provider and window only; see [Metrics, telemetry, and alerts](#metrics-telemetry-and-alerts). ### Sending service mail -Implemented (TASK-016): the sending usecase `ServiceMailSender` (`backend/internal/usecase/notification/service_sender.go`), the enqueue usecase `ServiceMailer` (`service_mail.go`), the minimum retry schedule `RetryPolicy` (`send_retry.go`), `Delivery.CheckServiceMail` and `Delivery.Cancel` with the cancel reasons (`backend/internal/domain/delivery.go`, `delivery_guard.go`), the loop in `backend/internal/worker/mailsender/`, the inbound port `inbound.MailPass` (`port/inbound/mail_sender.go`), the repository methods `ClaimDue`, `ReleaseClaim`, `Cancel`, and `ServiceMailState`, migration `00012_add_delivery_sending.sql`, the gauge `lincodex_mail_sender_running`, and the wiring in `bootstrap/mail_sender.go`. Not implemented: sending product notifications (TASK-462), the retry and unknown outcome policy (TASK-017), and the identity flows that call `ServiceMailer`. +Implemented: the sending usecase `ServiceMailSender` (`backend/internal/usecase/notification/service_sender.go`), the enqueue usecase `ServiceMailer` (`service_mail.go`), the minimum retry schedule `RetryPolicy` (`send_retry.go`), `Delivery.CheckServiceMail` and `Delivery.Cancel` with the cancel reasons (`backend/internal/domain/delivery.go`, `delivery_guard.go`), the loop in `backend/internal/worker/mailsender/`, the inbound port `inbound.MailPass` (`port/inbound/mail_sender.go`), the repository methods `ClaimDue`, `ReleaseClaim`, `Cancel`, and `ServiceMailState`, migration `00012_add_delivery_sending.sql`, the gauge `lincodex_mail_sender_running`, and the wiring in `bootstrap/mail_sender.go`. Not implemented: sending product notifications, the retry and unknown outcome policy, and the identity flows that call `ServiceMailer`. Scope. The worker claims only the kinds `verification` and `password_reset`. A product notification is never claimed here, whatever its state. Service mail needs no consent record of any purpose: it is part of the account flow, so nothing reads the consent ledger, and C2 (publication of the candidate card) and the other product consents play no part. What stands between the account and the mail is the check below, not a consent. @@ -385,7 +385,7 @@ What a provider answer becomes. The delivery state machine of `domain.Delivery` | `rejected` `permanent` or `invalid_request` | `rejected` | none | released | | `rejected` `temporary` or `rate_limited` | `pending` | now plus `RetryPolicy`: 1 minute, doubling to at most 30 minutes, never shorter than the provider's `Retry-After` | released | | `rejected` `quota_exhausted` | `waiting_quota` | the reset the gate returns (next 00:00 UTC for a day, the first of the next month for a month); none when the provider named no window | window marked full | -| `unknown` | `unknown` | none: no automatic retry (TASK-017) | counted | +| `unknown` | `unknown` | none: no automatic retry | counted | | `Send` error: no transport (`ErrMailChannelUnavailable`) or the context ended | unchanged, lease released | still due | released | | `Send` error: invalid message (`ErrInvalidOutgoingMail`) | `cancelled`, `content_invalid` | none | released | | `Send` error: anything else without an answer | not counted against the row; it moves back by `RetryPolicy` and the worker backs off | now plus `RetryPolicy` | released | @@ -408,11 +408,11 @@ Test fixture only. `resendfixture` and `resend.NewLoopbackSender` are never used Tests. `integration_test/mail_sender_test.go` runs a local Resend fixture (`resendfixture`, an `httptest` server speaking the part of the API the transport uses, reached through `resend.NewLoopbackSender`, which accepts only a loopback endpoint) against PostgreSQL; see [TESTING.md](TESTING.md). It is a test fixture only; production binds the real Resend transport with its fixed endpoint. -Open points. `unknown` has no automatic retry or escalation until TASK-017. Sending notifications, and the permission check they need, belong to TASK-462; until then they wait, and they are not counted in the overdue gauge, so a notification backlog does not fire `LincodexMailDeliveriesOverdue` (the gauge `lincodex_mail_delivery_oldest_due_pending_age_seconds` covers `domain.ServiceMailKinds`; its predicate is the one of `deliveries_due_idx`). Whether a password reset goes to unverified accounts is for the reset flow to decide. The poll runs every 5 seconds and the claim reads one indexed statement, which suits the current volume. +Open points. Automatic retry or escalation for `unknown` is not implemented. Sending product notifications, and the permission check they need, are planned; until then notifications wait, and they are not counted in the overdue gauge, so a notification backlog does not fire `LincodexMailDeliveriesOverdue` (the gauge `lincodex_mail_delivery_oldest_due_pending_age_seconds` covers `domain.ServiceMailKinds`; its predicate is the one of `deliveries_due_idx`). Whether a password reset goes to unverified accounts is for the reset flow to decide. The poll runs every 5 seconds and the claim reads one indexed statement, which suits the current volume. ### Product policy versions -Implemented as storage, a publisher, and a startup seed (TASK-005): migration `backend/db/migrations/00003_create_policy_versions.sql`, queries in `backend/db/queries/policy.sql`, the typed policy in `backend/internal/domain/` (`policy.go`, `policy_document.go`, `policy_version.go`, `policy_demo.go`), the `outbound.PolicyRepository` port (`port/outbound/policy.go`), the sqlc-backed adapter in `backend/internal/adapter/secondary/postgres/policy.go`, and the publisher in `backend/internal/usecase/policy/`. No product rule reads the policy yet; invitations, quotas, assessment, sessions, and the search status will read it as their tasks are implemented. +Implemented as storage, a publisher, and a startup seed: migration `backend/db/migrations/00003_create_policy_versions.sql`, queries in `backend/db/queries/policy.sql`, the typed policy in `backend/internal/domain/` (`policy.go`, `policy_document.go`, `policy_version.go`, `policy_demo.go`), the `outbound.PolicyRepository` port (`port/outbound/policy.go`), the sqlc-backed adapter in `backend/internal/adapter/secondary/postgres/policy.go`, and the publisher in `backend/internal/usecase/policy/`. No product rule reads the policy yet; invitations, quotas, assessment, sessions, and the search status will read it as their tasks are implemented. `policy_versions` columns: @@ -426,9 +426,9 @@ Implemented as storage, a publisher, and a startup seed (TASK-005): migration `b The database enforces immutability. The trigger function `policy_versions_refuse_change` refuses every UPDATE and DELETE (row trigger) and TRUNCATE (statement trigger) with SQLSTATE 23000 and the constraint name `policy_versions_immutable`; the adapter maps exactly that pair to `outbound.ErrPolicyVersionImmutable`, never the message. The port has no update or delete method, so a change is always a new version. The guarantee covers application statements and manual SQL; a role that owns the table can still disable the trigger or drop the table, so a least-privilege runtime role remains future work. -Typed policy, `domain.ProductPolicy`: every value is a named field whose type carries the unit: `CalendarDays`, `BusinessDays` (no conversion to a duration; the consuming feature supplies the business calendar), `Hours`, and `BasisPoints` for probabilities and the standard error, an integer count of 0.0001 (0.80 is 8000). Basis points compare exactly, without floating-point drift, and keep integers in the document. The `Validate` method of each section rejects zero, missing, and out-of-range values and inconsistent combinations, such as a default deadline outside the options, a higher quota tier with a lower limit, an inactive E0, an active tier above an inactive one, or stop probabilities that do not surround the confirmation threshold. The ranges are sanity bounds against unit mistakes, not product decisions. Quota tiers E0 < E1 < E2 are looked up with `OrganizationQuotaPolicy.Tier(domain.OrganizationTier)` (for TASK-087); every organization starts at E0, and the rules that move it between tiers belong to the quota feature. +Typed policy, `domain.ProductPolicy`: every value is a named field whose type carries the unit: `CalendarDays`, `BusinessDays` (no conversion to a duration; the consuming feature supplies the business calendar), `Hours`, and `BasisPoints` for probabilities and the standard error, an integer count of 0.0001 (0.80 is 8000). Basis points compare exactly, without floating-point drift, and keep integers in the document. The `Validate` method of each section rejects zero, missing, and out-of-range values and inconsistent combinations, such as a default deadline outside the options, a higher quota tier with a lower limit, an inactive E0, an active tier above an inactive one, or stop probabilities that do not surround the confirmation threshold. The ranges are sanity bounds against unit mistakes, not product decisions. Quota tiers E0 < E1 < E2 are looked up with `OrganizationQuotaPolicy.Tier(domain.OrganizationTier)` (for organization quota enforcement); every organization starts at E0, and the rules that move it between tiers belong to the quota feature. -Open question for the attempt tasks (TASK-157 and TASK-158): `MaxAttemptsPerWindow` stores only the number. Whether the limit counts per grade, per specialty, or across all assessments of a candidate is not decided. +Open question for the attempt tasks: `MaxAttemptsPerWindow` stores only the number. Whether the limit counts per grade, per specialty, or across all assessments of a candidate is not decided. The document has `schema_version` 1 and the sections `invitations`, `organization_quotas`, `assessment`, `identity`, and `search_status`; field names carry their unit (`_days`, `_business_days`, `_hours`, `_bp`). Decoding is strict: it rejects unknown fields, missing or null fields, wrong types, fractions, values outside int32, an unknown schema version, trailing data, and documents over 64 KiB. The canonical form is the compact Go encoding in field declaration order. jsonb normalizes key order, so `domain.RestorePolicyVersion` decodes the stored document, validates it, encodes it again, and compares its SHA-256 with `document_sha256`; a mismatch returns `domain.ErrPolicyDocumentIntegrity`. A golden test pins the canonical form, because a change would make every stored version fail this check; a new layout needs a new schema version and decoder. @@ -591,7 +591,7 @@ These intervals are the accepted initial policy, stored as demo version 1 of the ### Assessment bank -Implemented as storage and a loader (TASK-154), not as a candidate-facing feature: migration `backend/db/migrations/00011_create_assessment_bank.sql`, queries in `backend/db/queries/assessment_bank.sql`, the domain types in `backend/internal/domain/` (`assessment_family.go`, `assessment_generator.go`, `assessment_algorithms.go`), the `outbound.AssessmentBankRepository` port (`port/outbound/assessment_bank.go`, reachable through `UnitOfWork.AssessmentBank()`), the sqlc-backed adapter in `backend/internal/adapter/secondary/postgres/assessment_bank.go`, and the loader in `backend/internal/usecase/assessment/` (`Bank`, `Bundle`). Nothing in bootstrap or the HTTP API calls it yet, and no category is open. +Implemented as storage and a loader, not as a candidate-facing feature: migration `backend/db/migrations/00011_create_assessment_bank.sql`, queries in `backend/db/queries/assessment_bank.sql`, the domain types in `backend/internal/domain/` (`assessment_family.go`, `assessment_generator.go`, `assessment_algorithms.go`), the `outbound.AssessmentBankRepository` port (`port/outbound/assessment_bank.go`, reachable through `UnitOfWork.AssessmentBank()`), the sqlc-backed adapter in `backend/internal/adapter/secondary/postgres/assessment_bank.go`, and the loader in `backend/internal/usecase/assessment/` (`Bank`, `Bundle`). Nothing in bootstrap or the HTTP API calls it yet, and no category is open. - Family version. One `assessment_families` row is one version of one family (`family_key`, `version`): category, specialization (the domain inside the category), title, author (`ai:` or `operator:`), reviewer (`operator:` or NULL), `review_status` (`pending`, `approved`, `rejected`), the seed generator, the answer key, the rubric, a content hash with its `hash_scheme`, a lifecycle (`draft`, `published`, `retired`), and the operators and times of publication and retirement. The reviewer is never the author, and a review is pending exactly while there is no reviewer (CHECK constraints; the domain applies the same rules). The reviewer in a bundle and the operator of a publication are declared values, not authenticated identities, until reviewer and operator accounts exist. - Immutability. The content of a stored version never changes: the trigger `assessment_families_guard_update` refuses every UPDATE that changes a column other than the lifecycle columns (`lifecycle`, `published_at`, `published_by`, `retired_at`, `retired_by`), and `assessment_families_refuse_removal` refuses DELETE and TRUNCATE, all with SQLSTATE 23000 and the constraint name `assessment_families_immutable`, which the adapter maps to `outbound.ErrAssessmentFamilyImmutable`. The lifecycle moves only forward (draft, published, retired), the trigger sets the times and keeps the publisher through a retirement, and a version is published only with an approved review by a reviewer (`assessment_families_published_requires_review`). A change is a new version with the next number; the loader accepts only version 1 for a new family and the successor of the latest version otherwise. A pending draft is never approved in place: its review is recorded by importing a new version of the family that carries the review, and the pending version stays an unpublished draft. The domain recomputes the content hash when it reads a row and returns `ErrAssessmentFamilyIntegrity` for a row changed outside the application. The hash is the SHA-256 of a canonical JSON document that holds the content without the bundle name, ID, lifecycle, and publication fields. The `hash_scheme` column (a smallint with a CHECK of the known values, one of the immutable columns) names the layout: the domain verifies a row with the hash function of the scheme the row was stored with, so a later scheme (a new function and a new CHECK value, never an edit of scheme 1) verifies new rows without invalidating old ones, and a row with an unknown scheme is refused; tests verify a row with its own scheme and pin the scheme 1 hash of a fixed input. As for `policy_versions`, a role that owns the table can still disable the triggers. @@ -646,7 +646,7 @@ The brief references Russian Federal Law 152-FZ. The system design calls for sep ### Identity storage -Implemented as storage only (TASK-051): migration `backend/db/migrations/00002_create_identity_tables.sql`, queries in `backend/db/queries/identity.sql`, domain types in `backend/internal/domain/`, ports in `backend/internal/port/outbound/identity.go`, and the sqlc-backed adapter in `backend/internal/adapter/secondary/postgres/identity.go`. The registration, verification, login, and session behavior described in [api/README.en.md](../../api/README.en.md#identity-sessions-cookie-and-csrf) is planned (TASK-053 to TASK-056); no usecase or handler uses this storage yet. +Implemented as storage only: migration `backend/db/migrations/00002_create_identity_tables.sql`, queries in `backend/db/queries/identity.sql`, domain types in `backend/internal/domain/`, ports in `backend/internal/port/outbound/identity.go`, and the sqlc-backed adapter in `backend/internal/adapter/secondary/postgres/identity.go`. The registration, verification, login, and session behavior described in [api/README.en.md](../../api/README.en.md#identity-sessions-cookie-and-csrf) is planned; no usecase or handler uses this storage yet. - `users`: UUIDv7 `id`; `email`, the delivery form (trimmed ASCII, letter case as typed, returned as `Account.email`), and `email_normalized`, the unique comparison key (the same address with A-Z lowercased); `password_hash`, an Argon2id v19 PHC string; `scenario` and `onboarding_step` with a CHECK that the step belongs to the scenario; nullable `email_verified_at`; `registration_version`; `last_registered_at` with a partial index over unverified accounts for the planned 7-day cleanup; the optimistic `version`; `created_at` and `updated_at`. The delivery form is kept because RFC 5321 allows a case-sensitive local part: mail goes to the address as typed, while uniqueness ignores letter case. - `email_tokens`: `token_hash` (SHA-256, 32-byte `bytea`, unique), `purpose` (`email_verification`; a CHECK lists the allowed purposes, so a password reset can be added later), `user_id`, the `registration_version` the token is bound to, `created_at`, `expires_at`, `consumed_at`, and `invalidated_at`. A CHECK allows at most one of consumed and invalidated. @@ -659,13 +659,13 @@ Decisions: - The database stores hashes, never passwords or raw tokens. A token carries 256 bits from crypto/rand, so an unsalted SHA-256 cannot be reversed by guessing and a lookup stays one index probe; passwords need the slow Argon2id KDF instead. `bytea` keeps the digest at half the size of hex text, with an exact length CHECK and no letter-case variants. `domain.SecretToken`, `domain.PasswordHash`, and `domain.EmailAddress` redact themselves in `fmt` (every verb) and `slog` output, so printing a `domain.User` shows neither the address nor the hash; explicit accessors return the real values. Unmapped PostgreSQL errors from the identity repositories keep only the SQLSTATE and the constraint name, because the message and detail can quote row values. - Enum-like columns are text with CHECK constraints rather than PostgreSQL enum types. A new scenario, step, or purpose replaces one constraint in a reversible migration; an enum value cannot be removed and cannot be used in the transaction that adds it. - Every stored time comes from the application clock that the caller passes, so deadlines and the checks against them use one clock. Repositories reject the zero time. -- There is no CSRF column. `GetCurrentSession` must return the session's CSRF token after a reload, which a stored hash cannot reproduce. TASK-056 can derive the token from the session token with a server key, which needs no storage, or add a column in an additive migration. +- There is no CSRF column. `GetCurrentSession` must return the session's CSRF token after a reload, which a stored hash cannot reproduce. Session authentication can derive the token from the session token with a server key, which needs no storage, or add a column in an additive migration. What the ports guarantee: - `UserRepository.Create` returns `ErrEmailTaken` for a duplicate key. `UpdateRegistration` stores the result of `domain.User.ReRegister` only when the stored `version` matches and the email is unverified; the same statement advances `version` and `registration_version` by one, so no caller chooses the registration version, and deletes the registration C1 of the earlier registrant (see [Consent ledger](#consent-ledger)). `MarkEmailVerified` applies only to an unverified account with the given registration version. Both return `ErrUserVersionConflict` otherwise. - `EmailTokenRepository.Consume` is one `UPDATE ... RETURNING` that requires an unconsumed, uninvalidated, unexpired token. Concurrent callers queue on the token row lock; under READ COMMITTED each waiter re-checks the row after the holder finishes, so exactly one succeeds and, if the holder rolls back, a waiter can still succeed. A miss is reported as `ErrEmailTokenNotFound`, `ErrEmailTokenConsumed`, `ErrEmailTokenInvalidated` (replaced, or issued for an earlier registration version), or `ErrEmailTokenExpired`. `InvalidateActive` marks every earlier token of a user and purpose. -- Consume compares the token's registration version with the account only as its statement reads the account, without locking it, so it cannot see a re-registration that commits right after it. The binding of a token to the current registration therefore holds only when a confirmation calls `MarkEmailVerified(token.UserID, token.RegistrationVersion)` in the same transaction and rolls back on `ErrUserVersionConflict`; the rollback also restores the token, which is then superseded. The confirmation usecase (TASK-054) maps that outcome to `verification_token_invalid`. +- Consume compares the token's registration version with the account only as its statement reads the account, without locking it, so it cannot see a re-registration that commits right after it. The binding of a token to the current registration therefore holds only when a confirmation calls `MarkEmailVerified(token.UserID, token.RegistrationVersion)` in the same transaction and rolls back on `ErrUserVersionConflict`; the rollback also restores the token, which is then superseded. The confirmation usecase maps that outcome to `verification_token_invalid`. - `SessionRepository.FindActive` and `Touch` take the idle timeout from the caller and accept only an unrevoked session before its absolute deadline and within the idle timeout. `Touch` writes `last_seen_at` only when the stored value is more than one minute older, so frequent requests do not rewrite the row and the idle timeout can end a session up to a minute early; it never moves `last_seen_at` back or revives an ended session. `Revoke` and `RevokeAllForUser` set `revoked_at`. - `DeleteUnverifiedRegisteredBefore` deletes one batch of unverified accounts, oldest first, and never waits for a lock. It locks the candidate accounts, their tokens, their sessions, their mail requests, their mail deliveries, and their consent records with `FOR UPDATE SKIP LOCKED` and skips every account whose row, or any token, session, mail request, delivery, or consent row, is locked by another transaction, such as a re-registration, a resend, a confirmation, the delivery consumer, or a delivery worker; skipped accounts stay for the next run. The mail requests, deliveries, and attempts go with the account by cascade; the consent records, which restrict the delete, are deleted explicitly in the same statement. - `postgres.IdentityStore` runs the same repositories outside a transaction. Called with a context from a `Transactor` callback, it returns `ErrNestedTransaction` instead of committing on a separate connection. @@ -674,20 +674,20 @@ What the ports guarantee: ### Password hashing -Implemented (TASK-052) and tested: registration (TASK-053) creates the hasher from configuration and calls it; login (TASK-055) will do the same. +Implemented and tested: registration creates the hasher from configuration and calls it; login will do the same. - `domain.Password` holds the password normalized to Unicode NFKC. `domain.NewPassword` applies the registration policy, 15 to 128 code points after normalization; `domain.ParseLoginPassword` accepts 1 to 128. Before normalizing, both reject raw input over 512 bytes (128 code points of at most 4 UTF-8 bytes, so every value the contract schema accepts fits) and invalid UTF-8. These checks run before any hashing and fail with `domain.ErrInvalidPassword`, naming the rule but never the value. The blocklist of common or breached passwords is a separate planned check. - The `outbound.PasswordHasher` port (`port/outbound/password.go`) has `Hash`, `Verify`, and `VerifyDummy`; the `adapter/secondary/argon2id` adapter implements it with `golang.org/x/crypto/argon2`. New hashes use Argon2id v19 with m=65536 KiB, t=3, p=4 (the second recommended option of RFC 9106, above the OWASP baseline of 19 MiB, t=2, p=1), a 16-byte salt from crypto/rand, and a 32-byte key, encoded as `$argon2id$v=19$m=65536,t=3,p=4$$` in unpadded base64, the format that `domain.NewPasswordHash` and the `users_password_hash_format` CHECK accept. One hash took about 26 to 33 ms on an Apple M5 development machine (`BenchmarkHashRecommendedParameters`, also with one CPU); this is not a production latency figure. - Memory budget: derivations share a weighted semaphore (`golang.org/x/sync/semaphore`) of `PASSWORD_HASH_CONCURRENCY` times 64 MiB, and each holds its own memory parameter while it runs. The setting accepts 1 to 4; when unset it is the smaller of 2 and GOMAXPROCS, which Go derives from the container CPU limit. Compose passes `PASSWORD_HASH_CONCURRENCY=1` for the 1-CPU backend container, so hashes run one at a time with 64 MiB live; the maximum of 4 needs 256 MiB. Memory of a finished derivation is garbage until the next collection; `GOMEMLIMIT=600MiB` in Compose makes the collector reclaim it before the heap reaches about 78% of the 768 MiB container limit, and the rest is left for stacks and non-heap memory. Waiting calls queue in FIFO order, bounded only by their request context; request rate limiting comes with the HTTP operations. - `Verify` parses the stored PHC string strictly and recomputes the key with the stored parameters, salt, and key length, then compares in constant time. A wrong password returns `outbound.ErrPasswordMismatch`. A malformed hash, or one outside the stored-hash bounds (memory from 8 KiB per lane to 128 MiB and within the hashing budget, 1 to 16 passes, 1 to 16 lanes, a salt of 8 to 64 bytes, a digest of 16 to 64 bytes), returns `outbound.ErrPasswordHashCorrupt` without any derivation, so a crafted row cannot demand unbounded memory or time. `ErrPasswordHashCorrupt` wraps `domain.ErrInvalidPasswordHash`, which the repository returns for a stored hash that fails `domain.NewPasswordHash`. On a match `needsRehash` reports parameters, salt, or key length that differ from the current ones, so a login can store a new hash. - `VerifyDummy` runs `Verify` against a hash with the current parameters, a random salt, and a random digest, and returns `ErrPasswordMismatch` (or the context error). Login will call it for an unknown email, so both branches parse, wait for memory, derive, and compare alike. -- Login (TASK-055) must answer `invalid_credentials` for an unknown email, a wrong password, and an invalid stored hash (`errors.Is(err, domain.ErrInvalidPasswordHash)`, from the repository or from `Verify`); for an invalid hash it must also log an error and call `VerifyDummy`. Remaining timing differences: a corrupt hash is refused without a derivation, which `VerifyDummy` compensates, and a hash with older parameters costs what its own parameters cost until the next successful login rehashes it. +- Login must answer `invalid_credentials` for an unknown email, a wrong password, and an invalid stored hash (`errors.Is(err, domain.ErrInvalidPasswordHash)`, from the repository or from `Verify`); for an invalid hash it must also log an error and call `VerifyDummy`. Remaining timing differences: a corrupt hash is refused without a derivation, which `VerifyDummy` compensates, and a hash with older parameters costs what its own parameters cost until the next successful login rehashes it. - `identity.Credentials.HashNewPassword` validates a new password and only then hashes it; registration will call it on every branch before it looks up the email. - Errors and logs never contain the password or the hash. `domain.Password`, `domain.PasswordHash`, `domain.SecretToken`, and `domain.EmailAddress` redact themselves in `fmt`, `slog`, and JSON output, and keep their value behind a pointer, so printing an enclosing struct, even through an unexported field, shows only an address. ### Consent ledger -Implemented as storage, ports, and a read contract (TASK-062): migration `backend/db/migrations/00009_create_consent_ledger.sql`, queries in `backend/db/queries/consents.sql`, domain types in `backend/internal/domain/consent.go`, the ports in `backend/internal/port/outbound/consents.go`, the sqlc-backed adapter in `backend/internal/adapter/secondary/postgres/consents.go`, and `ListMyConsents` in the public contract ([api/README.en.md](../../api/README.en.md#consents)). Granting C1-C3 and C5 with a current-version check is implemented as the usecase `consent.Service` (TASK-063, see [Consent usecase](#consent-usecase)). Revocation with its downstream effects and the HTTP handler (TASK-064), C1 in the registration transaction (TASK-053), and C4 in the invitation acceptance (TASK-201) are planned; no product flow calls the usecase yet. +Implemented as storage, ports, and a read contract: migration `backend/db/migrations/00009_create_consent_ledger.sql`, queries in `backend/db/queries/consents.sql`, domain types in `backend/internal/domain/consent.go`, the ports in `backend/internal/port/outbound/consents.go`, the sqlc-backed adapter in `backend/internal/adapter/secondary/postgres/consents.go`, and `ListMyConsents` in the public contract ([api/README.en.md](../../api/README.en.md#consents)). Granting C1-C3 and C5 with a current-version check is implemented as the usecase `consent.Service` (see [Consent usecase](#consent-usecase)). Revocation with its downstream effects and the HTTP handler, C1 in the registration transaction, and C4 in the invitation acceptance are planned; no product flow calls the usecase yet. The consents C1-C5 of PRD FR01 are independent purposes: a grant or a revocation of one never changes another. @@ -698,12 +698,12 @@ The consents C1-C5 of PRD FR01 are independent purposes: a grant or a revocation Decisions: - Text binding. A foreign key on (`purpose`, `text_version`) refuses a version that was never published for the purpose, and a BEFORE INSERT trigger refuses a version published after the grant time (`consent_records_text_published`). For C1-C3 and C5 a second foreign key over a generated column requires `text_hash` to equal the hash of the published text. For C4 the same trigger requires `text_hash` to equal the SHA-256 of the published text with `organization_name` filled in (`consent_records_c4_text_hash`). The domain computes that hash itself in `domain.NewContactConsentGrant` from the published `ConsentText` and the name, so no caller supplies hash bytes, and a client can invent neither a version nor a hash. The stored name is the snapshot that proves the shown text; a later rename of the organization does not change it, and the read model returns it as `ConsentOrganization.name`. -- History. The only UPDATE a trigger allows is the revocation stamp on an unrevoked row with every other column unchanged (`consent_records_immutable`). A newer text version is a new row next to the older one; a grant after a revocation is a new row. The state (`active`, `superseded`, `revoked`) is computed by the queries, never stored: among the unrevoked rows of a subject and purpose other than C4, the row granted last (by `granted_at`, then ID) is `active` and the others are `superseded`, whatever their versions. The ledger therefore accepts any published version, and the grant usecase `consent.Service` (TASK-063) checks that the version is the current text before it calls `Grant`. A partial unique index keeps one unrevoked row per subject, purpose, and version, so a repeated or concurrent grant returns the existing record; a unique index on `invitation_id` keeps one C4 row per invitation, revoked or not, so a revoked C4 never comes back. -- Revocation. `ConsentLedger.Revoke` stamps every unrevoked row of the purpose, superseded rows included, and for C4 only those of one organization. A repeat finds nothing and keeps the first stamp. A revocation time before the grant time of a row, from clock skew between instances, is stamped at the grant time (`greatest`), so the `consent_records_revocation_stamp` CHECK stays a backstop. The downstream effects of a revocation (deletion request for C1, closing publication and grants for C2 and C4, the manual path for C3, stopping the import for C5) belong to TASK-064 and are not implemented. -- Retention and deletion. PRD 7.3 plans to keep consents for three years, which can outlive the account, so `subject_id` references `users` with `ON DELETE RESTRICT`, and a BEFORE DELETE trigger refuses deleting a row whose subject is a confirmed account (`consent_records_retained`). Rows of an unconfirmed account may be deleted, because a registration that the email owner never confirmed is not evidence of anyone's consent: the unverified account cleanup deletes the rows of the accounts it removes in the same statement, and `UpdateRegistration` deletes the registration C1 of the account it re-registers (see below). TRUNCATE fires no row trigger and stays allowed for test isolation. Whether a deleted account leaves its ledger, a tombstone, or nothing is decided by the C1 deletion request of TASK-064 and the account deletion procedure that executes it, which has no MVP task yet; the retention rule extends the delete condition in its own migration. -- Re-registration. An unverified account keeps its `users.id` when the same email registers again, so the earlier registrant's C1 would otherwise stand for the new one. The `UpdateUserRegistration` statement deletes the C1 rows with the source `registration` of the account it updates, and only when the update applies. This is a binding requirement for TASK-053: the registration usecase calls `UpdateRegistration` and records the new C1 with `consent.Service.GrantAtRegistration`, strictly after `UpdateRegistration`, in the same transaction (see [Consent usecase](#consent-usecase)). -- C2 and the published field set. A C2 row proves the consent to the publication text, not which fields were published. The published field set and its changes are kept with their times and the C2 record behind each in the history of TASK-088 (`candidate_publications` and `candidate_privacy_events`, see [Candidate visibility](#candidate-visibility)). Adding a field scope to C2 rows later is an additive migration and contract change. -- C4 in a business transaction. `UnitOfWork.ConsentLedger().GrantContact` takes a `domain.ContactConsentGrant`, which only `domain.NewContactConsentGrant` builds and which requires the C4 text, the organization and its name, a non-empty field set, the invitation, and its terms version; `domain.NewConsentGrant` refuses C4. The acceptance (TASK-201) calls it in the transaction that moves the invitation to `accepted`, creates the grant, and writes the audit event, so all of them commit or roll back together. A repeated acceptance gets the existing record with `created` false and compares its scope; an invitation whose C4 belongs to another subject returns `ErrConsentInvitationTaken`. +- History. The only UPDATE a trigger allows is the revocation stamp on an unrevoked row with every other column unchanged (`consent_records_immutable`). A newer text version is a new row next to the older one; a grant after a revocation is a new row. The state (`active`, `superseded`, `revoked`) is computed by the queries, never stored: among the unrevoked rows of a subject and purpose other than C4, the row granted last (by `granted_at`, then ID) is `active` and the others are `superseded`, whatever their versions. The ledger therefore accepts any published version, and the grant usecase `consent.Service` checks that the version is the current text before it calls `Grant`. A partial unique index keeps one unrevoked row per subject, purpose, and version, so a repeated or concurrent grant returns the existing record; a unique index on `invitation_id` keeps one C4 row per invitation, revoked or not, so a revoked C4 never comes back. +- Revocation. `ConsentLedger.Revoke` stamps every unrevoked row of the purpose, superseded rows included, and for C4 only those of one organization. A repeat finds nothing and keeps the first stamp. A revocation time before the grant time of a row, from clock skew between instances, is stamped at the grant time (`greatest`), so the `consent_records_revocation_stamp` CHECK stays a backstop. The downstream effects of a revocation (deletion request for C1, closing publication and grants for C2 and C4, the manual path for C3, stopping the import for C5) belong to consent revocation and are not implemented. +- Retention and deletion. PRD 7.3 plans to keep consents for three years, which can outlive the account, so `subject_id` references `users` with `ON DELETE RESTRICT`, and a BEFORE DELETE trigger refuses deleting a row whose subject is a confirmed account (`consent_records_retained`). Rows of an unconfirmed account may be deleted, because a registration that the email owner never confirmed is not evidence of anyone's consent: the unverified account cleanup deletes the rows of the accounts it removes in the same statement, and `UpdateRegistration` deletes the registration C1 of the account it re-registers (see below). TRUNCATE fires no row trigger and stays allowed for test isolation. Whether a deleted account leaves its ledger, a tombstone, or nothing is decided by the C1 deletion request and the account deletion procedure that executes it, which has no MVP task yet; the retention rule extends the delete condition in its own migration. +- Re-registration. An unverified account keeps its `users.id` when the same email registers again, so the earlier registrant's C1 would otherwise stand for the new one. The `UpdateUserRegistration` statement deletes the C1 rows with the source `registration` of the account it updates, and only when the update applies. This is a binding requirement for registration: the registration usecase calls `UpdateRegistration` and records the new C1 with `consent.Service.GrantAtRegistration`, strictly after `UpdateRegistration`, in the same transaction (see [Consent usecase](#consent-usecase)). +- C2 and the published field set. A C2 row proves the consent to the publication text, not which fields were published. The published field set and its changes are kept with their times and the C2 record behind each in the candidate visibility history (`candidate_publications` and `candidate_privacy_events`, see [Candidate visibility](#candidate-visibility)). Adding a field scope to C2 rows later is an additive migration and contract change. +- C4 in a business transaction. `UnitOfWork.ConsentLedger().GrantContact` takes a `domain.ContactConsentGrant`, which only `domain.NewContactConsentGrant` builds and which requires the C4 text, the organization and its name, a non-empty field set, the invitation, and its terms version; `domain.NewConsentGrant` refuses C4. The acceptance calls it in the transaction that moves the invitation to `accepted`, creates the grant, and writes the audit event, so all of them commit or roll back together. A repeated acceptance gets the existing record with `created` false and compares its scope; an invitation whose C4 belongs to another subject returns `ErrConsentInvitationTaken`. - Cleanup race. The cleanup checks consent rows in its statement snapshot. A consent committed for a candidate account after that snapshot but before the account lock fails the restricting foreign key at the end of the statement (SQLSTATE 23001); the adapter reports it as `ErrTransactionConflict`, nothing is deleted, and the next run sees the consent. - Scoping. Every read and revocation takes the subject, and the contract operation takes it from the session, so the read model returns only the caller's own records. Errors of the adapter keep the SQLSTATE and constraint name only, and `domain.ConsentRecord`, `ConsentGrant`, `ContactConsentGrant`, and `ConsentRevocation` show no subject, organization, name, or fields in `fmt` and `slog` output. @@ -717,31 +717,31 @@ What the ports guarantee (`outbound.ConsentRepositories`, available on `UnitOfWo ### Consent usecase -Implemented (TASK-063): `consent.Service` in `backend/internal/usecase/consent/`. It is not wired into bootstrap yet, because no handler or registration flow calls it; the first caller builds it with `consent.NewService(transactor, clock)`, the `Transactor` and the application clock that the other usecases already receive. A nil transactor or clock panics at construction, so a wiring mistake shows at startup and not at the first grant. +Implemented: `consent.Service` in `backend/internal/usecase/consent/`. It is not wired into bootstrap yet, because no handler or registration flow calls it; the first caller builds it with `consent.NewService(transactor, clock)`, the `Transactor` and the application clock that the other usecases already receive. A nil transactor or clock panics at construction, so a wiring mistake shows at startup and not at the first grant. -- Entry points fix the source. `GrantAtRegistration(ctx, repositories, subjectID, version)` records C1 with the source `registration`; `GrantInSettings(ctx, repositories, SettingsGrantInput)` records C1, C2, C3, or C5 with the source `consent_settings`. Neither takes a source or a time, so a handler cannot read either from the client. `repositories` is an `outbound.ConsentRepositories`: pass the `UnitOfWork` of a business operation and the grant commits or rolls back with it. The registration (TASK-053) creates the account and records C1 in one transaction on the subject ID alone, so no session is needed. `GrantInSettingsInNewTransaction` opens its own transaction for a grant that is not part of another operation, and retries an `ErrTransactionConflict` up to three attempts in total with a short jittered wait (10 ms plus up to 10 ms) between them, which is safe because a repeat is idempotent; the wait ends at once when the context is canceled. +- Entry points fix the source. `GrantAtRegistration(ctx, repositories, subjectID, version)` records C1 with the source `registration`; `GrantInSettings(ctx, repositories, SettingsGrantInput)` records C1, C2, C3, or C5 with the source `consent_settings`. Neither takes a source or a time, so a handler cannot read either from the client. `repositories` is an `outbound.ConsentRepositories`: pass the `UnitOfWork` of a business operation and the grant commits or rolls back with it. The registration creates the account and records C1 in one transaction on the subject ID alone, so no session is needed. `GrantInSettingsInNewTransaction` opens its own transaction for a grant that is not part of another operation, and retries an `ErrTransactionConflict` up to three attempts in total with a short jittered wait (10 ms plus up to 10 ms) between them, which is safe because a repeat is idempotent; the wait ends at once when the context is canceled. - Re-registration order. For an unverified account that registers again, call `GrantAtRegistration` strictly after `UserRepository.UpdateRegistration` in the same transaction. `UpdateRegistration` deletes the registration C1 of the earlier registrant, and a grant that ran before it would find that record, return it with `Created` false, and leave the account without any C1 once it is deleted. The integration test shows both orders. -- Version check before the email branch. `CheckTextVersion(ctx, repositories, purpose, version)` returns the current text when `version` is current and fails like a grant otherwise, without writing anything. The registration (TASK-053) must call it with C1 and the submitted version before it branches on a new or an existing email; otherwise a stale version would be refused only for new addresses, and the difference would reveal which accounts exist. +- Version check before the email branch. `CheckTextVersion(ctx, repositories, purpose, version)` returns the current text when `version` is current and fails like a grant otherwise, without writing anything. The registration must call it with C1 and the submitted version before it branches on a new or an existing email; otherwise a stale version would be refused only for new addresses, and the difference would reveal which accounts exist. - Current text only. A grant reads `ConsentTexts().Current` at the application time and refuses any other version with `*StaleConsentTextError`, which matches `ErrStaleConsentText` and carries the purpose, the requested version, and the current one, so a handler can map it to one problem code and show the new text. An older version, a version that is scheduled but not yet published, and a version that never existed are all stale. The ledger accepts any published version, so this check is what keeps a grant of an outdated text out. The check and the insert are not locked against a publication between them: texts are published by migrations, and a grant that named the current text when it was checked is valid. - Server time. The input has no time field. The grant uses one reading of the injected clock for the check and for the record time; a client cannot choose the time. The database still refuses a version published after that time. - Idempotency. A repeat of the same subject, purpose, and current version returns the existing unrevoked record with `Created` false, keeps its first time, stores nothing, and does not abort a surrounding transaction. A grant after a revocation is a new record. A repeat that names an older version after a newer text was published is stale, not a repeat: the subject has to see the new text, and the ledger keeps its one record. -- C4 only through its scope. `GrantInSettings` refuses C4 with `ErrScopedConsentRequired` before it reads anything. `GrantContact(ctx, repositories, input)` is the explicitly scoped operation for the invitation acceptance (TASK-201): the input carries the organization and the name shown, the field set, the invitation, the invitation terms version, and the C4 text version. It checks that the C4 text is current, lets `domain.NewContactConsentGrant` hash the text as shown, and calls `ConsentLedger().GrantContact` in the caller's transaction. A repeat of the same subject and invitation returns the existing record with `Created` false; the caller compares its scope. The text check comes first, so a repeat after a newer C4 text was published is stale; the acceptance that wants to answer such a repeat with the earlier result must find its existing record before it calls. -- C3 may be withheld. The purposes are independent: no grant requires, implies, or changes another, and no code path requires an active C3 for the profile, the manual assessment path, or another function. A subject without C3 has no C3 record, and `Current` returns `ErrConsentNotFound` for it, which is not an error state of the account. Whoever reads C3 (the manual assessment request of TASK-315, the revocation of TASK-064) treats a missing record as "not given" and keeps the manual path open. -- No revocation here. `Revoke` stays on the ledger port, and TASK-064 calls it with the downstream effects and the outbox events in one transaction. -- Errors keep their identity: a stale version, `ErrScopedConsentRequired`, `ErrUserNotFound`, `ErrConsentTextNotFound` (the purpose has no published text), `ErrConsentInvitationTaken`, `domain.ErrInvalidConsent`, and `domain.ErrInvalidConsentText`. `outbound.ErrTransactionConflict` is the one that needs action: the ledger returns it, without aborting the transaction, when the record of a repeat was revoked between its insert and its select. A caller inside a `UnitOfWork` must return it, roll the transaction back, and retry the whole operation; `GrantInSettingsInNewTransaction` does so itself. Mapping the other errors to problem codes belongs to the handlers (TASK-064, TASK-053, TASK-201). -- Demo texts need a release gate. The texts that the migration publishes have the kind `demo`: synthetic, without a legal review. Nothing in the usecase distinguishes them from texts of the operator, so a deployment that accepts real data would record consent to a demo text. Before real data are accepted (PRD 7.3), a release gate must check that the current text of every purpose has the kind `operator`; the owner is the release gate or TASK-064, and neither exists yet. +- C4 only through its scope. `GrantInSettings` refuses C4 with `ErrScopedConsentRequired` before it reads anything. `GrantContact(ctx, repositories, input)` is the explicitly scoped operation for the invitation acceptance: the input carries the organization and the name shown, the field set, the invitation, the invitation terms version, and the C4 text version. It checks that the C4 text is current, lets `domain.NewContactConsentGrant` hash the text as shown, and calls `ConsentLedger().GrantContact` in the caller's transaction. A repeat of the same subject and invitation returns the existing record with `Created` false; the caller compares its scope. The text check comes first, so a repeat after a newer C4 text was published is stale; the acceptance that wants to answer such a repeat with the earlier result must find its existing record before it calls. +- C3 may be withheld. The purposes are independent: no grant requires, implies, or changes another, and no code path requires an active C3 for the profile, the manual assessment path, or another function. A subject without C3 has no C3 record, and `Current` returns `ErrConsentNotFound` for it, which is not an error state of the account. Whoever reads C3 (the manual assessment request, consent revocation) treats a missing record as "not given" and keeps the manual path open. +- No revocation here. `Revoke` stays on the ledger port, and consent revocation must call it with the downstream effects and the outbox events in one transaction. +- Errors keep their identity: a stale version, `ErrScopedConsentRequired`, `ErrUserNotFound`, `ErrConsentTextNotFound` (the purpose has no published text), `ErrConsentInvitationTaken`, `domain.ErrInvalidConsent`, and `domain.ErrInvalidConsentText`. `outbound.ErrTransactionConflict` is the one that needs action: the ledger returns it, without aborting the transaction, when the record of a repeat was revoked between its insert and its select. A caller inside a `UnitOfWork` must return it, roll the transaction back, and retry the whole operation; `GrantInSettingsInNewTransaction` does so itself. Mapping the other errors to problem codes belongs to the handlers. +- Demo texts need a release gate. The texts that the migration publishes have the kind `demo`: synthetic, without a legal review. Nothing in the usecase distinguishes them from texts of the operator, so a deployment that accepts real data would record consent to a demo text. Before real data are accepted (PRD 7.3), a release gate must check that the current text of every purpose has the kind `operator`; the owner is the release gate or consent revocation, and neither exists yet. ### Registration and verification resend -Implemented (TASK-053): `RegisterAccount` and `ResendEmailVerification` are served by `backend/internal/usecase/identity/register.go` (`identity.Registration`) behind the handler `backend/internal/adapter/primary/http/v1/identity.go`. Without `DATABASE_URL` both answer 501 as before. The router mounts `middleware.ClientIP` with `TRUSTED_PROXY_CIDRS`. +Implemented: `RegisterAccount` and `ResendEmailVerification` are served by `backend/internal/usecase/identity/register.go` (`identity.Registration`) behind the handler `backend/internal/adapter/primary/http/v1/identity.go`. Without `DATABASE_URL` both answer 501 as before. The router mounts `middleware.ClientIP` with `TRUSTED_PROXY_CIDRS`. One transaction. A new address creates the account (scenario and the first `onboarding_step` of the scenario), the C1 record (`GrantAtRegistration`, current text version and hash, source `registration`), the SHA-256 hash of a one-time token bound to the registration version, and the verification delivery (`ServiceMailer.EnqueueVerification`); the sending worker sends it later through the mail transport. C4 and every other purpose are never recorded: the body accepts only C1. Re-registration of an unverified address follows the lock order of the identity repositories (invalidate tokens, then `AdvanceRegistration`, then the new C1). An address that is already verified changes nothing and receives nothing: the "you already have an account" notice is not implemented, because any message to a verified address needs its own template and its own limit, and silence cannot reveal the account. Pending credentials (pre-hijack protection). Every registration, the first and each repeat, stores its password hash, scenario, and first onboarding step on its own verification token (columns `pending_*` of `email_tokens`, migration 00014). A repeat registration of an unverified address never changes the credentials, scenario, or onboarding step of the `users` row: `UserRepository.AdvanceRegistration` only advances the registration version and the registration time (and discards the earlier registration C1), and the new token carries the new pending credentials. A resend copies the pending credentials of the newest token of the registration. The `password_hash`, `scenario`, and `onboarding_step` of an unverified account row are not authoritative until a verification applies the clicked token's pending data: they hold the first registrant's values only because the columns are mandatory, and no code may authenticate with them or trust them (see the comment on `domain.User`). Invalidating a token (`InvalidateActive`) clears its `pending_*` columns, and a CHECK constraint keeps an invalidated token from holding a pending hash. A resend that finds no pending credentials for the registration issues nothing. Requirements for the hand-off: -- TASK-054 (`ConfirmEmail`): confirming a token applies the pending credentials of the clicked token, and only those, to the account row in the confirmation transaction (password hash, scenario, onboarding step), and must require the password of that registration to confirm a token that carries pending credentials, verified against the token's pending hash. Then a victim who clicks an attacker's link cannot adopt the attacker's password, and an attacker cannot confirm the victim's token. `EmailVerificationRequest` has no password field today; adding it is a contract change of TASK-054, not made here. The description of `RegisterAccount` in the contract still says a repeat registration replaces the password hash on the account; TASK-054 corrects it with that change. -- TASK-054 also: test both orderings (the attacker registers first and the victim second, and the reverse) and show that the owner never ends up with a password they did not choose; require that a C1 record exists and belongs to the registration version of the confirmed token; refuse a token that carries no pending credentials, with no legacy path that skips the password; null the `pending_*` columns of the token when it is consumed. -- TASK-055 (login): an unverified account never signs in. Login answers as for a wrong password (or `email_not_verified` only where the contract allows it) without comparing the password with the row of an unverified account or with pending credentials. +- Email confirmation (`ConfirmEmail`): confirming a token applies the pending credentials of the clicked token, and only those, to the account row in the confirmation transaction (password hash, scenario, onboarding step), and must require the password of that registration to confirm a token that carries pending credentials, verified against the token's pending hash. Then a victim who clicks an attacker's link cannot adopt the attacker's password, and an attacker cannot confirm the victim's token. `EmailVerificationRequest` has no password field today; adding it is an email confirmation contract change, not made here. The description of `RegisterAccount` in the contract still says a repeat registration replaces the password hash on the account; email confirmation must correct it with that change. +- Email confirmation also requires: test both orderings (the attacker registers first and the victim second, and the reverse) and show that the owner never ends up with a password they did not choose; require that a C1 record exists and belongs to the registration version of the confirmed token; refuse a token that carries no pending credentials, with no legacy path that skips the password; null the `pending_*` columns of the token when it is consumed. +- Login: an unverified account never signs in. Login answers as for a wrong password (or `email_not_verified` only where the contract allows it) without comparing the password with the row of an unverified account or with pending credentials. Order of checks in registration: validation of the whole body and the C1 text version, replay check, rate limit, password hash (on every branch, before the account is read), transaction. A validation error (400) never depends on the stored accounts and consumes no limit. @@ -759,7 +759,7 @@ Known limits. A resend for an unknown or verified address skips the token and me ### Organizations and memberships -Implemented as storage, ports, and a source contract (TASK-077): migration `backend/db/migrations/00010_create_organizations.sql`, queries in `backend/db/queries/organizations.sql`, domain types in `backend/internal/domain/organization.go` and `membership.go`, the ports in `backend/internal/port/outbound/organizations.go`, the sqlc-backed adapter in `backend/internal/adapter/secondary/postgres/organizations.go`, and `ListMyOrganizations`, `CreateOrganization`, `GetOrganization`, and `UpdateOrganization` in the public contract ([api/README.en.md](../../api/README.en.md#organizations)). The create, read, and update usecases with their handlers (TASK-078) and the server-side context and membership checks of every tenant operation (TASK-079) are planned; until then the operations answer 401 or 501 and nothing in bootstrap calls the repositories. The only implemented behavior is the storage and its constraints. +Implemented as storage, ports, and a source contract: migration `backend/db/migrations/00010_create_organizations.sql`, queries in `backend/db/queries/organizations.sql`, domain types in `backend/internal/domain/organization.go` and `membership.go`, the ports in `backend/internal/port/outbound/organizations.go`, the sqlc-backed adapter in `backend/internal/adapter/secondary/postgres/organizations.go`, and `ListMyOrganizations`, `CreateOrganization`, `GetOrganization`, and `UpdateOrganization` in the public contract ([api/README.en.md](../../api/README.en.md#organizations)). The create, read, and update usecases with their handlers and the server-side context and membership checks of every tenant operation are planned; until then the operations answer 401 or 501 and nothing in bootstrap calls the repositories. The only implemented behavior is the storage and its constraints. Tables: @@ -769,13 +769,13 @@ Tables: Decisions: -- Active context. It is not a server-side session attribute. The organization is the `org_id` in the path, and the server derives the right from the active membership on every request, so a removal, a suspension, or a leave closes the next read with nothing to invalidate. `ListMyOrganizations` is the directory a client picks from; remembering the last choice is a browser convenience. The decision follows TASK-079 (the context comes only from the caller's active memberships, and a terminated membership closes reads at once) and TASK-085 (a switch clears the client's tenant queries). -- Role and state in the membership only. `OrganizationRole` is `owner`, `recruiter`, `hiring_manager`, or `technical_expert` (PRD 2.2, Q3, and the FR07 matrix), and `MembershipState` is `active`, `suspended`, `removed`, or `left`, each a CHECK constraint, not a PostgreSQL enum, so a later value is a constraint change in a migration. There is no `invited` state: PRD 6.4 lists `MemberInvite` as its own entity, an invitation to an email address that may have no account yet, and a membership row appears when its owner accepts it (TASK-081, TASK-082). `organizations` has no role, owner, or member column (an integration test reads the catalog to prove it), and `Organization`, `OrganizationCreate`, and `OrganizationUpdate` have no such field. Only the owner manages the company (`OrganizationRole.CanManageOrganization`); the rest of the matrix is applied by the operations it governs, and in the MVP the other roles grant nothing (TASK-083, TASK-463). -- Verification level. `verification_level` is `e0` to `e3` with `verification_basis` (`confirmed_email`, `corporate_domain`, `requisites_and_authority`, `manual_review`, `partner_status`), and one CHECK ties each level to its own bases. The columns are separate from the profile: `UpdateOrganizationProfile` never names them, `domain.NewOrganization` cannot choose a level and starts every organization at `e0` on `confirmed_email`, `Organization.ApplyProfile` keeps the verification, and the contract has no operation or request field that sets it. A test updates a profile after a process moved the level and checks that it stays. E1 to E3 are set by the verification processes that do not exist yet; TASK-086 adds E0/E1 with evidence, a scope, and an append-only history, and it will update these columns together with its history row and must first write a history record from the current row of every existing organization (level, basis, and time as stored), so the history has no gap before its first process. `OrganizationVerificationLevel.QuotaTier` maps `e0` to `e2` to the quota tiers of the product policy and has none for `e3`, which the PRD gives a separate policy (TASK-087 reads the tier and must fail closed on an `e3` organization: no quota granted, the action refused, never a fallback to another tier). -- An organization has an owner. A deferred constraint trigger (`organizations_owner_required`, SQLSTATE 23514) refuses at commit an organization with no `owner` membership in the `active` state, so creating an organization without its owner fails whichever code inserted it, and `CreateWithOwner` stores the organization, its representatives, and the owner in one transaction. Removing or demoting the last owner later is a rule of the member management (TASK-084), not of this constraint, which would otherwise block a platform decision about an abusive organization. -- Update. `UpdateProfile` is one statement that applies only when the stored version equals the version the caller read, and advances it by one. The same statement requires an active membership of the actor with a manager role (the roles come from `domain.ManagerRoles`, not from SQL), so a membership that ended after the caller's read still stops the write. When the statement matches nothing, the adapter reads the membership to answer `ErrOrganizationNotFound` (unknown organization or no active membership), `ErrOrganizationManagerRequired`, or `ErrOrganizationVersionConflict`, in that order, so a stale version never tells an outsider anything. The representative list is then replaced in the same transaction under the row lock of the update. The statement locks the organization row (`FOR UPDATE`) and then the actor's membership row `FOR SHARE`, so a revocation that commits while the statement waits for the membership lock is re-evaluated and stops the write (an integration test holds a revocation open, queues the update behind it, and commits it). The lock order of every writer is organizations, then memberships: the member management of TASK-084, which changes a membership and the organization together, and the tenant repository of TASK-079 must take the locks in that order, or two transactions can deadlock. -- Foreign keys and deletion. `memberships` restricts the deletion of an organization and of an account, so an account with memberships cannot be deleted until a procedure ends them, in the same way as the consent ledger restricts the account. The application never deletes an organization. The consent ledger does not reference `organizations` yet: `consent_records.organization_id` is still a plain column with the snapshot name beside it. Adding the foreign key now would force the ledger tests of TASK-062 and TASK-063 to create real organizations, and the same migration has to add the `invitation_id` key, which needs the invitation table; both arrive with the migration that creates the invitation records (TASK-198), together with the keys of needs (TASK-179). All of them are `ON DELETE RESTRICT`, so an organization with consent history, needs, or invitations stays undeletable, which is the intended protection of consent evidence (PRD 7.3). -- Privacy. Contacts are public company channels; the contract and the domain accept no personal contact of an employee, and the owner answers for the content. Representative names are personal data of employees: `OrganizationRepresentative` hides its fields behind a pointer and redacts itself in `fmt` and `slog` output, `Organization` logs only its identifier, version, and level, and adapter errors keep the SQLSTATE and the constraint name without the failing row. The website is only stored: the server never fetches it, and a later feature that does must resolve the address and refuse private ranges itself. `StoredRepresentative`, `OrganizationRepresentativeInput`, `OrganizationProfileInput`, and the generated sqlc parameter structs of this repository hold names and must never be logged. The idempotency store of `CreateOrganization` (TASK-078) keeps the stored 201 for 24 hours, and that response holds the representatives' names: the store must keep it out of logs and metrics, protect it like the other personal data, and delete it at the end of the replay window; its request fingerprint must be a hash, not the body. The candidate card is shown only to a candidate who received an invitation from the organization, and its `representatives` may be absent. The open questions (the publication of representative names, a sphere taxonomy) and the blocking one, a limit of organizations per account, which the PRD does not set and without which an account can multiply quotas by creating organizations (TASK-078 and TASK-087 need the owner's decision, and the prepared mechanism is a 409 `state_conflict` on create), are in [api/README.en.md](../../api/README.en.md#organizations). +- Active context. It is not a server-side session attribute. The organization is the `org_id` in the path, and the server derives the right from the active membership on every request, so a removal, a suspension, or a leave closes the next read with nothing to invalidate. `ListMyOrganizations` is the directory a client picks from; remembering the last choice is a browser convenience. The context comes only from the caller's active memberships, and a terminated membership closes reads at once. A switch clears the client's tenant queries. +- Role and state in the membership only. `OrganizationRole` is `owner`, `recruiter`, `hiring_manager`, or `technical_expert` (PRD 2.2, Q3, and the FR07 matrix), and `MembershipState` is `active`, `suspended`, `removed`, or `left`, each a CHECK constraint, not a PostgreSQL enum, so a later value is a constraint change in a migration. There is no `invited` state: PRD 6.4 lists `MemberInvite` as its own entity, an invitation to an email address that may have no account yet, and a membership row appears when its owner accepts it. `organizations` has no role, owner, or member column (an integration test reads the catalog to prove it), and `Organization`, `OrganizationCreate`, and `OrganizationUpdate` have no such field. Only the owner manages the company (`OrganizationRole.CanManageOrganization`); the rest of the matrix is applied by the operations it governs, and in the MVP the other roles grant nothing. +- Verification level. `verification_level` is `e0` to `e3` with `verification_basis` (`confirmed_email`, `corporate_domain`, `requisites_and_authority`, `manual_review`, `partner_status`), and one CHECK ties each level to its own bases. The columns are separate from the profile: `UpdateOrganizationProfile` never names them, `domain.NewOrganization` cannot choose a level and starts every organization at `e0` on `confirmed_email`, `Organization.ApplyProfile` keeps the verification, and the contract has no operation or request field that sets it. A test updates a profile after a process moved the level and checks that it stays. E1 to E3 are set by the verification processes that do not exist yet; the planned verification flow adds E0/E1 with evidence, a scope, and an append-only history, and it will update these columns together with its history row and must first write a history record from the current row of every existing organization (level, basis, and time as stored), so the history has no gap before its first process. `OrganizationVerificationLevel.QuotaTier` maps `e0` to `e2` to the quota tiers of the product policy and has none for `e3`, which the PRD gives a separate policy (quota enforcement reads the tier and must fail closed on an `e3` organization: no quota granted, the action refused, never a fallback to another tier). +- An organization has an owner. A deferred constraint trigger (`organizations_owner_required`, SQLSTATE 23514) refuses at commit an organization with no `owner` membership in the `active` state, so creating an organization without its owner fails whichever code inserted it, and `CreateWithOwner` stores the organization, its representatives, and the owner in one transaction. Removing or demoting the last owner later is a rule of the member management, not of this constraint, which would otherwise block a platform decision about an abusive organization. +- Update. `UpdateProfile` is one statement that applies only when the stored version equals the version the caller read, and advances it by one. The same statement requires an active membership of the actor with a manager role (the roles come from `domain.ManagerRoles`, not from SQL), so a membership that ended after the caller's read still stops the write. When the statement matches nothing, the adapter reads the membership to answer `ErrOrganizationNotFound` (unknown organization or no active membership), `ErrOrganizationManagerRequired`, or `ErrOrganizationVersionConflict`, in that order, so a stale version never tells an outsider anything. The representative list is then replaced in the same transaction under the row lock of the update. The statement locks the organization row (`FOR UPDATE`) and then the actor's membership row `FOR SHARE`, so a revocation that commits while the statement waits for the membership lock is re-evaluated and stops the write (an integration test holds a revocation open, queues the update behind it, and commits it). The lock order of every writer is organizations, then memberships: the member management, which changes a membership and the organization together, and the tenant repository must take the locks in that order, or two transactions can deadlock. +- Foreign keys and deletion. `memberships` restricts the deletion of an organization and of an account, so an account with memberships cannot be deleted until a procedure ends them, in the same way as the consent ledger restricts the account. The application never deletes an organization. The consent ledger does not reference `organizations` yet: `consent_records.organization_id` is still a plain column with the snapshot name beside it. Adding the foreign key now would force the consent ledger tests to create real organizations, and the same migration has to add the `invitation_id` key, which needs the invitation table; both arrive with the migration that creates the invitation records, together with the keys of needs. All of them are `ON DELETE RESTRICT`, so an organization with consent history, needs, or invitations stays undeletable, which is the intended protection of consent evidence (PRD 7.3). +- Privacy. Contacts are public company channels; the contract and the domain accept no personal contact of an employee, and the owner answers for the content. Representative names are personal data of employees: `OrganizationRepresentative` hides its fields behind a pointer and redacts itself in `fmt` and `slog` output, `Organization` logs only its identifier, version, and level, and adapter errors keep the SQLSTATE and the constraint name without the failing row. The website is only stored: the server never fetches it, and a later feature that does must resolve the address and refuse private ranges itself. `StoredRepresentative`, `OrganizationRepresentativeInput`, `OrganizationProfileInput`, and the generated sqlc parameter structs of this repository hold names and must never be logged. The idempotency store of `CreateOrganization` keeps the stored 201 for 24 hours, and that response holds the representatives' names: the store must keep it out of logs and metrics, protect it like the other personal data, and delete it at the end of the replay window; its request fingerprint must be a hash, not the body. The candidate card is shown only to a candidate who received an invitation from the organization, and its `representatives` may be absent. The open questions (the publication of representative names, a sphere taxonomy) and the blocking one, a limit of organizations per account, which the PRD does not set and without which an account can multiply quotas by creating organizations (organization creation and quota enforcement need the owner's decision, and the prepared mechanism is a 409 `state_conflict` on create), are in [api/README.en.md](../../api/README.en.md#organizations). What the ports guarantee (`outbound.OrganizationRepositories`, available on `UnitOfWork` only, because a write needs the transaction): @@ -785,7 +785,7 @@ What the ports guarantee (`outbound.OrganizationRepositories`, available on `Uni ### Candidate profile -Implemented as storage, domain, and the source contract (TASK-066): the migration `backend/db/migrations/00013_create_candidate_profiles.sql`, the queries in `backend/db/queries/candidate.sql`, the domain types in `backend/internal/domain/candidate.go`, the schemas in `api/core/components/schemas/candidate_schemas.yml`, and the operations `GetMyProfile` and `SaveMyProfile` in `api/core/routes/candidate_profile.yml`. There is no port, adapter, or handler yet: the operations answer 401 `unauthenticated` while there are no sessions and 501 `not_implemented` after validation. The port and the adapter will come with the handlers and must join `UnitOfWork`; the queries and the domain conversion of rows (`StoredClaims`, `RestoreCandidateProfile`) are ready and covered by an integration test. +Implemented as storage, domain, and the source contract: the migration `backend/db/migrations/00013_create_candidate_profiles.sql`, the queries in `backend/db/queries/candidate.sql`, the domain types in `backend/internal/domain/candidate.go`, the schemas in `api/core/components/schemas/candidate_schemas.yml`, and the operations `GetMyProfile` and `SaveMyProfile` in `api/core/routes/candidate_profile.yml`. There is no port, adapter, or handler yet: the operations answer 401 `unauthenticated` while there are no sessions and 501 `not_implemented` after validation. The port and the adapter will come with the handlers and must join `UnitOfWork`; the queries and the domain conversion of rows (`StoredClaims`, `RestoreCandidateProfile`) are ready and covered by an integration test. Tables: @@ -804,7 +804,7 @@ Decisions: ### Candidate visibility -Implemented as storage, domain, and the source contract (TASK-088): the migration `backend/db/migrations/00015_create_candidate_privacy.sql` (number 00014 belongs to the idempotency records of the registration task), the queries in `backend/db/queries/privacy.sql`, the domain types in `backend/internal/domain/visibility.go`, the schemas in `api/core/components/schemas/privacy_schemas.yml`, and nine operations of the tag `privacy` in `api/core/routes/candidate_privacy*.yml` under `/api/v1/me/privacy` ([api/README.en.md](../../api/README.en.md#candidate-visibility)). There is no port, adapter, or handler yet: the operations answer 401 `unauthenticated` while there are no sessions and 501 `not_implemented` after validation. The port and the adapter come with the handlers and must join `UnitOfWork`; the queries and the domain conversion of rows (`RestorePublication`, `RestoreSearchStatus`) are ready and covered by an integration test. +Implemented as storage, domain, and the source contract: the migration `backend/db/migrations/00015_create_candidate_privacy.sql` (number 00014 belongs to the idempotency records of the registration task), the queries in `backend/db/queries/privacy.sql`, the domain types in `backend/internal/domain/visibility.go`, the schemas in `api/core/components/schemas/privacy_schemas.yml`, and nine operations of the tag `privacy` in `api/core/routes/candidate_privacy*.yml` under `/api/v1/me/privacy` ([api/README.en.md](../../api/README.en.md#candidate-visibility)). There is no port, adapter, or handler yet: the operations answer 401 `unauthenticated` while there are no sessions and 501 `not_implemented` after validation. The port and the adapter come with the handlers and must join `UnitOfWork`; the queries and the domain conversion of rows (`RestorePublication`, `RestoreSearchStatus`) are ready and covered by an integration test. Four independent pieces of state, each with its own table and its own version. No statement of one table writes another, and the consent C2 is neither copied nor replaced: @@ -825,20 +825,20 @@ Decisions: - History instead of a field scope. The C2 record proves the consent to the publication text, and `candidate_privacy_events` keeps what the consent ledger note asked for: the published field set and its changes with their times and the C2 record behind each. A revocation of C2 and a lapse are computed, not events. Whether C2 needs its own field scope as a consent under article 10.1 of 152-FZ is still a legal question (see the consent ledger). - Privacy. The tables hold identifiers, card field codes, and times; no profile value, name, contact, or file (a test lists the columns). `Publication`, `SearchStatus`, `HiddenOrganization`, and `PrivacyEvent` log only identifiers, versions, and kinds. No query selects another account's row: every statement is scoped by `user_id`. The adapter must report only the SQLSTATE and the constraint name, as the others do. -- One structural barrier for organization-facing reads. The view `candidate_effective_publications` is published AND backed by an unrevoked C2 record. Every read on behalf of an organization (the search, the card, the contact read: TASK-185, TASK-089, TASK-090) must select from this view and add `NOT EXISTS` over `candidate_hidden_organizations` for the reading organization, as `ReadPublicationVisibleToOrganization` does; no row means "nothing to read" whichever reason applies, so an organization cannot tell a hidden candidate from an unpublished one. Reading `candidate_publications` directly is reserved for the candidate's own settings queries, and `backend/db/privacy_queries_test.go` fails when any other query in `db/queries` names the table. -- Closing over a revoked C2. A closing sent over a stored `published` row whose C2 was revoked is a real change: the row is normalized to `closed`, `publication_closed` is recorded, and the contact grants are revoked with `visibility_closed` like for any closing. Only a stored `closed` row makes a closing a repeat. The C2 revocation path (TASK-064) must itself close the stored publication and revoke the contact grants of the account in its own transaction; the computed state closes the card at once, but it does not revoke grants. +- One structural barrier for organization-facing reads. The view `candidate_effective_publications` is published AND backed by an unrevoked C2 record. Every read on behalf of an organization (the search, the card, the contact read) must select from this view and add `NOT EXISTS` over `candidate_hidden_organizations` for the reading organization, as `ReadPublicationVisibleToOrganization` does; no row means "nothing to read" whichever reason applies, so an organization cannot tell a hidden candidate from an unpublished one. Reading `candidate_publications` directly is reserved for the candidate's own settings queries, and `backend/db/privacy_queries_test.go` fails when any other query in `db/queries` names the table. +- Closing over a revoked C2. A closing sent over a stored `published` row whose C2 was revoked is a real change: the row is normalized to `closed`, `publication_closed` is recorded, and the contact grants are revoked with `visibility_closed` like for any closing. Only a stored `closed` row makes a closing a repeat. The C2 revocation path must itself close the stored publication and revoke the contact grants of the account in its own transaction; the computed state closes the card at once, but it does not revoke grants. - Publish and revoke race. The publish transaction takes the current C2 with `LockCurrentC2Record` (`SELECT ... FOR SHARE`) and writes the publication under that lock, then re-reads the effective state with `ReadCandidatePublication` in the same transaction to build its response. The revocation stamp is an UPDATE of the same row, so it either commits first (the lock returns no row and the publication is refused with 409) or waits until the publication commits and closes the card right after; an integration test holds the lock and proves both orders. - Verified email. Publishing, hiding, and the history exist only for accounts with a verified email (a usecase requirement). The unverified account cleanup (`DeleteUnverifiedUsersRegisteredBefore`) deletes its consent records explicitly and would meet the restricting reference of a publication to its C2 record, so that no unconfirmed account holds a publication is a usecase requirement, not a physical impossibility: the cleanup also works over an unverified account that does hold a C2, a publication, and history, and over a C2 revoked and granted again (an integration scenario verifies it, and it depends on the order in which the data-modifying statements of the cleanup apply). Hiding records and history cascade. - Two kinds of 409 `state_conflict` 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. The hiding limit is enforced by the trigger under a lock on the account row; when an insertion fails with SQLSTATE 23514 and `candidate_hidden_organizations_limit`, the adapter must re-read the pair before answering 409, because a concurrent PUT of the same pair at 999 records can have created it, and the idempotent answer is 200; an integration test fires eight concurrent insertions at 999 records and expects exactly one success. - A new card field is a contract change and a migration. The codes are listed in the function `candidate_card_fields_are_canonical` and the CHECK constraints of the publication and event tables, as well as in the `CardField` enum, `domain.CardField`, and the card builder. -Content of the card (hard requirements for TASK-089, which builds it): +Content of the card (hard requirements for its builder): - Only values that the candidate confirmed ever reach the card; an unconfirmed suggestion (status `extracted`) and an unknown value never do, whatever the field set says. - A free text value (a stack tag, a soft skill, the location) that looks like a contact (an email address, a phone number, a URL or domain, a Telegram link, an @handle) is dropped, never published. `domain.CardTextLooksLikeContact` is the check the builder must apply to every free text; it errs on the side of dropping. -- Quasi-identifiers (a rare combination of location, stack, and experience) and the generalization of rare features are an acceptance criterion of TASK-089, not decided here (see the open question in the API README). +- Quasi-identifiers (a rare combination of location, stack, and experience) and the generalization of rare features are an acceptance criterion for the card builder, not decided here (see the open question in the API README). -The anonymous card for organizations is not built here: `AnonymousCardContent` is the closed set of properties that a published card can hold (confirmed categories, stack, total months of experience, soft skills, location, relocation), with no name, contact, employer, salary, or identifier, and a contract test walks the references of the card and the preview and fails on any profile, contact, consent, or organization schema. The card of an organization's search result (TASK-185) must reuse it. `GetMyCardPreview` and `ListMyCardAccessHistory` are contract-only: the preview needs the profile, the confirmed categories, and the publication read together, and the access records are written by the search and contact-read tasks, so the table for them comes with those tasks. +The anonymous card for organizations is not built here: `AnonymousCardContent` is the closed set of properties that a published card can hold (confirmed categories, stack, total months of experience, soft skills, location, relocation), with no name, contact, employer, salary, or identifier, and a contract test walks the references of the card and the preview and fails on any profile, contact, consent, or organization schema. The card of an organization's search result must reuse it. `GetMyCardPreview` and `ListMyCardAccessHistory` are contract-only: the preview needs the profile, the confirmed categories, and the publication read together, and the access records are written by the search and contact-read tasks, so the table for them comes with those tasks. ## Frontend @@ -875,7 +875,7 @@ Contract rules: UUID identifiers, UTC date-time, explicit enums, integer RUB amo ## Metrics, telemetry, and alerts -The Go service exports standard Go/process metrics and the product metrics of TASK-022 on an internal `/metrics` listener outside `/api/v1`: +The Go service exports standard Go/process metrics and the product metrics on an internal `/metrics` listener outside `/api/v1`: - API: `lincodex_http_requests_total{method,route,status}`, `lincodex_http_request_duration_seconds{method,route,status_class}`, and `lincodex_http_problems_total{route,code}`. `route` is the chi route template of an operational route and, under `/api/v1`, the OpenAPI path template of the matched operation, such as `/api/v1/me/invitations/{invitation_id}`, which the router resolves with the generated server's `FindPath`; a path or method without an operation keeps the mount pattern `/api/v1/*` or `/api/*`, and a path outside every route is `unmatched`. `status_class` is `1xx` to `5xx`. `code` is the RFC 9457 problem code: `problem.New` records it from the closed catalogue through the request-scoped `observe` package (`adapter/primary/http/observe/`), the middleware counts it only for a 4xx or 5xx response, and the adapter counts a code outside its mirrored list as `other`. An error without a problem body, such as `/readyz` 503, is counted by status only. The request log (`middleware.RequestLog`, which replaces the go-httpkit logger) uses the same route template and logs the request ID, method, status and class, problem code, latency, response size, and the number of query parameters, never the raw path, a query key or value, a header, the client address, or the user agent; `/healthz` and `/readyz` are not logged. - Outbox and events: the relay, consumer, and scheduled job metrics in [Outbox relay](#outbox-relay), [Event consumers](#event-consumers), and [Scheduled jobs](#scheduled-jobs). Outbox lag is `lincodex_outbox_relay_oldest_pending_age_seconds`. diff --git a/docs/en/DEPLOY.md b/docs/en/DEPLOY.md index 4a69ccf..b311bae 100644 --- a/docs/en/DEPLOY.md +++ b/docs/en/DEPLOY.md @@ -233,7 +233,7 @@ A worker claims it within one poll interval and runs it with fresh attempts. To The backend sends mail through the `MailSender` port. `EMAIL_PROVIDER` selects exactly one transport: `resend` (the Resend HTTP API, the primary provider for the working stand), `smtp` (a separate SMTP relay), or `disabled`. It has no default, and there is no fallback: when the selected transport cannot start, the backend stops instead of switching to another one. Settings of transports that are not selected are not read. -Current state: this build contains the `disabled` and `resend` transports. With `smtp`, the backend validates the SMTP settings and then exits with `EMAIL_PROVIDER=smtp: mail transport is not available in this build`; under Compose, `restart: unless-stopped` restarts the container repeatedly. SMTP is outside the MVP. `.env.example` and `make -C deploy smoke` use `disabled`, so local runs need no key; the working stand sets `EMAIL_PROVIDER=resend` and `RESEND_API_KEY` explicitly. The backend process runs a sending worker for service identity mail (email verification and password reset) whenever `EMAIL_PROVIDER` is `resend`; see [Sending service mail](#sending-service-mail). No account flow creates such mail yet, and product notifications are stored as deliveries but not sent until TASK-462, so a production stand sends no message today. +Current state: this build contains the `disabled` and `resend` transports. With `smtp`, the backend validates the SMTP settings and then exits with `EMAIL_PROVIDER=smtp: mail transport is not available in this build`; under Compose, `restart: unless-stopped` restarts the container repeatedly. SMTP is outside the MVP. `.env.example` and `make -C deploy smoke` use `disabled`, so local runs need no key; the working stand sets `EMAIL_PROVIDER=resend` and `RESEND_API_KEY` explicitly. The backend process runs a sending worker for service identity mail (email verification and password reset) whenever `EMAIL_PROVIDER` is `resend`; see [Sending service mail](#sending-service-mail). No account flow creates such mail yet, and product notifications are stored as deliveries but not sent until product notification sending is implemented, so a production stand sends no message today. `resend` sends each message with one request to `https://api.resend.com/emails`. Building the transport makes no network call, so startup checks neither the key nor the sender domain; a wrong key or an unverified domain in `EMAIL_FROM` shows up as a rejected send. One attempt is limited by `EMAIL_TIMEOUT`. The transport follows no redirects, never retries, and logs nothing; retries, backoff, rate-limit pacing, and outcome records belong to the planned delivery layer, and the wait for a daily or monthly quota reset is decided by the quota gate (see [Mail quotas](#mail-quotas)). Each request carries the message's idempotency key, and Resend deduplicates the same key and body for 24 hours; after that window a retry may send the mail twice. A success means that Resend accepted the request and returned a message ID, not that the mail was delivered or read. A timeout, a lost answer after the request was sent, or a Resend 500 error is `unknown` (`delivery_uncertain`), not a failure. The backend process follows the standard `HTTPS_PROXY` and `NO_PROXY` variables, but the Compose backend service does not pass them, so under Compose the request goes directly to Resend; a stand that needs an egress proxy must add them to the backend `environment`. The full mapping of answers is in [ARCHITECTURE.md](ARCHITECTURE.md#mail-transport). @@ -258,18 +258,18 @@ Compose passes these variables from the root `.env`; it passes an unset `EMAIL_Q ### Mail deliveries -A notification request is a row in `mail_requests` until the consumer `notification_delivery` turns it into a row in `deliveries` and deletes it; the model is in [ARCHITECTURE.md](ARCHITECTURE.md#mail-deliveries). Migration 00006 creates `mail_requests`, `deliveries`, and `delivery_attempts` at startup; it needs no setting. Notification deliveries are only stored for now: the sending worker claims verification and password reset mail only, so a notification stays `pending` until TASK-462 connects product notifications. Notifications are created only for accounts with a verified address; a request for an unverified address is dropped with a log line. +A notification request is a row in `mail_requests` until the consumer `notification_delivery` turns it into a row in `deliveries` and deletes it; the model is in [ARCHITECTURE.md](ARCHITECTURE.md#mail-deliveries). Migration 00006 creates `mail_requests`, `deliveries`, and `delivery_attempts` at startup; it needs no setting. Notification deliveries are only stored for now: the sending worker claims verification and password reset mail only, so a notification stays `pending` until product notification sending is implemented. Notifications are created only for accounts with a verified address; a request for an unverified address is dropped with a log line. - Each delivery is pinned to `EMAIL_PROVIDER` and `EMAIL_ACCOUNT` at creation, and a later configuration change applies only to new deliveries. Change `EMAIL_ACCOUNT` together with `RESEND_API_KEY` whenever the key belongs to another Resend account, so deliveries that started under the old account are never sent through the new one. Service mail created while `EMAIL_PROVIDER=disabled` stays pinned to `disabled` until the backend runs with a transport: the sending worker then moves it with `Rebind` (allowed only before the first attempt) and sends it if its token and account still pass the check. Do not rebind by hand. - The rows hold the recipient address and the rendered bodies, and a waiting `mail_requests` row holds the raw notification text; verification and password reset bodies hold a live one-time token until it is used or expires. Treat read access to `deliveries` like access to those links, and keep database dumps and backups under the same protection. Retention of finished deliveries is not implemented yet. - To inspect deliveries, select metadata only, for example `SELECT id, kind, template_version, status, attempt_count, next_attempt_at, last_attempt_at, provider, provider_account, created_at FROM deliveries ORDER BY created_at DESC LIMIT 50`, and `SELECT attempt_number, attempted_at, outcome, rejection, provider_code, status_after FROM delivery_attempts WHERE delivery_id = '' ORDER BY attempt_number`. `SELECT count(*), min(created_at) FROM mail_requests` shows requests the consumer has not handled yet; a growing count means the consumer is stopped or its events are dead-lettered. Do not select `recipient_email`, `subject`, `text_body`, `html_body`, or the `mail_requests` text columns, and never paste them into tickets or chats. -- Without SQL, the internal /metrics endpoint shows `lincodex_mail_deliveries{kind,status}` for every kind and status, zero included, and `lincodex_mail_delivery_oldest_due_pending_age_seconds`, the time the earliest pending delivery has been due. The backend reads them every 30 seconds with one aggregate over `deliveries`; every instance reports the same values, so aggregate them with `max`. A read that fails keeps the previous values and logs `delivery metrics could not be read; the gauges are stale`. Notifications stay `pending` until TASK-462; they are not counted in the due age. The age series appears only after the first successful read, so a fresh start never claims that nothing is late; `lincodex_mail_metrics_last_success_timestamp_seconds` is the Unix time of the last read in which every aggregate was read (0 from the start until the first one), and `LincodexMailMetricsStale` fires when it is more than 5 minutes old for 5 minutes. The alert `LincodexMailDeliveryUnknownOutcome` fires while any delivery has an unknown outcome. `LincodexMailDeliveriesOverdue` (a pending delivery due for more than 15 minutes) also requires `lincodex_mail_sender_running` to be 1 on some instance: the sending worker exports it, 1 while its loop runs and 0 otherwise, so the alert stays silent with `EMAIL_PROVIDER=disabled` (no loop starts) and without traffic. The age counts only service mail (verification and password reset), so a backlog of notifications, which the worker does not send until TASK-462, does not fire it. The status `cancelled` is counted like the others, and `accepted` means accepted by the provider. +- Without SQL, the internal /metrics endpoint shows `lincodex_mail_deliveries{kind,status}` for every kind and status, zero included, and `lincodex_mail_delivery_oldest_due_pending_age_seconds`, the time the earliest pending delivery has been due. The backend reads them every 30 seconds with one aggregate over `deliveries`; every instance reports the same values, so aggregate them with `max`. A read that fails keeps the previous values and logs `delivery metrics could not be read; the gauges are stale`. Notifications stay `pending` until product notification sending is implemented; they are not counted in the due age. The age series appears only after the first successful read, so a fresh start never claims that nothing is late; `lincodex_mail_metrics_last_success_timestamp_seconds` is the Unix time of the last read in which every aggregate was read (0 from the start until the first one), and `LincodexMailMetricsStale` fires when it is more than 5 minutes old for 5 minutes. The alert `LincodexMailDeliveryUnknownOutcome` fires while any delivery has an unknown outcome. `LincodexMailDeliveriesOverdue` (a pending delivery due for more than 15 minutes) also requires `lincodex_mail_sender_running` to be 1 on some instance: the sending worker exports it, 1 while its loop runs and 0 otherwise, so the alert stays silent with `EMAIL_PROVIDER=disabled` (no loop starts) and without traffic. The age counts only service mail (verification and password reset), so a backlog of notifications, which the worker does not send until product notification sending is implemented, does not fire it. The status `cancelled` is counted like the others, and `accepted` means accepted by the provider. - Do not edit a stored delivery by hand: a trigger refuses any change to the recipient, content, or idempotency key and a change of the provider account after the first attempt, and the attempt history refuses updates. A delivery in `waiting_quota` waits for the quota reset at `next_attempt_at`; see [Mail quotas](#mail-quotas). Without `next_attempt_at` its reset is unknown and it needs an operator decision. - Logs name a delivery only by `delivery_id` (with the event ID), never by address or subject. Skipped requests are logged at info level: `mail request skipped because it was already handled or its account was deleted` and `notification skipped because the recipient address is not verified`. A request that breaks the event contract is a `handler_rejected` dead letter of the consumer `notification_delivery`; see [Dead letters and replay](#dead-letters-and-replay). Replaying it is safe: the delivery ID keeps one delivery per request. ### Mail quotas -Migration 00007 creates `mail_quota_usage` and the reservation journal `mail_quota_reservations` at startup; it needs no setting. The sending worker calls the quota gate around every send (see [Sending service mail](#sending-service-mail)), so service mail counts against the quota and notifications do not until TASK-462. The model is in [ARCHITECTURE.md](ARCHITECTURE.md#mail-quotas). +Migration 00007 creates `mail_quota_usage` and the reservation journal `mail_quota_reservations` at startup; it needs no setting. The sending worker calls the quota gate around every send (see [Sending service mail](#sending-service-mail)), so service mail counts against the quota and notifications do not until product notification sending is implemented. The model is in [ARCHITECTURE.md](ARCHITECTURE.md#mail-quotas). - Set `EMAIL_QUOTA_DAILY` and `EMAIL_QUOTA_MONTHLY` to the plan of the provider account named by `EMAIL_ACCOUNT`. The defaults are Resend Free: 100 recipients per UTC day and 3000 per month, as checked on 2026-10-05. Check the account's current quota in the Resend dashboard before the stand goes live and after any plan change. With `smtp`, set both to the relay's limits; startup fails without them. A changed value applies after a restart. - Change `EMAIL_ACCOUNT` only together with a real change of the provider account, that is, a key of another account. The local count is kept per account label, so renaming the label for the same account starts a new count from zero while the provider keeps the old one. At startup the backend logs `mail quota usage` with the provider, account, and the current day and month usage and limits, and warns when other labels of the same provider have usage this month. @@ -278,7 +278,7 @@ Migration 00007 creates `mail_quota_usage` and the reservation journal `mail_quo - The internal /metrics endpoint shows the current windows of the configured account, read every 30 seconds: `lincodex_mail_quota_used_recipients`, `lincodex_mail_quota_limit_recipients`, and `lincodex_mail_quota_provider_exhausted` (1 after a quota refusal by the provider), each with the labels `provider` and `window` (`day` or `month`). `EMAIL_ACCOUNT` is not a label, because the operator chooses its text; with `EMAIL_PROVIDER=disabled` there are no quota series. The alert `LincodexMailQuotaUsedUp` (severity info) fires while a window is used up. - Choices while mail waits: wait for the reset, which needs no action; or, after a deliberate plan change with the provider, raise the limits and restart the backend, so new sends are admitted again while parked deliveries keep their stored `next_attempt_at`; or deliberately switch the transport or account (see [Mail deliveries](#mail-deliveries) for what stays pinned). Do not lower `used_recipients` or edit the journal by hand to free sends: the provider keeps its own count, so the sends would only be refused. - `provider_exhausted_at` on a row means that the provider refused with a quota answer while the local count still had room. Possible reasons: the account also sends from elsewhere; Resend counts received (inbound) mail against the same quota; or the configured limit is above the plan. Align the limits with the plan. -- Resend's monthly quota follows the account's billing cycle, while the gate's month is the UTC calendar month. After a monthly refusal the delivery retries at the next UTC month start; if the billing cycle resets later, that retry is refused again and waits another month. A manual retry with an audit record is planned with the retry policy (TASK-017). +- Resend's monthly quota follows the account's billing cycle, while the gate's month is the UTC calendar month. After a monthly refusal the delivery retries at the next UTC month start; if the billing cycle resets later, that retry is refused again and waits another month. A manual retry with an audit record is planned with the retry policy. - Lowering a limit takes effect on the next reservation. During a rolling deploy, instances with the old and the new limits run side by side and each checks the limit it was started with, so a lowered limit holds only once every instance runs the new configuration. Switching `EMAIL_PROVIDER` to `smtp` starts separate counters for the relay under its own stated limits; deliveries pinned to the old account are refused by the gate rather than sent without a limit. ### Sending service mail @@ -289,7 +289,7 @@ The backend process runs one sending loop for service identity mail (email verif - With `EMAIL_PROVIDER=disabled` the loop does not start and the log says `mail sender worker is not started because EMAIL_PROVIDER is disabled; stored deliveries wait`; `lincodex_mail_sender_running` is 0, nothing is sent, and stored service mail waits for the next start with a transport. The worker never spins: after a pass that could not send it backs off. - Before it sends, the worker checks the token and the account. A delivery that must not go out ends as `cancelled` with a `cancel_reason`, no attempt, and no quota use: `token_missing`, `token_purpose_mismatch`, `token_owner_mismatch`, `token_consumed`, `token_revoked`, `token_expired`, `account_not_current`, `recipient_mismatch`, `content_invalid`, or `processing_failed`. The user-caused reasons are normal: a user asked for a new link, confirmed the address, registered again, or waited too long. To see the reasons: `SELECT cancel_reason, count(*) FROM deliveries WHERE status = 'cancelled' GROUP BY cancel_reason`. A user sees a cancelled mail as "not sent, request a new one". - Provider answers: `accepted` means accepted by the provider, not delivered to a person; the backend has no delivery confirmation. A refusal for now (`temporary`, `rate_limited`) leaves the delivery `pending` with a later `next_attempt_at`, and the retry reuses the same key and body; it repeats until it succeeds, is refused for good, or the token expires and the delivery is cancelled. A permanent or invalid-request refusal ends it as `rejected`: read the provider code in `delivery_attempts.provider_code` (for example `validation_error` for an unverified sender domain, or `invalid_api_key`) and fix the cause. A quota answer parks it in `waiting_quota`; see [Mail quotas](#mail-quotas). -- `unknown` is never retried by the worker. It means that the provider may have accepted the mail (a lost answer, a 5xx answer) or that the worker that sent it was lost for longer than the provider's 24-hour idempotency window. Check the provider's own log for the message; the alert `LincodexMailDeliveryUnknownOutcome` fires meanwhile. A manual retry with an audit record is planned with the retry policy (TASK-017). +- `unknown` is never retried by the worker. It means that the provider may have accepted the mail (a lost answer, a 5xx answer) or that the worker that sent it was lost for longer than the provider's 24-hour idempotency window. Check the provider's own log for the message; the alert `LincodexMailDeliveryUnknownOutcome` fires meanwhile. A manual retry with an audit record is planned with the retry policy. - A claimed delivery holds a lease: `SELECT id, kind, claimed_until FROM deliveries WHERE claim_owner IS NOT NULL`. A row whose `claimed_until` is long past means that its worker died; another instance takes it over by itself. Do not clear leases by hand. - `content_invalid` and `processing_failed` are not user actions: the first means that a stored row does not match its content hash (a manual edit) or holds a message no transport accepts, the second that the worker failed on the row three times in a row (the retries are spaced by the retry schedule). The alert `LincodexMailCancelledBroken` fires on an increase; read the worker logs for the `delivery_id` and inspect the row's metadata. A row that keeps failing does not block the others: it is retried later (`failure_count`, `next_attempt_at`) and then cancelled. - The bodies of a token mail are cleared when it is accepted, rejected, or cancelled (`body_redacted_at` is set), so database dumps and backups of finished token mail hold no token. A mail that is `unknown` keeps its body until an operator resolves it. Do not copy bodies of waiting mail anywhere. diff --git a/docs/en/DEVELOPMENT.md b/docs/en/DEVELOPMENT.md index b8d9d63..edddebf 100644 --- a/docs/en/DEVELOPMENT.md +++ b/docs/en/DEVELOPMENT.md @@ -50,7 +50,7 @@ What exists now: - Health and readiness routes. Nginx answers `GET /healthz` itself and proxies only `/api/` to Go (deploy/nginx/conf.d/app.conf). Go serves `GET /healthz` (`ok`) and `GET /readyz` (`ready` or 503 `not_ready` after checking PostgreSQL, Redis, and SeaweedFS) on its internal port 8080 outside the OpenAPI contract, plus `GET /api/v1/healthz` from api/core/routes/healthz.yml through the ogen handler (backend/internal/adapter/primary/http). The Go metrics listener uses port 9090 (`METRICS_ADDR`) and Prometheus scrapes `/metrics`. ML serves `GET /healthz`, `GET /readyz` (always 503 `not_ready` because no model is connected), and `/metrics` (ml/src/lincodex_ml, api/ml/routes). deploy/scripts/smoke.sh checks Nginx `/healthz`, `/api/v1/healthz`, Go `/readyz` from inside the Compose network, a 404 for an unknown API route, and that the backend started with `EMAIL_PROVIDER=disabled`; it does not start ML or send mail. - Adapters: PostgreSQL through pgxpool with a generated `SELECT 1` query, a goose migration runner applied at startup, a transactor with the transactional outbox writer, sqlc-backed identity repositories for accounts, email tokens, and sessions, and the versioned policy repository with the demo policy seed at startup; Redis through go-cachekit, and SeaweedFS through the S3 API. The Argon2id password hasher and the `identity.Credentials` password check exist and are tested but are not wired into bootstrap. A generated Go client for the ML contract exists but is not wired into bootstrap. -- Mail: the outbound `MailSender` port, the `disabled` and `resend` transports, and the `EMAIL_PROVIDER` selection in bootstrap; `smtp` stops startup after its settings are validated. Notification requests (`mail_requests`) are turned into deliveries (`deliveries`, `delivery_attempts`) by the `notification_delivery` consumer, but nothing sends notifications yet (TASK-462). With `resend` the backend runs a sending worker for service identity mail (verification and password reset, bound to their tokens, checked before the send, with a quota gate and a stable idempotency key); no account flow creates such mail yet. See [DEPLOY.md](DEPLOY.md#mail) and [ARCHITECTURE.md](ARCHITECTURE.md#mail-deliveries). +- Mail: the outbound `MailSender` port, the `disabled` and `resend` transports, and the `EMAIL_PROVIDER` selection in bootstrap; `smtp` stops startup after its settings are validated. Notification requests (`mail_requests`) are turned into deliveries (`deliveries`, `delivery_attempts`) by the `notification_delivery` consumer, but nothing sends notifications yet. With `resend` the backend runs a sending worker for service identity mail (verification and password reset, bound to their tokens, checked before the send, with a quota gate and a stable idempotency key); no account flow creates such mail yet. See [DEPLOY.md](DEPLOY.md#mail) and [ARCHITECTURE.md](ARCHITECTURE.md#mail-deliveries). - OpenAPI contracts api/core/ and api/ml/ with schema merge, bundles, lint, and generation for Go (ogen), TypeScript (Orval), and Python (datamodel-code-generator). The SPA has an interface scaffold with placeholder screens, a generated API client, and MSW handlers. - Compose projects: core (`deploy/docker/docker-compose.yml`: PostgreSQL, Redis, SeaweedFS, Kafka, backend, frontend), ML (`docker-compose.ml.yml`), and monitoring (`docker-compose.monitoring.yml`). - Kafka: one KRaft node in the core Compose project with an internal-only listener, a named volume, a health check, and a memory limit. The backend runs the outbox relay, which creates the `lincodex.domain.events` topic and publishes committed outbox events to it through a franz-go producer; see [Outbox relay](#outbox-relay). Readiness does not check Kafka. The event consumer runtime runs one product handler, the mail delivery consumer, and no product flow emits its event yet; see [Event consumers](#event-consumers). @@ -88,7 +88,7 @@ Security tools have a separate install and work loop: `make -C security install` The planned session cookie is `__Host-lincodex_session` with `Secure`, `HttpOnly`, and `SameSite=Strict` (see [api/README.en.md](../../api/README.en.md#identity-sessions-cookie-and-csrf)). The local stack serves plain HTTP. Chromium and Firefox treat `http://localhost` and `http://127.0.0.1` as secure contexts and keep a `Secure` cookie there; WebKit and Safari may reject it. Use Chromium or Firefox for local sign-in, or put a local TLS proxy in front. The project adds no flag that drops `Secure` or the `__Host-` prefix, so the local cookie never differs from production. -Planned Origin rule (TASK-056): every unsafe request (POST, PUT, PATCH, DELETE), including public ones such as login, must carry an `Origin` from an allowlist in the backend configuration, for example the Nginx origin and the Vite dev origin. The server does not compare `Origin` with `Host`. An unsafe request without `Origin` or with another value answers 403 `csrf_check_failed`. +Planned Origin rule: every unsafe request (POST, PUT, PATCH, DELETE), including public ones such as login, must carry an `Origin` from an allowlist in the backend configuration, for example the Nginx origin and the Vite dev origin. The server does not compare `Origin` with `Host`. An unsafe request without `Origin` or with another value answers 403 `csrf_check_failed`. ## Layout diff --git a/docs/en/TESTING.md b/docs/en/TESTING.md index baf6d29..2a14b7d 100644 --- a/docs/en/TESTING.md +++ b/docs/en/TESTING.md @@ -199,7 +199,7 @@ Unit tests (`make -C backend test`) cover the quota rules without a database: - Startup report: with usage under the label `old-label` and under the configured label, the report through `postgres.MailQuotaStore` logs the configured account's usage and warns with `old-label`. - The database refuses an unknown period kind, a month that does not start on day one, negative usage, a malformed account label, a reservation whose day is outside its month, and an unknown outcome. -`TestPostgresMigrations` also checks that migration 00007 creates and drops `mail_quota_usage` and `mail_quota_reservations` and leaves the delivery tables. The quota suite does not call a transport; the worker that runs `PrepareSend`, `Send`, and `SettleSend` in sequence (TASK-016) is covered by the service mail sending tests below. +`TestPostgresMigrations` also checks that migration 00007 creates and drops `mail_quota_usage` and `mail_quota_reservations` and leaves the delivery tables. The quota suite does not call a transport; the worker that runs `PrepareSend`, `Send`, and `SettleSend` in sequence is covered by the service mail sending tests below. ## Service mail sending tests @@ -264,7 +264,7 @@ Unit tests (`make -C backend test`) cover the job runtime with an in-memory stor ## Product metrics tests -Unit tests (`make -C backend test`) cover the product metrics (TASK-022). In `internal/adapter/primary/http/`, requests through the real router and the real collector are labeled with the route template of their operation (`/api/v1/me/invitations/{invitation_id}`, `/api/v1/me/assessment-attempts/{attempt_id}`) and never with a path parameter, an address in the path, or a query string; unknown paths and methods keep `/api/v1/*`, `/api/*`, or `unmatched`; problem responses are counted by code (`unauthenticated`, `not_found`, `method_not_allowed`, `not_implemented`), a plain 404 outside `/api` is not; and the exposition holds no email-like or UUID-like value; every contract problem code keeps its own label. The request log test sends an address and a UUID in paths and queries through the same router and checks that the JSON log names only route templates, statuses, problem codes, and query parameter counts, skips `/healthz` and `/readyz`, and holds neither value. `internal/adapter/primary/http/middleware/` tests the log and metrics middleware on a plain chi router: the shared route and problem code, no problem for a response that finally succeeded, the error level for 5xx, an unknown method logged as `OTHER`, and a collector without problem counting. In `internal/adapter/secondary/prometheus/`: latency by status class, every delivery kind and status pair exposed at zero and reset when a status empties, quota gauges without an account label, the answer save hook mapping unknown values to `other` and exposing no series before its first call, and a scan of the whole exposition after every hook was called with email and UUID fixtures. `internal/worker/deliverymetrics/` covers the due age of the earliest pending delivery (zero when it is not due yet), the current quota windows, a failed read that does not skip the other, and the loop lifecycle; `internal/bootstrap/` covers the skip without a database, the quota only for an active transport, and an application that runs the sampler against an unreachable database and still stops. `pkg/testutil/` tests the identifier scan itself. +Unit tests (`make -C backend test`) cover the product metrics. In `internal/adapter/primary/http/`, requests through the real router and the real collector are labeled with the route template of their operation (`/api/v1/me/invitations/{invitation_id}`, `/api/v1/me/assessment-attempts/{attempt_id}`) and never with a path parameter, an address in the path, or a query string; unknown paths and methods keep `/api/v1/*`, `/api/*`, or `unmatched`; problem responses are counted by code (`unauthenticated`, `not_found`, `method_not_allowed`, `not_implemented`), a plain 404 outside `/api` is not; and the exposition holds no email-like or UUID-like value; every contract problem code keeps its own label. The request log test sends an address and a UUID in paths and queries through the same router and checks that the JSON log names only route templates, statuses, problem codes, and query parameter counts, skips `/healthz` and `/readyz`, and holds neither value. `internal/adapter/primary/http/middleware/` tests the log and metrics middleware on a plain chi router: the shared route and problem code, no problem for a response that finally succeeded, the error level for 5xx, an unknown method logged as `OTHER`, and a collector without problem counting. In `internal/adapter/secondary/prometheus/`: latency by status class, every delivery kind and status pair exposed at zero and reset when a status empties, quota gauges without an account label, the answer save hook mapping unknown values to `other` and exposing no series before its first call, and a scan of the whole exposition after every hook was called with email and UUID fixtures. `internal/worker/deliverymetrics/` covers the due age of the earliest pending delivery (zero when it is not due yet), the current quota windows, a failed read that does not skip the other, and the loop lifecycle; `internal/bootstrap/` covers the skip without a database, the quota only for an active transport, and an application that runs the sampler against an unreachable database and still stops. `pkg/testutil/` tests the identifier scan itself. `TestDeliveryStatistics` in `backend/integration_test/delivery_statistics_test.go` checks the sqlc query `GetDeliveryStatistics` on PostgreSQL: an empty table, then deliveries of three kinds in all five statuses, set within the table constraints, give exact counts per kind and status, and the earliest due time comes only from deliveries that are still pending. diff --git a/docs/ru/ARCHITECTURE.md b/docs/ru/ARCHITECTURE.md index a5f0503..7e0fc65 100644 --- a/docs/ru/ARCHITECTURE.md +++ b/docs/ru/ARCHITECTURE.md @@ -54,7 +54,7 @@ SeaweedFS работает отдельным сервером в основно ### HTTP-периметр и адрес клиента -Реализовано (TASK-042). Frontend Nginx - единственная публичная HTTP-точка входа. Он отдает SPA, проксирует `/api/v1/` в Go и ограниченный `/telemetry`; любой другой путь, включая `/metrics`, `/readyz` и административные пути других сервисов, отклоняется с 404. Там же заданы заголовки безопасности, строгий CSP только для того же origin, лимит тела по умолчанию 1 МБ с ответом 413 в формате problem из контракта и грубые `limit_req`/`limit_conn` на клиента (429 с `Retry-After`); значения намного выше обычного использования и не заменяют доменные квоты, которые остаются в backend. Подробности и проверки - в [DEPLOY.md](DEPLOY.md#публичный-периметр-и-адрес-клиента). +Реализовано. Frontend Nginx - единственная публичная HTTP-точка входа. Он отдает SPA, проксирует `/api/v1/` в Go и ограниченный `/telemetry`; любой другой путь, включая `/metrics`, `/readyz` и административные пути других сервисов, отклоняется с 404. Там же заданы заголовки безопасности, строгий CSP только для того же origin, лимит тела по умолчанию 1 МБ с ответом 413 в формате problem из контракта и грубые `limit_req`/`limit_conn` на клиента (429 с `Retry-After`); значения намного выше обычного использования и не заменяют доменные квоты, которые остаются в backend. Подробности и проверки - в [DEPLOY.md](DEPLOY.md#публичный-периметр-и-адрес-клиента). Адрес клиента определяется только через доверенные прокси. Edge заменяет `X-Forwarded-For`; app Nginx доверяет адресу туннеля edge и передает backend одну найденную запись; `middleware.ClientIP` (`backend/internal/adapter/primary/http/middleware/clientip.go`) доверяет `X-Forwarded-For` только от `TRUSTED_PROXY_CIDRS` (по умолчанию только закрепленный адрес frontend контейнера) и читает его справа, поэтому запись, которую клиент поставил слева от первого недоверенного узла, не учитывается. Сценарии и обработчики, которым нужен адрес для лимитера, читают его через `middleware.ClientAddr(ctx)` и строят ключ лимитера через `middleware.LimiterKey` (IPv6 сводится к /64). Адрес не логируется и не хранится дольше окна лимитера; в журнале запросов и метриках для него нет поля. Первый потребитель - лимиты регистрации и повторной отправки (см. раздел о регистрации); роутер подключает `ClientIP`. @@ -64,7 +64,7 @@ SeaweedFS работает отдельным сервером в основно - Ключ имеет вид `/<32 hex-символа>` из 128 случайных бит. Из кода приходит только проверенный namespace политики; имена файлов и другой ввод клиента никогда не попадают в ключ. `Open` и `Delete` принимают только ключи namespace и формата своей политики, поэтому ключ, сформированный клиентом, путь с обходом каталогов или ключ другого сценария отклоняется до обращения к хранилищу. - Запись требует точный размер. Заявленный размер больше лимита политики отклоняется до запроса. Поток проходит через ограничитель на основе `io.LimitReader`, который придерживает последний фрагмент, пока источник не закончился, поэтому более длинный или более короткий источник прерывает запрос раньше, чем хранилище получит полное тело. Любая ошибка после начала записи удаляет ключ, в том числе после отмены контекста вызывающим. Источники неизвестной длины не буферизуются; сценарию, которому они нужны, придется сохранять их в ограниченный временный файл или добавить multipart upload. Источнику нужен собственный дедлайн, например `http.ResponseController.SetReadDeadline` для тела запроса: `Put` ждет заблокированное чтение, и отмена контекста его не прерывает. -- `Put` возвращает `Record`: ключ, media type без параметров, размер, SHA-256, посчитанный во время потока, и очищенное исходное имя файла. Слой не ведет индекс и не добавляет таблиц. Вызывающий соблюдает один порядок: `Put`, затем сохранение записи вместе с данными о владельце в транзакции БД, затем `Delete` ключа, если транзакция не удалась. Остается одна гонка: если тело целиком ушло до отмены вызывающим, сервер может зафиксировать объект уже после завершения очищающего `Delete`. У таких сирот нет записи, и ни один запрос до них не доходит; sweeper по namespace, который удаляет ключи без записи, запланирован вместе с резервным копированием и выгрузками (TASK-030, TASK-458) и пока не существует. Исходное имя - только метаданные для отображения: оно не сохраняется в SeaweedFS и не используется в ключах и логах, но может содержать персональные данные. Очистка удаляет элементы пути, управляющие символы, символы форматирования, разделители строк и абзацев и символы частного использования и не нормализует Unicode. Content type заявляет вызывающий; определение типа по содержимому относится к разбору документов. +- `Put` возвращает `Record`: ключ, media type без параметров, размер, SHA-256, посчитанный во время потока, и очищенное исходное имя файла. Слой не ведет индекс и не добавляет таблиц. Вызывающий соблюдает один порядок: `Put`, затем сохранение записи вместе с данными о владельце в транзакции БД, затем `Delete` ключа, если транзакция не удалась. Остается одна гонка: если тело целиком ушло до отмены вызывающим, сервер может зафиксировать объект уже после завершения очищающего `Delete`. У таких сирот нет записи, и ни один запрос до них не доходит; sweeper по namespace, который удаляет ключи без записи, запланирован вместе с резервным копированием и выгрузками и пока не существует. Исходное имя - только метаданные для отображения: оно не сохраняется в SeaweedFS и не используется в ключах и логах, но может содержать персональные данные. Очистка удаляет элементы пути, управляющие символы, символы форматирования, разделители строк и абзацев и символы частного использования и не нормализует Unicode. Content type заявляет вызывающий; определение типа по содержимому относится к разбору документов. - `Open` проверяет, что сохраненный объект по-прежнему соответствует политике, и закрывает ответ при каждом отказе. Возвращенный `File` закрывает вызывающий; чтение завершается ошибкой, если тело отличается от сохраненного размера. `SEAWEEDFS_TIMEOUT` адаптера ограничивает установку соединения, TLS handshake и ожидание заголовков ответа, но не передачу тела в `Put` и `Get`, поэтому длинный или медленный поток ограничивает только контекст вызывающего. `Delete` идемпотентен, отсутствие объекта отображается в `files.ErrNotFound`. - Публичных URL нет. Слой не создает публичных, постоянных или presigned URL, у bucket нет публичной политики и анонимного ACL. Скачивание в браузере должно идти через аутентифицированный endpoint backend, который проверяет текущие права и передает `File` потоком с `Content-Disposition: attachment` и `X-Content-Type-Options: nosniff`, чтобы сохраненный файл никогда не отображался как страница origin приложения. Ключ, bucket и URL хранилища не попадают к клиентам. @@ -99,7 +99,7 @@ Relay, который публикует эти строки, описан в р ### Relay outbox -Реализовано (TASK-009): цикл relay в `backend/internal/worker/outboxrelay/`, порты `outbound.OutboxRelayStore` и `outbound.EventPublisher` (`backend/internal/port/outbound/outbox_relay.go`), хранилище PostgreSQL (`adapter/secondary/postgres/outbox_relay.go`) и producer на franz-go (`adapter/secondary/kafka/`). Bootstrap запускает relay вместе с HTTP-серверами в том же процессе и останавливает его при завершении. У relay свой пул PostgreSQL не больше чем на два соединения: одно для транзакции захвата и одно для чтения размера очереди, поэтому он не забирает соединения у обработки запросов. Relay не запускается при `RELAY_ENABLED=false` или без `DATABASE_URL`; тогда события остаются в outbox. Настройки перечислены в [DEPLOY.md](DEPLOY.md#relay-outbox). +Реализовано: цикл relay в `backend/internal/worker/outboxrelay/`, порты `outbound.OutboxRelayStore` и `outbound.EventPublisher` (`backend/internal/port/outbound/outbox_relay.go`), хранилище PostgreSQL (`adapter/secondary/postgres/outbox_relay.go`) и producer на franz-go (`adapter/secondary/kafka/`). Bootstrap запускает relay вместе с HTTP-серверами в том же процессе и останавливает его при завершении. У relay свой пул PostgreSQL не больше чем на два соединения: одно для транзакции захвата и одно для чтения размера очереди, поэтому он не забирает соединения у обработки запросов. Relay не запускается при `RELAY_ENABLED=false` или без `DATABASE_URL`; тогда события остаются в outbox. Настройки перечислены в [DEPLOY.md](DEPLOY.md#relay-outbox). Один проход - одна транзакция READ COMMITTED: @@ -134,7 +134,7 @@ Producer требует подтверждения от всех in-sync реп ### Обработчики событий -Реализовано (TASK-010): runtime обработчиков в `backend/internal/worker/eventconsumer/`, порт обработчика `inbound.EventHandler` (`backend/internal/port/inbound/event_handler.go`), порты `outbound.EventSource` и `outbound.EventConsumerStore` (`backend/internal/port/outbound/event_consumer.go`), участник consumer group на franz-go (`adapter/secondary/kafka/consumer.go`), хранилище PostgreSQL (`adapter/secondary/postgres/event_consumer.go`) и миграция `00005_create_event_consumer_tables.sql` с таблицами `consumer_processed_events` и `consumer_dead_letters`. Зарегистрирован один продуктовый обработчик (TASK-015): `eventHandlers()` в `backend/internal/bootstrap/consumers.go` возвращает обработчик доставки писем `notification_delivery`, описанный в разделе [Доставки писем](#доставки-писем), поэтому backend с `CONSUMER_ENABLED` и `DATABASE_URL` запускает один обработчик в группе `.notification_delivery`. Интеграционные тесты runtime используют тестовый обработчик, который пишет в таблицу, созданную самим тестом. Продуктовый модуль добавляет свой обработчик в этот список. Настройки перечислены в [DEPLOY.md](DEPLOY.md#обработчики-событий). +Реализовано: runtime обработчиков в `backend/internal/worker/eventconsumer/`, порт обработчика `inbound.EventHandler` (`backend/internal/port/inbound/event_handler.go`), порты `outbound.EventSource` и `outbound.EventConsumerStore` (`backend/internal/port/outbound/event_consumer.go`), участник consumer group на franz-go (`adapter/secondary/kafka/consumer.go`), хранилище PostgreSQL (`adapter/secondary/postgres/event_consumer.go`) и миграция `00005_create_event_consumer_tables.sql` с таблицами `consumer_processed_events` и `consumer_dead_letters`. Зарегистрирован один продуктовый обработчик: `eventHandlers()` в `backend/internal/bootstrap/consumers.go` возвращает обработчик доставки писем `notification_delivery`, описанный в разделе [Доставки писем](#доставки-писем), поэтому backend с `CONSUMER_ENABLED` и `DATABASE_URL` запускает один обработчик в группе `.notification_delivery`. Интеграционные тесты runtime используют тестовый обработчик, который пишет в таблицу, созданную самим тестом. Продуктовый модуль добавляет свой обработчик в этот список. Настройки перечислены в [DEPLOY.md](DEPLOY.md#обработчики-событий). Обработчик реализует три метода: @@ -174,7 +174,7 @@ Offsets и партиции. Каждый обработчик - один уча ### Задания по сроку -Реализовано (TASK-035): устойчивые задания, которые выполняются один раз, когда наступает их срок, например срок ответа. Runtime находится в `backend/internal/worker/jobrunner/`, порт обработчика `inbound.JobHandler` - в `backend/internal/port/inbound/job_handler.go`, порты `outbound.JobScheduler` и `outbound.JobStore` - в `backend/internal/port/outbound/scheduled_job.go`, проверенный `domain.ScheduledJob` - в `backend/internal/domain/scheduled_job.go`, хранилище и планировщик PostgreSQL - в `adapter/secondary/postgres/scheduled_job.go`, миграция `00008_create_scheduled_jobs.sql` создает таблицу `scheduled_jobs`. Продуктовый обработчик пока не зарегистрирован: `jobHandlers()` в `backend/internal/bootstrap/jobs.go` возвращает пустой список, поэтому backend пишет в журнал `no scheduled job kind is registered` и не запускает worker. Тесты используют вид задания, который есть только в тестах. Первый запланированный продуктовый вид - срок ответа на приглашение (TASK-205). Настройки описаны в [DEPLOY.md](DEPLOY.md#задания-по-сроку). +Реализовано: устойчивые задания, которые выполняются один раз, когда наступает их срок, например срок ответа. Runtime находится в `backend/internal/worker/jobrunner/`, порт обработчика `inbound.JobHandler` - в `backend/internal/port/inbound/job_handler.go`, порты `outbound.JobScheduler` и `outbound.JobStore` - в `backend/internal/port/outbound/scheduled_job.go`, проверенный `domain.ScheduledJob` - в `backend/internal/domain/scheduled_job.go`, хранилище и планировщик PostgreSQL - в `adapter/secondary/postgres/scheduled_job.go`, миграция `00008_create_scheduled_jobs.sql` создает таблицу `scheduled_jobs`. Продуктовый обработчик пока не зарегистрирован: `jobHandlers()` в `backend/internal/bootstrap/jobs.go` возвращает пустой список, поэтому backend пишет в журнал `no scheduled job kind is registered` и не запускает worker. Тесты используют вид задания, который есть только в тестах. Первый запланированный продуктовый вид - срок ответа на приглашение. Настройки описаны в [DEPLOY.md](DEPLOY.md#задания-по-сроку). Планирование. Usecase вызывает `unit.ScheduledJobs().Schedule(ctx, job)` в своей бизнес-транзакции, поэтому задание существует ровно тогда, когда зафиксировано изменение, которому оно нужно; `Cancel(ctx, kind, key)` останавливает незавершенное задание. У задания есть вид (имя обработчика, строчное имя с точками), ключ логического задания внутри вида (например, ID агрегата), срок по часам приложения, необязательный лимит попыток и payload: плоский JSON-объект из идентификаторов не больше 2 КиБ. Ни ключ, ни payload не должны содержать персональные данные; остальное обработчик читает из исходных таблиц в момент выполнения. Пара `(kind, key)` уникальна, и побеждает первое планирование: повтор ничего не вставляет (`INSERT ... ON CONFLICT DO NOTHING`) и возвращает `false`, в том числе после выполнения или отмены задания. Это намеренно insert-or-ignore, а не upsert: повторная команда не может сдвинуть срок, который нельзя сбрасывать, а устаревший писатель не может оживить завершенное задание. Для нового повторения нужен новый ключ, например `:`. @@ -196,7 +196,7 @@ Offsets и партиции. Каждый обработчик - один уча ### Почтовый транспорт -Реализовано: outbound порт `MailSender` (`backend/internal/port/outbound/mail.go`), транспорт `disabled` (`adapter/secondary/mail/disabled/`), транспорт Resend (`adapter/secondary/mail/resend/`, основной провайдер рабочего стенда) и выбор транспорта в bootstrap. Usecase, шаблоны и доменные события зависят только от порта; `EMAIL_PROVIDER` выбирает ровно один транспорт (`resend`, `smtp` или `disabled`), и bootstrap связывает с ним порт до запуска миграций. Переключения между транспортами нет: непригодный выбор останавливает запуск. Запланировано: транспорт SMTP relay (`mail/smtp/`, TASK-014, вне MVP); пока его нет, `smtp` после проверки своих настроек останавливает запуск. Единственный вызывающий - worker отправки служебной почты identity (TASK-016, см. [Отправка служебной почты](#отправка-служебной-почты)); продуктовые уведомления сохраняются как доставки, но не отправляются до TASK-462. Настройки описаны в [DEPLOY.md](DEPLOY.md#почта). +Реализовано: outbound порт `MailSender` (`backend/internal/port/outbound/mail.go`), транспорт `disabled` (`adapter/secondary/mail/disabled/`), транспорт Resend (`adapter/secondary/mail/resend/`, основной провайдер рабочего стенда) и выбор транспорта в bootstrap. Usecase, шаблоны и доменные события зависят только от порта; `EMAIL_PROVIDER` выбирает ровно один транспорт (`resend`, `smtp` или `disabled`), и bootstrap связывает с ним порт до запуска миграций. Переключения между транспортами нет: непригодный выбор останавливает запуск. Запланировано: транспорт SMTP relay (`mail/smtp/`, вне MVP); пока его нет, `smtp` после проверки своих настроек останавливает запуск. Единственный вызывающий - worker отправки служебной почты identity (см. [Отправка служебной почты](#отправка-служебной-почты)); продуктовые уведомления сохраняются как доставки, но не отправляются до реализации отправки продуктовых уведомлений. Настройки описаны в [DEPLOY.md](DEPLOY.md#почта). `Send(ctx, OutgoingMail)` делает ровно одну попытку. `OutgoingMail` содержит получателя, тему, текстовое и HTML тело и ключ идемпотентности, который не меняется для одной логической доставки между повторами (от 1 до 256 печатных ASCII символов, предел Resend, без персональных данных); отправитель берется из `EMAIL_FROM`. При nil ошибке результат один из: @@ -206,7 +206,7 @@ Offsets и партиции. Каждый обработчик - один уча `rejected` и `unknown` могут содержать `RetryAfter`, подсказку провайдера о паузе или паузу, которую транспорт вычислил по документированным правилам провайдера, и `ProviderCode`, имя ошибки провайдера. Отказ `quota_exhausted` еще и называет исчерпанное окно в `QuotaPeriod` (`day` или `month`), если провайдер это сообщил; иначе поле пустое. Транспорт берет `ProviderCode` только из своего фиксированного списка документированных имен, а иначе оставляет пустым; поэтому в нем не бывает текста провайдера, и его можно логировать и хранить. -Ненулевая ошибка значит, что письмо точно не покинуло процесс: `ErrMailChannelUnavailable` в режиме `disabled`, `ErrInvalidOutgoingMail` для некорректного письма или ошибка контекста, если контекст вызывающего завершился до записи запроса. Сбой до записи запроса при живом контексте - это `rejected`/`temporary`, а не ошибка. Повторы, backoff и учет результатов относятся к единому запланированному слою доставки, а не к транспорту. Сценарии подтверждения (TASK-053, TASK-054) обязаны считать `ErrMailChannelUnavailable` неотправкой: он никогда не подтверждает адрес и не заменяет проверку аккаунта. `OutgoingMail` скрывает себя в выводе `fmt` и `slog`, а ошибки и логи транспорта никогда не содержат получателей, темы, тела писем, учетные данные или сырые ответы провайдера. +Ненулевая ошибка значит, что письмо точно не покинуло процесс: `ErrMailChannelUnavailable` в режиме `disabled`, `ErrInvalidOutgoingMail` для некорректного письма или ошибка контекста, если контекст вызывающего завершился до записи запроса. Сбой до записи запроса при живом контексте - это `rejected`/`temporary`, а не ошибка. Повторы, backoff и учет результатов относятся к единому запланированному слою доставки, а не к транспорту. Сценарии подтверждения обязаны считать `ErrMailChannelUnavailable` неотправкой: он никогда не подтверждает адрес и не заменяет проверку аккаунта. `OutgoingMail` скрывает себя в выводе `fmt` и `slog`, а ошибки и логи транспорта никогда не содержат получателей, темы, тела писем, учетные данные или сырые ответы провайдера. Транспорт Resend использует `net/http` без SDK. Один `Send` - это один `POST https://api.resend.com/emails` с полями `from` (`EMAIL_FROM`), `to` (один получатель), `subject`, `text` и `html` (пустая или пробельная часть не передается), ключом в `Authorization: Bearer`, заголовком `User-Agent` и `Idempotency-Key`, равным ключу письма. Resend хранит ключ 24 часа и на тот же ключ с тем же телом возвращает исходный результат без повторной отправки, поэтому повтор обязан передать сохраненное тело под тем же ключом; измененное тело под старым ключом - это конфликт, а не повод создать новый ключ. `EMAIL_TIMEOUT` ограничивает всю попытку. Клиент не следует редиректам, использует HTTP/1.1 и открывает новое соединение для каждой отправки: keep-alive соединение, которое сервер закрыл по простою, сломалось бы уже после передачи запроса и превратило бы письмо, которого Resend не видел, в ложный `unknown`. У запроса также нет `GetBody`, потому что `net/http` считает POST с `Idempotency-Key` повторяемым после обрыва переиспользованного соединения. В адаптере нет цикла повторов, и он ничего не логирует. Ответ читается не больше 64 KiB; разбираются только идентификатор письма и `name` ошибки, а сообщение провайдера и тело ответа не сохраняются. @@ -230,11 +230,11 @@ Offsets и партиции. Каждый обработчик - один уча | Сбой до записи запроса: DNS, соединение, TLS или таймаут попытки | `rejected`, `temporary`: полный запрос до Resend не дошел | | Контекст вызывающего завершился до записи запроса | ошибка контекста; ничего не отправлено | -Каждый ответ `rejected` или `unknown` с известным именем ошибки заполняет `ProviderCode` этим именем, например `invalid_idempotent_request`, `invalid_api_key` или `daily_quota_exceeded`. Известны имена со страницы ошибок Resend и старые имена, которые все еще перечисляет официальный Node SDK (`invalid_api_key`, `invalid_from_address`, `invalid_access`, `invalid_region`, `security_error`, `internal_server_error`); любое другое имя считается отсутствующим. `RetryAfter` ограничен 24 часами. Темп при rate limit и предел числа попыток относятся к политике повторов (TASK-017), worker отправки применяет только минимальное расписание из раздела [Отправка служебной почты](#отправка-служебной-почты), а остановка по окончании 24-часового окна ключа - его правило для попытки, чей worker потерян; ожидание сброса квоты решает шлюз квот из раздела [Квоты почты](#квоты-почты). +Каждый ответ `rejected` или `unknown` с известным именем ошибки заполняет `ProviderCode` этим именем, например `invalid_idempotent_request`, `invalid_api_key` или `daily_quota_exceeded`. Известны имена со страницы ошибок Resend и старые имена, которые все еще перечисляет официальный Node SDK (`invalid_api_key`, `invalid_from_address`, `invalid_access`, `invalid_region`, `security_error`, `internal_server_error`); любое другое имя считается отсутствующим. `RetryAfter` ограничен 24 часами. Темп при rate limit и предел числа попыток относятся к политике повторов, worker отправки применяет только минимальное расписание из раздела [Отправка служебной почты](#отправка-служебной-почты), а остановка по окончании 24-часового окна ключа - его правило для попытки, чей worker потерян; ожидание сброса квоты решает шлюз квот из раздела [Квоты почты](#квоты-почты). ### Доставки писем -Реализовано (TASK-015): агрегат `domain.Delivery`, `domain.MailContent` и `domain.MailRequest` (`backend/internal/domain/delivery.go`, `mail_content.go`, `mail_request.go`), порты `outbound.DeliveryRepository` и `outbound.MailRequestRepository` (`port/outbound/delivery.go`) через `UnitOfWork.Deliveries()`, `UnitOfWork.MailRequests()` и `postgres.DeliveryStore`, миграция `00006_create_deliveries.sql` с таблицами `mail_requests`, `deliveries` и `delivery_attempts`, запросы в `backend/db/queries/delivery.sql`, а в `backend/internal/usecase/notification/` usecase запроса `MailRequester` и обработчик `DeliveryHandler`. Шлюз квот, который допускает или откладывает отправку, реализован в TASK-018; см. [Квоты почты](#квоты-почты). Реализовано (TASK-016): worker, который берет к отправке служебные письма, проверяет их токен и аккаунт, пропускает через шлюз квот и вызывает `MailSender`, вместе с миграцией `00012_add_delivery_sending.sql`; см. [Отправка служебной почты](#отправка-служебной-почты). Запланировано: повторы и политика неизвестного исхода (TASK-017) и отправка продуктовых уведомлений с проверкой разрешений перед отправкой (TASK-462). Gauges состояний доставки реализованы в TASK-022; см. [Метрики, телеметрия и alerts](#метрики-телеметрия-и-alerts). Ни один продуктовый сценарий пока не вызывает `MailRequester`, и ни один сценарий identity пока не вызывает `ServiceMailer` (регистрация и сброс пароля - отдельные задачи), поэтому сохраненное уведомление ждет, а служебных писем вне тестов нет. +Реализовано: агрегат `domain.Delivery`, `domain.MailContent` и `domain.MailRequest` (`backend/internal/domain/delivery.go`, `mail_content.go`, `mail_request.go`), порты `outbound.DeliveryRepository` и `outbound.MailRequestRepository` (`port/outbound/delivery.go`) через `UnitOfWork.Deliveries()`, `UnitOfWork.MailRequests()` и `postgres.DeliveryStore`, миграция `00006_create_deliveries.sql` с таблицами `mail_requests`, `deliveries` и `delivery_attempts`, запросы в `backend/db/queries/delivery.sql`, а в `backend/internal/usecase/notification/` usecase запроса `MailRequester` и обработчик `DeliveryHandler`. Шлюз квот, который допускает или откладывает отправку, реализован; см. [Квоты почты](#квоты-почты). Реализовано: worker, который берет к отправке служебные письма, проверяет их токен и аккаунт, пропускает через шлюз квот и вызывает `MailSender`, вместе с миграцией `00012_add_delivery_sending.sql`; см. [Отправка служебной почты](#отправка-служебной-почты). Запланировано: повторы и политика неизвестного исхода и отправка продуктовых уведомлений с проверкой разрешений перед отправкой. Gauges состояний доставки реализованы; см. [Метрики, телеметрия и alerts](#метрики-телеметрия-и-alerts). Ни один продуктовый сценарий пока не вызывает `MailRequester`, и ни один сценарий identity пока не вызывает `ServiceMailer` (регистрация и сброс пароля - отдельные задачи), поэтому сохраненное уведомление ждет, а служебных писем вне тестов нет. Доставка - устойчивое состояние отправки одного письма одному получателю. Строка `deliveries` содержит: @@ -254,7 +254,7 @@ Offsets и партиции. Каждый обработчик - один уча Почему событие несет только ссылку. События хранятся в `outbox_events` и в Kafka в пределах retention топика, а правило доменных событий разрешает только идентификаторы и минимальные факты. FR19 также требует, чтобы очередь не сохраняла доступ к отозванным данным. Поэтому текст лежит в `mail_requests`, которые удаление аккаунта убирает каскадно, и только пока он нужен: обработчик удаляет строку в той же транзакции, где сохраняет сформированную доставку. После этого текст есть только в доставке, с ее правилами хранения и доступа. Адрес обработчик читает из аккаунта в своей транзакции, поэтому это адрес, актуальный на момент создания. -Письма с токеном. Тела писем подтверждения почты и сброса пароля содержат одноразовый bearer-токен, который никогда не должен попадать в событие или строку запроса, а хранилище держит только его SHA-256. Поэтому `mail_requests` и версия схемы 1 допускают только вид `notification`. Доставки писем с токеном создают сценарии identity прямо в транзакции, которая выпускает токен, через `ServiceMailer` (TASK-016): он использует `domain.NewDelivery` и `DeliveryRepository.Create` и привязывает доставку к токену; сами сценарии identity, которые его вызывают (регистрация, повторная отправка, сброс), - отдельные задачи. +Письма с токеном. Тела писем подтверждения почты и сброса пароля содержат одноразовый bearer-токен, который никогда не должен попадать в событие или строку запроса, а хранилище держит только его SHA-256. Поэтому `mail_requests` и версия схемы 1 допускают только вид `notification`. Доставки писем с токеном создают сценарии identity прямо в транзакции, которая выпускает токен, через `ServiceMailer`: он использует `domain.NewDelivery` и `DeliveryRepository.Create` и привязывает доставку к токену; сами сценарии identity, которые его вызывают (регистрация, повторная отправка, сброс), - отдельные задачи. Неизменяемое содержимое. Доставка хранит отрендеренное тело и никогда не рендерит его заново. Для рендеринга во время отправки нужен исходный токен, который существует только в памяти в момент выпуска, а повтор под тем же ключом идемпотентности должен повторить ровно то же тело: Resend считает измененное тело под старым ключом конфликтом. Domain пересчитывает hash содержимого при каждом чтении и при несовпадении возвращает `domain.ErrMailContentIntegrity`. Trigger `deliveries_refuse_content_change` отклоняет UPDATE, меняющий получателя, содержимое, ключ идемпотентности, исходное событие или время создания (SQLSTATE 23000, ограничение `deliveries_content_immutable`, адаптер переводит его в `outbound.ErrDeliveryContentImmutable`). Поэтому новая версия шаблона применяется только к новым доставкам, а для отправки сохраненной доставки старые файлы шаблона не нужны. @@ -263,7 +263,7 @@ Offsets и партиции. Каждый обработчик - один уча - Запросы для эксплуатации выбирают столбцы метаданных (ID, вид, статус, попытки, время, провайдер) и никогда не выбирают тела, текст запроса и адрес; см. [DEPLOY.md](DEPLOY.md#доставки-писем). - Удаление аккаунта каскадно удаляет его запросы писем, доставки и их попытки. Очистка неподтвержденных аккаунтов блокирует их через `FOR UPDATE SKIP LOCKED`, как токены и сессии, поэтому никогда не ждет обработчик доставки или worker, который держит строку. - Тела письма с токеном очищаются, когда доставка достигает `accepted`, `rejected` или `cancelled` (`body_redacted_at`, см. [Отправка служебной почты](#отправка-служебной-почты)), поэтому дамп или резервная копия базы не содержат токена завершенного письма; правило хранения, которое удаляет остальные завершенные доставки через ограниченный срок, еще не реализовано, и пока его нет, эти строки остаются. Шифрование тел в хранилище тоже не реализовано. -- `Delivery`, `MailContent`, `MailRequest`, `NotificationText` и `EmailAddress` скрывают себя в выводе `fmt` и `slog`: доставка попадает в лог только как ID, вид, статус и провайдер. Ошибки обработчика называют нарушенное правило и никогда не цитируют payload, а адаптер заменяет текст ошибки PostgreSQL на SQLSTATE и имя ограничения. Метрики доставки (TASK-022) несут только labels вида, статуса, провайдера и окна квоты, без адреса, ID пользователя или доставки, метки аккаунта провайдера и темы. +- `Delivery`, `MailContent`, `MailRequest`, `NotificationText` и `EmailAddress` скрывают себя в выводе `fmt` и `slog`: доставка попадает в лог только как ID, вид, статус и провайдер. Ошибки обработчика называют нарушенное правило и никогда не цитируют payload, а адаптер заменяет текст ошибки PostgreSQL на SQLSTATE и имя ограничения. Метрики доставки несут только labels вида, статуса, провайдера и окна квоты, без адреса, ID пользователя или доставки, метки аккаунта провайдера и темы. Статусы. Значения следуют исходам `MailSender`: @@ -279,25 +279,25 @@ Offsets и партиции. Каждый обработчик - один уча Переходы: - `Delivery.RecordAttempt` принимает результат одной попытки транспорта и добавляет строку попытки. `pending`, `waiting_quota` и `unknown` принимают попытку: `accepted` дает `accepted`, отказ `permanent` или `invalid_request` дает `rejected`, `temporary` или `rate_limited` - `pending`, `quota_exhausted` - `waiting_quota`, а `unknown` - `unknown`. `accepted`, `rejected` и `cancelled` отклоняют любую следующую попытку с `domain.ErrDeliveryTransition`. -- `Delivery.WaitForQuota(at, until)` переводит доставку из `pending` или `waiting_quota` в `waiting_quota` без попытки - для случая, когда локальная квота TASK-018 откладывает отправку до вызова транспорта; нулевой `until` значит, что момент сброса неизвестен. Переход отклоняет `unknown`, чья прошлая попытка могла быть принята и чей повтор решает политика повторов, и конечные статусы. Сохраняет его `DeliveryRepository.WaitForQuota`. +- `Delivery.WaitForQuota(at, until)` переводит доставку из `pending` или `waiting_quota` в `waiting_quota` без попытки - для случая, когда локальная почтовая квота откладывает отправку до вызова транспорта; нулевой `until` значит, что момент сброса неизвестен. Переход отклоняет `unknown`, чья прошлая попытка могла быть принята и чей повтор решает политика повторов, и конечные статусы. Сохраняет его `DeliveryRepository.WaitForQuota`. - `Delivery.Cancel(at, reason)` завершает доставку из `pending` или `waiting_quota` в `cancelled` без попытки; причина - одна из `token_missing`, `token_purpose_mismatch`, `token_owner_mismatch`, `token_consumed`, `token_revoked`, `token_expired`, `account_not_current`, `recipient_mismatch`, `content_invalid` или `processing_failed`. Переход отклоняет `unknown`, как `WaitForQuota`: прошлая попытка могла быть принята, поэтому письмо никогда не объявляется неотправленным. Сохраняет его `DeliveryRepository.Cancel`. - `Delivery.Rebind(at, account)` переносит доставку без единой попытки на другой аккаунт провайдера; см. ниже. Сохраняет его `DeliveryRepository.Rebind`. -Каждое изменение увеличивает `version`, и хранилище применяет его только поверх предыдущей версии. Время следующей попытки задает политика повторов вызывающего кода (TASK-017), и оно должно соответствовать целевому статусу; CHECK `deliveries_next_attempt_matches_status` повторяет это правило, а `deliveries_provider_message_id_when_accepted` требует ID провайдера ровно для `accepted`. +Каждое изменение увеличивает `version`, и хранилище применяет его только поверх предыдущей версии. Время следующей попытки задает политика повторов вызывающего кода, и оно должно соответствовать целевому статусу; CHECK `deliveries_next_attempt_matches_status` повторяет это правило, а `deliveries_provider_message_id_when_accepted` требует ID провайдера ровно для `accepted`. Попытки. Текущее состояние лежит в счетчиках `deliveries`, поэтому worker читает одну строку, а каждая попытка - отдельная строка `delivery_attempts`: номер, время, исход, причина отказа, код провайдера, ID письма у провайдера, подсказка ожидания, итоговый статус и время следующей попытки. История нужна оператору, чтобы оценить неизвестный исход, от нее (от первой попытки) отсчитывается конец 24-часового окна ключа, и на нее ссылается аудит ручного решения. Подсказка ожидания хранится точно как Go `time.Duration` в наносекундах (`retry_after_ns`), поэтому чтение после записи ее не меняет. `RecordAttempt` сохраняет доставку и попытку одним запросом: data-modifying CTE обновляет доставку, только пока ее версия равна версии до попытки, и добавляет попытку, только если обновление прошло. Второй писатель той же попытки получает `outbound.ErrDeliveryVersionConflict` и ничего не записывает. Trigger отклоняет UPDATE попытки. Учет квот не строится на этой истории: каскад от удаления аккаунта удаляет его доставки и попытки, поэтому подсчет отправок по `delivery_attempts` потерял бы отправки удаленных аккаунтов и позволил бы превысить квоту провайдера. Поэтому у квоты собственный счетчик без каскада с ключом из провайдера, аккаунта провайдера и UTC-суток или месяца; см. [Квоты почты](#квоты-почты). -Аккаунт провайдера. Каждая доставка закреплена за транспортом и аккаунтом, которые были настроены при ее создании. У провайдеров и аккаунтов нет общих ключей идемпотентности, поэтому FR19 запрещает переносить неопределенную доставку на другой; изменение конфигурации применяется только к новым доставкам, а worker отправки обязан использовать закрепленный аккаунт. `EMAIL_ACCOUNT` называет аккаунт (`default`, если не задан); меняйте его каждый раз, когда `RESEND_API_KEY` переходит к другому аккаунту Resend. Аккаунт можно сменить, только пока у доставки нет попыток, потому что до первой попытки ключ не видел ни один провайдер: `Delivery.Rebind` отклоняет доставку с попыткой или в конечном статусе, а trigger отклоняет смену провайдера после попытки (ограничение `deliveries_provider_pinned`, адаптер переводит его в `outbound.ErrDeliveryProviderPinned`). TASK-016 использует это для доставок, созданных при `EMAIL_PROVIDER=disabled`, когда стенд включит транспорт; переносить их автоматически или по запросу оператора, решает эта задача. +Аккаунт провайдера. Каждая доставка закреплена за транспортом и аккаунтом, которые были настроены при ее создании. У провайдеров и аккаунтов нет общих ключей идемпотентности, поэтому FR19 запрещает переносить неопределенную доставку на другой; изменение конфигурации применяется только к новым доставкам, а worker отправки обязан использовать закрепленный аккаунт. `EMAIL_ACCOUNT` называет аккаунт (`default`, если не задан); меняйте его каждый раз, когда `RESEND_API_KEY` переходит к другому аккаунту Resend. Аккаунт можно сменить, только пока у доставки нет попыток, потому что до первой попытки ключ не видел ни один провайдер: `Delivery.Rebind` отклоняет доставку с попыткой или в конечном статусе, а trigger отклоняет смену провайдера после попытки (ограничение `deliveries_provider_pinned`, адаптер переводит его в `outbound.ErrDeliveryProviderPinned`). Worker служебной почты использует это для доставок, созданных при `EMAIL_PROVIDER=disabled`, когда стенд включит транспорт; переносить их автоматически или по запросу оператора, решает эта задача. -Миграция `00012_add_delivery_sending.sql` (TASK-016) аддитивна; существующие строки остаются корректными. Она добавляет в `deliveries`: `email_token_id` (необязательный внешний ключ на `email_tokens.id` для писем с токеном, неизменяемый, как остальное содержимое; NULL для уведомлений), `cancel_reason` (задан ровно когда статус `cancelled`, CHECK ограничивает его перечисленными причинами), столбцы lease `claim_owner` и `claimed_until` (оба или ни одного; lease держит только доставка, которую worker еще может отправить), `first_send_started_at` (когда начался первый запрос, по часам базы), `failure_count` (подряд идущие сбои worker на строке), `body_redacted_at` (тела письма с токеном очищены), статус `cancelled` с его CHECK и два частичных индекса: `deliveries_due_idx` по `(next_attempt_at, id)`, чей предикат называет служебные виды и статусы, которые берутся снова, поэтому строки уведомлений в него не попадают, а холостой опрос их не сканирует, и индекс по `email_token_id`. Trigger `deliveries_refuse_content_change` разрешает еще ровно одно изменение тел: у конечного письма с токеном оба тела один раз становятся пустыми вместе с `body_redacted_at`. В `email_tokens` добавляется назначение токена `password_reset`. Откат миграции превращает отмененные доставки в отклоненные и удаляет токены сброса. Запланировано: отмена доставки по отозванному разрешению (TASK-462). +Миграция `00012_add_delivery_sending.sql` аддитивна; существующие строки остаются корректными. Она добавляет в `deliveries`: `email_token_id` (необязательный внешний ключ на `email_tokens.id` для писем с токеном, неизменяемый, как остальное содержимое; NULL для уведомлений), `cancel_reason` (задан ровно когда статус `cancelled`, CHECK ограничивает его перечисленными причинами), столбцы lease `claim_owner` и `claimed_until` (оба или ни одного; lease держит только доставка, которую worker еще может отправить), `first_send_started_at` (когда начался первый запрос, по часам базы), `failure_count` (подряд идущие сбои worker на строке), `body_redacted_at` (тела письма с токеном очищены), статус `cancelled` с его CHECK и два частичных индекса: `deliveries_due_idx` по `(next_attempt_at, id)`, чей предикат называет служебные виды и статусы, которые берутся снова, поэтому строки уведомлений в него не попадают, а холостой опрос их не сканирует, и индекс по `email_token_id`. Trigger `deliveries_refuse_content_change` разрешает еще ровно одно изменение тел: у конечного письма с токеном оба тела один раз становятся пустыми вместе с `body_redacted_at`. В `email_tokens` добавляется назначение токена `password_reset`. Откат миграции превращает отмененные доставки в отклоненные и удаляет токены сброса. Запланировано: отмена доставки по отозванному разрешению. Хранилище дает `Get`, `ListAttempts`, `RecordAttempt` с проверкой версии, `WaitForQuota`, `Cancel` и `Rebind`, а для worker отправки - `ClaimDue`, `ReleaseClaim` и `ServiceMailState`. ### Квоты почты -Реализовано (TASK-018): окна и лимиты квот в `backend/internal/domain/mail_quota.go`; порт `outbound.MailQuotaRepository` (`port/outbound/mail_quota.go`), запись через который идет через `UnitOfWork.MailQuotas()`, а чтение еще и через `postgres.MailQuotaStore`; миграция `00007_create_mail_quota_usage.sql` с таблицами `mail_quota_usage` и `mail_quota_reservations`; запросы в `backend/db/queries/mail_quota.sql`; в `backend/internal/usecase/notification/` - `QuotaGate` с `PrepareSend` и `SettleSend` (`quota.go`), отчет при запуске `ReportQuotaUsage` и чтение статуса для пользователя `DeliveryStatusReader` (`delivery_status.go`); `SendResult.QuotaPeriod` в почтовом порте, который заполняет адаптер Resend; отчет при запуске в bootstrap (`bootstrap/mail_quota.go`). Worker отправки (TASK-016) вызывает шлюз вокруг `MailSender.Send`, а `bootstrap/mail_sender.go` собирает его из конфигурации с `resend.IdempotencyWindow` или нулем для SMTP; см. [Отправка служебной почты](#отправка-служебной-почты). Запланировано: API или сценарий identity, который показывает результат чтения статуса. Пока открыта TASK-462, в квоту считается только служебная почта identity. +Реализовано: окна и лимиты квот в `backend/internal/domain/mail_quota.go`; порт `outbound.MailQuotaRepository` (`port/outbound/mail_quota.go`), запись через который идет через `UnitOfWork.MailQuotas()`, а чтение еще и через `postgres.MailQuotaStore`; миграция `00007_create_mail_quota_usage.sql` с таблицами `mail_quota_usage` и `mail_quota_reservations`; запросы в `backend/db/queries/mail_quota.sql`; в `backend/internal/usecase/notification/` - `QuotaGate` с `PrepareSend` и `SettleSend` (`quota.go`), отчет при запуске `ReportQuotaUsage` и чтение статуса для пользователя `DeliveryStatusReader` (`delivery_status.go`); `SendResult.QuotaPeriod` в почтовом порте, который заполняет адаптер Resend; отчет при запуске в bootstrap (`bootstrap/mail_quota.go`). Worker отправки вызывает шлюз вокруг `MailSender.Send`, а `bootstrap/mail_sender.go` собирает его из конфигурации с `resend.IdempotencyWindow` или нулем для SMTP; см. [Отправка служебной почты](#отправка-служебной-почты). Запланировано: API или сценарий identity, который показывает результат чтения статуса. Пока отправка продуктовых уведомлений не реализована, в квоту считается только служебная почта identity. Лимиты. `EMAIL_QUOTA_DAILY` и `EMAIL_QUOTA_MONTHLY` ограничивают число получателей, отправленных через настроенный аккаунт провайдера (`EMAIL_PROVIDER` и `EMAIL_ACCOUNT`), за UTC-сутки, с 00:00 до 00:00 UTC, и за календарный месяц UTC. Считается каждый получатель, как считает Resend; у доставки один получатель. Значения по умолчанию - лимиты Resend Free, проверенные 05.10.2026: 100 и 3000; они действуют для `resend` и для `disabled`, который ничего не отправляет. У `smtp` значений по умолчанию нет, и без обоих значений он не запускается: лимиты relay не совпадают с лимитами Resend. Допустимы значения от 1 до 1000000000, суточный лимит не больше месячного. Значения, которое отключает квоту, нет, поэтому ни один провайдер не работает без шлюза. Лимиты - это конфигурация, а не доменные константы, и они не хранятся: измененный лимит действует со следующего резервирования, а лимит, сниженный ниже текущего расхода, откладывает каждую новую отправку до сброса окна. @@ -311,9 +311,9 @@ Offsets и партиции. Каждый обработчик - один уча Резервирование. `QuotaGate.PrepareSend(ctx, unit, delivery)` выполняется в транзакции вызывающего: 1. Доставка, закрепленная за другим аккаунтом провайдера, чем настроенный, завершается ошибкой `notification.ErrQuotaNotConfigured`: лимиты для нее неизвестны, а аккаунт без квоты никогда не считается "безлимитным". Доставка в `accepted` или `rejected` завершается ошибкой `domain.ErrDeliveryTransition`. -2. Повтор внутри окна идемпотентности провайдера повторно использует открытое резервирование той же доставки (прошлая попытка закончилась `unknown` или ее процесс остановился до расчета) и проходит без нового учета: на повтор с тем же ключом провайдер отвечает исходным результатом, а не отправляет письмо второй раз. Окно - параметр шлюза: `resend.IdempotencyWindow`, 24 часа по документации API Resend, или ноль для SMTP, у которого нет дедупликации на стороне провайдера, поэтому каждый повтор через SMTP считается заново. После окна повтор считается заново; допустим ли он вообще, решает политика повторов (TASK-017). +2. Повтор внутри окна идемпотентности провайдера повторно использует открытое резервирование той же доставки (прошлая попытка закончилась `unknown` или ее процесс остановился до расчета) и проходит без нового учета: на повтор с тем же ключом провайдер отвечает исходным результатом, а не отправляет письмо второй раз. Окно - параметр шлюза: `resend.IdempotencyWindow`, 24 часа по документации API Resend, или ноль для SMTP, у которого нет дедупликации на стороне провайдера, поэтому каждый повтор через SMTP считается заново. После окна повтор считается заново; допустим ли он вообще, решает политика повторов. 3. Иначе репозиторий блокирует строки суток и месяца, добавляет одного получателя в обе, только если он укладывается в оба лимита, и записывает резервирование в журнал. Если не укладывается, ничего не меняется, а результат сообщает, какой лимит был бы превышен. Резервирование выполняется по обоим окнам целиком или не выполняется вовсе. -4. Если отправка допущена, решение содержит разрешение, а доставка не меняется. Иначе доставка ждет сброса заполненного окна: ближайших 00:00 UTC для суток и первого числа следующего месяца для месяца; если заполнены оба, побеждает сброс месяца. Доставка в `pending` или `waiting_quota` сохраняется в `waiting_quota` с `next_attempt_at` на этот момент через `Delivery.WaitForQuota`. Временем изменения берется более позднее из показаний часов и последнего изменения доставки, а сброс не раньше него, поэтому экземпляр, чьи часы отстают на несколько миллисекунд от того, кто последним записал доставку, все равно может ее отложить. Доставка в `unknown` возвращается без изменений вместе с моментом сброса: ее повтор решает политика повторов (TASK-017), а перевод в ожидание скрыл бы, что прошлая попытка могла быть принята. +4. Если отправка допущена, решение содержит разрешение, а доставка не меняется. Иначе доставка ждет сброса заполненного окна: ближайших 00:00 UTC для суток и первого числа следующего месяца для месяца; если заполнены оба, побеждает сброс месяца. Доставка в `pending` или `waiting_quota` сохраняется в `waiting_quota` с `next_attempt_at` на этот момент через `Delivery.WaitForQuota`. Временем изменения берется более позднее из показаний часов и последнего изменения доставки, а сброс не раньше него, поэтому экземпляр, чьи часы отстают на несколько миллисекунд от того, кто последним записал доставку, все равно может ее отложить. Доставка в `unknown` возвращается без изменений вместе с моментом сброса: ее повтор решает политика повторов, а перевод в ожидание скрыл бы, что прошлая попытка могла быть принята. Блокировки строк держатся до конца транзакции вызывающего, поэтому worker обязан зафиксировать транзакцию до вызова транспорта; цена - отправки одного аккаунта резервируются по очереди. @@ -338,11 +338,11 @@ Offsets и партиции. Каждый обработчик - один уча | `rejected` | Ваше письмо не удалось отправить | | `cancelled` | Ваше письмо не отправлено, потому что ссылка в нем больше не действует; запросите новое | -Операторы читают те же строки запросами из [DEPLOY.md](DEPLOY.md#квоты-почты). Шлюз пишет в журнал `mail quota is used up; the delivery waits for the reset` на уровне info и `the mail provider reported its quota used up; local sending stops until the reset` на уровне warn, только с ID доставки, провайдером, периодом и моментом сброса. Gauges квот (TASK-022) читаются через `MailQuotaUsageReader.Usage` для настроенного аккаунта только с labels provider и window; см. [Метрики, телеметрия и alerts](#метрики-телеметрия-и-alerts). +Операторы читают те же строки запросами из [DEPLOY.md](DEPLOY.md#квоты-почты). Шлюз пишет в журнал `mail quota is used up; the delivery waits for the reset` на уровне info и `the mail provider reported its quota used up; local sending stops until the reset` на уровне warn, только с ID доставки, провайдером, периодом и моментом сброса. Gauges квот читаются через `MailQuotaUsageReader.Usage` для настроенного аккаунта только с labels provider и window; см. [Метрики, телеметрия и alerts](#метрики-телеметрия-и-alerts). ### Отправка служебной почты -Реализовано (TASK-016): usecase отправки `ServiceMailSender` (`backend/internal/usecase/notification/service_sender.go`), usecase постановки `ServiceMailer` (`service_mail.go`), минимальное расписание повторов `RetryPolicy` (`send_retry.go`), `Delivery.CheckServiceMail` и `Delivery.Cancel` с причинами отмены (`backend/internal/domain/delivery.go`, `delivery_guard.go`), цикл в `backend/internal/worker/mailsender/`, входящий порт `inbound.MailPass` (`port/inbound/mail_sender.go`), методы репозитория `ClaimDue`, `ReleaseClaim`, `Cancel` и `ServiceMailState`, миграция `00012_add_delivery_sending.sql`, gauge `lincodex_mail_sender_running` и подключение в `bootstrap/mail_sender.go`. Не реализовано: отправка продуктовых уведомлений (TASK-462), политика повторов и неизвестного исхода (TASK-017) и сценарии identity, которые вызывают `ServiceMailer`. +Реализовано: usecase отправки `ServiceMailSender` (`backend/internal/usecase/notification/service_sender.go`), usecase постановки `ServiceMailer` (`service_mail.go`), минимальное расписание повторов `RetryPolicy` (`send_retry.go`), `Delivery.CheckServiceMail` и `Delivery.Cancel` с причинами отмены (`backend/internal/domain/delivery.go`, `delivery_guard.go`), цикл в `backend/internal/worker/mailsender/`, входящий порт `inbound.MailPass` (`port/inbound/mail_sender.go`), методы репозитория `ClaimDue`, `ReleaseClaim`, `Cancel` и `ServiceMailState`, миграция `00012_add_delivery_sending.sql`, gauge `lincodex_mail_sender_running` и подключение в `bootstrap/mail_sender.go`. Не реализовано: отправка продуктовых уведомлений, политика повторов и неизвестного исхода и сценарии identity, которые вызывают `ServiceMailer`. Область. Worker берет только виды `verification` и `password_reset`. Продуктовое уведомление он не берет никогда, в каком бы состоянии оно ни было. Служебной почте не нужна запись согласия ни для какого назначения: она часть сценария аккаунта, поэтому ничто не читает журнал согласий, а C2 (публикация карточки кандидата) и остальные продуктовые согласия не участвуют. Между аккаунтом и письмом стоит проверка ниже, а не согласие. @@ -385,7 +385,7 @@ Offsets и партиции. Каждый обработчик - один уча | `rejected` `permanent` или `invalid_request` | `rejected` | нет | возвращается | | `rejected` `temporary` или `rate_limited` | `pending` | сейчас плюс `RetryPolicy`: 1 минута, удвоение до 30 минут, не меньше `Retry-After` провайдера | возвращается | | `rejected` `quota_exhausted` | `waiting_quota` | сброс, который вернул шлюз (ближайшие 00:00 UTC для суток, первое число следующего месяца для месяца); нет, если провайдер не назвал окно | окно отмечено заполненным | -| `unknown` | `unknown` | нет: автоматического повтора нет (TASK-017) | считается | +| `unknown` | `unknown` | нет: автоматического повтора нет | считается | | Ошибка `Send`: нет транспорта (`ErrMailChannelUnavailable`) или context завершился | без изменений, lease освобожден | остается срок | возвращается | | Ошибка `Send`: неверное сообщение (`ErrInvalidOutgoingMail`) | `cancelled`, `content_invalid` | нет | возвращается | | Ошибка `Send`: любая другая без ответа | не считается против строки; она отодвигается по `RetryPolicy`, а worker делает паузу | сейчас плюс `RetryPolicy` | возвращается | @@ -408,11 +408,11 @@ Worker потерян после вызова. Если worker останови Тесты. `integration_test/mail_sender_test.go` запускает локальную имитацию Resend (`resendfixture`, сервер `httptest`, который говорит на части API, используемой транспортом, и доступен через `resend.NewLoopbackSender`, принимающий только loopback endpoint) против PostgreSQL; см. [TESTING.md](TESTING.md). Это только тестовая подмена; production использует настоящий транспорт Resend с фиксированным endpoint. -Открытые вопросы. У `unknown` нет автоматического повтора и эскалации до TASK-017. Отправка уведомлений и нужная ей проверка разрешений относятся к TASK-462; до нее они ждут и не учитываются в gauge просрочки, поэтому очередь уведомлений не включает `LincodexMailDeliveriesOverdue` (gauge `lincodex_mail_delivery_oldest_due_pending_age_seconds` охватывает `domain.ServiceMailKinds`; его предикат - предикат `deliveries_due_idx`). Идет ли сброс пароля на неподтвержденные аккаунты, решает сценарий сброса. Опрос выполняется каждые 5 секунд, захват читает один индексированный запрос, что подходит для текущего объема. +Открытые вопросы. Автоматический повтор и эскалация для `unknown` пока не реализованы. Отправка продуктовых уведомлений и нужная ей проверка разрешений запланированы; до их реализации уведомления ждут и не учитываются в gauge просрочки, поэтому очередь уведомлений не включает `LincodexMailDeliveriesOverdue` (gauge `lincodex_mail_delivery_oldest_due_pending_age_seconds` охватывает `domain.ServiceMailKinds`; его предикат - предикат `deliveries_due_idx`). Идет ли сброс пароля на неподтвержденные аккаунты, решает сценарий сброса. Опрос выполняется каждые 5 секунд, захват читает один индексированный запрос, что подходит для текущего объема. ### Версии продуктовой политики -Реализованы хранение, публикация и начальное заполнение при старте (TASK-005): миграция `backend/db/migrations/00003_create_policy_versions.sql`, запросы в `backend/db/queries/policy.sql`, типизированная политика в `backend/internal/domain/` (`policy.go`, `policy_document.go`, `policy_version.go`, `policy_demo.go`), порт `outbound.PolicyRepository` (`port/outbound/policy.go`), адаптер на sqlc в `backend/internal/adapter/secondary/postgres/policy.go` и публикация в `backend/internal/usecase/policy/`. Ни одно продуктовое правило пока не читает политику; приглашения, квоты, оценивание, сессии и статус поиска начнут читать ее по мере реализации своих задач. +Реализованы хранение, публикация и начальное заполнение при старте: миграция `backend/db/migrations/00003_create_policy_versions.sql`, запросы в `backend/db/queries/policy.sql`, типизированная политика в `backend/internal/domain/` (`policy.go`, `policy_document.go`, `policy_version.go`, `policy_demo.go`), порт `outbound.PolicyRepository` (`port/outbound/policy.go`), адаптер на sqlc в `backend/internal/adapter/secondary/postgres/policy.go` и публикация в `backend/internal/usecase/policy/`. Ни одно продуктовое правило пока не читает политику; приглашения, квоты, оценивание, сессии и статус поиска начнут читать ее по мере реализации своих задач. Колонки `policy_versions`: @@ -426,9 +426,9 @@ Worker потерян после вызова. Если worker останови Неизменяемость обеспечивает база данных. Функция триггера `policy_versions_refuse_change` отклоняет каждый UPDATE и DELETE (строчный триггер) и TRUNCATE (триггер на оператор) с SQLSTATE 23000 и именем ограничения `policy_versions_immutable`; адаптер сопоставляет с `outbound.ErrPolicyVersionImmutable` именно эту пару, а не текст сообщения. В порту нет методов изменения и удаления, поэтому изменение - всегда новая версия. Гарантия покрывает запросы приложения и ручной SQL; роль-владелец таблицы все еще может отключить триггер или удалить таблицу, поэтому runtime-роль с минимальными правами остается будущей работой. -Типизированная политика `domain.ProductPolicy`: каждое значение - именованное поле, тип которого несет единицу измерения: `CalendarDays`, `BusinessDays` (без перевода в длительность; производственный календарь задает использующая функция), `Hours` и `BasisPoints` для вероятностей и стандартной ошибки - целое число долей 0.0001 (0.80 - это 8000). Базисные пункты сравниваются точно, без погрешности чисел с плавающей точкой, и оставляют в документе целые числа. Метод `Validate` каждого раздела отклоняет нулевые, отсутствующие и выходящие за диапазон значения и несогласованные сочетания, например срок по умолчанию вне списка вариантов, более высокий уровень квоты с меньшим лимитом, неактивный E0, активный уровень над неактивным или вероятности остановки, которые не охватывают порог подтверждения. Диапазоны - защита от ошибок в единицах, а не продуктовые решения. Уровни квот E0 < E1 < E2 доступны через `OrganizationQuotaPolicy.Tier(domain.OrganizationTier)` (для TASK-087); каждая организация начинает с E0, а правила перехода между уровнями относятся к функции квот. +Типизированная политика `domain.ProductPolicy`: каждое значение - именованное поле, тип которого несет единицу измерения: `CalendarDays`, `BusinessDays` (без перевода в длительность; производственный календарь задает использующая функция), `Hours` и `BasisPoints` для вероятностей и стандартной ошибки - целое число долей 0.0001 (0.80 - это 8000). Базисные пункты сравниваются точно, без погрешности чисел с плавающей точкой, и оставляют в документе целые числа. Метод `Validate` каждого раздела отклоняет нулевые, отсутствующие и выходящие за диапазон значения и несогласованные сочетания, например срок по умолчанию вне списка вариантов, более высокий уровень квоты с меньшим лимитом, неактивный E0, активный уровень над неактивным или вероятности остановки, которые не охватывают порог подтверждения. Диапазоны - защита от ошибок в единицах, а не продуктовые решения. Уровни квот E0 < E1 < E2 доступны через `OrganizationQuotaPolicy.Tier(domain.OrganizationTier)` (для применения квот организации); каждая организация начинает с E0, а правила перехода между уровнями относятся к функции квот. -Открытый вопрос для задач попыток (TASK-157 и TASK-158): `MaxAttemptsPerWindow` хранит только число. Считается ли лимит по грейду, по специальности или по всем оцениваниям кандидата, не решено. +Открытый вопрос для задач попыток: `MaxAttemptsPerWindow` хранит только число. Считается ли лимит по грейду, по специальности или по всем оцениваниям кандидата, не решено. У документа `schema_version` 1 и разделы `invitations`, `organization_quotas`, `assessment`, `identity` и `search_status`; имена полей несут единицу (`_days`, `_business_days`, `_hours`, `_bp`). Разбор строгий: отклоняются неизвестные поля, отсутствующие поля и null, неверные типы, дробные числа, значения вне int32, неизвестная версия схемы, данные после объекта и документы больше 64 KiB. Каноническая форма - компактная кодировка Go в порядке объявления полей. jsonb нормализует порядок ключей, поэтому `domain.RestorePolicyVersion` разбирает сохраненный документ, проверяет его, кодирует заново и сравнивает SHA-256 с `document_sha256`; при расхождении возвращается `domain.ErrPolicyDocumentIntegrity`. Golden-тест фиксирует каноническую форму, потому что ее изменение сломало бы проверку всех сохраненных версий; новой структуре нужны новая версия схемы и свой декодер. @@ -591,7 +591,7 @@ contact_grant относится к паре кандидат-компания ### Банк заданий оценки -Реализованы хранилище и загрузчик (TASK-154), а не функция для кандидата: миграция `backend/db/migrations/00011_create_assessment_bank.sql`, запросы в `backend/db/queries/assessment_bank.sql`, доменные типы в `backend/internal/domain/` (`assessment_family.go`, `assessment_generator.go`, `assessment_algorithms.go`), порт `outbound.AssessmentBankRepository` (`port/outbound/assessment_bank.go`, доступен через `UnitOfWork.AssessmentBank()`), адаптер на sqlc в `backend/internal/adapter/secondary/postgres/assessment_bank.go` и загрузчик в `backend/internal/usecase/assessment/` (`Bank`, `Bundle`). Bootstrap и HTTP API его пока не вызывают, и ни одна категория не открыта. +Реализованы хранилище и загрузчик, а не функция для кандидата: миграция `backend/db/migrations/00011_create_assessment_bank.sql`, запросы в `backend/db/queries/assessment_bank.sql`, доменные типы в `backend/internal/domain/` (`assessment_family.go`, `assessment_generator.go`, `assessment_algorithms.go`), порт `outbound.AssessmentBankRepository` (`port/outbound/assessment_bank.go`, доступен через `UnitOfWork.AssessmentBank()`), адаптер на sqlc в `backend/internal/adapter/secondary/postgres/assessment_bank.go` и загрузчик в `backend/internal/usecase/assessment/` (`Bank`, `Bundle`). Bootstrap и HTTP API его пока не вызывают, и ни одна категория не открыта. - Версия семейства. Одна строка `assessment_families` - одна версия одного семейства (`family_key`, `version`): категория, специализация (область внутри категории), название, автор (`ai:` или `operator:`), рецензент (`operator:` или NULL), `review_status` (`pending`, `approved`, `rejected`), генератор по seed, ключ ответа, рубрика, хеш содержимого с его `hash_scheme`, жизненный цикл (`draft`, `published`, `retired`) и операторы и время публикации и вывода из обращения. Рецензент не бывает автором, а рецензия остается `pending`, пока рецензента нет (CHECK-ограничения; домен применяет те же правила). Рецензент в пакете и оператор публикации - заявленные значения, а не аутентифицированные личности, пока нет учетных записей рецензентов и операторов. - Неизменяемость. Содержимое сохраненной версии не меняется: триггер `assessment_families_guard_update` отклоняет любой UPDATE, который меняет колонки кроме колонок жизненного цикла (`lifecycle`, `published_at`, `published_by`, `retired_at`, `retired_by`), а `assessment_families_refuse_removal` отклоняет DELETE и TRUNCATE, все с SQLSTATE 23000 и именем ограничения `assessment_families_immutable`, которое адаптер преобразует в `outbound.ErrAssessmentFamilyImmutable`. Жизненный цикл идет только вперед (draft, published, retired), время ставит триггер и он же сохраняет публикатора при выводе из обращения, а версия публикуется только с одобренной рецензией рецензента (`assessment_families_published_requires_review`). Изменение - это новая версия со следующим номером: загрузчик принимает версию 1 для нового семейства и преемника последней версии для существующего. Черновик с рецензией `pending` никогда не одобряется на месте: рецензия записывается импортом новой версии семейства, которая ее несет, а версия `pending` остается неопубликованным черновиком. Домен пересчитывает хеш содержимого при чтении строки и возвращает `ErrAssessmentFamilyIntegrity`, если строку изменили вне приложения. Хеш - это SHA-256 канонического JSON-документа, который содержит содержимое без имени пакета, ID, жизненного цикла и полей публикации. Колонка `hash_scheme` (smallint с CHECK известных значений, одна из неизменяемых колонок) называет формат: домен проверяет строку хеш-функцией той схемы, с которой строка сохранена, поэтому следующая схема (новая функция и новое значение CHECK, а не правка схемы 1) проверяет новые строки и не ломает старые, а строка с неизвестной схемой отклоняется; тесты проверяют строку ее собственной схемой и фиксируют хеш схемы 1 для заданного входа. Как и для `policy_versions`, роль-владелец таблицы все еще может отключить триггеры. @@ -646,7 +646,7 @@ contact_grant относится к паре кандидат-компания ### Хранение identity -Реализовано только хранение (TASK-051): миграция `backend/db/migrations/00002_create_identity_tables.sql`, запросы в `backend/db/queries/identity.sql`, доменные типы в `backend/internal/domain/`, порты в `backend/internal/port/outbound/identity.go` и адаптер на sqlc в `backend/internal/adapter/secondary/postgres/identity.go`. Регистрация, подтверждение, вход и сессии из [api/README.md](../../api/README.md#identity-сессии-cookie-и-csrf) запланированы (TASK-053 - TASK-056); ни один usecase или обработчик это хранение пока не использует. +Реализовано только хранение: миграция `backend/db/migrations/00002_create_identity_tables.sql`, запросы в `backend/db/queries/identity.sql`, доменные типы в `backend/internal/domain/`, порты в `backend/internal/port/outbound/identity.go` и адаптер на sqlc в `backend/internal/adapter/secondary/postgres/identity.go`. Регистрация, подтверждение, вход и сессии из [api/README.md](../../api/README.md#identity-сессии-cookie-и-csrf) запланированы; ни один usecase или обработчик это хранение пока не использует. - `users`: UUIDv7 `id`; `email` - форма для доставки (ASCII без пробелов по краям, регистр как при вводе, возвращается в `Account.email`), и `email_normalized` - уникальный ключ сравнения (тот же адрес, в котором A-Z переведены в нижний регистр); `password_hash` - строка PHC Argon2id v19; `scenario` и `onboarding_step` с CHECK, что шаг относится к сценарию; nullable `email_verified_at`; `registration_version`; `last_registered_at` с частичным индексом по неподтвержденным аккаунтам для запланированной очистки через 7 дней; оптимистичная `version`; `created_at` и `updated_at`. Форма для доставки хранится, потому что RFC 5321 допускает local part с учетом регистра: письмо уходит на адрес в введенном виде, а уникальность не учитывает регистр. - `email_tokens`: `token_hash` (SHA-256, `bytea` из 32 байт, уникальный), `purpose` (`email_verification`; CHECK перечисляет допустимые назначения, поэтому сброс пароля можно добавить позже), `user_id`, `registration_version`, к которой привязан токен, `created_at`, `expires_at`, `consumed_at` и `invalidated_at`. CHECK допускает не больше одного из consumed и invalidated. @@ -659,13 +659,13 @@ contact_grant относится к паре кандидат-компания - База хранит хеши, а не пароли и исходные токены. Токен несет 256 бит из crypto/rand, поэтому SHA-256 без соли нельзя обратить перебором, а поиск остается одним обращением к индексу; для паролей нужен медленный KDF Argon2id. `bytea` вдвое компактнее hex-текста, допускает точную проверку длины и не имеет вариантов регистра. `domain.SecretToken`, `domain.PasswordHash` и `domain.EmailAddress` скрывают значение в выводе `fmt` (для любого verb) и `slog`, поэтому при печати `domain.User` не видны ни адрес, ни хеш; настоящие значения возвращают явные методы доступа. Неотображенные ошибки PostgreSQL из репозиториев identity сохраняют только SQLSTATE и имя ограничения, потому что текст и detail ошибки могут содержать значения строки. - Колонки с перечислимыми значениями - text с CHECK, а не enum-типы PostgreSQL. Новый сценарий, шаг или назначение заменяет одно ограничение в обратимой миграции; значение enum нельзя удалить и нельзя использовать в транзакции, которая его добавила. - Каждое сохраняемое время берется из часов приложения, которые передает вызывающий код, поэтому сроки и проверки по ним используют одни часы. Репозитории отклоняют нулевое время. -- Колонки для CSRF нет. `GetCurrentSession` должен вернуть CSRF-токен сессии после перезагрузки страницы, а сохраненный хеш не позволяет его восстановить. TASK-056 может выводить токен из токена сессии с серверным ключом, что не требует хранения, или добавить колонку аддитивной миграцией. +- Колонки для CSRF нет. `GetCurrentSession` должен вернуть CSRF-токен сессии после перезагрузки страницы, а сохраненный хеш не позволяет его восстановить. Аутентификация сессий может выводить токен из токена сессии с серверным ключом, что не требует хранения, или добавить колонку аддитивной миграцией. Что гарантируют порты: - `UserRepository.Create` возвращает `ErrEmailTaken` для повторного ключа. `UpdateRegistration` сохраняет результат `domain.User.ReRegister`, только если сохраненная `version` совпадает и email не подтвержден; тот же запрос увеличивает `version` и `registration_version` на единицу, поэтому версию регистрации не выбирает вызывающий код, и удаляет регистрационное C1 прежнего регистранта (см. [Журнал согласий](#журнал-согласий)). `MarkEmailVerified` применяется только к неподтвержденному аккаунту с указанной версией регистрации. В остальных случаях оба возвращают `ErrUserVersionConflict`. - `EmailTokenRepository.Consume` - один `UPDATE ... RETURNING`, который требует непогашенный, неаннулированный и неистекший токен. Параллельные вызовы ждут в очереди на блокировку строки токена; при READ COMMITTED каждый ожидающий заново проверяет строку после завершения владельца блокировки, поэтому успешен ровно один, а если владелец откатился, ожидающий еще может погасить токен. Неудача сообщается как `ErrEmailTokenNotFound`, `ErrEmailTokenConsumed`, `ErrEmailTokenInvalidated` (заменен или выдан для более ранней версии регистрации) или `ErrEmailTokenExpired`. `InvalidateActive` помечает все прежние токены пользователя с этим назначением. -- Consume сравнивает версию регистрации токена с аккаунтом только в том виде, в каком его прочитал запрос, без блокировки, поэтому не видит повторную регистрацию, зафиксированную сразу после него. Привязка токена к текущей регистрации поэтому соблюдается, только если подтверждение вызывает `MarkEmailVerified(token.UserID, token.RegistrationVersion)` в той же транзакции и откатывает ее при `ErrUserVersionConflict`; откат возвращает и токен, который затем считается замененным. Usecase подтверждения (TASK-054) переводит этот исход в `verification_token_invalid`. +- Consume сравнивает версию регистрации токена с аккаунтом только в том виде, в каком его прочитал запрос, без блокировки, поэтому не видит повторную регистрацию, зафиксированную сразу после него. Привязка токена к текущей регистрации поэтому соблюдается, только если подтверждение вызывает `MarkEmailVerified(token.UserID, token.RegistrationVersion)` в той же транзакции и откатывает ее при `ErrUserVersionConflict`; откат возвращает и токен, который затем считается замененным. Usecase подтверждения переводит этот исход в `verification_token_invalid`. - `SessionRepository.FindActive` и `Touch` получают таймаут простоя от вызывающего кода и принимают только неотозванную сессию до ее абсолютного срока и в пределах таймаута простоя. `Touch` записывает `last_seen_at`, только если сохраненное значение старше более чем на минуту, поэтому частые запросы не переписывают строку, а таймаут простоя может завершить сессию на минуту раньше; `Touch` не сдвигает `last_seen_at` назад и не возобновляет завершенную сессию. `Revoke` и `RevokeAllForUser` устанавливают `revoked_at`. - `DeleteUnverifiedRegisteredBefore` удаляет одну пачку неподтвержденных аккаунтов, начиная со старых, и никогда не ждет блокировку. Он блокирует аккаунты-кандидаты, их токены, сессии, запросы писем, доставки писем и записи согласий через `FOR UPDATE SKIP LOCKED` и пропускает каждый аккаунт, у которого строка аккаунта или любая строка токена, сессии, запроса письма, доставки или согласия заблокирована другой транзакцией, например повторной регистрацией, повторной отправкой, подтверждением, обработчиком доставки или worker доставки; пропущенные аккаунты остаются до следующего запуска. Запросы писем, доставки и попытки удаляются вместе с аккаунтом каскадно; записи согласий, которые запрещают удаление аккаунта, удаляются явно в том же запросе. - `postgres.IdentityStore` выполняет те же репозитории вне транзакции. При вызове с контекстом из callback `Transactor` он возвращает `ErrNestedTransaction`, а не фиксирует изменения через отдельное соединение. @@ -674,20 +674,20 @@ contact_grant относится к паре кандидат-компания ### Хеширование паролей -Реализовано (TASK-052) и покрыто тестами: регистрация (TASK-053) создает hasher из конфигурации и вызывает его; вход (TASK-055) будет делать то же. +Реализовано и покрыто тестами: регистрация создает hasher из конфигурации и вызывает его; вход будет делать то же. - `domain.Password` хранит пароль, нормализованный в Unicode NFKC. `domain.NewPassword` применяет политику регистрации: от 15 до 128 кодовых точек после нормализации; `domain.ParseLoginPassword` принимает от 1 до 128. До нормализации оба отклоняют исходный ввод длиннее 512 байт (128 кодовых точек по 4 байта UTF-8 максимум, поэтому любое значение, принятое схемой контракта, помещается) и некорректный UTF-8. Эти проверки выполняются до любого хеширования и завершаются `domain.ErrInvalidPassword` с названием правила, но без значения. Blocklist распространенных и утекших паролей - отдельная запланированная проверка. - Порт `outbound.PasswordHasher` (`port/outbound/password.go`) содержит `Hash`, `Verify` и `VerifyDummy`; адаптер `adapter/secondary/argon2id` реализует его через `golang.org/x/crypto/argon2`. Новые хеши используют Argon2id v19 с m=65536 KiB, t=3, p=4 (второй рекомендованный вариант RFC 9106, выше базового уровня OWASP 19 MiB, t=2, p=1), соль 16 байт из crypto/rand и ключ 32 байта в формате `$argon2id$v=19$m=65536,t=3,p=4$$` в base64 без дополнения - этот формат принимают `domain.NewPasswordHash` и CHECK `users_password_hash_format`. Один хеш занял примерно 26-33 ms на машине разработчика Apple M5 (`BenchmarkHashRecommendedParameters`, в том числе на одном CPU); это не измерение задержки в production. - Бюджет памяти: вычисления делят взвешенный семафор (`golang.org/x/sync/semaphore`) размером `PASSWORD_HASH_CONCURRENCY`, умноженное на 64 MiB, и каждое держит свой параметр памяти, пока выполняется. Настройка принимает от 1 до 4; если она не задана, берется меньшее из 2 и GOMAXPROCS, который Go выводит из лимита CPU контейнера. Compose передает `PASSWORD_HASH_CONCURRENCY=1` для backend-контейнера с 1 CPU, поэтому хеши вычисляются по одному и занимают 64 MiB живой памяти; максимум 4 требует 256 MiB. Память завершенного вычисления остается мусором до следующей сборки; `GOMEMLIMIT=600MiB` в Compose заставляет сборщик освободить ее раньше, чем куча дойдет примерно до 78% лимита контейнера 768 MiB, а остаток приходится на стеки и память вне кучи. Ожидающие вызовы стоят в очереди FIFO, ограниченной только контекстом запроса; ограничение частоты запросов появится вместе с HTTP-операциями. - `Verify` строго разбирает сохраненную строку PHC, заново вычисляет ключ с сохраненными параметрами, солью и длиной ключа и сравнивает за постоянное время. Неверный пароль возвращает `outbound.ErrPasswordMismatch`. Некорректный хеш или хеш вне границ для сохраненных значений (память от 8 KiB на lane до 128 MiB и в пределах бюджета хеширования, от 1 до 16 проходов, от 1 до 16 lanes, соль 8-64 байта, digest 16-64 байта) возвращает `outbound.ErrPasswordHashCorrupt` без вычисления, поэтому подделанная строка не может потребовать неограниченную память или время. `ErrPasswordHashCorrupt` оборачивает `domain.ErrInvalidPasswordHash`, который репозиторий возвращает для сохраненного хеша, не прошедшего `domain.NewPasswordHash`. При совпадении `needsRehash` сообщает, что параметры, соль или длина ключа отличаются от текущих, и вход может сохранить новый хеш. - `VerifyDummy` выполняет `Verify` для хеша с текущими параметрами, случайной солью и случайным digest и возвращает `ErrPasswordMismatch` (или ошибку контекста). Вход будет вызывать его для неизвестного email, поэтому обе ветки одинаково разбирают хеш, ждут память, вычисляют и сравнивают. -- Вход (TASK-055) должен отвечать `invalid_credentials` для неизвестного email, неверного пароля и некорректного сохраненного хеша (`errors.Is(err, domain.ErrInvalidPasswordHash)`, из репозитория или из `Verify`); для некорректного хеша он также должен записать ошибку в лог и вызвать `VerifyDummy`. Оставшиеся различия во времени: поврежденный хеш отклоняется без вычисления, что компенсирует `VerifyDummy`, а хеш со старыми параметрами стоит столько, сколько стоят его параметры, пока следующий успешный вход его не перехеширует. +- Вход должен отвечать `invalid_credentials` для неизвестного email, неверного пароля и некорректного сохраненного хеша (`errors.Is(err, domain.ErrInvalidPasswordHash)`, из репозитория или из `Verify`); для некорректного хеша он также должен записать ошибку в лог и вызвать `VerifyDummy`. Оставшиеся различия во времени: поврежденный хеш отклоняется без вычисления, что компенсирует `VerifyDummy`, а хеш со старыми параметрами стоит столько, сколько стоят его параметры, пока следующий успешный вход его не перехеширует. - `identity.Credentials.HashNewPassword` проверяет новый пароль и только потом хеширует его; регистрация будет вызывать его в каждой ветке до поиска email. - Ошибки и логи никогда не содержат пароль или хеш. `domain.Password`, `domain.PasswordHash`, `domain.SecretToken` и `domain.EmailAddress` скрывают значение в выводе `fmt`, `slog` и JSON и хранят его за указателем, поэтому при печати внешней структуры, даже через неэкспортируемое поле, виден только адрес. ### Журнал согласий -Реализованы хранение, порты и контракт чтения (TASK-062): миграция `backend/db/migrations/00009_create_consent_ledger.sql`, запросы в `backend/db/queries/consents.sql`, доменные типы в `backend/internal/domain/consent.go`, порты в `backend/internal/port/outbound/consents.go`, адаптер на sqlc в `backend/internal/adapter/secondary/postgres/consents.go` и `ListMyConsents` в публичном контракте ([api/README.md](../../api/README.md#согласия)). Выдача C1-C3 и C5 с проверкой актуальной версии реализована как usecase `consent.Service` (TASK-063, см. [Usecase согласий](#usecase-согласий)). Отзыв с последствиями и HTTP-обработчик (TASK-064), C1 в транзакции регистрации (TASK-053) и C4 при принятии приглашения (TASK-201) запланированы; ни один продуктовый поток пока не вызывает usecase. +Реализованы хранение, порты и контракт чтения: миграция `backend/db/migrations/00009_create_consent_ledger.sql`, запросы в `backend/db/queries/consents.sql`, доменные типы в `backend/internal/domain/consent.go`, порты в `backend/internal/port/outbound/consents.go`, адаптер на sqlc в `backend/internal/adapter/secondary/postgres/consents.go` и `ListMyConsents` в публичном контракте ([api/README.md](../../api/README.md#согласия)). Выдача C1-C3 и C5 с проверкой актуальной версии реализована как usecase `consent.Service` (см. [Usecase согласий](#usecase-согласий)). Отзыв с последствиями и HTTP-обработчик, C1 в транзакции регистрации и C4 при принятии приглашения запланированы; ни один продуктовый поток пока не вызывает usecase. Согласия C1-C5 из PRD FR01 - независимые цели: выдача или отзыв одной цели никогда не меняет другую. @@ -698,12 +698,12 @@ contact_grant относится к паре кандидат-компания Решения: - Привязка к тексту. Внешний ключ на (`purpose`, `text_version`) отклоняет версию, которая для цели не публиковалась, а триггер BEFORE INSERT отклоняет версию, опубликованную позже времени выдачи (`consent_records_text_published`). Для C1-C3 и C5 второй внешний ключ через генерируемую колонку требует, чтобы `text_hash` совпадал с хэшем опубликованного текста. Для C4 тот же триггер требует, чтобы `text_hash` был SHA-256 опубликованного текста с подставленным `organization_name` (`consent_records_c4_text_hash`). Домен сам считает этот хэш в `domain.NewContactConsentGrant` из опубликованного `ConsentText` и названия, поэтому вызывающий код не передает байты хэша, а клиент не может придумать ни версию, ни хэш. Сохраненное название - снимок, который доказывает показанный текст; последующее переименование организации его не меняет, и модель чтения возвращает его как `ConsentOrganization.name`. -- История. Единственный UPDATE, который пропускает триггер, - отметка отзыва у неотозванной строки без изменения остальных колонок (`consent_records_immutable`). Новая версия текста - новая строка рядом со старой; выдача после отзыва - новая строка. Состояние (`active`, `superseded`, `revoked`) вычисляют запросы, оно не хранится: среди неотозванных строк субъекта и цели, кроме C4, строка, выданная последней (по `granted_at`, затем по ID), - `active`, остальные - `superseded`, независимо от их версий. Поэтому журнал принимает любую опубликованную версию, а usecase выдачи `consent.Service` (TASK-063) проверяет, что версия - актуальный текст, до вызова `Grant`. Частичный уникальный индекс оставляет одну неотозванную строку на субъекта, цель и версию, поэтому повторная или конкурентная выдача возвращает существующую запись; уникальный индекс по `invitation_id` оставляет одну строку C4 на приглашение, отозванную или нет, поэтому отозванное C4 не возвращается. -- Отзыв. `ConsentLedger.Revoke` ставит отметку на все неотозванные строки цели, включая `superseded`, а для C4 - только на строки одной организации. Повтор ничего не находит и сохраняет первую отметку. Время отзыва раньше времени выдачи строки, из-за расхождения часов между экземплярами, записывается временем выдачи (`greatest`), поэтому CHECK `consent_records_revocation_stamp` остается последней защитой. Последствия отзыва (запрос удаления для C1, закрытие публикации и grants для C2 и C4, ручной путь для C3, остановка импорта для C5) относятся к TASK-064 и не реализованы. -- Хранение и удаление. PRD 7.3 планирует хранить согласия три года, и это может быть дольше жизни аккаунта, поэтому `subject_id` ссылается на `users` с `ON DELETE RESTRICT`, а триггер BEFORE DELETE запрещает удалять строку подтвержденного аккаунта (`consent_records_retained`). Строки неподтвержденного аккаунта удалять можно, потому что регистрация, которую владелец адреса не подтвердил, не доказывает чье-либо согласие: очистка неподтвержденных аккаунтов удаляет строки удаляемых аккаунтов в том же запросе, а `UpdateRegistration` удаляет регистрационное C1 повторно регистрируемого аккаунта (см. ниже). TRUNCATE не вызывает строковый триггер и остается разрешенным для изоляции тестов. Оставит ли удаленный аккаунт журнал, tombstone или ничего, решают запрос удаления по C1 из TASK-064 и процедура удаления аккаунта, которая его исполняет и пока не имеет задачи в MVP; правило хранения расширит условие удаления своей миграцией. -- Повторная регистрация. Неподтвержденный аккаунт сохраняет `users.id`, когда тот же email регистрируется снова, поэтому иначе C1 прежнего регистранта стояло бы за новым. Запрос `UpdateUserRegistration` удаляет строки C1 с источником `registration` обновляемого аккаунта, и только если обновление применилось. Это обязательное требование для TASK-053: usecase регистрации вызывает `UpdateRegistration` и записывает новое C1 через `consent.Service.GrantAtRegistration` строго после `UpdateRegistration` в той же транзакции (см. [Usecase согласий](#usecase-согласий)). -- C2 и набор публикуемых полей. Строка C2 доказывает согласие с текстом публикации, а не то, какие поля опубликованы. Набор опубликованных полей и его изменения хранятся со временем и записью C2 за каждым в истории TASK-088 (`candidate_publications` и `candidate_privacy_events`, см. [Видимость кандидата](#видимость-кандидата)). Добавить scope полей в строки C2 позже - аддитивное изменение миграции и контракта. -- C4 в бизнес-транзакции. `UnitOfWork.ConsentLedger().GrantContact` принимает `domain.ContactConsentGrant`, который строит только `domain.NewContactConsentGrant` и который требует текст C4, организацию и ее название, непустой набор полей, приглашение и его версию условий; `domain.NewConsentGrant` отклоняет C4. Принятие приглашения (TASK-201) вызывает его в транзакции, которая переводит приглашение в `accepted`, создает grant и пишет событие аудита, поэтому все это фиксируется или откатывается вместе. Повторное принятие получает существующую запись с `created` false и сравнивает ее scope; для приглашения, чье C4 принадлежит другому субъекту, возвращается `ErrConsentInvitationTaken`. +- История. Единственный UPDATE, который пропускает триггер, - отметка отзыва у неотозванной строки без изменения остальных колонок (`consent_records_immutable`). Новая версия текста - новая строка рядом со старой; выдача после отзыва - новая строка. Состояние (`active`, `superseded`, `revoked`) вычисляют запросы, оно не хранится: среди неотозванных строк субъекта и цели, кроме C4, строка, выданная последней (по `granted_at`, затем по ID), - `active`, остальные - `superseded`, независимо от их версий. Поэтому журнал принимает любую опубликованную версию, а usecase выдачи `consent.Service` проверяет, что версия - актуальный текст, до вызова `Grant`. Частичный уникальный индекс оставляет одну неотозванную строку на субъекта, цель и версию, поэтому повторная или конкурентная выдача возвращает существующую запись; уникальный индекс по `invitation_id` оставляет одну строку C4 на приглашение, отозванную или нет, поэтому отозванное C4 не возвращается. +- Отзыв. `ConsentLedger.Revoke` ставит отметку на все неотозванные строки цели, включая `superseded`, а для C4 - только на строки одной организации. Повтор ничего не находит и сохраняет первую отметку. Время отзыва раньше времени выдачи строки, из-за расхождения часов между экземплярами, записывается временем выдачи (`greatest`), поэтому CHECK `consent_records_revocation_stamp` остается последней защитой. Последствия отзыва (запрос удаления для C1, закрытие публикации и grants для C2 и C4, ручной путь для C3, остановка импорта для C5) относятся к отзыву согласий и не реализованы. +- Хранение и удаление. PRD 7.3 планирует хранить согласия три года, и это может быть дольше жизни аккаунта, поэтому `subject_id` ссылается на `users` с `ON DELETE RESTRICT`, а триггер BEFORE DELETE запрещает удалять строку подтвержденного аккаунта (`consent_records_retained`). Строки неподтвержденного аккаунта удалять можно, потому что регистрация, которую владелец адреса не подтвердил, не доказывает чье-либо согласие: очистка неподтвержденных аккаунтов удаляет строки удаляемых аккаунтов в том же запросе, а `UpdateRegistration` удаляет регистрационное C1 повторно регистрируемого аккаунта (см. ниже). TRUNCATE не вызывает строковый триггер и остается разрешенным для изоляции тестов. Оставит ли удаленный аккаунт журнал, tombstone или ничего, решают запрос удаления по C1 и процедура удаления аккаунта, которая его исполняет и пока не имеет задачи в MVP; правило хранения расширит условие удаления своей миграцией. +- Повторная регистрация. Неподтвержденный аккаунт сохраняет `users.id`, когда тот же email регистрируется снова, поэтому иначе C1 прежнего регистранта стояло бы за новым. Запрос `UpdateUserRegistration` удаляет строки C1 с источником `registration` обновляемого аккаунта, и только если обновление применилось. Это обязательное требование для регистрации: usecase регистрации вызывает `UpdateRegistration` и записывает новое C1 через `consent.Service.GrantAtRegistration` строго после `UpdateRegistration` в той же транзакции (см. [Usecase согласий](#usecase-согласий)). +- C2 и набор публикуемых полей. Строка C2 доказывает согласие с текстом публикации, а не то, какие поля опубликованы. Набор опубликованных полей и его изменения хранятся со временем и записью C2 за каждым в истории видимости кандидата (`candidate_publications` и `candidate_privacy_events`, см. [Видимость кандидата](#видимость-кандидата)). Добавить scope полей в строки C2 позже - аддитивное изменение миграции и контракта. +- C4 в бизнес-транзакции. `UnitOfWork.ConsentLedger().GrantContact` принимает `domain.ContactConsentGrant`, который строит только `domain.NewContactConsentGrant` и который требует текст C4, организацию и ее название, непустой набор полей, приглашение и его версию условий; `domain.NewConsentGrant` отклоняет C4. Принятие приглашения вызывает его в транзакции, которая переводит приглашение в `accepted`, создает grant и пишет событие аудита, поэтому все это фиксируется или откатывается вместе. Повторное принятие получает существующую запись с `created` false и сравнивает ее scope; для приглашения, чье C4 принадлежит другому субъекту, возвращается `ErrConsentInvitationTaken`. - Гонка очистки. Очистка проверяет строки согласий в снимке своего запроса. Согласие, зафиксированное для аккаунта-кандидата после этого снимка, но до блокировки аккаунта, нарушает ограничивающий внешний ключ в конце запроса (SQLSTATE 23001); адаптер возвращает его как `ErrTransactionConflict`, ничего не удаляется, а следующий запуск видит согласие. - Ограничение субъектом. Каждое чтение и отзыв принимают субъекта, а операция контракта берет его из сессии, поэтому модель чтения возвращает только собственные записи вызывающего. Ошибки адаптера сохраняют только SQLSTATE и имя ограничения, а `domain.ConsentRecord`, `ConsentGrant`, `ContactConsentGrant` и `ConsentRevocation` не показывают в выводе `fmt` и `slog` субъекта, организацию, название или поля. @@ -717,31 +717,31 @@ contact_grant относится к паре кандидат-компания ### Usecase согласий -Реализовано (TASK-063): `consent.Service` в `backend/internal/usecase/consent/`. В bootstrap он пока не подключен, потому что его не вызывает ни обработчик, ни регистрация; первый вызывающий код создаст его через `consent.NewService(transactor, clock)` с `Transactor` и часами приложения, которые получают остальные usecase. Нулевой transactor или часы вызывают панику при создании, поэтому ошибка сборки видна при старте, а не при первой выдаче. +Реализовано: `consent.Service` в `backend/internal/usecase/consent/`. В bootstrap он пока не подключен, потому что его не вызывает ни обработчик, ни регистрация; первый вызывающий код создаст его через `consent.NewService(transactor, clock)` с `Transactor` и часами приложения, которые получают остальные usecase. Нулевой transactor или часы вызывают панику при создании, поэтому ошибка сборки видна при старте, а не при первой выдаче. -- Точки входа фиксируют источник. `GrantAtRegistration(ctx, repositories, subjectID, version)` записывает C1 с источником `registration`; `GrantInSettings(ctx, repositories, SettingsGrantInput)` записывает C1, C2, C3 или C5 с источником `consent_settings`. Ни одна не принимает источник или время, поэтому обработчик не может взять их от клиента. `repositories` - это `outbound.ConsentRepositories`: если передать `UnitOfWork` бизнес-операции, выдача фиксируется или откатывается вместе с ней. Регистрация (TASK-053) создает аккаунт и записывает C1 в одной транзакции только по ID субъекта, поэтому сессия не нужна. `GrantInSettingsInNewTransaction` открывает собственную транзакцию для выдачи вне другой операции и повторяет `ErrTransactionConflict` до трех попыток всего с короткой случайной паузой (10 мс плюс до 10 мс) между ними; это безопасно, потому что повтор идемпотентен, а пауза прерывается сразу при отмене контекста. +- Точки входа фиксируют источник. `GrantAtRegistration(ctx, repositories, subjectID, version)` записывает C1 с источником `registration`; `GrantInSettings(ctx, repositories, SettingsGrantInput)` записывает C1, C2, C3 или C5 с источником `consent_settings`. Ни одна не принимает источник или время, поэтому обработчик не может взять их от клиента. `repositories` - это `outbound.ConsentRepositories`: если передать `UnitOfWork` бизнес-операции, выдача фиксируется или откатывается вместе с ней. Регистрация создает аккаунт и записывает C1 в одной транзакции только по ID субъекта, поэтому сессия не нужна. `GrantInSettingsInNewTransaction` открывает собственную транзакцию для выдачи вне другой операции и повторяет `ErrTransactionConflict` до трех попыток всего с короткой случайной паузой (10 мс плюс до 10 мс) между ними; это безопасно, потому что повтор идемпотентен, а пауза прерывается сразу при отмене контекста. - Порядок при повторной регистрации. Для неподтвержденного аккаунта, который регистрируется снова, вызывайте `GrantAtRegistration` строго после `UserRepository.UpdateRegistration` в той же транзакции. `UpdateRegistration` удаляет регистрационное C1 прежнего регистранта, а выдача, выполненная до него, нашла бы эту запись, вернула ее с `Created` false и после удаления оставила бы аккаунт без C1. Интеграционный тест показывает оба порядка. -- Проверка версии до ветвления по email. `CheckTextVersion(ctx, repositories, purpose, version)` возвращает актуальный текст, если `version` актуальна, а иначе завершается как выдача, ничего не записывая. Регистрация (TASK-053) обязана вызвать ее с C1 и присланной версией до ветвления на новый или существующий email; иначе устаревшая версия отклонялась бы только для новых адресов, и разница выдала бы, какие аккаунты существуют. +- Проверка версии до ветвления по email. `CheckTextVersion(ctx, repositories, purpose, version)` возвращает актуальный текст, если `version` актуальна, а иначе завершается как выдача, ничего не записывая. Регистрация обязана вызвать ее с C1 и присланной версией до ветвления на новый или существующий email; иначе устаревшая версия отклонялась бы только для новых адресов, и разница выдала бы, какие аккаунты существуют. - Только актуальный текст. Выдача читает `ConsentTexts().Current` на время приложения и отклоняет любую другую версию ошибкой `*StaleConsentTextError`, которая совпадает с `ErrStaleConsentText` и содержит цель, запрошенную и актуальную версии, поэтому обработчик может сопоставить ее одному коду problem и показать новый текст. Устаревшая версия, версия, которая запланирована, но еще не опубликована, и версия, которой никогда не было, считаются устаревшими. Журнал принимает любую опубликованную версию, поэтому именно эта проверка не пускает выдачу устаревшего текста. Проверка и вставка не блокируются от публикации между ними: тексты публикуют миграции, а выдача, назвавшая актуальный текст на момент проверки, допустима. - Серверное время. Во входе нет поля времени. Выдача берет одно чтение внедренных часов для проверки и для времени записи; клиент не выбирает время. База по-прежнему отклоняет версию, опубликованную после этого времени. - Идемпотентность. Повтор того же субъекта, цели и актуальной версии возвращает существующую неотозванную запись с `Created` false, сохраняет ее первое время, ничего не записывает и не прерывает внешнюю транзакцию. Выдача после отзыва - новая запись. Повтор с более старой версией после публикации нового текста - не повтор, а устаревшая версия: субъект должен увидеть новый текст, а в журнале остается одна запись. -- C4 только через scope. `GrantInSettings` отклоняет C4 ошибкой `ErrScopedConsentRequired`, ничего не прочитав. `GrantContact(ctx, repositories, input)` - явно ограниченная операция для принятия приглашения (TASK-201): вход содержит организацию и показанное название, набор полей, приглашение, версию условий приглашения и версию текста C4. Она проверяет, что текст C4 актуален, поручает `domain.NewContactConsentGrant` посчитать хэш показанного текста и вызывает `ConsentLedger().GrantContact` в транзакции вызывающего кода. Повтор того же субъекта и приглашения возвращает существующую запись с `Created` false; scope сравнивает вызывающий код. Проверка текста идет первой, поэтому повтор после публикации нового текста C4 считается устаревшим; принятие, которое хочет ответить на такой повтор прежним результатом, должно найти свою запись до вызова. -- C3 можно не давать. Цели независимы: ни одна выдача не требует, не подразумевает и не меняет другую, и ни один путь кода не требует активного C3 для профиля, ручного пути оценки или другой функции. У субъекта без C3 нет записи C3, и `Current` возвращает для него `ErrConsentNotFound`; это не ошибочное состояние аккаунта. Код, который читает C3 (запрос ручной оценки TASK-315, отзыв TASK-064), считает отсутствие записи состоянием "не дано" и оставляет ручной путь доступным. -- Отзыва здесь нет. `Revoke` остается на порте журнала, а TASK-064 вызывает его вместе с последующими эффектами и событиями outbox в одной транзакции. -- Ошибки сохраняют идентичность: устаревшая версия, `ErrScopedConsentRequired`, `ErrUserNotFound`, `ErrConsentTextNotFound` (у цели нет опубликованного текста), `ErrConsentInvitationTaken`, `domain.ErrInvalidConsent` и `domain.ErrInvalidConsentText`. Действия требует `outbound.ErrTransactionConflict`: журнал возвращает его, не прерывая транзакцию, когда запись повтора была отозвана между вставкой и выборкой. Вызывающий код внутри `UnitOfWork` обязан вернуть эту ошибку, откатить транзакцию и повторить всю операцию; `GrantInSettingsInNewTransaction` делает это сам. Сопоставление остальных ошибок с кодами problem - дело обработчиков (TASK-064, TASK-053, TASK-201). -- Демо-тексты требуют проверки перед выпуском. Тексты, которые публикует миграция, имеют вид `demo`: синтетические, без юридической проверки. Usecase не отличает их от текстов оператора, поэтому установка, принимающая реальные данные, записала бы согласие на демо-текст. До приема реальных данных (PRD 7.3) проверка перед выпуском должна убедиться, что актуальный текст каждой цели имеет вид `operator`; владелец - проверка перед выпуском или TASK-064, и ни той, ни другой пока нет. +- C4 только через scope. `GrantInSettings` отклоняет C4 ошибкой `ErrScopedConsentRequired`, ничего не прочитав. `GrantContact(ctx, repositories, input)` - явно ограниченная операция для принятия приглашения: вход содержит организацию и показанное название, набор полей, приглашение, версию условий приглашения и версию текста C4. Она проверяет, что текст C4 актуален, поручает `domain.NewContactConsentGrant` посчитать хэш показанного текста и вызывает `ConsentLedger().GrantContact` в транзакции вызывающего кода. Повтор того же субъекта и приглашения возвращает существующую запись с `Created` false; scope сравнивает вызывающий код. Проверка текста идет первой, поэтому повтор после публикации нового текста C4 считается устаревшим; принятие, которое хочет ответить на такой повтор прежним результатом, должно найти свою запись до вызова. +- C3 можно не давать. Цели независимы: ни одна выдача не требует, не подразумевает и не меняет другую, и ни один путь кода не требует активного C3 для профиля, ручного пути оценки или другой функции. У субъекта без C3 нет записи C3, и `Current` возвращает для него `ErrConsentNotFound`; это не ошибочное состояние аккаунта. Код, который читает C3 (запрос ручной оценки, отзыв согласия), считает отсутствие записи состоянием "не дано" и оставляет ручной путь доступным. +- Отзыва здесь нет. `Revoke` остается на порте журнала, а отзыв согласий должен вызывать его вместе с последующими эффектами и событиями outbox в одной транзакции. +- Ошибки сохраняют идентичность: устаревшая версия, `ErrScopedConsentRequired`, `ErrUserNotFound`, `ErrConsentTextNotFound` (у цели нет опубликованного текста), `ErrConsentInvitationTaken`, `domain.ErrInvalidConsent` и `domain.ErrInvalidConsentText`. Действия требует `outbound.ErrTransactionConflict`: журнал возвращает его, не прерывая транзакцию, когда запись повтора была отозвана между вставкой и выборкой. Вызывающий код внутри `UnitOfWork` обязан вернуть эту ошибку, откатить транзакцию и повторить всю операцию; `GrantInSettingsInNewTransaction` делает это сам. Сопоставление остальных ошибок с кодами problem - дело обработчиков. +- Демо-тексты требуют проверки перед выпуском. Тексты, которые публикует миграция, имеют вид `demo`: синтетические, без юридической проверки. Usecase не отличает их от текстов оператора, поэтому установка, принимающая реальные данные, записала бы согласие на демо-текст. До приема реальных данных (PRD 7.3) проверка перед выпуском должна убедиться, что актуальный текст каждой цели имеет вид `operator`; владелец - проверка перед выпуском или отзыв согласий, и ни той, ни другой пока нет. ### Регистрация и повторная отправка подтверждения -Реализовано (TASK-053): `RegisterAccount` и `ResendEmailVerification` обслуживает `backend/internal/usecase/identity/register.go` (`identity.Registration`) за обработчиком `backend/internal/adapter/primary/http/v1/identity.go`. Без `DATABASE_URL` обе операции по-прежнему отвечают 501. Роутер подключает `middleware.ClientIP` с `TRUSTED_PROXY_CIDRS`. +Реализовано: `RegisterAccount` и `ResendEmailVerification` обслуживает `backend/internal/usecase/identity/register.go` (`identity.Registration`) за обработчиком `backend/internal/adapter/primary/http/v1/identity.go`. Без `DATABASE_URL` обе операции по-прежнему отвечают 501. Роутер подключает `middleware.ClientIP` с `TRUSTED_PROXY_CIDRS`. Одна транзакция. Новый адрес создает аккаунт (сценарий и первый `onboarding_step` сценария), запись C1 (`GrantAtRegistration`, текущая версия и хеш текста, источник `registration`), SHA-256 хеш одноразового токена, привязанного к версии регистрации, и доставку подтверждения (`ServiceMailer.EnqueueVerification`); отправляет ее позже воркер отправки через почтовый транспорт. C4 и любая другая цель никогда не записываются: тело принимает только C1. Повторная регистрация неподтвержденного адреса соблюдает порядок блокировок репозиториев identity (аннулировать токены, затем `AdvanceRegistration`, затем новая C1). Уже подтвержденный адрес ничего не меняет и ничего не получает: уведомление "у вас уже есть аккаунт" не реализовано, потому что любое письмо на подтвержденный адрес требует своего шаблона и своего лимита, а молчание не раскрывает аккаунт. Отложенные учетные данные (защита от pre-hijack). Каждая регистрация, первая и каждая повторная, хранит хеш пароля, сценарий и первый шаг онбординга на своем токене подтверждения (столбцы `pending_*` таблицы `email_tokens`, миграция 00014). Повторная регистрация неподтвержденного адреса никогда не меняет учетные данные, сценарий и шаг онбординга строки `users`: `UserRepository.AdvanceRegistration` только увеличивает версию регистрации и время регистрации (и удаляет C1 прежней регистрации), а новый токен несет новые отложенные данные. Повторная отправка копирует отложенные данные новейшего токена регистрации. `password_hash`, `scenario` и `onboarding_step` строки неподтвержденного аккаунта не авторитетны, пока подтверждение не применит отложенные данные нажатого токена: в них значения первого регистранта лишь потому, что столбцы обязательны, и никакой код не вправе по ним аутентифицировать или им доверять (см. комментарий к `domain.User`). Аннулирование токена (`InvalidateActive`) очищает его столбцы `pending_*`, а CHECK не дает аннулированному токену хранить отложенный хеш. Повторная отправка, не нашедшая отложенных данных регистрации, ничего не выпускает. Требования для передачи следующим задачам: -- TASK-054 (`ConfirmEmail`): подтверждение токена применяет отложенные данные нажатого токена, и только их, к строке аккаунта в транзакции подтверждения (хеш пароля, сценарий, шаг онбординга) и обязано требовать пароль этой регистрации, чтобы подтвердить токен с отложенными данными, проверяя его по отложенному хешу токена. Тогда жертва, перешедшая по ссылке злоумышленника, не может принять его пароль, а злоумышленник не может подтвердить токен жертвы. Поля пароля в `EmailVerificationRequest` сегодня нет; его добавление - изменение контракта в TASK-054, здесь не делается. Описание `RegisterAccount` в контракте по-прежнему говорит, что повторная регистрация заменяет хеш пароля аккаунта; TASK-054 исправляет его вместе с этим изменением. -- TASK-054 дополнительно: тесты обоих порядков (злоумышленник регистрируется первым, жертва вторым, и наоборот), показывающие, что владелец никогда не получает пароль, который не выбирал; требовать, чтобы запись C1 существовала и относилась к версии регистрации подтверждаемого токена; отклонять токен без отложенных данных, без устаревшего пути в обход пароля; обнулять столбцы `pending_*` токена при его расходовании. -- TASK-055 (вход): неподтвержденный аккаунт никогда не входит. Вход отвечает как при неверном пароле (или `email_not_verified` только там, где это разрешает контракт) и не сравнивает пароль со строкой неподтвержденного аккаунта или с отложенными данными. +- Подтверждение почты (`ConfirmEmail`): подтверждение токена применяет отложенные данные нажатого токена, и только их, к строке аккаунта в транзакции подтверждения (хеш пароля, сценарий, шаг онбординга) и обязано требовать пароль этой регистрации, чтобы подтвердить токен с отложенными данными, проверяя его по отложенному хешу токена. Тогда жертва, перешедшая по ссылке злоумышленника, не может принять его пароль, а злоумышленник не может подтвердить токен жертвы. Поля пароля в `EmailVerificationRequest` сегодня нет; его добавление - изменение контракта подтверждения почты, здесь не делается. Описание `RegisterAccount` в контракте по-прежнему говорит, что повторная регистрация заменяет хеш пароля аккаунта; при реализации подтверждения почты нужно исправить его вместе с этим изменением. +- Для подтверждения почты также нужны: тесты обоих порядков (злоумышленник регистрируется первым, жертва вторым, и наоборот), показывающие, что владелец никогда не получает пароль, который не выбирал; требовать, чтобы запись C1 существовала и относилась к версии регистрации подтверждаемого токена; отклонять токен без отложенных данных, без устаревшего пути в обход пароля; обнулять столбцы `pending_*` токена при его расходовании. +- Вход: неподтвержденный аккаунт никогда не входит. Вход отвечает как при неверном пароле (или `email_not_verified` только там, где это разрешает контракт) и не сравнивает пароль со строкой неподтвержденного аккаунта или с отложенными данными. Порядок проверок регистрации: валидация всего тела и версии текста C1, проверка воспроизведения, лимит, хеш пароля (в каждой ветке, до чтения аккаунта), транзакция. Ошибка валидации (400) не зависит от хранимых аккаунтов и не расходует лимит. @@ -759,7 +759,7 @@ contact_grant относится к паре кандидат-компания ### Организации и членства -Реализовано как хранение, порты и исходный контракт (TASK-077): миграция `backend/db/migrations/00010_create_organizations.sql`, запросы в `backend/db/queries/organizations.sql`, доменные типы в `backend/internal/domain/organization.go` и `membership.go`, порты в `backend/internal/port/outbound/organizations.go`, адаптер на sqlc в `backend/internal/adapter/secondary/postgres/organizations.go`, а также `ListMyOrganizations`, `CreateOrganization`, `GetOrganization` и `UpdateOrganization` в публичном контракте ([api/README.md](../../api/README.md#организации)). Usecase создания, чтения и обновления с обработчиками (TASK-078) и серверные проверки контекста и членства для каждой tenant-операции (TASK-079) запланированы; до этого операции отвечают 401 или 501, а bootstrap не вызывает репозитории. Реализованы только хранение и его ограничения. +Реализовано как хранение, порты и исходный контракт: миграция `backend/db/migrations/00010_create_organizations.sql`, запросы в `backend/db/queries/organizations.sql`, доменные типы в `backend/internal/domain/organization.go` и `membership.go`, порты в `backend/internal/port/outbound/organizations.go`, адаптер на sqlc в `backend/internal/adapter/secondary/postgres/organizations.go`, а также `ListMyOrganizations`, `CreateOrganization`, `GetOrganization` и `UpdateOrganization` в публичном контракте ([api/README.md](../../api/README.md#организации)). Usecase создания, чтения и обновления с обработчиками и серверные проверки контекста и членства для каждой tenant-операции запланированы; до этого операции отвечают 401 или 501, а bootstrap не вызывает репозитории. Реализованы только хранение и его ограничения. Таблицы: @@ -769,13 +769,13 @@ contact_grant относится к паре кандидат-компания Решения: -- Активный контекст. Это не атрибут серверной сессии. Организация - это `org_id` в пути, а сервер выводит право из активного членства на каждом запросе, поэтому удаление, приостановка или выход закрывают следующее чтение без чего-либо, что нужно сбрасывать. `ListMyOrganizations` - справочник, из которого клиент выбирает; запоминание последнего выбора - удобство браузера. Решение следует TASK-079 (контекст берется только из активных членств вызывающего, а прекращенное членство сразу закрывает чтение) и TASK-085 (переключение очищает клиентские запросы с областью организации). -- Роль и состояние только в членстве. `OrganizationRole` - `owner`, `recruiter`, `hiring_manager` или `technical_expert` (2.2, Q3 и матрица FR07 в PRD), а `MembershipState` - `active`, `suspended`, `removed` или `left`; каждое задано CHECK, а не enum PostgreSQL, поэтому новое значение - изменение ограничения в миграции. Состояния `invited` нет: в 6.4 PRD `MemberInvite` - отдельная сущность, приглашение на email, у которого еще может не быть аккаунта, а строка членства появляется, когда владелец адреса его принимает (TASK-081, TASK-082). В `organizations` нет столбца роли, владельца или участника (интеграционный тест читает каталог, чтобы это доказать), а в `Organization`, `OrganizationCreate` и `OrganizationUpdate` нет такого поля. Компанией управляет только владелец (`OrganizationRole.CanManageOrganization`); остальная матрица применяется операциями, которыми она управляет, а в MVP остальные роли ничего не дают (TASK-083, TASK-463). -- Уровень проверки. `verification_level` - от `e0` до `e3` с `verification_basis` (`confirmed_email`, `corporate_domain`, `requisites_and_authority`, `manual_review`, `partner_status`), а один CHECK связывает каждый уровень с его основаниями. Столбцы отделены от профиля: `UpdateOrganizationProfile` никогда их не называет, `domain.NewOrganization` не может выбрать уровень и начинает каждую организацию с `e0` на основании `confirmed_email`, `Organization.ApplyProfile` сохраняет проверку, а в контракте нет операции или поля запроса, которые ее задают. Тест обновляет профиль после того, как процесс сдвинул уровень, и проверяет, что он остается. E1-E3 задаются процессами проверки, которых еще нет; TASK-086 добавляет E0/E1 с доказательствами, областью действия и историей только на добавление и будет обновлять эти столбцы вместе со строкой истории, а сначала обязан записать историю из текущей строки каждой существующей организации (уровень, основание и время как сохранены), чтобы в истории не было разрыва до первого процесса. `OrganizationVerificationLevel.QuotaTier` сопоставляет `e0`-`e2` ступеням квот продуктовой политики и не имеет ступени для `e3`, которому PRD отводит отдельную политику (ступень читает TASK-087 и обязан отказывать по умолчанию для организации с `e3`: квота не выдается, действие отклоняется, возврата на другую ступень нет). -- У организации есть владелец. Отложенный constraint trigger (`organizations_owner_required`, SQLSTATE 23514) при фиксации отказывает организации без членства `owner` в состоянии `active`, поэтому создание организации без владельца падает, каким бы кодом ее ни вставили, а `CreateWithOwner` сохраняет организацию, представителей и владельца в одной транзакции. Удаление или понижение последнего владельца позже - правило управления участниками (TASK-084), а не этого ограничения, которое иначе блокировало бы решение платформы о недобросовестной организации. -- Обновление. `UpdateProfile` - один оператор, который применяется только когда сохраненная версия равна версии, прочитанной вызывающим, и увеличивает ее на единицу. Тот же оператор требует активного членства исполнителя с управляющей ролью (роли берутся из `domain.ManagerRoles`, а не из SQL), поэтому членство, закончившееся после чтения вызывающего, все равно останавливает запись. Если оператор ничего не нашел, адаптер читает членство и отвечает `ErrOrganizationNotFound` (неизвестная организация или нет активного членства), `ErrOrganizationManagerRequired` или `ErrOrganizationVersionConflict` в этом порядке, поэтому устаревшая версия ничего не сообщает постороннему. Затем список представителей заменяется в той же транзакции под блокировкой строки обновления. Оператор блокирует строку организации (`FOR UPDATE`), а затем строку членства исполнителя `FOR SHARE`, поэтому отзыв, зафиксированный, пока оператор ждет блокировку членства, проверяется заново и останавливает запись (интеграционный тест держит отзыв открытым, ставит обновление за ним в очередь и фиксирует отзыв). Порядок блокировок у каждого писателя: сначала организации, затем членства; управление участниками TASK-084, которое меняет членство и организацию вместе, и tenant-репозиторий TASK-079 обязаны брать блокировки в этом порядке, иначе две транзакции могут взаимно заблокироваться. -- Внешние ключи и удаление. `memberships` ограничивает удаление организации и аккаунта, поэтому аккаунт с членствами нельзя удалить, пока процедура их не завершит, так же как журнал согласий ограничивает аккаунт. Приложение никогда не удаляет организацию. Журнал согласий пока не ссылается на `organizations`: `consent_records.organization_id` остается обычным столбцом со снимком названия рядом. Ключ сейчас заставил бы тесты журнала TASK-062 и TASK-063 создавать настоящие организации, а та же миграция должна добавить ключ `invitation_id`, которому нужна таблица приглашений; оба появятся с миграцией, создающей записи приглашений (TASK-198), вместе с ключами потребностей (TASK-179). Все они `ON DELETE RESTRICT`, поэтому организацию с историей согласий, потребностями или приглашениями нельзя удалить, что и является задуманной защитой доказательств согласия (7.3 в PRD). -- Приватность. Контакты - публичные каналы компании; контракт и домен не принимают личных контактов сотрудника, а за содержимое отвечает владелец. Имена представителей - персональные данные сотрудников: `OrganizationRepresentative` прячет поля за указателем и скрывает себя в выводе `fmt` и `slog`, `Organization` логирует только идентификатор, версию и уровень, а ошибки адаптера хранят SQLSTATE и имя ограничения без строки с ошибкой. Сайт только хранится: сервер никогда не обращается по его адресу, а будущая функция, которая это делает, обязана сама разрешить адрес и отказать приватным диапазонам. `StoredRepresentative`, `OrganizationRepresentativeInput`, `OrganizationProfileInput` и сгенерированные sqlc-структуры параметров этого репозитория содержат имена и никогда не логируются. Хранилище идемпотентности `CreateOrganization` (TASK-078) держит сохраненный ответ 201 24 часа, а в нем имена представителей: хранилище обязано не пускать его в логи и метрики, защищать как остальные персональные данные и удалять по окончании окна повтора; отпечаток запроса должен быть хешем, а не телом. Карточку кандидата видит только кандидат, получивший приглашение от организации, и ее `representatives` может отсутствовать. Открытые вопросы (публикация имен представителей, таксономия сферы) и блокирующий вопрос о лимите организаций на аккаунт, который PRD не задает и без которого аккаунт умножает квоты созданием организаций (TASK-078 и TASK-087 нужно решение владельца, а подготовленный механизм - 409 `state_conflict` при создании), в [api/README.md](../../api/README.md#организации). +- Активный контекст. Это не атрибут серверной сессии. Организация - это `org_id` в пути, а сервер выводит право из активного членства на каждом запросе, поэтому удаление, приостановка или выход закрывают следующее чтение без чего-либо, что нужно сбрасывать. `ListMyOrganizations` - справочник, из которого клиент выбирает; запоминание последнего выбора - удобство браузера. Контекст берется только из активных членств вызывающего, а прекращенное членство сразу закрывает чтение. Переключение очищает клиентские запросы с областью организации. +- Роль и состояние только в членстве. `OrganizationRole` - `owner`, `recruiter`, `hiring_manager` или `technical_expert` (2.2, Q3 и матрица FR07 в PRD), а `MembershipState` - `active`, `suspended`, `removed` или `left`; каждое задано CHECK, а не enum PostgreSQL, поэтому новое значение - изменение ограничения в миграции. Состояния `invited` нет: в 6.4 PRD `MemberInvite` - отдельная сущность, приглашение на email, у которого еще может не быть аккаунта, а строка членства появляется, когда владелец адреса его принимает. В `organizations` нет столбца роли, владельца или участника (интеграционный тест читает каталог, чтобы это доказать), а в `Organization`, `OrganizationCreate` и `OrganizationUpdate` нет такого поля. Компанией управляет только владелец (`OrganizationRole.CanManageOrganization`); остальная матрица применяется операциями, которыми она управляет, а в MVP остальные роли ничего не дают. +- Уровень проверки. `verification_level` - от `e0` до `e3` с `verification_basis` (`confirmed_email`, `corporate_domain`, `requisites_and_authority`, `manual_review`, `partner_status`), а один CHECK связывает каждый уровень с его основаниями. Столбцы отделены от профиля: `UpdateOrganizationProfile` никогда их не называет, `domain.NewOrganization` не может выбрать уровень и начинает каждую организацию с `e0` на основании `confirmed_email`, `Organization.ApplyProfile` сохраняет проверку, а в контракте нет операции или поля запроса, которые ее задают. Тест обновляет профиль после того, как процесс сдвинул уровень, и проверяет, что он остается. E1-E3 задаются процессами проверки, которых еще нет; запланированный процесс проверки добавляет E0/E1 с доказательствами, областью действия и историей только на добавление и будет обновлять эти столбцы вместе со строкой истории, а сначала обязан записать историю из текущей строки каждой существующей организации (уровень, основание и время как сохранены), чтобы в истории не было разрыва до первого процесса. `OrganizationVerificationLevel.QuotaTier` сопоставляет `e0`-`e2` ступеням квот продуктовой политики и не имеет ступени для `e3`, которому PRD отводит отдельную политику (механизм квот читает ступень и обязан отказывать по умолчанию для организации с `e3`: квота не выдается, действие отклоняется, возврата на другую ступень нет). +- У организации есть владелец. Отложенный constraint trigger (`organizations_owner_required`, SQLSTATE 23514) при фиксации отказывает организации без членства `owner` в состоянии `active`, поэтому создание организации без владельца падает, каким бы кодом ее ни вставили, а `CreateWithOwner` сохраняет организацию, представителей и владельца в одной транзакции. Удаление или понижение последнего владельца позже - правило управления участниками, а не этого ограничения, которое иначе блокировало бы решение платформы о недобросовестной организации. +- Обновление. `UpdateProfile` - один оператор, который применяется только когда сохраненная версия равна версии, прочитанной вызывающим, и увеличивает ее на единицу. Тот же оператор требует активного членства исполнителя с управляющей ролью (роли берутся из `domain.ManagerRoles`, а не из SQL), поэтому членство, закончившееся после чтения вызывающего, все равно останавливает запись. Если оператор ничего не нашел, адаптер читает членство и отвечает `ErrOrganizationNotFound` (неизвестная организация или нет активного членства), `ErrOrganizationManagerRequired` или `ErrOrganizationVersionConflict` в этом порядке, поэтому устаревшая версия ничего не сообщает постороннему. Затем список представителей заменяется в той же транзакции под блокировкой строки обновления. Оператор блокирует строку организации (`FOR UPDATE`), а затем строку членства исполнителя `FOR SHARE`, поэтому отзыв, зафиксированный, пока оператор ждет блокировку членства, проверяется заново и останавливает запись (интеграционный тест держит отзыв открытым, ставит обновление за ним в очередь и фиксирует отзыв). Порядок блокировок у каждого писателя: сначала организации, затем членства; управление участниками, которое меняет членство и организацию вместе, и tenant-репозиторий обязаны брать блокировки в этом порядке, иначе две транзакции могут взаимно заблокироваться. +- Внешние ключи и удаление. `memberships` ограничивает удаление организации и аккаунта, поэтому аккаунт с членствами нельзя удалить, пока процедура их не завершит, так же как журнал согласий ограничивает аккаунт. Приложение никогда не удаляет организацию. Журнал согласий пока не ссылается на `organizations`: `consent_records.organization_id` остается обычным столбцом со снимком названия рядом. Ключ сейчас заставил бы тесты журнала согласий создавать настоящие организации, а та же миграция должна добавить ключ `invitation_id`, которому нужна таблица приглашений; оба появятся с миграцией, создающей записи приглашений, вместе с ключами потребностей. Все они `ON DELETE RESTRICT`, поэтому организацию с историей согласий, потребностями или приглашениями нельзя удалить, что и является задуманной защитой доказательств согласия (7.3 в PRD). +- Приватность. Контакты - публичные каналы компании; контракт и домен не принимают личных контактов сотрудника, а за содержимое отвечает владелец. Имена представителей - персональные данные сотрудников: `OrganizationRepresentative` прячет поля за указателем и скрывает себя в выводе `fmt` и `slog`, `Organization` логирует только идентификатор, версию и уровень, а ошибки адаптера хранят SQLSTATE и имя ограничения без строки с ошибкой. Сайт только хранится: сервер никогда не обращается по его адресу, а будущая функция, которая это делает, обязана сама разрешить адрес и отказать приватным диапазонам. `StoredRepresentative`, `OrganizationRepresentativeInput`, `OrganizationProfileInput` и сгенерированные sqlc-структуры параметров этого репозитория содержат имена и никогда не логируются. Хранилище идемпотентности `CreateOrganization` держит сохраненный ответ 201 24 часа, а в нем имена представителей: хранилище обязано не пускать его в логи и метрики, защищать как остальные персональные данные и удалять по окончании окна повтора; отпечаток запроса должен быть хешем, а не телом. Карточку кандидата видит только кандидат, получивший приглашение от организации, и ее `representatives` может отсутствовать. Открытые вопросы (публикация имен представителей, таксономия сферы) и блокирующий вопрос о лимите организаций на аккаунт, который PRD не задает и без которого аккаунт умножает квоты созданием организаций (для создания организаций и применения квот нужно решение владельца, а подготовленный механизм - 409 `state_conflict` при создании), в [api/README.md](../../api/README.md#организации). Что гарантируют порты (`outbound.OrganizationRepositories`, доступны только через `UnitOfWork`, потому что запись требует транзакции): @@ -785,7 +785,7 @@ contact_grant относится к паре кандидат-компания ### Профиль кандидата -Реализовано как хранение, домен и исходный контракт (TASK-066): миграция `backend/db/migrations/00013_create_candidate_profiles.sql`, запросы в `backend/db/queries/candidate.sql`, доменные типы в `backend/internal/domain/candidate.go`, схемы в `api/core/components/schemas/candidate_schemas.yml` и операции `GetMyProfile` и `SaveMyProfile` в `api/core/routes/candidate_profile.yml`. Порта, адаптера и обработчиков пока нет: операции отвечают 401 `unauthenticated`, пока сессий нет, и 501 `not_implemented` после валидации. Порт и адаптер придут с обработчиками и должны войти в `UnitOfWork`; запросы и доменное преобразование строк (`StoredClaims`, `RestoreCandidateProfile`) уже готовы и проверены интеграционным тестом. +Реализовано как хранение, домен и исходный контракт: миграция `backend/db/migrations/00013_create_candidate_profiles.sql`, запросы в `backend/db/queries/candidate.sql`, доменные типы в `backend/internal/domain/candidate.go`, схемы в `api/core/components/schemas/candidate_schemas.yml` и операции `GetMyProfile` и `SaveMyProfile` в `api/core/routes/candidate_profile.yml`. Порта, адаптера и обработчиков пока нет: операции отвечают 401 `unauthenticated`, пока сессий нет, и 501 `not_implemented` после валидации. Порт и адаптер придут с обработчиками и должны войти в `UnitOfWork`; запросы и доменное преобразование строк (`StoredClaims`, `RestoreCandidateProfile`) уже готовы и проверены интеграционным тестом. Таблицы: @@ -804,7 +804,7 @@ contact_grant относится к паре кандидат-компания ### Видимость кандидата -Реализовано как хранилище, домен и исходный контракт (TASK-088): миграция `backend/db/migrations/00015_create_candidate_privacy.sql` (номер 00014 занят записями идемпотентности задачи регистрации), запросы в `backend/db/queries/privacy.sql`, доменные типы в `backend/internal/domain/visibility.go`, схемы в `api/core/components/schemas/privacy_schemas.yml` и девять операций тега `privacy` в `api/core/routes/candidate_privacy*.yml` под `/api/v1/me/privacy` ([api/README.md](../../api/README.md#видимость-кандидата)). Порта, адаптера и обработчика еще нет: пока нет сессий, операции отвечают 401 `unauthenticated`, а после валидации - 501 `not_implemented`. Порт и адаптер появятся вместе с обработчиками и должны войти в `UnitOfWork`; запросы и доменное восстановление строк (`RestorePublication`, `RestoreSearchStatus`) готовы и покрыты интеграционным тестом. +Реализовано как хранилище, домен и исходный контракт: миграция `backend/db/migrations/00015_create_candidate_privacy.sql` (номер 00014 занят записями идемпотентности задачи регистрации), запросы в `backend/db/queries/privacy.sql`, доменные типы в `backend/internal/domain/visibility.go`, схемы в `api/core/components/schemas/privacy_schemas.yml` и девять операций тега `privacy` в `api/core/routes/candidate_privacy*.yml` под `/api/v1/me/privacy` ([api/README.md](../../api/README.md#видимость-кандидата)). Порта, адаптера и обработчика еще нет: пока нет сессий, операции отвечают 401 `unauthenticated`, а после валидации - 501 `not_implemented`. Порт и адаптер появятся вместе с обработчиками и должны войти в `UnitOfWork`; запросы и доменное восстановление строк (`RestorePublication`, `RestoreSearchStatus`) готовы и покрыты интеграционным тестом. Четыре независимых состояния, у каждого своя таблица и своя версия. Ни один оператор одной таблицы не пишет другую, а согласие C2 не копируется и не заменяется: @@ -825,20 +825,20 @@ contact_grant относится к паре кандидат-компания - История вместо области полей. Запись C2 доказывает согласие с текстом публикации, а `candidate_privacy_events` хранит то, о чем просила заметка журнала согласий: набор опубликованных полей и его изменения с временами и записью C2 за каждым. Отзыв C2 и истечение статуса вычисляются и не являются событиями. Нужна ли C2 собственная область полей как согласию по статье 10.1 152-ФЗ - по-прежнему юридический вопрос (см. журнал согласий). - Приватность. Таблицы хранят идентификаторы, коды полей карточки и времена; значений профиля, имен, контактов и файлов нет (тест перечисляет столбцы). `Publication`, `SearchStatus`, `HiddenOrganization` и `PrivacyEvent` пишут в журналы только идентификаторы, версии и виды. Ни один запрос не выбирает строку чужого аккаунта: каждый оператор ограничен `user_id`. Адаптер должен сообщать только SQLSTATE и имя ограничения, как остальные. -- Один структурный барьер для чтений со стороны организации. Представление `candidate_effective_publications` - опубликовано И держится на неотозванной записи C2. Каждое чтение от имени организации (поиск, карточка, чтение контактов: TASK-185, TASK-089, TASK-090) обязано выбирать из этого представления и добавлять `NOT EXISTS` по `candidate_hidden_organizations` для читающей организации, как это делает `ReadPublicationVisibleToOrganization`; отсутствие строки значит "читать нечего" по любой причине, поэтому организация не отличает скрывшего кандидата от неопубликованного. Прямое чтение `candidate_publications` оставлено только запросам настроек самого кандидата, а `backend/db/privacy_queries_test.go` падает, когда другой запрос в `db/queries` называет таблицу. -- Закрытие поверх отозванной C2. Закрытие поверх сохраненной строки `published`, чья C2 отозвана, - настоящее изменение: строка нормализуется в `closed`, пишется `publication_closed`, а контактные разрешения отзываются с `visibility_closed`, как при любом закрытии. Повтором закрытия считается только сохраненное состояние `closed`. Путь отзыва C2 (TASK-064) сам обязан закрыть сохраненную публикацию и отозвать контактные разрешения аккаунта в своей транзакции; вычисляемое состояние закрывает карточку сразу, но разрешения не отзывает. +- Один структурный барьер для чтений со стороны организации. Представление `candidate_effective_publications` - опубликовано И держится на неотозванной записи C2. Каждое чтение от имени организации (поиск, карточка, чтение контактов) обязано выбирать из этого представления и добавлять `NOT EXISTS` по `candidate_hidden_organizations` для читающей организации, как это делает `ReadPublicationVisibleToOrganization`; отсутствие строки значит "читать нечего" по любой причине, поэтому организация не отличает скрывшего кандидата от неопубликованного. Прямое чтение `candidate_publications` оставлено только запросам настроек самого кандидата, а `backend/db/privacy_queries_test.go` падает, когда другой запрос в `db/queries` называет таблицу. +- Закрытие поверх отозванной C2. Закрытие поверх сохраненной строки `published`, чья C2 отозвана, - настоящее изменение: строка нормализуется в `closed`, пишется `publication_closed`, а контактные разрешения отзываются с `visibility_closed`, как при любом закрытии. Повтором закрытия считается только сохраненное состояние `closed`. Путь отзыва C2 сам обязан закрыть сохраненную публикацию и отозвать контактные разрешения аккаунта в своей транзакции; вычисляемое состояние закрывает карточку сразу, но разрешения не отзывает. - Гонка публикации и отзыва. Транзакция публикации берет текущую C2 через `LockCurrentC2Record` (`SELECT ... FOR SHARE`), пишет публикацию под этой блокировкой и затем перечитывает действующее состояние `ReadCandidatePublication` в той же транзакции, чтобы построить ответ. Отметка отзыва - UPDATE той же строки, поэтому он либо фиксируется раньше (блокировка не вернет строку, публикация отклонена с 409), либо ждет фиксации публикации и закрывает карточку сразу после; интеграционный тест удерживает блокировку и доказывает оба порядка. - Подтвержденный email. Публикация, скрытие и история существуют только у аккаунтов с подтвержденным email (требование юзкейса). Очистка неподтвержденных аккаунтов (`DeleteUnverifiedUsersRegisteredBefore`) удаляет их записи согласий явно и столкнулась бы с ограничивающей ссылкой публикации на запись C2, поэтому отсутствие публикации у неподтвержденного аккаунта - требование юзкейса, а не физическая невозможность: очистка работает и для неподтвержденного аккаунта, у которого есть C2, публикация и история, и для C2, отозванной и выданной снова (это проверяет интеграционный сценарий, и он зависит от порядка применения изменяющих операторов очистки). Записи скрытия и история удаляются каскадом. - Два вида 409 `state_conflict` различаются через `errors[]`: `{in: body, pointer: /state, code: consent_required}` для публикации без действующей C2 и `{in: path, pointer: /org_id, code: limit_reached}` для 1001-й скрытой организации. Предел скрытий обеспечивает триггер под блокировкой строки аккаунта; когда вставка падает с SQLSTATE 23514 и `candidate_hidden_organizations_limit`, адаптер обязан перечитать пару перед ответом 409, потому что параллельный PUT той же пары при 999 записях мог ее создать, а идемпотентный ответ - 200; интеграционный тест запускает восемь параллельных вставок при 999 записях и ожидает ровно один успех. - Новое поле карточки - это изменение контракта и миграция. Коды перечислены в функции `candidate_card_fields_are_canonical` и в CHECK таблиц публикации и событий, а также в enum `CardField`, `domain.CardField` и построителе карточки. -Содержимое карточки (жесткие требования к TASK-089, который ее строит): +Содержимое карточки (жесткие требования к ее построителю): - В карточку попадают только значения, которые кандидат подтвердил; неподтвержденное предложение (статус `extracted`) и неизвестное значение не попадают никогда, что бы ни говорил набор полей. - Свободный текст (тег стека, софт-скилл, место), похожий на контакт (адрес email, номер телефона, URL или домен, ссылка Telegram, @handle), отбрасывается и не публикуется. Проверка, которую построитель обязан применять к каждому свободному тексту, - `domain.CardTextLooksLikeContact`; она ошибается в сторону отбрасывания. -- Квазиидентификаторы (редкое сочетание места, стека и опыта) и обобщение редких признаков - критерий приемки TASK-089, здесь не решаются (см. открытый вопрос в README API). +- Квазиидентификаторы (редкое сочетание места, стека и опыта) и обобщение редких признаков - критерий приемки построителя карточки, здесь не решаются (см. открытый вопрос в README API). -Анонимная карточка для организаций здесь не строится: `AnonymousCardContent` - закрытый набор свойств, которые может содержать опубликованная карточка (подтвержденные категории, стек, суммарный опыт в месяцах, софт-скиллы, место, переезд), без имени, контакта, работодателя, зарплаты и идентификатора, а контрактный тест обходит ссылки карточки и предпросмотра и падает на любой схеме профиля, контакта, согласия или организации. Карточку результата поиска организации (TASK-185) нужно строить на ней. `GetMyCardPreview` и `ListMyCardAccessHistory` только в контракте: предпросмотру нужно читать профиль, подтвержденные категории и публикацию вместе, а записи обращений пишут задачи поиска и чтения контактов, поэтому таблица для них придет с этими задачами. +Анонимная карточка для организаций здесь не строится: `AnonymousCardContent` - закрытый набор свойств, которые может содержать опубликованная карточка (подтвержденные категории, стек, суммарный опыт в месяцах, софт-скиллы, место, переезд), без имени, контакта, работодателя, зарплаты и идентификатора, а контрактный тест обходит ссылки карточки и предпросмотра и падает на любой схеме профиля, контакта, согласия или организации. Карточку результата поиска организации нужно строить на ней. `GetMyCardPreview` и `ListMyCardAccessHistory` только в контракте: предпросмотру нужно читать профиль, подтвержденные категории и публикацию вместе, а записи обращений пишут задачи поиска и чтения контактов, поэтому таблица для них придет с этими задачами. ## Frontend @@ -875,7 +875,7 @@ k3s не входит в критический путь. Его можно ра ## Метрики, телеметрия и alerts -Go экспортирует стандартные Go/process метрики и продуктовые метрики TASK-022 на внутреннем listener `/metrics`, вне `/api/v1`: +Go экспортирует стандартные Go/process метрики и продуктовые метрики на внутреннем listener `/metrics`, вне `/api/v1`: - API: `lincodex_http_requests_total{method,route,status}`, `lincodex_http_request_duration_seconds{method,route,status_class}` и `lincodex_http_problems_total{route,code}`. `route` - шаблон маршрута chi для операционных маршрутов, а под `/api/v1` - шаблон пути OpenAPI найденной операции, например `/api/v1/me/invitations/{invitation_id}`; router находит его через `FindPath` сгенерированного сервера. Путь или метод без операции сохраняет шаблон монтирования `/api/v1/*` или `/api/*`, а путь вне всех маршрутов получает `unmatched`. `status_class` - от `1xx` до `5xx`. `code` - код problem по RFC 9457: `problem.New` записывает его из закрытого каталога через пакет `observe` уровня запроса (`adapter/primary/http/observe/`), middleware учитывает его только для ответа 4xx или 5xx, а адаптер считает код вне своего зеркального списка как `other`. Ошибка без тела problem, например 503 от `/readyz`, учитывается только по статусу. Журнал запросов (`middleware.RequestLog`, заменяет logger из go-httpkit) использует тот же шаблон маршрута и пишет request ID, метод, статус и класс, код problem, задержку, размер ответа и число параметров query, но никогда не пишет исходный путь, ключ или значение query, заголовок, адрес клиента и user agent; `/healthz` и `/readyz` не журналируются. - Outbox и события: метрики relay, обработчиков и заданий по сроку описаны в разделах [Relay outbox](#relay-outbox), [Обработчики событий](#обработчики-событий) и [Задания по сроку](#задания-по-сроку). Отставание outbox показывает `lincodex_outbox_relay_oldest_pending_age_seconds`. diff --git a/docs/ru/DEPLOY.md b/docs/ru/DEPLOY.md index 25e477c..1c9ed28 100644 --- a/docs/ru/DEPLOY.md +++ b/docs/ru/DEPLOY.md @@ -235,7 +235,7 @@ Worker захватит его в течение одного интервала Backend отправляет почту через порт `MailSender`. `EMAIL_PROVIDER` выбирает ровно один транспорт: `resend` (HTTP API Resend, основной провайдер рабочего стенда), `smtp` (отдельный SMTP relay) или `disabled`. Значения по умолчанию нет, и запасного варианта тоже нет: если выбранный транспорт не может запуститься, backend останавливается, а не переключается на другой. Настройки невыбранных транспортов не читаются. -Текущее состояние: в этой сборке есть транспорты `disabled` и `resend`. С `smtp` backend проверяет настройки SMTP и затем завершается с ошибкой `EMAIL_PROVIDER=smtp: mail transport is not available in this build`; в Compose `restart: unless-stopped` будет перезапускать контейнер снова и снова. SMTP вне MVP. `.env.example` и `make -C deploy smoke` используют `disabled`, поэтому локальному запуску ключ не нужен; рабочий стенд явно задает `EMAIL_PROVIDER=resend` и `RESEND_API_KEY`. Процесс backend запускает worker отправки служебной почты identity (подтверждение почты и сброс пароля), когда `EMAIL_PROVIDER` равен `resend`; см. [Отправка служебной почты](#отправка-служебной-почты). Ни один сценарий аккаунта пока не создает такие письма, а продуктовые уведомления сохраняются как доставки, но не отправляются до TASK-462, так что боевой стенд сегодня не отправляет ни одного письма. +Текущее состояние: в этой сборке есть транспорты `disabled` и `resend`. С `smtp` backend проверяет настройки SMTP и затем завершается с ошибкой `EMAIL_PROVIDER=smtp: mail transport is not available in this build`; в Compose `restart: unless-stopped` будет перезапускать контейнер снова и снова. SMTP вне MVP. `.env.example` и `make -C deploy smoke` используют `disabled`, поэтому локальному запуску ключ не нужен; рабочий стенд явно задает `EMAIL_PROVIDER=resend` и `RESEND_API_KEY`. Процесс backend запускает worker отправки служебной почты identity (подтверждение почты и сброс пароля), когда `EMAIL_PROVIDER` равен `resend`; см. [Отправка служебной почты](#отправка-служебной-почты). Ни один сценарий аккаунта пока не создает такие письма, а продуктовые уведомления сохраняются как доставки, но не отправляются до реализации отправки продуктовых уведомлений, так что боевой стенд сегодня не отправляет ни одного письма. `resend` отправляет каждое письмо одним запросом к `https://api.resend.com/emails`. Создание транспорта не обращается к сети, поэтому при запуске не проверяются ни ключ, ни домен отправителя; неверный ключ или неподтвержденный домен в `EMAIL_FROM` проявятся как отказ при отправке. Одну попытку ограничивает `EMAIL_TIMEOUT`. Транспорт не следует редиректам, никогда не повторяет запрос и ничего не логирует; повторы, backoff, темп при rate limit и учет результатов относятся к запланированному слою доставки, а ожидание сброса дневной или месячной квоты решает шлюз квот (см. [Квоты почты](#квоты-почты)). Каждый запрос несет ключ идемпотентности письма, и Resend 24 часа не отправляет повторно письмо с тем же ключом и телом; после этого окна повтор может отправить письмо дважды. Успех значит, что Resend принял запрос и вернул идентификатор письма, а не что письмо доставлено или прочитано. Таймаут, потерянный ответ после отправки запроса или ошибка 500 от Resend дают `unknown` (`delivery_uncertain`), а не ошибку. Процесс backend учитывает стандартные переменные `HTTPS_PROXY` и `NO_PROXY`, но сервис backend в Compose их не передает, поэтому под Compose запрос идет в Resend напрямую; если стенду нужен прокси для исходящего трафика, добавьте эти переменные в `environment` сервиса backend. Полное соответствие ответов описано в [ARCHITECTURE.md](ARCHITECTURE.md#почтовый-транспорт). @@ -260,18 +260,18 @@ Compose передает эти переменные из корневого `.e ### Доставки писем -Запрос уведомления - строка `mail_requests`, пока обработчик `notification_delivery` не превратит его в строку `deliveries` и не удалит; модель описана в [ARCHITECTURE.md](ARCHITECTURE.md#доставки-писем). Миграция 00006 создает `mail_requests`, `deliveries` и `delivery_attempts` при запуске; настройки для этого не нужны. Доставки уведомлений пока только сохраняются: worker отправки берет только письма подтверждения и сброса пароля, поэтому уведомление остается в `pending`, пока TASK-462 не подключит продуктовые уведомления. Уведомления создаются только для аккаунтов с подтвержденным адресом; запрос на неподтвержденный адрес отбрасывается со строкой в логе. +Запрос уведомления - строка `mail_requests`, пока обработчик `notification_delivery` не превратит его в строку `deliveries` и не удалит; модель описана в [ARCHITECTURE.md](ARCHITECTURE.md#доставки-писем). Миграция 00006 создает `mail_requests`, `deliveries` и `delivery_attempts` при запуске; настройки для этого не нужны. Доставки уведомлений пока только сохраняются: worker отправки берет только письма подтверждения и сброса пароля, поэтому уведомление остается в `pending`, пока не реализована отправка продуктовых уведомлений. Уведомления создаются только для аккаунтов с подтвержденным адресом; запрос на неподтвержденный адрес отбрасывается со строкой в логе. - Каждая доставка закрепляется за `EMAIL_PROVIDER` и `EMAIL_ACCOUNT` в момент создания, а последующее изменение конфигурации применяется только к новым доставкам. Меняйте `EMAIL_ACCOUNT` вместе с `RESEND_API_KEY` каждый раз, когда ключ принадлежит другому аккаунту Resend, чтобы доставки, начатые под старым аккаунтом, никогда не отправлялись через новый. Служебная почта, созданная при `EMAIL_PROVIDER=disabled`, остается закрепленной за `disabled`, пока backend не запущен с транспортом: тогда worker отправки переносит ее через `Rebind` (разрешено только до первой попытки) и отправляет, если ее токен и аккаунт все еще проходят проверку. Не переносите вручную. - Строки содержат адрес получателя и сформированные тела писем, а ожидающая строка `mail_requests` - исходный текст уведомления; тела писем подтверждения почты и сброса пароля содержат действующий одноразовый токен, пока его не использовали или пока не истек срок. Относитесь к доступу на чтение к `deliveries` как к доступу к этим ссылкам и защищайте дампы и резервные копии базы так же. Срок хранения завершенных доставок пока не реализован. - Для просмотра доставок выбирайте только метаданные, например `SELECT id, kind, template_version, status, attempt_count, next_attempt_at, last_attempt_at, provider, provider_account, created_at FROM deliveries ORDER BY created_at DESC LIMIT 50` и `SELECT attempt_number, attempted_at, outcome, rejection, provider_code, status_after FROM delivery_attempts WHERE delivery_id = '' ORDER BY attempt_number`. `SELECT count(*), min(created_at) FROM mail_requests` показывает запросы, которые обработчик еще не обработал; растущее число значит, что обработчик остановлен или его события уходят в dead letters. Не выбирайте `recipient_email`, `subject`, `text_body`, `html_body` и текстовые столбцы `mail_requests` и никогда не вставляйте их в задачи и чаты. -- Без SQL внутренний endpoint /metrics показывает `lincodex_mail_deliveries{kind,status}` для каждого вида и статуса, включая нулевые, и `lincodex_mail_delivery_oldest_due_pending_age_seconds` - сколько времени самая ранняя доставка в `pending` уже ждет своего срока. Backend читает их каждые 30 секунд одним агрегатом по `deliveries`; все экземпляры сообщают одинаковые значения, поэтому агрегируйте их через `max`. Неудачное чтение сохраняет прежние значения и пишет в журнал `delivery metrics could not be read; the gauges are stale`. Уведомления остаются в `pending` до TASK-462; в просрочку они не считаются. Серия просрочки появляется только после первого успешного чтения, поэтому свежий запуск не заявляет, что ничего не просрочено; `lincodex_mail_metrics_last_success_timestamp_seconds` - Unix-время последнего чтения, в котором прочитаны все агрегаты (0 от запуска до первого такого чтения), а `LincodexMailMetricsStale` срабатывает, когда оно старше 5 минут в течение 5 минут. Alert `LincodexMailDeliveryUnknownOutcome` срабатывает, пока у какой-либо доставки неизвестный исход. `LincodexMailDeliveriesOverdue` (доставка в `pending` просрочена больше чем на 15 минут) требует еще, чтобы `lincodex_mail_sender_running` был 1 хотя бы на одном экземпляре: его экспортирует worker отправки, 1 пока цикл работает и 0 иначе, поэтому alert молчит при `EMAIL_PROVIDER=disabled` (цикл не запускается) и без трафика. Просрочка считает только служебную почту (подтверждение и сброс пароля), поэтому очередь уведомлений, которые worker не отправляет до TASK-462, его не включает. Статус `cancelled` считается наравне с остальными, а `accepted` означает принято провайдером. +- Без SQL внутренний endpoint /metrics показывает `lincodex_mail_deliveries{kind,status}` для каждого вида и статуса, включая нулевые, и `lincodex_mail_delivery_oldest_due_pending_age_seconds` - сколько времени самая ранняя доставка в `pending` уже ждет своего срока. Backend читает их каждые 30 секунд одним агрегатом по `deliveries`; все экземпляры сообщают одинаковые значения, поэтому агрегируйте их через `max`. Неудачное чтение сохраняет прежние значения и пишет в журнал `delivery metrics could not be read; the gauges are stale`. Уведомления остаются в `pending` до реализации отправки продуктовых уведомлений; в просрочку они не считаются. Серия просрочки появляется только после первого успешного чтения, поэтому свежий запуск не заявляет, что ничего не просрочено; `lincodex_mail_metrics_last_success_timestamp_seconds` - Unix-время последнего чтения, в котором прочитаны все агрегаты (0 от запуска до первого такого чтения), а `LincodexMailMetricsStale` срабатывает, когда оно старше 5 минут в течение 5 минут. Alert `LincodexMailDeliveryUnknownOutcome` срабатывает, пока у какой-либо доставки неизвестный исход. `LincodexMailDeliveriesOverdue` (доставка в `pending` просрочена больше чем на 15 минут) требует еще, чтобы `lincodex_mail_sender_running` был 1 хотя бы на одном экземпляре: его экспортирует worker отправки, 1 пока цикл работает и 0 иначе, поэтому alert молчит при `EMAIL_PROVIDER=disabled` (цикл не запускается) и без трафика. Просрочка считает только служебную почту (подтверждение и сброс пароля), поэтому очередь уведомлений, которые worker не отправляет до реализации отправки продуктовых уведомлений, его не включает. Статус `cancelled` считается наравне с остальными, а `accepted` означает принято провайдером. - Не правьте сохраненную доставку вручную: trigger отклоняет любое изменение получателя, содержимого или ключа идемпотентности и смену аккаунта провайдера после первой попытки, а история попыток отклоняет обновления. Доставка в `waiting_quota` ждет сброса квоты в `next_attempt_at`; см. [Квоты почты](#квоты-почты). Без `next_attempt_at` момент сброса неизвестен, и нужно решение оператора. - Логи называют доставку только по `delivery_id` (вместе с ID события), никогда по адресу или теме. Пропущенные запросы пишутся на уровне info: `mail request skipped because it was already handled or its account was deleted` и `notification skipped because the recipient address is not verified`. Запрос, нарушающий контракт события, становится dead letter класса `handler_rejected` обработчика `notification_delivery`; см. [Dead letters и повторный запуск](#dead-letters-и-повторный-запуск). Повторять его безопасно: ID доставки сохраняет одну доставку на запрос. ### Квоты почты -Миграция 00007 создает `mail_quota_usage` и журнал резервирований `mail_quota_reservations` при запуске; настройка не нужна. Worker отправки вызывает шлюз квот при каждой отправке (см. [Отправка служебной почты](#отправка-служебной-почты)), поэтому служебная почта считается в квоту, а уведомления - нет до TASK-462. Модель описана в [ARCHITECTURE.md](ARCHITECTURE.md#квоты-почты). +Миграция 00007 создает `mail_quota_usage` и журнал резервирований `mail_quota_reservations` при запуске; настройка не нужна. Worker отправки вызывает шлюз квот при каждой отправке (см. [Отправка служебной почты](#отправка-служебной-почты)), поэтому служебная почта считается в квоту, а уведомления - нет до реализации отправки продуктовых уведомлений. Модель описана в [ARCHITECTURE.md](ARCHITECTURE.md#квоты-почты). - Задайте `EMAIL_QUOTA_DAILY` и `EMAIL_QUOTA_MONTHLY` по тарифу аккаунта провайдера, который назван в `EMAIL_ACCOUNT`. Значения по умолчанию соответствуют Resend Free: 100 получателей за UTC-сутки и 3000 за месяц по проверке 05.10.2026. Сверьте текущую квоту аккаунта в панели Resend до запуска стенда и после любой смены тарифа. Для `smtp` задайте оба значения по лимитам relay; без них запуск завершается ошибкой. Измененное значение действует после перезапуска. - Меняйте `EMAIL_ACCOUNT` только вместе с настоящей сменой аккаунта провайдера, то есть с ключом другого аккаунта. Локальный счет ведется по метке аккаунта, поэтому переименование метки для того же аккаунта начинает счет с нуля, а у провайдера остается прежний. При запуске backend пишет в журнал `mail quota usage` с провайдером, аккаунтом, текущим расходом и лимитами суток и месяца и предупреждает, если у других меток того же провайдера есть расход в этом месяце. @@ -280,7 +280,7 @@ Compose передает эти переменные из корневого `.e - Внутренний endpoint /metrics показывает текущие окна настроенного аккаунта, которые читаются каждые 30 секунд: `lincodex_mail_quota_used_recipients`, `lincodex_mail_quota_limit_recipients` и `lincodex_mail_quota_provider_exhausted` (1 после отказа провайдера по квоте), каждая с labels `provider` и `window` (`day` или `month`). `EMAIL_ACCOUNT` не становится label, потому что его текст выбирает оператор; при `EMAIL_PROVIDER=disabled` серий квот нет. Alert `LincodexMailQuotaUsedUp` (severity info) срабатывает, пока окно исчерпано. - Варианты, пока письма ждут: дождаться сброса, для этого ничего делать не нужно; или после осознанной смены тарифа у провайдера поднять лимиты и перезапустить backend, тогда новые отправки снова допускаются, а отложенные доставки сохраняют свой `next_attempt_at`; или осознанно сменить транспорт или аккаунт (что остается закрепленным, описано в [Доставки писем](#доставки-писем)). Не уменьшайте `used_recipients` и не правьте журнал вручную, чтобы освободить отправки: у провайдера свой счет, и такие отправки он только отклонит. - `provider_exhausted_at` в строке значит, что провайдер ответил отказом по квоте, хотя по локальному счету место было. Возможные причины: аккаунт отправляет письма еще откуда-то; Resend учитывает в той же квоте полученные (входящие) письма; или настроенный лимит выше тарифа. Приведите лимиты в соответствие с тарифом. -- Месячная квота Resend следует платежному циклу аккаунта, а месяц шлюза - календарный месяц UTC. После месячного отказа доставка повторяется в начале следующего месяца UTC; если платежный цикл сбрасывается позже, этот повтор снова получит отказ и будет ждать еще месяц. Ручной повтор с записью в аудит запланирован вместе с политикой повторов (TASK-017). +- Месячная квота Resend следует платежному циклу аккаунта, а месяц шлюза - календарный месяц UTC. После месячного отказа доставка повторяется в начале следующего месяца UTC; если платежный цикл сбрасывается позже, этот повтор снова получит отказ и будет ждать еще месяц. Ручной повтор с записью в аудит запланирован вместе с политикой повторов. - Сниженный лимит действует со следующего резервирования. Во время поэтапного обновления экземпляры со старым и новым лимитом работают одновременно, и каждый проверяет лимит, с которым запущен, поэтому сниженный лимит соблюдается только после того, как все экземпляры работают с новой конфигурацией. Переключение `EMAIL_PROVIDER` на `smtp` начинает для relay отдельные счетчики с его явно заданными лимитами; доставки, закрепленные за прежним аккаунтом, шлюз отклоняет, а не отправляет без лимита. ### Отправка служебной почты @@ -291,7 +291,7 @@ Compose передает эти переменные из корневого `.e - При `EMAIL_PROVIDER=disabled` цикл не запускается, а в журнале пишется `mail sender worker is not started because EMAIL_PROVIDER is disabled; stored deliveries wait`; `lincodex_mail_sender_running` равен 0, ничего не отправляется, а сохраненная служебная почта ждет следующего запуска с транспортом. Worker никогда не крутится вхолостую: после прохода, который ничего не смог отправить, он делает паузу. - Перед отправкой worker проверяет токен и аккаунт. Доставка, которую нельзя отправлять, завершается как `cancelled` с `cancel_reason`, без попытки и без расхода квоты: `token_missing`, `token_purpose_mismatch`, `token_owner_mismatch`, `token_consumed`, `token_revoked`, `token_expired`, `account_not_current`, `recipient_mismatch`, `content_invalid` или `processing_failed`. Причины, вызванные пользователем, нормальны: пользователь запросил новую ссылку, подтвердил адрес, зарегистрировался заново или слишком долго ждал. Причины можно посмотреть так: `SELECT cancel_reason, count(*) FROM deliveries WHERE status = 'cancelled' GROUP BY cancel_reason`. Пользователь видит отмененное письмо как "не отправлено, запросите новое". - Ответы провайдера: `accepted` означает принято провайдером, а не доставлено человеку; подтверждения доставки у backend нет. Отказ "пока" (`temporary`, `rate_limited`) оставляет доставку в `pending` с более поздним `next_attempt_at`, а повтор использует тот же ключ и тело; он повторяется, пока не удастся, пока не будет отказа навсегда или пока токен не истечет и доставка не будет отменена. Постоянный отказ или отказ из-за запроса завершает ее как `rejected`: прочитайте код провайдера в `delivery_attempts.provider_code` (например `validation_error` для неподтвержденного домена отправителя или `invalid_api_key`) и устраните причину. Ответ о квоте переводит ее в `waiting_quota`; см. [Квоты почты](#квоты-почты). -- `unknown` worker никогда не повторяет. Это значит, что провайдер мог принять письмо (потерянный ответ, ответ 5xx) или что worker, отправивший его, был потерян дольше 24-часового окна идемпотентности провайдера. Найдите сообщение в журнале самого провайдера; пока срабатывает alert `LincodexMailDeliveryUnknownOutcome`. Ручной повтор с записью аудита запланирован вместе с политикой повторов (TASK-017). +- `unknown` worker никогда не повторяет. Это значит, что провайдер мог принять письмо (потерянный ответ, ответ 5xx) или что worker, отправивший его, был потерян дольше 24-часового окна идемпотентности провайдера. Найдите сообщение в журнале самого провайдера; пока срабатывает alert `LincodexMailDeliveryUnknownOutcome`. Ручной повтор с записью аудита запланирован вместе с политикой повторов. - Захваченная доставка держит lease: `SELECT id, kind, claimed_until FROM deliveries WHERE claim_owner IS NOT NULL`. Строка с давно прошедшим `claimed_until` значит, что ее worker умер; другой экземпляр подхватит ее сам. Не сбрасывайте lease вручную. - `content_invalid` и `processing_failed` - не действия пользователя: первое значит, что сохраненная строка не совпадает со своим хешем содержимого (ручная правка) или содержит сообщение, которое не принимает ни один транспорт, второе - что worker трижды подряд потерпел сбой на строке (повторы разнесены расписанием). Alert `LincodexMailCancelledBroken` срабатывает при росте; прочитайте журнал worker по `delivery_id` и осмотрите метаданные строки. Строка, которая сбоит постоянно, не блокирует остальные: она повторяется позже (`failure_count`, `next_attempt_at`), а затем отменяется. - Тела письма с токеном очищаются, когда оно принято, отклонено или отменено (ставится `body_redacted_at`), поэтому дампы и резервные копии завершенной почты с токеном токенов не содержат. Письмо в `unknown` сохраняет тело, пока оператор его не разрешит. Не копируйте тела ожидающих писем никуда. diff --git a/docs/ru/DEVELOPMENT.md b/docs/ru/DEVELOPMENT.md index 9d355ce..ec50e96 100644 --- a/docs/ru/DEVELOPMENT.md +++ b/docs/ru/DEVELOPMENT.md @@ -50,7 +50,7 @@ Frontend зависимости выбираются из актуальных s - Маршруты health и readiness. Nginx сам отвечает на `GET /healthz` и проксирует в Go только `/api/` (deploy/nginx/conf.d/app.conf). Go обслуживает `GET /healthz` (`ok`) и `GET /readyz` (`ready` или 503 `not_ready` после проверки PostgreSQL, Redis и SeaweedFS) на внутреннем порту 8080 вне OpenAPI контракта, а также `GET /api/v1/healthz` из api/core/routes/healthz.yml через ogen handler (backend/internal/adapter/primary/http). Метрики Go отдаются на порту 9090 (`METRICS_ADDR`), Prometheus читает `/metrics`. ML обслуживает `GET /healthz`, `GET /readyz` (всегда 503 `not_ready`, потому что модель не подключена) и `/metrics` (ml/src/lincodex_ml, api/ml/routes). deploy/scripts/smoke.sh проверяет `/healthz` Nginx, `/api/v1/healthz`, `/readyz` Go изнутри сети Compose, 404 для неизвестного API маршрута и то, что backend запустился с `EMAIL_PROVIDER=disabled`; ML он не запускает и писем не отправляет. - Адаптеры: PostgreSQL через pgxpool и generated запрос `SELECT 1`, runner миграций goose, применяемый при старте, transactor с записью transactional outbox, репозитории identity на sqlc для аккаунтов, email-токенов и сессий, а также версионированный репозиторий политики, который при старте заполняет демонстрационную политику; Redis через go-cachekit, SeaweedFS через S3 API. Hasher паролей Argon2id и проверка пароля `identity.Credentials` есть и покрыты тестами, но в bootstrap не подключены. Generated Go client для ML контракта есть, но в bootstrap не подключен. -- Почта: outbound порт `MailSender`, транспорты `disabled` и `resend` и выбор `EMAIL_PROVIDER` в bootstrap; `smtp` после проверки своих настроек останавливает запуск. Запросы уведомлений (`mail_requests`) превращаются в доставки (`deliveries`, `delivery_attempts`) обработчиком `notification_delivery`, но пока ничто не отправляет уведомления (TASK-462). С `resend` backend запускает worker отправки служебной почты identity (подтверждение и сброс пароля, привязанные к своим токенам, с проверкой перед отправкой, шлюзом квот и стабильным ключом идемпотентности); ни один сценарий аккаунта пока не создает такие письма. См. [DEPLOY.md](DEPLOY.md#почта) и [ARCHITECTURE.md](ARCHITECTURE.md#доставки-писем). +- Почта: outbound порт `MailSender`, транспорты `disabled` и `resend` и выбор `EMAIL_PROVIDER` в bootstrap; `smtp` после проверки своих настроек останавливает запуск. Запросы уведомлений (`mail_requests`) превращаются в доставки (`deliveries`, `delivery_attempts`) обработчиком `notification_delivery`, но пока ничто не отправляет уведомления. С `resend` backend запускает worker отправки служебной почты identity (подтверждение и сброс пароля, привязанные к своим токенам, с проверкой перед отправкой, шлюзом квот и стабильным ключом идемпотентности); ни один сценарий аккаунта пока не создает такие письма. См. [DEPLOY.md](DEPLOY.md#почта) и [ARCHITECTURE.md](ARCHITECTURE.md#доставки-писем). - OpenAPI контракты api/core/ и api/ml/ с объединением схем, bundles, lint и генерацией для Go (ogen), TypeScript (Orval) и Python (datamodel-code-generator). В SPA есть каркас интерфейса с экранами-заготовками, generated API client и MSW handlers. - Compose проекты: core (`deploy/docker/docker-compose.yml`: PostgreSQL, Redis, SeaweedFS, Kafka, backend, frontend), ML (`docker-compose.ml.yml`) и monitoring (`docker-compose.monitoring.yml`). - Kafka: один узел KRaft в core Compose проекте с listener только во внутренней сети, именованным volume, healthcheck и лимитом памяти. Backend запускает relay outbox, который создает топик `lincodex.domain.events` и публикует в него зафиксированные события outbox через producer на franz-go; см. [Relay outbox](#relay-outbox). Readiness не проверяет Kafka. Runtime обработчиков событий запускает один продуктовый обработчик - обработчик доставки писем, а продуктовые сценарии пока не создают его событие; см. [Обработчики событий](#обработчики-событий). @@ -88,7 +88,7 @@ make check не является бизнес-E2E проверкой. make verif Запланированная cookie сессии - `__Host-lincodex_session` с `Secure`, `HttpOnly` и `SameSite=Strict` (см. [api/README.md](../../api/README.md#identity-сессии-cookie-и-csrf)). Локальный стек отдает обычный HTTP. Chromium и Firefox считают `http://localhost` и `http://127.0.0.1` безопасным контекстом и сохраняют там `Secure` cookie; WebKit и Safari могут ее отклонить. Для локального входа используйте Chromium или Firefox либо локальный TLS-прокси. Проект не добавляет флаг, отключающий `Secure` или префикс `__Host-`, поэтому локальная cookie не отличается от production. -Запланированное правило Origin (TASK-056): любой небезопасный запрос (POST, PUT, PATCH, DELETE), включая публичные, например вход, должен нести `Origin` из allowlist в конфигурации backend, например origin Nginx и origin dev-сервера Vite. Сервер не сравнивает `Origin` с `Host`. Небезопасный запрос без `Origin` или с другим значением получает 403 `csrf_check_failed`. +Запланированное правило Origin: любой небезопасный запрос (POST, PUT, PATCH, DELETE), включая публичные, например вход, должен нести `Origin` из allowlist в конфигурации backend, например origin Nginx и origin dev-сервера Vite. Сервер не сравнивает `Origin` с `Host`. Небезопасный запрос без `Origin` или с другим значением получает 403 `csrf_check_failed`. ## Структура diff --git a/docs/ru/TESTING.md b/docs/ru/TESTING.md index 6b46b7c..120005e 100644 --- a/docs/ru/TESTING.md +++ b/docs/ru/TESTING.md @@ -199,7 +199,7 @@ Unit-тесты (`make -C backend test`) проверяют правила кв - Отчет при запуске: при расходе под меткой `old-label` и под настроенной меткой отчет через `postgres.MailQuotaStore` пишет расход настроенного аккаунта и предупреждает об `old-label`. - База отклоняет неизвестный вид периода, месяц, который начинается не с первого числа, отрицательный расход, неверную метку аккаунта, резервирование, у которого сутки вне его месяца, и неизвестный исход. -`TestPostgresMigrations` дополнительно проверяет, что миграция 00007 создает и удаляет `mail_quota_usage` и `mail_quota_reservations` и оставляет таблицы доставок. Набор квот не вызывает транспорт; worker, который последовательно выполняет `PrepareSend`, `Send` и `SettleSend` (TASK-016), покрыт тестами отправки служебной почты ниже. +`TestPostgresMigrations` дополнительно проверяет, что миграция 00007 создает и удаляет `mail_quota_usage` и `mail_quota_reservations` и оставляет таблицы доставок. Набор квот не вызывает транспорт; worker, который последовательно выполняет `PrepareSend`, `Send` и `SettleSend`, покрыт тестами отправки служебной почты ниже. ## Тесты отправки служебной почты @@ -264,7 +264,7 @@ Unit-тесты (`make -C backend test`) проверяют runtime задани ## Тесты продуктовых метрик -Unit-тесты (`make -C backend test`) покрывают продуктовые метрики (TASK-022). В `internal/adapter/primary/http/` запросы через настоящий router и настоящий collector получают шаблон маршрута своей операции (`/api/v1/me/invitations/{invitation_id}`, `/api/v1/me/assessment-attempts/{attempt_id}`) и никогда не получают параметр пути, адрес в пути или query string; неизвестные пути и методы сохраняют `/api/v1/*`, `/api/*` или `unmatched`; ответы problem считаются по коду (`unauthenticated`, `not_found`, `method_not_allowed`, `not_implemented`), а обычный 404 вне `/api` - нет; в выдаче нет значений, похожих на email или UUID; каждый код problem контракта сохраняет свой label. Тест журнала запросов отправляет адрес и UUID в путях и query через тот же router и проверяет, что JSON-журнал называет только шаблоны маршрутов, статусы, коды problem и число параметров query, пропускает `/healthz` и `/readyz` и не содержит ни одного из значений. `internal/adapter/primary/http/middleware/` проверяет middleware журнала и метрик на простом router chi: общий маршрут и код problem, отсутствие problem для ответа, который в итоге успешен, уровень error для 5xx, неизвестный метод в журнале как `OTHER` и collector без учета problem. В `internal/adapter/secondary/prometheus/`: задержка по классу статуса, каждая пара вида и статуса доставки с нулем и сбросом, когда статус опустел, gauges квот без label аккаунта, hook сохранения ответов, который превращает неизвестные значения в `other` и не создает серий до первого вызова, и проверка всей выдачи после вызова каждого hook с fixture email и UUID. `internal/worker/deliverymetrics/` покрывает просрочку самой ранней доставки в `pending` (ноль, пока срок не наступил), текущие окна квоты, неудачное чтение, которое не отменяет второе, и жизненный цикл цикла чтения; `internal/bootstrap/` - пропуск без базы, квоты только для активного транспорта и приложение, которое запускает sampler против недоступной базы и все равно останавливается. `pkg/testutil/` проверяет сам поиск идентификаторов. +Unit-тесты (`make -C backend test`) покрывают продуктовые метрики. В `internal/adapter/primary/http/` запросы через настоящий router и настоящий collector получают шаблон маршрута своей операции (`/api/v1/me/invitations/{invitation_id}`, `/api/v1/me/assessment-attempts/{attempt_id}`) и никогда не получают параметр пути, адрес в пути или query string; неизвестные пути и методы сохраняют `/api/v1/*`, `/api/*` или `unmatched`; ответы problem считаются по коду (`unauthenticated`, `not_found`, `method_not_allowed`, `not_implemented`), а обычный 404 вне `/api` - нет; в выдаче нет значений, похожих на email или UUID; каждый код problem контракта сохраняет свой label. Тест журнала запросов отправляет адрес и UUID в путях и query через тот же router и проверяет, что JSON-журнал называет только шаблоны маршрутов, статусы, коды problem и число параметров query, пропускает `/healthz` и `/readyz` и не содержит ни одного из значений. `internal/adapter/primary/http/middleware/` проверяет middleware журнала и метрик на простом router chi: общий маршрут и код problem, отсутствие problem для ответа, который в итоге успешен, уровень error для 5xx, неизвестный метод в журнале как `OTHER` и collector без учета problem. В `internal/adapter/secondary/prometheus/`: задержка по классу статуса, каждая пара вида и статуса доставки с нулем и сбросом, когда статус опустел, gauges квот без label аккаунта, hook сохранения ответов, который превращает неизвестные значения в `other` и не создает серий до первого вызова, и проверка всей выдачи после вызова каждого hook с fixture email и UUID. `internal/worker/deliverymetrics/` покрывает просрочку самой ранней доставки в `pending` (ноль, пока срок не наступил), текущие окна квоты, неудачное чтение, которое не отменяет второе, и жизненный цикл цикла чтения; `internal/bootstrap/` - пропуск без базы, квоты только для активного транспорта и приложение, которое запускает sampler против недоступной базы и все равно останавливается. `pkg/testutil/` проверяет сам поиск идентификаторов. `TestDeliveryStatistics` в `backend/integration_test/delivery_statistics_test.go` проверяет запрос sqlc `GetDeliveryStatistics` на PostgreSQL: пустая таблица, затем доставки трех видов во всех пяти статусах, выставленных в рамках ограничений таблицы, дают точные числа по виду и статусу, а самый ранний срок берется только из доставок, которые еще в `pending`. diff --git a/frontend/src/entities/need/model/need-form.test.ts b/frontend/src/entities/need/model/need-form.test.ts index b3cf107..e6a2f94 100644 --- a/frontend/src/entities/need/model/need-form.test.ts +++ b/frontend/src/entities/need/model/need-form.test.ts @@ -45,7 +45,7 @@ import type { } from "./types"; import { needFormFieldOf, validateNeedCreate, validateNeedUpdate } from "./validate"; -// The fixtures are the named examples of the need contract (TASK-177), read +// The fixtures are the named examples of the need contract, read // from the same bundled OpenAPI document that Orval generates the client // from, so the tests follow the contract instead of a hand-made copy. diff --git a/frontend/src/shared/api/consent-contract.test.ts b/frontend/src/shared/api/consent-contract.test.ts index e5819e0..5a8b114 100644 --- a/frontend/src/shared/api/consent-contract.test.ts +++ b/frontend/src/shared/api/consent-contract.test.ts @@ -3,7 +3,7 @@ import { listMyConsents } from "./endpoints/consent/consent"; import { ConsentRecord, ConsentRecordList, ListMyConsentsParams } from "./schemas"; // These tests pin the generated consent ledger contract that the consent -// screen (TASK-065) consumes. They fail when regeneration lets a record lose +// screen consumes. They fail when regeneration lets a record lose // its purpose, text version, state, or revocation, accepts a C4 scope // without fields, or adds a field that would carry the text hash, another // subject, or a contact value into the read model. diff --git a/frontend/src/shared/api/endpoints/consent/consent.ts b/frontend/src/shared/api/endpoints/consent/consent.ts index 7bf0e19..8732fc0 100644 --- a/frontend/src/shared/api/endpoints/consent/consent.ts +++ b/frontend/src/shared/api/endpoints/consent/consent.ts @@ -68,9 +68,9 @@ export const getListMyConsentsUrl = (params?: ListMyConsentsParams,) => { * * The ledger is append-only. Every grant is a record with its purpose, the accepted text version, the source, and the grant time; the server also stores the hash of exactly the text the subject saw. A newer text version of the same purpose is a new record, and the earlier one becomes `superseded` without any change. A revocation stamps every unrevoked record of the purpose, and for c4 of one organization, once; a later grant is a new record. Purposes are independent. * - * Without `state` the page lists the whole history; `state=active` lists the consents that hold now, one per purpose for c1, c2, c3, and c5 and one per accepted invitation for c4. A c4 record names the organization with the name its consent text showed (a snapshot that a later rename does not change), the selected contact fields, and the invitation with its terms version; it never carries a contact value. A c2 record proves the consent to the publication text; the published field set and its changes are evidence of the publication history (TASK-088). + * Without `state` the page lists the whole history; `state=active` lists the consents that hold now, one per purpose for c1, c2, c3, and c5 and one per accepted invitation for c4. A c4 record names the organization with the name its consent text showed (a snapshot that a later rename does not change), the selected contact fields, and the invitation with its terms version; it never carries a contact value. A c2 record proves the consent to the publication text; the published field set and its changes are evidence of the publication history. * - * Granting c1, c2, c3, and c5 in the consent settings and revoking any purpose are planned operations of this tag (TASK-063 and TASK-064); c1 is given at registration and c4 only in AcceptMyInvitation. + * Granting c1, c2, c3, and c5 in the consent settings and revoking any purpose are planned operations of this tag; c1 is given at registration and c4 only in AcceptMyInvitation. * * Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated. A malformed `limit`, `cursor`, or `state` answers 400 validation_failed. * @summary List the consents of the current account with their history. diff --git a/frontend/src/shared/api/endpoints/invitation/invitation.ts b/frontend/src/shared/api/endpoints/invitation/invitation.ts index f1803bc..b7cb743 100644 --- a/frontend/src/shared/api/endpoints/invitation/invitation.ts +++ b/frontend/src/shared/api/endpoints/invitation/invitation.ts @@ -205,7 +205,7 @@ export const getCreateOrganizationInvitationUrl = (orgId: string,) => { * * The terms are complete from the start (PRD FR12): the role, the specialization and the grade, the offer type, the tasks, the team, the technology stack, the work formats and the place of work, the communication method, the salary range in RUB with its tax basis, and the package. Each package condition is either `provided` with a description or explicitly `not_provided`; leaving one out fails validation. A draft without the tax basis or the communication method therefore cannot exist. The draft is created as version 1 with terms version 1, and the candidate does not see it until SendOrganizationInvitation. * - * Salary: SalaryRange applies the same rules as for a need: whole rubles, positive multiples of 1000, `salary_from < salary_to`, and a width from 10% to 40% of the midpoint, checked by the server in integer arithmetic. The response carries `salary_fit`, the coarse indicator of PRD FR13 against the candidate's hidden minimum; the exact minimum appears in no response. The server never rejects a range because of the minimum, since a rejection would reveal it. Creating a draft is an indicator-relevant setting: it counts against the limit shared by the whole organization with the ranges of needs, at most three settings a day, and against the withheld counter, after five settings within seven days the indicator is `withheld` for seven days from the fifth, on every draft and invitation of the organization (PRD FR13, planned in TASK-211; see InvitationSalaryFit). Over the limit the server answers 429 with Retry-After and creates nothing. + * Salary: SalaryRange applies the same rules as for a need: whole rubles, positive multiples of 1000, `salary_from < salary_to`, and a width from 10% to 40% of the midpoint, checked by the server in integer arithmetic. The response carries `salary_fit`, the coarse indicator of PRD FR13 against the candidate's hidden minimum; the exact minimum appears in no response. The server never rejects a range because of the minimum, since a rejection would reveal it. Creating a draft is an indicator-relevant setting: it counts against the limit shared by the whole organization with the ranges of needs, at most three settings a day, and against the withheld counter, after five settings within seven days the indicator is `withheld` for seven days from the fifth, on every draft and invitation of the organization (PRD FR13, enforcement planned; see InvitationSalaryFit). Over the limit the server answers 429 with Retry-After and creates nothing. * * Idempotency: a retry with the same key and body within 24 hours replays the stored 201 and creates nothing, so a lost response never creates a second draft. A different body with the same key answers 422 idempotency_key_reused. 400 and 429 are never stored. * @@ -421,7 +421,7 @@ export const getUpdateOrganizationInvitationUrl = (orgId: string, * * Versions: every committed change creates version `expected_version + 1`; a change of the terms also creates the next terms version, an immutable snapshot, and a change of anything else keeps the terms version. `expected_version` is the `version` the client read; when it is not current, the server answers 412 version_conflict and changes nothing, and the client reads the invitation again. The version travels in the body because the generated client cannot read the ETag response header yet. The operation needs no Idempotency-Key: a body that changes nothing when applied to the current version, such as a retry of a change that already succeeded, keeps the version and answers 200 with the current invitation even when `expected_version` is older. * - * Salary limit: every change that can move `salary_fit` is an indicator-relevant setting: a change of either salary bound, of the tax basis, or of `work_formats`, because the indicator compares with the candidate's minimum for the offered formats, and switching formats or the basis would otherwise probe the minimum for free. Such a change counts against the limit shared by the organization with needs and other drafts, at most three settings a day, and against the withheld counter, which withholds `salary_fit` for seven days from the fifth setting within seven days (PRD FR13, planned in TASK-211; see InvitationSalaryFit). Over the limit the server answers 429 with Retry-After and changes nothing. A change that keeps the range, the basis, and the formats does not count. The operation follows the convention of UpdateOrganizationNeed: no Idempotency-Key, and a body that changes nothing answers 200. + * Salary limit: every change that can move `salary_fit` is an indicator-relevant setting: a change of either salary bound, of the tax basis, or of `work_formats`, because the indicator compares with the candidate's minimum for the offered formats, and switching formats or the basis would otherwise probe the minimum for free. Such a change counts against the limit shared by the organization with needs and other drafts, at most three settings a day, and against the withheld counter, which withholds `salary_fit` for seven days from the fifth setting within seven days (PRD FR13, enforcement planned; see InvitationSalaryFit). Over the limit the server answers 429 with Retry-After and changes nothing. A change that keeps the range, the basis, and the formats does not count. The operation follows the convention of UpdateOrganizationNeed: no Idempotency-Key, and a body that changes nothing answers 200. * * Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for a candidate), membership (404 not_found) and role (403 forbidden), the invitation (404 not_found), a body that changes nothing (200), the version (412), the state (409 state_conflict), domain rules (400 with the pointers of CreateOrganizationInvitation), then the salary limit (429). * @summary Change the terms, the need link, or the response period of a draft. @@ -516,9 +516,9 @@ export const useUpdateOrganizationInvitation = , /** * Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. In the MVP only the owner of the organization sends invitations. * - * Sends the current terms version of a `draft`. Sending is internal and never visible as a state: in one transaction the server records the delivery, creates the candidate's inbox entry, starts the deadline `response_deadline_at = delivered_at + response_period_days`, spends one invitation of the weekly organization quota, and writes the outbox event for the notification (TASK-199), then answers 200 with the state `delivered`. A successful answer therefore means the candidate can already read the invitation; an email is a separate notification that never blocks or delays it, and its retries never move the deadline. No contact of the candidate is disclosed by sending. + * Sends the current terms version of a `draft`. Sending is internal and never visible as a state: in one transaction the server records the delivery, creates the candidate's inbox entry, starts the deadline `response_deadline_at = delivered_at + response_period_days`, spends one invitation of the weekly organization quota, and writes the outbox event for the notification, then answers 200 with the state `delivered`. A successful answer therefore means the candidate can already read the invitation; an email is a separate notification that never blocks or delays it, and its retries never move the deadline. No contact of the candidate is disclosed by sending. * - * The server checks again that the candidate is still visible to the organization: a revoked publication C2 or a profile hidden from the organization answers 409 state_conflict without telling which. It also enforces the limits of the product policy: at most 20 invitations waiting for an answer per need (`delivered`, `viewed`, `counter`) and the 30-day pause for the pair of the organization and the candidate after a decline or a no deal, regardless of the member or the need, both with 409 state_conflict; and the rolling weekly quota of the organization (TASK-087), with 429 and Retry-After. The pending limit and the quota are planned in TASK-205 and TASK-087. + * The server checks again that the candidate is still visible to the organization: a revoked publication C2 or a profile hidden from the organization answers 409 state_conflict without telling which. It also enforces the limits of the product policy: at most 20 invitations waiting for an answer per need (`delivered`, `viewed`, `counter`) and the 30-day pause for the pair of the organization and the candidate after a decline or a no deal, regardless of the member or the need, both with 409 state_conflict; and the rolling weekly quota of the organization, with 429 and Retry-After. Enforcement of the pending limit and the organization quota is planned. * * Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, and a send of an invitation that was already sent answers 200 with the invitation in its current state even with a new key or an older `expected_version`; the quota is spent once. A stale `expected_version` on a draft answers 412 version_conflict, so the organization never sends terms it did not read. * @@ -814,13 +814,13 @@ export const useWithdrawOrganizationInvitation = , } /** - * Requires the session cookie of an employer account with an active membership in `org_id`. In the MVP only the owner of the organization reads contacts (TASK-202); the other roles of PRD FR07 are planned. + * Requires the session cookie of an employer account with an active membership in `org_id`. In the MVP only the owner of the organization reads contacts; the other roles of PRD FR07 are planned. * * This is the only operation that returns contact values, and its response is separate from the terms and from the invitation. It answers only while a grant created by the acceptance of this invitation is active and the read is allowed now: on every request the server checks the membership, the consent C4 for this organization, the grant and its fields, and the current visibility of the profile (C2 and the organizations the candidate hid the profile from), with no cache in between, so a revocation closes the next read at once. The response holds exactly the fields that the grant covers; every other field is null. A grant of organization A never answers for organization B. * * Without such a grant the contacts do not exist for the caller, and the operation answers 404 not_found, the same as for an unknown invitation: before an acceptance, after a decline or an expiry, after the candidate revoked C4 or cancelled the participation, after the candidate closed the visibility, and while a grant created when the profile was not published or was hidden from the organization stays blocked. The answer does not tell which applies; `contact_access` of GetOrganizationInvitation tells the organization whether access is `not_granted`, `available`, or `closed`, without the reason, and the candidate sees `readable` and `blocked_by` on the grant. Withdrawing the invitation keeps an existing grant. A later publication of the profile never reopens a closed grant; only a new explicit C4 creates a new one. * - * Every successful read is recorded in the access audit (planned in TASK-090 and TASK-202), and the response has `Cache-Control: no-store`. + * Every successful read is recorded in the access audit (planned with the contact access history), and the response has `Cache-Control: no-store`. * * Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden; an account without an active membership in the organization, an unknown organization, an unknown invitation, an invitation of another organization, and an invitation without an active readable grant all answer 404 not_found; a member whose role does not allow reading contacts answers 403 forbidden. An `org_id` or `invitation_id` that is not a UUID answers 400 validation_failed with the path pointer. * @summary Read the contacts that the candidate disclosed to the organization. @@ -1151,7 +1151,7 @@ export const getViewMyInvitationUrl = (invitationId: string,) => { /** * Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The candidate comes from the session. The request has no body. * - * The view transition of PRD FR12 (TASK-200) is an explicit command, so reading the invitation with GetMyInvitation stays free of side effects. The client sends it when the candidate opens the terms screen. For a `delivered` invitation the server moves it to `viewed`, sets `viewed_at`, advances `version`, and keeps the deadline. In any other state, including `viewed`, `accepted`, and the terminal states, it changes nothing and answers 200 with the current invitation. A view never reopens, extends, or answers an invitation, and the organization sees only the state `viewed` and `viewed_at`. + * The view transition of PRD FR12 is an explicit command, so reading the invitation with GetMyInvitation stays free of side effects. The client sends it when the candidate opens the terms screen. For a `delivered` invitation the server moves it to `viewed`, sets `viewed_at`, advances `version`, and keeps the deadline. In any other state, including `viewed`, `accepted`, and the terminal states, it changes nothing and answers 200 with the current invitation. A view never reopens, extends, or answers an invitation, and the organization sees only the state `viewed` and `viewed_at`. * * The command is idempotent by its effect: the first view wins and every repeat returns the current invitation. It therefore needs no Idempotency-Key and no `expected_version`: a view must never fail because the invitation changed after the client read it, for example after a salary raise. A view at the deadline or later first applies the due expiry and answers 200 with `expired`. * @@ -1235,11 +1235,11 @@ export const useViewMyInvitation = , * * Only an acceptance of the current terms version with the consent C4 creates access to contacts (PRD FR12). The body names the `terms_version` the candidate read and accepts, the `expected_version` of the invitation, and `consent_c4`: the C4 text version that the candidate saw, `accepted: true`, and the contact fields the candidate selected. At least one field is required and nothing is preselected or defaulted, so a grant never covers a field the candidate did not choose. The fields come only from the candidate's profile; the request never carries contact values. * - * Allowed in `delivered` and `viewed` before `response_deadline_at`; accepting directly from `delivered` is allowed, as in the PRD FR12 transition table. In one transaction the server moves the invitation to `accepted`, records the consent C4 in the consent ledger with the organization, the fields, the invitation, the terms version, and the text version and its hash (TASK-062), creates the contact grant for exactly those fields, and writes the audit event (TASK-201). The response is the invitation with `contact_grant`. The acceptance never publishes the profile (C2) and never bypasses a profile hidden from the organization: the grant alone does not guarantee a read, and the organization reads only while the visibility allows it. + * Allowed in `delivered` and `viewed` before `response_deadline_at`; accepting directly from `delivered` is allowed, as in the PRD FR12 transition table. In one transaction the server moves the invitation to `accepted`, records the consent C4 in the consent ledger with the organization, the fields, the invitation, the terms version, and the text version and its hash, creates the contact grant for exactly those fields, and writes the audit event. The response is the invitation with `contact_grant`. The acceptance never publishes the profile (C2) and never bypasses a profile hidden from the organization: the grant alone does not guarantee a read, and the organization reads only while the visibility allows it. * - * 412 or 409: a `terms_version` or `expected_version` that is not current answers 412 version_conflict, the repository status for a stale version, and records nothing; this is the stale terms case, for example after the organization raised the salary, and the client reads the invitation again and shows the new terms for a new decision. A state that does not allow an acceptance answers 409 state_conflict: `withdrawn`, `expired`, `declined`, `cancelled_by_candidate`, the planned `counter`, or a command received at the deadline or later, which is late. A terminal state and a passed deadline are checked before the versions: the server first applies the due expiry, and the client then gets 409 for a withdrawn, expired, or late invitation even when its versions are stale, so it shows the final state instead of rereading and retrying. TASK-197, TASK-201, and TASK-204 say 409 for stale terms; the repository rule keeps 412 for any stale version, so clients branch on `version_conflict` to reread and on `state_conflict` to show the final state. + * 412 or 409: a `terms_version` or `expected_version` that is not current answers 412 version_conflict, the repository status for a stale version, and records nothing; this is the stale terms case, for example after the organization raised the salary, and the client reads the invitation again and shows the new terms for a new decision. A state that does not allow an acceptance answers 409 state_conflict: `withdrawn`, `expired`, `declined`, `cancelled_by_candidate`, the planned `counter`, or a command received at the deadline or later, which is late. A terminal state and a passed deadline are checked before the versions: the server first applies the due expiry, and the client then gets 409 for a withdrawn, expired, or late invitation even when its versions are stale, so it shows the final state instead of rereading and retrying. The repository rule keeps 412 for any stale version, so clients branch on `version_conflict` to reread and on `state_conflict` to show the final state. * - * Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, and an acceptance of an invitation that is already `accepted` whose `terms_version` and set of fields equal those of its `contact_grant`, the terms version and fields that the candidate accepted, answers 200 with it even with a new key, an older `expected_version`, or a current `terms_version` that a later raise advanced; no second consent, grant, or audit event is created. A different terms version or field set on an accepted invitation answers 409 state_conflict; changing the disclosed fields is a matter of the consent operations (TASK-064). Of two concurrent acceptances only one makes the transition. + * Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, and an acceptance of an invitation that is already `accepted` whose `terms_version` and set of fields equal those of its `contact_grant`, the terms version and fields that the candidate accepted, answers 200 with it even with a new key, an older `expected_version`, or a current `terms_version` that a later raise advanced; no second consent, grant, or audit event is created. A different terms version or field set on an accepted invitation answers 409 state_conflict; changing the disclosed fields is a matter of the consent operations. Of two concurrent acceptances only one makes the transition. * * Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for an employer), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the invitation (404 not_found, after any due expiry), the repeat on an accepted invitation (200), a terminal state or a passed deadline (409 state_conflict, whatever the versions), the versions (412), any other state that does not allow an acceptance (409 state_conflict), then the consent rules (400 with the pointer `/consent_c4/text_version` for a text version that is not the published one, or `/consent_c4/fields/0` for a field that the profile does not hold). The schema rejects a missing `terms_version`, an empty or repeated field list, an unknown field kind, `accepted` other than true, and unknown fields such as `email` or `phone`. The general rate limit can answer 429 with Retry-After before any check. 404 and 409 state_conflict are stored under the key; 400, 412, and 429 are not. * @summary Accept the current terms and disclose the selected contacts. @@ -1431,7 +1431,7 @@ export const useDeclineMyInvitation = , /** * Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The candidate comes from the session. * - * Moves an unfinished invitation to the terminal state `cancelled_by_candidate` (PRD FR12): `delivered`, `viewed`, `accepted`, and the planned stages up to `negotiation`. The process closes. In the same transaction the server revokes the contact grant that the acceptance of this invitation created, with the reason `participation_cancelled`, so the next contact read of the organization answers 404. Grants of other invitations or applications stay; revoking the consent C4 for the organization as a whole, which closes all of them, belongs to the consent operations (TASK-064). + * Moves an unfinished invitation to the terminal state `cancelled_by_candidate` (PRD FR12): `delivered`, `viewed`, `accepted`, and the planned stages up to `negotiation`. The process closes. In the same transaction the server revokes the contact grant that the acceptance of this invitation created, with the reason `participation_cancelled`, so the next contact read of the organization answers 404. Grants of other invitations or applications stay; revoking the consent C4 for the organization as a whole, which closes all of them, belongs to the consent operations. * * Cancel differs from decline and withdraw: a decline is the structured answer before an acceptance and counts as a response; a cancellation leaves the process at any unfinished stage, mostly after an acceptance, and carries no reason; a withdrawal is the organization's command and keeps the grant. Before an answer the client offers the decline. * diff --git a/frontend/src/shared/api/endpoints/need/need.ts b/frontend/src/shared/api/endpoints/need/need.ts index abbe76c..6ec1bd2 100644 --- a/frontend/src/shared/api/endpoints/need/need.ts +++ b/frontend/src/shared/api/endpoints/need/need.ts @@ -193,7 +193,7 @@ export const getCreateOrganizationNeedUrl = (orgId: string,) => { * * The need is saved even when critical fields are missing: the response is 201 with version 1, and `readiness.missing_fields` names each critical field without a confirmed value with a specific question. `recommendations` is computed by the server from the confirmed requirements only; the request cannot set a recommendation, its score, or its components. Creating a need never contacts a candidate or sends an invitation. * - * Salary limit: setting a salary range counts against a limit shared by the whole organization, every member and every need, on creation as on a change: at most three range settings a day (PRD FR13, planned in TASK-211). Over the limit the server answers 429 with Retry-After and creates nothing. After five settings within seven days the money component of the recommendations is `withheld` for seven days. The limit keeps an organization from probing hidden candidate minimums with new needs instead of edits; repeated range changes also feed the private risk signals of TASK-319. + * Salary limit: setting a salary range counts against a limit shared by the whole organization, every member and every need, on creation as on a change: at most three range settings a day (PRD FR13, enforcement planned). Over the limit the server answers 429 with Retry-After and creates nothing. After five settings within seven days the money component of the recommendations is `withheld` for seven days. The limit keeps an organization from probing hidden candidate minimums with new needs instead of edits; repeated range changes also feed the private organization risk signals. * * Idempotency: a retry with the same key and body within 24 hours replays the stored 201 and creates nothing, so a lost response never creates a second need. A different body with the same key answers 422 idempotency_key_reused. 400 is never stored, so a corrected retry is evaluated again. * @@ -418,7 +418,7 @@ export const getUpdateOrganizationNeedUrl = (orgId: string, * * The operation needs no Idempotency-Key: a body that changes nothing when applied to the current version, such as a retry of a change that already succeeded, keeps the version and answers 200 with the current need even when `expected_version` is older. An incomplete need is a valid result; `readiness.missing_fields` tells what remains. * - * Salary limit: the recommendations aggregate candidates' minimums against the upper bound, so setting or changing a confirmed salary range counts against a limit shared by the whole organization, every member and every need, together with ranges set on creation: at most three a day (PRD FR13, planned in TASK-211). 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 risk signals of TASK-319. + * Salary limit: the recommendations aggregate candidates' minimums against the upper bound, so setting or changing a confirmed salary range counts against a limit shared by the whole organization, every member and every need, together with ranges set on creation: at most three a day (PRD FR13, enforcement planned). 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. * * Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for a candidate), membership (404 not_found) and role (403 forbidden), the need (404 not_found), a body that changes nothing (200), the version (412), domain rules (400 with a pointer such as `/salary/value/salary_to` for a range whose lower bound is not below the upper one or whose width is outside 10-40%, `/desired_skills/0/name` for a skill that is also in the required list, `/grade/status` or `/required_skills/2/status` for `extracted` with a value that is not the stored suggestion, or `/vacancy_id`), then the salary change limit (429). The schema rejects a missing or non-positive `expected_version`, unknown fields such as `rec_score`, `members`, `candidate_minimum`, or `version`, a field sent as a bare value instead of `{value, status}`, a list sent as null, a salary bound that is not a positive multiple of 1000, and an unknown currency, period, or tax basis. * @summary Confirm, change, or delete requirements of a need. diff --git a/frontend/src/shared/api/endpoints/privacy/privacy.ts b/frontend/src/shared/api/endpoints/privacy/privacy.ts index 220980e..b1ec619 100644 --- a/frontend/src/shared/api/endpoints/privacy/privacy.ts +++ b/frontend/src/shared/api/endpoints/privacy/privacy.ts @@ -179,7 +179,7 @@ export const getSetMyPublicationUrl = () => { /** * Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The body is the complete new publication setting: `state` `published` with the non-empty set of card fields, or `closed` with an empty set. It changes only the publication; the search status and the hidden organizations stay as they were. * - * Publication is not a consent and does not duplicate one. The consent C2 lives in the consent ledger (`ListMyConsents`); this setting refers to it. Publishing requires an active, unrevoked C2 record of the account and binds the publication to that record, so a client sends no consent identifier and cannot forge one. Without one the server answers 409 state_conflict with the entry `{in: body, pointer: /state, code: consent_required}` in `errors`, which tells it apart from every other conflict, and changes nothing: the client gives C2 first (planned in the consent settings, TASK-063) and then publishes. The server takes the C2 record under a share lock in the transaction that writes the publication, so a revocation that races with a publication either commits first (the publication is refused) or closes the card right after. A revocation of C2 closes the card at once, because `state` is computed from the unrevoked record; a later C2 grant never reopens it, and the candidate publishes again under the new record. The revocation path itself (TASK-064) closes the stored publication and revokes the contact grants in its own transaction. A closing sent over a stored publication whose C2 was revoked is a real change: it stores the closing, records `publication_closed`, and revokes the grants as any closing does. Publishing, like every visibility change, needs a verified email (a usecase requirement; the unverified account cleanup deletes only accounts without such records). Publishing never adds a field that the body did not name, and a new `CardField` value is never published for a candidate who did not choose it. + * Publication is not a consent and does not duplicate one. The consent C2 lives in the consent ledger (`ListMyConsents`); this setting refers to it. Publishing requires an active, unrevoked C2 record of the account and binds the publication to that record, so a client sends no consent identifier and cannot forge one. Without one the server answers 409 state_conflict with the entry `{in: body, pointer: /state, code: consent_required}` in `errors`, which tells it apart from every other conflict, and changes nothing: the client gives C2 first (planned in the consent settings) and then publishes. The server takes the C2 record under a share lock in the transaction that writes the publication, so a revocation that races with a publication either commits first (the publication is refused) or closes the card right after. A revocation of C2 closes the card at once, because `state` is computed from the unrevoked record; a later C2 grant never reopens it, and the candidate publishes again under the new record. The revocation path itself closes the stored publication and revokes the contact grants in its own transaction. A closing sent over a stored publication whose C2 was revoked is a real change: it stores the closing, records `publication_closed`, and revokes the grants as any closing does. Publishing, like every visibility change, needs a verified email (a usecase requirement; the unverified account cleanup deletes only accounts without such records). Publishing never adds a field that the body did not name, and a new `CardField` value is never published for a candidate who did not choose it. * * The field set contains only the groups of `CardField`. The full name, contacts, and the lowest salary have no value there, so no body can publish them. Only values that the candidate confirmed ever reach the card. Contacts reach an organization only through the contact grant (C4), and a profile that is published or closed changes none of the grants that exist; closing the publication, and hiding an organization that holds a grant, revoke the contact grants concerned with the reason `visibility_closed` in the same transaction as the change (planned together with the operations, see the invitation contract). * @@ -871,7 +871,7 @@ export const getListMyCardAccessHistoryUrl = (params?: ListMyCardAccessHistoryPa * * An access is a view of the anonymous card by an organization (`card_viewed`) or a read of the contacts through an active contact grant (`contact_read`). Reading the history is not an access and writes nothing. A view of the card by an organization that has no invitation relation with the candidate carries `organization` null, so the candidate sees that the card was viewed without learning a company that they cannot otherwise see; a contact read always names the organization, because the candidate accepted its invitation. The entries carry no search query, filter, or ranking of the organization, and no organization the candidate hides ever appears as a viewer, because a hidden organization cannot read the card. * - * The storage of accesses is planned with the card and contact operations of the organization side (TASK-185 and the contact read of the invitation contract); until then the operation answers 501 not_implemented after the session and request checks. + * The storage of accesses is planned with the card and contact operations of the organization side (anonymous card reads and contact reads under the invitation contract); until then the operation answers 501 not_implemented after the session and request checks. * * A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. A malformed `limit` or `cursor` answers 400 validation_failed. * @summary List the accesses of organizations to the card of the current candidate. diff --git a/frontend/src/shared/api/endpoints/support/support.ts b/frontend/src/shared/api/endpoints/support/support.ts index ae894b9..06d755f 100644 --- a/frontend/src/shared/api/endpoints/support/support.ts +++ b/frontend/src/shared/api/endpoints/support/support.ts @@ -188,7 +188,7 @@ export const getCreateMySupportCaseUrl = () => { * | `anticheat_appeal` | candidate | required; `assessment_attempt` of the caller with an anti-cheat review decision | none | * | `manual_assessment` | candidate | optional; a prior `assessment_attempt` of the caller in the same specialization | required `assessment_target` | * - * An organization is visible to a candidate when it sent the candidate an invitation or when the organization contract (TASK-077) shows the candidate its profile, and to an employer account when the account has an active membership in it. Invitations are in the contract (TASK-196) but not implemented yet, so until they are, every `invitation` reference answers 404 not_found; anti-cheat review decisions are not either, so until TASK-173 every anti-cheat appeal answers 409 state_conflict. The schema rejects an object type that the case type does not accept, for example an organization in a grade appeal. + * An organization is visible to a candidate when it sent the candidate an invitation or when the organization contract shows the candidate its profile, and to an employer account when the account has an active membership in it. Invitations are in the contract but not implemented yet, so until they are, every `invitation` reference answers 404 not_found; anti-cheat review decisions are not either, so until review decisions are implemented, every anti-cheat appeal answers 409 state_conflict. The schema rejects an object type that the case type does not accept, for example an organization in a grade appeal. * * Ownership of the reference: the server checks the object against the session account on every create. An unknown object and an object of someone else, such as another candidate's attempt, another account's case, or an invitation addressed to another person, both answer 404 not_found, so a reference never reveals whether a foreign object exists. An own case that a grade appeal cannot dispute, because it is not a manual assessment, is not resolved yet, or was resolved with another outcome, answers 409 state_conflict. An identifier that is not a UUID fails validation with the pointer `/object/id`. The case stores only the type and the identifier of the object. * @@ -297,7 +297,7 @@ export const useCreateMySupportCase = , * * The history lists every public event and is never truncated: the server keeps a case within 200 events by rejecting a staff event that would leave no room for the terminal one. * - * The case must belong to the account of the session: a case of another account, including another member of the same organization, answers 404 not_found, the same as an unknown identifier, so identifiers cannot be probed. TASK-314 says forbidden for a foreign case URL; the contract answers 404 instead, so the client shows the same "not found" state for a foreign and an unknown case. A malformed `case_id` answers 400 validation_failed with the path pointer. + * The case must belong to the account of the session: a case of another account, including another member of the same organization, answers 404 not_found, the same as an unknown identifier, so identifiers cannot be probed. The contract answers 404, so the client shows the same "not found" state for a foreign and an unknown case. A malformed `case_id` answers 400 validation_failed with the path pointer. * @summary Read a support case of the current account. */ export const getMySupportCase = async (caseId: string, options?: Parameters[1]): Promise => { diff --git a/frontend/src/shared/api/organization-contract.test.ts b/frontend/src/shared/api/organization-contract.test.ts index 18a8601..4add69d 100644 --- a/frontend/src/shared/api/organization-contract.test.ts +++ b/frontend/src/shared/api/organization-contract.test.ts @@ -15,7 +15,7 @@ import { } from "./schemas"; // These tests pin the generated organization contract that the employer -// cabinet (TASK-080) and the organization switcher consume. They fail when +// cabinet and the organization switcher consume. They fail when // regeneration drops a limit of the profile, loses a level, role, or state of // the PRD, lets a request carry a role or a verification level, or lets a // response name a member or an account. diff --git a/frontend/src/shared/api/privacy-contract.test.ts b/frontend/src/shared/api/privacy-contract.test.ts index 6920243..7fe5385 100644 --- a/frontend/src/shared/api/privacy-contract.test.ts +++ b/frontend/src/shared/api/privacy-contract.test.ts @@ -15,7 +15,7 @@ import { SearchStatusUpdate, } from "./schemas"; -// These tests pin the generated visibility contract (TASK-088) that the +// These tests pin the generated visibility contract that the // privacy settings screen consumes. They fail when regeneration lets a // request name a consent or a time, lets a card field name a name, a contact, // or the salary, lets the anonymous card gain a contact, mixes the search @@ -248,7 +248,9 @@ describe("generated AnonymousCardContent", () => { }; expect(CardPreview.parse(closed)).toEqual(closed); - expect(CardPreview.parse({ ...closed, state: "published", fields: ["stack"], card })).toMatchObject({ + expect( + CardPreview.parse({ ...closed, state: "published", fields: ["stack"], card }), + ).toMatchObject({ card: { stack: ["PostgreSQL", "Kafka"] }, }); }); @@ -268,10 +270,9 @@ describe("privacy schemas", () => { })); const privacySide = [...sourcesIn(join("schemas", "privacy"))]; - const otherSide = ["organization", "invitation", "need", "candidate", "consent"].flatMap((tag) => [ - ...sourcesIn(join("schemas", tag)), - ...sourcesIn(join("endpoints", tag)), - ]); + const otherSide = ["organization", "invitation", "need", "candidate", "consent"].flatMap( + (tag) => [...sourcesIn(join("schemas", tag)), ...sourcesIn(join("endpoints", tag))], + ); // Generated object keys that only the visibility settings have, matched as // quoted keys because endpoint comments quote contract prose. @@ -293,7 +294,7 @@ describe("privacy schemas", () => { '"confirmed_categories":', '"text_version":', '"invitation_id":', - '"fields": zod.array(zod.enum([\'email\'', + "\"fields\": zod.array(zod.enum(['email'", ]; it("finds the generated files of both sides", () => { diff --git a/frontend/src/shared/api/profile-contract.test.ts b/frontend/src/shared/api/profile-contract.test.ts index fa5ef3c..783fc19 100644 --- a/frontend/src/shared/api/profile-contract.test.ts +++ b/frontend/src/shared/api/profile-contract.test.ts @@ -13,7 +13,7 @@ import { SaveMyProfileBody, } from "./schemas"; -// These tests pin the generated candidate profile contract (TASK-066) that +// These tests pin the generated candidate profile contract that // the profile form consumes. They fail when regeneration drops a limit, lets a // request carry a confirmed grade, a category, or provenance, loses the trust // level of a claim, or mixes the private profile with organization DTOs. diff --git a/frontend/src/shared/api/schemas/consent/consentPurposeCode.zod.ts b/frontend/src/shared/api/schemas/consent/consentPurposeCode.zod.ts index 485a117..d3b196d 100644 --- a/frontend/src/shared/api/schemas/consent/consentPurposeCode.zod.ts +++ b/frontend/src/shared/api/schemas/consent/consentPurposeCode.zod.ts @@ -6,7 +6,7 @@ */ import * as zod from 'zod'; -export const ConsentPurposeCode = zod.enum(['c1', 'c2', 'c3', 'c4', 'c5']).describe('One of the independent consents of PRD FR01. A grant or a revocation of one purpose never changes another.\n\n- c1: processing of personal data, given at registration.\n- c2: publication of the candidate card. The record proves the consent to the published text; which fields were published and when is evidence of the publication history (TASK-088), not of this record. Adding a field scope to c2 records later is an additive change.\n- c3: automatic categorization. Without it the candidate can request a manual assessment by the same rubric.\n- c4: transfer of the selected contact data to one organization, currently given only in an invitation acceptance.\n- c5: import of FSP results.\n\nConsentPurpose lists the subset whose text the client may read before an account exists.') +export const ConsentPurposeCode = zod.enum(['c1', 'c2', 'c3', 'c4', 'c5']).describe('One of the independent consents of PRD FR01. A grant or a revocation of one purpose never changes another.\n\n- c1: processing of personal data, given at registration.\n- c2: publication of the candidate card. The record proves the consent to the published text; which fields were published and when is evidence of the publication history, not of this record. Adding a field scope to c2 records later is an additive change.\n- c3: automatic categorization. Without it the candidate can request a manual assessment by the same rubric.\n- c4: transfer of the selected contact data to one organization, currently given only in an invitation acceptance.\n- c5: import of FSP results.\n\nConsentPurpose lists the subset whose text the client may read before an account exists.') export type ConsentPurposeCode = zod.input; export type ConsentPurposeCodeOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/consent/consentRecord.zod.ts b/frontend/src/shared/api/schemas/consent/consentRecord.zod.ts index bb6ba42..4f5a047 100644 --- a/frontend/src/shared/api/schemas/consent/consentRecord.zod.ts +++ b/frontend/src/shared/api/schemas/consent/consentRecord.zod.ts @@ -18,10 +18,10 @@ export const consentRecordFieldsMax = 4; export const ConsentRecord = zod.object({ "id": zod.uuid().describe('Identifier of the record.'), - "purpose": zod.enum(['c1', 'c2', 'c3', 'c4', 'c5']).describe('One of the independent consents of PRD FR01. A grant or a revocation of one purpose never changes another.\n\n- c1: processing of personal data, given at registration.\n- c2: publication of the candidate card. The record proves the consent to the published text; which fields were published and when is evidence of the publication history (TASK-088), not of this record. Adding a field scope to c2 records later is an additive change.\n- c3: automatic categorization. Without it the candidate can request a manual assessment by the same rubric.\n- c4: transfer of the selected contact data to one organization, currently given only in an invitation acceptance.\n- c5: import of FSP results.\n\nConsentPurpose lists the subset whose text the client may read before an account exists.'), + "purpose": zod.enum(['c1', 'c2', 'c3', 'c4', 'c5']).describe('One of the independent consents of PRD FR01. A grant or a revocation of one purpose never changes another.\n\n- c1: processing of personal data, given at registration.\n- c2: publication of the candidate card. The record proves the consent to the published text; which fields were published and when is evidence of the publication history, not of this record. Adding a field scope to c2 records later is an additive change.\n- c3: automatic categorization. Without it the candidate can request a manual assessment by the same rubric.\n- c4: transfer of the selected contact data to one organization, currently given only in an invitation acceptance.\n- c5: import of FSP results.\n\nConsentPurpose lists the subset whose text the client may read before an account exists.'), "state": zod.enum(['active', 'superseded', 'revoked']).describe('State of a consent record, computed from the ledger.\n\n- active: the consent holds. For c1, c2, c3, and c5 it is the newest unrevoked record of its purpose; every unrevoked c4 record is active, one per accepted invitation.\n- superseded: the subject later accepted another text version of the same purpose and has not revoked either. The record stays as evidence for its own time; it never applies to c4.\n- revoked: the consent was revoked. The record keeps its grant and its one revocation time; a later grant is a new record and never reopens it.'), "text_version": zod.string().min(1).max(consentRecordTextVersionOneMax).regex(consentRecordTextVersionOneRegExp).describe('Identifier of the published consent text that the user saw and accepted. The server stores the acceptance with this version and the hash of its text; the client never sends or receives the hash.').describe('Version of the consent text that the subject accepted.'), - "source": zod.enum(['registration', 'consent_settings', 'invitation_acceptance']).describe('Where the subject gave the consent.\n\n- registration: the c1 acceptance of RegisterAccount.\n- consent_settings: the consent settings of the account, for c1, c2, c3, and c5 (planned, TASK-063 and TASK-064).\n- invitation_acceptance: the c4 acceptance of AcceptMyInvitation.\n\nA c4 given when sending an application (PRD Q9) is planned as an additional value.'), + "source": zod.enum(['registration', 'consent_settings', 'invitation_acceptance']).describe('Where the subject gave the consent.\n\n- registration: the c1 acceptance of RegisterAccount.\n- consent_settings: the consent settings of the account, for c1, c2, c3, and c5 (planned).\n- invitation_acceptance: the c4 acceptance of AcceptMyInvitation.\n\nA c4 given when sending an application (PRD Q9) is planned as an additional value.'), "granted_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'), "revoked_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('Moment of the revocation, or null unless `state` is `revoked`.'), "revocation_source": zod.union([zod.enum(['consent_settings', 'support_request']).describe('Who recorded a revocation.\n\n- consent_settings: the subject revoked the consent in the product.\n- support_request: an operator recorded a revocation that the subject requested through support.'),zod.null()]).describe('Who recorded the revocation, or null unless `state` is `revoked`.'), @@ -29,7 +29,7 @@ export const ConsentRecord = zod.object({ "id": zod.uuid().describe('Identifier of the organization.'), "name": zod.string().min(1).max(consentRecordOrganizationOneNameMax).describe('Name of the organization in the consent text at the time of the consent. Plain text; clients show it as text, never as HTML.') }).describe('Organization of a c4 consent as the consent recorded it. `name` is a snapshot of the name that the shown consent text carried at the time of the consent, and the stored text hash proves that text with this name; a later rename of the organization does not change it, so it can differ from the current name.'),zod.null()]).describe('Organization that a c4 consent allows to read the fields, with the name the consent text showed, or null for every other purpose.'), - "fields": zod.array(zod.enum(['full_name', 'email', 'phone', 'telegram']).describe('Kind of personal data that the consent C4 can disclose to one organization (PRD FR01 and FR12). The candidate selects each kind separately; one kind never implies another.\n\n- full_name: the full name from the profile.\n- email: the contact email address from the profile.\n- phone: the contact phone number from the profile.\n- telegram: the Telegram username from the profile.\n\nThe value formats are those of ContactDisclosure: 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, TASK-066) must store contacts in the same formats, so a disclosure never has to convert or drop a stored value. The FSP results of FR14, which need their own explicit permission, are planned as additional kinds. Adding a value is a contract change.')).min(1).max(consentRecordFieldsMax).nullable().describe('Contact fields that a c4 consent covers, or null for every other purpose. One kind never implies another.'), + "fields": zod.array(zod.enum(['full_name', 'email', 'phone', 'telegram']).describe('Kind of personal data that the consent C4 can disclose to one organization (PRD FR01 and FR12). The candidate selects each kind separately; one kind never implies another.\n\n- full_name: the full name from the profile.\n- email: the contact email address from the profile.\n- phone: the contact phone number from the profile.\n- telegram: the Telegram username from the profile.\n\nThe value formats are those of ContactDisclosure: 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 has to convert or drop a stored value. The FSP results of FR14, which need their own explicit permission, are planned as additional kinds. Adding a value is a contract change.')).min(1).max(consentRecordFieldsMax).nullable().describe('Contact fields that a c4 consent covers, or null for every other purpose. One kind never implies another.'), "invitation_id": zod.uuid().nullable().describe('Invitation whose acceptance gave a c4 consent, or null for every other purpose.'), "invitation_terms_version": zod.union([zod.int().min(1).describe('Version of the terms of an invitation. The terms of a version are an immutable snapshot: every committed change of the terms, in the draft or by the one raise of the upper salary bound after sending, creates the next terms version, and a change of anything else keeps it. An acceptance names the terms version it accepts, and the consent C4 and the contact grant record it.'),zod.null()]).describe('Terms version that the acceptance accepted, or null for every other purpose.') }).describe('One record of the consent ledger as its subject reads it: the purpose, the text version the subject accepted, where and when the consent was given, its state, and the revocation. A c4 record also names the organization, the contact fields, and the invitation with its terms version; these fields are null for every other purpose. The server also stores the SHA-256 hash of exactly the text the subject saw, which a client never sends or receives.') diff --git a/frontend/src/shared/api/schemas/consent/consentRecordList.zod.ts b/frontend/src/shared/api/schemas/consent/consentRecordList.zod.ts index d34a9bc..d4e2fe2 100644 --- a/frontend/src/shared/api/schemas/consent/consentRecordList.zod.ts +++ b/frontend/src/shared/api/schemas/consent/consentRecordList.zod.ts @@ -25,10 +25,10 @@ export const consentRecordListPageNextCursorRegExp = new RegExp('^[A-Za-z0-9_-]+ export const ConsentRecordList = zod.object({ "items": zod.array(zod.object({ "id": zod.uuid().describe('Identifier of the record.'), - "purpose": zod.enum(['c1', 'c2', 'c3', 'c4', 'c5']).describe('One of the independent consents of PRD FR01. A grant or a revocation of one purpose never changes another.\n\n- c1: processing of personal data, given at registration.\n- c2: publication of the candidate card. The record proves the consent to the published text; which fields were published and when is evidence of the publication history (TASK-088), not of this record. Adding a field scope to c2 records later is an additive change.\n- c3: automatic categorization. Without it the candidate can request a manual assessment by the same rubric.\n- c4: transfer of the selected contact data to one organization, currently given only in an invitation acceptance.\n- c5: import of FSP results.\n\nConsentPurpose lists the subset whose text the client may read before an account exists.'), + "purpose": zod.enum(['c1', 'c2', 'c3', 'c4', 'c5']).describe('One of the independent consents of PRD FR01. A grant or a revocation of one purpose never changes another.\n\n- c1: processing of personal data, given at registration.\n- c2: publication of the candidate card. The record proves the consent to the published text; which fields were published and when is evidence of the publication history, not of this record. Adding a field scope to c2 records later is an additive change.\n- c3: automatic categorization. Without it the candidate can request a manual assessment by the same rubric.\n- c4: transfer of the selected contact data to one organization, currently given only in an invitation acceptance.\n- c5: import of FSP results.\n\nConsentPurpose lists the subset whose text the client may read before an account exists.'), "state": zod.enum(['active', 'superseded', 'revoked']).describe('State of a consent record, computed from the ledger.\n\n- active: the consent holds. For c1, c2, c3, and c5 it is the newest unrevoked record of its purpose; every unrevoked c4 record is active, one per accepted invitation.\n- superseded: the subject later accepted another text version of the same purpose and has not revoked either. The record stays as evidence for its own time; it never applies to c4.\n- revoked: the consent was revoked. The record keeps its grant and its one revocation time; a later grant is a new record and never reopens it.'), "text_version": zod.string().min(1).max(consentRecordListItemsItemTextVersionOneMax).regex(consentRecordListItemsItemTextVersionOneRegExp).describe('Identifier of the published consent text that the user saw and accepted. The server stores the acceptance with this version and the hash of its text; the client never sends or receives the hash.').describe('Version of the consent text that the subject accepted.'), - "source": zod.enum(['registration', 'consent_settings', 'invitation_acceptance']).describe('Where the subject gave the consent.\n\n- registration: the c1 acceptance of RegisterAccount.\n- consent_settings: the consent settings of the account, for c1, c2, c3, and c5 (planned, TASK-063 and TASK-064).\n- invitation_acceptance: the c4 acceptance of AcceptMyInvitation.\n\nA c4 given when sending an application (PRD Q9) is planned as an additional value.'), + "source": zod.enum(['registration', 'consent_settings', 'invitation_acceptance']).describe('Where the subject gave the consent.\n\n- registration: the c1 acceptance of RegisterAccount.\n- consent_settings: the consent settings of the account, for c1, c2, c3, and c5 (planned).\n- invitation_acceptance: the c4 acceptance of AcceptMyInvitation.\n\nA c4 given when sending an application (PRD Q9) is planned as an additional value.'), "granted_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'), "revoked_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('Moment of the revocation, or null unless `state` is `revoked`.'), "revocation_source": zod.union([zod.enum(['consent_settings', 'support_request']).describe('Who recorded a revocation.\n\n- consent_settings: the subject revoked the consent in the product.\n- support_request: an operator recorded a revocation that the subject requested through support.'),zod.null()]).describe('Who recorded the revocation, or null unless `state` is `revoked`.'), @@ -36,7 +36,7 @@ export const ConsentRecordList = zod.object({ "id": zod.uuid().describe('Identifier of the organization.'), "name": zod.string().min(1).max(consentRecordListItemsItemOrganizationOneNameMax).describe('Name of the organization in the consent text at the time of the consent. Plain text; clients show it as text, never as HTML.') }).describe('Organization of a c4 consent as the consent recorded it. `name` is a snapshot of the name that the shown consent text carried at the time of the consent, and the stored text hash proves that text with this name; a later rename of the organization does not change it, so it can differ from the current name.'),zod.null()]).describe('Organization that a c4 consent allows to read the fields, with the name the consent text showed, or null for every other purpose.'), - "fields": zod.array(zod.enum(['full_name', 'email', 'phone', 'telegram']).describe('Kind of personal data that the consent C4 can disclose to one organization (PRD FR01 and FR12). The candidate selects each kind separately; one kind never implies another.\n\n- full_name: the full name from the profile.\n- email: the contact email address from the profile.\n- phone: the contact phone number from the profile.\n- telegram: the Telegram username from the profile.\n\nThe value formats are those of ContactDisclosure: 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, TASK-066) must store contacts in the same formats, so a disclosure never has to convert or drop a stored value. The FSP results of FR14, which need their own explicit permission, are planned as additional kinds. Adding a value is a contract change.')).min(1).max(consentRecordListItemsItemFieldsMax).nullable().describe('Contact fields that a c4 consent covers, or null for every other purpose. One kind never implies another.'), + "fields": zod.array(zod.enum(['full_name', 'email', 'phone', 'telegram']).describe('Kind of personal data that the consent C4 can disclose to one organization (PRD FR01 and FR12). The candidate selects each kind separately; one kind never implies another.\n\n- full_name: the full name from the profile.\n- email: the contact email address from the profile.\n- phone: the contact phone number from the profile.\n- telegram: the Telegram username from the profile.\n\nThe value formats are those of ContactDisclosure: 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 has to convert or drop a stored value. The FSP results of FR14, which need their own explicit permission, are planned as additional kinds. Adding a value is a contract change.')).min(1).max(consentRecordListItemsItemFieldsMax).nullable().describe('Contact fields that a c4 consent covers, or null for every other purpose. One kind never implies another.'), "invitation_id": zod.uuid().nullable().describe('Invitation whose acceptance gave a c4 consent, or null for every other purpose.'), "invitation_terms_version": zod.union([zod.int().min(1).describe('Version of the terms of an invitation. The terms of a version are an immutable snapshot: every committed change of the terms, in the draft or by the one raise of the upper salary bound after sending, creates the next terms version, and a change of anything else keeps it. An acceptance names the terms version it accepts, and the consent C4 and the contact grant record it.'),zod.null()]).describe('Terms version that the acceptance accepted, or null for every other purpose.') }).describe('One record of the consent ledger as its subject reads it: the purpose, the text version the subject accepted, where and when the consent was given, its state, and the revocation. A c4 record also names the organization, the contact fields, and the invitation with its terms version; these fields are null for every other purpose. The server also stores the SHA-256 hash of exactly the text the subject saw, which a client never sends or receives.')).max(consentRecordListItemsMax).describe('Records of the page.'), diff --git a/frontend/src/shared/api/schemas/consent/consentSource.zod.ts b/frontend/src/shared/api/schemas/consent/consentSource.zod.ts index eeed5a8..9a5060a 100644 --- a/frontend/src/shared/api/schemas/consent/consentSource.zod.ts +++ b/frontend/src/shared/api/schemas/consent/consentSource.zod.ts @@ -6,7 +6,7 @@ */ import * as zod from 'zod'; -export const ConsentSource = zod.enum(['registration', 'consent_settings', 'invitation_acceptance']).describe('Where the subject gave the consent.\n\n- registration: the c1 acceptance of RegisterAccount.\n- consent_settings: the consent settings of the account, for c1, c2, c3, and c5 (planned, TASK-063 and TASK-064).\n- invitation_acceptance: the c4 acceptance of AcceptMyInvitation.\n\nA c4 given when sending an application (PRD Q9) is planned as an additional value.') +export const ConsentSource = zod.enum(['registration', 'consent_settings', 'invitation_acceptance']).describe('Where the subject gave the consent.\n\n- registration: the c1 acceptance of RegisterAccount.\n- consent_settings: the consent settings of the account, for c1, c2, c3, and c5 (planned).\n- invitation_acceptance: the c4 acceptance of AcceptMyInvitation.\n\nA c4 given when sending an application (PRD Q9) is planned as an additional value.') export type ConsentSource = zod.input; export type ConsentSourceOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/contactFieldKind.zod.ts b/frontend/src/shared/api/schemas/contactFieldKind.zod.ts index 541293a..85f5507 100644 --- a/frontend/src/shared/api/schemas/contactFieldKind.zod.ts +++ b/frontend/src/shared/api/schemas/contactFieldKind.zod.ts @@ -6,7 +6,7 @@ */ import * as zod from 'zod'; -export const ContactFieldKind = zod.enum(['full_name', 'email', 'phone', 'telegram']).describe('Kind of personal data that the consent C4 can disclose to one organization (PRD FR01 and FR12). The candidate selects each kind separately; one kind never implies another.\n\n- full_name: the full name from the profile.\n- email: the contact email address from the profile.\n- phone: the contact phone number from the profile.\n- telegram: the Telegram username from the profile.\n\nThe value formats are those of ContactDisclosure: 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, TASK-066) must store contacts in the same formats, so a disclosure never has to convert or drop a stored value. The FSP results of FR14, which need their own explicit permission, are planned as additional kinds. Adding a value is a contract change.') +export const ContactFieldKind = zod.enum(['full_name', 'email', 'phone', 'telegram']).describe('Kind of personal data that the consent C4 can disclose to one organization (PRD FR01 and FR12). The candidate selects each kind separately; one kind never implies another.\n\n- full_name: the full name from the profile.\n- email: the contact email address from the profile.\n- phone: the contact phone number from the profile.\n- telegram: the Telegram username from the profile.\n\nThe value formats are those of ContactDisclosure: 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 has to convert or drop a stored value. The FSP results of FR14, which need their own explicit permission, are planned as additional kinds. Adding a value is a contract change.') export type ContactFieldKind = zod.input; export type ContactFieldKindOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/acceptMyInvitationBody.zod.ts b/frontend/src/shared/api/schemas/invitation/acceptMyInvitationBody.zod.ts index 3475c6f..7e8c99a 100644 --- a/frontend/src/shared/api/schemas/invitation/acceptMyInvitationBody.zod.ts +++ b/frontend/src/shared/api/schemas/invitation/acceptMyInvitationBody.zod.ts @@ -21,7 +21,7 @@ export const AcceptMyInvitationBody = zod.object({ "consent_c4": zod.object({ "text_version": zod.string().min(1).max(acceptMyInvitationBodyConsentC4TextVersionMax).regex(acceptMyInvitationBodyConsentC4TextVersionRegExp).describe('Identifier of the published consent text that the user saw and accepted. The server stores the acceptance with this version and the hash of its text; the client never sends or receives the hash.'), "accepted": zod.literal(true).describe('Explicit consent. Only true is valid.'), - "fields": zod.array(zod.enum(['full_name', 'email', 'phone', 'telegram']).describe('Kind of personal data that the consent C4 can disclose to one organization (PRD FR01 and FR12). The candidate selects each kind separately; one kind never implies another.\n\n- full_name: the full name from the profile.\n- email: the contact email address from the profile.\n- phone: the contact phone number from the profile.\n- telegram: the Telegram username from the profile.\n\nThe value formats are those of ContactDisclosure: 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, TASK-066) must store contacts in the same formats, so a disclosure never has to convert or drop a stored value. The FSP results of FR14, which need their own explicit permission, are planned as additional kinds. Adding a value is a contract change.')).min(1).max(acceptMyInvitationBodyConsentC4FieldsMax).describe('Contact fields the organization may read after the acceptance. The grant covers exactly these fields and no other.') + "fields": zod.array(zod.enum(['full_name', 'email', 'phone', 'telegram']).describe('Kind of personal data that the consent C4 can disclose to one organization (PRD FR01 and FR12). The candidate selects each kind separately; one kind never implies another.\n\n- full_name: the full name from the profile.\n- email: the contact email address from the profile.\n- phone: the contact phone number from the profile.\n- telegram: the Telegram username from the profile.\n\nThe value formats are those of ContactDisclosure: 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 has to convert or drop a stored value. The FSP results of FR14, which need their own explicit permission, are planned as additional kinds. Adding a value is a contract change.')).min(1).max(acceptMyInvitationBodyConsentC4FieldsMax).describe('Contact fields the organization may read after the acceptance. The grant covers exactly these fields and no other.') }).describe('Consent C4 given in an acceptance: the text version the candidate saw, an explicit `accepted`, and the contact fields the candidate selected. At least one field is required, so a hidden default or an empty choice never creates a grant. A text version that is not the currently published one answers 400 validation_failed with the pointer `/consent_c4/text_version`, and a field that the profile does not hold answers 400 with the pointer of that item, such as `/consent_c4/fields/1`. C4 is given only here, never at registration. The permission to pass the selected data on to the organization\'s ATS (PRD C4 and FR19) is planned as an additive optional flag that defaults to no transfer.') }).describe('Acceptance of the current terms with the consent C4. The client sends the `version` and the `terms_version` it read and the contact fields the candidate selected; nothing is preselected or defaulted. Unknown fields are rejected, so a request cannot carry contact values, a grant, or another consent.') diff --git a/frontend/src/shared/api/schemas/invitation/candidateHandle.zod.ts b/frontend/src/shared/api/schemas/invitation/candidateHandle.zod.ts index dbf3a39..ad3f2b4 100644 --- a/frontend/src/shared/api/schemas/invitation/candidateHandle.zod.ts +++ b/frontend/src/shared/api/schemas/invitation/candidateHandle.zod.ts @@ -11,7 +11,7 @@ export const CandidateHandleMax = 128; export const CandidateHandleRegExp = new RegExp('^[A-Za-z0-9_-]+$'); -export const CandidateHandle = zod.string().min(1).max(CandidateHandleMax).regex(CandidateHandleRegExp).describe('Opaque reference to a candidate as one organization sees it, taken from a search result card of that organization. It is not the candidate\'s account or profile identifier, it never contains an email address or a phone number, and it means nothing to another organization. The server resolves it only for the organization in the path. Clients never parse it. It is shared by the invitations of FR12 and the search results of FR11 (TASK-185), which issue it.') +export const CandidateHandle = zod.string().min(1).max(CandidateHandleMax).regex(CandidateHandleRegExp).describe('Opaque reference to a candidate as one organization sees it, taken from a search result card of that organization. It is not the candidate\'s account or profile identifier, it never contains an email address or a phone number, and it means nothing to another organization. The server resolves it only for the organization in the path. Clients never parse it. It is shared by the invitations of FR12 and the search results of FR11, which issue it.') export type CandidateHandle = zod.input; export type CandidateHandleOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/candidateInvitation.zod.ts b/frontend/src/shared/api/schemas/invitation/candidateInvitation.zod.ts index 99a9be5..fdb398e 100644 --- a/frontend/src/shared/api/schemas/invitation/candidateInvitation.zod.ts +++ b/frontend/src/shared/api/schemas/invitation/candidateInvitation.zod.ts @@ -151,8 +151,8 @@ export const CandidateInvitation = zod.object({ "text": zod.object({ "text_version": zod.string().min(1).max(candidateInvitationContactConsentOneTextTextVersionMax).regex(candidateInvitationContactConsentOneTextTextVersionRegExp).describe('Identifier of the published consent text that the user saw and accepted. The server stores the acceptance with this version and the hash of its text; the client never sends or receives the hash.'), "text": zod.string().min(1).max(candidateInvitationContactConsentOneTextTextMax).describe('Full consent text in plain UTF-8 with the name of the organization; paragraphs are separated by an empty line. The client shows it as text, never as HTML, next to the field choice.') -}).describe('Currently published text of the consent C4 for this invitation. The server stores an acceptance with `text_version` and the hash of exactly this text, together with the organization, the selected fields, the invitation, and its terms version (the ledger of TASK-062).'), - "available_fields": zod.array(zod.enum(['full_name', 'email', 'phone', 'telegram']).describe('Kind of personal data that the consent C4 can disclose to one organization (PRD FR01 and FR12). The candidate selects each kind separately; one kind never implies another.\n\n- full_name: the full name from the profile.\n- email: the contact email address from the profile.\n- phone: the contact phone number from the profile.\n- telegram: the Telegram username from the profile.\n\nThe value formats are those of ContactDisclosure: 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, TASK-066) must store contacts in the same formats, so a disclosure never has to convert or drop a stored value. The FSP results of FR14, which need their own explicit permission, are planned as additional kinds. Adding a value is a contract change.')).min(1).max(candidateInvitationContactConsentOneAvailableFieldsMax).describe('Kinds of contact that the profile holds and that an acceptance may select. A kind outside this list answers 400 in an acceptance.') +}).describe('Currently published text of the consent C4 for this invitation. The server stores an acceptance with `text_version` and the hash of exactly this text, together with the organization, the selected fields, the invitation, and its terms version (the consent ledger).'), + "available_fields": zod.array(zod.enum(['full_name', 'email', 'phone', 'telegram']).describe('Kind of personal data that the consent C4 can disclose to one organization (PRD FR01 and FR12). The candidate selects each kind separately; one kind never implies another.\n\n- full_name: the full name from the profile.\n- email: the contact email address from the profile.\n- phone: the contact phone number from the profile.\n- telegram: the Telegram username from the profile.\n\nThe value formats are those of ContactDisclosure: 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 has to convert or drop a stored value. The FSP results of FR14, which need their own explicit permission, are planned as additional kinds. Adding a value is a contract change.')).min(1).max(candidateInvitationContactConsentOneAvailableFieldsMax).describe('Kinds of contact that the profile holds and that an acceptance may select. A kind outside this list answers 400 in an acceptance.') }).describe('What the candidate can consent to in an acceptance: the consent text and the kinds of contact that the candidate\'s profile holds now. It holds kinds only, never contact values, and nothing is preselected.'),zod.null()]).describe('Text and choice of the consent C4 for an acceptance, or null when an acceptance is impossible now: the state does not allow it, the deadline has passed, or the profile holds no contact to disclose. In the last case the client tells the candidate to add a contact to the profile first, because a grant must cover at least one field.'), "decline": zod.union([zod.object({ "reason": zod.enum(['salary', 'tasks', 'stack', 'work_format', 'package', 'company', 'not_looking', 'other_offer', 'other']).describe('Structured reason of a decline. Every reason is neutral and none requires a comment.\n\n- salary: the salary range does not fit.\n- tasks: the role or the tasks do not fit.\n- stack: the technologies do not fit.\n- work_format: the work format or the place of work does not fit.\n- package: the package does not fit.\n- company: the company or its domain does not fit.\n- not_looking: the candidate is not looking for a job now.\n- other_offer: the candidate accepted another offer.\n- other: another reason ("Другое"); a comment stays optional.\n\nThe organization never sees the reason of an individual decline: a reason such as `salary` would tell it that the hidden minimum is above the range. Reasons feed only the aggregates of FR12 with a minimum group size (planned). Adding a value is a contract change.'), @@ -161,7 +161,7 @@ export const CandidateInvitation = zod.object({ }).describe('The candidate\'s own decline, as the candidate reads it back.'),zod.null()]).describe('The candidate\'s decline, or null unless `state` is `declined`.'), "contact_grant": zod.union([zod.object({ "id": zod.uuid().describe('Identifier of the grant.'), - "fields": zod.array(zod.enum(['full_name', 'email', 'phone', 'telegram']).describe('Kind of personal data that the consent C4 can disclose to one organization (PRD FR01 and FR12). The candidate selects each kind separately; one kind never implies another.\n\n- full_name: the full name from the profile.\n- email: the contact email address from the profile.\n- phone: the contact phone number from the profile.\n- telegram: the Telegram username from the profile.\n\nThe value formats are those of ContactDisclosure: 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, TASK-066) must store contacts in the same formats, so a disclosure never has to convert or drop a stored value. The FSP results of FR14, which need their own explicit permission, are planned as additional kinds. Adding a value is a contract change.')).min(1).max(candidateInvitationContactGrantOneFieldsMax).describe('Contact fields that the grant covers.'), + "fields": zod.array(zod.enum(['full_name', 'email', 'phone', 'telegram']).describe('Kind of personal data that the consent C4 can disclose to one organization (PRD FR01 and FR12). The candidate selects each kind separately; one kind never implies another.\n\n- full_name: the full name from the profile.\n- email: the contact email address from the profile.\n- phone: the contact phone number from the profile.\n- telegram: the Telegram username from the profile.\n\nThe value formats are those of ContactDisclosure: 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 has to convert or drop a stored value. The FSP results of FR14, which need their own explicit permission, are planned as additional kinds. Adding a value is a contract change.')).min(1).max(candidateInvitationContactGrantOneFieldsMax).describe('Contact fields that the grant covers.'), "status": zod.enum(['active', 'revoked']).describe('State of a contact grant.\n\n- active: the grant exists. Each read by the organization still checks the consent C4, the grant, and the current visibility of the profile.\n- revoked: the grant is closed for good; the organization reads no contact through it. A later publication of the profile or a new acceptance never reopens it; only a new explicit C4 creates a new grant.'), "readable": zod.boolean().describe('Whether the organization can read the covered fields now: true only for an active grant whose current consent and visibility allow the read. The organization sees the same fact as `contact_access.status` `available`, without the reason.'), "blocked_by": zod.union([zod.enum(['visibility']).describe('Why an active grant does not allow a read now, shown only to the candidate.\n\n- visibility: the profile was not published (C2) or was hidden from the organization when the candidate accepted, and it still is. The acceptance never publishes the profile or lifts the hiding by itself (PRD FR12); the grant becomes readable once the candidate publishes the profile or unhides it for the organization.'),zod.null()]).describe('Why an active grant is not readable now, or null when it is readable or revoked; a revoked grant has `revocation_reason` instead.'), diff --git a/frontend/src/shared/api/schemas/invitation/contactConsentAcceptance.zod.ts b/frontend/src/shared/api/schemas/invitation/contactConsentAcceptance.zod.ts index c167dc5..369f78b 100644 --- a/frontend/src/shared/api/schemas/invitation/contactConsentAcceptance.zod.ts +++ b/frontend/src/shared/api/schemas/invitation/contactConsentAcceptance.zod.ts @@ -16,7 +16,7 @@ export const contactConsentAcceptanceFieldsMax = 4; export const ContactConsentAcceptance = zod.object({ "text_version": zod.string().min(1).max(contactConsentAcceptanceTextVersionMax).regex(contactConsentAcceptanceTextVersionRegExp).describe('Identifier of the published consent text that the user saw and accepted. The server stores the acceptance with this version and the hash of its text; the client never sends or receives the hash.'), "accepted": zod.literal(true).describe('Explicit consent. Only true is valid.'), - "fields": zod.array(zod.enum(['full_name', 'email', 'phone', 'telegram']).describe('Kind of personal data that the consent C4 can disclose to one organization (PRD FR01 and FR12). The candidate selects each kind separately; one kind never implies another.\n\n- full_name: the full name from the profile.\n- email: the contact email address from the profile.\n- phone: the contact phone number from the profile.\n- telegram: the Telegram username from the profile.\n\nThe value formats are those of ContactDisclosure: 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, TASK-066) must store contacts in the same formats, so a disclosure never has to convert or drop a stored value. The FSP results of FR14, which need their own explicit permission, are planned as additional kinds. Adding a value is a contract change.')).min(1).max(contactConsentAcceptanceFieldsMax).describe('Contact fields the organization may read after the acceptance. The grant covers exactly these fields and no other.') + "fields": zod.array(zod.enum(['full_name', 'email', 'phone', 'telegram']).describe('Kind of personal data that the consent C4 can disclose to one organization (PRD FR01 and FR12). The candidate selects each kind separately; one kind never implies another.\n\n- full_name: the full name from the profile.\n- email: the contact email address from the profile.\n- phone: the contact phone number from the profile.\n- telegram: the Telegram username from the profile.\n\nThe value formats are those of ContactDisclosure: 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 has to convert or drop a stored value. The FSP results of FR14, which need their own explicit permission, are planned as additional kinds. Adding a value is a contract change.')).min(1).max(contactConsentAcceptanceFieldsMax).describe('Contact fields the organization may read after the acceptance. The grant covers exactly these fields and no other.') }).describe('Consent C4 given in an acceptance: the text version the candidate saw, an explicit `accepted`, and the contact fields the candidate selected. At least one field is required, so a hidden default or an empty choice never creates a grant. A text version that is not the currently published one answers 400 validation_failed with the pointer `/consent_c4/text_version`, and a field that the profile does not hold answers 400 with the pointer of that item, such as `/consent_c4/fields/1`. C4 is given only here, never at registration. The permission to pass the selected data on to the organization\'s ATS (PRD C4 and FR19) is planned as an additive optional flag that defaults to no transfer.') export type ContactConsentAcceptance = zod.input; diff --git a/frontend/src/shared/api/schemas/invitation/contactConsentOffer.zod.ts b/frontend/src/shared/api/schemas/invitation/contactConsentOffer.zod.ts index 1bc653a..245ec31 100644 --- a/frontend/src/shared/api/schemas/invitation/contactConsentOffer.zod.ts +++ b/frontend/src/shared/api/schemas/invitation/contactConsentOffer.zod.ts @@ -19,8 +19,8 @@ export const ContactConsentOffer = zod.object({ "text": zod.object({ "text_version": zod.string().min(1).max(contactConsentOfferTextTextVersionMax).regex(contactConsentOfferTextTextVersionRegExp).describe('Identifier of the published consent text that the user saw and accepted. The server stores the acceptance with this version and the hash of its text; the client never sends or receives the hash.'), "text": zod.string().min(1).max(contactConsentOfferTextTextMax).describe('Full consent text in plain UTF-8 with the name of the organization; paragraphs are separated by an empty line. The client shows it as text, never as HTML, next to the field choice.') -}).describe('Currently published text of the consent C4 for this invitation. The server stores an acceptance with `text_version` and the hash of exactly this text, together with the organization, the selected fields, the invitation, and its terms version (the ledger of TASK-062).'), - "available_fields": zod.array(zod.enum(['full_name', 'email', 'phone', 'telegram']).describe('Kind of personal data that the consent C4 can disclose to one organization (PRD FR01 and FR12). The candidate selects each kind separately; one kind never implies another.\n\n- full_name: the full name from the profile.\n- email: the contact email address from the profile.\n- phone: the contact phone number from the profile.\n- telegram: the Telegram username from the profile.\n\nThe value formats are those of ContactDisclosure: 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, TASK-066) must store contacts in the same formats, so a disclosure never has to convert or drop a stored value. The FSP results of FR14, which need their own explicit permission, are planned as additional kinds. Adding a value is a contract change.')).min(1).max(contactConsentOfferAvailableFieldsMax).describe('Kinds of contact that the profile holds and that an acceptance may select. A kind outside this list answers 400 in an acceptance.') +}).describe('Currently published text of the consent C4 for this invitation. The server stores an acceptance with `text_version` and the hash of exactly this text, together with the organization, the selected fields, the invitation, and its terms version (the consent ledger).'), + "available_fields": zod.array(zod.enum(['full_name', 'email', 'phone', 'telegram']).describe('Kind of personal data that the consent C4 can disclose to one organization (PRD FR01 and FR12). The candidate selects each kind separately; one kind never implies another.\n\n- full_name: the full name from the profile.\n- email: the contact email address from the profile.\n- phone: the contact phone number from the profile.\n- telegram: the Telegram username from the profile.\n\nThe value formats are those of ContactDisclosure: 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 has to convert or drop a stored value. The FSP results of FR14, which need their own explicit permission, are planned as additional kinds. Adding a value is a contract change.')).min(1).max(contactConsentOfferAvailableFieldsMax).describe('Kinds of contact that the profile holds and that an acceptance may select. A kind outside this list answers 400 in an acceptance.') }).describe('What the candidate can consent to in an acceptance: the consent text and the kinds of contact that the candidate\'s profile holds now. It holds kinds only, never contact values, and nothing is preselected.') export type ContactConsentOffer = zod.input; diff --git a/frontend/src/shared/api/schemas/invitation/contactConsentText.zod.ts b/frontend/src/shared/api/schemas/invitation/contactConsentText.zod.ts index 2c39d94..cdfabd8 100644 --- a/frontend/src/shared/api/schemas/invitation/contactConsentText.zod.ts +++ b/frontend/src/shared/api/schemas/invitation/contactConsentText.zod.ts @@ -16,7 +16,7 @@ export const contactConsentTextTextMax = 100000; export const ContactConsentText = zod.object({ "text_version": zod.string().min(1).max(contactConsentTextTextVersionMax).regex(contactConsentTextTextVersionRegExp).describe('Identifier of the published consent text that the user saw and accepted. The server stores the acceptance with this version and the hash of its text; the client never sends or receives the hash.'), "text": zod.string().min(1).max(contactConsentTextTextMax).describe('Full consent text in plain UTF-8 with the name of the organization; paragraphs are separated by an empty line. The client shows it as text, never as HTML, next to the field choice.') -}).describe('Currently published text of the consent C4 for this invitation. The server stores an acceptance with `text_version` and the hash of exactly this text, together with the organization, the selected fields, the invitation, and its terms version (the ledger of TASK-062).') +}).describe('Currently published text of the consent C4 for this invitation. The server stores an acceptance with `text_version` and the hash of exactly this text, together with the organization, the selected fields, the invitation, and its terms version (the consent ledger).') export type ContactConsentText = zod.input; export type ContactConsentTextOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/contactDisclosure.zod.ts b/frontend/src/shared/api/schemas/invitation/contactDisclosure.zod.ts index abfe0f6..7a5ec8b 100644 --- a/frontend/src/shared/api/schemas/invitation/contactDisclosure.zod.ts +++ b/frontend/src/shared/api/schemas/invitation/contactDisclosure.zod.ts @@ -29,13 +29,13 @@ export const contactDisclosureTelegramOneRegExp = new RegExp('^@[A-Za-z0-9_]{5,3 export const ContactDisclosure = zod.object({ "invitation_id": zod.uuid().describe('Invitation whose acceptance created the grant.'), "grant_id": zod.uuid().describe('Grant that allows the read.'), - "fields": zod.array(zod.enum(['full_name', 'email', 'phone', 'telegram']).describe('Kind of personal data that the consent C4 can disclose to one organization (PRD FR01 and FR12). The candidate selects each kind separately; one kind never implies another.\n\n- full_name: the full name from the profile.\n- email: the contact email address from the profile.\n- phone: the contact phone number from the profile.\n- telegram: the Telegram username from the profile.\n\nThe value formats are those of ContactDisclosure: 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, TASK-066) must store contacts in the same formats, so a disclosure never has to convert or drop a stored value. The FSP results of FR14, which need their own explicit permission, are planned as additional kinds. Adding a value is a contract change.')).min(1).max(contactDisclosureFieldsMax).describe('Contact fields that the grant covers.'), + "fields": zod.array(zod.enum(['full_name', 'email', 'phone', 'telegram']).describe('Kind of personal data that the consent C4 can disclose to one organization (PRD FR01 and FR12). The candidate selects each kind separately; one kind never implies another.\n\n- full_name: the full name from the profile.\n- email: the contact email address from the profile.\n- phone: the contact phone number from the profile.\n- telegram: the Telegram username from the profile.\n\nThe value formats are those of ContactDisclosure: 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 has to convert or drop a stored value. The FSP results of FR14, which need their own explicit permission, are planned as additional kinds. Adding a value is a contract change.')).min(1).max(contactDisclosureFieldsMax).describe('Contact fields that the grant covers.'), "granted_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'), "full_name": zod.union([zod.string().min(1).max(contactDisclosureFullNameOneMax).regex(contactDisclosureFullNameOneRegExp).describe('Full name as the candidate wrote it in the profile. Plain text without line breaks; clients show it as text, never as HTML.'),zod.null()]), "email": zod.union([zod.email().min(contactDisclosureEmailOneMin).max(contactDisclosureEmailOneMax).describe('Account email address. The server compares addresses without regard to letter case and never reveals in a response whether an address belongs to an account.'),zod.null()]), "phone": zod.union([zod.string().min(contactDisclosurePhoneOneMin).max(contactDisclosurePhoneOneMax).regex(contactDisclosurePhoneOneRegExp).describe('Phone number in the E.164 format, for example +70000000000.'),zod.null()]), "telegram": zod.union([zod.string().min(contactDisclosureTelegramOneMin).max(contactDisclosureTelegramOneMax).regex(contactDisclosureTelegramOneRegExp).describe('Telegram username with the leading @.'),zod.null()]) -}).describe('Contacts of the candidate that the organization may read through an active grant of this invitation. This is the only response that carries contact values, and it is separate from the terms and from the invitation. Each field the grant does not cover is null, and so is a covered field that the profile no longer holds. The response is never cached or stored by the server for later reads, so a revocation closes the next read at once. The value formats depend on the profile contract (FR02, TASK-066), which must store the same formats; see ContactFieldKind.') +}).describe('Contacts of the candidate that the organization may read through an active grant of this invitation. This is the only response that carries contact values, and it is separate from the terms and from the invitation. Each field the grant does not cover is null, and so is a covered field that the profile no longer holds. The response is never cached or stored by the server for later reads, so a revocation closes the next read at once. The value formats depend on the profile contract (FR02), which must store the same formats; see ContactFieldKind.') export type ContactDisclosure = zod.input; export type ContactDisclosureOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/contactGrant.zod.ts b/frontend/src/shared/api/schemas/invitation/contactGrant.zod.ts index dd713e6..fd5a3ab 100644 --- a/frontend/src/shared/api/schemas/invitation/contactGrant.zod.ts +++ b/frontend/src/shared/api/schemas/invitation/contactGrant.zod.ts @@ -16,7 +16,7 @@ export const contactGrantConsentTextVersionOneRegExp = new RegExp('^[A-Za-z0-9._ export const ContactGrant = zod.object({ "id": zod.uuid().describe('Identifier of the grant.'), - "fields": zod.array(zod.enum(['full_name', 'email', 'phone', 'telegram']).describe('Kind of personal data that the consent C4 can disclose to one organization (PRD FR01 and FR12). The candidate selects each kind separately; one kind never implies another.\n\n- full_name: the full name from the profile.\n- email: the contact email address from the profile.\n- phone: the contact phone number from the profile.\n- telegram: the Telegram username from the profile.\n\nThe value formats are those of ContactDisclosure: 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, TASK-066) must store contacts in the same formats, so a disclosure never has to convert or drop a stored value. The FSP results of FR14, which need their own explicit permission, are planned as additional kinds. Adding a value is a contract change.')).min(1).max(contactGrantFieldsMax).describe('Contact fields that the grant covers.'), + "fields": zod.array(zod.enum(['full_name', 'email', 'phone', 'telegram']).describe('Kind of personal data that the consent C4 can disclose to one organization (PRD FR01 and FR12). The candidate selects each kind separately; one kind never implies another.\n\n- full_name: the full name from the profile.\n- email: the contact email address from the profile.\n- phone: the contact phone number from the profile.\n- telegram: the Telegram username from the profile.\n\nThe value formats are those of ContactDisclosure: 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 has to convert or drop a stored value. The FSP results of FR14, which need their own explicit permission, are planned as additional kinds. Adding a value is a contract change.')).min(1).max(contactGrantFieldsMax).describe('Contact fields that the grant covers.'), "status": zod.enum(['active', 'revoked']).describe('State of a contact grant.\n\n- active: the grant exists. Each read by the organization still checks the consent C4, the grant, and the current visibility of the profile.\n- revoked: the grant is closed for good; the organization reads no contact through it. A later publication of the profile or a new acceptance never reopens it; only a new explicit C4 creates a new grant.'), "readable": zod.boolean().describe('Whether the organization can read the covered fields now: true only for an active grant whose current consent and visibility allow the read. The organization sees the same fact as `contact_access.status` `available`, without the reason.'), "blocked_by": zod.union([zod.enum(['visibility']).describe('Why an active grant does not allow a read now, shown only to the candidate.\n\n- visibility: the profile was not published (C2) or was hidden from the organization when the candidate accepted, and it still is. The acceptance never publishes the profile or lifts the hiding by itself (PRD FR12); the grant becomes readable once the candidate publishes the profile or unhides it for the organization.'),zod.null()]).describe('Why an active grant is not readable now, or null when it is readable or revoked; a revoked grant has `revocation_reason` instead.'), diff --git a/frontend/src/shared/api/schemas/invitation/createOrganizationInvitationBody.zod.ts b/frontend/src/shared/api/schemas/invitation/createOrganizationInvitationBody.zod.ts index 0715d8b..22ef736 100644 --- a/frontend/src/shared/api/schemas/invitation/createOrganizationInvitationBody.zod.ts +++ b/frontend/src/shared/api/schemas/invitation/createOrganizationInvitationBody.zod.ts @@ -67,7 +67,7 @@ export const createOrganizationInvitationBodyTermsPackageHealthInsuranceOneDescr export const createOrganizationInvitationBodyTermsPackageHealthInsuranceOneDescriptionRegExp = new RegExp('^\\S(?:.*\\S)?$'); export const CreateOrganizationInvitationBody = zod.object({ - "candidate_handle": zod.string().min(1).max(createOrganizationInvitationBodyCandidateHandleMax).regex(createOrganizationInvitationBodyCandidateHandleRegExp).describe('Opaque reference to a candidate as one organization sees it, taken from a search result card of that organization. It is not the candidate\'s account or profile identifier, it never contains an email address or a phone number, and it means nothing to another organization. The server resolves it only for the organization in the path. Clients never parse it. It is shared by the invitations of FR12 and the search results of FR11 (TASK-185), which issue it.'), + "candidate_handle": zod.string().min(1).max(createOrganizationInvitationBodyCandidateHandleMax).regex(createOrganizationInvitationBodyCandidateHandleRegExp).describe('Opaque reference to a candidate as one organization sees it, taken from a search result card of that organization. It is not the candidate\'s account or profile identifier, it never contains an email address or a phone number, and it means nothing to another organization. The server resolves it only for the organization in the path. Clients never parse it. It is shared by the invitations of FR12 and the search results of FR11, which issue it.'), "need": zod.union([zod.object({ "need_id": zod.uuid().describe('Identifier of a need of the organization in the path.'), "requirements_version": zod.int().min(1).describe('Version of an employer need. Creation makes version 1, and every committed change of the need advances it by exactly one, including a change made by the server, such as a planned asynchronous ML suggestion. Each version is an immutable snapshot of the need. `requirements_version` names the version whose confirmed requirements are current, so a change that leaves them unchanged creates a need version without a new requirements version.').describe('`requirements_version` of the need that the invitation refers to; it must be a version that the need has had.') diff --git a/frontend/src/shared/api/schemas/invitation/invitationAcceptance.zod.ts b/frontend/src/shared/api/schemas/invitation/invitationAcceptance.zod.ts index 5f0b105..24c8591 100644 --- a/frontend/src/shared/api/schemas/invitation/invitationAcceptance.zod.ts +++ b/frontend/src/shared/api/schemas/invitation/invitationAcceptance.zod.ts @@ -21,7 +21,7 @@ export const InvitationAcceptance = zod.object({ "consent_c4": zod.object({ "text_version": zod.string().min(1).max(invitationAcceptanceConsentC4TextVersionMax).regex(invitationAcceptanceConsentC4TextVersionRegExp).describe('Identifier of the published consent text that the user saw and accepted. The server stores the acceptance with this version and the hash of its text; the client never sends or receives the hash.'), "accepted": zod.literal(true).describe('Explicit consent. Only true is valid.'), - "fields": zod.array(zod.enum(['full_name', 'email', 'phone', 'telegram']).describe('Kind of personal data that the consent C4 can disclose to one organization (PRD FR01 and FR12). The candidate selects each kind separately; one kind never implies another.\n\n- full_name: the full name from the profile.\n- email: the contact email address from the profile.\n- phone: the contact phone number from the profile.\n- telegram: the Telegram username from the profile.\n\nThe value formats are those of ContactDisclosure: 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, TASK-066) must store contacts in the same formats, so a disclosure never has to convert or drop a stored value. The FSP results of FR14, which need their own explicit permission, are planned as additional kinds. Adding a value is a contract change.')).min(1).max(invitationAcceptanceConsentC4FieldsMax).describe('Contact fields the organization may read after the acceptance. The grant covers exactly these fields and no other.') + "fields": zod.array(zod.enum(['full_name', 'email', 'phone', 'telegram']).describe('Kind of personal data that the consent C4 can disclose to one organization (PRD FR01 and FR12). The candidate selects each kind separately; one kind never implies another.\n\n- full_name: the full name from the profile.\n- email: the contact email address from the profile.\n- phone: the contact phone number from the profile.\n- telegram: the Telegram username from the profile.\n\nThe value formats are those of ContactDisclosure: 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 has to convert or drop a stored value. The FSP results of FR14, which need their own explicit permission, are planned as additional kinds. Adding a value is a contract change.')).min(1).max(invitationAcceptanceConsentC4FieldsMax).describe('Contact fields the organization may read after the acceptance. The grant covers exactly these fields and no other.') }).describe('Consent C4 given in an acceptance: the text version the candidate saw, an explicit `accepted`, and the contact fields the candidate selected. At least one field is required, so a hidden default or an empty choice never creates a grant. A text version that is not the currently published one answers 400 validation_failed with the pointer `/consent_c4/text_version`, and a field that the profile does not hold answers 400 with the pointer of that item, such as `/consent_c4/fields/1`. C4 is given only here, never at registration. The permission to pass the selected data on to the organization\'s ATS (PRD C4 and FR19) is planned as an additive optional flag that defaults to no transfer.') }).describe('Acceptance of the current terms with the consent C4. The client sends the `version` and the `terms_version` it read and the contact fields the candidate selected; nothing is preselected or defaulted. Unknown fields are rejected, so a request cannot carry contact values, a grant, or another consent.') diff --git a/frontend/src/shared/api/schemas/invitation/invitationContactAccess.zod.ts b/frontend/src/shared/api/schemas/invitation/invitationContactAccess.zod.ts index 405bb66..497be4a 100644 --- a/frontend/src/shared/api/schemas/invitation/invitationContactAccess.zod.ts +++ b/frontend/src/shared/api/schemas/invitation/invitationContactAccess.zod.ts @@ -11,7 +11,7 @@ export const invitationContactAccessFieldsMax = 4; export const InvitationContactAccess = zod.object({ "status": zod.enum(['not_granted', 'available', 'closed']).describe('Whether the organization may read the candidate\'s contacts through GetOrganizationInvitationContacts now.\n\n- not_granted: the candidate has not accepted this invitation, so no grant exists.\n- available: a grant from this invitation is active and the current consent and visibility allow the read.\n- closed: a grant from this invitation exists but does not allow the read now: it was revoked (the candidate revoked C4, cancelled the participation, or revoked the publication C2 or hid the profile after the acceptance), or it was created while the visibility already did not allow the read. The organization is not told which. A revoked grant never becomes `available` again; a grant blocked from the start becomes `available` once the candidate\'s visibility allows the read, which only follows the candidate\'s own choice to publish the profile or unhide it for the organization. Since every visibility change after a grant exists revokes the grant, a later toggle is never visible to the organization.'), - "fields": zod.array(zod.enum(['full_name', 'email', 'phone', 'telegram']).describe('Kind of personal data that the consent C4 can disclose to one organization (PRD FR01 and FR12). The candidate selects each kind separately; one kind never implies another.\n\n- full_name: the full name from the profile.\n- email: the contact email address from the profile.\n- phone: the contact phone number from the profile.\n- telegram: the Telegram username from the profile.\n\nThe value formats are those of ContactDisclosure: 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, TASK-066) must store contacts in the same formats, so a disclosure never has to convert or drop a stored value. The FSP results of FR14, which need their own explicit permission, are planned as additional kinds. Adding a value is a contract change.')).max(invitationContactAccessFieldsMax).describe('Kinds of contact that the read returns while `status` is `available`; empty otherwise.') + "fields": zod.array(zod.enum(['full_name', 'email', 'phone', 'telegram']).describe('Kind of personal data that the consent C4 can disclose to one organization (PRD FR01 and FR12). The candidate selects each kind separately; one kind never implies another.\n\n- full_name: the full name from the profile.\n- email: the contact email address from the profile.\n- phone: the contact phone number from the profile.\n- telegram: the Telegram username from the profile.\n\nThe value formats are those of ContactDisclosure: 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 has to convert or drop a stored value. The FSP results of FR14, which need their own explicit permission, are planned as additional kinds. Adding a value is a contract change.')).max(invitationContactAccessFieldsMax).describe('Kinds of contact that the read returns while `status` is `available`; empty otherwise.') }).describe('Contact access of the organization through this invitation, without any contact value. The values come only from GetOrganizationInvitationContacts.') export type InvitationContactAccess = zod.input; diff --git a/frontend/src/shared/api/schemas/invitation/invitationSalaryFit.zod.ts b/frontend/src/shared/api/schemas/invitation/invitationSalaryFit.zod.ts index 545e01e..f1dfc89 100644 --- a/frontend/src/shared/api/schemas/invitation/invitationSalaryFit.zod.ts +++ b/frontend/src/shared/api/schemas/invitation/invitationSalaryFit.zod.ts @@ -6,7 +6,7 @@ */ import * as zod from 'zod'; -export const InvitationSalaryFit = zod.enum(['within_range', 'up_to_10_percent_above', 'above', 'withheld', 'not_available']).describe('Coarse indicator for the organization of how the salary range relates to the candidate\'s hidden minimum (PRD FR13). It is the only information about the minimum that the organization receives; the exact minimum never appears in any response, log, or problem. The server compares the upper bound `B` with the lowest minimum the candidate set for the offered work formats, in integer arithmetic and only in the same tax basis.\n\n- within_range: the minimum is not above `B`.\n- up_to_10_percent_above: the minimum is above `B` by at most 10%, that is `10 * minimum <= 11 * B`.\n- above: the minimum is more than 10% above `B`.\n- withheld: the organization made five indicator-relevant settings within seven days, so the indicator is off for seven days from the fifth (the limit of TASK-211). The response to the fifth setting already carries `withheld`, and so does every draft and invitation of the organization, existing ones included, until the period ends.\n- not_available: the candidate set no minimum for the offered formats, or set it in the other tax basis.\n\nEvery change that can move this indicator is an indicator-relevant setting: the range set on creation, and in a draft a change of either bound, of the tax basis, or of `work_formats`, since the minimum depends on the format. Each counts against the organization-wide limit of three settings a day (429) and against the withheld counter of five settings within seven days, together with the ranges of needs. The one raise of the upper bound of a sent invitation counts against the withheld counter but not against the daily limit, because FR13 gives it its own once-only rule. 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.\n\nThe server never rejects or changes a range because of the minimum: a rejection would itself reveal it.') +export const InvitationSalaryFit = zod.enum(['within_range', 'up_to_10_percent_above', 'above', 'withheld', 'not_available']).describe('Coarse indicator for the organization of how the salary range relates to the candidate\'s hidden minimum (PRD FR13). It is the only information about the minimum that the organization receives; the exact minimum never appears in any response, log, or problem. The server compares the upper bound `B` with the lowest minimum the candidate set for the offered work formats, in integer arithmetic and only in the same tax basis.\n\n- within_range: the minimum is not above `B`.\n- up_to_10_percent_above: the minimum is above `B` by at most 10%, that is `10 * minimum <= 11 * B`.\n- above: the minimum is more than 10% above `B`.\n- withheld: the organization made five indicator-relevant settings within seven days, so the indicator is off for seven days from the fifth. The response to the fifth setting already carries `withheld`, and so does every draft and invitation of the organization, existing ones included, until the period ends.\n- not_available: the candidate set no minimum for the offered formats, or set it in the other tax basis.\n\nEvery change that can move this indicator is an indicator-relevant setting: the range set on creation, and in a draft a change of either bound, of the tax basis, or of `work_formats`, since the minimum depends on the format. Each counts against the organization-wide limit of three settings a day (429) and against the withheld counter of five settings within seven days, together with the ranges of needs. The one raise of the upper bound of a sent invitation counts against the withheld counter but not against the daily limit, because FR13 gives it its own once-only rule. 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.\n\nThe server never rejects or changes a range because of the minimum: a rejection would itself reveal it.') export type InvitationSalaryFit = zod.input; export type InvitationSalaryFitOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/organizationInvitation.zod.ts b/frontend/src/shared/api/schemas/invitation/organizationInvitation.zod.ts index bb8cc52..9a46ce3 100644 --- a/frontend/src/shared/api/schemas/invitation/organizationInvitation.zod.ts +++ b/frontend/src/shared/api/schemas/invitation/organizationInvitation.zod.ts @@ -73,7 +73,7 @@ export const organizationInvitationContactAccessFieldsMax = 4; export const OrganizationInvitation = zod.object({ "id": zod.uuid().describe('Identifier of the invitation.'), "organization_id": zod.uuid().describe('Organization that owns the invitation, equal to `org_id` of the path. It never changes.'), - "candidate_handle": zod.string().min(1).max(organizationInvitationCandidateHandleMax).regex(organizationInvitationCandidateHandleRegExp).describe('Opaque reference to a candidate as one organization sees it, taken from a search result card of that organization. It is not the candidate\'s account or profile identifier, it never contains an email address or a phone number, and it means nothing to another organization. The server resolves it only for the organization in the path. Clients never parse it. It is shared by the invitations of FR12 and the search results of FR11 (TASK-185), which issue it.'), + "candidate_handle": zod.string().min(1).max(organizationInvitationCandidateHandleMax).regex(organizationInvitationCandidateHandleRegExp).describe('Opaque reference to a candidate as one organization sees it, taken from a search result card of that organization. It is not the candidate\'s account or profile identifier, it never contains an email address or a phone number, and it means nothing to another organization. The server resolves it only for the organization in the path. Clients never parse it. It is shared by the invitations of FR12 and the search results of FR11, which issue it.'), "need": zod.union([zod.object({ "need_id": zod.uuid().describe('Identifier of a need of the organization in the path.'), "requirements_version": zod.int().min(1).describe('Version of an employer need. Creation makes version 1, and every committed change of the need advances it by exactly one, including a change made by the server, such as a planned asynchronous ML suggestion. Each version is an immutable snapshot of the need. `requirements_version` names the version whose confirmed requirements are current, so a change that leaves them unchanged creates a need version without a new requirements version.').describe('`requirements_version` of the need that the invitation refers to; it must be a version that the need has had.') @@ -133,10 +133,10 @@ export const OrganizationInvitation = zod.object({ "response_period_days": zod.union([zod.literal(3),zod.literal(7),zod.literal(14)]).describe('Days the candidate has to answer, chosen by the organization in the draft from the product policy: 3, 7, or 14. The deadline starts at the first delivery and is never reset by an email, a view, or a counter offer.'), "response_deadline_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('Moment when the candidate\'s time to answer ends, set at the first delivery to `delivered_at` plus `response_period_days`, or null for a draft. A command received at this moment or later is late. After an acceptance the deadline no longer applies.'), "salary_raise_used": zod.boolean().describe('Whether the one raise of the upper salary bound after sending (PRD FR13) has been used. It counts the whole history of the invitation.'), - "salary_fit": zod.enum(['within_range', 'up_to_10_percent_above', 'above', 'withheld', 'not_available']).describe('Coarse indicator for the organization of how the salary range relates to the candidate\'s hidden minimum (PRD FR13). It is the only information about the minimum that the organization receives; the exact minimum never appears in any response, log, or problem. The server compares the upper bound `B` with the lowest minimum the candidate set for the offered work formats, in integer arithmetic and only in the same tax basis.\n\n- within_range: the minimum is not above `B`.\n- up_to_10_percent_above: the minimum is above `B` by at most 10%, that is `10 * minimum <= 11 * B`.\n- above: the minimum is more than 10% above `B`.\n- withheld: the organization made five indicator-relevant settings within seven days, so the indicator is off for seven days from the fifth (the limit of TASK-211). The response to the fifth setting already carries `withheld`, and so does every draft and invitation of the organization, existing ones included, until the period ends.\n- not_available: the candidate set no minimum for the offered formats, or set it in the other tax basis.\n\nEvery change that can move this indicator is an indicator-relevant setting: the range set on creation, and in a draft a change of either bound, of the tax basis, or of `work_formats`, since the minimum depends on the format. Each counts against the organization-wide limit of three settings a day (429) and against the withheld counter of five settings within seven days, together with the ranges of needs. The one raise of the upper bound of a sent invitation counts against the withheld counter but not against the daily limit, because FR13 gives it its own once-only rule. 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.\n\nThe server never rejects or changes a range because of the minimum: a rejection would itself reveal it.'), + "salary_fit": zod.enum(['within_range', 'up_to_10_percent_above', 'above', 'withheld', 'not_available']).describe('Coarse indicator for the organization of how the salary range relates to the candidate\'s hidden minimum (PRD FR13). It is the only information about the minimum that the organization receives; the exact minimum never appears in any response, log, or problem. The server compares the upper bound `B` with the lowest minimum the candidate set for the offered work formats, in integer arithmetic and only in the same tax basis.\n\n- within_range: the minimum is not above `B`.\n- up_to_10_percent_above: the minimum is above `B` by at most 10%, that is `10 * minimum <= 11 * B`.\n- above: the minimum is more than 10% above `B`.\n- withheld: the organization made five indicator-relevant settings within seven days, so the indicator is off for seven days from the fifth. The response to the fifth setting already carries `withheld`, and so does every draft and invitation of the organization, existing ones included, until the period ends.\n- not_available: the candidate set no minimum for the offered formats, or set it in the other tax basis.\n\nEvery change that can move this indicator is an indicator-relevant setting: the range set on creation, and in a draft a change of either bound, of the tax basis, or of `work_formats`, since the minimum depends on the format. Each counts against the organization-wide limit of three settings a day (429) and against the withheld counter of five settings within seven days, together with the ranges of needs. The one raise of the upper bound of a sent invitation counts against the withheld counter but not against the daily limit, because FR13 gives it its own once-only rule. 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.\n\nThe server never rejects or changes a range because of the minimum: a rejection would itself reveal it.'), "contact_access": zod.object({ "status": zod.enum(['not_granted', 'available', 'closed']).describe('Whether the organization may read the candidate\'s contacts through GetOrganizationInvitationContacts now.\n\n- not_granted: the candidate has not accepted this invitation, so no grant exists.\n- available: a grant from this invitation is active and the current consent and visibility allow the read.\n- closed: a grant from this invitation exists but does not allow the read now: it was revoked (the candidate revoked C4, cancelled the participation, or revoked the publication C2 or hid the profile after the acceptance), or it was created while the visibility already did not allow the read. The organization is not told which. A revoked grant never becomes `available` again; a grant blocked from the start becomes `available` once the candidate\'s visibility allows the read, which only follows the candidate\'s own choice to publish the profile or unhide it for the organization. Since every visibility change after a grant exists revokes the grant, a later toggle is never visible to the organization.'), - "fields": zod.array(zod.enum(['full_name', 'email', 'phone', 'telegram']).describe('Kind of personal data that the consent C4 can disclose to one organization (PRD FR01 and FR12). The candidate selects each kind separately; one kind never implies another.\n\n- full_name: the full name from the profile.\n- email: the contact email address from the profile.\n- phone: the contact phone number from the profile.\n- telegram: the Telegram username from the profile.\n\nThe value formats are those of ContactDisclosure: 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, TASK-066) must store contacts in the same formats, so a disclosure never has to convert or drop a stored value. The FSP results of FR14, which need their own explicit permission, are planned as additional kinds. Adding a value is a contract change.')).max(organizationInvitationContactAccessFieldsMax).describe('Kinds of contact that the read returns while `status` is `available`; empty otherwise.') + "fields": zod.array(zod.enum(['full_name', 'email', 'phone', 'telegram']).describe('Kind of personal data that the consent C4 can disclose to one organization (PRD FR01 and FR12). The candidate selects each kind separately; one kind never implies another.\n\n- full_name: the full name from the profile.\n- email: the contact email address from the profile.\n- phone: the contact phone number from the profile.\n- telegram: the Telegram username from the profile.\n\nThe value formats are those of ContactDisclosure: 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 has to convert or drop a stored value. The FSP results of FR14, which need their own explicit permission, are planned as additional kinds. Adding a value is a contract change.')).max(organizationInvitationContactAccessFieldsMax).describe('Kinds of contact that the read returns while `status` is `available`; empty otherwise.') }).describe('Contact access of the organization through this invitation, without any contact value. The values come only from GetOrganizationInvitationContacts.'), "created_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'), "updated_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'), diff --git a/frontend/src/shared/api/schemas/invitation/organizationInvitationCreate.zod.ts b/frontend/src/shared/api/schemas/invitation/organizationInvitationCreate.zod.ts index 46f26ef..0cf0ebb 100644 --- a/frontend/src/shared/api/schemas/invitation/organizationInvitationCreate.zod.ts +++ b/frontend/src/shared/api/schemas/invitation/organizationInvitationCreate.zod.ts @@ -67,7 +67,7 @@ export const organizationInvitationCreateTermsPackageHealthInsuranceOneDescripti export const organizationInvitationCreateTermsPackageHealthInsuranceOneDescriptionRegExp = new RegExp('^\\S(?:.*\\S)?$'); export const OrganizationInvitationCreate = zod.object({ - "candidate_handle": zod.string().min(1).max(organizationInvitationCreateCandidateHandleMax).regex(organizationInvitationCreateCandidateHandleRegExp).describe('Opaque reference to a candidate as one organization sees it, taken from a search result card of that organization. It is not the candidate\'s account or profile identifier, it never contains an email address or a phone number, and it means nothing to another organization. The server resolves it only for the organization in the path. Clients never parse it. It is shared by the invitations of FR12 and the search results of FR11 (TASK-185), which issue it.'), + "candidate_handle": zod.string().min(1).max(organizationInvitationCreateCandidateHandleMax).regex(organizationInvitationCreateCandidateHandleRegExp).describe('Opaque reference to a candidate as one organization sees it, taken from a search result card of that organization. It is not the candidate\'s account or profile identifier, it never contains an email address or a phone number, and it means nothing to another organization. The server resolves it only for the organization in the path. Clients never parse it. It is shared by the invitations of FR12 and the search results of FR11, which issue it.'), "need": zod.union([zod.object({ "need_id": zod.uuid().describe('Identifier of a need of the organization in the path.'), "requirements_version": zod.int().min(1).describe('Version of an employer need. Creation makes version 1, and every committed change of the need advances it by exactly one, including a change made by the server, such as a planned asynchronous ML suggestion. Each version is an immutable snapshot of the need. `requirements_version` names the version whose confirmed requirements are current, so a change that leaves them unchanged creates a need version without a new requirements version.').describe('`requirements_version` of the need that the invitation refers to; it must be a version that the need has had.') diff --git a/frontend/src/shared/api/schemas/invitation/organizationInvitationList.zod.ts b/frontend/src/shared/api/schemas/invitation/organizationInvitationList.zod.ts index f80cc34..d5dcde2 100644 --- a/frontend/src/shared/api/schemas/invitation/organizationInvitationList.zod.ts +++ b/frontend/src/shared/api/schemas/invitation/organizationInvitationList.zod.ts @@ -37,7 +37,7 @@ export const organizationInvitationListPageNextCursorRegExp = new RegExp('^[A-Za export const OrganizationInvitationList = zod.object({ "items": zod.array(zod.object({ "id": zod.uuid().describe('Identifier of the invitation.'), - "candidate_handle": zod.string().min(1).max(organizationInvitationListItemsItemCandidateHandleMax).regex(organizationInvitationListItemsItemCandidateHandleRegExp).describe('Opaque reference to a candidate as one organization sees it, taken from a search result card of that organization. It is not the candidate\'s account or profile identifier, it never contains an email address or a phone number, and it means nothing to another organization. The server resolves it only for the organization in the path. Clients never parse it. It is shared by the invitations of FR12 and the search results of FR11 (TASK-185), which issue it.'), + "candidate_handle": zod.string().min(1).max(organizationInvitationListItemsItemCandidateHandleMax).regex(organizationInvitationListItemsItemCandidateHandleRegExp).describe('Opaque reference to a candidate as one organization sees it, taken from a search result card of that organization. It is not the candidate\'s account or profile identifier, it never contains an email address or a phone number, and it means nothing to another organization. The server resolves it only for the organization in the path. Clients never parse it. It is shared by the invitations of FR12 and the search results of FR11, which issue it.'), "need": zod.union([zod.object({ "need_id": zod.uuid().describe('Identifier of a need of the organization in the path.'), "requirements_version": zod.int().min(1).describe('Version of an employer need. Creation makes version 1, and every committed change of the need advances it by exactly one, including a change made by the server, such as a planned asynchronous ML suggestion. Each version is an immutable snapshot of the need. `requirements_version` names the version whose confirmed requirements are current, so a change that leaves them unchanged creates a need version without a new requirements version.').describe('`requirements_version` of the need that the invitation refers to; it must be a version that the need has had.') @@ -57,7 +57,7 @@ export const OrganizationInvitationList = zod.object({ "response_deadline_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]), "contact_access": zod.object({ "status": zod.enum(['not_granted', 'available', 'closed']).describe('Whether the organization may read the candidate\'s contacts through GetOrganizationInvitationContacts now.\n\n- not_granted: the candidate has not accepted this invitation, so no grant exists.\n- available: a grant from this invitation is active and the current consent and visibility allow the read.\n- closed: a grant from this invitation exists but does not allow the read now: it was revoked (the candidate revoked C4, cancelled the participation, or revoked the publication C2 or hid the profile after the acceptance), or it was created while the visibility already did not allow the read. The organization is not told which. A revoked grant never becomes `available` again; a grant blocked from the start becomes `available` once the candidate\'s visibility allows the read, which only follows the candidate\'s own choice to publish the profile or unhide it for the organization. Since every visibility change after a grant exists revokes the grant, a later toggle is never visible to the organization.'), - "fields": zod.array(zod.enum(['full_name', 'email', 'phone', 'telegram']).describe('Kind of personal data that the consent C4 can disclose to one organization (PRD FR01 and FR12). The candidate selects each kind separately; one kind never implies another.\n\n- full_name: the full name from the profile.\n- email: the contact email address from the profile.\n- phone: the contact phone number from the profile.\n- telegram: the Telegram username from the profile.\n\nThe value formats are those of ContactDisclosure: 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, TASK-066) must store contacts in the same formats, so a disclosure never has to convert or drop a stored value. The FSP results of FR14, which need their own explicit permission, are planned as additional kinds. Adding a value is a contract change.')).max(organizationInvitationListItemsItemContactAccessFieldsMax).describe('Kinds of contact that the read returns while `status` is `available`; empty otherwise.') + "fields": zod.array(zod.enum(['full_name', 'email', 'phone', 'telegram']).describe('Kind of personal data that the consent C4 can disclose to one organization (PRD FR01 and FR12). The candidate selects each kind separately; one kind never implies another.\n\n- full_name: the full name from the profile.\n- email: the contact email address from the profile.\n- phone: the contact phone number from the profile.\n- telegram: the Telegram username from the profile.\n\nThe value formats are those of ContactDisclosure: 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 has to convert or drop a stored value. The FSP results of FR14, which need their own explicit permission, are planned as additional kinds. Adding a value is a contract change.')).max(organizationInvitationListItemsItemContactAccessFieldsMax).describe('Kinds of contact that the read returns while `status` is `available`; empty otherwise.') }).describe('Contact access of the organization through this invitation, without any contact value. The values come only from GetOrganizationInvitationContacts.'), "created_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'), "updated_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.') diff --git a/frontend/src/shared/api/schemas/invitation/organizationInvitationSummary.zod.ts b/frontend/src/shared/api/schemas/invitation/organizationInvitationSummary.zod.ts index 56b9c3e..0a6299f 100644 --- a/frontend/src/shared/api/schemas/invitation/organizationInvitationSummary.zod.ts +++ b/frontend/src/shared/api/schemas/invitation/organizationInvitationSummary.zod.ts @@ -30,7 +30,7 @@ export const organizationInvitationSummaryContactAccessFieldsMax = 4; export const OrganizationInvitationSummary = zod.object({ "id": zod.uuid().describe('Identifier of the invitation.'), - "candidate_handle": zod.string().min(1).max(organizationInvitationSummaryCandidateHandleMax).regex(organizationInvitationSummaryCandidateHandleRegExp).describe('Opaque reference to a candidate as one organization sees it, taken from a search result card of that organization. It is not the candidate\'s account or profile identifier, it never contains an email address or a phone number, and it means nothing to another organization. The server resolves it only for the organization in the path. Clients never parse it. It is shared by the invitations of FR12 and the search results of FR11 (TASK-185), which issue it.'), + "candidate_handle": zod.string().min(1).max(organizationInvitationSummaryCandidateHandleMax).regex(organizationInvitationSummaryCandidateHandleRegExp).describe('Opaque reference to a candidate as one organization sees it, taken from a search result card of that organization. It is not the candidate\'s account or profile identifier, it never contains an email address or a phone number, and it means nothing to another organization. The server resolves it only for the organization in the path. Clients never parse it. It is shared by the invitations of FR12 and the search results of FR11, which issue it.'), "need": zod.union([zod.object({ "need_id": zod.uuid().describe('Identifier of a need of the organization in the path.'), "requirements_version": zod.int().min(1).describe('Version of an employer need. Creation makes version 1, and every committed change of the need advances it by exactly one, including a change made by the server, such as a planned asynchronous ML suggestion. Each version is an immutable snapshot of the need. `requirements_version` names the version whose confirmed requirements are current, so a change that leaves them unchanged creates a need version without a new requirements version.').describe('`requirements_version` of the need that the invitation refers to; it must be a version that the need has had.') @@ -50,7 +50,7 @@ export const OrganizationInvitationSummary = zod.object({ "response_deadline_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]), "contact_access": zod.object({ "status": zod.enum(['not_granted', 'available', 'closed']).describe('Whether the organization may read the candidate\'s contacts through GetOrganizationInvitationContacts now.\n\n- not_granted: the candidate has not accepted this invitation, so no grant exists.\n- available: a grant from this invitation is active and the current consent and visibility allow the read.\n- closed: a grant from this invitation exists but does not allow the read now: it was revoked (the candidate revoked C4, cancelled the participation, or revoked the publication C2 or hid the profile after the acceptance), or it was created while the visibility already did not allow the read. The organization is not told which. A revoked grant never becomes `available` again; a grant blocked from the start becomes `available` once the candidate\'s visibility allows the read, which only follows the candidate\'s own choice to publish the profile or unhide it for the organization. Since every visibility change after a grant exists revokes the grant, a later toggle is never visible to the organization.'), - "fields": zod.array(zod.enum(['full_name', 'email', 'phone', 'telegram']).describe('Kind of personal data that the consent C4 can disclose to one organization (PRD FR01 and FR12). The candidate selects each kind separately; one kind never implies another.\n\n- full_name: the full name from the profile.\n- email: the contact email address from the profile.\n- phone: the contact phone number from the profile.\n- telegram: the Telegram username from the profile.\n\nThe value formats are those of ContactDisclosure: 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, TASK-066) must store contacts in the same formats, so a disclosure never has to convert or drop a stored value. The FSP results of FR14, which need their own explicit permission, are planned as additional kinds. Adding a value is a contract change.')).max(organizationInvitationSummaryContactAccessFieldsMax).describe('Kinds of contact that the read returns while `status` is `available`; empty otherwise.') + "fields": zod.array(zod.enum(['full_name', 'email', 'phone', 'telegram']).describe('Kind of personal data that the consent C4 can disclose to one organization (PRD FR01 and FR12). The candidate selects each kind separately; one kind never implies another.\n\n- full_name: the full name from the profile.\n- email: the contact email address from the profile.\n- phone: the contact phone number from the profile.\n- telegram: the Telegram username from the profile.\n\nThe value formats are those of ContactDisclosure: 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 has to convert or drop a stored value. The FSP results of FR14, which need their own explicit permission, are planned as additional kinds. Adding a value is a contract change.')).max(organizationInvitationSummaryContactAccessFieldsMax).describe('Kinds of contact that the read returns while `status` is `available`; empty otherwise.') }).describe('Contact access of the organization through this invitation, without any contact value. The values come only from GetOrganizationInvitationContacts.'), "created_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'), "updated_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.') diff --git a/frontend/src/shared/api/schemas/need/createOrganizationNeedBody.zod.ts b/frontend/src/shared/api/schemas/need/createOrganizationNeedBody.zod.ts index b60683f..3f9f331 100644 --- a/frontend/src/shared/api/schemas/need/createOrganizationNeedBody.zod.ts +++ b/frontend/src/shared/api/schemas/need/createOrganizationNeedBody.zod.ts @@ -52,7 +52,7 @@ export const createOrganizationNeedBodySalaryOneValueSalaryToMultipleOf = 1000; export const CreateOrganizationNeedBody = zod.object({ "title": zod.string().min(1).max(createOrganizationNeedBodyTitleMax).regex(createOrganizationNeedBodyTitleRegExp).describe('Short name of the need inside the organization, for example "Backend for the payments team". It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML.'), "vacancy_id": zod.uuid().nullish().describe('Vacancy of the same organization to link, or null or absent for a need without a vacancy.'), - "source_text": zod.union([zod.string().min(1).max(createOrganizationNeedBodySourceTextOneMax).describe('Free description of the team\'s tasks as the employer wrote or pasted it. The server extracts proposed requirements from it; the text itself is never a requirement. It may contain line breaks. Plain text; clients show it as text, never as HTML. It describes the job and must not contain personal data of candidates. The server stores it as written: it may contain requirements that discriminate by a protected characteristic, and the extractor never turns such a requirement into a need field. Exclusions, the requirements that a candidate must not meet, are planned as a separate additive field with the Labor Code article 64 check (TASK-182).'),zod.null()]).exactOptional(), + "source_text": zod.union([zod.string().min(1).max(createOrganizationNeedBodySourceTextOneMax).describe('Free description of the team\'s tasks as the employer wrote or pasted it. The server extracts proposed requirements from it; the text itself is never a requirement. It may contain line breaks. Plain text; clients show it as text, never as HTML. It describes the job and must not contain personal data of candidates. The server stores it as written: it may contain requirements that discriminate by a protected characteristic, and the extractor never turns such a requirement into a need field. Exclusions, the requirements that a candidate must not meet, are planned as a separate additive field with the Labor Code article 64 check.'),zod.null()]).exactOptional(), "specialization": zod.union([zod.object({ "value": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'), "status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a list item, and the decision that a request sends for a field or an item: `confirmed` or `extracted`, with the meaning of NeedValueStatus. A request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value. An item is never `unknown`; a list with no confirmed item is what readiness reports as missing.') diff --git a/frontend/src/shared/api/schemas/need/need.zod.ts b/frontend/src/shared/api/schemas/need/need.zod.ts index db110cd..b290686 100644 --- a/frontend/src/shared/api/schemas/need/need.zod.ts +++ b/frontend/src/shared/api/schemas/need/need.zod.ts @@ -160,7 +160,7 @@ export const Need = zod.object({ "organization_id": zod.uuid().describe('Organization that owns the need, equal to `org_id` of the path. It never changes.'), "vacancy_id": zod.uuid().nullable().describe('Linked vacancy of the same organization, or null. A need never requires a vacancy.'), "title": zod.string().min(1).max(needTitleMax).regex(needTitleRegExp).describe('Short name of the need inside the organization, for example "Backend for the payments team". It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML.'), - "source_text": zod.union([zod.string().min(1).max(needSourceTextOneMax).describe('Free description of the team\'s tasks as the employer wrote or pasted it. The server extracts proposed requirements from it; the text itself is never a requirement. It may contain line breaks. Plain text; clients show it as text, never as HTML. It describes the job and must not contain personal data of candidates. The server stores it as written: it may contain requirements that discriminate by a protected characteristic, and the extractor never turns such a requirement into a need field. Exclusions, the requirements that a candidate must not meet, are planned as a separate additive field with the Labor Code article 64 check (TASK-182).'),zod.null()]).describe('Text the requirements were extracted from, or null.'), + "source_text": zod.union([zod.string().min(1).max(needSourceTextOneMax).describe('Free description of the team\'s tasks as the employer wrote or pasted it. The server extracts proposed requirements from it; the text itself is never a requirement. It may contain line breaks. Plain text; clients show it as text, never as HTML. It describes the job and must not contain personal data of candidates. The server stores it as written: it may contain requirements that discriminate by a protected characteristic, and the extractor never turns such a requirement into a need field. Exclusions, the requirements that a candidate must not meet, are planned as a separate additive field with the Labor Code article 64 check.'),zod.null()]).describe('Text the requirements were extracted from, or null.'), "version": zod.int().min(1).describe('Version of an employer need. Creation makes version 1, and every committed change of the need advances it by exactly one, including a change made by the server, such as a planned asynchronous ML suggestion. Each version is an immutable snapshot of the need. `requirements_version` names the version whose confirmed requirements are current, so a change that leaves them unchanged creates a need version without a new requirements version.'), "requirements_version": zod.int().min(1).describe('Version of an employer need. Creation makes version 1, and every committed change of the need advances it by exactly one, including a change made by the server, such as a planned asynchronous ML suggestion. Each version is an immutable snapshot of the need. `requirements_version` names the version whose confirmed requirements are current, so a change that leaves them unchanged creates a need version without a new requirements version.').describe('Need version in which the current confirmed requirements were last changed, at most `version`. A change that confirms, changes, or removes a requirement makes it equal to the new `version`. A change of the title, the vacancy link, or the text, or of suggestions only, creates a new `version` but keeps `requirements_version`, so it invalidates neither the recommendations nor search results and selection snapshots. Search runs and selection snapshots (PRD FR10) refer to `(need id, requirements_version)`, and a new selection snapshot is due only when it changes.'), "requirements": zod.object({ @@ -287,7 +287,7 @@ export const Need = zod.object({ "uncovered_skills": zod.array(zod.string().min(1).max(needRecommendationsCategoriesItemSkillOverlapUncoveredSkillsItemMax).regex(needRecommendationsCategoriesItemSkillOverlapUncoveredSkillsItemRegExp).describe('Name of a skill or technology as the employer gave it, for example Go, PostgreSQL, or Temporal. It has no leading or trailing whitespace and no line breaks. The server compares names without regard to letter case. Plain text; clients show it as text, never as HTML.')).max(needRecommendationsCategoriesItemSkillOverlapUncoveredSkillsMax).describe('Confirmed skills of the need that the category does not cover, including skills without a taxonomy code.') }).describe('Skill coverage of a category: the weighted share of the confirmed skills of the need that the category taxonomy covers, with weight 2 for a required and 1 for a desired skill.'), "money": zod.object({ - "status": zod.enum(['computed', 'insufficient_data', 'no_salary', 'withheld']).describe('How the salary component of a recommendation was obtained.\n\n- computed: at least five available candidates of the category have a known minimum comparable with the confirmed range; `share` is given.\n- insufficient_data: fewer than five such candidates; the policy uses the neutral value 0.5 and `share` is null.\n- no_salary: the need has no confirmed salary range; the policy uses the neutral value 0.5 and `share` is null.\n- withheld: the organization changed salary ranges five times within seven days, so salary aggregates are withheld for seven days (PRD FR13, planned in TASK-211); the policy uses the neutral value 0.5 and `share` is null.\n\nAn unknown candidate minimum never counts as zero.'), + "status": zod.enum(['computed', 'insufficient_data', 'no_salary', 'withheld']).describe('How the salary component of a recommendation was obtained.\n\n- computed: at least five available candidates of the category have a known minimum comparable with the confirmed range; `share` is given.\n- insufficient_data: fewer than five such candidates; the policy uses the neutral value 0.5 and `share` is null.\n- no_salary: the need has no confirmed salary range; the policy uses the neutral value 0.5 and `share` is null.\n- withheld: the organization changed salary ranges five times within seven days, so salary aggregates are withheld for seven days (PRD FR13, enforcement planned); the policy uses the neutral value 0.5 and `share` is null.\n\nAn unknown candidate minimum never counts as zero.'), "share": zod.number().min(needRecommendationsCategoriesItemMoneyShareMin).max(needRecommendationsCategoriesItemMoneyShareMax).nullable().describe('Share of those candidates whose minimum is not above the upper bound of the range, rounded down to a multiple of 0.25 (one of 0, 0.25, 0.5, 0.75, 1), or null unless `status` is `computed`. The score and the ranking use this rounded value, never the exact share. A quarter step gives five levels: each probe of a new upper bound tells at most which quarter of the group accepts it, and in the smallest allowed group of five candidates 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.') }).describe('Salary component of a recommendation. It is an aggregate over at least five candidates and never reveals a minimum of any candidate.'), "supply": zod.enum(['fewer_than_5', 'from_5_to_29', '30_or_more']).describe('Number of available candidates of the category in the allowed detail: `fewer_than_5`, `from_5_to_29`, or `30_or_more`. Smaller groups are never counted exactly.') diff --git a/frontend/src/shared/api/schemas/need/needCategoryRecommendation.zod.ts b/frontend/src/shared/api/schemas/need/needCategoryRecommendation.zod.ts index 6294f4f..bc1848b 100644 --- a/frontend/src/shared/api/schemas/need/needCategoryRecommendation.zod.ts +++ b/frontend/src/shared/api/schemas/need/needCategoryRecommendation.zod.ts @@ -38,7 +38,7 @@ export const NeedCategoryRecommendation = zod.object({ "uncovered_skills": zod.array(zod.string().min(1).max(needCategoryRecommendationSkillOverlapUncoveredSkillsItemMax).regex(needCategoryRecommendationSkillOverlapUncoveredSkillsItemRegExp).describe('Name of a skill or technology as the employer gave it, for example Go, PostgreSQL, or Temporal. It has no leading or trailing whitespace and no line breaks. The server compares names without regard to letter case. Plain text; clients show it as text, never as HTML.')).max(needCategoryRecommendationSkillOverlapUncoveredSkillsMax).describe('Confirmed skills of the need that the category does not cover, including skills without a taxonomy code.') }).describe('Skill coverage of a category: the weighted share of the confirmed skills of the need that the category taxonomy covers, with weight 2 for a required and 1 for a desired skill.'), "money": zod.object({ - "status": zod.enum(['computed', 'insufficient_data', 'no_salary', 'withheld']).describe('How the salary component of a recommendation was obtained.\n\n- computed: at least five available candidates of the category have a known minimum comparable with the confirmed range; `share` is given.\n- insufficient_data: fewer than five such candidates; the policy uses the neutral value 0.5 and `share` is null.\n- no_salary: the need has no confirmed salary range; the policy uses the neutral value 0.5 and `share` is null.\n- withheld: the organization changed salary ranges five times within seven days, so salary aggregates are withheld for seven days (PRD FR13, planned in TASK-211); the policy uses the neutral value 0.5 and `share` is null.\n\nAn unknown candidate minimum never counts as zero.'), + "status": zod.enum(['computed', 'insufficient_data', 'no_salary', 'withheld']).describe('How the salary component of a recommendation was obtained.\n\n- computed: at least five available candidates of the category have a known minimum comparable with the confirmed range; `share` is given.\n- insufficient_data: fewer than five such candidates; the policy uses the neutral value 0.5 and `share` is null.\n- no_salary: the need has no confirmed salary range; the policy uses the neutral value 0.5 and `share` is null.\n- withheld: the organization changed salary ranges five times within seven days, so salary aggregates are withheld for seven days (PRD FR13, enforcement planned); the policy uses the neutral value 0.5 and `share` is null.\n\nAn unknown candidate minimum never counts as zero.'), "share": zod.number().min(needCategoryRecommendationMoneyShareMin).max(needCategoryRecommendationMoneyShareMax).nullable().describe('Share of those candidates whose minimum is not above the upper bound of the range, rounded down to a multiple of 0.25 (one of 0, 0.25, 0.5, 0.75, 1), or null unless `status` is `computed`. The score and the ranking use this rounded value, never the exact share. A quarter step gives five levels: each probe of a new upper bound tells at most which quarter of the group accepts it, and in the smallest allowed group of five candidates 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.') }).describe('Salary component of a recommendation. It is an aggregate over at least five candidates and never reveals a minimum of any candidate.'), "supply": zod.enum(['fewer_than_5', 'from_5_to_29', '30_or_more']).describe('Number of available candidates of the category in the allowed detail: `fewer_than_5`, `from_5_to_29`, or `30_or_more`. Smaller groups are never counted exactly.') diff --git a/frontend/src/shared/api/schemas/need/needCategoryRecommendations.zod.ts b/frontend/src/shared/api/schemas/need/needCategoryRecommendations.zod.ts index 8ac8285..3aa787c 100644 --- a/frontend/src/shared/api/schemas/need/needCategoryRecommendations.zod.ts +++ b/frontend/src/shared/api/schemas/need/needCategoryRecommendations.zod.ts @@ -52,7 +52,7 @@ export const NeedCategoryRecommendations = zod.object({ "uncovered_skills": zod.array(zod.string().min(1).max(needCategoryRecommendationsCategoriesItemSkillOverlapUncoveredSkillsItemMax).regex(needCategoryRecommendationsCategoriesItemSkillOverlapUncoveredSkillsItemRegExp).describe('Name of a skill or technology as the employer gave it, for example Go, PostgreSQL, or Temporal. It has no leading or trailing whitespace and no line breaks. The server compares names without regard to letter case. Plain text; clients show it as text, never as HTML.')).max(needCategoryRecommendationsCategoriesItemSkillOverlapUncoveredSkillsMax).describe('Confirmed skills of the need that the category does not cover, including skills without a taxonomy code.') }).describe('Skill coverage of a category: the weighted share of the confirmed skills of the need that the category taxonomy covers, with weight 2 for a required and 1 for a desired skill.'), "money": zod.object({ - "status": zod.enum(['computed', 'insufficient_data', 'no_salary', 'withheld']).describe('How the salary component of a recommendation was obtained.\n\n- computed: at least five available candidates of the category have a known minimum comparable with the confirmed range; `share` is given.\n- insufficient_data: fewer than five such candidates; the policy uses the neutral value 0.5 and `share` is null.\n- no_salary: the need has no confirmed salary range; the policy uses the neutral value 0.5 and `share` is null.\n- withheld: the organization changed salary ranges five times within seven days, so salary aggregates are withheld for seven days (PRD FR13, planned in TASK-211); the policy uses the neutral value 0.5 and `share` is null.\n\nAn unknown candidate minimum never counts as zero.'), + "status": zod.enum(['computed', 'insufficient_data', 'no_salary', 'withheld']).describe('How the salary component of a recommendation was obtained.\n\n- computed: at least five available candidates of the category have a known minimum comparable with the confirmed range; `share` is given.\n- insufficient_data: fewer than five such candidates; the policy uses the neutral value 0.5 and `share` is null.\n- no_salary: the need has no confirmed salary range; the policy uses the neutral value 0.5 and `share` is null.\n- withheld: the organization changed salary ranges five times within seven days, so salary aggregates are withheld for seven days (PRD FR13, enforcement planned); the policy uses the neutral value 0.5 and `share` is null.\n\nAn unknown candidate minimum never counts as zero.'), "share": zod.number().min(needCategoryRecommendationsCategoriesItemMoneyShareMin).max(needCategoryRecommendationsCategoriesItemMoneyShareMax).nullable().describe('Share of those candidates whose minimum is not above the upper bound of the range, rounded down to a multiple of 0.25 (one of 0, 0.25, 0.5, 0.75, 1), or null unless `status` is `computed`. The score and the ranking use this rounded value, never the exact share. A quarter step gives five levels: each probe of a new upper bound tells at most which quarter of the group accepts it, and in the smallest allowed group of five candidates 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.') }).describe('Salary component of a recommendation. It is an aggregate over at least five candidates and never reveals a minimum of any candidate.'), "supply": zod.enum(['fewer_than_5', 'from_5_to_29', '30_or_more']).describe('Number of available candidates of the category in the allowed detail: `fewer_than_5`, `from_5_to_29`, or `30_or_more`. Smaller groups are never counted exactly.') diff --git a/frontend/src/shared/api/schemas/need/needCreate.zod.ts b/frontend/src/shared/api/schemas/need/needCreate.zod.ts index 127683c..2c55cb0 100644 --- a/frontend/src/shared/api/schemas/need/needCreate.zod.ts +++ b/frontend/src/shared/api/schemas/need/needCreate.zod.ts @@ -52,7 +52,7 @@ export const needCreateSalaryOneValueSalaryToMultipleOf = 1000; export const NeedCreate = zod.object({ "title": zod.string().min(1).max(needCreateTitleMax).regex(needCreateTitleRegExp).describe('Short name of the need inside the organization, for example "Backend for the payments team". It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML.'), "vacancy_id": zod.uuid().nullish().describe('Vacancy of the same organization to link, or null or absent for a need without a vacancy.'), - "source_text": zod.union([zod.string().min(1).max(needCreateSourceTextOneMax).describe('Free description of the team\'s tasks as the employer wrote or pasted it. The server extracts proposed requirements from it; the text itself is never a requirement. It may contain line breaks. Plain text; clients show it as text, never as HTML. It describes the job and must not contain personal data of candidates. The server stores it as written: it may contain requirements that discriminate by a protected characteristic, and the extractor never turns such a requirement into a need field. Exclusions, the requirements that a candidate must not meet, are planned as a separate additive field with the Labor Code article 64 check (TASK-182).'),zod.null()]).exactOptional(), + "source_text": zod.union([zod.string().min(1).max(needCreateSourceTextOneMax).describe('Free description of the team\'s tasks as the employer wrote or pasted it. The server extracts proposed requirements from it; the text itself is never a requirement. It may contain line breaks. Plain text; clients show it as text, never as HTML. It describes the job and must not contain personal data of candidates. The server stores it as written: it may contain requirements that discriminate by a protected characteristic, and the extractor never turns such a requirement into a need field. Exclusions, the requirements that a candidate must not meet, are planned as a separate additive field with the Labor Code article 64 check.'),zod.null()]).exactOptional(), "specialization": zod.union([zod.object({ "value": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'), "status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a list item, and the decision that a request sends for a field or an item: `confirmed` or `extracted`, with the meaning of NeedValueStatus. A request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value. An item is never `unknown`; a list with no confirmed item is what readiness reports as missing.') diff --git a/frontend/src/shared/api/schemas/need/needMoneyFit.zod.ts b/frontend/src/shared/api/schemas/need/needMoneyFit.zod.ts index af71fbb..f9869c9 100644 --- a/frontend/src/shared/api/schemas/need/needMoneyFit.zod.ts +++ b/frontend/src/shared/api/schemas/need/needMoneyFit.zod.ts @@ -11,7 +11,7 @@ export const needMoneyFitShareMax = 1; export const NeedMoneyFit = zod.object({ - "status": zod.enum(['computed', 'insufficient_data', 'no_salary', 'withheld']).describe('How the salary component of a recommendation was obtained.\n\n- computed: at least five available candidates of the category have a known minimum comparable with the confirmed range; `share` is given.\n- insufficient_data: fewer than five such candidates; the policy uses the neutral value 0.5 and `share` is null.\n- no_salary: the need has no confirmed salary range; the policy uses the neutral value 0.5 and `share` is null.\n- withheld: the organization changed salary ranges five times within seven days, so salary aggregates are withheld for seven days (PRD FR13, planned in TASK-211); the policy uses the neutral value 0.5 and `share` is null.\n\nAn unknown candidate minimum never counts as zero.'), + "status": zod.enum(['computed', 'insufficient_data', 'no_salary', 'withheld']).describe('How the salary component of a recommendation was obtained.\n\n- computed: at least five available candidates of the category have a known minimum comparable with the confirmed range; `share` is given.\n- insufficient_data: fewer than five such candidates; the policy uses the neutral value 0.5 and `share` is null.\n- no_salary: the need has no confirmed salary range; the policy uses the neutral value 0.5 and `share` is null.\n- withheld: the organization changed salary ranges five times within seven days, so salary aggregates are withheld for seven days (PRD FR13, enforcement planned); the policy uses the neutral value 0.5 and `share` is null.\n\nAn unknown candidate minimum never counts as zero.'), "share": zod.number().min(needMoneyFitShareMin).max(needMoneyFitShareMax).nullable().describe('Share of those candidates whose minimum is not above the upper bound of the range, rounded down to a multiple of 0.25 (one of 0, 0.25, 0.5, 0.75, 1), or null unless `status` is `computed`. The score and the ranking use this rounded value, never the exact share. A quarter step gives five levels: each probe of a new upper bound tells at most which quarter of the group accepts it, and in the smallest allowed group of five candidates 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.') }).describe('Salary component of a recommendation. It is an aggregate over at least five candidates and never reveals a minimum of any candidate.') diff --git a/frontend/src/shared/api/schemas/need/needMoneyStatus.zod.ts b/frontend/src/shared/api/schemas/need/needMoneyStatus.zod.ts index 53ee522..97db64a 100644 --- a/frontend/src/shared/api/schemas/need/needMoneyStatus.zod.ts +++ b/frontend/src/shared/api/schemas/need/needMoneyStatus.zod.ts @@ -6,7 +6,7 @@ */ import * as zod from 'zod'; -export const NeedMoneyStatus = zod.enum(['computed', 'insufficient_data', 'no_salary', 'withheld']).describe('How the salary component of a recommendation was obtained.\n\n- computed: at least five available candidates of the category have a known minimum comparable with the confirmed range; `share` is given.\n- insufficient_data: fewer than five such candidates; the policy uses the neutral value 0.5 and `share` is null.\n- no_salary: the need has no confirmed salary range; the policy uses the neutral value 0.5 and `share` is null.\n- withheld: the organization changed salary ranges five times within seven days, so salary aggregates are withheld for seven days (PRD FR13, planned in TASK-211); the policy uses the neutral value 0.5 and `share` is null.\n\nAn unknown candidate minimum never counts as zero.') +export const NeedMoneyStatus = zod.enum(['computed', 'insufficient_data', 'no_salary', 'withheld']).describe('How the salary component of a recommendation was obtained.\n\n- computed: at least five available candidates of the category have a known minimum comparable with the confirmed range; `share` is given.\n- insufficient_data: fewer than five such candidates; the policy uses the neutral value 0.5 and `share` is null.\n- no_salary: the need has no confirmed salary range; the policy uses the neutral value 0.5 and `share` is null.\n- withheld: the organization changed salary ranges five times within seven days, so salary aggregates are withheld for seven days (PRD FR13, enforcement planned); the policy uses the neutral value 0.5 and `share` is null.\n\nAn unknown candidate minimum never counts as zero.') export type NeedMoneyStatus = zod.input; export type NeedMoneyStatusOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/need/needSourceText.zod.ts b/frontend/src/shared/api/schemas/need/needSourceText.zod.ts index 0011624..3046526 100644 --- a/frontend/src/shared/api/schemas/need/needSourceText.zod.ts +++ b/frontend/src/shared/api/schemas/need/needSourceText.zod.ts @@ -9,7 +9,7 @@ import * as zod from 'zod'; export const NeedSourceTextMax = 10000; -export const NeedSourceText = zod.string().min(1).max(NeedSourceTextMax).describe('Free description of the team\'s tasks as the employer wrote or pasted it. The server extracts proposed requirements from it; the text itself is never a requirement. It may contain line breaks. Plain text; clients show it as text, never as HTML. It describes the job and must not contain personal data of candidates. The server stores it as written: it may contain requirements that discriminate by a protected characteristic, and the extractor never turns such a requirement into a need field. Exclusions, the requirements that a candidate must not meet, are planned as a separate additive field with the Labor Code article 64 check (TASK-182).') +export const NeedSourceText = zod.string().min(1).max(NeedSourceTextMax).describe('Free description of the team\'s tasks as the employer wrote or pasted it. The server extracts proposed requirements from it; the text itself is never a requirement. It may contain line breaks. Plain text; clients show it as text, never as HTML. It describes the job and must not contain personal data of candidates. The server stores it as written: it may contain requirements that discriminate by a protected characteristic, and the extractor never turns such a requirement into a need field. Exclusions, the requirements that a candidate must not meet, are planned as a separate additive field with the Labor Code article 64 check.') export type NeedSourceText = zod.input; export type NeedSourceTextOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/need/needUpdate.zod.ts b/frontend/src/shared/api/schemas/need/needUpdate.zod.ts index 06a0474..376c006 100644 --- a/frontend/src/shared/api/schemas/need/needUpdate.zod.ts +++ b/frontend/src/shared/api/schemas/need/needUpdate.zod.ts @@ -54,7 +54,7 @@ export const NeedUpdate = zod.object({ "expected_version": zod.int().min(1).describe('Version of an employer need. Creation makes version 1, and every committed change of the need advances it by exactly one, including a change made by the server, such as a planned asynchronous ML suggestion. Each version is an immutable snapshot of the need. `requirements_version` names the version whose confirmed requirements are current, so a change that leaves them unchanged creates a need version without a new requirements version.'), "title": zod.string().min(1).max(needUpdateTitleMax).regex(needUpdateTitleRegExp).exactOptional().describe('Short name of the need inside the organization, for example "Backend for the payments team". It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML.'), "vacancy_id": zod.uuid().nullish().describe('Vacancy of the same organization to link, or null to unlink.'), - "source_text": zod.union([zod.string().min(1).max(needUpdateSourceTextOneMax).describe('Free description of the team\'s tasks as the employer wrote or pasted it. The server extracts proposed requirements from it; the text itself is never a requirement. It may contain line breaks. Plain text; clients show it as text, never as HTML. It describes the job and must not contain personal data of candidates. The server stores it as written: it may contain requirements that discriminate by a protected characteristic, and the extractor never turns such a requirement into a need field. Exclusions, the requirements that a candidate must not meet, are planned as a separate additive field with the Labor Code article 64 check (TASK-182).'),zod.null()]).exactOptional(), + "source_text": zod.union([zod.string().min(1).max(needUpdateSourceTextOneMax).describe('Free description of the team\'s tasks as the employer wrote or pasted it. The server extracts proposed requirements from it; the text itself is never a requirement. It may contain line breaks. Plain text; clients show it as text, never as HTML. It describes the job and must not contain personal data of candidates. The server stores it as written: it may contain requirements that discriminate by a protected characteristic, and the extractor never turns such a requirement into a need field. Exclusions, the requirements that a candidate must not meet, are planned as a separate additive field with the Labor Code article 64 check.'),zod.null()]).exactOptional(), "specialization": zod.union([zod.object({ "value": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'), "status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a list item, and the decision that a request sends for a field or an item: `confirmed` or `extracted`, with the meaning of NeedValueStatus. A request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value. An item is never `unknown`; a list with no confirmed item is what readiness reports as missing.') diff --git a/frontend/src/shared/api/schemas/need/updateOrganizationNeedBody.zod.ts b/frontend/src/shared/api/schemas/need/updateOrganizationNeedBody.zod.ts index 95c5207..62fa433 100644 --- a/frontend/src/shared/api/schemas/need/updateOrganizationNeedBody.zod.ts +++ b/frontend/src/shared/api/schemas/need/updateOrganizationNeedBody.zod.ts @@ -54,7 +54,7 @@ export const UpdateOrganizationNeedBody = zod.object({ "expected_version": zod.int().min(1).describe('Version of an employer need. Creation makes version 1, and every committed change of the need advances it by exactly one, including a change made by the server, such as a planned asynchronous ML suggestion. Each version is an immutable snapshot of the need. `requirements_version` names the version whose confirmed requirements are current, so a change that leaves them unchanged creates a need version without a new requirements version.'), "title": zod.string().min(1).max(updateOrganizationNeedBodyTitleMax).regex(updateOrganizationNeedBodyTitleRegExp).exactOptional().describe('Short name of the need inside the organization, for example "Backend for the payments team". It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML.'), "vacancy_id": zod.uuid().nullish().describe('Vacancy of the same organization to link, or null to unlink.'), - "source_text": zod.union([zod.string().min(1).max(updateOrganizationNeedBodySourceTextOneMax).describe('Free description of the team\'s tasks as the employer wrote or pasted it. The server extracts proposed requirements from it; the text itself is never a requirement. It may contain line breaks. Plain text; clients show it as text, never as HTML. It describes the job and must not contain personal data of candidates. The server stores it as written: it may contain requirements that discriminate by a protected characteristic, and the extractor never turns such a requirement into a need field. Exclusions, the requirements that a candidate must not meet, are planned as a separate additive field with the Labor Code article 64 check (TASK-182).'),zod.null()]).exactOptional(), + "source_text": zod.union([zod.string().min(1).max(updateOrganizationNeedBodySourceTextOneMax).describe('Free description of the team\'s tasks as the employer wrote or pasted it. The server extracts proposed requirements from it; the text itself is never a requirement. It may contain line breaks. Plain text; clients show it as text, never as HTML. It describes the job and must not contain personal data of candidates. The server stores it as written: it may contain requirements that discriminate by a protected characteristic, and the extractor never turns such a requirement into a need field. Exclusions, the requirements that a candidate must not meet, are planned as a separate additive field with the Labor Code article 64 check.'),zod.null()]).exactOptional(), "specialization": zod.union([zod.object({ "value": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'), "status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a list item, and the decision that a request sends for a field or an item: `confirmed` or `extracted`, with the meaning of NeedValueStatus. A request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value. An item is never `unknown`; a list with no confirmed item is what readiness reports as missing.') diff --git a/frontend/src/shared/api/schemas/organization/membershipState.zod.ts b/frontend/src/shared/api/schemas/organization/membershipState.zod.ts index 802d476..0b3c4c1 100644 --- a/frontend/src/shared/api/schemas/organization/membershipState.zod.ts +++ b/frontend/src/shared/api/schemas/organization/membershipState.zod.ts @@ -6,7 +6,7 @@ */ import * as zod from 'zod'; -export const MembershipState = zod.enum(['active', 'suspended', 'removed', 'left']).describe('State of a membership. Only `active` gives access: every other state answers as if the account were no member.\n\n- active: the member works in the organization with the role.\n- suspended: access is stopped, and the owner or the platform may restore it.\n- removed: the owner or the platform ended the membership. A removal by the platform is not undone by the owner or by an invitation: the acceptance of an employee invitation and the member management (TASK-082, TASK-084) must not reactivate it on their own. Who removed the member and why become additive fields of the member management.\n- left: the member ended the membership.\n\nOne account has at most one membership per organization, so a former member who returns gets the same membership back in `active`, and the history of the pair is the history of its audit events (planned). The listing of this contract returns only `active` memberships; the other states are listed now so that generated clients accept them when the member management reads them. Adding a state is a contract change.') +export const MembershipState = zod.enum(['active', 'suspended', 'removed', 'left']).describe('State of a membership. Only `active` gives access: every other state answers as if the account were no member.\n\n- active: the member works in the organization with the role.\n- suspended: access is stopped, and the owner or the platform may restore it.\n- removed: the owner or the platform ended the membership. A removal by the platform is not undone by the owner or by an invitation: the acceptance of an employee invitation and the member management must not reactivate it on their own. Who removed the member and why become additive fields of the member management.\n- left: the member ended the membership.\n\nOne account has at most one membership per organization, so a former member who returns gets the same membership back in `active`, and the history of the pair is the history of its audit events (planned). The listing of this contract returns only `active` memberships; the other states are listed now so that generated clients accept them when the member management reads them. Adding a state is a contract change.') export type MembershipState = zod.input; export type MembershipStateOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/organization/myOrganization.zod.ts b/frontend/src/shared/api/schemas/organization/myOrganization.zod.ts index a68383b..f66a61b 100644 --- a/frontend/src/shared/api/schemas/organization/myOrganization.zod.ts +++ b/frontend/src/shared/api/schemas/organization/myOrganization.zod.ts @@ -20,8 +20,8 @@ export const MyOrganization = zod.object({ "membership": zod.object({ "organization_id": zod.uuid().describe('Identifier of the organization.'), "role": zod.enum(['owner', 'recruiter', 'hiring_manager', 'technical_expert']).describe('Role of a member in an organization (PRD 2.2 and the FR07 matrix). The role belongs to the membership, never to the organization or to any editable profile.\n\n- owner: manages the organization and its members, and acts on behalf of the company.\n- recruiter: leads the selection of candidates for all needs.\n- hiring_manager: acts on the needs assigned to the member.\n- technical_expert: refines the requirements of the assigned needs; reads no contacts and sends no invitations.\n\nIn the MVP only the owner acts, so the other roles grant nothing yet: an operation that is not open to a role answers 403 `forbidden`. The full matrix is planned, and applying it changes no field of this contract. Adding a role is a contract change.'), - "state": zod.enum(['active', 'suspended', 'removed', 'left']).describe('State of a membership. Only `active` gives access: every other state answers as if the account were no member.\n\n- active: the member works in the organization with the role.\n- suspended: access is stopped, and the owner or the platform may restore it.\n- removed: the owner or the platform ended the membership. A removal by the platform is not undone by the owner or by an invitation: the acceptance of an employee invitation and the member management (TASK-082, TASK-084) must not reactivate it on their own. Who removed the member and why become additive fields of the member management.\n- left: the member ended the membership.\n\nOne account has at most one membership per organization, so a former member who returns gets the same membership back in `active`, and the history of the pair is the history of its audit events (planned). The listing of this contract returns only `active` memberships; the other states are listed now so that generated clients accept them when the member management reads them. Adding a state is a contract change.'), - "joined_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.').describe('Moment the membership was first created. A member who left and returns keeps the same value, because the pair has one membership; the moment of the latest activation is a planned additive field (`activated_at`, TASK-082).') + "state": zod.enum(['active', 'suspended', 'removed', 'left']).describe('State of a membership. Only `active` gives access: every other state answers as if the account were no member.\n\n- active: the member works in the organization with the role.\n- suspended: access is stopped, and the owner or the platform may restore it.\n- removed: the owner or the platform ended the membership. A removal by the platform is not undone by the owner or by an invitation: the acceptance of an employee invitation and the member management must not reactivate it on their own. Who removed the member and why become additive fields of the member management.\n- left: the member ended the membership.\n\nOne account has at most one membership per organization, so a former member who returns gets the same membership back in `active`, and the history of the pair is the history of its audit events (planned). The listing of this contract returns only `active` memberships; the other states are listed now so that generated clients accept them when the member management reads them. Adding a state is a contract change.'), + "joined_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.').describe('Moment the membership was first created. A member who left and returns keeps the same value, because the pair has one membership; the moment of the latest activation is a planned additive field (`activated_at`).') }).describe('The membership of the caller in one organization. The caller is the account of the session, so the object holds no account identifier. Only the server sets the role and the state, through the operations that manage members, which are planned; no operation of this contract changes them.') }).describe('An organization available to the caller together with the caller\'s membership in it.') diff --git a/frontend/src/shared/api/schemas/organization/myOrganizationList.zod.ts b/frontend/src/shared/api/schemas/organization/myOrganizationList.zod.ts index e00d4de..33a59ca 100644 --- a/frontend/src/shared/api/schemas/organization/myOrganizationList.zod.ts +++ b/frontend/src/shared/api/schemas/organization/myOrganizationList.zod.ts @@ -27,8 +27,8 @@ export const MyOrganizationList = zod.object({ "membership": zod.object({ "organization_id": zod.uuid().describe('Identifier of the organization.'), "role": zod.enum(['owner', 'recruiter', 'hiring_manager', 'technical_expert']).describe('Role of a member in an organization (PRD 2.2 and the FR07 matrix). The role belongs to the membership, never to the organization or to any editable profile.\n\n- owner: manages the organization and its members, and acts on behalf of the company.\n- recruiter: leads the selection of candidates for all needs.\n- hiring_manager: acts on the needs assigned to the member.\n- technical_expert: refines the requirements of the assigned needs; reads no contacts and sends no invitations.\n\nIn the MVP only the owner acts, so the other roles grant nothing yet: an operation that is not open to a role answers 403 `forbidden`. The full matrix is planned, and applying it changes no field of this contract. Adding a role is a contract change.'), - "state": zod.enum(['active', 'suspended', 'removed', 'left']).describe('State of a membership. Only `active` gives access: every other state answers as if the account were no member.\n\n- active: the member works in the organization with the role.\n- suspended: access is stopped, and the owner or the platform may restore it.\n- removed: the owner or the platform ended the membership. A removal by the platform is not undone by the owner or by an invitation: the acceptance of an employee invitation and the member management (TASK-082, TASK-084) must not reactivate it on their own. Who removed the member and why become additive fields of the member management.\n- left: the member ended the membership.\n\nOne account has at most one membership per organization, so a former member who returns gets the same membership back in `active`, and the history of the pair is the history of its audit events (planned). The listing of this contract returns only `active` memberships; the other states are listed now so that generated clients accept them when the member management reads them. Adding a state is a contract change.'), - "joined_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.').describe('Moment the membership was first created. A member who left and returns keeps the same value, because the pair has one membership; the moment of the latest activation is a planned additive field (`activated_at`, TASK-082).') + "state": zod.enum(['active', 'suspended', 'removed', 'left']).describe('State of a membership. Only `active` gives access: every other state answers as if the account were no member.\n\n- active: the member works in the organization with the role.\n- suspended: access is stopped, and the owner or the platform may restore it.\n- removed: the owner or the platform ended the membership. A removal by the platform is not undone by the owner or by an invitation: the acceptance of an employee invitation and the member management must not reactivate it on their own. Who removed the member and why become additive fields of the member management.\n- left: the member ended the membership.\n\nOne account has at most one membership per organization, so a former member who returns gets the same membership back in `active`, and the history of the pair is the history of its audit events (planned). The listing of this contract returns only `active` memberships; the other states are listed now so that generated clients accept them when the member management reads them. Adding a state is a contract change.'), + "joined_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.').describe('Moment the membership was first created. A member who left and returns keeps the same value, because the pair has one membership; the moment of the latest activation is a planned additive field (`activated_at`).') }).describe('The membership of the caller in one organization. The caller is the account of the session, so the object holds no account identifier. Only the server sets the role and the state, through the operations that manage members, which are planned; no operation of this contract changes them.') }).describe('An organization available to the caller together with the caller\'s membership in it.')).max(myOrganizationListItemsMax).describe('Organizations of the page.'), "page": zod.object({ diff --git a/frontend/src/shared/api/schemas/organization/organizationMembership.zod.ts b/frontend/src/shared/api/schemas/organization/organizationMembership.zod.ts index 87f00be..7d9c4ad 100644 --- a/frontend/src/shared/api/schemas/organization/organizationMembership.zod.ts +++ b/frontend/src/shared/api/schemas/organization/organizationMembership.zod.ts @@ -9,8 +9,8 @@ import * as zod from 'zod'; export const OrganizationMembership = zod.object({ "organization_id": zod.uuid().describe('Identifier of the organization.'), "role": zod.enum(['owner', 'recruiter', 'hiring_manager', 'technical_expert']).describe('Role of a member in an organization (PRD 2.2 and the FR07 matrix). The role belongs to the membership, never to the organization or to any editable profile.\n\n- owner: manages the organization and its members, and acts on behalf of the company.\n- recruiter: leads the selection of candidates for all needs.\n- hiring_manager: acts on the needs assigned to the member.\n- technical_expert: refines the requirements of the assigned needs; reads no contacts and sends no invitations.\n\nIn the MVP only the owner acts, so the other roles grant nothing yet: an operation that is not open to a role answers 403 `forbidden`. The full matrix is planned, and applying it changes no field of this contract. Adding a role is a contract change.'), - "state": zod.enum(['active', 'suspended', 'removed', 'left']).describe('State of a membership. Only `active` gives access: every other state answers as if the account were no member.\n\n- active: the member works in the organization with the role.\n- suspended: access is stopped, and the owner or the platform may restore it.\n- removed: the owner or the platform ended the membership. A removal by the platform is not undone by the owner or by an invitation: the acceptance of an employee invitation and the member management (TASK-082, TASK-084) must not reactivate it on their own. Who removed the member and why become additive fields of the member management.\n- left: the member ended the membership.\n\nOne account has at most one membership per organization, so a former member who returns gets the same membership back in `active`, and the history of the pair is the history of its audit events (planned). The listing of this contract returns only `active` memberships; the other states are listed now so that generated clients accept them when the member management reads them. Adding a state is a contract change.'), - "joined_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.').describe('Moment the membership was first created. A member who left and returns keeps the same value, because the pair has one membership; the moment of the latest activation is a planned additive field (`activated_at`, TASK-082).') + "state": zod.enum(['active', 'suspended', 'removed', 'left']).describe('State of a membership. Only `active` gives access: every other state answers as if the account were no member.\n\n- active: the member works in the organization with the role.\n- suspended: access is stopped, and the owner or the platform may restore it.\n- removed: the owner or the platform ended the membership. A removal by the platform is not undone by the owner or by an invitation: the acceptance of an employee invitation and the member management must not reactivate it on their own. Who removed the member and why become additive fields of the member management.\n- left: the member ended the membership.\n\nOne account has at most one membership per organization, so a former member who returns gets the same membership back in `active`, and the history of the pair is the history of its audit events (planned). The listing of this contract returns only `active` memberships; the other states are listed now so that generated clients accept them when the member management reads them. Adding a state is a contract change.'), + "joined_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.').describe('Moment the membership was first created. A member who left and returns keeps the same value, because the pair has one membership; the moment of the latest activation is a planned additive field (`activated_at`).') }).describe('The membership of the caller in one organization. The caller is the account of the session, so the object holds no account identifier. Only the server sets the role and the state, through the operations that manage members, which are planned; no operation of this contract changes them.') export type OrganizationMembership = zod.input; diff --git a/frontend/src/shared/api/schemas/privacy/anonymousCardContent.zod.ts b/frontend/src/shared/api/schemas/privacy/anonymousCardContent.zod.ts index 36ddf1c..aed615d 100644 --- a/frontend/src/shared/api/schemas/privacy/anonymousCardContent.zod.ts +++ b/frontend/src/shared/api/schemas/privacy/anonymousCardContent.zod.ts @@ -38,7 +38,7 @@ export const AnonymousCardContent = zod.object({ "soft_skills": zod.array(zod.string().min(1).max(anonymousCardContentSoftSkillsItemMax).regex(anonymousCardContentSoftSkillsItemRegExp).describe('Plain text; clients show it as text, never as HTML.')).max(anonymousCardContentSoftSkillsMax).nullable().describe('Soft skills of the candidate, or null.'), "location": zod.string().min(1).max(anonymousCardContentLocationMax).regex(anonymousCardContentLocationRegExp).nullable().describe('City or region as free text, never a street address, or null. Plain text; clients show it as text, never as HTML.'), "relocation": zod.boolean().nullable().describe('Whether the candidate is ready to relocate, or null.') -}).describe('The anonymous candidate card as an organization reads it. Only values that the candidate confirmed reach it; an unconfirmed suggestion and an unknown value never do. A free text value (a stack tag, a soft skill, the location) that looks like a contact (an email address, a phone number, a URL or domain, a Telegram link, an @handle) is dropped by the builder (TASK-089) and never published. It carries no name, contact, resume text, employer, salary figure, account or profile identifier, and no schema of the private profile or of a contact disclosure is reachable from it; a contact reaches an organization only through the contact grant of an accepted invitation. Each property is null when its field is not published or the candidate has no value for it, so the card does not tell the two apart. The set of properties is closed, and an organization-visible card must never gain a property that identifies the candidate. The search ranking and the full card of an organization\'s search result are defined by the search contract (TASK-185), which reuses this content.') +}).describe('The anonymous candidate card as an organization reads it. Only values that the candidate confirmed reach it; an unconfirmed suggestion and an unknown value never do. A free text value (a stack tag, a soft skill, the location) that looks like a contact (an email address, a phone number, a URL or domain, a Telegram link, an @handle) is dropped by the builder and never published. It carries no name, contact, resume text, employer, salary figure, account or profile identifier, and no schema of the private profile or of a contact disclosure is reachable from it; a contact reaches an organization only through the contact grant of an accepted invitation. Each property is null when its field is not published or the candidate has no value for it, so the card does not tell the two apart. The set of properties is closed, and an organization-visible card must never gain a property that identifies the candidate. The search ranking and the full card of an organization\'s search result are defined by the search contract, which reuses this content.') export type AnonymousCardContent = zod.input; export type AnonymousCardContentOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/privacy/cardPreview.zod.ts b/frontend/src/shared/api/schemas/privacy/cardPreview.zod.ts index 08fc52c..cd86133 100644 --- a/frontend/src/shared/api/schemas/privacy/cardPreview.zod.ts +++ b/frontend/src/shared/api/schemas/privacy/cardPreview.zod.ts @@ -44,7 +44,7 @@ export const CardPreview = zod.object({ "soft_skills": zod.array(zod.string().min(1).max(cardPreviewCardOneSoftSkillsItemMax).regex(cardPreviewCardOneSoftSkillsItemRegExp).describe('Plain text; clients show it as text, never as HTML.')).max(cardPreviewCardOneSoftSkillsMax).nullable().describe('Soft skills of the candidate, or null.'), "location": zod.string().min(1).max(cardPreviewCardOneLocationMax).regex(cardPreviewCardOneLocationRegExp).nullable().describe('City or region as free text, never a street address, or null. Plain text; clients show it as text, never as HTML.'), "relocation": zod.boolean().nullable().describe('Whether the candidate is ready to relocate, or null.') -}).describe('The anonymous candidate card as an organization reads it. Only values that the candidate confirmed reach it; an unconfirmed suggestion and an unknown value never do. A free text value (a stack tag, a soft skill, the location) that looks like a contact (an email address, a phone number, a URL or domain, a Telegram link, an @handle) is dropped by the builder (TASK-089) and never published. It carries no name, contact, resume text, employer, salary figure, account or profile identifier, and no schema of the private profile or of a contact disclosure is reachable from it; a contact reaches an organization only through the contact grant of an accepted invitation. Each property is null when its field is not published or the candidate has no value for it, so the card does not tell the two apart. The set of properties is closed, and an organization-visible card must never gain a property that identifies the candidate. The search ranking and the full card of an organization\'s search result are defined by the search contract (TASK-185), which reuses this content.'),zod.null()]), +}).describe('The anonymous candidate card as an organization reads it. Only values that the candidate confirmed reach it; an unconfirmed suggestion and an unknown value never do. A free text value (a stack tag, a soft skill, the location) that looks like a contact (an email address, a phone number, a URL or domain, a Telegram link, an @handle) is dropped by the builder and never published. It carries no name, contact, resume text, employer, salary figure, account or profile identifier, and no schema of the private profile or of a contact disclosure is reachable from it; a contact reaches an organization only through the contact grant of an accepted invitation. Each property is null when its field is not published or the candidate has no value for it, so the card does not tell the two apart. The set of properties is closed, and an organization-visible card must never gain a property that identifies the candidate. The search ranking and the full card of an organization\'s search result are defined by the search contract, which reuses this content.'),zod.null()]), "generated_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.') }).describe('What an organization that the candidate does not hide the profile from would read now, computed from the current profile, the current publication, and the consent ledger. It is a read for the candidate: it creates no view and no history record, and it never reaches an organization. `card` is null while the profile is closed.') diff --git a/frontend/src/shared/api/schemas/support/createMySupportCaseBody.zod.ts b/frontend/src/shared/api/schemas/support/createMySupportCaseBody.zod.ts index 209d86b..81a660b 100644 --- a/frontend/src/shared/api/schemas/support/createMySupportCaseBody.zod.ts +++ b/frontend/src/shared/api/schemas/support/createMySupportCaseBody.zod.ts @@ -31,7 +31,7 @@ export const CreateMySupportCaseBody = zod.union([zod.object({ "type": zod.enum(['support']), "description": zod.string().min(1).max(createMySupportCaseBodyOneDescriptionMax).regex(createMySupportCaseBodyOneDescriptionRegExp).describe('What the user asks or reports, as the user wrote it. It must contain at least one character that is not whitespace, so an empty or blank text fails validation with the pointer `/description`; it may contain line breaks. The pattern `\\S` uses the ECMAScript white space set in both generated validators: ogen converts it to that set for Go, so a text made only of spaces such as U+00A0, U+2003, or U+3000 fails in the server schema and in Zod alike. ECMAScript white space omits U+0085 (NEL), which Go `unicode.IsSpace` includes; the server therefore also rejects a text whose every character is `unicode.IsSpace` or U+FEFF, with the same 400 and the pointer `/description`, while generated Zod accepts a text of NEL. Plain text; clients show it as text, never as HTML. The server stores it as written, shows it only to the author and to the staff of the queue, and never writes it to logs or notifications. Users should not put passwords or other people\'s contact data into it. Generated Zod validators count UTF-16 code units, so the server stays authoritative for the length.'), "object": zod.object({ - "type": zod.enum(['assessment_attempt', 'organization', 'invitation', 'support_case']).describe('Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a contract change: generated clients reject an unknown value. Planned values: `vacancy` and `application` with the vacancies and protected applications of PRD FR16, and a profile finding with TASK-272.\n\n- assessment_attempt: an assessment attempt of the caller.\n- organization: an organization that the caller can see.\n- invitation: an invitation addressed to the caller. Invitations are in the contract (TASK-196) but not implemented yet; until they are, every invitation reference answers 404 not_found.\n- support_case: another case of the caller, for example the resolved manual assessment that a grade appeal disputes.'), + "type": zod.enum(['assessment_attempt', 'organization', 'invitation', 'support_case']).describe('Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a contract change: generated clients reject an unknown value. Planned values: `vacancy` and `application` with the vacancies and protected applications of PRD FR16, and a profile finding with profile analysis.\n\n- assessment_attempt: an assessment attempt of the caller.\n- organization: an organization that the caller can see.\n- invitation: an invitation addressed to the caller. Invitations are in the contract but not implemented yet; until they are, every invitation reference answers 404 not_found.\n- support_case: another case of the caller, for example the resolved manual assessment that a grade appeal disputes.'), "id": zod.uuid().describe('Identifier of the object.') }).exactOptional().describe('Typed reference to an object that the case is about. The server checks on creation that the caller may see the object; an unknown object and an object of someone else both answer 404 not_found, so a reference never reveals whether another person\'s object exists. The case keeps only the type and the identifier, never a copy of the object.'), "assessment_target": zod.object({ diff --git a/frontend/src/shared/api/schemas/support/supportCase.zod.ts b/frontend/src/shared/api/schemas/support/supportCase.zod.ts index 94c170e..e78d981 100644 --- a/frontend/src/shared/api/schemas/support/supportCase.zod.ts +++ b/frontend/src/shared/api/schemas/support/supportCase.zod.ts @@ -34,7 +34,7 @@ export const SupportCase = zod.object({ "status": zod.enum(['submitted', 'in_review', 'waiting_for_user', 'waiting_expert', 'resolved', 'closed']).describe('Processing status of a case. Only the server changes it; no request field sets it. Adding a value is a contract change: generated clients reject an unknown value.\n\n- submitted: the case was accepted and waits in its queue.\n- in_review: support or a moderator works on it.\n- waiting_for_user: support asked the author for more detail. Not set yet: it starts with the planned operation that lets the author reply, and until then no case has this status.\n- waiting_expert: a grade appeal, an anti-cheat appeal, or a manual assessment waits for a subject expert. The server sets it in the same transaction as the creation of such a case. The case stays here until a person decides; it is never resolved by the passing of time.\n- resolved: terminal; a decision was made and `decision` holds its outcome and public reason.\n- closed: terminal; the case ended without a decision on the merits, for example as a duplicate of another case. The last history event says why.'), "description": zod.string().min(1).max(supportCaseDescriptionMax).regex(supportCaseDescriptionRegExp).describe('What the user asks or reports, as the user wrote it. It must contain at least one character that is not whitespace, so an empty or blank text fails validation with the pointer `/description`; it may contain line breaks. The pattern `\\S` uses the ECMAScript white space set in both generated validators: ogen converts it to that set for Go, so a text made only of spaces such as U+00A0, U+2003, or U+3000 fails in the server schema and in Zod alike. ECMAScript white space omits U+0085 (NEL), which Go `unicode.IsSpace` includes; the server therefore also rejects a text whose every character is `unicode.IsSpace` or U+FEFF, with the same 400 and the pointer `/description`, while generated Zod accepts a text of NEL. Plain text; clients show it as text, never as HTML. The server stores it as written, shows it only to the author and to the staff of the queue, and never writes it to logs or notifications. Users should not put passwords or other people\'s contact data into it. Generated Zod validators count UTF-16 code units, so the server stays authoritative for the length.'), "object": zod.union([zod.object({ - "type": zod.enum(['assessment_attempt', 'organization', 'invitation', 'support_case']).describe('Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a contract change: generated clients reject an unknown value. Planned values: `vacancy` and `application` with the vacancies and protected applications of PRD FR16, and a profile finding with TASK-272.\n\n- assessment_attempt: an assessment attempt of the caller.\n- organization: an organization that the caller can see.\n- invitation: an invitation addressed to the caller. Invitations are in the contract (TASK-196) but not implemented yet; until they are, every invitation reference answers 404 not_found.\n- support_case: another case of the caller, for example the resolved manual assessment that a grade appeal disputes.'), + "type": zod.enum(['assessment_attempt', 'organization', 'invitation', 'support_case']).describe('Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a contract change: generated clients reject an unknown value. Planned values: `vacancy` and `application` with the vacancies and protected applications of PRD FR16, and a profile finding with profile analysis.\n\n- assessment_attempt: an assessment attempt of the caller.\n- organization: an organization that the caller can see.\n- invitation: an invitation addressed to the caller. Invitations are in the contract but not implemented yet; until they are, every invitation reference answers 404 not_found.\n- support_case: another case of the caller, for example the resolved manual assessment that a grade appeal disputes.'), "id": zod.uuid().describe('Identifier of the object.') }).describe('Typed reference to an object that the case is about. The server checks on creation that the caller may see the object; an unknown object and an object of someone else both answer 404 not_found, so a reference never reveals whether another person\'s object exists. The case keeps only the type and the identifier, never a copy of the object.'),zod.null()]).describe('Object that the case is about, as sent on creation, or null when the case has none.'), "assessment_target": zod.union([zod.object({ @@ -58,8 +58,8 @@ export const SupportCase = zod.object({ }).describe('Decision visible to the user. It exists only once the case is `resolved`. It holds the outcome and the public reason; it never names the moderator or the expert and never contains internal notes, evidence, sanctions against another party, or risk signals. An upheld grade appeal never rewrites the original result: the corrected result is a separate decision of the assessment, and both stay in the history of that attempt.'),zod.null()]).describe('Decision once the case is `resolved`, otherwise null.'), "history": zod.array(zod.object({ "sequence": zod.int().min(1).describe('Position of the event in the history, starting at 1 and increasing by one.'), - "kind": zod.enum(['created', 'status_changed', 'reply', 'decision']).describe('Kind of a public history event. Adding a value is a contract change. A reply of the author, planned with `waiting_for_user`, is a `reply` with the actor `user`, and a later revision of a decision (TASK-317) is another `decision` event, so neither needs a new value.\n\n- created: the case was created; `status` is `submitted`. For an appeal or a manual assessment, a `status_changed` event of the actor `system` to `waiting_expert` follows in the same transaction.\n- status_changed: the status changed; `status` is the new status, and `message` may explain a closure.\n- reply: support replied; `message` holds the reply and `status` is null.\n- decision: a decision was made; `status` is `resolved` and `message` holds the public reason.'), - "actor": zod.enum(['user', 'support', 'system']).describe('Who caused an event, by kind only. A case never names or identifies a moderator, an expert, or a support agent; experts and moderators of TASK-316 and TASK-323 are `support` too. Adding a value is a contract change.\n\n- user: the author of the case.\n- support: a person of the support, moderation, or expert staff.\n- system: the server, for example on creation or when it routes the case.'), + "kind": zod.enum(['created', 'status_changed', 'reply', 'decision']).describe('Kind of a public history event. Adding a value is a contract change. A reply of the author, planned with `waiting_for_user`, is a `reply` with the actor `user`, and a later revision of a decision is another `decision` event, so neither needs a new value.\n\n- created: the case was created; `status` is `submitted`. For an appeal or a manual assessment, a `status_changed` event of the actor `system` to `waiting_expert` follows in the same transaction.\n- status_changed: the status changed; `status` is the new status, and `message` may explain a closure.\n- reply: support replied; `message` holds the reply and `status` is null.\n- decision: a decision was made; `status` is `resolved` and `message` holds the public reason.'), + "actor": zod.enum(['user', 'support', 'system']).describe('Who caused an event, by kind only. A case never names or identifies a moderator, an expert, or a support agent; assessment experts and appeal moderators are `support` too. Adding a value is a contract change.\n\n- user: the author of the case.\n- support: a person of the support, moderation, or expert staff.\n- system: the server, for example on creation or when it routes the case.'), "occurred_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'), "status": zod.union([zod.enum(['submitted', 'in_review', 'waiting_for_user', 'waiting_expert', 'resolved', 'closed']).describe('Processing status of a case. Only the server changes it; no request field sets it. Adding a value is a contract change: generated clients reject an unknown value.\n\n- submitted: the case was accepted and waits in its queue.\n- in_review: support or a moderator works on it.\n- waiting_for_user: support asked the author for more detail. Not set yet: it starts with the planned operation that lets the author reply, and until then no case has this status.\n- waiting_expert: a grade appeal, an anti-cheat appeal, or a manual assessment waits for a subject expert. The server sets it in the same transaction as the creation of such a case. The case stays here until a person decides; it is never resolved by the passing of time.\n- resolved: terminal; a decision was made and `decision` holds its outcome and public reason.\n- closed: terminal; the case ended without a decision on the merits, for example as a duplicate of another case. The last history event says why.'),zod.null()]).describe('Status of the case after the event, or null for a reply.'), "message": zod.union([zod.string().min(1).max(supportCaseHistoryItemMessageOneMax).describe('Text that support or a moderator wrote for the user: a public reply or the public reason of a decision. Plain text; clients show it as text, never as HTML. Internal notes of the staff are never public texts.'),zod.null()]).describe('Public text of the event, or null.') diff --git a/frontend/src/shared/api/schemas/support/supportCaseActorKind.zod.ts b/frontend/src/shared/api/schemas/support/supportCaseActorKind.zod.ts index 0409118..895e7ef 100644 --- a/frontend/src/shared/api/schemas/support/supportCaseActorKind.zod.ts +++ b/frontend/src/shared/api/schemas/support/supportCaseActorKind.zod.ts @@ -6,7 +6,7 @@ */ import * as zod from 'zod'; -export const SupportCaseActorKind = zod.enum(['user', 'support', 'system']).describe('Who caused an event, by kind only. A case never names or identifies a moderator, an expert, or a support agent; experts and moderators of TASK-316 and TASK-323 are `support` too. Adding a value is a contract change.\n\n- user: the author of the case.\n- support: a person of the support, moderation, or expert staff.\n- system: the server, for example on creation or when it routes the case.') +export const SupportCaseActorKind = zod.enum(['user', 'support', 'system']).describe('Who caused an event, by kind only. A case never names or identifies a moderator, an expert, or a support agent; assessment experts and appeal moderators are `support` too. Adding a value is a contract change.\n\n- user: the author of the case.\n- support: a person of the support, moderation, or expert staff.\n- system: the server, for example on creation or when it routes the case.') export type SupportCaseActorKind = zod.input; export type SupportCaseActorKindOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/support/supportCaseCreate.zod.ts b/frontend/src/shared/api/schemas/support/supportCaseCreate.zod.ts index 84bbf24..3b8d6a0 100644 --- a/frontend/src/shared/api/schemas/support/supportCaseCreate.zod.ts +++ b/frontend/src/shared/api/schemas/support/supportCaseCreate.zod.ts @@ -31,7 +31,7 @@ export const SupportCaseCreate = zod.union([zod.object({ "type": zod.enum(['support']), "description": zod.string().min(1).max(supportCaseCreateOneDescriptionMax).regex(supportCaseCreateOneDescriptionRegExp).describe('What the user asks or reports, as the user wrote it. It must contain at least one character that is not whitespace, so an empty or blank text fails validation with the pointer `/description`; it may contain line breaks. The pattern `\\S` uses the ECMAScript white space set in both generated validators: ogen converts it to that set for Go, so a text made only of spaces such as U+00A0, U+2003, or U+3000 fails in the server schema and in Zod alike. ECMAScript white space omits U+0085 (NEL), which Go `unicode.IsSpace` includes; the server therefore also rejects a text whose every character is `unicode.IsSpace` or U+FEFF, with the same 400 and the pointer `/description`, while generated Zod accepts a text of NEL. Plain text; clients show it as text, never as HTML. The server stores it as written, shows it only to the author and to the staff of the queue, and never writes it to logs or notifications. Users should not put passwords or other people\'s contact data into it. Generated Zod validators count UTF-16 code units, so the server stays authoritative for the length.'), "object": zod.object({ - "type": zod.enum(['assessment_attempt', 'organization', 'invitation', 'support_case']).describe('Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a contract change: generated clients reject an unknown value. Planned values: `vacancy` and `application` with the vacancies and protected applications of PRD FR16, and a profile finding with TASK-272.\n\n- assessment_attempt: an assessment attempt of the caller.\n- organization: an organization that the caller can see.\n- invitation: an invitation addressed to the caller. Invitations are in the contract (TASK-196) but not implemented yet; until they are, every invitation reference answers 404 not_found.\n- support_case: another case of the caller, for example the resolved manual assessment that a grade appeal disputes.'), + "type": zod.enum(['assessment_attempt', 'organization', 'invitation', 'support_case']).describe('Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a contract change: generated clients reject an unknown value. Planned values: `vacancy` and `application` with the vacancies and protected applications of PRD FR16, and a profile finding with profile analysis.\n\n- assessment_attempt: an assessment attempt of the caller.\n- organization: an organization that the caller can see.\n- invitation: an invitation addressed to the caller. Invitations are in the contract but not implemented yet; until they are, every invitation reference answers 404 not_found.\n- support_case: another case of the caller, for example the resolved manual assessment that a grade appeal disputes.'), "id": zod.uuid().describe('Identifier of the object.') }).exactOptional().describe('Typed reference to an object that the case is about. The server checks on creation that the caller may see the object; an unknown object and an object of someone else both answer 404 not_found, so a reference never reveals whether another person\'s object exists. The case keeps only the type and the identifier, never a copy of the object.'), "assessment_target": zod.object({ diff --git a/frontend/src/shared/api/schemas/support/supportCaseCreateSupport.zod.ts b/frontend/src/shared/api/schemas/support/supportCaseCreateSupport.zod.ts index f9a2875..3e6850c 100644 --- a/frontend/src/shared/api/schemas/support/supportCaseCreateSupport.zod.ts +++ b/frontend/src/shared/api/schemas/support/supportCaseCreateSupport.zod.ts @@ -15,7 +15,7 @@ export const SupportCaseCreateSupport = zod.object({ "type": zod.enum(['support']), "description": zod.string().min(1).max(supportCaseCreateSupportDescriptionMax).regex(supportCaseCreateSupportDescriptionRegExp).describe('What the user asks or reports, as the user wrote it. It must contain at least one character that is not whitespace, so an empty or blank text fails validation with the pointer `/description`; it may contain line breaks. The pattern `\\S` uses the ECMAScript white space set in both generated validators: ogen converts it to that set for Go, so a text made only of spaces such as U+00A0, U+2003, or U+3000 fails in the server schema and in Zod alike. ECMAScript white space omits U+0085 (NEL), which Go `unicode.IsSpace` includes; the server therefore also rejects a text whose every character is `unicode.IsSpace` or U+FEFF, with the same 400 and the pointer `/description`, while generated Zod accepts a text of NEL. Plain text; clients show it as text, never as HTML. The server stores it as written, shows it only to the author and to the staff of the queue, and never writes it to logs or notifications. Users should not put passwords or other people\'s contact data into it. Generated Zod validators count UTF-16 code units, so the server stays authoritative for the length.'), "object": zod.object({ - "type": zod.enum(['assessment_attempt', 'organization', 'invitation', 'support_case']).describe('Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a contract change: generated clients reject an unknown value. Planned values: `vacancy` and `application` with the vacancies and protected applications of PRD FR16, and a profile finding with TASK-272.\n\n- assessment_attempt: an assessment attempt of the caller.\n- organization: an organization that the caller can see.\n- invitation: an invitation addressed to the caller. Invitations are in the contract (TASK-196) but not implemented yet; until they are, every invitation reference answers 404 not_found.\n- support_case: another case of the caller, for example the resolved manual assessment that a grade appeal disputes.'), + "type": zod.enum(['assessment_attempt', 'organization', 'invitation', 'support_case']).describe('Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a contract change: generated clients reject an unknown value. Planned values: `vacancy` and `application` with the vacancies and protected applications of PRD FR16, and a profile finding with profile analysis.\n\n- assessment_attempt: an assessment attempt of the caller.\n- organization: an organization that the caller can see.\n- invitation: an invitation addressed to the caller. Invitations are in the contract but not implemented yet; until they are, every invitation reference answers 404 not_found.\n- support_case: another case of the caller, for example the resolved manual assessment that a grade appeal disputes.'), "id": zod.uuid().describe('Identifier of the object.') }).exactOptional().describe('Typed reference to an object that the case is about. The server checks on creation that the caller may see the object; an unknown object and an object of someone else both answer 404 not_found, so a reference never reveals whether another person\'s object exists. The case keeps only the type and the identifier, never a copy of the object.'), "assessment_target": zod.object({ diff --git a/frontend/src/shared/api/schemas/support/supportCaseEvent.zod.ts b/frontend/src/shared/api/schemas/support/supportCaseEvent.zod.ts index 9750880..0fef5e3 100644 --- a/frontend/src/shared/api/schemas/support/supportCaseEvent.zod.ts +++ b/frontend/src/shared/api/schemas/support/supportCaseEvent.zod.ts @@ -12,8 +12,8 @@ export const supportCaseEventMessageOneMax = 4000; export const SupportCaseEvent = zod.object({ "sequence": zod.int().min(1).describe('Position of the event in the history, starting at 1 and increasing by one.'), - "kind": zod.enum(['created', 'status_changed', 'reply', 'decision']).describe('Kind of a public history event. Adding a value is a contract change. A reply of the author, planned with `waiting_for_user`, is a `reply` with the actor `user`, and a later revision of a decision (TASK-317) is another `decision` event, so neither needs a new value.\n\n- created: the case was created; `status` is `submitted`. For an appeal or a manual assessment, a `status_changed` event of the actor `system` to `waiting_expert` follows in the same transaction.\n- status_changed: the status changed; `status` is the new status, and `message` may explain a closure.\n- reply: support replied; `message` holds the reply and `status` is null.\n- decision: a decision was made; `status` is `resolved` and `message` holds the public reason.'), - "actor": zod.enum(['user', 'support', 'system']).describe('Who caused an event, by kind only. A case never names or identifies a moderator, an expert, or a support agent; experts and moderators of TASK-316 and TASK-323 are `support` too. Adding a value is a contract change.\n\n- user: the author of the case.\n- support: a person of the support, moderation, or expert staff.\n- system: the server, for example on creation or when it routes the case.'), + "kind": zod.enum(['created', 'status_changed', 'reply', 'decision']).describe('Kind of a public history event. Adding a value is a contract change. A reply of the author, planned with `waiting_for_user`, is a `reply` with the actor `user`, and a later revision of a decision is another `decision` event, so neither needs a new value.\n\n- created: the case was created; `status` is `submitted`. For an appeal or a manual assessment, a `status_changed` event of the actor `system` to `waiting_expert` follows in the same transaction.\n- status_changed: the status changed; `status` is the new status, and `message` may explain a closure.\n- reply: support replied; `message` holds the reply and `status` is null.\n- decision: a decision was made; `status` is `resolved` and `message` holds the public reason.'), + "actor": zod.enum(['user', 'support', 'system']).describe('Who caused an event, by kind only. A case never names or identifies a moderator, an expert, or a support agent; assessment experts and appeal moderators are `support` too. Adding a value is a contract change.\n\n- user: the author of the case.\n- support: a person of the support, moderation, or expert staff.\n- system: the server, for example on creation or when it routes the case.'), "occurred_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'), "status": zod.union([zod.enum(['submitted', 'in_review', 'waiting_for_user', 'waiting_expert', 'resolved', 'closed']).describe('Processing status of a case. Only the server changes it; no request field sets it. Adding a value is a contract change: generated clients reject an unknown value.\n\n- submitted: the case was accepted and waits in its queue.\n- in_review: support or a moderator works on it.\n- waiting_for_user: support asked the author for more detail. Not set yet: it starts with the planned operation that lets the author reply, and until then no case has this status.\n- waiting_expert: a grade appeal, an anti-cheat appeal, or a manual assessment waits for a subject expert. The server sets it in the same transaction as the creation of such a case. The case stays here until a person decides; it is never resolved by the passing of time.\n- resolved: terminal; a decision was made and `decision` holds its outcome and public reason.\n- closed: terminal; the case ended without a decision on the merits, for example as a duplicate of another case. The last history event says why.'),zod.null()]).describe('Status of the case after the event, or null for a reply.'), "message": zod.union([zod.string().min(1).max(supportCaseEventMessageOneMax).describe('Text that support or a moderator wrote for the user: a public reply or the public reason of a decision. Plain text; clients show it as text, never as HTML. Internal notes of the staff are never public texts.'),zod.null()]).describe('Public text of the event, or null.') diff --git a/frontend/src/shared/api/schemas/support/supportCaseEventKind.zod.ts b/frontend/src/shared/api/schemas/support/supportCaseEventKind.zod.ts index b8dac05..62c1d58 100644 --- a/frontend/src/shared/api/schemas/support/supportCaseEventKind.zod.ts +++ b/frontend/src/shared/api/schemas/support/supportCaseEventKind.zod.ts @@ -6,7 +6,7 @@ */ import * as zod from 'zod'; -export const SupportCaseEventKind = zod.enum(['created', 'status_changed', 'reply', 'decision']).describe('Kind of a public history event. Adding a value is a contract change. A reply of the author, planned with `waiting_for_user`, is a `reply` with the actor `user`, and a later revision of a decision (TASK-317) is another `decision` event, so neither needs a new value.\n\n- created: the case was created; `status` is `submitted`. For an appeal or a manual assessment, a `status_changed` event of the actor `system` to `waiting_expert` follows in the same transaction.\n- status_changed: the status changed; `status` is the new status, and `message` may explain a closure.\n- reply: support replied; `message` holds the reply and `status` is null.\n- decision: a decision was made; `status` is `resolved` and `message` holds the public reason.') +export const SupportCaseEventKind = zod.enum(['created', 'status_changed', 'reply', 'decision']).describe('Kind of a public history event. Adding a value is a contract change. A reply of the author, planned with `waiting_for_user`, is a `reply` with the actor `user`, and a later revision of a decision is another `decision` event, so neither needs a new value.\n\n- created: the case was created; `status` is `submitted`. For an appeal or a manual assessment, a `status_changed` event of the actor `system` to `waiting_expert` follows in the same transaction.\n- status_changed: the status changed; `status` is the new status, and `message` may explain a closure.\n- reply: support replied; `message` holds the reply and `status` is null.\n- decision: a decision was made; `status` is `resolved` and `message` holds the public reason.') export type SupportCaseEventKind = zod.input; export type SupportCaseEventKindOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/support/supportCaseList.zod.ts b/frontend/src/shared/api/schemas/support/supportCaseList.zod.ts index 0979403..9b4ede6 100644 --- a/frontend/src/shared/api/schemas/support/supportCaseList.zod.ts +++ b/frontend/src/shared/api/schemas/support/supportCaseList.zod.ts @@ -28,7 +28,7 @@ export const SupportCaseList = zod.object({ "type": zod.enum(['support', 'complaint', 'grade_appeal', 'anticheat_appeal', 'manual_assessment']).describe('Kind of the case. It fixes the allowed object reference, the type-specific fields, the response target, and the queue that handles the case.\n\n- support: a question or a problem, for example an assessment that is not available or a failed sandbox run. Candidate and employer accounts.\n- complaint: a complaint about an organization or an offer, including a breach of the salary terms or a disclosure of personal data (PRD FR18). Candidate accounts.\n- grade_appeal: an appeal of a category the caller received: the result of one own assessment attempt, or the outcome of one own resolved manual assessment case. An expert reviews it, and the original result stays in the history. Candidate accounts.\n- anticheat_appeal: an appeal of an anti-cheat review decision on one own assessment attempt. Candidate accounts.\n- manual_assessment: a request for a manual assessment of a category by a subject expert with the same rubric, the alternative to automated categorization (consent C3). Candidate accounts.'), "status": zod.enum(['submitted', 'in_review', 'waiting_for_user', 'waiting_expert', 'resolved', 'closed']).describe('Processing status of a case. Only the server changes it; no request field sets it. Adding a value is a contract change: generated clients reject an unknown value.\n\n- submitted: the case was accepted and waits in its queue.\n- in_review: support or a moderator works on it.\n- waiting_for_user: support asked the author for more detail. Not set yet: it starts with the planned operation that lets the author reply, and until then no case has this status.\n- waiting_expert: a grade appeal, an anti-cheat appeal, or a manual assessment waits for a subject expert. The server sets it in the same transaction as the creation of such a case. The case stays here until a person decides; it is never resolved by the passing of time.\n- resolved: terminal; a decision was made and `decision` holds its outcome and public reason.\n- closed: terminal; the case ended without a decision on the merits, for example as a duplicate of another case. The last history event says why.'), "object": zod.union([zod.object({ - "type": zod.enum(['assessment_attempt', 'organization', 'invitation', 'support_case']).describe('Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a contract change: generated clients reject an unknown value. Planned values: `vacancy` and `application` with the vacancies and protected applications of PRD FR16, and a profile finding with TASK-272.\n\n- assessment_attempt: an assessment attempt of the caller.\n- organization: an organization that the caller can see.\n- invitation: an invitation addressed to the caller. Invitations are in the contract (TASK-196) but not implemented yet; until they are, every invitation reference answers 404 not_found.\n- support_case: another case of the caller, for example the resolved manual assessment that a grade appeal disputes.'), + "type": zod.enum(['assessment_attempt', 'organization', 'invitation', 'support_case']).describe('Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a contract change: generated clients reject an unknown value. Planned values: `vacancy` and `application` with the vacancies and protected applications of PRD FR16, and a profile finding with profile analysis.\n\n- assessment_attempt: an assessment attempt of the caller.\n- organization: an organization that the caller can see.\n- invitation: an invitation addressed to the caller. Invitations are in the contract but not implemented yet; until they are, every invitation reference answers 404 not_found.\n- support_case: another case of the caller, for example the resolved manual assessment that a grade appeal disputes.'), "id": zod.uuid().describe('Identifier of the object.') }).describe('Typed reference to an object that the case is about. The server checks on creation that the caller may see the object; an unknown object and an object of someone else both answer 404 not_found, so a reference never reveals whether another person\'s object exists. The case keeps only the type and the identifier, never a copy of the object.'),zod.null()]).describe('Object that the case is about, or null.'), "assessment_target": zod.union([zod.object({ diff --git a/frontend/src/shared/api/schemas/support/supportCaseObjectReference.zod.ts b/frontend/src/shared/api/schemas/support/supportCaseObjectReference.zod.ts index 515acae..179a7bd 100644 --- a/frontend/src/shared/api/schemas/support/supportCaseObjectReference.zod.ts +++ b/frontend/src/shared/api/schemas/support/supportCaseObjectReference.zod.ts @@ -7,7 +7,7 @@ import * as zod from 'zod'; export const SupportCaseObjectReference = zod.object({ - "type": zod.enum(['assessment_attempt', 'organization', 'invitation', 'support_case']).describe('Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a contract change: generated clients reject an unknown value. Planned values: `vacancy` and `application` with the vacancies and protected applications of PRD FR16, and a profile finding with TASK-272.\n\n- assessment_attempt: an assessment attempt of the caller.\n- organization: an organization that the caller can see.\n- invitation: an invitation addressed to the caller. Invitations are in the contract (TASK-196) but not implemented yet; until they are, every invitation reference answers 404 not_found.\n- support_case: another case of the caller, for example the resolved manual assessment that a grade appeal disputes.'), + "type": zod.enum(['assessment_attempt', 'organization', 'invitation', 'support_case']).describe('Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a contract change: generated clients reject an unknown value. Planned values: `vacancy` and `application` with the vacancies and protected applications of PRD FR16, and a profile finding with profile analysis.\n\n- assessment_attempt: an assessment attempt of the caller.\n- organization: an organization that the caller can see.\n- invitation: an invitation addressed to the caller. Invitations are in the contract but not implemented yet; until they are, every invitation reference answers 404 not_found.\n- support_case: another case of the caller, for example the resolved manual assessment that a grade appeal disputes.'), "id": zod.uuid().describe('Identifier of the object.') }).describe('Typed reference to an object that the case is about. The server checks on creation that the caller may see the object; an unknown object and an object of someone else both answer 404 not_found, so a reference never reveals whether another person\'s object exists. The case keeps only the type and the identifier, never a copy of the object.') diff --git a/frontend/src/shared/api/schemas/support/supportCaseObjectType.zod.ts b/frontend/src/shared/api/schemas/support/supportCaseObjectType.zod.ts index c86d0d9..67de78e 100644 --- a/frontend/src/shared/api/schemas/support/supportCaseObjectType.zod.ts +++ b/frontend/src/shared/api/schemas/support/supportCaseObjectType.zod.ts @@ -6,7 +6,7 @@ */ import * as zod from 'zod'; -export const SupportCaseObjectType = zod.enum(['assessment_attempt', 'organization', 'invitation', 'support_case']).describe('Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a contract change: generated clients reject an unknown value. Planned values: `vacancy` and `application` with the vacancies and protected applications of PRD FR16, and a profile finding with TASK-272.\n\n- assessment_attempt: an assessment attempt of the caller.\n- organization: an organization that the caller can see.\n- invitation: an invitation addressed to the caller. Invitations are in the contract (TASK-196) but not implemented yet; until they are, every invitation reference answers 404 not_found.\n- support_case: another case of the caller, for example the resolved manual assessment that a grade appeal disputes.') +export const SupportCaseObjectType = zod.enum(['assessment_attempt', 'organization', 'invitation', 'support_case']).describe('Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a contract change: generated clients reject an unknown value. Planned values: `vacancy` and `application` with the vacancies and protected applications of PRD FR16, and a profile finding with profile analysis.\n\n- assessment_attempt: an assessment attempt of the caller.\n- organization: an organization that the caller can see.\n- invitation: an invitation addressed to the caller. Invitations are in the contract but not implemented yet; until they are, every invitation reference answers 404 not_found.\n- support_case: another case of the caller, for example the resolved manual assessment that a grade appeal disputes.') export type SupportCaseObjectType = zod.input; export type SupportCaseObjectTypeOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/support/supportCaseSummary.zod.ts b/frontend/src/shared/api/schemas/support/supportCaseSummary.zod.ts index 3ead3c9..ea1d203 100644 --- a/frontend/src/shared/api/schemas/support/supportCaseSummary.zod.ts +++ b/frontend/src/shared/api/schemas/support/supportCaseSummary.zod.ts @@ -21,7 +21,7 @@ export const SupportCaseSummary = zod.object({ "type": zod.enum(['support', 'complaint', 'grade_appeal', 'anticheat_appeal', 'manual_assessment']).describe('Kind of the case. It fixes the allowed object reference, the type-specific fields, the response target, and the queue that handles the case.\n\n- support: a question or a problem, for example an assessment that is not available or a failed sandbox run. Candidate and employer accounts.\n- complaint: a complaint about an organization or an offer, including a breach of the salary terms or a disclosure of personal data (PRD FR18). Candidate accounts.\n- grade_appeal: an appeal of a category the caller received: the result of one own assessment attempt, or the outcome of one own resolved manual assessment case. An expert reviews it, and the original result stays in the history. Candidate accounts.\n- anticheat_appeal: an appeal of an anti-cheat review decision on one own assessment attempt. Candidate accounts.\n- manual_assessment: a request for a manual assessment of a category by a subject expert with the same rubric, the alternative to automated categorization (consent C3). Candidate accounts.'), "status": zod.enum(['submitted', 'in_review', 'waiting_for_user', 'waiting_expert', 'resolved', 'closed']).describe('Processing status of a case. Only the server changes it; no request field sets it. Adding a value is a contract change: generated clients reject an unknown value.\n\n- submitted: the case was accepted and waits in its queue.\n- in_review: support or a moderator works on it.\n- waiting_for_user: support asked the author for more detail. Not set yet: it starts with the planned operation that lets the author reply, and until then no case has this status.\n- waiting_expert: a grade appeal, an anti-cheat appeal, or a manual assessment waits for a subject expert. The server sets it in the same transaction as the creation of such a case. The case stays here until a person decides; it is never resolved by the passing of time.\n- resolved: terminal; a decision was made and `decision` holds its outcome and public reason.\n- closed: terminal; the case ended without a decision on the merits, for example as a duplicate of another case. The last history event says why.'), "object": zod.union([zod.object({ - "type": zod.enum(['assessment_attempt', 'organization', 'invitation', 'support_case']).describe('Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a contract change: generated clients reject an unknown value. Planned values: `vacancy` and `application` with the vacancies and protected applications of PRD FR16, and a profile finding with TASK-272.\n\n- assessment_attempt: an assessment attempt of the caller.\n- organization: an organization that the caller can see.\n- invitation: an invitation addressed to the caller. Invitations are in the contract (TASK-196) but not implemented yet; until they are, every invitation reference answers 404 not_found.\n- support_case: another case of the caller, for example the resolved manual assessment that a grade appeal disputes.'), + "type": zod.enum(['assessment_attempt', 'organization', 'invitation', 'support_case']).describe('Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a contract change: generated clients reject an unknown value. Planned values: `vacancy` and `application` with the vacancies and protected applications of PRD FR16, and a profile finding with profile analysis.\n\n- assessment_attempt: an assessment attempt of the caller.\n- organization: an organization that the caller can see.\n- invitation: an invitation addressed to the caller. Invitations are in the contract but not implemented yet; until they are, every invitation reference answers 404 not_found.\n- support_case: another case of the caller, for example the resolved manual assessment that a grade appeal disputes.'), "id": zod.uuid().describe('Identifier of the object.') }).describe('Typed reference to an object that the case is about. The server checks on creation that the caller may see the object; an unknown object and an object of someone else both answer 404 not_found, so a reference never reveals whether another person\'s object exists. The case keeps only the type and the identifier, never a copy of the object.'),zod.null()]).describe('Object that the case is about, or null.'), "assessment_target": zod.union([zod.object({ diff --git a/observability/grafana/dashboards/lincodex-product.json b/observability/grafana/dashboards/lincodex-product.json index 956a12f..2643fac 100644 --- a/observability/grafana/dashboards/lincodex-product.json +++ b/observability/grafana/dashboards/lincodex-product.json @@ -725,7 +725,7 @@ "type": "prometheus", "uid": "prometheus" }, - "description": "How long the earliest pending service mail (verification or password reset) has been due. Notifications are not counted: they wait until TASK-462 connects them. With EMAIL_PROVIDER=disabled nothing is sent and service mail waits.", + "description": "How long the earliest pending service mail (verification or password reset) has been due. Notifications are not counted: they wait until product notification sending is implemented. With EMAIL_PROVIDER=disabled nothing is sent and service mail waits.", "fieldConfig": { "defaults": { "color": { diff --git a/observability/prometheus/rules/lincodex.yml b/observability/prometheus/rules/lincodex.yml index 11773d9..e27a469 100644 --- a/observability/prometheus/rules/lincodex.yml +++ b/observability/prometheus/rules/lincodex.yml @@ -92,13 +92,13 @@ groups: summary: Mail deliveries have an unknown outcome. description: An attempt may have reached the provider without a conclusive answer; a retry needs the same idempotency key, and after the idempotency window an operator decides. - # Needs the sending worker (TASK-016), which exports + # Needs the sending worker, which exports # lincodex_mail_sender_running: 1 while its loop runs, 0 otherwise, and # 0 for the whole process lifetime with EMAIL_PROVIDER=disabled, where no # loop starts. The rule fires only while at least one backend instance # reports 1, so a stand without a transport stays silent. The age gauge # counts only service mail (verification and password reset), the kinds - # the worker sends: a due notification waits for TASK-462 and is not + # the worker sends: a due notification awaits product notification sending and is not # counted, so a notification backlog never fires this alert. - alert: LincodexMailDeliveriesOverdue expr: | diff --git a/observability/scripts/verify-product-metrics.sh b/observability/scripts/verify-product-metrics.sh index 5ad0b2f..b9a8e91 100755 --- a/observability/scripts/verify-product-metrics.sh +++ b/observability/scripts/verify-product-metrics.sh @@ -7,9 +7,9 @@ # metrics nor the logs in Loki. Everything it creates is removed on exit. # # Mail: EMAIL_PROVIDER=resend with a placeholder key, so the quota gauges -# exist. The sending worker (TASK-016) sends only verification and password +# exist. The sending worker sends only verification and password # reset mail; the stored fixture delivery is a notification, which stays -# pending until TASK-462 connects product notifications, and no call reaches +# pending until product notification sending is implemented, and no call reaches # Resend. set -euo pipefail