diff --git a/.agents/sources-of-truth.md b/.agents/sources-of-truth.md index 1955501..4c5ef45 100644 --- a/.agents/sources-of-truth.md +++ b/.agents/sources-of-truth.md @@ -3,12 +3,13 @@ Use the source that owns the fact being discussed. Read the relevant source before changing a dependent document or generated artifact. - The user's request sets the authorized task scope and product choices for that task. +- When present, the root PRD.md defines product requirements, delivery stages, and acceptance criteria. It is a self-contained specification, not an implementation status report. - Source code shows behavior that exists in this checkout. A passing test gives evidence only for the behavior it exercises. -- api/core/openapi.yml, api/ml/openapi.yml, and api/runner/openapi.yml, with their referenced source files, define the public and internal HTTP contracts. Bundles and generated clients are derived output. +- api/core/openapi.yml, api/ml/openapi.yml, api/runner/openapi.yml, and api/labd/openapi.yml, with their referenced source files, define the public and internal HTTP contracts. Bundles and generated clients are derived output. - Backend migrations define the database schema. sqlc query files define queries that sqlc generates. - Makefiles and checked-in tool configuration define supported project commands and options. Lockfiles preserve selected application dependency versions. Toolchain declarations define runtime versions; the Go backend uses exact version 1.26.9. Compose and Dockerfiles define image references, including intentionally moving `latest` or `alpine` tags. - Compose, Nginx, and observability configuration define the local deployment scaffold. They do not prove that a remote deployment or production security review occurred. -- docs/ru/ARCHITECTURE.md records product and architecture decisions. docs/en/ARCHITECTURE.md is its maintained English counterpart. These documents include planned behavior and must label it as planned. +- docs/ru/ARCHITECTURE.md explains the architecture and current service boundaries. docs/en/ARCHITECTURE.md is its maintained English counterpart. Any planned behavior must be labeled as planned. - README.md is the primary Russian entry point; README.en.md is its maintained English counterpart. Neither replaces service guides or contracts. When sources disagree, do not resolve the conflict by file age alone. State what the code currently does, what the design asks for, and which source needs correction. Ask for a decision only when the conflict blocks work within the authorized scope. diff --git a/.agents/standards/backend.md b/.agents/standards/backend.md index eed1ea2..9e77597 100644 --- a/.agents/standards/backend.md +++ b/.agents/standards/backend.md @@ -27,8 +27,8 @@ Use PostgreSQL through the repository's pgx and sqlc boundary. Schema changes ar Prefer the selected wahrwelt-kit packages only where they provide a useful technical boundary and have a pinned, verified version. Libraries such as logging, HTTP, metrics, and PostgreSQL helpers do not own product behavior. Do not add unused JWT, WebSocket, or other framework dependencies. -Redis belongs behind the outbound cache port and its secondary adapter. Bootstrap owns its client lifecycle. Redis, PostgreSQL, and the SeaweedFS bucket are required for readiness. Set cache entries with a positive TTL; future product consumers must tolerate misses, eviction, and restart. Do not treat cache entries as authoritative product records or add product caching without defining ownership and invalidation. +Redis belongs behind the outbound cache port and its secondary adapter. Bootstrap owns its client lifecycle. Redis, PostgreSQL, and the SeaweedFS bucket are required for readiness. Set cache entries with a positive TTL; consumers must tolerate misses, eviction, and restart. Do not treat cache entries as authoritative product records or add product caching without defining ownership and invalidation. SeaweedFS belongs behind the outbound ObjectStorage port and the seaweedfs secondary adapter. Keep AWS SDK and S3 types inside that adapter. Bootstrap owns client resources; HeadBucket checks readiness without creating the bucket. Stream object content and close Get response bodies. Product upload/download authorization, content limits, and retention rules must be defined before exposing file operations. -Current code is an operational scaffold. Do not describe the health handler, database ping, or wiring as account, assessment, matching, or invitation behavior. +Describe implemented behavior from the current usecases, routes, and tests. Health checks and dependency wiring alone do not establish a working product flow. diff --git a/.agents/standards/contracts.md b/.agents/standards/contracts.md index 44f85cd..15beea3 100644 --- a/.agents/standards/contracts.md +++ b/.agents/standards/contracts.md @@ -5,10 +5,11 @@ The repository has separate public and internal OpenAPI contracts: - api/core/openapi.yml describes browser-to-Go operations. - api/ml/openapi.yml describes internal Go-to-ML operations. - api/runner/openapi.yml describes internal operations between Go and the code runner. +- api/labd/openapi.yml describes internal lab provisioner operations. Edit the split source files referenced by these roots. Use the API Makefile to merge schemas, bundle, and lint every specification. Do not hand-edit bundled files. -The selected Go server generator is ogen. The generated Go handler is mounted under chi. Orval generates the TypeScript client and related frontend artifacts. The Go ML client is configured in backend/codegen/ogen-ml.yml and generated into backend/internal/adapter/secondary/ml/api/. The Go code runner client is configured in backend/codegen/ogen-code-runner.yml and generated into backend/internal/adapter/secondary/code_runner/api/. datamodel-code-generator uses ml/codegen/pyproject.toml to generate Pydantic v2 models in ml/src/lincodex_ml/api/models.py from the ML bundle. There are three code generation unit directories: backend/codegen/, frontend/codegen/, and ml/codegen/. Each consumer owns the configuration for its generated code; contract sources remain shared under api/. +ogen generates Go servers and clients; chi mounts the backend HTTP handler. Orval generates frontend clients, hooks, schemas, and mocks. datamodel-code-generator generates ML Pydantic v2 models. Each consumer keeps configuration in its own codegen/ directory: backend, frontend, ml, runner, or labd. Backend client settings are ogen-ml.yml, ogen-code-runner.yml, and ogen-labd.yml; their output stays in the corresponding secondary adapter's api/ directory. Contract sources remain shared under api/. OpenAPI 3.2.0 is the target contract version. Verify only the feature subset used by this repository through the pinned bundler, linter, ogen, Go runtime path, Orval, Python Pydantic models, and documentation pipeline. A passing fixture does not establish full support for every OpenAPI 3.2 feature. Record the exact checks run. diff --git a/.agents/standards/database.md b/.agents/standards/database.md index 0e2a8cc..4ea7974 100644 --- a/.agents/standards/database.md +++ b/.agents/standards/database.md @@ -1,6 +1,6 @@ # Database standard -PostgreSQL is the planned system of record for product data and future background jobs. The current schema contains only what the technical scaffold needs. +PostgreSQL is the system of record for product data and durable jobs. Use the migrations and queries to establish the current schema. Put schema changes in ordered backend/db/migrations/ files and queries in backend/db/queries/. sqlc output is derived. Never edit generated SQL models or query code by hand. diff --git a/.agents/standards/frontend.md b/.agents/standards/frontend.md index 7988bdc..58f9714 100644 --- a/.agents/standards/frontend.md +++ b/.agents/standards/frontend.md @@ -4,14 +4,14 @@ The frontend is a React single-page application built with Vite, TypeScript, and When changing the frontend toolchain or dependencies, select current stable releases and commit the matching runtime declarations, package manifest, and lockfile updates. Do not add prereleases unless the task explicitly calls for them. Keep the lockfile so installs remain repeatable after selecting the stable release. -Use FSD boundaries when product features are added: app composes pages, widgets, features, entities, and shared code. Higher layers can import lower layers; shared code must not depend on product entities. Keep transport DTOs separate from UI models. +Use FSD boundaries: app composes pages, widgets, features, entities, and shared code. Higher layers can import lower layers; shared code must not depend on product entities. Keep transport DTOs separate from UI models. Use the generated Orval client as the contract-derived transport surface. Put shared fetch behavior in the existing API client. Do not hand-edit generated files. Keep the API prefix in one layer so it is not duplicated. Model server data in the selected query library and form drafts in form state. Avoid adding a second store for data already owned by the server cache. Show loading, empty, error, retry, and forbidden states as product flows are implemented. -MSW fixtures are test inputs. They do not prove that a backend workflow exists. The current interface is a scaffold: a React Router data router with public routes and separate candidate and employer cabinet shells, shared UI tokens, and primitives for loading, empty, error, forbidden, and saving states. The sign-in, registration, email confirmation, support, and all cabinet screens are placeholders; business screens are later tasks, so do not document candidate or employer workflows as implemented. /status is a technical API liveness page, not a product readiness indicator. +MSW fixtures are test inputs, not evidence of a backend workflow. Check current route and feature implementations before describing a screen as available. Protected cabinet routes restore the server session through SessionGate. /status checks API liveness, not product readiness. -Vitest runs in the Node environment without a DOM. Component and route tests check rendered markup and query behavior; clicks, keyboard focus, and layout are verified manually in a browser until the planned Playwright suite exists. +Vitest runs in the Node environment without a DOM. Component and route tests check rendered markup and query behavior. Use the existing Playwright suite through make -C deploy test-e2e for browser interactions against an isolated local stack; inspect its selected scenarios and skips before claiming coverage. All source comments are in English. User-facing interface copy can be localized. diff --git a/.agents/standards/infrastructure.md b/.agents/standards/infrastructure.md index 4860eb1..9db77f9 100644 --- a/.agents/standards/infrastructure.md +++ b/.agents/standards/infrastructure.md @@ -1,12 +1,12 @@ # Infrastructure standard -The local scaffold uses three independent Compose projects: core application, ML, and monitoring. Starting the core project does not start monitoring or ML. +Core application, ML, and monitoring use separate Compose projects. Start core first: ML and monitoring join its network. Starting core does not start either project. The code runner and LXD lab provisioner have separate host setup under deploy/labs/. The runner development container uses deploy/docker/docker-compose.runner.dev.yml. Upstream container images use the requested moving `latest` or `alpine` tags where the image publishes them. These tags can change; read the current Compose and Dockerfile references instead of recording an old component version. Keep Go at exact version 1.26.9 in `go.mod`, toolchain declarations, and the backend build image. Application dependency lockfiles remain checked in and should not be removed when image tags float. The core frontend container serves static assets with Nginx and proxies /api to Go. The default host binding is loopback at port 8080. This scaffold does not terminate production TLS. Grafana is also bound to loopback at port 3000. -The ML Compose file binds to 127.0.0.1:8000 by default. A remote ML host needs an explicit private bind address, restricted firewall rules, and a deliberate scrape target. Leave ML_METRICS_TARGET empty when Prometheus must not scrape a remote ML host. +The ML Compose file binds to 127.0.0.1:8000 by default and requires a shared ML_SERVICE_TOKEN. A remote ML host needs an explicit private bind address and restricted firewall rules. Leave ML_METRICS_TARGET empty when no ML scrape is configured; a nonempty target also needs bearer authentication in Prometheus because ML protects /metrics. Start the core project before monitoring because monitoring joins its Docker network. The monitoring Compose project collects only the explicitly configured core services. Do not expose PostgreSQL, Redis, SeaweedFS, Kafka, backend metrics, Prometheus, Loki, exporters, or the Docker socket proxy publicly. diff --git a/.agents/standards/ml.md b/.agents/standards/ml.md index 0c74bbc..5ac23fd 100644 --- a/.agents/standards/ml.md +++ b/.agents/standards/ml.md @@ -8,7 +8,7 @@ Use make -C ml generate to bundle the contract and generate models. The root gen Readiness must describe whether the required model or inference runtime is available. Return not-ready while it is unavailable. Do not invent a successful result or label a fixture as a model response. -When inference is added, validate structured output, bound input and output size, apply timeouts, and preserve model and schema versions. Avoid logging resume text, contact details, credentials, or full prompts. Treat document contents and model output as untrusted data. +Validate inference output, bound input and output size, apply timeouts, and preserve model and schema versions. Avoid logging resume text, contact details, credentials, or full prompts. Treat document contents and model output as untrusted data. Use uv with the checked-in lockfile. Keep ordinary lint, type checks, and tests independent of external model downloads and GPU access. Model quality evaluation is a separate, reproducible task with documented data and limits. diff --git a/.agents/standards/security.md b/.agents/standards/security.md index fb57f9e..ed460f7 100644 --- a/.agents/standards/security.md +++ b/.agents/standards/security.md @@ -10,6 +10,6 @@ Treat resumes, API payloads, model output, repository documents, dependencies, t Keep health routes minimal. Keep /metrics and infrastructure administration surfaces on internal interfaces. Review bind addresses and network access whenever a Compose or Nginx change affects reachability. -Architecture notes about privacy controls are requirements for future product behavior. They are not proof of legal compliance, completed authorization, or a security audit. +Verify privacy controls in the current code and access tests. Architecture notes alone are not proof of enforcement, legal compliance, or a security audit. Run configured security checks through `security/Makefile`. Trivy HIGH/CRITICAL findings, including unfixed vulnerabilities, block validation; Gitleaks, govulncheck, configured Semgrep findings, and scanner errors also fail their checks. Scan both repository inputs and built images, and require complete Git history for secret scanning. Keep reports local and redact secret values. Any exception must be specific, reviewed, and record a reason, owner, and expiry; review expiry explicitly where the tool does not enforce it. Do not add broad exclusions to make a scan pass. These checks complement gosec and do not replace authorization tests or a security audit. diff --git a/.agents/standards/testing.md b/.agents/standards/testing.md index f1262ae..f8ddee0 100644 --- a/.agents/standards/testing.md +++ b/.agents/standards/testing.md @@ -6,7 +6,7 @@ Use unit tests for domain and application behavior, component tests for frontend Contract changes need bundle and lint checks, regeneration of affected consumers, and generated drift checks. Infrastructure changes need rendered Compose configuration and the validator for each changed monitoring or deployment file. -The technical deployment smoke checks service routes and infrastructure readiness. It does not validate a candidate or employer workflow. The deploy test-e2e target runs the Playwright suite against an isolated throwaway stack; it currently covers only the SPA, API health, and error routes, so a pass does not validate a business workflow. +The technical deployment smoke checks service routes and infrastructure readiness. The deploy test-e2e target runs Playwright against an isolated throwaway stack, including candidate and employer scenarios in frontend/e2e/. Report which scenarios ran, failed, or were skipped; a smoke pass alone does not validate a business workflow. Do not report ranking accuracy, assessment validity, production latency, load capacity, privacy correctness, or model quality without the corresponding measured test and its dataset, environment, and limits. Planned targets and synthetic examples are not results. diff --git a/.agents/workflows/development.md b/.agents/workflows/development.md index 7d4a7c0..e72b15b 100644 --- a/.agents/workflows/development.md +++ b/.agents/workflows/development.md @@ -10,4 +10,6 @@ Use Make targets instead of maintaining duplicate shell command lists. Generate 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 READMEs short: purpose, essential commands, and links to the relevant guide. Document current behavior from code and configuration. Update existing sections instead of appending implementation diaries, old test results, or copies of API schemas. Preserve required setup steps and operational limits in both languages. + 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/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.en.md b/README.en.md index c6e4465..eabe0c7 100644 --- a/README.en.md +++ b/README.en.md @@ -2,61 +2,61 @@ [Русский](README.md) | English -Lincodex is a platform that helps employers find IT specialists by confirmed skills. The current MVP consists of a Go backend, a React interface, PostgreSQL, Redis, SeaweedFS, and Kafka in Docker Compose, a separate ML service without a model, and optional monitoring. +Lincodex helps employers find IT specialists by verified skills. Candidates complete a profile, take assessments, and control their card's visibility. Employers describe hiring needs, search for candidates, and send invitations; contact details become available after the candidate consents. -Implemented: registration with email confirmation and sign-in; the candidate cabinet with consents, a manual profile without a resume or FSP ID, the questionnaire, an express run without a grade, the full test, results, skill evidence, and privacy settings; the employer cabinet with organizations, the company profile, needs, and deterministic candidate search without ML; support cases and the notification inbox. Invitations work from a draft to the candidate's answer: the organization sends an invitation from a search result, the candidate accepts it with the consent C4 or declines, and after the acceptance the organization reads the disclosed contacts. Planned: withdrawing invitations, salary raise, password reset, resumes and PDF, FSP integration, ML inference, and calibrated grades. The [MVP quick start](docs/en/DEPLOY.md#running-the-mvp-quick-start) lists the details and limits. +The core stack is Go + chi, React + TypeScript, PostgreSQL, Redis, SeaweedFS, and Kafka. ML, code execution, lab environments, and monitoring run separately. Demonstration categories do not establish assessment validity for real candidates. -## Start locally +## Quick start -You need Docker with the Compose plugin, GNU make, python3, and openssl; no GPU, external inference key, or FSP access is needed. Copy .env.example to .env, replace every `replace-this-...` value, set `IDENTITY_KEY_SECRET` to the output of `openssl rand -base64 48`, then run: +Install Docker with the Compose plugin, GNU make, Python 3, and openssl. - make -C deploy config - make -C deploy up +1. Copy `.env.example` to `.env` and replace the `replace-this-...` values. +2. Generate `IDENTITY_KEY_SECRET` with `openssl rand -base64 48`. +3. Build and start the core stack: -Open http://localhost:8080 (use `localhost`: the address must match `APP_PUBLIC_URL`). The port is bound to loopback and does not provide production TLS. The default `EMAIL_PROVIDER=disabled` sends no mail, so a new account cannot be confirmed. For real mail set `EMAIL_PROVIDER=resend` and a Resend key in the server environment. `make -C deploy smoke` runs a separate throwaway technical check. +```sh +make -C deploy config +make -C deploy build +make -C deploy up +``` -To start the separate monitoring stack after the core services: +Open http://localhost:8080. The address must match `APP_PUBLIC_URL`. The `config` check uses the example environment; it does not validate your `.env` values. - make -C deploy monitoring-up +Mail defaults to `EMAIL_PROVIDER=disabled`, so new accounts cannot verify their email. Configure Resend for real delivery using the [deployment guide](docs/en/DEPLOYMENT.md). `make -C deploy down` stops the services and keeps their data. -Grafana is available at http://127.0.0.1:3000 on the local machine. See the deployment guide before exposing any service to another host. +## Demonstration -## Demo stand +A separate stand provides synthetic data and prepared accounts: -To show the product, use the isolated stand with synthetic data and prepared candidate and employer accounts that need no mail: +```sh +make -C deploy demo-seed DEMO_MODE=isolated +``` - make -C deploy demo-seed DEMO_MODE=isolated +Open http://localhost:8090 and follow `/demo`. The command prints account names; `DEMO_ACCOUNT_PASSWORD` in the demo settings supplies their password. These accounts do not require email delivery. See [DEPLOYMENT.md](docs/en/DEPLOYMENT.md) for details and cleanup. -The stand opens at http://localhost:8090. The jury guide, an eight-minute route across two roles, is at http://localhost:8090/demo. The command prints the logins; the password is `DEMO_ACCOUNT_PASSWORD` from `deploy/demo/demo.env.example` (a published demo credential, not a secret). The [MVP quick start](docs/en/DEPLOY.md#running-the-mvp-quick-start) describes the demonstration route, the stand parameters, the mail, FSP, and ML modes, and how to stop the stands. +Start monitoring separately with `make -C deploy monitoring-up`. Grafana defaults to http://127.0.0.1:3000. -## Development - -The root Makefile provides install, generate, fmt, fmt-check, lint, test, check, verify, and docs-check targets. Run make help for the current command list. The development and testing guides describe the service-specific commands and what the current checks cover. - -## Documentation - -Short directory guides: +## Directories | Directory | Purpose | | --- | --- | | [api/](api/README.en.md) | Shared OpenAPI contracts | -| [backend/](backend/README.en.md) | Main Go service | +| [backend/](backend/README.en.md) | Core Go service | | [frontend/](frontend/README.en.md) | React and TypeScript interface | -| [ml/](ml/README.en.md) | Separate Python service for ML | -| [runner/](runner/README.en.md) | Go code runner with nsjail | -| [deploy/](deploy/README.en.md) | Docker Compose, Nginx, and service startup | +| [ml/](ml/README.en.md) | ML API and models | +| [runner/](runner/README.en.md) | Isolated code execution | +| [labd/](labd/README.en.md) | Lab environment provisioning | +| [deploy/](deploy/README.en.md) | Compose, Nginx, and deployment | | [observability/](observability/README.en.md) | Metrics, logs, and dashboards | -| [security/](security/README.en.md) | Security scanners and rules | -| [docs/](docs/README.en.md) | Detailed Russian and English guides | -| [requirements/](requirements/README.en.md) | Original specification and brand assets | -| [scripts/](scripts/README.en.md) | Shared code generation and validation scripts | -| [.github/](.github/workflows/) | GitHub Actions workflows | -| [.agents/](.agents/README.en.md) | Agent rules | +| [security/](security/README.en.md) | Security checks | +| [docs/](docs/README.en.md) | Russian and English guides | +| [requirements/](requirements/README.en.md) | Specification and brand assets | +| [scripts/](scripts/README.en.md) | Shared scripts and checks | +| [.github/](.github/workflows/) | GitHub Actions | +| [.agents/](.agents/README.en.md) | Repository working rules | -- Source materials: [specification](requirements/specification.pdf), [brandbook](requirements/brandbook/). -- Russian: [architecture](docs/ru/ARCHITECTURE.md), [development](docs/ru/DEVELOPMENT.md), [deployment](docs/ru/DEPLOY.md), [testing](docs/ru/TESTING.md), [security](docs/ru/SECURITY.md), [MVP package](docs/ru/MVP.md) -- English: [architecture](docs/en/ARCHITECTURE.md), [development](docs/en/DEVELOPMENT.md), [deployment](docs/en/DEPLOY.md), [testing](docs/en/TESTING.md), [security](docs/en/SECURITY.md), [MVP package](docs/en/MVP.md) +Development commands: `make help`. Start with [DEVELOPMENT.md](docs/en/DEVELOPMENT.md); see [TESTING.md](docs/en/TESTING.md) for checks and [ARCHITECTURE.md](docs/en/ARCHITECTURE.md) for the design. ## License -No project-wide license has been assigned in this repository. Check the license terms of each dependency and container image before redistribution. +Project code is distributed under [GPL-3.0-only](LICENSE). Dependencies and source materials may have their own terms of use. diff --git a/README.md b/README.md index 71e42d9..90f5240 100644 --- a/README.md +++ b/README.md @@ -2,67 +2,61 @@ Русский | [English](README.en.md) -Lincodex - платформа, на которой работодатели находят IT-специалистов по подтвержденным навыкам. Текущий MVP состоит из Go backend, React-интерфейса, PostgreSQL, Redis, SeaweedFS и Kafka в Docker Compose, отдельного ML-сервиса без модели и отдельно запускаемого мониторинга. +Lincodex помогает работодателям находить IT-специалистов по подтвержденным навыкам. Кандидат заполняет профиль, проходит оценку и управляет видимостью карточки. Работодатель описывает потребность, ищет кандидатов и отправляет приглашения; контакты открываются после согласия кандидата. -Реализовано: регистрация с подтверждением email и вход; кабинет кандидата с согласиями, ручным профилем без резюме и ФСП ID, анкетой, экспресс-запуском без грейда, полным тестом, результатами, доказательствами навыков и настройками приватности; кабинет работодателя с организациями, профилем компании, потребностями и детерминированным поиском кандидатов без ML; обращения в поддержку и inbox уведомлений. Приглашения работают от черновика до ответа: организация отправляет приглашение из результата поиска, кандидат принимает его с согласием C4 или отказывается, после принятия организация читает переданные контакты. Запланированы отзыв приглашения, повышение зарплаты, сброс пароля, резюме и PDF, интеграция с ФСП, ML inference и откалиброванные грейды. Полный перечень и границы описаны в [быстром старте MVP](docs/ru/DEPLOY.md#запуск-mvp-быстрый-старт). +Основной стек: Go + chi, React + TypeScript, PostgreSQL, Redis, SeaweedFS и Kafka. ML, исполнитель кода, лабораторные окружения и мониторинг подключаются отдельно. Демонстрационные категории не означают, что оценка уже откалибрована на реальных кандидатах. -## Локальный запуск +## Быстрый старт -Нужны Docker с Compose plugin, GNU make, python3 и openssl; GPU, ключи внешнего inference и доступ к ФСП не нужны. Скопируйте `.env.example` в `.env`, замените все значения `replace-this-...`, впишите в `IDENTITY_KEY_SECRET` вывод `openssl rand -base64 48` и выполните: +Нужны Docker с Compose plugin, GNU make, Python 3 и openssl. + +1. Скопируйте `.env.example` в `.env` и замените значения `replace-this-...`. +2. Для `IDENTITY_KEY_SECRET` создайте секрет: `openssl rand -base64 48`. +3. Соберите и запустите основной стек: ```sh make -C deploy config +make -C deploy build make -C deploy up ``` -Откройте http://localhost:8080 (именно `localhost`: адрес должен совпадать с `APP_PUBLIC_URL`). Порт привязан к loopback-интерфейсу; TLS для продакшена не настроен. По умолчанию `EMAIL_PROVIDER=disabled`: письма не отправляются, поэтому новый аккаунт нельзя подтвердить. Для настоящих писем задайте `EMAIL_PROVIDER=resend` и ключ Resend в окружении сервера. `make -C deploy smoke` запускает отдельную одноразовую техническую проверку. +Откройте http://localhost:8080. Адрес должен совпадать с `APP_PUBLIC_URL`. Проверка `config` использует пример окружения; она не подтверждает правильность вашего `.env`. -Мониторинг запускается отдельно, после основных сервисов: +По умолчанию `EMAIL_PROVIDER=disabled`: новый аккаунт нельзя подтвердить без почты. Для реальной отправки настройте Resend по [руководству развертывания](docs/ru/DEPLOYMENT.md). Команда `make -C deploy down` останавливает сервисы, сохраняя данные. -```sh -make -C deploy monitoring-up -``` +## Демонстрация -Grafana доступна на локальной машине по адресу http://127.0.0.1:3000. Перед открытием доступа с других хостов прочитайте руководство по развертыванию. - -## Демонстрационный стенд - -Для показа продукта используйте изолированный стенд с синтетическими данными и подготовленными аккаунтами кандидатов и работодателей, которым почта не нужна: +Отдельный стенд содержит синтетические данные и готовые аккаунты: ```sh make -C deploy demo-seed DEMO_MODE=isolated ``` -Стенд открывается на http://localhost:8090. Гид для жюри с маршрутом на восемь минут двумя ролями открыт на http://localhost:8090/demo. Логины печатает сама команда, пароль - `DEMO_ACCOUNT_PASSWORD` из `deploy/demo/demo.env.example` (опубликованные демонстрационные учетные данные, а не секрет). Маршрут демонстрации, параметры стендов, режимы почты, ФСП и ML и остановка описаны в [быстром старте MVP](docs/ru/DEPLOY.md#запуск-mvp-быстрый-старт). +Адрес стенда: http://localhost:8090, маршрут демонстрации: `/demo`. Команда выводит логины; пароль задает `DEMO_ACCOUNT_PASSWORD` в настройках демонстрации. Эти аккаунты не требуют отправки писем. Подробности и очистка стенда описаны в [DEPLOYMENT.md](docs/ru/DEPLOYMENT.md). -## Разработка +Мониторинг запускается отдельно командой `make -C deploy monitoring-up`. Grafana по умолчанию доступна на http://127.0.0.1:3000. -Корневой Makefile содержит цели `install`, `generate`, `fmt`, `fmt-check`, `lint`, `test`, `check`, `verify` и `docs-check`. Актуальный список команд доступен через `make help`. Команды отдельных сервисов и границы текущих проверок описаны в руководствах по разработке и тестированию. - -## Документация - -Краткие описания каталогов: +## Каталоги | Каталог | Назначение | | --- | --- | | [api/](api/README.md) | Общие OpenAPI-контракты | -| [backend/](backend/README.md) | Основной сервис на Go | -| [frontend/](frontend/README.md) | Интерфейс на React и TypeScript | -| [ml/](ml/README.md) | Отдельный Python-сервис для ML | -| [runner/](runner/README.md) | Исполнитель кода на Go с nsjail | -| [deploy/](deploy/README.md) | Docker Compose, Nginx и запуск сервисов | +| [backend/](backend/README.md) | Основной Go-сервис | +| [frontend/](frontend/README.md) | Интерфейс React и TypeScript | +| [ml/](ml/README.md) | ML API и модели | +| [runner/](runner/README.md) | Изолированное выполнение кода | +| [labd/](labd/README.md) | Подготовка лабораторных окружений | +| [deploy/](deploy/README.md) | Compose, Nginx и развертывание | | [observability/](observability/README.md) | Метрики, логи и дашборды | -| [security/](security/README.md) | Сканеры и правила безопасности | -| [docs/](docs/README.md) | Подробные руководства на русском и английском | -| [requirements/](requirements/README.md) | Исходное ТЗ и брендбук | -| [scripts/](scripts/README.md) | Общие скрипты кодогенерации и проверок | -| [.github/](.github/workflows/) | Workflow GitHub Actions | -| [.agents/](.agents/README.md) | Правила работы агентов | +| [security/](security/README.md) | Проверки безопасности | +| [docs/](docs/README.md) | Руководства на русском и английском | +| [requirements/](requirements/README.md) | ТЗ и брендбук | +| [scripts/](scripts/README.md) | Общие скрипты и проверки | +| [.github/](.github/workflows/) | GitHub Actions | +| [.agents/](.agents/README.md) | Правила работы с репозиторием | -- Исходные материалы: [ТЗ](requirements/specification.pdf), [брендбук](requirements/brandbook/). -- На русском: [архитектура](docs/ru/ARCHITECTURE.md), [разработка](docs/ru/DEVELOPMENT.md), [развертывание](docs/ru/DEPLOY.md), [тестирование](docs/ru/TESTING.md), [безопасность](docs/ru/SECURITY.md), [пакет сдачи MVP](docs/ru/MVP.md). -- На английском: [архитектура](docs/en/ARCHITECTURE.md), [разработка](docs/en/DEVELOPMENT.md), [развертывание](docs/en/DEPLOY.md), [тестирование](docs/en/TESTING.md), [безопасность](docs/en/SECURITY.md), [пакет сдачи MVP](docs/en/MVP.md). +Команды разработки: `make help`. Начните с [DEVELOPMENT.md](docs/ru/DEVELOPMENT.md); проверки описаны в [TESTING.md](docs/ru/TESTING.md), архитектура - в [ARCHITECTURE.md](docs/ru/ARCHITECTURE.md). ## Лицензия -Общая лицензия проекта пока не определена. Перед распространением проверьте условия лицензий каждой зависимости и образа контейнера. +Код проекта распространяется на условиях [GPL-3.0-only](LICENSE). Зависимости и исходные материалы могут иметь собственные условия использования. diff --git a/api/README.en.md b/api/README.en.md index d0f84e7..2cbb3a3 100644 --- a/api/README.en.md +++ b/api/README.en.md @@ -2,827 +2,57 @@ [Русский](README.md) | English -Shared OpenAPI contracts for Go, the frontend, and ML. Contract changes come first; consumers then generate their types, server code, and clients from them. +OpenAPI 3.2.0 is the shared source for HTTP contracts. Change the specification first, then generate server adapters, clients, and models. -- `core/` defines the main backend's public API. -- `ml/` defines the ML service's internal HTTP API. -- `runner/` defines the internal HTTP API of the own code runner. -- `testdata/` contains a specification for checking tool compatibility with OpenAPI 3.2.0. +## Structure -Routes live in `routes/` and schemas in `components/`. The `openapi.bundle.yml` files are built automatically. Generator configuration lives in `backend/codegen/`, `frontend/codegen/`, and `ml/codegen/`; the code runner server code is generated from `runner/codegen/`. +| Directory | API | +| --- | --- | +| [core/](core/openapi.yml) | Public Go API under `/api/v1` | +| [ml/](ml/openapi.yml) | Internal ML API | +| [runner/](runner/openapi.yml) | Code execution | +| [labd/](labd/openapi.yml) | Lab environment provisioning | +| [testdata/](testdata/openapi-3.2.0.yml) | Generator compatibility fixture | -From the repository root, `make -C api check` checks contracts and `make generate` updates all generated code. +Each contract's `openapi.yml` references `routes/` and `components/`. [merge-schemas.py](../scripts/merge-schemas.py) merges schemas grouped by subject, then Redocly builds `openapi.bundle.yml`. Do not edit derived files by hand. + +## Generation + +Run these commands from the repository root: + +```sh +make -C api install +make -C api check +make generate +make check-generated +``` + +`check` builds and validates contracts. `generate` updates every consumer. `check-generated` detects differences from committed output; it does not run generation itself. + +| Consumer | Generator and configuration | +| --- | --- | +| Go backend | ogen, [backend/codegen/](../backend/codegen/) | +| Go runner and labd | ogen, each service's `codegen/` directory | +| React | Orval: client, query hooks, Zod schemas, and MSW; [frontend/codegen/](../frontend/codegen/) | +| Python ML | datamodel-code-generator: Pydantic; [ml/codegen/](../ml/codegen/) | + +`make -C api check-toolchain` checks the OpenAPI 3.2 features in a dedicated fixture. It verifies the current toolchain, not every feature of the standard. + +Compare the public contract with an existing Git ref using `make -C api check-compat API_BASE_REF=`. ## Contract conventions -`api/core/` fixes these conventions as reusable components in `openapi.yml` and the files under `components/`: schemas in `components/schemas/*_schemas.yml`, parameters in `parameters.yml`, response headers in `headers.yml`, responses in `responses.yml`, and examples in `examples.yml`. Operations reference them as they are added. Currently implemented: problem responses for errors of the Go public API and the ML service. Idempotency-Key storage, If-Match checks, and pagination are planned behavior for business operations; the declared `RegisterAccount` operation, the assessment commands, `CreateOrganization`, `CreateOrganizationNeed`, `CreateMySupportCase`, and the invitation commands require Idempotency-Key, but no operation stores keys yet. +- Errors: RFC 9457, `application/problem+json`, stable `code`, and safe messages. The `Problem` schema defines the response fields. +- Sessions: an HttpOnly cookie; mutating session requests also send `X-CSRF-Token`. The origin must match the application configuration. +- Send `Idempotency-Key` where the operation requires it. Reuse the key when retrying the same action; use a new key for different content. +- Concurrent updates use `If-Match` or `expected_version` as specified by the operation. On conflict, reload server state and preserve the user's draft. +- Lists use bounded cursor pagination. Identifiers are UUIDs and timestamps are UTC date-times. An absent field may differ from `null`. +- Read exact codes, limits, required headers, and examples from each operation and its shared components. -### Errors +## Boundaries -Every error is an RFC 9457 problem with the `application/problem+json` media type and the `Problem` schema. Required fields are `type` (`urn:lincodex:problem:`), `title`, `status`, and `code`; optional ones are `detail`, `instance`, `trace_id` (equal to the `X-Request-ID` response header), and `errors`. Clients branch on `code`. Titles and details are fixed per code and never contain internal error text, stack traces, credentials, contact data, or submitted values. +An operation in the specification does not prove its handler is complete. Check `backend/internal/adapter/primary/http/v1/` and its tests. An unimplemented operation can return `501 not_implemented`. -| Code | Status | Meaning | -| --- | --- | --- | -| `validation_failed` | 400 | Parameters or body do not match the contract, or the body violates a domain rule; `errors` lists the fields | -| `verification_token_invalid` | 400 | The email verification token is unknown, already used, or replaced | -| `verification_token_expired` | 400 | The email verification token is past its lifetime | -| `unauthenticated` | 401 | No valid session | -| `invalid_credentials` | 401 | Login failed; an unknown email and a wrong password are not distinguished | -| `forbidden` | 403 | The caller may not perform the operation | -| `email_not_verified` | 403 | Correct credentials, but the email is not verified | -| `csrf_check_failed` | 403 | Missing or wrong `X-CSRF-Token`, or a disallowed `Origin` | -| `not_found` | 404 | Unknown route, or an object that does not exist or is not visible | -| `method_not_allowed` | 405 | Unsupported method; see `Allow` | -| `idempotency_in_progress` | 409 | A request with the same Idempotency-Key is still running | -| `state_conflict` | 409 | The operation is not allowed in the current state of the resource | -| `version_conflict` | 412 | If-Match, or a body `expected_version`, does not match the current version | -| `payload_too_large` | 413 | The body exceeds the operation limit | -| `unsupported_media_type` | 415 | The request Content-Type is not accepted | -| `idempotency_key_reused` | 422 | The Idempotency-Key was used with a different request | -| `precondition_required` | 428 | The operation requires If-Match | -| `rate_limited` | 429 | Too many requests; see `Retry-After` | -| `internal` | 500 | Unexpected server error | -| `not_implemented` | 501 | The operation is in the contract but not implemented | +Internal ML, runner, and labd APIs are not browser entry points. The public health route is `/api/v1/healthz`; service guides cover operational `/healthz`, `/readyz`, and metrics. -Request validation uses 400 rather than 422. The generated ogen server reports malformed and schema-invalid parameters and bodies through the same decoding errors, and for parameters it does not separate syntax from schema violations; one status keeps client handling uniform. 422 then stays free for Idempotency-Key reuse, as the IETF Idempotency-Key header draft recommends. Domain rules on the body, such as `salary_from <= salary_to`, also answer 400 `validation_failed` with body pointers to the fields involved. Each `errors` item has `in` (`body`, `query`, `path`, `header`, `cookie`), `pointer` (JSON Pointer: `/salary_from` in the body, an empty string for the whole body, `/limit` for a parameter), `code` (`required` or `invalid`; clients tolerate new values), and a fixed `message`. Body pointers follow the rules in Body pointers below. A body cut by an `http.MaxBytesReader` limit answers 413 `payload_too_large`. - -`state_conflict` covers business state conflicts, such as accepting an invitation that was already withdrawn. `idempotency_in_progress` is reserved for concurrent retries; the reusable responses are `StateConflict` and `IdempotencyInProgress`. - -Every operation declares `default: $ref: ../components/responses.yml#/Problem`; ogen then generates a single error type. An operation adds a specific response (for example `PreconditionFailed`) when clients need it in the generated types. In the Go API, unknown paths under `/api`, including paths outside `/api/v1`, answer 404 `not_found`, and a panic in an operation answers 500 `internal`; only the panic type and stack are logged. - -Both verification token codes use 400 because the token is request content, not the target resource: 404 and 410 describe the URI, 409 a resource state, and 422 stays reserved for Idempotency-Key reuse. A malformed token fails schema validation and answers 400 `validation_failed` with the pointer `/token`. `invalid_credentials` and `unauthenticated` share 401 but mean a failed login and a missing session respectively. `email_not_verified` is returned only after the password matched, so it tells the verification state only to someone who already proved the password. - -#### Body pointers - -The generated decoder records no path of its own. It wraps the error of each object field as `decode field ""` with go-faster/errors, and `problem.Responder` rebuilds the pointer from those wrappers, reading each link through the typed `errors.Formatter` instead of the joined error text. The rules: - -- A missing required field answers `required` with its own pointer at any depth, for example `/terms/communication_method` or `/terms/salary/tax_basis`. -- A value that fails during decoding, such as a wrong JSON type, a malformed UUID, or an ambiguous `oneOf` value, answers `invalid` with the pointer of that value, for example `/grade` for a bare grade or `/object/id`. -- A value that decodes but breaks a schema rule, such as a length, a pattern, a multiple of 1000, or an enum, answers `invalid` with its full pointer, including array indices, for example `/required_skills/2/status`; this check runs after decoding. -- An unknown property answers `invalid` with the pointer of the object that contains it, for example `/terms/salary` for a `candidate_minimum` inside the range; the property name is not echoed. -- A failure inside an array element during decoding answers `invalid` with the pointer of the array, for example `/required_skills`, because jx reports no element index. -- The whole-body pointer `""` remains only for a malformed JSON document, a missing body, an unknown top-level property, an unknown or missing discriminator of a top-level `oneOf`, and an error chain that the responder does not recognize, which falls back safely to the whole body. - -`responder_test.go` covers a nested object, an array element, a `oneOf` variant field, a top-level field, and an unrecognized chain; the router tests of every contract pin the pointers through the generated server. - -### Retries and Idempotency-Key - -A mutating command declares the `IdempotencyKey` parameter. The client generates a key (a UUID v4 is recommended) and sends it in the `Idempotency-Key` header without quotes: 1-255 characters `A-Z a-z 0-9 . _ : -`. The server scopes the key by caller and operation and fingerprints the request by method, path, and body. - -An anonymous operation defines its key scope and fingerprint in its own description; for `RegisterAccount` see the Identity section below. - -Stored for 24 hours and replayed with the same status, headers, and body: the final 2xx outcome and final deterministic 4xx business outcomes of the command, such as 404 `not_found` or 409 `state_conflict`. A replay does not repeat the side effect. - -Not stored, so a retry with the same key is evaluated again: 400 `validation_failed`, 413, and 415 for the request itself; 401 and 403; 409 `idempotency_in_progress`; 412 `version_conflict` and 428 `precondition_required` (nothing changed; read the resource again and retry); 422 `idempotency_key_reused`; 429; and every 5xx. - -The server checks in this order: - -1. Authentication (401), request validation (400, 413, 415), and authorization (403). Nothing is recorded for the key. -2. A stored or running request with the same key and a different fingerprint: 422 `idempotency_key_reused`. This check comes before the in-progress check. -3. A running request with the same key and fingerprint: 409 `idempotency_in_progress`; retry later. -4. A stored outcome with the same key and fingerprint: the outcome is replayed. -5. If-Match (428, 412), then the command itself; a storable outcome is recorded. - -Because the replay check comes before If-Match, a retry of a completed change replays its outcome instead of failing on the version that the change itself advanced. A missing or malformed key returns 400 `validation_failed` with the pointer `/Idempotency-Key`. After 24 hours the key may be accepted as new. - -### Versions: ETag and If-Match - -A response with a versioned resource returns a strong `ETag`, for example `"v7"`. An operation that changes such a resource says in its description that it requires `If-Match` with that value. A missing value returns 428 `precondition_required`; a value that does not equal the current ETag returns 412 `version_conflict` and changes nothing. The parameter is optional in the schema so that a missing header reaches the application, which answers 428. Weak tags, lists, and `*` fail validation with 400. The questionnaire carries its version as `expected_version` in the body instead; see Catalog and questionnaire below. - -### Pagination - -Lists use cursor pagination: `limit` from 1 to 100 (20 by default) and an opaque `cursor` of up to 512 characters `A-Z a-z 0-9 _ -`. The response holds the items in a bounded array and `page` (`PageInfo`) with `has_more` and `next_cursor`, which is null on the last page. A malformed cursor returns 400 `validation_failed`. - -### Time and money - -Timestamps use the `Timestamp` schema: `string`, `format: date-time`, UTC with the `Z` suffix (RFC 3339). Servers always emit UTC. ogen generates `Timestamp` as a named Go type over `time.Time`; call `.UTC()` where a value is converted to it. Money is an integer number of whole rubles (`RubAmount`, int64) with an explicit base: `SalaryRange` requires `salary_from`, `salary_to`, `currency` (`RUB`), `period` (`month`), and `tax_basis` (`net` or `gross`); see Needs below. Invitation terms reuse `SalaryRange` with the same rules. - -### ML service errors - -The ML service answers its errors with the same `Problem` schema. Its `ProblemCode` enum keeps the public identity codes so both contracts share one shape, but the service never returns them. FastAPI request validation answers 400 `validation_failed`. An HTTP exception raised inside the service maps by status: 400, 401, 403, 404, 405, 409 (`state_conflict`), 412, 413, 415, 428, 429, 501, and 503 (`service_unavailable`, while the model is not ready) to their codes, 422 to 400 `validation_failed`, any other 4xx to 400 `validation_failed`, and any other 5xx to 500 `internal`. An unhandled exception answers 500 `internal` inside the application, so Starlette does not re-raise it to uvicorn; only its type is logged. The service also routes the uvicorn loggers through its JSON log format, which keeps only the exception type of a record and never its text or traceback. - -### Code runner contract - -`runner/openapi.yml` describes the internal API of the code runner, which only the Go backend calls. ogen generates the Go client from `backend/codegen/ogen-code-runner.yml` into `backend/internal/adapter/secondary/code_runner/api/`; no use case calls it yet. - -- Transport and sign-in. The runner listens on a private interface of its host over HTTPS (TLS 1.3). Every operation except `/healthz` and `/readyz` requires `Authorization: Bearer `; the token is a shared random secret of at least 32 characters from the deployment secret store. A wrong or missing token answers 401 `unauthenticated`. Plain HTTP is allowed only by an explicit switch of the local dev Compose file. -- Data. `RunRequest` carries only the language, the source code, the limits, and the test groups; each group has a label, a visibility (`public` or `hidden`), a checker kind, and tests with an input and an expected output. It has no candidate, account, attempt, task, or company field; `scripts/test_runner_contract.py` checks this for every request schema, together with `additionalProperties: false` on every request object. -- Idempotency. `PUT /v1/runs/{run_id}` (`SubmitRun`) takes a random UUID from the backend. A new ID with a free slot starts the run and answers 202, the same ID with the same body returns the current state with 200 without running again, and the same ID with a different body answers 422 `idempotency_key_reused`. Bodies are compared by a SHA-256 fingerprint of the decoded request. When every slot is busy or the process is stopping, the answer is 503 `runner_busy` with `Retry-After`; nothing is stored, and the backend keeps the queue. -- Result. `GetRun` returns `state` (`running` or `finished`) and, per group, the outcome `accepted`, `wrong_answer`, `compile_error`, `time_limit_exceeded`, `memory_limit_exceeded`, `output_limit_exceeded`, `runtime_error`, or `infrastructure_failure`, the number of passed tests, the CPU time, and the peak memory. `limit` names the limit that stopped a test (`cpu_time`, `wall_time`, `memory`, `output`, `processes`). Only public tests carry a stderr diagnostic; hidden tests never carry program output. -- Languages: `python3` and `go`. Go is compiled in a separate phase with its own limits; a compile error gives `compile_error` and no test runs. -- A checker is set per group: `exact` (comparison after normalizing CRLF, trailing spaces of lines, and trailing empty lines), `tokens` (token sequences split on ASCII whitespace), `numbers` (like `tokens`, but numbers are equal within `abs_tolerance` or `rel_tolerance`), and `custom` (`program` with the language and source of the task family checker; it runs in nsjail, reads the files input, expected, and actual, and answers with exit status 0 or 1). The server rejects parameters that do not fit the checker kind. -- Errors use the api/core `Problem` shape with a runner-specific `ProblemCode` enum: `validation_failed`, `unauthenticated`, `not_found`, `method_not_allowed`, `payload_too_large`, `unsupported_media_type`, `idempotency_key_reused`, `internal`, and `runner_busy`. `scripts/test_runner_contract.py` checks that the shape matches api/core. - -### Identity: sessions, cookie, and CSRF - -The `identity` tag covers registration, email verification, login, logout, and the current account. All operations are in the contract. `RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, `ConfirmEmailByCode`, `Login`, `GetCurrentSession`, `Logout`, and `GetCurrentAccount` are implemented in the backend. The session boundary authenticates every operation protected by the contract; its principal comes from a verified account and an active PostgreSQL session. Except for identity and the consent operations below, protected business operations currently pass the security boundary and answer 501 `not_implemented` after request validation. Frontend registration and confirmation screens remain placeholders. - -| Method and path | operationId | Security | Success | Specific errors | -| --- | --- | --- | --- | --- | -| `GET /api/v1/identity/consent-texts/{purpose}` | `GetConsentText` | public | 200 `ConsentText` | 400 `validation_failed` | -| `POST /api/v1/identity/registrations` | `RegisterAccount` | public, Idempotency-Key | 202 `IdentityRequestAccepted` | 400 `validation_failed`, 403 `csrf_check_failed`, 409 `idempotency_in_progress`, 422 `idempotency_key_reused`, 429 | -| `POST /api/v1/identity/email-verification-requests` | `ResendEmailVerification` | public | 202 `IdentityRequestAccepted` | 400, 403 `csrf_check_failed`, 429 | -| `POST /api/v1/identity/email-verifications` | `ConfirmEmail` | public | 200 `EmailVerificationResult` | 400 `verification_token_expired`, `verification_token_invalid`, or `validation_failed`; 403 `csrf_check_failed`; 429 | -| `POST /api/v1/identity/email-verifications/code` | `ConfirmEmailByCode` | public | 200 `EmailVerificationResult` | 400 `verification_token_invalid` or `validation_failed`; 403 `csrf_check_failed`; 429 | -| `POST /api/v1/identity/sessions` | `Login` | public | 201 `Session`, `Set-Cookie`, `Cache-Control: no-store` | 400, 401 `invalid_credentials`, 403 `email_not_verified` or `csrf_check_failed`, 429 | -| `GET /api/v1/identity/sessions/current` | `GetCurrentSession` | session | 200 `Session`, `Cache-Control: no-store` | 401 `unauthenticated` | -| `DELETE /api/v1/identity/sessions/current` | `Logout` | session and CSRF | 204, `Set-Cookie` clears the cookie | 401 `unauthenticated` (also clears the cookie), 403 `csrf_check_failed` | -| `GET /api/v1/identity/me` | `GetCurrentAccount` | session | 200 `Account`, `Cache-Control: no-store` | 401 `unauthenticated` | - -Every operation also declares the `default` problem response. - -Registration and verification: - -- Accounts are not enumerated. Registration and resend answer the same neutral 202 for a new, unverified, verified, or unknown email. Login answers the same 401 `invalid_credentials` for an unknown email, a wrong password, or an invalid stored hash; unknown emails and invalid hashes also receive extra Argon2id work. A correct password for an unverified account answers 403 `email_not_verified` and creates no session. -- Before the server looks up the email, it validates the whole registration body (password bounds after NFKC normalization, the password blocklist, the C1 version) and computes the Argon2id hash on every branch, so neither a 400 nor the response time depends on whether the account exists. -- Registering an unverified email again never changes the password hash, scenario, or onboarding step of the account row. Every registration, the first and each repeat, stores its pending credentials (password hash, scenario, and first onboarding step) on its own verification token, replaces the C1 record, advances the registration version, and invalidates earlier verification tokens. `ConfirmEmail` requires the password chosen for that registration and checks it against the pending hash on the clicked token. In one transaction the server checks the current registration version and its C1 record, consumes the token, verifies the email, applies that token's pending credentials to the account, clears its `pending_*` fields, and records exactly one `identity.email_verified` event. Any refusal leaves the account and token unchanged. An unknown, used, replaced, or superseded token, a wrong password, or missing pending credentials answers 400 `verification_token_invalid`; an expired token answers 400 `verification_token_expired`. This prevents an address owner who clicks someone else's link from accepting that registrant's password, and vice versa. Confirmation does not create a session or cookie; sign-in is a separate endpoint and requires a verified account. -- Implementation of registration, resend, and login. A verified address changes nothing and receives no message during registration (the "you already have an account" notice is not implemented). Mail limits per address (shared by registration and resend, keyed by an HMAC of the normalized address, counted whether or not an account exists): at least `VERIFICATION_MAIL_MIN_INTERVAL` (default 60 s) between messages and at most `VERIFICATION_MAIL_DAILY_LIMIT` (default 5) per 24 hours. `IDENTITY_CLIENT_HOURLY_LIMIT` (default 30 per hour, range 1 to 10000) limits registration, confirmation, resend, and login per resolved client address. `IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT` (default 10 per hour, range 1 to 10000) limits login by normalized email whether or not an account exists. `ConfirmEmail` also limits each token to 5 attempts per hour and uses the client limit. A refused request answers 429 `rate_limited` with `Retry-After`. Token replacement policy: every issue first invalidates all unused verification tokens of the account, so one link works at a time; resend changes only the token. `IDENTITY_KEY_SECRET` (at least 32 bytes, required; `IDENTITY_ALLOW_EPHEMERAL_KEY=true` allows a random one on a development stand) keys the idempotency scope, the fingerprint, the limiter keys, and session CSRF. A concurrent request with the same key waits for the first and is replayed, so `idempotency_in_progress` is not produced. Details: [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#registration-email-verification-and-resend). -- Every verification token is bound to the registration version it was issued for, so a token issued before a re-registration never confirms the newer credentials. Resend issues a token for the current version with the pending credentials of that registration, invalidates the earlier ones, and changes nothing else. Planned values: tokens live 24 hours; an account that stays unverified is deleted with its consent record and tokens 7 days after its last registration. These lifetimes come from the versioned product policy (demo version 1 of the `product` family), not from configuration; see [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#product-policy-versions). -- Registration requires Idempotency-Key. For this anonymous operation the key is scoped by the operation, the key, and an HMAC of the normalized email; the fingerprint is an HMAC-SHA-256 with a server secret over the canonical JSON body. The body, the password, and plain hashes of either are never stored, and the secret keeps the fingerprint from serving as an offline password check. -- `ConfirmEmail` takes both `token` and the `password` selected for that registration; clients that sent only a token must be updated. The password follows `LoginPassword`: NFKC normalization and 1 to 128 code points; the registration blocklist is not applied again. `Origin` must match `APP_PUBLIC_URL`; a missing Origin, the literal value null, or a foreign Origin answers 403 `csrf_check_failed`. Confirmation attempts are limited to 5 per token per hour and also use the shared `IDENTITY_CLIENT_HOURLY_LIMIT`; a refused attempt answers 429 `rate_limited` with `Retry-After`. -- `ConfirmEmailByCode` takes `email`, `code` (exactly six digits, `VerificationCode`), and `password`, the password of the registration that issued the code. Every refusal, including an unknown address, a wrong or expired code, a wrong password, and an invalidated token, answers 400 `verification_token_invalid`; a malformed body answers 400 `validation_failed` with the pointer `/code`, `/email`, or `/password`. Five failed checks against one open code invalidate its token, and the link stops working too. The code lives 30 minutes, or until the token ends when that is sooner. The address limit is shared with login (`IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT`), and the client limit is `IDENTITY_CLIENT_HOURLY_LIMIT`. Success answers the same body as `ConfirmEmail` and creates no session. Details: [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#registration-email-verification-and-resend). -- The verification link is `/verify-email#token=`. The frontend confirmation screen is still a placeholder. A client page must remove the fragment with `history.replaceState`, wait for an explicit user action, and post both token and registration password; a link scanner that only opens the page does not consume the token. -- An expired token answers `verification_token_expired`; an unknown, used, replaced, or superseded token, a wrong password, or missing pending credentials answers `verification_token_invalid`. The client offers a new link for either error; after confirmation the user can sign in separately. A repeated confirmation with a used token is deliberately not an idempotent 200: exactly one request succeeds per token. - -Consent C1 and the account: - -- `GetConsentText(c1)` returns the current C1 text, its `text_version`, and `published_at`. Registration sends that version in `consent_c1`; the server records it with the hash of the same stored text. A version that is no longer current answers 400 `validation_failed` with the pointer `/consent_c1/text_version`, and the client reads the text again. A dedicated code would trigger the same client action, and the field pointer already identifies it, so no new code is added. -- Unknown body fields are rejected, so no other consent, including C4, can be part of registration. -- Passwords are normalized to NFKC and must have 15-128 Unicode code points, without composition rules. Generated Zod validators count UTF-16 code units, so the server stays authoritative for the length. -- The account has a `scenario` (`candidate` or `employer`) and a saved `onboarding_step` that the server advances; after login the client returns the user to that step. Candidate steps are `candidate_consents`, `candidate_profile`, `candidate_questionnaire`, `candidate_assessment`, and `completed`; the employer has `employer_company` and `completed`. DTOs never contain password hashes, token hashes, or session identifiers. - -Sessions and CSRF: - -- Implemented session operations: Login issues a `__Host-lincodex_session` cookie with `Path=/; Secure; HttpOnly; SameSite=Strict`, no Domain, and Expires/Max-Age at the absolute session deadline. PostgreSQL stores only the SHA-256 hash of the cookie token; the current-session GET returns the account and CSRF token after a reload. Successful login transactionally revokes an active session from the request and creates a new one; only a verified account can sign in. Logout revokes the session and clears the cookie; an expired or revoked cookie is also cleared on 401. `IDENTITY_SESSION_IDLE_TIMEOUT` defaults to `24h` (range `1m` to `30d`) and `IDENTITY_SESSION_ABSOLUTE_LIFETIME` defaults to `168h` (range `1m` to `365d`); idle cannot exceed absolute, and invalid values stop startup. Requests extend only the idle deadline. -- The `sessionCsrf` scheme is the `X-CSRF-Token` header with the current session's token from `Session.csrf_token`. The backend derives it with domain-separated HMAC-SHA-256 from the cookie token and `IDENTITY_KEY_SECRET`, compares it in constant time, and does not store it in the database. All instances must share one `IDENTITY_KEY_SECRET` (at least 32 bytes), stable across restarts; changing it invalidates old CSRF values but does not revoke PostgreSQL sessions. Every unsafe operation that requires `sessionCookie` must also require `sessionCsrf`; `TestUnsafeSessionOperationsRequireCSRFToken` in the backend enforces it on the bundle. The client keeps the token in memory and restores it with `GetCurrentSession` after a reload or after 403 `csrf_check_failed`. -- Every unsafe public identity operation requires exactly one `Origin` header matching `APP_PUBLIC_URL`, including `RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, and `Login`. Unsafe operations protected by a session also require the session-bound CSRF token. Origin checks do not use `Host` or forwarded headers. Public identity operations are rate-limited (429 with `Retry-After`). -- Responses with a session or account carry `Cache-Control: no-store`. -- The root `security` requires `sessionCookie`, so an operation that does not declare `security: []` is protected by default. - -How the generated server (ogen v1.24.0) evaluates the schemes, and how `v1.SessionSecurity` applies the current session boundary, are pinned by `TestGeneratedServerSecurityOrder`: - -- It calls `HandleSessionCookie` before `HandleSessionCsrf` and passes the context returned by a successful call on. An absent value (no cookie, empty `X-CSRF-Token`) does not call the handler, and a handler that returns `ogenerrors.ErrSkipServerSecurity` counts as unsatisfied; both continue with the next scheme, so `HandleSessionCsrf` also runs without a cookie, with the original context. -- Any other handler error stops evaluation and reaches `NewError` as a `SecurityError` whose `Security` is `SessionCookie` or `SessionCsrf`. An unsatisfied requirement reaches `NewError` as a `SecurityError` with `ErrSecurityRequirementIsNotSatisfied` and no `Security` field. -- Implemented mapping: `HandleSessionCookie` authenticates every operation whose contract requires `sessionCookie`; missing, unknown, expired, revoked, or unverified sessions leave the requirement unsatisfied and answer 401 `unauthenticated`. For protected unsafe operations, `HandleSessionCsrf` checks the exact Origin and the token for that same session. Without a verified principal the result is 401; with one, a missing or wrong Origin or CSRF token is 403 `csrf_check_failed`. A 401 from `Logout` also clears the cookie, while a 403 leaves a valid session intact. - -### Catalog and questionnaire - -The `catalog` and `candidate` tags cover the specialization catalog and the candidate questionnaire (PRD FR03). The catalog is public and answers 501 `not_implemented` until its handler exists. The questionnaire is protected: a guest answers 401 `unauthenticated`, while a valid session passes the security boundary and reaches 501 `not_implemented` after request validation. Unsafe protected operations also require the session-bound CSRF token and exact Origin. - -| Method and path | operationId | Security | Success | Specific errors | -| --- | --- | --- | --- | --- | -| `GET /api/v1/specializations` | `GetSpecializationCatalog` | public | 200 `SpecializationCatalog` | none | -| `GET /api/v1/me/questionnaire` | `GetMyQuestionnaire` | session | 200 `CandidateQuestionnaire`, `Cache-Control: no-store` | 401 `unauthenticated`, 403 `forbidden` | -| `PUT /api/v1/me/questionnaire` | `SaveMyQuestionnaire` | session and CSRF | 200 `CandidateQuestionnaire`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `csrf_check_failed` or `forbidden`, 412 `version_conflict` | - -Every operation also declares the `default` problem response. - -Catalog: - -- Five directions and nine specializations: Development (`backend`, `frontend`, `mobile`), Infrastructure (`network_engineer`, `devops_sre`), Data (`data_analyst`, `ds_ml`), Security (`information_security`), Quality (`qa`). The MVP grade scale is `intern`, `junior`, `middle`, `senior`; Lead and Architect come after the MVP. The codes are enums, so adding a value is a contract change. Titles are Russian plain text. -- A category is a specialization together with a confirmed grade. Task languages (`python`, `go`) and stack tags are attributes of a chosen specialization and never form a category: Backend with Go is the category `backend`. Algorithms is a shared assessment module, not a specialization. -- Each specialization has `test_availability`: `status` (`available` or `in_development`), the `grades` with a published task bank, and the `task_languages` that bank offers. The MVP opens an assessment only for a category with a published bank. The server derives the values from the published banks, so they change without a contract change; the example in the contract is illustrative and says nothing about a deployed bank. -- The catalog is public (`security: []`): it is the same for every caller, contains no personal data, is shown before registration, and can be cached. - -Questionnaire: - -- The candidate comes from the session; an employer account answers 403 `forbidden`. A candidate without a saved questionnaire gets 200 with `version: 0`, no specializations, and null `work_context` and `updated_at` rather than 404, so the first save reads the version the same way as later ones. -- Each chosen specialization has `self_assessed_grade`, `task_languages`, `stack`, and `experience` in months or null when not stated; `work_context` holds only the acceptable work formats and no personal data. The questionnaire never contains a confirmed grade or a category, and unknown fields such as `confirmed_grade` answer 400. The self-assessed grade is the expected grade that the `candidate_assessment` onboarding step offers first; it influences where the assessment starts but adds no points, and no self-assessed grade or stack tag such as "Senior" assigns a category. A real profile stays invisible to employers until an assessment confirms a category. -- The schema allows one or two specializations on save and rejects an unknown specialization, grade, task language, or work format. JSON Schema `uniqueItems` cannot compare array items by one field, so the server rejects a repeated specialization with 400 and the pointer `/specializations//specialization`. It also rejects a task language that the specialization's published bank does not offer, with the pointer of that language. A specialization whose test is `in_development` can be chosen; no assessment starts for it. -- Concurrency uses `expected_version` in the body instead of If-Match, because the generated client cannot read the `ETag` header yet. The first save sends 0. A stale value answers 412 `version_conflict`, the same status and code as a failed If-Match, because the client does the same thing: it reads the questionnaire again. `version_conflict` keeps its 412 status, so `state_conflict` (409) is not used here. -- PUT replaces the whole questionnaire and needs no Idempotency-Key. A body equal to the stored state changes nothing, keeps the version, and answers 200 even with an older `expected_version`, so a retry after a lost response does not fail with 412. -- Order of checks for a save: session (401), CSRF and Origin (403), request validation (400), account scenario (403 `forbidden`), domain rules (400), version (412). `TestQuestionnaireSchemaValidationPrecedesImplementation` checks the schema rejections through the generated server. - -### Candidate profile - -The `candidate` tag includes implemented `GetMyProfile` and `SaveMyProfile` operations for the private manual profile. A verified candidate reads and edits only their own profile; an employer receives 403 and a guest receives 401. PUT requires the session CSRF token and exact Origin. Data, version, overlap confirmations, history, and the step transition commit in one transaction. Without DATABASE_URL, the operations retain their 501 fallback. `confirmed_categories` is read-only: one category per specialization in catalog order, from assessment results, with `basis` (`synthetic_demo` for a demonstration category), `confirmed_at`, and `attempt_id`; no request carries it. - -| Method and path | operationId | Protection | Success | Specific errors | -| --- | --- | --- | --- | --- | -| `GET /api/v1/me/profile` | `GetMyProfile` | session | 200 `CandidateProfile`, `Cache-Control: no-store` | 401 `unauthenticated`, 403 `forbidden` | -| `PUT /api/v1/me/profile` | `SaveMyProfile` | session and CSRF | 200 `CandidateProfile`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `csrf_check_failed` or `forbidden`, 412 `version_conflict` | -| `POST /api/v1/me/profile/repository-checks` | `RequestMyRepositoryChecks` | session and CSRF | 202 `ProfileRepositoryCheckRequest`, `Cache-Control: no-store` | 401, 403 `csrf_check_failed` or `forbidden`, 429 `rate_limited` with Retry-After | - -Each operation also declares the default problem response. No new problem code is added: the contract uses `validation_failed`, `unauthenticated`, `forbidden`, `csrf_check_failed`, and `version_conflict`. - -`experience_overlaps` lists intersecting inclusive month ranges and their decision state. A changed save requires explicit `confirmed_parallel_periods` with indices and exact dates for that version; an earlier decision survives only for the same indices and dates. A stored unconfirmed overlap permits an exact no-op, but no other edit without a decision. History is appended only on change. A successful PUT advances only `candidate_profile` to `candidate_questionnaire`; the earlier `candidate_consents` and later steps stay unchanged. Consent-step completion has no separate operation yet. - -What the profile holds: - -- The full name and contacts (`full_name`, `contacts.email`, `contacts.phone`, `contacts.telegram`), the stack (`stack`, `StackTag` tags), roles (`roles`: a catalog specialization and a self-assessed grade), work experience (`experience`: entries with a month-precision period `YYYY-MM`, a specialization, and a description of the tasks rather than a job title), soft skills (`soft_skills`, free text), and terms (`terms`: place, readiness to relocate, and the lowest salary with its currency, period, and tax basis). This is personal data of the candidate; the description of each such schema says so, and the values never reach logs, metrics, URLs, or events. -- Contacts are exactly the four kinds that the consent C4 can disclose (`ContactFieldKind`), with the same formats (E.164, the leading `@` of a Telegram name, a single line of up to 200 characters for the name), so a disclosure never converts or drops a stored value. The contact email of the profile is not the login of the account: the server sends no mail to it and does not verify it. -- Acceptable work formats are not repeated in the profile: they stay only in the `WorkContext` of the questionnaire. -- The profile is private: only its owner reads it, and no organization, invitation, or need schema refers to it (`$ref`). An organization sees a candidate only through the anonymous card and, after an accepted invitation, through the contact grant. The lowest salary is never disclosed to an organization; an invitation shows only a compatibility indicator that the server computes. - -Self-assessment and confirmed category: - -- The grade of a role (`roles[].self_assessed_grade`) is a claim of the candidate, the same one that the questionnaire calls `self_assessed_grade`; it adds nothing and never becomes a confirmed grade. The confirmed category is a separate list, `confirmed_categories` (specialization, grade, time, and the assessment attempt that confirmed it). It is read-only, the server derives it from assessment results, no request carries it, and the profile storage has no column for it. A request with `confirmed_grade`, `category`, or `confirmed_categories` is rejected as an unknown field. - -Source and confirmation: - -- Every value carries `status` and `source`. For a single field `status` is `confirmed`, `extracted`, or `unknown`; for `unknown` the value and the source are null, and the server fills in no default. For a list item `status` is `confirmed` or `extracted`. `source` holds `origin` (`manual`; `extracted_from_resume` and `imported` are planned and no MVP operation produces them), `trust_level`, `quote`, `extraction_version`, and `confirmed_at`. -- Every claim of the profile has `trust_level` 0, whatever its source: a schema limit (`minimum` and `maximum` are 0), a CHECK in the database, and a type in the domain. Confirming a suggestion changes its status, not its level; higher levels belong to evidence (an assessment result, a confirmation by a third party), which is stored separately and never written into a claim. -- A request carries a decision for each value (`value` and `status`): `confirmed` sets a manual value or confirms a stored suggestion with the same value (the source and the quote are kept), and `extracted` keeps a stored suggestion unconfirmed and is accepted only with exactly the same value. Any other use of `extracted` answers 400 with the pointer of that status, for example `/stack/1/status`, so a form submitted unchanged confirms nothing by accident, as for needs. The client never sends the source, the trust level, or the confirmation time. - -Version and retries: - -- The version starts at 0 for a candidate without a saved profile; such a candidate gets 200 with every field `unknown` and empty lists, not 404. `PUT` replaces the whole profile and a list replaces the list; a field sent as null becomes unknown and is removed. -- Concurrent edits are controlled by `expected_version` in the body, as in the questionnaire: the generated client cannot read `ETag` yet. A stale value answers 412 `version_conflict` and changes nothing, and the client reads the profile again, so an edit from another tab is never lost silently. A body that changes nothing keeps the version and answers 200 even with an older version, so no Idempotency-Key is needed. Every saved change advances the version by one. -- Order of checks: session (401), CSRF and Origin (403 `csrf_check_failed`), request validation (400), account scenario (403 `forbidden` for an employer), a version above the current one (412), domain rules that depend on the body alone (400), then the rules that depend on the stored claims, with the version: a decision `extracted` for something that is not a stored suggestion answers 412 on a stale version (another tab may have confirmed the value) and 400 on the current one; an unchanged body is 200; any other change over a stale version is 412. A version above the current one never existed and answers 412 even for an unchanged body. The domain rules that the schema cannot express are: a repeated tag, skill, or role specialization (without regard to letter case for tags and skills), a period that ends before it starts or lies in the future, and a decision `extracted` for something that is not a stored suggestion. The 400 response never repeats a submitted value. - -No file, ML, or FSP: - -- The profile is filled in entirely by hand. No field requires a resume, ML extraction, or an FSP account, and the migration and queries create no mandatory link to a file, ML, or FSP. Resume upload and linking an FSP ID are planned additive features; they will add their own fields and sources without changing these. - -Relation to the questionnaire: - -- The questionnaire (`/me/questionnaire`) names at most two specializations for assessment; the profile is what the candidate presents about themselves. Same-named concepts are not duplicated under different meanings: the self-assessed grade and the stack are the same claim in two places (in the questionnaire for the start of the assessment and per specialization, in the profile for display), saved separately, and the server never copies one into the other; the total months of experience in the questionnaire and the experience entries of the profile are different claims; work formats live only in the questionnaire, while place, relocation, and salary live only in the profile. The schema descriptions of both sides refer to each other. - -Storage (migration 00013): `candidate_profiles` (the profile row: `user_id`, `version`, times) and `candidate_profile_claims` (one row per stored claim: `kind`, `ordinal`, `value` jsonb, `status`, `origin`, `trust_level`, `quote`, `extraction_version`, `confirmed_at`). A missing row means `unknown`. Each kind of value has a CHECK for the format and bounds of the contract; `trust_level` is always 0; the tables have no file column, no FSP column, and no confirmed grade. Details are in [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#candidate-profile). - -Open questions for the product owner and legal: - -- Contact kinds: only the four C4 kinds are allowed. Whether links to GitHub, social networks, or a website are needed (the PRD hides them until an invitation is accepted); that would be a contract change in `ContactFieldKind` too. -- The 152-FZ basis: which consent covers storing the profile (C1 at registration or a separate one), whether the name and the contacts need separate consents, the retention periods, and the deletion procedure. Today deleting an account cascades to its profile, and there are no retention rules. -- The order of the version and the domain rules: the version is checked before the rules that depend on stored claims (a stale tab gets 412, not 400); the product owner should confirm. -- Full replacement: `PUT` drops stored import suggestions that the client did not render and send back with the status `extracted`; whether that is acceptable or the server should keep suggestions that were never shown. -- The minimum for the onboarding step `candidate_profile`: the current contract requires no field, so any successful PUT completes that step, including an empty no-op. Requiring fields later needs a separate product decision and contract change. -- One source between the questionnaire and the profile: keep the self-assessment and the stack independent, or store one claim and show it in both places. -- Soft skills: there is no taxonomy, only free text, up to 10 items of 50 characters; whether a dictionary is needed. -- Experience: employer names and descriptions are personal data; how the anonymous card generalizes them (PRD: industry and size) is for the card contract, not this one. -- Contact verification (confirming the phone or the email of the profile) is not provided: contacts are claims of level 0. - -`TestCandidateProfileOperationsFollowTheConventions`, `TestCandidateProfileSeparatesSelfAssessedGradeFromConfirmedCategory`, `TestCandidateProfileClaimsCarrySourceAndTrustLevelZero`, `TestPrivateProfileSchemasAreNotMixedWithOrganizationVisibleDTOs`, `TestGeneratedProfileDTOsCarryNoConfirmedGradeInRequests`, `TestProfileSchemaValidationPrecedesImplementation`, and `TestProfileAccessBeforeImplementation` pin the generated server and the bundle, and `frontend/src/shared/api/profile-contract.test.ts` pins the generated Zod rules, the request types without a confirmed grade, and the absence of profile fields from the organization, invitation, and need schemas. - - -Projects: the optional `projects` list of the `SaveMyProfile` body (up to 10; an absent list keeps the projects, an empty array removes them) with a title, description, tags, and an address `https://github.com//`; other addresses answer 400 with the pointer `/projects//repository_url`. The `CandidateProfile` response carries `projects[].repository_check` (`pending`, `verified`, `not_found`, `unavailable`). `RequestMyRepositoryChecks` repeats the checks on `api.github.com` at most once per stand interval. Publishing projects on the card is the separate `projects` value of `CardField` (see [architecture](../docs/en/ARCHITECTURE.md#candidate-projects-and-github-repositories)). -### Assessment - -The `assessment` tag covers the assessment attempts of the current candidate (PRD FR04 and FR05): availability, start and resume, answers including the code practice, finalization, and the result. The operations are in the contract, but their business logic is not implemented: a guest answers 401 `unauthenticated`, and a request with a verified session reaches 501 `not_implemented` after request validation. Unsafe protected operations also require the session-bound CSRF token and exact Origin. - -| Method and path | operationId | Security | Success | Specific errors | -| --- | --- | --- | --- | --- | -| `GET /api/v1/me/assessment-availability` | `GetMyAssessmentAvailability` | session | 200 `AssessmentAvailability`, `Cache-Control: no-store` | 401 `unauthenticated`, 403 `forbidden` | -| `POST /api/v1/me/assessment-attempts` | `CreateMyAssessmentAttempt` | session and CSRF, Idempotency-Key | 201 `AssessmentAttempt`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `csrf_check_failed` or `forbidden`, 409 `state_conflict` or `idempotency_in_progress`, 422 `idempotency_key_reused`, 429 | -| `GET /api/v1/me/assessment-attempts/{attempt_id}` | `GetMyAssessmentAttempt` | session | 200 `AssessmentAttempt`, `Cache-Control: no-store` | 401, 403 `forbidden`, 404 `not_found` | -| `POST /api/v1/me/assessment-attempts/{attempt_id}/sessions` | `StartMyAssessmentAttemptSession` | session and CSRF, Idempotency-Key | 200 `AssessmentAttempt`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict` or `idempotency_in_progress`, 412 `version_conflict`, 422, 429 | -| `POST /api/v1/me/assessment-attempts/{attempt_id}/answers` | `SubmitMyAssessmentAnswer` | session and CSRF, Idempotency-Key | 200 `AssessmentAttempt`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict` or `idempotency_in_progress`, 412 `version_conflict`, 422, 429 | -| `POST /api/v1/me/assessment-attempts/{attempt_id}/practice-runs` | `CreateMyAssessmentPracticeRun` | session and CSRF, Idempotency-Key | 202 `PracticeRun`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict`, 422, 429 `rate_limited`, 503 `service_unavailable` | -| `GET /api/v1/me/assessment-attempts/{attempt_id}/practice-runs/{run_id}` | `GetMyAssessmentPracticeRun` | session | 200 `PracticeRun`, `Cache-Control: no-store` | 401, 403 `forbidden`, 404 `not_found` | -| `PUT /api/v1/me/assessment-attempts/{attempt_id}/work-session` | `HoldMyAssessmentWorkSession` | session and CSRF, `X-Attempt-Client` | 200 `AssessmentWorkSession`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict` (another page holds it, or the attempt has no work session) | -| `DELETE /api/v1/me/assessment-attempts/{attempt_id}/work-session` | `ReleaseMyAssessmentWorkSession` | session and CSRF, `X-Attempt-Client` | 204, `Cache-Control: no-store` | 400, 401, 403, 404 | -| `POST /api/v1/me/assessment-attempts/{attempt_id}/finalize` | `FinalizeMyAssessmentAttempt` | session and CSRF, Idempotency-Key | 200 `AssessmentAttempt`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict` or `idempotency_in_progress`, 412 `version_conflict`, 422 | -| `GET /api/v1/me/assessment-attempts/{attempt_id}/result` | `GetMyAssessmentResult` | session | 200 `AssessmentResult`, `Cache-Control: no-store` | 401, 403 `forbidden`, 404 `not_found`, 409 `state_conflict` | -| `GET /api/v1/me/assessment-results` | `ListMyAssessmentResults` | session | 200 `AssessmentResultHistoryPage`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `forbidden` | -| `GET /api/v1/me/assessment-signal-notice` | `GetMyAssessmentSignalNotice` | session | 200 `AssessmentSignalNotice`, `Cache-Control: no-store` | 401, 403 `forbidden` | -| `PUT /api/v1/me/assessment-signal-notice` | `AcknowledgeMyAssessmentSignalNotice` | session and CSRF | 200 `AssessmentSignalNotice`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `csrf_check_failed` or `forbidden`, 409 `state_conflict` | - -Every operation also declares the `default` problem response. - -The signal notice (`assessment-signal-notice`) lists the signals collected during a real attempt: browser events (focus loss, copy, paste and cut with a size, fullscreen exit, a screenshot key, and a guess that the developer tools are open; stored only while C3 is current) and server signals (response time, change of network address, parallel sessions, change of User-Agent, comparison of answer digests; only one-way keyed digests are stored, never addresses, User-Agents, or session tokens). `GET` returns the notice version the server requires and whether the candidate acknowledged it; `PUT` stores the acknowledgement for the account and that version. The acknowledgement is a record that the candidate was informed, not a consent: it does not change C3, and the signal operation neither reads it nor refuses a batch without it. `PUT` needs no Idempotency-Key, because a repeat keeps the first time and answers 200; another version answers 409 `state_conflict`. The notice also lists the measures the page applies during a real attempt (fullscreen, covering the task, blocks on copying, selecting, and printing the task text, the paste rule, the one-window rule, and the watermark of the task screen and text) and says plainly that a screenshot or a phone photo cannot be prevented and that signals lead only to a manual check; it is text version 4, and an acknowledgement of an earlier version never counts for the current one. The `demo_express` mode collects no signals and needs no acknowledgement. - -Access: - -- The candidate comes only from the session; no operation takes a candidate identifier. An employer account answers 403 `forbidden`. An attempt of another candidate answers 404 `not_found`, the same as an unknown identifier, so attempt identifiers cannot be probed. -- No operation offers an employer answers, attempt history, or anti-cheat signals. Employers see the current category on the anonymous card and the permitted skill evidence of that card ([Skill evidence](#skill-evidence)), never a result. - -Modes and versions: - -- `kind` is required on creation: `root`, `corrective`, or `demo_express`. A real attempt uses `demo_basic` or `adaptive`; the server picks the mode from the published bank and the client never sends it. `demo_basic` scores a fixed form of reviewed demo items by their keys against the pass mark of the versioned basic grading policy, computes no ability estimate, and decides in one step: it never offers an additional practice. `adaptive` is the adaptive test of FR04. A candidate may explicitly request `demo_express`, a separate interactive 3 to 5 minute training run with no category, target grade, percentile, real-assessment quota, or qualification evidence. -- A corrective real attempt includes `root_attempt_id`. The server allows only a strictly lower target grade not already tried in that chain. Creating the root reserves one slot in the three-root-attempts-per-180-days quota; corrections share that slot and the root's immutable `chain_deadline` (72 hours from the root start under the current policy), while keeping their own item, practice, and session limits. A correction spends no additional root slot, cannot extend the deadline, and does not reset the 30/90-day timers. A root preflight refusal creates no attempt and reserves no slot. An expired or incomplete attempt does not create a free new chain, and an insufficient bank does not grant another root slot. `demo_express` is outside correction chains and real-assessment availability. -- Creation fixes `versions`: `policy_version` (the number of the `product` policy version), `bank_version`, and `algorithm_version`. The attempt and its result keep them, so a result is reproduced from the stored answers and these versions, and a later version never rewrites it. -- The attempt `version` advances by exactly one with each committed change, including a verdict, an explicit session start, expiry, or automatic finalization. GET operations are projections only: they never change the state, consume session quota, or advance the version. A command or background transition commits due outcomes. - -Attempt lifecycle, with the commands each state accepts: - -| State | Meaning | Accepts | -| --- | --- | --- | -| `in_progress` | Items are being answered; `current_item` is the item to answer | an answer to `current_item` | -| `practice_pending` | The item part is done; the main practice has no finished verdict (not submitted, `pending`, or `failed`) | a practice solution while it is `not_started` or `failed` | -| `additional_practice_pending` | Adaptive only: finalize found the probability in the band below confirmation and offered one additional practice in the same attempt | the additional practice solution while it is `not_started` or `failed`; finalize in the same statuses declines the offer | -| `ready_to_finalize` | Every required part is done | finalize | -| `completed` | A decision was made; the result is available | only the repeat of finalize | -| `expired` | The time or session limit passed before the candidate finished; the result confirms no grade | none | -| `insufficient_bank` | The bank could not cover the blueprint within the limit; the result confirms no grade | none | - -- Additional practice (PRD FR04): with 0.50 <= P_G < 0.80 in the demo policy, the first finalize of an adaptive attempt completes nothing. It appends a practice of kind `additional` to `practices`, moves the attempt to `additional_practice_pending`, and returns the attempt. The practice continues the same attempt, keeps its time and session limits, and spends no new attempt. The next finalize after its verdict decides; P_G still below 0.80 gives `not_confirmed`. Finalizing without submitting it declines the offer with the same outcome. `practices` is a list with a `kind` rather than one more nullable field, so later practice kinds stay additive. -- Finalize therefore always answers with `AssessmentAttempt`, never with a result or a `oneOf` of both. When the state is `completed`, the client reads `GetMyAssessmentResult`. One response type keeps generated clients unambiguous and leaves room for non-terminal decisions without a breaking change. -- Limits: `expires_at` and `sessions` (`used`, `max`, `idle_timeout_seconds`, null when the policy defines no session limit) come from the policy version; PRD FR04 allows two sessions within 72 hours. Creation starts session 1. After an idle timeout the candidate explicitly calls `StartMyAssessmentAttemptSession` with the latest `expected_version`; it starts the next session only if quota and deadline allow. Calling it during an active session is a no-op. Session start does not extend `expires_at` or `chain_deadline`. -- At the limits: a practice already `pending` is graded first. A command or background transition then finalizes `ready_to_finalize` as `completed`, declines an unsubmitted additional practice (`completed`, `not_confirmed`), or moves `in_progress` and `practice_pending` to `expired`. GET never commits these transitions. `GetMyAssessmentResult` answers 409 while a due transition has not yet been stored. -- Insufficient bank is a distinct state in two places. Before a root attempt starts, `GetMyAssessmentAvailability` shows `insufficient_bank` for a grade without a published bank or enough unseen families, and `CreateMyAssessmentAttempt` answers 409 `state_conflict` without creating an attempt or reserving a root slot. A correction with an expired chain deadline or insufficient safe bank is also refused; it does not create a new chain. During an existing attempt, the terminal state `insufficient_bank` ends it without a confirmed grade instead of repeating families. -- Confirmed grade. `confirmed_grade` and `confirmed_basis` of each questionnaire specialization are read together from the current category, in one snapshot. `confirmed_basis` is `synthetic_demo` for a demonstration grade and null exactly when no grade is confirmed. An attempt does not set them directly: only a category upgrade changes them. -- No new problem code is added, so attempt creation gets 409 `state_conflict` plus the availability status instead of a `bank_unavailable` code. The `ProblemCode` enum is copied byte-for-byte into the ML contract (`test_contract_copies.py`), so a new code would also change the ML contract and its generated models. The availability read also tells the client why an attempt cannot start and, for `cooldown`, from when, which a fixed problem detail cannot carry. -- Availability shows the limits of each grade before the start: `time_limit_seconds`, `max_sessions`, `max_items`, and `practice_required`, null when unknown. -- Root-attempt quota and retry timers are separate. Only root creation reserves one of the three root slots per 180 days; corrections in that chain do not reserve another. `insufficient_bank` or an unavailable sandbox does not create a new attempt or open a free chain. After a failure, including the first test, a strictly lower grade can be tested through the same chain; lower-grade corrections do not reset the 30-day same-grade or 90-day promotion timers. - -Items and answers: - -- An item has an `id` (the instance), `sequence`, a plain-text `prompt`, and `content` (`ItemContent`) in one of the formats `choice`, `number`, `string`, `order`, `find_error`, `configuration`, and `practice`. It never contains an answer key, a correct option, a score, a family or variant identifier, a seed, or a hidden check, and seed items look like scored ones. `multiple`, `max_selections`, and `max_length` are properties of the format or the task family and never derived from the key. The variant is fixed when first served, so a reload, a retry, or a resumed session returns the same instance. -- Watermark. A real attempt (`root` or `corrective`) carries `watermark.code`, a keyed pseudonym of the attempt such as `7K3QD-9XM2T`, which the client shows with the time as a faint tile over the task screen; a `demo_express` attempt omits the field. The `prompt` of a real attempt also carries an invisible mark and interchangeable wordings chosen by the same server secret; they change neither the meaning nor the reference answer, and a client keeps the invisible characters (zero width space, non-joiner, joiner, word joiner) out of the accessibility tree. Neither the code nor the mark names the candidate, and no operation gives either to an employer. See [Watermark of the task text](../docs/en/ARCHITECTURE.md#watermark-of-the-task-text). -- One open window. A real attempt allows one open page at a time. The page generates a random identifier when it loads and sends it as `X-Attempt-Client` (16 to 64 characters of `A-Za-z0-9_-`) to `HoldMyAssessmentWorkSession`, which holds the work session for 120 seconds and asks the page to renew every 15 seconds, and to `ReleaseMyAssessmentWorkSession` when it closes. `StartMyAssessmentAttemptSession` and `SubmitMyAssessmentAnswer` take the same header as an optional parameter; while another page holds the session, a request from a different page or from none answers 409 `state_conflict` and changes nothing, and that refusal is not stored under the Idempotency-Key. An attempt that nobody holds, a released hold, and a hold that stopped renewing admit every page. It is a one-page-at-a-time rule, not a security boundary, and it is separate from `sessions` (`used`, `max`, `idle_timeout_seconds`), which count sequential work sessions. The server keeps only keyed digests of the page identifier and of the User-Agent bound to the attempt. No new problem code is added, so the page reads 409 on these operations as "open in another window". -- An answer (`AssessmentAnswer`) has the same seven formats and carries only the answer. Unknown fields such as `score`, `duration`, or `seed` answer 400. The server records the times and scores the answer with the key of the item instance; time never enters the grade decision. Responses never say whether an answer was correct. -- The practice solution runs asynchronously in the sandbox against three hidden check groups; the client polls the attempt while it is `pending`. The verdict shows only the score 0-3 and the pass state of each group. Every outcome caused by the solution (a compilation or runtime error, a time or memory limit) is `finished` with groups not passed. `failed` (`sandbox_busy` or `sandbox_error`) means only that the infrastructure could not run it; it consumes nothing. This keeps `failed` from acting as an oracle for hidden checks and from allowing endless retries. After `finished` no other solution is accepted. -- Debug runs (`CreateMyAssessmentPracticeRun`, `GetMyAssessmentPracticeRun`) run a solution against the public examples and up to ten tests of the candidate while the practice is the current item. They never run, list, or score a hidden check, and change neither the practice state, the verdict, nor the attempt version. A run is queued and read by its own identifier; a repeat with the same Idempotency-Key and body returns the stored run. A per-candidate rate limit and one unfinished run per practice answer 429 `rate_limited` with `Retry-After`. The sandbox queue holds one running and ten waiting runs and solutions together; when it is full, a run answers 503 `service_unavailable` with `Retry-After`, and a final solution leaves the practice `failed` with `sandbox_busy`, which consumes nothing. Without a configured sandbox the operation answers 503 `service_unavailable` without `Retry-After`. A refusal stores nothing. -- If the latest submission is still `failed` when the limit passes, the result is `not_determined` with the reason `sandbox_unavailable`. A practice never submitted gives `practice_incomplete`. -- An attempt has no practice only in `demo_basic` while code practice is disabled until the sandbox isolation is verified; the result then lists the `practice_not_included` limitation. - -Commands, retries, and versions: - -- Create, start/resume session, answer, and finalize require Idempotency-Key with the 24-hour replay described above, so a repeated command returns the same outcome. Session start, answers, and finalize carry `expected_version`, the attempt `version` the client read. Creation has no version to compare and relies on the key; the single active real attempt per specialization is enforced by the state. -- Each item accepts one answer. Sending the stored answer again, even with a new key or an older `expected_version`, stores nothing, keeps the version, and answers 200 with the current attempt. Equality is defined per format: sets for `option_ids` and `line_numbers`, the exact sequence for `element_ids`, numeric equality for `number`, identical text without normalization for `text` and `config`, and the same language with identical source for a practice. A different answer for an answered item answers 409 `state_conflict` with the current version; with a stale version the version check comes first and answers 412. -- Exception: a practice whose latest verdict is `failed` is outside the repeat rule. A submission with the same or a different solution and the current version queues it again and advances the version. -- Finalizing a `completed` attempt answers 200 with that attempt, so the result is computed once. A retry of the finalize that offered an additional practice, sent with a new key, carries the old version and answers 412, so it never declines the offer by accident. -- A stale `expected_version` answers 412 `version_conflict`, not 409. This keeps the repository rule and questionnaire precedent: `version_conflict` is 412 for If-Match and for a body `expected_version` alike, because the client action is to read the resource again. 409 `state_conflict` is kept for a command that the attempt state does not allow at the current version: the work session ended, the item is not current or has another answer, the attempt is terminal or past its limits, a practice verdict is pending, or the attempt is not ready to finalize. The two codes lead to different client actions. -- A premature finalize answers 409 `state_conflict` without listing the unfinished items, because `Problem` allows no extension fields. The client reads them from the attempt: `state`, `progress`, `current_item`, and `practices`. -- Order of checks for a command: session (401), CSRF and Origin (403), request validation (400), account scenario (403 `forbidden`), the Idempotency-Key (422, 409 `idempotency_in_progress`, replay), attempt ownership (404), the attempt version (412 when supplied), due time or session transitions, then the command state (409 `state_conflict`) and domain rules (400 with pointers such as `/answer/option_ids/0`). An explicit session-start command returns the updated attempt when it commits a due terminal transition. Following the Idempotency-Key convention, stored 404 and 409 responses replay under the key; 400, 412, 429, and 5xx are not stored. Create and answers are rate-limited (429 with `Retry-After`), which also limits sandbox load. `TestAssessmentSchemaValidationPrecedesImplementation` checks the schema rejections through the generated server. - -Result: - -- `GetMyAssessmentResult` answers for a terminal attempt and 409 `state_conflict` for an active one, including `additional_practice_pending`. `outcome` is `confirmed`, `not_confirmed`, or `not_determined` with `not_determined_reason` (`expired`, `practice_incomplete`, `insufficient_bank`, `sandbox_unavailable`). A result never lowers a confirmed grade: `previous_confirmed_grade` stays in force when the attempt confirmed nothing. -- Attempt and result responses carry the `kind` discriminator: `root`, `corrective`, or `demo_express`. Real results always include the correction-chain field pair: both are null for a root attempt, and both are populated for a corrective result. A `demo_express` result is a separate educational shape with a short summary and `demonstration_only`; it has null category, target grade, confirmed grade, strength, uncertainty, and score, and empty practices, gaps, and next steps. It cannot be used as qualification evidence and is never visible to employers. -- `calibration_status` and `limitations` describe the method. Fields that the method does not compute are null, never zero: `demo_basic` has null `uncertainty` and `strength`, and `adaptive` has null `basic_score`. `uncertainty` holds `theta`, `standard_error`, `interval_95`, and `p_grade`. `practices` lists the verdicts by kind. `durations` is a separate label and never enters the decision. -- `next_steps` come from the server: `retake_same_grade`, `take_lower_grade`, `accept_lower_grade` (the command is planned), and `take_higher_grade`. A first confirmation is not a promotion, so `take_higher_grade` after it has a null `available_at`; after a promotion the next one waits for the 90-day promotion interval. -- The result never contains answers, per-item correctness, keys, seeds, hidden checks, or anti-cheat signals. -- Category from a `demo_basic` result. A real result carries `category_decision`: `status` (`not_eligible`, `not_confirmed`, `assigned`, `unchanged`), the grade in force before and after the attempt, `method` (`demo_basic_pass_mark`), `source` (`synthetic_demo`), and `calibration_status`. The threshold comes from the accepted policy version pinned to the attempt: reaching it counts, and no request parameter sets it. A category is assigned only when `ASSESSMENT_DEMO_CATEGORIES_ENABLED` is on, the policy version is a complete demonstration policy with `demo_basic` (its threshold is its own `basic_pass_mark_bp`), and an operator attestation exists for the opening, its manifest, and the policy version; otherwise `status` is `not_eligible` and `confirmed_grade` is null even though `outcome` may be `confirmed`. `confirmed_grade` is set only when a reviewed source accepted the confirmation (`assigned` or `unchanged`). A failure, an equal grade, or a lower grade neither lowers nor changes the current category. `demo_express` never gets a `category_decision` and never creates a category. A result stored before category decisions existed has no `category_decision`: its current grade is not reconstructed afterwards. -- `GET /api/v1/me/assessment-results` returns the history of the candidate only: completed `root` and `corrective` results, newest first by `decided_at` and `attempt_id`. The cursor is opaque, bound to the candidate, and uses only `[A-Za-z0-9_-]`; a foreign, altered, or malformed cursor answers 400 `validation_failed` with pointer `/cursor`. An employer account gets 403. A later change of the current policy, bank, or category changes no stored record. An employer receives only the current category (specialization, grade, the coarse strength `standard`, and the basis `basis`) through the anonymous card when the candidate published the `categories` field; the projection holds no attempt, score, version, or reason for a missing confirmation. - -Planned, additive: a short approach description of up to 1500 characters next to the practice, which never decides the grade (PRD FR05); the debug run operation of the practice; the server signals of the anti-cheat layer (answer time, parallel sessions, address changes), which lead to a review and an appeal, never to a public label and never to the employer (PRD FR05). - -### Needs - -The `need` tag covers the hiring needs of an organization (PRD FR08, with the versions of FR10): requirements with their confirmation state and provenance, immutable versions, readiness, and category recommendations. The operations are in the contract, but their business logic is not implemented: a guest answers 401 `unauthenticated`, and a request with a verified session reaches 501 `not_implemented` after request validation. Unsafe protected operations also require the session-bound CSRF token and exact Origin. - -| Method and path | operationId | Security | Success | Specific errors | -| --- | --- | --- | --- | --- | -| `GET /api/v1/organizations/{org_id}/needs` | `ListOrganizationNeeds` | session | 200 `NeedList`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `forbidden`, 404 `not_found` | -| `POST /api/v1/organizations/{org_id}/needs` | `CreateOrganizationNeed` | session and CSRF, Idempotency-Key | 201 `Need`, `Cache-Control: no-store` | 400, 401, 403 `csrf_check_failed` or `forbidden`, 404, 409 `idempotency_in_progress`, 422 `idempotency_key_reused`, 429 | -| `GET /api/v1/organizations/{org_id}/needs/{need_id}` | `GetOrganizationNeed` | session | 200 `Need`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `forbidden`, 404 `not_found` | -| `PATCH /api/v1/organizations/{org_id}/needs/{need_id}` | `UpdateOrganizationNeed` | session and CSRF | 200 `Need`, `Cache-Control: no-store` | 400, 401, 403, 404, 412 `version_conflict`, 429 | - -Every operation also declares the `default` problem response. A malformed `org_id` or `need_id` answers 400 with the path pointer. - -Access: - -- `org_id` in the path is the only source of the organization, and the server checks it against the active membership of the session account; no request has an organization, membership, or role field. The organization contract owns organizations and memberships and reuses the same path parameter, `parameters.yml#/OrganizationId`. -- An account without an active membership in `org_id`, an unknown organization, an unknown need, and a need of another organization all answer 404 `not_found`, so identifiers cannot be probed. A candidate account answers 403 `forbidden`, and so does a member whose role does not allow the operation. -- In the MVP only the owner of the organization works with needs. The other roles of the PRD FR07 matrix (recruiter, hiring manager and technical expert for assigned needs) are planned and change no field of the contract. - -Fields and provenance: - -- `requirements` (`NeedRequirementSet`) holds `specialization`, `grade`, `required_skills`, `desired_skills`, `tasks`, `domain`, `work_formats`, `location`, and `salary`. A field in a response is `{status, value, source}`; a list item has its own `status` and `source`. -- `status` is `confirmed` (a member entered or confirmed the value), `extracted` (a suggestion that waits for confirmation), or `unknown` (no value). An unknown field has null `value` and `source`; the server never fills it with a default or a guess such as Senior, remote, or a zero salary. Only confirmed values feed readiness, recommendations, search, and invitations. -- `source` has `origin` (`manual`, `extracted_from_text`, or the planned `imported`), `quote` (an exact excerpt of up to 300 characters, or null), `extracted_in_version`, and `extraction_version`. The quote is an excerpt of the `source_text` of `extracted_in_version`, not necessarily of the current text: a confirmed value keeps its quote after the text changes. Confirming a suggestion keeps its provenance; changing the value makes it `manual`. -- A skill has `taxonomy_code`. It is null for a skill that the platform taxonomy does not know: the name stays as given, no code is guessed, and recommendations count the skill as not covered. -- With `source_text`, the server extracts suggestions with deterministic rules and a dictionary before it answers, so needs work while ML is disabled. ML suggestions with quotes are planned as an asynchronous addition that creates a new version and never overwrites a confirmed value. -- The text is stored as written and may contain requirements that discriminate by a protected characteristic; the extractor never turns them into a need field. The field for what a candidate must not have, with the Labor Code article 64 check, is deferred to the requirement validation feature and will be added without a breaking change. - -Requests, confirmation, and changes: - -- Every requirement field in a request is a decision `{value, status}` (`NeedSpecializationInput`, `NeedGradeInput`, `NeedDomainInput`, `NeedWorkFormatsInput`, `NeedLocationInput`, `NeedSalaryInput`), and every list item is `{name or text, status}`. `status` is `confirmed` or `extracted`. A bare value fails validation, so confirmation is always explicit. -- `confirmed` with the stored suggested value confirms it and keeps its provenance; `confirmed` with another value sets a confirmed manual value. `extracted` keeps a stored suggestion open and is allowed only with exactly the stored suggested value; any other value, or a field or item without a suggestion, answers 400 with the pointer of that status, such as `/grade/status` or `/required_skills/2/status`. A client that sends back an unchanged form therefore confirms nothing by accident: it sends each suggestion with `extracted` or leaves the field out. -- A need never requires a vacancy: only `title` is required, and `vacancy_id` is optional and nullable. Until vacancies exist in the contract, any vacancy identifier answers 400 with the pointer `/vacancy_id`. -- On creation every decision must be `confirmed`, because a new need has no stored suggestion. An absent field is extracted from `source_text` or stays unknown. A nullable field sent as null stays unknown, and a skill or task list sent empty stays empty; neither is extracted. An empty `work_formats` value fails `minItems`. -- `UpdateOrganizationNeed` uses explicit field replacement in `application/json`, not JSON Merge Patch (RFC 7396): a present field replaces that field as a whole, an absent field stays unchanged, a decision and a list are never merged, and a stored item left out of a sent list is deleted. Null removes a nullable field (it becomes `unknown`, or `vacancy_id` is unlinked); an empty skill or task list deletes every item; a list sent as null answers 400. ogen generates one optional, or optional and nullable, value per decision (`OptNilNeedGradeInput`, `OptNilNeedSalaryInput`). -- A different `source_text` extracts again. New suggestions replace only the `extracted` values and items of fields not named in the body; confirmed values are never overwritten, a suggested skill whose name is already in either skill list is skipped, and a suggestion that a member deleted is not proposed again for this need. -- The server also rejects a repeated skill or task and a skill in both lists, with 400 and the pointer of the later item, such as `/required_skills/1/name`. - -Versions and concurrency: - -- `version` starts at 1 and advances by exactly one with each committed change, including server-side ones. Each version is an immutable snapshot. GET always returns the latest version. -- `requirements_version` is the version in which the confirmed requirements were last changed. Confirming, changing, or removing a requirement sets it to the new `version`; a change of the title, the vacancy link, the text, or suggestions only keeps it and invalidates neither the recommendations nor search results. Search runs, selection snapshots (FR10), and invitations refer to `(need_id, requirements_version)`, and only a new `requirements_version` calls for a new selection snapshot. Reading and comparing earlier versions are planned as separate operations that return `NeedRequirementSet` for a version; they add nothing to `Need`. -- A change carries `expected_version`, the version the client read, in the body for the same reason as the questionnaire: the generated client cannot read `ETag` yet. A stale value answers 412 `version_conflict` and changes nothing; the repository rule keeps 412 for If-Match and a body version alike. A body that changes nothing answers 200 with the current need even with an older version, so PATCH needs no Idempotency-Key. POST needs one with the 24-hour replay; only the 201 is stored. - -Readiness: - -- `readiness.missing_fields` lists each critical field without a confirmed value: `specialization`, `grade`, `required_skills` (at least one confirmed skill), `work_formats`, `salary`, and `location` when the confirmed formats include `office` or `hybrid`. Each item has `reason` (`unknown` or `unconfirmed`) and a specific Russian `question`. -- An incomplete need is saved (201 or 200), not rejected. `Problem` allows no extension fields, so the missing fields live in the resource, not in a problem. Each later operation, such as search or an invitation, states which readiness it requires. - -Salary: - -- `SalaryRange` `[A; B]` has `salary_from` and `salary_to` (`RubAmount`, whole rubles), `currency` (`RUB` only), `period` (`month` only), and `tax_basis` (`net` or `gross`); every field is required. Requests send it as `salary: {value, status}`, so its pointers are under `/salary/value`. -- The schema requires bounds that are positive multiples of 1000 up to 100000000 and rejects another currency, period, or basis, for example with `/salary/value/tax_basis`. A missing field of the nested range answers `required` with its pointer, such as `/salary/value/tax_basis`. -- The server checks the cross-field rules of PRD FR13 in integer arithmetic: `A < B` and a width `(B - A) / ((A + B) / 2)` from 10% to 40% inclusive, that is `20 * (B - A) >= A + B` and `5 * (B - A) <= A + B`. A violation, including equal bounds, answers 400 with the pointer `/salary/value/salary_to`. `[95000; 105000]` (exactly 10%) and `[80000; 120000]` (exactly 40%) are accepted. FR13 applies the same rules to the range of a need and of an invitation, and `docs/*/ARCHITECTURE.md` now states them for invitations instead of `0 < salary_from <= salary_to`. -- Limit against probing hidden minimums (FR13, enforcement planned): setting a confirmed range, on creation or on a change, counts against a counter shared by the whole organization, every member and every need, so a new need does not reset it. At most three range settings a day; over the limit the server answers 429 with Retry-After and changes nothing. After five settings within seven days the money component is `withheld` for seven days. Repeated range changes also feed the private organization risk signals. - -Recommendations: - -- `recommendations` is computed by the server from the confirmed requirements of `requirements_version` with a versioned policy (`policy_version`, `algorithm_version`, `computed_at`). `status` is `computed`, `pending`, or `not_available` without a confirmed skill. The server may recompute them for the same `requirements_version`, for a new policy or a changed pool of candidates, without a new need version; `computed_at` and `policy_version` then change. -- Each category (`specialization` and `grade`) has `score`, `skill_overlap` (weighted share with weight 2 for required and 1 for desired skills, covered and uncovered skills), `money`, and `supply` as a band: `fewer_than_5`, `from_5_to_29`, `30_or_more`. The list order is the ranking. -- `money.status` is `computed`, `insufficient_data` (fewer than five candidates with a comparable known minimum), `no_salary`, or `withheld`; the last three use the neutral 0.5 and a null share. `money.share` is rounded down to a quarter (0, 0.25, 0.5, 0.75, 1): each probe of a new upper bound then tells at most which quarter of the group accepts it, and in the smallest allowed group of five a single minimum often does not move the value, while the share still separates a range that most candidates accept from one that few accept. -- `score` is `0.5 * Overlap + 0.3 * Money + 0.2 * Supply`, rounded half up to two decimals, computed from the published components: the exact overlap, the quarter-rounded share or the neutral 0.5, and `Supply = min(1, active / 30)`. It is null when `supply` is `fewer_than_5`. The ranking uses Supply only at band precision below five: every group of fewer than five candidates enters it with Supply 0, so neither the score nor the order reveals the exact size of a group below five, which FR08 forbids. For five or more candidates the exact Supply is used, so the recommendation fixture (Overlap 1, Money 0.5, 15 active candidates) gives `score` 0.75. -- Deviation from the PRD formula: the money share in the score and ranking is the quarter-rounded share, not the exact one, and a category with fewer than five candidates has no score. Otherwise the score with the exact share would reveal the share that `money.share` rounds, and a score with the exact Supply of a small group would reveal its size. The displayed breakdown consists of the published components. -- Requests cannot set a recommendation, its score, membership, or a candidate minimum: bodies have `additionalProperties: false`, and unknown fields such as `rec_score`, `members`, `candidate_minimum`, `version`, `requirements_version`, or `recommendations` answer 400 with the whole-body pointer. `TestNeedSchemaValidationPrecedesImplementation` checks the schema rejections through the generated server, `TestNeedUpdateDecodingKeepsAbsentAndEmptyListsApart` checks the list decoding, and `frontend/src/shared/api/needs-contract.test.ts` pins the generated Zod limits, the explicit status of every decision, and the absence of these fields in the request types. - -Planned, additive: reading and comparing versions, exclusions, the market range hint (P25-P75) of FR08, the check plan "vacancy -> tasks", a need status for archiving, list filters, and need assignments. - -### Support cases - -The `support` tag covers the cases of the current account (PRD FR18, with the manual assessment of FR04 and C3): questions to support, complaints, appeals of a grade or an anti-cheat decision, and manual assessment requests. The operations are implemented: a guest answers 401 `unauthenticated`, and a verified session passes request validation and the domain rules. Unsafe protected operations also require the session-bound CSRF token and exact Origin. - -| Method and path | operationId | Security | Success | Specific errors | -| --- | --- | --- | --- | --- | -| `GET /api/v1/me/support-cases` | `ListMySupportCases` | session | 200 `SupportCaseList` of `SupportCaseSummary`, `Cache-Control: no-store` | 400 `validation_failed`, 401 | -| `POST /api/v1/me/support-cases` | `CreateMySupportCase` | session and CSRF, Idempotency-Key | 201 `SupportCase`, `Cache-Control: no-store` | 400, 401, 403 `csrf_check_failed` or `forbidden`, 404 `not_found`, 409 `state_conflict` or `idempotency_in_progress`, 422 `idempotency_key_reused`, 429 | -| `GET /api/v1/me/support-cases/{case_id}` | `GetMySupportCase` | session | 200 `SupportCase`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 404 `not_found` | - -Every operation also declares the `default` problem response. - -Access: - -- The author is the account of the session; no request has a user, account, or organization field. PRD FR18 lets both candidates and company employees contact support, so `/me` serves both scenarios: an employer account opens `support` cases, and the other types answer 403 `forbidden` for it. A case belongs to the account that created it, not to an organization: other members of the same organization never see it. -- Another account's case answers 404 `not_found`, the same as an unknown identifier. The contract answers 404, so identifiers cannot be probed, and the client shows the same "not found" state for a foreign and an unknown case. The author reads the case whatever happened to the object since then, so a refused test or a revoked access never hides it. -- The moderation queues are separate staff operations with their own DTOs; they add nothing to these operations. - -Types and object references: - -| Type | Accounts | Object reference | Other fields | Response target | -| --- | --- | --- | --- | --- | -| `support` | candidate, employer | optional; `assessment_attempt` of the caller, an `organization` the caller can see, an `invitation` addressed to the caller, or another `support_case` of the caller | optional `assessment_target` | policy value | -| `complaint` | candidate | required; an `organization` the caller can see or an `invitation` addressed to the caller | required `complaint_reason` | policy value | -| `grade_appeal` | candidate | required; a terminal `assessment_attempt` of the caller, or a `support_case` of the caller of type `manual_assessment`, `resolved` with the outcome `assessed` | none | 10 business days | -| `anticheat_appeal` | candidate | required; an `assessment_attempt` of the caller with an anti-cheat review decision | none | 10 business days | -| `manual_assessment` | candidate | optional; a prior `assessment_attempt` of the caller in the same specialization | required `assessment_target`; the server fixes `rubric_version` | 5 business days | - -- The request is a `oneOf` of five variants selected by `type` (`SupportCaseCreateSupport`, `SupportCaseCreateComplaint`, `SupportCaseCreateGradeAppeal`, `SupportCaseCreateAnticheatAppeal`, `SupportCaseCreateManualAssessment`). Each variant restricts its reference schema, so the schema already rejects an organization in a grade appeal or a case in a complaint with the pointer `/object/type`, and a missing field of the type with its pointer, such as `/object` or `/assessment_target`. ogen selects the variant by the value of `type`. An unknown or missing type and a field of another variant such as `complaint_reason` in a support case answer 400 with the whole-body pointer `""`, because they concern the top-level variant; an `object.id` that is not a UUID answers 400 with `/object/id` (example `SupportCaseMalformedReference`). -- A category assigned without an attempt is appealed too (FR18): a grade appeal may reference the caller's own manual assessment case once it is `resolved` with `assessed`. An unknown case and another account's case answer 404 `not_found`; an own case of another type, not resolved yet, or resolved with another outcome answers 409 `state_conflict`. -- An organization is visible to a candidate that it invited or whose profile the organization contract shows to the candidate, and to an employer account with an active membership. The server checks every reference against the session account: an unknown object and someone else's object both answer 404 `not_found`, so a reference never reveals whether a foreign object exists. The case stores only `{type, id}`. -- Invitations are in the contract (see Invitations and contact grants below) but not implemented, and anti-cheat review decisions are not in the contract yet. Until they are implemented, every `invitation` reference answers 404 and every anti-cheat appeal answers 409 `state_conflict`; the request shapes stay the same. -- `offer_content` and `salary_terms_violation` complaints require an invitation; another object answers 400 with the pointer `/object/type` (a domain rule after the schema). -- A failed first test or no attempt at all never blocks a manual assessment. Creating a case never grants, revokes, or changes a consent, a grade, or an attempt; a manual assessment does not depend on C3. A candidate who revoked C3 (`DELETE /api/v1/me/consents/c3`) or never gave it creates the same request, and the request neither reads nor changes the consent ledger. A retry with the same `Idempotency-Key` returns the original case; a new key (for example after a page reload) while a manual assessment of the same specialization is open answers 409 `state_conflict`, and the open case stays the only one. `rubric_version` is `null` when the target has no single current reviewed category; the server does not guess a rubric, and the case still waits for an expert with no automatic result. - -Content and fields the client never sets: - -- `description` is plain text of 1-4000 characters with at least one character that is not white space (`pattern: \S`); line breaks are allowed. ogen converts `\S` to the ECMAScript white space set, so the Go server and generated Zod both reject an empty text or one of spaces such as U+00A0 or U+3000 with the pointer `/description`. ECMAScript white space omits U+0085 (NEL), which Go `unicode.IsSpace` includes, so the implementation adds a domain check: a description whose every character is `unicode.IsSpace` or U+FEFF answers 400 with the pointer `/description`; Zod accepts it and the server stays authoritative. The server stores the text as written and never writes it to logs or notifications. -- Every variant has `additionalProperties: false`. The client cannot set the status, the decision or its outcome, the priority, the response target, the rubric, the assignee, the moderator, or a contact: such fields, for example `status`, `decision`, `moderator_id`, `response_target`, `rubric_version`, or `reply_to`, answer 400 with the whole-body pointer. - -Case: - -- `number` is a human-readable number assigned on creation, `SC--` with at least six digits, for example `SC-2026-000123`. The sequence is global and never reused, so the number is unique and never changes. The API addresses a case only by its UUID `id`; the number is for letters and calls. A global sequence tells the approximate number of cases created so far, which is acceptable for the MVP. -- `status` is `submitted`, `in_review`, `waiting_for_user`, `waiting_expert`, `resolved` (terminal, with `decision`), or `closed` (terminal, without a decision on the merits, for example a duplicate). Only the server changes it. `waiting_for_user` is in the enum but not set yet: it starts with the planned operation that lets the author reply. An appeal and a manual assessment move to `waiting_expert` by a `system` event in the same transaction as their creation, so the 201 already shows it; they stay there until a person decides. -- `response_target` is the response deadline of FR18: `kind` `operational_goal` (a goal of the team, not a deadline set by law), `business_days`, `due_at` from the configured business calendar, `answered_at`, `late`, and `policy_version`. For `support` and `complaint` the first public reply, a decision, or a closure meets it; for the appeals and `manual_assessment` only a decision or a closure. Missing it never closes the case or changes a grade. -- `decision` is null until `resolved` and then holds `outcome` (`upheld`, `partially_upheld`, `not_upheld`, `answered` for support, `assessed` for a manual assessment), the public `reason`, and `decided_at`. An upheld grade appeal never rewrites the original result; the corrected result is a separate decision of the assessment. -- `history` lists every public event in order, starting with `created`: `kind` (`created`, `status_changed`, `reply`, `decision`), `actor` by kind only (`user`, `support`, `system`), `occurred_at`, the resulting `status`, and a public `message`. It is never truncated. Server invariant: a case holds at most 200 events, and the server rejects a staff reply or status change that would leave no room for the terminal event, so every case fits and can still be resolved or closed; further correspondence goes into a new case that references it as `support_case`. A truncation flag with paginated events was rejected: it would make the full case depend on a second read, while human staff cannot realistically produce 200 public events on one case. -- A case never contains the identity of a moderator, an expert, or a support agent, internal notes, evidence, assessment answers, anti-cheat or risk signals, or contact data of another person. -- Replies reach the user through the case. The server may also notify the verified email address of the account with the number and a link, never with the description, the reply, or assessment details; no request field names another address, so the operation cannot send mail to an address that the user typed. -- `ListMySupportCases` returns `SupportCaseSummary` items, newest first, with cursor pagination: the number, type, status, object reference, category, response target, `decision_outcome`, and timestamps, without the description and the history. The full case comes only from `GetMySupportCase`. - -Commands and limits: - -- Create requires Idempotency-Key with the 24-hour replay: a retry returns the 201 snapshot stored at creation, with the same case and number, following the repository convention; the client reads the current state with `GetMySupportCase`. 404 and 409 `state_conflict` are stored and replayed; 400, 403, and 429 are not. -- An attempt and a resolved manual assessment each accept at most one grade appeal, and an attempt at most one anti-cheat appeal, in any status; a disagreement with the decision goes into a support case that references the appeal as `support_case`. A specialization accepts one open manual assessment and an object one open complaint. A second one, and a grade appeal of an active attempt, answer 409 `state_conflict`. -- Every create that passed authentication, validation, and the account scenario counts against a per-account limit from the product policy, including replays, 404, and 409, so the limit also bounds probing of references; over the limit the server answers 429 with `Retry-After`. -- Order of checks for create: session (401), CSRF and Origin (403), request validation (400), account scenario (403 `forbidden`), the per-account case limit (429), the Idempotency-Key (422, 409 `idempotency_in_progress`, replay), domain rules (400), the object reference (404), then the state and the limits (409 `state_conflict`). The general rate limit can answer 429 before any check. -- No new problem code is added: the `ProblemCode` enum is copied byte-for-byte into the ML contract. An unavailable anti-cheat appeal and a repeated appeal both use 409 `state_conflict`, and the case or the attempt tells the client why. -- `TestSupportCaseSchemaValidationPrecedesImplementation` checks the schema rejections through the generated server, and `frontend/src/shared/api/support-contract.test.ts` pins the generated Zod rules, the absence of status, decision, moderator, and contact fields in the request types, and the absence of moderator identity and internal fields in the case and the summary. - -Open product question for manual assessment: whether repeated manual assessments of the same category follow the retest rules of FR04 (the same grade after 30 days, at most three attempts in 180 days) or their own rule. The contract only allows one open manual assessment per specialization and invents no interval. - -Open questions for manual assessment after a C3 refusal: whether the request needs a structured reason (for example a "C3 refused" marker) instead of the free-text `description`; whether a target with two current categories for the same specialization and grade (different task languages) should get a rubric chosen by language instead of `null`; whether a repeat with a new key should return the existing open case instead of 409. The contract invents none of these. - -Planned, additive (a new operation or an optional field): replies of the author, attachments, withdrawal of a case, list filters by status and type, the resulting category of a manual assessment in the decision, a next step for the author, staff queues and decisions, and the pause rules of the response target. - -Planned contract changes (new enum values; like the catalog codes, generated clients reject an unknown value, so each one is released with regenerated clients): object types `vacancy` and `application` for the vacancies and protected applications of FR16, and an object type for the profile analysis findings. `waiting_for_user` and `support_case` are already in the enums, so the reply operation and follow-up cases need no such change. No new event kind or actor kind is planned: an author reply is a `reply` with the actor `user`, a decision revision is another `decision` event, and experts and moderators are `support`. - -### Invitations and contact grants - -The `invitation` tag covers invitations from an organization to one candidate (PRD FR12, with the salary rules of FR13 and the consent C4): drafts with complete terms, immutable terms versions, sending, the candidate's inbox, the view, acceptance with C4, structured declines, withdrawal, cancellation, and the contact grant. The organization side of the draft is implemented: `ListOrganizationInvitations`, `CreateOrganizationInvitation`, `GetOrganizationInvitation`, and `UpdateOrganizationInvitation` follow the rules below, except that `salary_fit` is always `not_available` and the salary limit and the withheld counter are not enforced yet ([backend](../backend/README.en.md#invitation-drafts)). `SendOrganizationInvitation` and `ListMyInvitations` are implemented as well: the send checks the owner, the key, the version, the state, the current visibility of the candidate, the pending limit of a need, and the 30-day pause after a decline, and only then charges the weekly organization quota; the pause after a no deal is not checked yet, because no operation produces that state; a success means the invitation is already in `ListMyInvitations`, and the notification and the email follow through the outbox ([architecture](../docs/en/ARCHITECTURE.md#sending-invitations)). `GetMyInvitation`, `ViewMyInvitation`, and `DeclineMyInvitation` are implemented as described below, with one limit: the cancellation is not implemented yet. A read and a view at or after the deadline first move a waiting invitation to `expired` with the reason `invitation_timeout` (the read records no view), and a late decline answers 409 `state_conflict`; a declined invitation has `contact_consent` and `contact_grant` null. `AcceptMyInvitation` is implemented as the rules below describe, but the contact read and the revocation of a grant are not implemented yet ([architecture](../docs/en/ARCHITECTURE.md#candidate-acceptance)). The business logic of the other operations is not implemented: a guest answers 401 `unauthenticated`, and a request with a verified session reaches 501 `not_implemented` after request validation. Unsafe protected operations also require the session-bound CSRF token and exact Origin. - -| Method and path | operationId | Security | Success | Specific errors | -| --- | --- | --- | --- | --- | -| `GET /api/v1/organizations/{org_id}/invitations` | `ListOrganizationInvitations` | session | 200 `OrganizationInvitationList` | 400, 401, 403 `forbidden`, 404 | -| `POST /api/v1/organizations/{org_id}/invitations` | `CreateOrganizationInvitation` | session and CSRF, Idempotency-Key | 201 `OrganizationInvitation` (`draft`) | 400, 401, 403, 404, 409 `idempotency_in_progress`, 422, 429 | -| `GET /api/v1/organizations/{org_id}/invitations/{invitation_id}` | `GetOrganizationInvitation` | session | 200 `OrganizationInvitation` | 400, 401, 403, 404 | -| `PATCH /api/v1/organizations/{org_id}/invitations/{invitation_id}` | `UpdateOrganizationInvitation` | session and CSRF | 200 `OrganizationInvitation` | 400, 401, 403, 404, 409 `state_conflict`, 412, 429 | -| `POST .../invitations/{invitation_id}/send` | `SendOrganizationInvitation` | session and CSRF, Idempotency-Key | 200 `OrganizationInvitation` (`delivered`) | 400, 401, 403, 404, 409, 412, 422, 429 | -| `POST .../invitations/{invitation_id}/salary-raise` | `RaiseOrganizationInvitationSalary` | session and CSRF, Idempotency-Key | 200 `OrganizationInvitation` | 400, 401, 403, 404, 409, 412, 422, 429 | -| `POST .../invitations/{invitation_id}/withdraw` | `WithdrawOrganizationInvitation` | session and CSRF, Idempotency-Key | 200 `OrganizationInvitation` (`withdrawn`) | 400, 401, 403, 404, 409, 412, 422, 429 | -| `GET .../invitations/{invitation_id}/contacts` | `GetOrganizationInvitationContacts` | session | 200 `ContactDisclosure` | 400, 401, 403, 404 | -| `GET /api/v1/me/invitations` | `ListMyInvitations` | session | 200 `CandidateInvitationList` | 400, 401, 403 | -| `GET /api/v1/me/invitations/{invitation_id}` | `GetMyInvitation` | session | 200 `CandidateInvitation` | 400, 401, 403, 404 | -| `POST /api/v1/me/invitations/{invitation_id}/view` | `ViewMyInvitation` | session and CSRF | 200 `CandidateInvitation` (`viewed`) | 400, 401, 403, 404, 429 | -| `POST /api/v1/me/invitations/{invitation_id}/accept` | `AcceptMyInvitation` | session and CSRF, Idempotency-Key | 200 `CandidateInvitation` (`accepted`) | 400, 401, 403, 404, 409, 412, 422, 429 | -| `POST /api/v1/me/invitations/{invitation_id}/decline` | `DeclineMyInvitation` | session and CSRF, Idempotency-Key | 200 `CandidateInvitation` (`declined`) | 400, 401, 403, 404, 409, 412, 422, 429 | -| `POST /api/v1/me/invitations/{invitation_id}/cancel` | `CancelMyInvitation` | session and CSRF, Idempotency-Key | 200 `CandidateInvitation` (`cancelled_by_candidate`) | 400, 401, 403, 404, 409, 412, 422, 429 | - -Every success has `Cache-Control: no-store`, and every operation also declares the `default` problem response. The paths `...` start with `/api/v1/organizations/{org_id}`. 403 on an unsafe operation is `csrf_check_failed` or `forbidden`; 409 on a command is `state_conflict` or `idempotency_in_progress`; 412 is `version_conflict`; 422 is `idempotency_key_reused`. 429 on a command is the general rate limit with Retry-After, which can answer before any check; on create, update, and send it is also the salary limit or the weekly quota. The contact read and the plain reads declare no 429 of their own, like the other reads of the contract. - -Access: - -- Organization side: `org_id` in the path is the only source of the organization, checked against the active membership of the session account, as for needs. An account without the membership, an unknown organization, an unknown invitation, and an invitation of another organization all answer 404 `not_found`; a candidate account and a member whose role does not allow the operation answer 403 `forbidden`. In the MVP only the owner works with invitations; the other roles of FR07 are planned. -- Candidate side: `/me/invitations` is bound to the session account. A draft, an invitation addressed to another candidate, and an unknown identifier answer 404 `not_found`; an employer account answers 403 `forbidden`. No request has a user, candidate, organization, or role field. -- The candidate is named only by `candidate_handle` (`CandidateHandle` in `common_schemas.yml`, shared with the search results of FR11), never by an email address, a phone number, or an account or profile identifier. An unknown handle, a handle of another organization, and a profile that the organization may no longer see all answer 400 with the pointer `/candidate_handle`. - -Terms (`InvitationTerms`): - -- The terms are complete from the first draft and every field is required: `role_title`, `specialization`, `grade`, `offer_type` (`full_time`, `part_time`, `contract`, `internship`), `tasks`, `team`, `tech_stack`, `work_formats`, `location` (null only for a remote-only role; required for `office` or `hybrid` by a domain rule with the pointer `/terms/location`), `communication_method` (`channel` and an optional note), `salary` (`SalaryRange`), and `package`. A draft without the tax basis or the communication method therefore cannot exist: such a body answers 400 `required` with `/terms/salary/tax_basis` or `/terms/communication_method` (examples `InvitationWithoutTaxBasis` and `InvitationWithoutCommunicationMethod`). -- `package` has `bonus`, `equipment`, `training`, and `health_insurance` (ДМС). Each is a `oneOf`: `{status: provided, description}` or `{status: not_provided}` ("Не предусмотрено" in the interface). "Not provided" is an explicit choice: a condition left out answers `required` with its pointer, such as `/terms/package/training`; a `provided` one without a description answers `required` at its `description`; a `not_provided` one with a description answers `invalid` at the item. Generated Zod is not strict and strips that description, so only the server rejects it. -- Deliberate deviation from the wording of the acceptance criteria: the PRD package lists the work format next to the bonus, equipment, training, and ДМС, but here the format is the required `work_formats` term without a "not provided" variant, because a role always has a format and the indicator and the search compare it. This is an open question for the product owner. -- The same schema is the request field and the stored snapshot, so a response can be sent back unchanged. The terms never contain data of the candidate. - -Versions and conflicts: - -- `version` advances with every committed change, including the view and the server expiry. `terms_version` advances only when the terms change: a draft change of `terms`, or the one raise of the upper bound after sending. Each terms version is immutable. -- Every command except the view carries `expected_version`; `AcceptMyInvitation` also carries `terms_version`. 412 `version_conflict`: `expected_version` or, on acceptance, `terms_version` is not current (the stale terms case, example `InvitationStaleTerms`); nothing changed, nothing is stored under the key, and the client reads the invitation again. 409 `state_conflict`: the state does not allow the command, for example an acceptance of a withdrawn or expired invitation, a command at the deadline or later, a send blocked by the pending limit of a need or by the 30-day pause, a change of a sent invitation, or a second raise; it is stored under the key. The repository rule keeps 412 for any stale version, as for needs and the questionnaire. -- Order: after the invitation is found and a due expiry is applied, and after the repeat check, a terminal state (`declined`, `expired`, `withdrawn`, `cancelled_by_candidate`) or, for accept and decline, a passed deadline answers 409 before the version is compared, so the client gets 409 for a withdrawn, expired, or late invitation even with stale versions and shows the final state instead of rereading and retrying. Then come the versions (412) and the remaining state rules (409). This applies to accept, decline, cancel, withdraw, and the salary raise. -- Repeats return the same result: a retry with the same Idempotency-Key replays the stored outcome, and a repeated command whose transition already happened answers 200 with the current invitation even with a new key or an older version: a send of a sent invitation, a withdrawal of a withdrawn one, a decline with the same reason and comment, a cancellation of a cancelled one, the same raise, and an acceptance whose `terms_version` and fields equal those of `contact_grant`, the version and fields the candidate accepted, even when a later raise advanced the current `terms_version`. No second consent, grant, quota charge, or audit event is created. -- `UpdateOrganizationInvitation` follows the convention of `UpdateOrganizationNeed`: no Idempotency-Key, explicit field replacement, and a body that changes nothing answers 200. - -States and the view: - -- `InvitationState` lists every state of the FR12 table: `draft`, `delivered`, `viewed`, `counter`, `accepted`, `interview_scheduled`, `interviewed`, `negotiation`, `terms_agreed`, `no_deal`, `declined`, `expired`, `withdrawn`, `cancelled_by_candidate`. MVP operations produce `draft`, `delivered`, `viewed`, `accepted`, `declined`, `expired`, `withdrawn`, and `cancelled_by_candidate`; the others are listed now so that generated clients accept them when the counter offer, the interview, and the sealed final arrive. The internal `SENT` step is never visible: a send answers with `delivered` after the inbox entry exists. -- `expiry_reason` is `invitation_timeout` or the planned `negotiation_timeout`, non-null exactly in `expired`. -- The view is an explicit command, `ViewMyInvitation`: it moves `delivered` to `viewed`, keeps the deadline, and returns the current invitation unchanged in any other state. It is idempotent by its effect, so it needs neither an Idempotency-Key nor an `expected_version`, and it never fails because the invitation changed after the client read it. `GetMyInvitation` and `ListMyInvitations` have no side effect; a read only shows a due expiry, which the server applies at the deadline anyway. The command keeps prefetches, retries, and cache refreshes from changing the state that the organization sees. -- `withdrawn` is the organization's command from any unfinished state, including `draft` and `accepted`, and keeps an existing grant. `cancelled_by_candidate` is the candidate's command from any unfinished state after delivery and revokes the grant of this invitation. A decline is the structured answer before an acceptance. -- The deadline is `delivered_at + response_period_days` (3, 7, or 14 days, 7 by default). A view, an email, or a raise never moves it; a command received at the deadline or later is late. - -Salary and the hidden minimum: - -- The terms reuse `SalaryRange` with the rules of the Needs section: RUB, month, `net` or `gross`, positive multiples of 1000, `A < B`, and a width of 10-40%, checked by the server with the pointer `/terms/salary/salary_to`. -- The organization receives only `salary_fit`: `within_range`, `up_to_10_percent_above`, `above`, `withheld`, or `not_available` (no minimum for the offered formats, or one in the other tax basis). The exact minimum appears in no response, example, log, or problem. The server never rejects a range because of the minimum, since a rejection would reveal it. The candidate DTOs carry no indicator; the candidate compares with the own minimum in the profile. -- Every change that can move the indicator is an indicator-relevant setting: the range on creation, and in a draft a change of either bound, of the tax basis, or of `work_formats`, because the indicator compares with the minimum for the offered formats. Each counts against the organization-wide limit of three settings a day, shared with the ranges of needs (429 with Retry-After), and against the withheld counter. A change that keeps the range, the basis, and the formats does not count. -- `withheld`: after five indicator-relevant settings within seven days the indicator is off for seven days from the fifth. The response to the fifth setting already shows `withheld`, and so does every draft and invitation of the organization, existing ones included, until the period ends. -- Switching the tax basis turns `not_available` into a band or back and so tells the organization the basis of the minimum; this is accepted, and the switch counts against the limit like any other setting. -- After a send the base is fixed and the lower bound never decreases. `RaiseOrganizationInvitationSalary` raises `salary_to` once in the whole history of the invitation, creates the next terms version, and answers 409 on a second raise. It follows its own once-only rule and does not count against the daily limit, but it counts against the withheld counter because it moves the upper bound that the indicator compares. - -Consent C4 and the contact grant: - -- `GetMyInvitation` shows in `contact_consent` the C4 text for this organization and the kinds of contact that the profile holds. It is null when an acceptance is impossible: the state or the deadline does not allow it, or the profile holds no contact. In the last case the client asks the candidate to add a contact first, because a grant must cover at least one field. -- `AcceptMyInvitation` sends `terms_version`, `expected_version`, and `consent_c4` (`ContactConsentAcceptance`): the shown C4 text version, `accepted: true`, and `fields`, at least one of `full_name`, `email`, `phone`, `telegram`, with no default and no preselection. A text version that is not published answers 400 `/consent_c4/text_version`, and a field the profile does not hold answers 400 `/consent_c4/fields/`. The consent is analogous to the C1 acceptance by its `text_version`, and the record matches the C4 consent ledger (purpose, text version and hash, organization, field set, source invitation). The permission to pass the data on to the organization's ATS (C4 and FR19) is planned as an additive optional flag that defaults to no transfer. -- In one transaction the acceptance moves the invitation to `accepted`, records C4, creates the grant for exactly the selected fields, and writes the audit event. It never publishes the profile (C2) and never lifts a hiding. -- The candidate's `contact_grant` has `status` (`active` or `revoked`), `readable`, and `blocked_by`. A grant created while the profile was not published or was hidden from the organization stays `active` with `readable: false` and `blocked_by: visibility`, so the candidate sees why the organization cannot read it (PRD FR12); it becomes readable once the candidate publishes the profile or unhides it. Any visibility change after the grant exists revokes it (`visibility_closed`), and a later publication never reopens it. -- Contact values travel only in `ContactDisclosure` from `GetOrganizationInvitationContacts`, separate from the terms and the invitation. Each read checks the membership, C4, the grant and its fields, and the current visibility, without a cache. Without a readable grant the operation answers 404 `not_found`, the same as an unknown invitation. The organization's `contact_access` is `not_granted` (no grant), `available` (with the field kinds), or `closed`, which covers a revoked grant and a grant blocked from the start without saying which. This is the least revealing rule: a revocation, a hiding, and a missing publication look the same, and since every visibility change after the grant revokes it, the organization never observes a later toggle; only a grant blocked from the start can turn `available`, by the candidate's own choice. Fields that the grant does not cover are null. -- Revocation: `CancelMyInvitation` revokes the grant of this invitation (`participation_cancelled`); revoking C4 for the organization closes all its grants (`consent_revoked`); revoking C2 or hiding the profile closes them (`visibility_closed`). A withdrawal, a no deal, and a negotiation timeout never revoke a grant; only a new explicit C4 creates a new one. A standalone grant revocation operation belongs to the consent contract. -- Implementation: the contact read, the C4 and C2 revocations, the closing of the publication, and hiding are implemented, owner only, and close the grants as the bullet above states (architecture: [Contact reads and revocation](../docs/en/ARCHITECTURE.md#contact-reads-and-revocation)). The organization's `contact_access` is derived on every read of an invitation (`GetOrganizationInvitation`, the list, and the create, update, and send responses) with the checks of the contact read, so it shows `available` only where a read would succeed, and it never names a reason. `CancelMyInvitation` is not implemented yet. -- Value formats: a single-line full name of up to 200 characters, an E.164 phone number, and a Telegram username with the leading @. The profile contract (FR02) must store contacts in the same formats, so a disclosure never converts or drops a stored value. - -Decline and privacy: - -- `DeclineMyInvitation` takes `reason` (`salary`, `tasks`, `stack`, `work_format`, `package`, `company`, `not_looking`, `other_offer`, `other`) and an optional `comment` of up to 500 characters; `other` needs no comment. The organization sees only `declined` and `responded_at`, never the reason or the comment: a reason such as `salary` would tell it that the hidden minimum is above the range. Reasons feed only aggregates with a minimum group size (planned). The candidate reads both back in `decline`. -- No invitation DTO of either side carries the candidate's name, email address, phone number, Telegram username, account or profile identifier, or salary minimum; examples use synthetic data only. `TestInvitationSchemaValidationPrecedesImplementation` checks the schema rejections and pointers through the generated server, `TestInvitationDTOsCarryNoContactOrMinimum` checks the generated Go DTOs, and `frontend/src/shared/api/invitation-contract.test.ts` pins the generated Zod rules and, at the type level, the absence of contact, minimum, and decline fields. - -Open product questions: whether a second unfinished invitation of the same organization to the same candidate is allowed (the PRD is silent, so the contract invents no rule), the package format deviation above, the offer types, the contact kinds, and the decline reasons. - -Planned, additive: the counter offer and the company answer, reading earlier terms versions, interview and sealed final operations, list filters, the responsiveness metrics of the organization for the candidate, the approximate amount in the other tax basis, decline aggregates, the ATS flag of C4, and FSP fields as new contact kinds (a new enum value, released with regenerated clients). - -No new problem code is added: the `ProblemCode` enum is copied byte-for-byte into the ML contract, and `version_conflict` and `state_conflict` cover the stale terms and the state conflicts. - -### Consents - -The `consent` tag covers the consent ledger of the current account (PRD FR01, FR12, and 7.3): the independent consents C1-C5 with their text versions, sources, states, and revocations. Implemented handlers provide public C1 text, current settings text and the caller's own history, settings grants of C1/C2/C3/C5, revocation of C2/C3/C5, scoped C4 revocation for one organization, and a durable C1 account-deletion request. The request does not synchronously delete the account. Protected operations require an active verified PostgreSQL session; mutations also require the session-bound CSRF token and the sole `Origin` matching `APP_PUBLIC_URL`. Guests receive 401; a disallowed account role, Origin, or CSRF token receives 403. - -| Method and path | operationId | Security | Success | Specific errors | -| --- | --- | --- | --- | --- | -| `GET /api/v1/identity/consent-texts/c1` | `GetConsentText` | public | 200 `ConsentText` | 400 `validation_failed` | -| `GET /api/v1/me/consent-texts/{purpose}` | `GetMyConsentText` | session | 200 `ConsentText`, `Cache-Control: no-store` | 400, 401 | -| `GET /api/v1/me/consents` | `ListMyConsents` | session | 200 `ConsentRecordList`, `Cache-Control: no-store` | 400, 401 | -| `PUT /api/v1/me/consents/{purpose}` | `GrantMyConsent` | session and CSRF | 200 `ConsentRecord`, `Cache-Control: no-store` | 400, 401, 403 | -| `DELETE /api/v1/me/consents/{purpose}` | `RevokeMyConsent` | session and CSRF | 204 | 401, 403 | -| `DELETE /api/v1/me/consents/c4/organizations/{org_id}` | `RevokeMyOrganizationContactConsent` | session and CSRF | 204 | 400, 401, 403 | -| `POST /api/v1/me/account-deletion-requests` | `RequestMyAccountDeletion` | session and CSRF | 202 `ConsentDeletionRequest`, `Cache-Control: no-store` | 401, 403 | - -- Purposes (`ConsentPurposeCode`): `c1` personal data processing, `c2` publication of the candidate card, `c3` automatic categorization, `c4` transfer of selected contacts to one organization, `c5` import of FSP results. Public `GetConsentText` remains C1-only. `GetMyConsentText` returns the current C1/C2/C3/C5 text before a settings grant. C4 text remains part of an invitation with its specific scope. -- The subject comes from the session; no parameter names an account, so the response holds only the caller's own records. A page lists records newest grant first with cursor pagination; the optional `state` filter takes `active`, `superseded`, or `revoked`, and an unknown value answers 400 with the pointer `/state`. -- A `ConsentRecord` has the purpose, the accepted `text_version`, the `source` (`registration`, `consent_settings`, or `invitation_acceptance`), `granted_at`, the computed `state`, and `revoked_at` with `revocation_source` (`consent_settings` or `support_request`). A `c4` record also names the `organization` (`ConsentOrganization`, whose `name` is the snapshot the consent text showed, so a later rename does not change it), the contact `fields` (`ContactFieldKind`), the `invitation_id`, and the `invitation_terms_version`; they are null for every other purpose. A `c2` record proves the consent to the publication text; which fields were published, and when, is evidence of the publication history ([Candidate visibility](#candidate-visibility)), and a field scope on `c2` records would be an additive change. The record never carries a contact value, the subject, or the text hash: the server stores the SHA-256 of exactly the text the subject saw, and the client never sends or receives it, as for C1 at registration. -- Settings grants require explicit `accepted: true` and the current version of the text the user read. C1 is available to candidate and employer accounts; C2/C3/C5 are candidate-only. C4 is excluded from the general settings grant and is granted only when accepting a specific invitation. -- The ledger is append-only. A newer text version is a new record and the earlier one becomes `superseded` without changes; revocation stamps every unrevoked record of the purpose, including earlier versions. C4 revocation is limited to one organization and takes its fields from stored records, never from request data. Repeated revocation is harmless and creates no duplicate event. -- C2 revocation closes the current publication, clears its fields, appends privacy history, and writes a bounded outbox intent in one transaction. A later C2 grant does not reopen the old publication. C3 revocation does not block the manual assessment path. C5 revocation immediately closes the consent gate for future imports and writes a stop/delete intent; no external FSP adapter exists, so actual deletion at FSP is not claimed. -- A C1 deletion request revokes C1 and creates or returns an active durable request plus an outbox intent in one transaction. Repeats return the same request; a later C1 grant never cancels it. The future account-deletion processor is not synchronous and is not implemented yet. -- The C4 permission to pass data on to an ATS and the C4 of an application (PRD Q9) are planned as an additive flag and an additional `source` value. - -Open legal item: whether `c2` is a consent to the distribution of personal data under article 10.1 of 152-FZ, which requires its own consent with the categories of data. - -No new problem code is added: the contract uses `validation_failed`, `unauthenticated`, `forbidden`, and `csrf_check_failed`. Contract tests pin the security schemes and validation order, `TestConsentSettingsOverHTTP` exercises consent behavior with real PostgreSQL and Redis, and `frontend/src/shared/api/consent-contract.test.ts` pins generated Zod rules and the absence of hashes, subjects, and contacts from the DTOs. - -### Organizations - -The `organization` tag includes implemented creation, reading, editing, and the current account's organization directory. A verified employer creates an organization with an active owner; organization-scoped operations require an active owner on each request. Unsafe operations require the session CSRF token and exact Origin. The common middleware also protects unimplemented need and invitation operations before their 501 fallback. See [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#organizations-and-memberships). - -| Method and path | operationId | Security | Success | Specific errors | -| --- | --- | --- | --- | --- | -| `GET /api/v1/me/organizations` | `ListMyOrganizations` | session | 200 `MyOrganizationList`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `forbidden` | -| `POST /api/v1/organizations` | `CreateOrganization` | session and CSRF, Idempotency-Key | 201 `Organization`, `Cache-Control: no-store` | 400, 401, 403 `csrf_check_failed` or `forbidden`, 409 `idempotency_in_progress`, 422 `idempotency_key_reused`, 429 | -| `GET /api/v1/organizations/{org_id}` | `GetOrganization` | session | 200 `Organization`, `Cache-Control: no-store` | 400, 401, 403 `forbidden`, 404 `not_found` | -| `PATCH /api/v1/organizations/{org_id}` | `UpdateOrganization` | session and CSRF | 200 `Organization`, `Cache-Control: no-store` | 400, 401, 403 `csrf_check_failed` or `forbidden`, 404, 412 `version_conflict`, 429 | - -Every operation also declares the `default` problem response. A malformed `org_id` answers 400 with the path pointer. - -Active organization context: - -- The context is not stored on the server. Every organization-scoped operation, including the needs and invitations of this contract, names its organization in the path `org_id`, and the server checks that identifier against the active membership of the session account on every request. The identifier grants nothing; a switch between organizations is another `org_id` in the client's routes. -- Reason: a session attribute would be a cache of the membership that a removal, a suspension, or a leave would have to invalidate (the next read must be closed without waiting for the browser cache to expire), it would make two tabs in two organizations fight over one value, and the path form is already the contract of needs and invitations. Organization switching clears the tenant-scoped client queries on a switch, which fits a client-side context. -- `ListMyOrganizations` is the directory of contexts: the organizations where the caller has an `active` membership, newest membership first, with the caller's role and state. A client picks the context from it, may remember the last choice in the browser as a convenience, and reads the list again after a 404 from an organization path. A person with several memberships sees all of them and works in one at a time; the rights and the data of the organizations stay separate. - -Access: - -- An employer account only. A candidate account answers 403 `forbidden` on all four operations, and an account without a session answers 401. -- `GetOrganization` and `UpdateOrganization` answer 404 `not_found` for an account without an active membership in `org_id` and for an unknown organization alike, and also for a `suspended`, `removed`, or `left` member, so organizations cannot be enumerated and a revoked member loses the next read at once. A member whose role does not manage the organization answers 403 `forbidden` on `GetOrganization` and `UpdateOrganization`; the FR07 matrix gives managing the company and its staff to the owner only. In the MVP every member is an owner, because the operations that add members are planned. -- `CreateOrganization` creates the organization and the owner membership of the caller in one transaction (role `owner`, state `active`), so an organization never exists without an owner; the database refuses to commit one that has none. The body has no owner, role, membership, or verification field. - -Memberships: - -- A membership is `(user, organization, role, state)` and is unique per pair in any state. `OrganizationRole` has `owner`, `recruiter`, `hiring_manager`, and `technical_expert` (PRD 2.2 and Q3). `MembershipState` has `active`, `suspended` (access stopped, restorable), `removed` (ended by the owner or the platform), and `left` (ended by the member). Only `active` gives access, and the listing returns only `active` memberships; `joined_at` is the moment the membership was first created (a member who returns keeps it, and the latest activation time is a planned `activated_at` field); a membership `removed` by the platform must not be reactivated by the owner, by an invitation acceptance, or by the member management on their own, and who removed the member and why become additive fields of the member management; the other states are in the enum so that member management can show them without a contract change. Adding a role or a state is a contract change. -- The role lives in the membership only. `Organization`, `OrganizationCreate`, `OrganizationUpdate`, and `CandidateOrganizationCard` have no role, owner, or member field. The caller reads their own role in `OrganizationMembership` from `ListMyOrganizations`; the DTO names no account. -- There is no `invited` state: an employee joins only through an invitation to an email address (PRD 2.2), which the member-invitation tasks store as a separate record and turn into an `active` membership when the owner of the address accepts it. A person may hold independent memberships in several organizations. -- Applying the full role matrix (recruiter, hiring manager, technical expert) to needs, invitations, and contacts is planned as part of role-based access control. Until then the other roles grant nothing: the operations of needs and invitations answer 403 `forbidden` for them, as their sections say. Listing and managing members, changing roles, removing members, and the rule that the last owner cannot be removed are planned as part of membership management and add operations, not fields, to this contract. - -Profile: - -- `OrganizationCreate` requires only `name`. The profile fields are `name` (1-200 characters, no surrounding whitespace or line break, because a consent record keeps a copy), `description` (1-2000 characters, nullable, line breaks allowed), `sphere` (1-100 characters, nullable, free text: the PRD has no sphere taxonomy, and a taxonomy code would be an additive field), `contacts`, and `representatives`. -- `contacts` is one object with `website`, `email`, `phone`, and `telegram`, all required and nullable, so it is the request field and the stored value alike. They are public company channels: an https website without credentials, a port, or an IP address, a careers mailbox, an E.164 phone number, and a Telegram username with the leading `@`. The contract holds no personal contact of an employee, and the server cannot tell a personal address from a company one, so the owner answers for the content; a complaint about an organization goes through a support case. The server never fetches the website. -- `representatives` is a list of up to ten `{name, job_title}` entries in the order the owner gave them. A representative is presentation only: not a member, with no account link, no contact, and no right, and a member does not become one by joining. The name is personal data of an employee that the owner publishes, which makes the open question below. -- `UpdateOrganization` uses explicit field replacement, as `UpdateOrganizationNeed` does: a present field replaces that field as a whole, an absent field stays unchanged, and `contacts` and `representatives` are never merged. `description` and `sphere` sent as null become unset; `name`, `contacts`, and `representatives` cannot be null. ogen generates `OptNil` values for the nullable fields and a plain slice for `representatives`, where nil is absent and `[]` is an empty replacement; a handler must test it with `!= nil`, never with `len` (`TestOrganizationUpdateDecodingKeepsAbsentAndEmptyListsApart`). -- Text is plain: clients show every field as text, never as HTML. Domain rules that need more than the schema, such as the host rules of the website, answer 400 with a pointer (`/contacts/website`, `/representatives/0/job_title`); the examples show the shapes. - -Verification level: - -- `OrganizationVerificationLevel` is `e0`, `e1`, `e2`, or `e3` (PRD FR07). A new organization starts at `e0` on the basis `confirmed_email`, whatever its profile looks like. The server reports a higher level only after a verification process recorded it; the processes for `e1`, `e2`, and `e3` do not exist yet (the planned verification flow adds E0/E1 with evidence, a scope, and a history), so a client treats every level but `e0` as unavailable and the contract never reports `e1`, `e2`, or `e3` as reached on its own. -- No request sets or raises a level or its basis: `OrganizationCreate` and `OrganizationUpdate` are closed objects with only the profile fields, no operation of the contract changes the level, and editing the description, the contacts, or the representatives leaves it as it is. The database keeps the level and the basis in their own columns that the profile statement never writes, and a CHECK ties each level to its own bases. `OrganizationVerification` is read-only: `level`, `basis`, and `changed_at`; the scope of the check and the history of changes (PRD FR07) arrive as additive fields with the first process. -- The level selects the quota tier (E0 10 invitations and 50 cards, E1 40 and 150, E2 100 and 400 in the demo policy); `domain.OrganizationVerificationLevel.QuotaTier` maps `e0` to `e2` to the tiers of the policy and has none for `e3`, which the PRD gives a separate policy. Quota enforcement is a separate planned feature. - -Candidate card and versions: - -- `Organization.candidate_card` is the card as a candidate sees it, built by the server from the profile and the level: the preview of PRD FR07. Only a candidate who received an invitation from the organization sees it; it is not a public page, and no operation shows it to anyone else until the question about the names of representatives below is decided. It repeats the profile fields and adds the level only; it has no membership, role, account, version, or basis. Its `representatives` is optional and nullable: absent or null means that they are not published, not that there are none. The invitation contract names the organization with `InvitationOrganization` and plans to return this card to the candidate additively. -- `version` starts at 1 and advances with every committed change of the profile. A change carries `expected_version` in the body for the reason the needs give: the generated client cannot read `ETag` yet. A stale value answers 412 `version_conflict` and changes nothing; the repository rule keeps 412 for a stale version, as for needs. A body that changes nothing answers 200 with the current organization, so PATCH needs no Idempotency-Key. POST needs one with the 24-hour replay; only the 201 is stored. -- Order of the checks of `UpdateOrganization`: session (401), CSRF and Origin (403), request validation (400), account scenario (403), membership (404) and role (403), a body that changes nothing (200), the version (412), domain rules (400). - -Foreign keys to organizations: `memberships` and `organization_representatives` reference `organizations(id)` now. The consent ledger, the needs, and the invitations carry an `organization_id` and reference it with a restricting foreign key in the migration that creates the invitation records, because the C4 scope needs both references at once and the consent ledger tests use synthetic organization identifiers. The application never deletes an organization. - -Open questions for the product owner: - -- Representatives: may the card show their names to every candidate before an invitation is accepted, and who answers for the right to publish an employee's name (152-FZ)? The alternative is to show representatives only in an invitation sent by their organization. -- Sphere: free text now; a taxonomy for the sphere, matching the domains of needs, is a decision for the search filters. -- Contacts: whether the card needs a fifth kind, such as a careers page, and whether the email must share the domain of the website. - -Decided by the product owner: organizations per account are not limited. The organizations of one account form a holding, and the E0 quotas (in the demo policy 10 invitations per 7 days and 50 distinct card views per 24 hours) are shared by the E0 organizations of that holding; an organization at E1 and above counts its own quotas. The contract does not change: the holding is internal and no operation exposes it. - -Planned, additive: member invitations, listing, role changes, and removal, the full role matrix, the verification processes and their history, the quotas by level, the card in the candidate's invitation, and a sphere code. - -No new problem code is added: the contract reuses `validation_failed`, `unauthenticated`, `forbidden`, `csrf_check_failed`, `not_found`, `version_conflict`, `idempotency_in_progress`, `idempotency_key_reused`, and `rate_limited`. `TestOrganizationSchemaValidationPrecedesImplementation`, `TestOrganizationAccessBeforeImplementation`, `TestOrganizationDTOsCarryNoRoleOrVerificationInTheirRequests`, `TestOrganizationUpdateDecodingKeepsAbsentAndEmptyListsApart`, and `TestOrganizationContractFollowsThePRD` pin the generated server and the bundle, and `frontend/src/shared/api/organization-contract.test.ts` pins the generated Zod rules and, at the type level, the absence of role, owner, member, and verification fields in the requests. - -### Candidate visibility - -The tag `privacy` describes what organizations may see of the current candidate: the publication of the anonymous card, the search status, the organizations the candidate hides the profile from, a preview, and two histories (FR02 and FR12 in the PRD). The operations are in the contract but their business logic is not implemented: a guest answers 401 `unauthenticated`, and a request with a verified session reaches 501 `not_implemented` after request validation. Unsafe protected operations also require the session-bound CSRF token and exact Origin. The storage behind them exists (migration 00015, see [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#candidate-visibility)). - -| Method and path | operationId | Protection | Success | Specific errors | -| --- | --- | --- | --- | --- | -| `GET /api/v1/me/privacy` | `GetMyPrivacySettings` | session | 200 `PrivacySettings`, `Cache-Control: no-store` | 401, 403 `forbidden` | -| `PUT /api/v1/me/privacy/publication` | `SetMyPublication` | session and CSRF | 200 `Publication`, `Cache-Control: no-store` | 400, 401, 403 `csrf_check_failed` or `forbidden`, 409 `state_conflict`, 412 `version_conflict` | -| `GET /api/v1/me/privacy/preview` | `GetMyCardPreview` | session | 200 `CardPreview`, `Cache-Control: no-store` | 401, 403 | -| `PUT /api/v1/me/privacy/search-status` | `SetMySearchStatus` | session and CSRF | 200 `SearchStatus`, `Cache-Control: no-store` | 400, 401, 403, 412 | -| `GET /api/v1/me/privacy/hidden-organizations` | `ListMyHiddenOrganizations` | session | 200 `HiddenOrganizationList`, `Cache-Control: no-store` | 400, 401, 403 | -| `PUT /api/v1/me/privacy/hidden-organizations/{org_id}` | `HideOrganization` | session and CSRF | 200 `HiddenOrganization`, `Cache-Control: no-store` | 400, 401, 403, 404 `not_found`, 409 `state_conflict`, 429 | -| `DELETE /api/v1/me/privacy/hidden-organizations/{org_id}` | `UnhideOrganization` | session and CSRF | 204 | 400, 401, 403 | -| `GET /api/v1/me/privacy/history` | `ListMyPrivacyHistory` | session | 200 `PrivacyEventList`, `Cache-Control: no-store` | 400, 401, 403 | -| `GET /api/v1/me/privacy/access-history` | `ListMyCardAccessHistory` | session | 200 `CardAccessList`, `Cache-Control: no-store` | 400, 401, 403 | - -Each operation also declares the problem response `default`. No new problem code is added: the contract uses `validation_failed`, `unauthenticated`, `forbidden`, `csrf_check_failed`, `not_found`, `state_conflict`, `version_conflict`, and `rate_limited`. An employer account answers 403 `forbidden` on all nine operations. - -Closed by default and three independent settings: - -- A profile is closed by default. A candidate who never published reads `publication.state` `closed`, `closed_reason` `never_published`, an empty field set, and version 0; saving the profile, filling in the questionnaire, or taking an assessment never publishes it. Every setting has its own `version` (0 is "never set"), its own operation, and its own `expected_version` in the body, so a change of one never makes another stale. -- The publication and C2 are separate. The consent C2 stays in the consent ledger (`ListMyConsents`) and proves that the candidate accepted the publication text. `Publication` records which fields are published and when, and refers to the C2 record behind them (`consent_id`, the `id` of a `ConsentRecord` of the same account). It does not duplicate the consent: `state` is `published` only while that record is unrevoked, so a revocation of C2 closes the card at once, and `closed_reason` says `consent_revoked`. A new C2 grant never reopens it: the candidate publishes again and the new publication binds to the new record. The body of `SetMyPublication` names no consent: the server binds the current unrevoked C2 record of the account, and without one answers 409 `state_conflict` (the candidate gives C2 first; the grant operation is planned in the consent settings). -- The search status is not a consent. `SearchStatus` and `SearchStatusUpdate` have no consent, publication, or organization property, no schema of one family reaches another (a test walks the references), and `SetMySearchStatus` changes nothing but the status. A candidate whose profile is closed who sets `looking` becomes visible to no one. -- Hidden organizations are records of the candidate (`HiddenOrganization`: the organization with its current name and `hidden_at`). One record per candidate and organization, at most 1000 per candidate. An organization never reads them, never learns that it is hidden, and sees a hidden candidate exactly as it sees one who is not published. Hiding and lifting a hiding change neither C2, nor the publication, nor the search status. -- Hiding is a PUT of a state, so it is idempotent and takes no Idempotency-Key: hiding an organization again answers 200 with the original record and writes no history. Lifting is a DELETE that answers 204 whether the organization was hidden or not. - -The search status and its 30 days: - -- `looking` ("Ищу") stores `confirmed_at` and `lapses_at`. The interval is not a constant of the contract or the code: it is `search_status.searching_confirmation_interval_days` of the effective `product` policy version (30 in the demo version 1), read when the status is confirmed. The stored row names the policy version it used and fixes `lapses_at`, so a later policy change moves no stored time. The owner changes the interval by publishing a new policy version. -- After `lapses_at` the status holds as `not_looking` with `lapsed` true. The lapse is computed on every read and never written, so it needs no job and can only narrow: it never publishes, never unhides, and never changes C2 or the hidden organizations. The candidate confirms again with `SetMySearchStatus` and `looking`, which replaces `confirmed_at` and advances the version. A reminder before the lapse is a planned notification. -- A lapsed status is never "more public": the non-public `not_looking` is the only state a lapse reaches. Whether `looking` gates the appearance of a published card in search results is a search contract decision, not decided here. - -The anonymous card and the preview: - -- `CardField` is a closed set of groups of card values that the candidate chooses to publish: `categories` (the categories confirmed by assessment results), `stack`, `experience` (total months), `soft_skills`, `location`, and `relocation`. The full name, any contact, and the lowest salary have no value, so no request can publish them; contacts reach an organization only through the contact grant of an accepted invitation (C4), and the lowest salary never does. A self-assessed grade is not a category and is never published. The server stores and answers the set in ascending order of the codes. -- `AnonymousCardContent` is the card as an organization reads it: a closed object of the six properties above, each null when it is not published or has no value, so the card does not tell the two apart. It has no name, email, phone, Telegram name, employer, salary figure, or account or profile identifier, and no schema of the private profile, a contact, a consent, an invitation, or an organization is reachable from it (`TestAnonymousCardReachesNoProfileOrContactSchema` walks the references). `GetMyCardPreview` returns it with the published fields, or `card` null while the profile is closed, as a private read that creates no view and no history record. The card of an organization's search result must reuse this content and cannot add a property that identifies the candidate. - -Versions and checks: - -- Both `PUT` operations of the settings follow the profile pattern: the complete new state in the body, `expected_version` in the body (the generated client cannot read the ETag yet), 412 `version_conflict` for a stale or non-existent version, and an unchanged body answers 200 with the current state even over a stale version, so no Idempotency-Key is needed. Order of checks: session (401), CSRF and Origin (403), request validation (400), account scenario (403), a version above the current one (412), an unchanged state (200), a stale version (412), then the C2 for a publication (409). A published state without a field and a closed state with a field answer 400 with the pointer `/fields`; the schema rejects an unknown or repeated card field and unknown properties such as a consent identifier or a confirmation time. `looking` always changes the stored confirmation, so it answers 412 for a stale version even as a repeat. The two 409 `state_conflict` answers are told apart by `errors`: `{in: body, pointer: /state, code: consent_required}` for a publication without an active C2, and `{in: path, pointer: /org_id, code: limit_reached}` for the 1001st hidden organization. A closing over a stored publication whose C2 was revoked is a real change (it stores the closing, records `publication_closed`, and revokes the grants); the C2 revocation path closes the stored publication and revokes the grants in its own transaction. Publishing, hiding, and the history need a verified email (a usecase requirement). `Problem.errors` is not only for `validation_failed`: a `state_conflict` carries one entry as a disambiguator (`consent_required`, `limit_reached`), so a future problem writer must not strip `errors` from non-validation responses. Only values that the candidate confirmed reach the card, a free text value that looks like a contact (email, phone, URL, Telegram link, @handle) is dropped, and adding a card field is a contract change and a migration. -- 404 and anti-enumeration. `HideOrganization` answers the same 404 `not_found`, with the same body and without a different timing, for an organization that does not exist and for one that the candidate cannot see, so it is not a way to ask whether an identifier belongs to an organization. The candidate can see an organization that has sent them an invitation, and the organizations that a candidate lookup lists (planned). The identifiers are random, and the general rate limit can answer 429 with Retry-After before any check. `UnhideOrganization` reveals nothing: 204 for any well-formed identifier. A malformed `org_id` answers 400 with the pointer `/org_id`. -- Contact grants. Closing the publication, and hiding an organization that holds an active contact grant, revoke that grant with the reason `visibility_closed`, in the same transaction as the change (planned together with the operations; the reason is fixed in the invitation contract). Lifting a hiding or publishing again never reopens a grant. The search status never revokes a grant. - -History: - -- `ListMyPrivacyHistory` returns the append-only history of the settings, newest first (the history stores only the organization identifier, and the current name is resolved when it is read): `publication_opened`, `publication_changed` (with the published fields and the `consent_id` behind them), `publication_closed`, `search_status_confirmed`, `search_status_cleared`, `organization_hidden`, and `organization_unhidden` (with the organization's current name). This is the evidence of the published field set and its changes with their times that the C2 record does not carry. A revocation of C2 and a lapse are computed and are not events; the consent history shows the revocation. The history holds no profile value. -- `ListMyCardAccessHistory` returns the accesses of organizations to the card: `card_viewed` and `contact_read`. A view by an organization that has no invitation relation with the candidate has `organization` null; a contact read always names the organization. The entries carry no query or ranking. Its storage comes with the search and contact-read tasks, so the operation is contract-only. - -Open questions for the product owner and the lawyer: - -- The search status values: the contract has `looking` and `not_looking`. Whether the PRD needs a third status such as "open to offers" is not decided; a value is an additive change. -- Whether `looking` gates the appearance of a published card in search (an organization sees only candidates who are searching) or is only a label. This decides the meaning of a lapse for visibility and belongs to the search contract. -- The set of card fields. The six values are a proposal that matches the profile; the PRD card (FR11) may add, split, or drop some, for example a generalized employer industry and size instead of employers, and each is an additive contract change. -- Whether publishing needs a minimum: at least one confirmed category, or a saved profile. The contract only requires one card field and an active C2. -- Whether narrowing the published fields, not only closing the publication or hiding an organization, must revoke the contact grants. The invitation contract says any visibility change after a grant revokes it; this contract revokes on closing and hiding only. -- How a candidate finds an organization to hide before any invitation. The contract hides by identifier and answers 404 for an organization the candidate cannot see, so hiding the current employer in advance needs an organization lookup for candidates (by name or domain), which must itself be safe against enumeration (a minimum query length, a rate limit, public data only). Without it, hiding works only for organizations that have written to the candidate. -- Whether the candidate should learn the name of an organization that viewed the card without an invitation (`CardAccess.organization`), and how long accesses are kept. -- The limit of hidden organizations (1000 now) and the retention of the settings and their history together with the consent evidence (152-FZ, PRD 7.3). The history references the account with `ON DELETE CASCADE`, guarded by two triggers: UPDATE is always refused, and DELETE (and the deletion of the account) is refused while the account is verified, the same condition as the consent ledger; the unverified account cleanup removes the history of an account it deletes, and the account deletion procedure extends the condition. -- Free text in the card (stack tags, soft skills, location) is guarded only by `CardTextLooksLikeContact`, which errs on the side of dropping (Socket.io is dropped, a bare obfuscation can still slip through); the residual risk still requires a closed taxonomy in the card builder instead of free text. -- Whether C2 is a consent to the distribution of personal data under article 10.1 of 152-FZ and needs its own field scope (see Consents); the history keeps the fields and times in the meantime. -- Whether a new C2 text version requires the candidate to consent again for an existing publication. Now a publication stays effective while its C2 record is unrevoked, so a newer text version that the candidate has not accepted does not close it. -- Quasi-identifiers and k-anonymity of the card: a rare combination of location, stack, and experience can identify a candidate even without a name. The generalization of rare features and a minimum group size are acceptance criteria for the card builder; the contract here only fixes the closed set of fields, the confirmed-values-only rule, and the dropping of free text that looks like a contact. -- Retention and the right to erasure for the settings history. The hide and unhide records are sensitive (they say which employer a candidate avoids). The history is kept like the consent evidence and is not deletable while the account is confirmed; whether a candidate can erase it, when, and how this meets the three-year consent retention (PRD 7.3) is an open legal question. The account deletion procedure extends the delete condition of the table. - -No new problem code is added. `TestPrivacyOperationsFollowTheConventions`, `TestPublicationAndSearchStatusAreNotConsents`, `TestAnonymousCardReachesNoProfileOrContactSchema`, `TestGeneratedPrivacyDTOsCarryNoServerOwnedFields`, `TestPrivacySchemaValidationPrecedesImplementation`, and `TestPrivacyAccessBeforeImplementation` pin the generated server and the bundle, and `frontend/src/shared/api/privacy-contract.test.ts` pins the generated Zod rules, the absence of a consent, a time, a contact, or a salary in the request and card types, and the absence of settings in the organization, invitation, need, profile, and consent files. - -### Skill evidence - -The tag `evidence` describes the facts that confirmed assessments leave about a candidate's skills (FR06 in the PRD). It has two read operations; the logic behind them is implemented (see [architecture](../docs/en/ARCHITECTURE.md#skill-evidence)). - -| Method and path | operationId | Protection | Success | Specific errors | -| --- | --- | --- | --- | --- | -| `GET /api/v1/me/evidence` | `ListMyEvidence` | session | 200 `EvidenceFactList`, `Cache-Control: no-store` | 400, 401, 403 `forbidden` | -| `GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}/evidence` | `GetOrganizationCandidateEvidence` | session | 200 `OrganizationEvidence`, `Cache-Control: no-store` | 400, 401, 403, 404 `not_found`, 429 | - -Each operation also declares the problem response `default`. No new problem code is added. - -- One event is one fact. `EvidenceFact` is a source event; `skills` are the tags of that event (a non-empty set), so a second tag never makes a second fact. `source` names the event and the immutable result (`event_id` and `result_id`, equal for an assessment because a result is keyed by its attempt; the candidate opens it at `GetMyAssessmentResult`). -- A claim is not a measurement. `kind` is `claim` (trust 0) or `measurement` (trust 1 to 3). `EvidenceTrustLevel` is an integer from 0 to 3; an online assessment without a reliable confirmation of the identity is trust 1, and repetition never raises it. Only measurements from assessments are produced today. -- What a fact says is `result`: the grade that was passed, the `basis` (`synthetic_demo`), and the `calibration_status` (`uncalibrated`), so the candidate never reads a demonstration category as a validated measurement. The organization projection and the preview carry both labels as well. A fact has no score, answer, item, failed attempt, or anti-cheat datum, and a failed attempt, a result without a reviewed category source, and a `demo_express` run produce no fact. -- `ListMyEvidence` lists only the caller's facts, newest event first, hidden facts included (`visibility` `hidden`), with the shared `limit` (1 to 100, default 20) and an opaque `cursor` bound to the candidate. A malformed or foreign cursor and a limit out of range answer 400; an employer account answers 403. -- `GetOrganizationCandidateEvidence` is a section of the anonymous card. It answers only while `GetOrganizationCandidateCard` would answer for the same handle and the card shows at least one category; every other case (unknown handle, handle of another organization, closed or revoked publication, hidden organization, minimum cohort, card without categories) is the same 404, so the answer reveals nothing the card does not. For each category of the card it returns one `OrganizationEvidenceFact`: the earliest visible assessment that passed exactly the confirmed grade, with only `skill`, `grade`, `trust`, `observed_year` (the year, UTC), and `basis` and `calibration_status` (`synthetic_demo`, `uncalibrated`; the same for every candidate, so they add no fingerprint and say the fact is a demonstration). A lower grade, a retake, the other tags, the source, the basis, the month, and every identifier stay with the candidate; at most nine facts, ordered by skill, and a hidden fact is absent. No key joins the answer to a person, but it is not unlinkable: with the other values of the card, the skill, grade, trust, and year can narrow a small pool, and the minimum cohort does not cover the year. The read consumes the card-view quota and appears in the access history with the field `categories`. -- The preview. `CardPreview.evidence` is the same section computed for the candidate (`OrganizationEvidence`, or null exactly when `card` is null), so the candidate sees what an organization would read with the `categories` field. It applies no organization or cohort, so an organization can receive less. -- Closed schemas and the privacy walk. Every evidence object has `additionalProperties: false` and requires all its properties. `TestNoOrganizationOperationReachesRawAssessmentData` (Go) and `test_evidence_is_closed_and_no_organization_operation_reaches_raw_assessment_data` (Python) walk every organization operation and `ListMyEvidence` through all references and fail on an assessment, signal, or review schema or on a raw answer, score, or failure property. - -Open questions: whether the C2 consent text needs a new version now that publishing `categories` also sends one supporting assessment fact (skill, grade, trust level, year) to an organization - a decision for the owner and the lawyer, and the consent texts are not changed here; whether the evidence needs its own card field instead of the `categories` field; whether the year is the right precision for an employer; an operation for the candidate to hide or show a fact (the stored visibility exists, no operation changes it); and when claims of the profile and facts from other sources join the list. - -### Match search - -The tag `organization` has one search operation for the organization-visible candidate bank (PRD FR09). It is implemented as a deterministic search without ML; the model, the groups, and the data it reads are described in [architecture](../docs/en/ARCHITECTURE.md#matching-and-explanations). - -| Method and path | operationId | Protection | Success | Specific errors | -| --- | --- | --- | --- | --- | -| `POST /api/v1/organizations/{org_id}/matches` | `SearchOrganizationMatches` | session, CSRF, `Origin`, active owner | 200 `MatchSearchResponse`, `Cache-Control: no-store` | 400, 401, 403, 404 `not_found` | - -The operation changes nothing and needs no Idempotency-Key; `POST` carries the body. The 200 response also declares no 429. - -- Access. The organization comes from the path and the active owner membership of the session account. A missing session answers 401, a candidate account, a member who is not the owner, a missing CSRF token, and a foreign `Origin` answer 403, and an unknown organization, an organization without an active membership, a need of another organization, an unknown need, or a `requirements_version` that no change of the confirmed requirements created answer 404. Hidden profiles, a revoked or missing C2 publication, the organization's own hiding, and the minimum cohort of the card are applied before any entry exists: a handle in the result is a handle that `GetOrganizationCandidateCard` opens at that moment. -- Basis. `MatchSearchByNeed` searches the immutable `requirements_version` snapshot (not the general `version`), and its optional `filters` narrow it; `MatchSearchByBank` searches all organization-visible entries with explicit filters. The response `source` repeats the basis: the need reference, or the bank filters with every key present and null for a filter that was not sent (the stack is sorted). -- Entries. Every entry is one candidate specialization under the organization-scoped `candidate_handle`. `main` and `near` hold confirmed categories (`near` when a required skill of the request earns less than 0.25), `unconfirmed` holds the declared specializations, sorted by Fit, then Coverage, then an internal identifier that is never returned. An unconfirmed entry has `category: null`, `strength: null`, and only `fit` and `coverage`. The groups are not one scale, and one handle can be confirmed in one specialization and unconfirmed in another. -- Category basis. Each confirmed category of an entry carries `basis` (`synthetic_demo` for a demonstration category). The organization sees a demonstration as such, not as a standard confirmation; the field is required in `MatchCategory`. -- Neutral and unknown values. The semantics component is the calibrated cosine of the stored vectors of the need and the card, and 0.5 with `ml_unavailable` without them; `percentile` is null with `cohort_below_30` and T is 0.5 (no comparable real cohort exists, and demonstration results never form one); domain, freshness, and responsiveness are 0.5 with their flags; competition is 0 and is neither a penalty nor an unknown; a card value that is not published is `null` in `public_context` with `not_in_public_card`. -- A search is charged like card reads, because an entry carries card content. The whole visible bank is ranked, and each group returns at most `max_results_per_group` entries of the policy version (demo 10, so at most 30 reveals for one search, below the 50 views per day of tier E0); no total is returned. In the order `main`, `near`, `unconfirmed`, each newly revealed candidate counts as one distinct card view of the organization (the same reservation as `GetOrganizationCandidateCard`, so a candidate already viewed inside the window costs nothing again, and repeating the search or opening the card afterwards does not charge twice) and gets one `card_viewed` entry in the access history per search with the fields actually returned. When the allowance ends, the entries already paid for are returned with `truncated: true`, nothing is written for the rest, and no error and no new problem code is returned. `truncated` is also true when a group exceeded its limit and never carries a count. The response `truncated` is required. -- No contact, candidate location, salary amount or minimum, raw answer, failed attempt, or reason for withheld data is in any entry; the explanation uses the bounded `MatchEvidenceCode` and `MatchEvidenceState` values only. A deployment whose effective policy has no `matching` section answers an internal error and never ranks with defaults. -- `semantic_evidence` (up to 12, 6 by default) explains a need search: a requirement of the need, the closest item of the published card (`project`, `stack`, `roles`), the band `high` or `medium`, and `repository_verified`. A project is named only by its published title (the card field `projects`), never by the repository address or owner; no model text enters the explanation ([architecture](../docs/en/ARCHITECTURE.md#semantic-layer-and-explanations)). - -Accepted residual risks: `truncated` is one bit about the size of the visible bank, and the response time grows with it; both are bounded by the group limit and carry no count. When the real comparable cohort of a category reaches the policy minimum, the percentile is still null with the reason `percentile_not_computed` and the search does not fail. A change of the visible cohort during a search repeats it up to three times; two simultaneous searches of one organization are serialized by its quota lock. - -Open questions: the demo value 10 of `max_results_per_group` and whether the output needs paging beyond it; whether a search should charge a candidate for a summary entry at the price of a full card view; whether the grade of a need should be an implicit filter or only an explanation; whether the PRD values should keep an online Backend result (trust 0.6 times the broad relation 0.4 gives 0.24) below the near threshold 0.25 while a stated tag (0.25) reaches it, so that a candidate whose only evidence for a required technology is an assessment of the specialization is always in `near` for it; whether the `stack` filter should require every tag (as implemented) or any; and whether the demonstration relation between specializations and technologies (Backend over Go, PostgreSQL, Kafka, and Docker; DevOps over Docker) is the taxonomy the owner wants. - -### Notifications - -The tag `notification` describes the in-platform inbox of the current account, in the candidate cabinet and in the cabinet of one organization. It has four operations; the logic behind them is implemented, and no product module produces a real notification yet (see [architecture](../docs/en/ARCHITECTURE.md#internal-notifications)). - -| Method and path | operationId | Protection | Success | Specific errors | -| --- | --- | --- | --- | --- | -| `GET /api/v1/me/notifications` | `ListMyNotifications` | session | 200 `NotificationList`, `Cache-Control: no-store` | 400, 401, 403 `forbidden` (an employer account) | -| `POST /api/v1/me/notifications/{notification_id}/read` | `MarkMyNotificationRead` | session and CSRF | 200 `NotificationReadReceipt`, `Cache-Control: no-store` | 400, 401, 403, 404 `not_found`, 429 | -| `GET /api/v1/organizations/{org_id}/notifications` | `ListOrganizationNotifications` | session | 200 `NotificationList`, `Cache-Control: no-store` | 400, 401, 403 `forbidden` (a candidate account) or `email_not_verified`, 404 `not_found` | -| `POST /api/v1/organizations/{org_id}/notifications/{notification_id}/read` | `MarkOrganizationNotificationRead` | session and CSRF | 200 `NotificationReadReceipt`, `Cache-Control: no-store` | 400, 401, 403, 404 `not_found`, 429 | - -Each operation also declares the problem response `default`. No new problem code is added. - -- The inbox is the delivery state inside the platform. An item exists once the event reached the platform, whether or not an email was sent, and a failed or missing email never blocks it. A repeated delivery of the same event is the same item (`id` is the event identifier). -- The inbox stores references, not text. `content` is resolved from the current source for the recipient on every read and is `null` when the source is gone or the recipient may not see it now (for example the candidate hid the organization); the item stays in the list, can be marked, and a client shows a generic line, never an earlier copy. `content.link_path` is a same-origin absolute path (`^/[A-Za-z0-9/_-]{0,255}$`) or `null`. -- The recipient is the session account. The organization route also needs an active membership of any role in `org_id` and lists only the caller's items of that organization. A candidate on the organization route and an employer on the candidate route get 403 `forbidden`, and an employer with an unconfirmed email gets 403 `email_not_verified` on the organization route. A missing membership, an unknown organization, an item of another account or of another organization, and an unknown identifier get the same 404 `not_found`, so identifiers cannot be enumerated. -- Pagination follows the shared `limit` (1-100, default 20) and `cursor`, newest delivery first with the identifier as the tie-breaker. The cursor is bound to the account and the cabinet; a cursor of another account or cabinet gets 400. -- A mark is idempotent by its effect and needs no Idempotency-Key: the first read time is stored and every repeat returns it. It reads no source and returns no content. `kind` is `invitation_delivered` (no module produces it yet) or `synthetic` (a notice with no product meaning that exercises the path). -- Closed schemas and checks. Every notification object has `additionalProperties: false` and all properties required. `TestNotificationOperationsFollowTheConventions` and `TestNotificationSchemasAreClosedAndKeepTextInTheContent` (Go) check the tag, the security of reads and marks, the statuses, no-store, the parameters, and that an item carries no text, name, or contact outside `content`. - -### Generator checks - -`testdata/openapi-3.2.0.yml` contains test operations that use the components above: pagination, Idempotency-Key, If-Match, ETag, and problem responses. ogen does not resolve external references, so the fixture keeps copies of the api/core components; `scripts/test_contract_copies.py` (part of `make -C api check`) checks that they, the fixture responses, and the ML `Problem` copy match api/core. - -`make -C api check-toolchain` lints the fixture and runs the three generators on it; it needs the backend Go toolchain, pnpm, and uv, so pass the same `UV` override as for `make generate`. - -| Target | Generator | Exercised conventions | -| --- | --- | --- | -| `make -C backend check-ogen-compat` | ogen | All of them: Problem, PageInfo, Timestamp, PageLimit, PageCursor, IdempotencyKey, IfMatch, ETag. Its tests check validation errors, the retry scenario, the preconditions, and the 413 body limit against the backend problem mapping | -| `make -C frontend check-orval-compat` | Orval | Problem, PageInfo, Timestamp, PageLimit, PageCursor, IdempotencyKey, IfMatch. The output is type-checked with the frontend compiler settings | -| `make -C ml check-pydantic-compat` | datamodel-code-generator | Problem, PageInfo, Timestamp, PageLimit, PageCursor. The models pass `mypy --strict` and a validation script | - -Each target writes its output to a temporary directory and removes it. - -Known generator limitations: - -- Orval 8.40 writes no Zod schema for `components/responses` but imports a `Response` type for each reference. `frontend/codegen/orval.config.ts` therefore inlines response references before generation. -- Orval passes header parameters as a typed argument only with `headers: true`. With `exactOptionalPropertyTypes`, an optional header such as `If-Match` fits `RequestInit` only when Zod emits exact optional properties, so the configuration also sets `override.zod.exactOptional`. -- Orval generates no type for response headers, and `apiRequest` returns only the body, so a generated client cannot read `ETag` yet. The first operation with a versioned resource must expose it, for example through the response body or the mutator. -- datamodel-code-generator 0.83.0 generates models only for schemas and query and path parameters; header parameters and response headers (Idempotency-Key, If-Match, ETag) produce no Python model. -- Orval does not generate `additionalOperations` methods. -- ogen writes the header name in its canonical Go form (`Etag`); HTTP header names are case-insensitive. -- ogen requires a `SecurityHandler` as soon as the contract has security schemes and evaluates the schemes in the order of their generated type names, so renaming a scheme can change the order; `TestGeneratedServerSecurityOrder` fails if it does. Security failures reach `NewError` without a response header, so clearing the cookie on a 401 from `Logout` needs handwritten code. -- Orval does not expose security scheme values as typed arguments, so `X-CSRF-Token` is not a generated parameter; the shared API client is planned to attach it to mutating requests. Orval also generates no type for `Set-Cookie`, which the browser handles. -- Orval Zod schemas ignore `uniqueItems` and do not reject unknown fields of `additionalProperties: false` objects; the server stays authoritative for both. -- ogen generates an optional nullable field as `OptNil`, which tells absent (`IsSet` false), null (`IsNull`), and a value apart. An optional array that is not nullable is a plain slice instead, where nil and `[]` mean different things: an absent field decodes to nil (unchanged) and `[]` to an empty non-nil slice (delete every item), and null fails decoding. An `UpdateOrganizationNeed` handler must therefore test lists with `!= nil`, never with `len`; `TestNeedUpdateDecodingKeepsAbsentAndEmptyListsApart` pins this. -- Orval clears `src/shared/api/endpoints/` and `src/shared/api/schemas/` before generation (`clean: true`), because a schema used by several tags moves from a tag directory to the schema root. -- The post-Orval step `frontend/codegen/mock-patterns.ts` finds the length bounds of a patterned string by its property name and pattern, so two properties with the same name and pattern must have the same bounds. The invitation terms therefore name the technologies `tech_stack` (`SkillName`, up to 100 characters) next to the questionnaire `stack` (`StackTag`, up to 50), and a package condition carries `description` rather than `value`, which the need decisions use with other bounds. - -#### Format unions - -- Format unions such as `ItemContent` and `AssessmentAnswer` are `oneOf` without a `discriminator` object. Redocly resolves `discriminator.mapping` values as references, and `scripts/merge-schemas.py` rewrites only `$ref`, so a mapping in a split schema file cannot resolve in the merged `components/schemas.yml`. Every variant fixes `format` with a one-value enum; ogen discriminates by that value and by the fields unique to a variant and rejects a body that matches several variants, and Orval generates a Zod union. -- Orval names the constants of an inline property ``, so a property name that repeats another schema name collides in `index.ts` (TS2308). The union of item formats is therefore `ItemContent`, not `AssessmentItemContent`, next to the `AssessmentItem.content` property, and the parts of `Need` are `NeedRequirementSet`, `NeedReadinessReport`, and `NeedCategoryRecommendations`, not `NeedRequirements`, `NeedReadiness`, and `NeedRecommendations`. The response target of a case is `SupportResponseTarget`, not `SupportCaseResponseTarget`, next to the `SupportCase.response_target` property. - -Generated Zod is not strict. A body that mixes the fields of two formats or carries an extra `score` or `seed` is accepted after unknown keys are silently stripped, and `uniqueItems` is not checked; only the server rejects such bodies. `frontend/src/shared/api/assessment-contract.test.ts` pins the accepted formats and that no answer or item DTO has a score, key, seed, or correctness field. - -See the [development guide](../docs/en/DEVELOPMENT.md). +See [DEVELOPMENT.md](../docs/en/DEVELOPMENT.md) for contract changes and [TESTING.md](../docs/en/TESTING.md) for checks. diff --git a/api/README.md b/api/README.md index 7c3e51b..3045cb7 100644 --- a/api/README.md +++ b/api/README.md @@ -2,827 +2,57 @@ Русский | [English](README.en.md) -Общие OpenAPI-контракты для Go, frontend и ML. Сначала изменяется контракт, затем из него генерируются типы, серверный код и клиенты нужных сервисов. +OpenAPI 3.2.0 - общий источник HTTP-контрактов. Сначала меняется спецификация, затем генерируются серверные адаптеры, клиенты и модели. -- `core/` - публичный API основного backend. -- `ml/` - внутренний HTTP API ML-сервиса. -- `runner/` - внутренний HTTP API собственного исполнителя кода. -- `testdata/` - спецификация для проверки совместимости инструментов с OpenAPI 3.2.0. +## Структура -Маршруты лежат в `routes/`, схемы - в `components/`. Файлы `openapi.bundle.yml` собираются автоматически. Конфигурации генераторов находятся в `backend/codegen/`, `frontend/codegen/` и `ml/codegen/`; серверный код исполнителя генерируется по `runner/codegen/`. +| Каталог | API | +| --- | --- | +| [core/](core/openapi.yml) | Публичный Go API под `/api/v1` | +| [ml/](ml/openapi.yml) | Внутренний ML API | +| [runner/](runner/openapi.yml) | Исполнитель кода | +| [labd/](labd/openapi.yml) | Подготовка лабораторных окружений | +| [testdata/](testdata/openapi-3.2.0.yml) | Проверка совместимости генераторов | -Из корня: `make -C api check` проверяет контракты, `make generate` обновляет весь сгенерированный код. +В каждом контракте `openapi.yml` подключает `routes/` и `components/`. Тематические схемы объединяет [merge-schemas.py](../scripts/merge-schemas.py), после чего Redocly создает `openapi.bundle.yml`. Производные файлы вручную не редактируются. + +## Генерация + +Команды выполняются из корня репозитория: + +```sh +make -C api install +make -C api check +make generate +make check-generated +``` + +`check` собирает и проверяет контракты. `generate` обновляет всех потребителей. `check-generated` ищет отличия от закоммиченного результата и сам генерацию не запускает. + +| Потребитель | Генератор и настройки | +| --- | --- | +| Go backend | ogen, [backend/codegen/](../backend/codegen/) | +| Go runner и labd | ogen, настройки в `codegen/` каждого сервиса | +| React | Orval: клиент, query hooks, Zod-схемы и MSW; [frontend/codegen/](../frontend/codegen/) | +| Python ML | datamodel-code-generator: Pydantic; [ml/codegen/](../ml/codegen/) | + +`make -C api check-toolchain` проверяет используемые возможности OpenAPI 3.2 на отдельной спецификации. Это проверка текущего набора инструментов, а не обещание поддержки всех возможностей стандарта. + +Для сравнения публичного контракта с существующим Git ref: `make -C api check-compat API_BASE_REF=`. ## Соглашения контракта -`api/core/` закрепляет эти соглашения как переиспользуемые компоненты в `openapi.yml` и файлах `components/`: схемы в `components/schemas/*_schemas.yml`, параметры в `parameters.yml`, заголовки ответов в `headers.yml`, ответы в `responses.yml`, примеры в `examples.yml`. Операции ссылаются на них по мере появления. Сейчас реализованы problem-ответы для ошибок публичного Go API и ML-сервиса. Хранение Idempotency-Key, проверки If-Match и пагинация - запланированное поведение бизнес-операций; объявленная операция `RegisterAccount`, команды оценки, `CreateOrganization`, `CreateOrganizationNeed`, `CreateMySupportCase` и команды приглашений требуют Idempotency-Key, но ни одна операция пока не хранит ключи. +- Ошибки: RFC 9457, `application/problem+json`, стабильный `code` и безопасные сообщения. Поля ответа задает схема `Problem`. +- Сессия: HttpOnly cookie; изменяющие запросы с сессией также передают `X-CSRF-Token`. Origin должен соответствовать настройке приложения. +- `Idempotency-Key` передается для операций, где он требуется контрактом. Повтор того же действия использует прежний ключ; другое содержимое требует нового. +- Конкурентные изменения используют `If-Match` или `expected_version` согласно операции. При конфликте клиент перечитывает состояние и сохраняет пользовательский черновик. +- Списки используют ограниченную cursor pagination. Идентификаторы - UUID, время - UTC date-time. Отсутствующее поле и `null` могут иметь разный смысл. +- Коды, лимиты, обязательные заголовки и примеры берутся из конкретной операции и общих компонентов. -### Ошибки +## Границы -Любая ошибка - problem по RFC 9457 с media type `application/problem+json` и схемой `Problem`. Обязательные поля: `type` (`urn:lincodex:problem:`), `title`, `status` и `code`; необязательные: `detail`, `instance`, `trace_id` (равен заголовку ответа `X-Request-ID`) и `errors`. Клиенты принимают решения по `code`. Заголовок и описание фиксированы для каждого кода и никогда не содержат текст внутренних ошибок, stack trace, учетные данные, контакты или отправленные значения. +Наличие операции в спецификации не доказывает готовность ее обработчика. Проверяйте реализацию в `backend/internal/adapter/primary/http/v1/` и ее тесты. Нереализованная операция может вернуть `501 not_implemented`. -| Код | Статус | Значение | -| --- | --- | --- | -| `validation_failed` | 400 | Параметры или тело не соответствуют контракту или тело нарушает доменное правило; `errors` перечисляет поля | -| `verification_token_invalid` | 400 | Токен подтверждения email неизвестен, уже использован или заменен | -| `verification_token_expired` | 400 | Срок действия токена подтверждения email истек | -| `unauthenticated` | 401 | Нет действующей сессии | -| `invalid_credentials` | 401 | Вход не удался; неизвестный email и неверный пароль не различаются | -| `forbidden` | 403 | Вызывающему запрещена операция | -| `email_not_verified` | 403 | Учетные данные верны, но email не подтвержден | -| `csrf_check_failed` | 403 | Нет или неверен `X-CSRF-Token`, либо `Origin` не разрешен | -| `not_found` | 404 | Неизвестный маршрут или объект, который не существует или недоступен | -| `method_not_allowed` | 405 | Метод не поддерживается; см. `Allow` | -| `idempotency_in_progress` | 409 | Запрос с тем же Idempotency-Key еще выполняется | -| `state_conflict` | 409 | Операция недопустима в текущем состоянии ресурса | -| `version_conflict` | 412 | If-Match или `expected_version` в теле не совпадает с текущей версией | -| `payload_too_large` | 413 | Тело превышает лимит операции | -| `unsupported_media_type` | 415 | Content-Type запроса не принимается | -| `idempotency_key_reused` | 422 | Idempotency-Key уже использован с другим запросом | -| `precondition_required` | 428 | Операция требует If-Match | -| `rate_limited` | 429 | Слишком много запросов; см. `Retry-After` | -| `internal` | 500 | Непредвиденная ошибка сервера | -| `not_implemented` | 501 | Операция есть в контракте, но не реализована | +Внутренние API ML, runner и labd не предназначены для прямого доступа из браузера. Публичный health-маршрут - `/api/v1/healthz`; служебные `/healthz`, `/readyz` и метрики описаны в руководствах сервисов. -Для валидации запроса выбран 400, а не 422. Сгенерированный ogen-сервер сообщает о синтаксически неверных и не прошедших проверку схемы параметрах и теле через одни и те же ошибки декодирования, а для параметров не отделяет синтаксис от нарушения схемы; единый статус упрощает обработку на клиенте. Поэтому 422 остается для повторного использования Idempotency-Key, как рекомендует черновик IETF о заголовке Idempotency-Key. Доменные правила тела, например `salary_from <= salary_to`, тоже отвечают 400 `validation_failed` с body pointer на участвующие поля. Каждый элемент `errors` содержит `in` (`body`, `query`, `path`, `header`, `cookie`), `pointer` (JSON Pointer: `/salary_from` в теле, пустая строка для всего тела, `/limit` для параметра), `code` (`required` или `invalid`; клиенты допускают новые значения) и фиксированный `message`. Pointer тела строится по правилам из раздела Pointer тела ниже. Тело, обрезанное лимитом `http.MaxBytesReader`, дает 413 `payload_too_large`. - -`state_conflict` обозначает конфликты бизнес-состояния, например принятие уже отозванного приглашения. `idempotency_in_progress` зарезервирован для параллельных повторов; переиспользуемые ответы - `StateConflict` и `IdempotencyInProgress`. - -Каждая операция объявляет `default: $ref: ../components/responses.yml#/Problem`; тогда ogen генерирует единый тип ошибки. Конкретный ответ (например, `PreconditionFailed`) операция добавляет, когда он нужен клиентам в сгенерированных типах. В Go API неизвестные пути под `/api`, включая пути вне `/api/v1`, отвечают 404 `not_found`, а panic в операции - 500 `internal`; в лог попадают только тип panic и stack. - -Оба кода токена подтверждения используют 400, потому что токен - содержимое запроса, а не целевой ресурс: 404 и 410 описывают URI, 409 - состояние ресурса, а 422 зарезервирован для повторного использования Idempotency-Key. Синтаксически неверный токен не проходит проверку схемы и дает 400 `validation_failed` с pointer `/token`. `invalid_credentials` и `unauthenticated` используют 401, но означают соответственно неудачный вход и отсутствие сессии. `email_not_verified` возвращается только после совпадения пароля, поэтому раскрывает состояние подтверждения только тому, кто уже доказал знание пароля. - -#### Pointer тела - -Сгенерированный декодер сам путь не записывает. Ошибку каждого поля объекта он оборачивает как `decode field ""` через go-faster/errors, а `problem.Responder` восстанавливает pointer по этим оберткам, читая каждое звено через типизированный `errors.Formatter`, а не через склеенный текст ошибки. Правила: - -- Отсутствующее обязательное поле дает `required` со своим pointer на любой глубине, например `/terms/communication_method` или `/terms/salary/tax_basis`. -- Значение, которое не декодируется, например неверный тип JSON, некорректный UUID или неоднозначное значение `oneOf`, дает `invalid` с pointer этого значения, например `/grade` для грейда без решения или `/object/id`. -- Значение, которое декодируется, но нарушает правило схемы (длину, pattern, кратность 1000, enum), дает `invalid` с полным pointer, включая индексы массивов, например `/required_skills/2/status`; эта проверка идет после декодирования. -- Неизвестное свойство дает `invalid` с pointer объекта, который его содержит, например `/terms/salary` для `candidate_minimum` внутри вилки; имя свойства не повторяется. -- Ошибка внутри элемента массива при декодировании дает `invalid` с pointer массива, например `/required_skills`, потому что jx не сообщает индекс элемента. -- Pointer на все тело `""` остается только для некорректного JSON-документа, отсутствующего тела, неизвестного свойства верхнего уровня, неизвестного или отсутствующего дискриминатора `oneOf` верхнего уровня и цепочки ошибок, которую responder не распознал: она безопасно сводится ко всему телу. - -`responder_test.go` покрывает вложенный объект, элемент массива, поле варианта `oneOf`, поле верхнего уровня и нераспознанную цепочку; router-тесты каждого контракта закрепляют pointer через сгенерированный сервер. - -### Повторы и Idempotency-Key - -Изменяющая команда объявляет параметр `IdempotencyKey`. Клиент создает ключ (рекомендуется UUID v4) и передает его в заголовке `Idempotency-Key` без кавычек: 1-255 символов `A-Z a-z 0-9 . _ : -`. Сервер ограничивает ключ вызывающим и операцией и снимает отпечаток запроса по методу, пути и телу. - -Анонимная операция сама определяет область ключа и отпечаток в своем описании; для `RegisterAccount` они описаны в разделе Identity ниже. - -Хранятся 24 часа и воспроизводятся с теми же статусом, заголовками и телом: итоговый 2xx-результат и итоговые детерминированные бизнес-результаты 4xx, например 404 `not_found` или 409 `state_conflict`. Воспроизведение не повторяет побочный эффект. - -Не хранятся, поэтому повтор с тем же ключом обрабатывается заново: 400 `validation_failed`, 413 и 415 для самого запроса; 401 и 403; 409 `idempotency_in_progress`; 412 `version_conflict` и 428 `precondition_required` (ничего не изменилось; прочитайте ресурс снова и повторите); 422 `idempotency_key_reused`; 429; любой 5xx. - -Порядок проверок на сервере: - -1. Аутентификация (401), валидация запроса (400, 413, 415) и авторизация (403). Для ключа ничего не записывается. -2. Сохраненный или выполняющийся запрос с тем же ключом и другим отпечатком: 422 `idempotency_key_reused`. Эта проверка идет раньше проверки выполнения. -3. Выполняющийся запрос с тем же ключом и отпечатком: 409 `idempotency_in_progress`; повторите позже. -4. Сохраненный результат с тем же ключом и отпечатком: результат воспроизводится. -5. If-Match (428, 412), затем сама команда; результат, который можно хранить, записывается. - -Поскольку проверка воспроизведения идет раньше If-Match, повтор завершенного изменения воспроизводит его результат, а не падает на версии, которую само изменение и увеличило. Отсутствующий или некорректный ключ дает 400 `validation_failed` с pointer `/Idempotency-Key`. Через 24 часа ключ может быть принят как новый. - -### Версии: ETag и If-Match - -Ответ с версионируемым ресурсом возвращает сильный `ETag`, например `"v7"`. Операция, изменяющая такой ресурс, указывает в описании, что требует `If-Match` с этим значением. Отсутствующее значение дает 428 `precondition_required`; значение, не равное текущему ETag, дает 412 `version_conflict` без изменений. В схеме параметр необязательный, чтобы отсутствие заголовка доходило до приложения, которое отвечает 428. Слабые теги, списки и `*` не проходят валидацию и дают 400. Анкета вместо этого передает версию в теле как `expected_version`; см. раздел "Каталог и анкета" ниже. - -### Пагинация - -Списки используют cursor pagination: `limit` от 1 до 100 (по умолчанию 20) и непрозрачный `cursor` длиной до 512 символов `A-Z a-z 0-9 _ -`. Ответ содержит элементы в ограниченном массиве и `page` (`PageInfo`) с `has_more` и `next_cursor`, который равен null на последней странице. Некорректный cursor дает 400 `validation_failed`. - -### Время и деньги - -Метки времени используют схему `Timestamp`: `string`, `format: date-time`, UTC с суффиксом `Z` (RFC 3339). Серверы всегда отдают UTC. ogen генерирует `Timestamp` как именованный Go-тип поверх `time.Time`; при преобразовании к нему вызывайте `.UTC()`. Деньги - целое число полных рублей (`RubAmount`, int64) с явной базой: `SalaryRange` требует `salary_from`, `salary_to`, `currency` (`RUB`), `period` (`month`) и `tax_basis` (`net` или `gross`); см. раздел Потребности ниже. Условия приглашения переиспользуют `SalaryRange` с теми же правилами. - -### Ошибки ML-сервиса - -ML-сервис отвечает на ошибки той же схемой `Problem`. Его перечисление `ProblemCode` сохраняет публичные коды identity, чтобы оба контракта имели одну форму, но сервис их никогда не возвращает. Валидация запроса FastAPI дает 400 `validation_failed`. HTTP-исключение внутри сервиса преобразуется по статусу: 400, 401, 403, 404, 405, 409 (`state_conflict`), 412, 413, 415, 428, 429, 501 и 503 (`service_unavailable`, пока модель не готова) - в свои коды, 422 - в 400 `validation_failed`, любой другой 4xx - в 400 `validation_failed`, любой другой 5xx - в 500 `internal`. Необработанное исключение дает 500 `internal` внутри приложения, поэтому Starlette не пробрасывает его в uvicorn; в лог попадает только тип. Сервис также направляет логгеры uvicorn через свой JSON-формат, который сохраняет только тип исключения записи, но не текст и не traceback. - -### Контракт исполнителя кода - -`runner/openapi.yml` описывает внутренний API исполнителя кода, который вызывает только Go backend. Go-клиент генерируется ogen по `backend/codegen/ogen-code-runner.yml` в `backend/internal/adapter/secondary/code_runner/api/`; его пока не вызывает ни один usecase. - -- Транспорт и вход. Исполнитель слушает частный интерфейс своего хоста по HTTPS (TLS 1.3). Все операции, кроме `/healthz` и `/readyz`, требуют `Authorization: Bearer `; токен - общий случайный секрет не короче 32 символов из хранилища секретов развертывания. Неверный или отсутствующий токен дает 401 `unauthenticated`. Простой HTTP разрешен только явным переключателем локального dev Compose. -- Данные. `RunRequest` содержит только язык, исходный код, лимиты и группы тестов; у каждой группы есть метка, видимость (`public` или `hidden`), вид checker и тесты с входом и ожидаемым выводом. Полей кандидата, аккаунта, попытки, задания или компании нет; `scripts/test_runner_contract.py` проверяет это для всех схем запросов, а также `additionalProperties: false` у каждого объекта запроса. -- Идемпотентность. `PUT /v1/runs/{run_id}` (`SubmitRun`) принимает случайный UUID от backend. Новый ID при свободном слоте запускает прогон и отвечает 202, тот же ID с тем же телом возвращает текущее состояние с 200 без повторного запуска, тот же ID с другим телом дает 422 `idempotency_key_reused`. Тела сравниваются по SHA-256 отпечатку разобранного запроса. Когда все слоты заняты или процесс останавливается, ответ - 503 `runner_busy` с `Retry-After`; ничего не сохраняется, очередь держит backend. -- Результат. `GetRun` возвращает `state` (`running` или `finished`) и итог по каждой группе: `accepted`, `wrong_answer`, `compile_error`, `time_limit_exceeded`, `memory_limit_exceeded`, `output_limit_exceeded`, `runtime_error` или `infrastructure_failure`, число пройденных тестов, время CPU и пиковую память. `limit` называет сработавший лимит (`cpu_time`, `wall_time`, `memory`, `output`, `processes`). Диагностика stderr есть только у публичных тестов; у скрытых тестов нет вывода программы. -- Языки: `python3` и `go`. Go компилируется отдельной фазой со своими лимитами; ошибка компиляции дает `compile_error` без запуска тестов. -- Checker задается для группы: `exact` (сравнение после нормализации CRLF, хвостовых пробелов строк и пустых строк в конце), `tokens` (последовательности токенов по ASCII-пробелам), `numbers` (как `tokens`, но числа равны в пределах `abs_tolerance` или `rel_tolerance`) и `custom` (`program` с языком и исходником checker семейства заданий; он работает в nsjail, читает файлы input, expected и actual и отвечает кодом выхода 0 или 1). Сервер отклоняет параметры, не подходящие виду checker. -- Ошибки используют форму `Problem` из api/core; перечисление `ProblemCode` свое: `validation_failed`, `unauthenticated`, `not_found`, `method_not_allowed`, `payload_too_large`, `unsupported_media_type`, `idempotency_key_reused`, `internal` и `runner_busy`. Совпадение формы с api/core проверяет `scripts/test_runner_contract.py`. - -### Identity: сессии, cookie и CSRF - -Тег `identity` описывает регистрацию, подтверждение email, вход, выход и текущий аккаунт. Все операции есть в контракте. `RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, `ConfirmEmailByCode`, `Login`, `GetCurrentSession`, `Logout` и `GetCurrentAccount` реализованы в backend. Session boundary аутентифицирует все операции, защищенные контрактом; principal создается только из действующей PostgreSQL-сессии подтвержденного аккаунта. Помимо identity и перечисленных ниже операций согласий, защищенные бизнес-операции пока проходят security boundary и отвечают 501 `not_implemented` после проверки запроса. Экраны регистрации и подтверждения во frontend остаются заглушками. - -| Метод и путь | operationId | Защита | Успех | Конкретные ошибки | -| --- | --- | --- | --- | --- | -| `GET /api/v1/identity/consent-texts/{purpose}` | `GetConsentText` | публичная | 200 `ConsentText` | 400 `validation_failed` | -| `POST /api/v1/identity/registrations` | `RegisterAccount` | публичная, Idempotency-Key | 202 `IdentityRequestAccepted` | 400 `validation_failed`, 403 `csrf_check_failed`, 409 `idempotency_in_progress`, 422 `idempotency_key_reused`, 429 | -| `POST /api/v1/identity/email-verification-requests` | `ResendEmailVerification` | публичная | 202 `IdentityRequestAccepted` | 400, 403 `csrf_check_failed`, 429 | -| `POST /api/v1/identity/email-verifications` | `ConfirmEmail` | публичная | 200 `EmailVerificationResult` | 400 `verification_token_expired`, `verification_token_invalid` или `validation_failed`; 403 `csrf_check_failed`; 429 | -| `POST /api/v1/identity/email-verifications/code` | `ConfirmEmailByCode` | публичная | 200 `EmailVerificationResult` | 400 `verification_token_invalid` или `validation_failed`; 403 `csrf_check_failed`; 429 | -| `POST /api/v1/identity/sessions` | `Login` | публичная | 201 `Session`, `Set-Cookie`, `Cache-Control: no-store` | 400, 401 `invalid_credentials`, 403 `email_not_verified` или `csrf_check_failed`, 429 | -| `GET /api/v1/identity/sessions/current` | `GetCurrentSession` | сессия | 200 `Session`, `Cache-Control: no-store` | 401 `unauthenticated` | -| `DELETE /api/v1/identity/sessions/current` | `Logout` | сессия и CSRF | 204, `Set-Cookie` удаляет cookie | 401 `unauthenticated` (тоже удаляет cookie), 403 `csrf_check_failed` | -| `GET /api/v1/identity/me` | `GetCurrentAccount` | сессия | 200 `Account`, `Cache-Control: no-store` | 401 `unauthenticated` | - -Каждая операция также объявляет problem-ответ `default`. - -Регистрация и подтверждение: - -- Аккаунты не перечисляются. Регистрация и повторная отправка отвечают одинаковым нейтральным 202 для нового, неподтвержденного, подтвержденного и неизвестного email. Вход отвечает одинаковым 401 `invalid_credentials` для неизвестного email, неверного пароля и некорректного сохраненного хеша; для неизвестного email и некорректного хеша выполняется дополнительная работа Argon2id. Верный пароль неподтвержденной учетной записи дает 403 `email_not_verified` и не создает сессию. -- До поиска email сервер проверяет все тело регистрации (длину пароля после нормализации NFKC, blocklist паролей, версию C1) и в каждой ветке вычисляет хеш Argon2id, поэтому ни 400, ни время ответа не зависят от существования аккаунта. -- Повторная регистрация неподтвержденного email никогда не меняет хеш пароля, сценарий и шаг онбординга строки аккаунта. Каждая регистрация, первая и каждая повторная, хранит свои отложенные учетные данные (хеш пароля, сценарий и первый шаг онбординга) на своем токене подтверждения, заменяет запись C1, увеличивает версию регистрации и аннулирует прежние токены. `ConfirmEmail` требует пароль этой регистрации и проверяет его по отложенному хешу именно нажатого токена. В одной транзакции сервер проверяет текущую версию регистрации и связанную с ней запись C1, погашает токен, отмечает email подтвержденным, применяет отложенные данные токена к аккаунту, очищает поля `pending_*` и записывает ровно одно событие `identity.email_verified`. При любом отказе состояние аккаунта и токена не меняется. Неизвестный, использованный, замененный или устаревший токен, неверный пароль и отсутствие отложенных данных дают 400 `verification_token_invalid`; истекший токен дает 400 `verification_token_expired`. Так владелец адреса, перешедший по чужой ссылке, не принимает пароль, выбранный другим регистрантом, и наоборот. Подтверждение не создает сессию или cookie; вход доступен отдельно и принимает только пароль подтвержденной учетной записи. -- Реализация регистрации, повторной отправки и входа. Подтвержденный адрес при регистрации: ничего не меняется и ничего не отправляется (уведомление "у вас уже есть аккаунт" не реализовано). Лимиты на почту (общие для регистрации и повторной отправки, ключ - HMAC нормализованного адреса, считаются независимо от наличия аккаунта): не реже `VERIFICATION_MAIL_MIN_INTERVAL` (по умолчанию 60 с) между письмами и не больше `VERIFICATION_MAIL_DAILY_LIMIT` (по умолчанию 5) за 24 часа. `IDENTITY_CLIENT_HOURLY_LIMIT` (по умолчанию 30 в час, диапазон 1..10000) ограничивает регистрацию, подтверждение, повторную отправку и вход по адресу клиента, если он разрешен доверенной цепочкой. `IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT` (по умолчанию 10 в час, диапазон 1..10000) ограничивает вход по нормализованному email независимо от наличия аккаунта. `ConfirmEmail` дополнительно ограничивает каждый токен до 5 попыток в час и использует лимит клиента. Отклоненный запрос дает 429 `rate_limited` с `Retry-After`. Политика замены токена: каждый выпуск сначала аннулирует все неиспользованные токены подтверждения аккаунта, поэтому работает одна ссылка; повторная отправка меняет только токен. `IDENTITY_KEY_SECRET` (не меньше 32 байт, обязателен; `IDENTITY_ALLOW_EPHEMERAL_KEY=true` разрешает случайный на стенде разработки) ключует область идемпотентности, отпечаток, лимиты и session CSRF. Параллельный запрос с тем же ключом ждет первый и воспроизводится, поэтому `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 тела. Тело, пароль и их простые хеши не хранятся, а секрет не дает использовать отпечаток для офлайн-проверки пароля. -- Запрос `ConfirmEmail` принимает и `token`, и выбранный при этой регистрации `password`; прежние клиенты, отправлявшие только токен, нужно обновить. Пароль обрабатывается по правилам `LoginPassword`: NFKC-нормализация и от 1 до 128 кодовых точек; blocklist регистрации повторно не применяется. `Origin` должен совпадать с `APP_PUBLIC_URL`; отсутствующий Origin, значение null или посторонний Origin дают 403 `csrf_check_failed`. Endpoint ограничивает попытки подтверждения одним токеном до 5 в час и применяет общий лимит клиента `IDENTITY_CLIENT_HOURLY_LIMIT`; отказ по лимиту дает 429 `rate_limited` с `Retry-After`. -- Запрос `ConfirmEmailByCode` принимает `email`, `code` (ровно шесть цифр, `VerificationCode`) и `password` - пароль регистрации, которая выпустила код. Любой отказ, включая неизвестный адрес, неверный или истекший код, неверный пароль и аннулированный токен, отвечает 400 `verification_token_invalid`; некорректное тело отвечает 400 `validation_failed` с указателем `/code`, `/email` или `/password`. Пять неудачных проверок одного открытого кода аннулируют его токен, и ссылка тоже перестает работать. Код действует 30 минут или до конца срока токена, если токен заканчивается раньше. Лимит адреса общий со входом (`IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT`), лимит клиента - `IDENTITY_CLIENT_HOURLY_LIMIT`. Успех отвечает тем же телом, что и `ConfirmEmail`, и сессию не создает. Подробности: [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#регистрация-подтверждение-и-повторная-отправка). -- Ссылка подтверждения имеет вид `/verify-email#token=`. Экран подтверждения во frontend пока остается заглушкой. Клиентская страница должна удалить фрагмент через `history.replaceState`, запросить явное действие пользователя и отправить токен вместе с паролем регистрации; сканер ссылок, который только открывает страницу, не расходует токен. -- Истекший токен дает `verification_token_expired`; неизвестный, использованный, замененный или устаревший по версии, неверный пароль и отсутствие отложенных данных дают `verification_token_invalid`. В обоих случаях клиент предлагает новую ссылку; после подтверждения пользователь может отдельно войти. Повторное подтверждение использованным токеном намеренно не дает идемпотентный 200: по одному токену успешен ровно один запрос. - -Согласие C1 и аккаунт: - -- `GetConsentText(c1)` возвращает текущий текст C1, его `text_version` и `published_at`. Регистрация передает эту версию в `consent_c1`; сервер записывает ее вместе с хешем того же сохраненного текста. Версия, которая больше не текущая, дает 400 `validation_failed` с pointer `/consent_c1/text_version`, и клиент читает текст заново. Отдельный код вызвал бы то же действие клиента, а pointer поля уже указывает причину, поэтому новый код не добавлен. -- Неизвестные поля тела отклоняются, поэтому никакое другое согласие, включая C4, не может войти в регистрацию. -- Пароль нормализуется в NFKC и должен содержать от 15 до 128 кодовых точек Unicode, без правил состава. Сгенерированные Zod-валидаторы считают кодовые единицы UTF-16, поэтому длину окончательно проверяет сервер. -- У аккаунта есть `scenario` (`candidate` или `employer`) и сохраненный `onboarding_step`, который продвигает сервер; после входа клиент возвращает пользователя на этот шаг. Шаги кандидата: `candidate_consents`, `candidate_profile`, `candidate_questionnaire`, `candidate_assessment` и `completed`; у работодателя - `employer_company` и `completed`. DTO никогда не содержат хеши паролей, хеши токенов или идентификаторы сессий. - -Сессии и CSRF: - -- Реализованные операции сессии: Login выдает cookie `__Host-lincodex_session` с `Path=/; Secure; HttpOnly; SameSite=Strict`, без Domain, и с Expires/Max-Age до абсолютного срока. PostgreSQL хранит только SHA-256 хеш cookie token; GET текущей сессии возвращает аккаунт и CSRF-токен после перезагрузки. Успешный вход отзывает действующую сессию из запроса и создает новую транзакционно; войти может только подтвержденный аккаунт. Logout отзывает сессию и очищает cookie; устаревшая или отозванная cookie также очищается с ответом 401. `IDENTITY_SESSION_IDLE_TIMEOUT` по умолчанию `24h` (от `1m` до `30d`), а `IDENTITY_SESSION_ABSOLUTE_LIFETIME` по умолчанию `168h` (от `1m` до `365d`); idle timeout не может превышать absolute lifetime, некорректные значения останавливают запуск. Запросы продлевают только idle deadline. -- Схема `sessionCsrf` - заголовок `X-CSRF-Token` с токеном для текущей сессии из `Session.csrf_token`. Backend выводит его через domain-separated HMAC-SHA-256 из cookie token и `IDENTITY_KEY_SECRET`, сравнивает за постоянное время и не хранит в БД. Все экземпляры должны использовать один `IDENTITY_KEY_SECRET` (не менее 32 байт), одинаковый между перезапусками; смена ключа делает прежние CSRF-токены недействительными, но не отзывает сессии PostgreSQL. Любая небезопасная операция, требующая `sessionCookie`, обязана требовать и `sessionCsrf`; это проверяет `TestUnsafeSessionOperationsRequireCSRFToken` в backend по bundle. Клиент хранит токен только в памяти и восстанавливает его через `GetCurrentSession` после перезагрузки страницы или после 403 `csrf_check_failed`. -- Каждая небезопасная публичная identity-операция требует ровно один заголовок `Origin`, совпадающий с `APP_PUBLIC_URL`, включая `RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail` и `Login`. Небезопасные защищенные операции также требуют session-bound CSRF-токен. Проверка Origin не использует `Host` или forwarded headers. Публичные identity-операции ограничены по частоте (429 с `Retry-After`). -- Ответы с сессией или аккаунтом несут `Cache-Control: no-store`. -- Корневой `security` требует `sessionCookie`, поэтому операция без явного `security: []` защищена по умолчанию. - -Как сгенерированный сервер (ogen v1.24.0) проверяет схемы и как `v1.SessionSecurity` применяет текущую session boundary, закреплено тестом `TestGeneratedServerSecurityOrder`: - -- Он вызывает `HandleSessionCookie` раньше `HandleSessionCsrf` и передает дальше контекст, возвращенный успешным вызовом. Отсутствующее значение (нет cookie, пустой `X-CSRF-Token`) не вызывает обработчик, а обработчик, вернувший `ogenerrors.ErrSkipServerSecurity`, считается невыполненным; в обоих случаях проверка продолжается со следующей схемы, поэтому `HandleSessionCsrf` вызывается и без cookie, с исходным контекстом. -- Любая другая ошибка обработчика останавливает проверку и попадает в `NewError` как `SecurityError` с `Security`, равным `SessionCookie` или `SessionCsrf`. Невыполненное требование попадает в `NewError` как `SecurityError` с `ErrSecurityRequirementIsNotSatisfied` и без поля `Security`. -- Реализованное отображение: `HandleSessionCookie` аутентифицирует каждую операцию, для которой контракт требует `sessionCookie`; отсутствующая, неизвестная, истекшая, отозванная или неподтвержденная сессия отвечает 401 `unauthenticated`. Для небезопасных защищенных операций `HandleSessionCsrf` проверяет точный Origin и токен той же сессии. Без подтвержденного principal результат - 401; с ним отсутствующий или неверный Origin либо CSRF дает 403 `csrf_check_failed`. Ответ 401 от `Logout` также очищает cookie, а 403 сохраняет действующую сессию. - -### Каталог и анкета - -Теги `catalog` и `candidate` описывают каталог специализаций и анкету кандидата (FR03 в PRD). Каталог публичный и отвечает 501 `not_implemented`, пока не появится его обработчик. Анкета защищена: гость получает 401 `unauthenticated`, а запрос с действующей сессией проходит security boundary и после проверки запроса достигает 501 `not_implemented`. Небезопасные защищенные операции также требуют session-bound CSRF-токен и точный Origin. - -| Метод и путь | operationId | Защита | Успех | Конкретные ошибки | -| --- | --- | --- | --- | --- | -| `GET /api/v1/specializations` | `GetSpecializationCatalog` | публичная | 200 `SpecializationCatalog` | нет | -| `GET /api/v1/me/questionnaire` | `GetMyQuestionnaire` | сессия | 200 `CandidateQuestionnaire`, `Cache-Control: no-store` | 401 `unauthenticated`, 403 `forbidden` | -| `PUT /api/v1/me/questionnaire` | `SaveMyQuestionnaire` | сессия и CSRF | 200 `CandidateQuestionnaire`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `csrf_check_failed` или `forbidden`, 412 `version_conflict` | - -Каждая операция также объявляет problem-ответ `default`. - -Каталог: - -- Пять направлений и девять специализаций: Разработка (`backend`, `frontend`, `mobile`), Инфраструктура (`network_engineer`, `devops_sre`), Данные (`data_analyst`, `ds_ml`), Безопасность (`information_security`), Качество (`qa`). Шкала грейдов MVP: `intern`, `junior`, `middle`, `senior`; Lead и Architect появятся после MVP. Коды заданы перечислениями, поэтому новое значение - изменение контракта. Названия - русский простой текст. -- Категория - это специализация вместе с подтвержденным грейдом. Языки заданий (`python`, `go`) и теги стека - атрибуты выбранной специализации и никогда не образуют категорию: Backend с Go - это категория `backend`. Алгоритмы - общий модуль оценки, а не специализация. -- У каждой специализации есть `test_availability`: `status` (`available` или `in_development`), `grades` с опубликованным банком заданий и `task_languages`, которые этот банк предлагает. MVP открывает оценку только для категории с опубликованным банком. Сервер выводит значения из опубликованных банков, поэтому они меняются без изменения контракта; пример в контракте иллюстративный и ничего не говорит о развернутом банке. -- Каталог публичный (`security: []`): он одинаков для всех, не содержит персональных данных, показывается до регистрации и может кешироваться. - -Анкета: - -- Кандидат берется из сессии; аккаунт работодателя получает 403 `forbidden`. Кандидат без сохраненной анкеты получает 200 с `version: 0`, без специализаций и с null в `work_context` и `updated_at`, а не 404, поэтому первое сохранение читает версию так же, как последующие. -- У каждой выбранной специализации есть `self_assessed_grade`, `task_languages`, `stack` и `experience` в месяцах или null, если опыт не указан; `work_context` содержит только допустимые форматы работы и не содержит персональных данных. Анкета никогда не содержит подтвержденный грейд или категорию, а неизвестные поля, например `confirmed_grade`, дают 400. Самооценка - это ожидаемый грейд, который шаг онбординга `candidate_assessment` предлагает первым; она влияет на старт оценки, но не добавляет баллов, и ни самооценка, ни тег стека вроде "Senior" не присваивают категорию. Реальный профиль не виден работодателям, пока оценка не подтвердит категорию. -- При сохранении схема допускает одну или две специализации и отклоняет неизвестные специализацию, грейд, язык заданий или формат работы. JSON Schema `uniqueItems` не умеет сравнивать элементы массива по одному полю, поэтому повтор специализации отклоняет сервер: 400 с pointer `/specializations//specialization`. Сервер также отклоняет язык заданий, которого нет в опубликованном банке специализации, с pointer на этот язык. Специализацию с тестом `in_development` выбрать можно; оценка для нее не начинается. -- Конкурентные изменения контролирует `expected_version` в теле, а не If-Match, потому что сгенерированный клиент пока не читает заголовок `ETag`. Первое сохранение отправляет 0. Устаревшее значение дает 412 `version_conflict` - тот же статус и код, что при несовпадении If-Match, потому что действие клиента то же: прочитать анкету снова. `version_conflict` сохраняет статус 412, поэтому `state_conflict` (409) здесь не используется. -- PUT заменяет анкету целиком, и Idempotency-Key ему не нужен. Тело, равное сохраненному состоянию, ничего не меняет, сохраняет версию и дает 200 даже со старым `expected_version`, поэтому повтор после потерянного ответа не падает с 412. -- Порядок проверок при сохранении: сессия (401), CSRF и Origin (403), валидация запроса (400), сценарий аккаунта (403 `forbidden`), доменные правила (400), версия (412). `TestQuestionnaireSchemaValidationPrecedesImplementation` проверяет отказы схемы через сгенерированный сервер. - -### Профиль кандидата - -Тег `candidate` включает реализованные `GetMyProfile` и `SaveMyProfile` для приватного ручного профиля. Подтвержденный кандидат читает и меняет только свой профиль; работодатель получает 403, гость - 401. PUT требует CSRF-токен сессии и точный Origin. Данные, версия, подтверждения пересечений, история и переход шага сохраняются одной транзакцией. Без DATABASE_URL остается ответ 501. `confirmed_categories` только читается: одна категория на специализацию в порядке каталога из результатов оценки, с `basis` (`synthetic_demo` для демонстрационной категории), `confirmed_at` и `attempt_id`; ни один запрос ее не принимает. - -| Метод и путь | operationId | Защита | Успех | Конкретные ошибки | -| --- | --- | --- | --- | --- | -| `GET /api/v1/me/profile` | `GetMyProfile` | сессия | 200 `CandidateProfile`, `Cache-Control: no-store` | 401 `unauthenticated`, 403 `forbidden` | -| `PUT /api/v1/me/profile` | `SaveMyProfile` | сессия и CSRF | 200 `CandidateProfile`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `csrf_check_failed` или `forbidden`, 412 `version_conflict` | -| `POST /api/v1/me/profile/repository-checks` | `RequestMyRepositoryChecks` | сессия и CSRF | 202 `ProfileRepositoryCheckRequest`, `Cache-Control: no-store` | 401, 403 `csrf_check_failed` или `forbidden`, 429 `rate_limited` с Retry-After | - -Каждая операция также объявляет problem-ответ `default`. Новый код problem не добавляется: контракт использует `validation_failed`, `unauthenticated`, `forbidden`, `csrf_check_failed` и `version_conflict`. - -`experience_overlaps` перечисляет пересекающиеся включительные месяцы и состояние решения. Перед измененным сохранением требуется явное `confirmed_parallel_periods` с индексами и точными датами этой версии; прежнее решение переносится только при тех же индексах и датах. Сохраненный неподтвержденный overlap допускает точный no-op, но не изменение других полей без решения. История добавляется только при изменении. Успешный PUT переводит только `candidate_profile` в `candidate_questionnaire`; ранний `candidate_consents` и поздние шаги не меняются. Завершение шага согласий пока не имеет отдельной операции. - -Состав профиля: - -- Полное имя и контакты (`full_name`, `contacts.email`, `contacts.phone`, `contacts.telegram`), стек (`stack`, теги `StackTag`), роли (`roles`: специализация каталога и самооценка грейда), опыт работы (`experience`: записи с периодом по месяцам `YYYY-MM`, специализацией и описанием задач, а не названием должности), софт-скиллы (`soft_skills`, свободный текст) и условия (`terms`: место, готовность к переезду и минимальная зарплата с валютой, периодом и налоговой базой). Это ПДн кандидата; каждое такое поле в описании схемы помечено как персональные данные, а значения не попадают в логи, метрики, URL и события. -- Контакты - ровно те четыре вида, которые может раскрыть согласие C4 (`ContactFieldKind`), с теми же форматами (E.164, `@` у Telegram, одна строка до 200 символов для имени), поэтому раскрытие никогда не преобразует и не отбрасывает сохраненное значение. Контактный email профиля - не логин аккаунта: сервер не отправляет на него почту и не проверяет его. -- Допустимые форматы работы в профиле не повторяются: они остаются только в `WorkContext` анкеты. -- Профиль закрыт: его читает только владелец, а ни одна схема организации, приглашения или потребности его не ссылает (`$ref`). Организация видит кандидата только через анонимную карточку и, после принятого приглашения, через контактное разрешение. Минимальная зарплата не раскрывается организации никогда; приглашение показывает только индикатор совместимости, который считает сервер. - -Самооценка и подтвержденная категория: - -- Грейд роли (`roles[].self_assessed_grade`) - заявление кандидата, то же, что анкета называет `self_assessed_grade`; он ничего не добавляет и никогда не становится подтвержденным грейдом. Подтвержденная категория - отдельный список `confirmed_categories` (специализация, грейд, время и попытка оценки, которая его подтвердила). Он только для чтения, сервер выводит его из результатов оценки, ни один запрос его не несет, а в хранилище профиля для него нет столбца. Запрос с полем `confirmed_grade`, `category` или `confirmed_categories` отклоняется как неизвестное поле. - -Источник и подтверждение: - -- Каждое значение несет `status` и `source`. У одиночного поля `status` равен `confirmed`, `extracted` или `unknown`; при `unknown` значение и источник равны null, а сервер ничего не подставляет по умолчанию. У элемента списка `status` равен `confirmed` или `extracted`. `source` - `origin` (`manual`; запланированы `extracted_from_resume` и `imported`, ни одна операция MVP их не создает), `trust_level`, `quote`, `extraction_version` и `confirmed_at`. -- Каждое заявление профиля имеет `trust_level` 0, какой бы ни был источник: ограничение схемы (`minimum` и `maximum` равны 0), CHECK в базе и тип в домене. Подтверждение предложения меняет статус, а не уровень; более высокие уровни относятся к доказательствам (результату оценки, подтверждению третьей стороной), которые хранятся отдельно и не записываются в заявление. -- Запрос несет решение по каждому значению (`value` и `status`): `confirmed` задает ручное значение или подтверждает сохраненное предложение с тем же значением (тогда источник и цитата сохраняются), `extracted` оставляет сохраненное предложение неподтвержденным и допустим только с точно тем же значением. Любое другое использование `extracted` дает 400 с pointer на этот статус, например `/stack/1/status`, поэтому форма без изменений ничего не подтверждает случайно, как и в потребностях. Источник, уровень доверия и время подтверждения клиент не отправляет. - -Версия и повторы: - -- Версия начинается с 0 для кандидата без сохраненного профиля; такой кандидат получает 200 со всеми полями `unknown` и пустыми списками, а не 404. `PUT` заменяет профиль целиком, а список заменяет список; поле, посланное как null, становится неизвестным и удаляется. -- Конкурентные изменения контролирует `expected_version` в теле, как в анкете: сгенерированный клиент пока не читает `ETag`. Устаревшее значение дает 412 `version_conflict` без изменений, и клиент читает профиль заново; правка из другой вкладки не теряется молча. Тело без изменений сохраняет версию и дает 200 даже со старой версией, поэтому Idempotency-Key не нужен. Каждое сохраненное изменение увеличивает версию на единицу. -- Порядок проверок: сессия (401), CSRF и Origin (403 `csrf_check_failed`), валидация запроса (400), сценарий аккаунта (403 `forbidden` для работодателя), версия выше текущей (412), доменные правила, зависящие только от тела (400), затем правила, зависящие от сохраненных заявлений, и версия: решение `extracted` не для сохраненного предложения при устаревшей версии дает 412 (другая вкладка могла подтвердить значение), при текущей - 400; тело без изменений - 200; любое другое изменение по устаревшей версии - 412. Версия выше текущей никогда не существовала и дает 412 даже для тела без изменений. Доменные правила, которые схема не выражает: повтор тега, навыка или специализации роли (без учета регистра для тегов и навыков), период, который кончается раньше начала или лежит в будущем, и решение `extracted` не для сохраненного предложения. Ответ 400 не повторяет присланное значение. - -Без файла, ML и ФСП: - -- Профиль полностью заполняется вручную. Ни одно поле не требует резюме, извлечения ML или аккаунта ФСП, а миграция и запросы не создают обязательной связи с файлом, ML или ФСП. Загрузка резюме и привязка ФСП ID - запланированные аддитивные возможности; они добавят свои поля и источники, не меняя этих. - -Связь с анкетой: - -- Анкета (`/me/questionnaire`) задает не более двух специализаций для оценки; профиль - то, что кандидат показывает о себе. Одноименные понятия не дублируются под разным смыслом: самооценка грейда и стек - одно и то же заявление в двух местах (в анкете для старта оценки и по специализации, в профиле для показа), сохраняются раздельно, и сервер не копирует одно в другое; общий опыт в месяцах в анкете и записи опыта в профиле - разные заявления; форматы работы живут только в анкете, а место, переезд и зарплата - только в профиле. Описания схем обеих сторон ссылаются друг на друга. - -Хранение (миграция 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#профиль-кандидата). - -Открытые вопросы к владельцу продукта и юристу: - -- Виды контактов: допустимы только четыре вида C4. Нужны ли ссылки на GitHub, соцсети или сайт (PRD прячет их до принятия приглашения), и тогда это изменение контракта и в `ContactFieldKind`. -- Основание по 152-ФЗ: какое согласие покрывает хранение профиля (C1 при регистрации или отдельное), нужны ли отдельные согласия для имени и контактов, сроки хранения и порядок удаления. Сейчас удаление аккаунта каскадно удаляет профиль, а правил хранения нет. -- Порядок версии и доменных правил: выбрано проверять версию раньше правил, зависящих от сохраненных заявлений (устаревшая вкладка получает 412, а не 400); нужно подтверждение владельца продукта. -- Полная замена: `PUT` удаляет сохраненные предложения импорта, которых клиент не показал и не вернул со статусом `extracted`; допустимо ли это или сервер должен сохранять непоказанные предложения. -- Минимум для шага онбординга `candidate_profile`: текущий контракт не требует ни одного поля, поэтому любой успешный PUT завершает этот шаг, включая пустой no-op. Введение обязательных полей потребует отдельного решения владельца продукта и изменения контракта. -- Единый источник между анкетой и профилем: оставить самооценку и стек независимыми или хранить одно заявление и показывать в обоих местах. -- Софт-скиллы: таксономии нет, свободный текст до 10 штук по 50 символов; нужен ли справочник. -- Опыт: названия работодателей и описания - ПДн; как анонимная карточка их обобщает (PRD: отрасль и размер), решает контракт карточки, а не этот. -- Проверка контактов (подтверждение телефона или email профиля) не предусмотрена: контакты - заявления уровня 0. - -`TestCandidateProfileOperationsFollowTheConventions`, `TestCandidateProfileSeparatesSelfAssessedGradeFromConfirmedCategory`, `TestCandidateProfileClaimsCarrySourceAndTrustLevelZero`, `TestPrivateProfileSchemasAreNotMixedWithOrganizationVisibleDTOs`, `TestGeneratedProfileDTOsCarryNoConfirmedGradeInRequests`, `TestProfileSchemaValidationPrecedesImplementation` и `TestProfileAccessBeforeImplementation` закрепляют сгенерированный сервер и бандл, а `frontend/src/shared/api/profile-contract.test.ts` - сгенерированные правила Zod, типы запросов без подтвержденного грейда и отсутствие полей профиля в схемах организации, приглашения и потребности. - - -Проекты: необязательный в теле `SaveMyProfile` список `projects` (до 10; отсутствие сохраняет проекты, пустой массив удаляет) с названием, описанием, тегами и адресом `https://github.com//`; другие адреса дают 400 с указателем `/projects//repository_url`. Ответ `CandidateProfile` несет `projects[].repository_check` (`pending`, `verified`, `not_found`, `unavailable`). `RequestMyRepositoryChecks` повторяет проверки на `api.github.com` не чаще интервала стенда. Публикация проектов в карточке - отдельное поле `projects` в `CardField` (см. [архитектуру](../docs/ru/ARCHITECTURE.md#проекты-кандидата-и-репозитории-github)). -### Оценка - -Тег `assessment` описывает попытки оценки текущего кандидата (FR04 и FR05 в PRD): доступность, старт и возобновление, ответы вместе с кодовой практикой, завершение и результат. Операции есть в контракте, но их бизнес-логика еще не реализована: гость получает 401 `unauthenticated`, а запрос с подтвержденной сессией достигает 501 `not_implemented` после проверки запроса. Небезопасные защищенные операции также требуют session-bound CSRF-токен и точный Origin. - -| Метод и путь | operationId | Защита | Успех | Конкретные ошибки | -| --- | --- | --- | --- | --- | -| `GET /api/v1/me/assessment-availability` | `GetMyAssessmentAvailability` | сессия | 200 `AssessmentAvailability`, `Cache-Control: no-store` | 401 `unauthenticated`, 403 `forbidden` | -| `POST /api/v1/me/assessment-attempts` | `CreateMyAssessmentAttempt` | сессия и CSRF, Idempotency-Key | 201 `AssessmentAttempt`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `csrf_check_failed` или `forbidden`, 409 `state_conflict` или `idempotency_in_progress`, 422 `idempotency_key_reused`, 429 | -| `GET /api/v1/me/assessment-attempts/{attempt_id}` | `GetMyAssessmentAttempt` | сессия | 200 `AssessmentAttempt`, `Cache-Control: no-store` | 401, 403 `forbidden`, 404 `not_found` | -| `POST /api/v1/me/assessment-attempts/{attempt_id}/sessions` | `StartMyAssessmentAttemptSession` | сессия и CSRF, Idempotency-Key | 200 `AssessmentAttempt`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict` или `idempotency_in_progress`, 412 `version_conflict`, 422, 429 | -| `POST /api/v1/me/assessment-attempts/{attempt_id}/answers` | `SubmitMyAssessmentAnswer` | сессия и CSRF, Idempotency-Key | 200 `AssessmentAttempt`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict` или `idempotency_in_progress`, 412 `version_conflict`, 422, 429 | -| `POST /api/v1/me/assessment-attempts/{attempt_id}/practice-runs` | `CreateMyAssessmentPracticeRun` | сессия и CSRF, Idempotency-Key | 202 `PracticeRun`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict`, 422, 429 `rate_limited`, 503 `service_unavailable` | -| `GET /api/v1/me/assessment-attempts/{attempt_id}/practice-runs/{run_id}` | `GetMyAssessmentPracticeRun` | сессия | 200 `PracticeRun`, `Cache-Control: no-store` | 401, 403 `forbidden`, 404 `not_found` | -| `PUT /api/v1/me/assessment-attempts/{attempt_id}/work-session` | `HoldMyAssessmentWorkSession` | сессия и CSRF, `X-Attempt-Client` | 200 `AssessmentWorkSession`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict` (сеанс занят другой страницей или у попытки нет рабочего сеанса) | -| `DELETE /api/v1/me/assessment-attempts/{attempt_id}/work-session` | `ReleaseMyAssessmentWorkSession` | сессия и CSRF, `X-Attempt-Client` | 204, `Cache-Control: no-store` | 400, 401, 403, 404 | -| `POST /api/v1/me/assessment-attempts/{attempt_id}/finalize` | `FinalizeMyAssessmentAttempt` | сессия и CSRF, Idempotency-Key | 200 `AssessmentAttempt`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict` или `idempotency_in_progress`, 412 `version_conflict`, 422 | -| `GET /api/v1/me/assessment-attempts/{attempt_id}/result` | `GetMyAssessmentResult` | сессия | 200 `AssessmentResult`, `Cache-Control: no-store` | 401, 403 `forbidden`, 404 `not_found`, 409 `state_conflict` | -| `GET /api/v1/me/assessment-results` | `ListMyAssessmentResults` | сессия | 200 `AssessmentResultHistoryPage`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `forbidden` | -| `GET /api/v1/me/assessment-signal-notice` | `GetMyAssessmentSignalNotice` | сессия | 200 `AssessmentSignalNotice`, `Cache-Control: no-store` | 401, 403 `forbidden` | -| `PUT /api/v1/me/assessment-signal-notice` | `AcknowledgeMyAssessmentSignalNotice` | сессия и CSRF | 200 `AssessmentSignalNotice`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `csrf_check_failed` или `forbidden`, 409 `state_conflict` | - -Каждая операция также объявляет problem-ответ `default`. - -Уведомление о сигналах (`assessment-signal-notice`) перечисляет сигналы, которые собираются во время реальной попытки: события браузера (потеря фокуса, копирование, вставка и вырезание с размером, выход из полноэкранного режима, сохраняются только при действующем C3) и серверные (время ответа, смена сетевого адреса, параллельные сессии, сравнение отпечатков ответов; хранятся только односторонние ключевые отпечатки, адреса и токены сессий не хранятся). `GET` возвращает версию уведомления, которую требует сервер, и признак, что кандидат ее подтвердил; `PUT` сохраняет подтверждение для аккаунта и этой версии. Подтверждение - запись о том, что кандидат ознакомлен, а не согласие: оно не меняет C3, и операция приема сигналов его не читает и не отклоняет пакет без него. `PUT` не требует Idempotency-Key: повтор сохраняет первое время и отвечает 200; другая версия отвечает 409 `state_conflict`. Уведомление также перечисляет меры, которые страница применяет во время реальной попытки (полноэкранный режим, скрытие задания, запрет копирования, выделения и печати текста задания, правило вставки, правило одного окна и водяной знак экрана и текста задания) и прямо говорит, что снимок экрана или фото телефоном предотвратить нельзя, а сигналы ведут только к ручной проверке; это версия 4 текста, и подтверждение более ранней версии для текущей никогда не засчитывается. Режим `demo_express` сигналы не собирает и подтверждения не требует. - -Доступ: - -- Кандидат берется только из сессии; ни одна операция не принимает идентификатор кандидата. Аккаунт работодателя получает 403 `forbidden`. Попытка другого кандидата дает 404 `not_found`, как и неизвестный идентификатор, поэтому идентификаторы попыток нельзя перебирать. -- Ни одна операция не дает работодателю ответы, историю попыток или античит-сигналы. Работодатель видит текущую категорию в анонимной карточке и разрешенные доказательства навыков этой карточки ([Доказательства навыков](#доказательства-навыков)), но не результат. - -Режимы и версии: - -- При создании обязательно передается `kind`: `root`, `corrective` или `demo_express`. Реальная попытка использует `demo_basic` или `adaptive`; сервер выбирает режим по опубликованному банку, клиент его не передает. `demo_basic` оценивает фиксированную форму проверенных демо-заданий по их ключам относительно проходного балла версионированной базовой политики, не вычисляет оценку способности и решает за один шаг: дополнительную практику он не предлагает. `adaptive` - адаптивный тест из FR04. Кандидат может явно запросить `demo_express` - отдельный интерактивный учебный запуск на 3-5 минут без категории, целевого грейда, перцентиля, квоты реальных оценок или квалификационных данных. -- Корректирующая реальная попытка содержит `root_attempt_id`. Сервер разрешает только строго меньший целевой грейд, который еще не проверялся в этой цепочке. Создание корневой попытки резервирует один слот квоты из трех корневых попыток за 180 дней; корректировки используют этот же слот и неизменяемый `chain_deadline` корневой попытки (72 часа от ее старта по текущей политике), но имеют собственные лимиты заданий, практики и сессий. Корректировка не списывает еще один слот, не продлевает срок и не сбрасывает таймеры 30/90 дней. Предварительный отказ в запуске корневой попытки не создает попытку и не резервирует слот. Истечение или незавершенная практика не открывают бесплатную новую цепочку, а недостаточный банк не дает дополнительную корневую квоту. `demo_express` не входит в цепочки корректировок и доступность реальных оценок. -- Создание фиксирует `versions`: `policy_version` (номер версии политики `product`), `bank_version` и `algorithm_version`. Попытка и ее результат хранят их, поэтому результат воспроизводится по сохраненным ответам и этим версиям, а более поздняя версия его не переписывает. -- `version` попытки растет ровно на единицу с каждым зафиксированным изменением: вердикт, явное начало сессии, истечение или автоматическое завершение. GET-операции возвращают только проекцию: они не меняют состояние, не расходуют квоту сессий и не увеличивают версию. Назревшие исходы фиксирует команда или фоновый переход. - -Жизненный цикл попытки и команды, которые принимает каждое состояние: - -| Состояние | Значение | Принимает | -| --- | --- | --- | -| `in_progress` | Идут ответы на задания; `current_item` - задание, на которое нужно ответить | ответ на `current_item` | -| `practice_pending` | Задания пройдены; у основной практики нет готового вердикта (не отправлена, `pending` или `failed`) | решение практики, пока она `not_started` или `failed` | -| `additional_practice_pending` | Только adaptive: завершение нашло вероятность в полосе ниже подтверждения и предложило одну дополнительную практику в той же попытке | решение дополнительной практики, пока она `not_started` или `failed`; завершение в тех же статусах отклоняет предложение | -| `ready_to_finalize` | Все обязательные части выполнены | завершение | -| `completed` | Решение принято; результат доступен | только повтор завершения | -| `expired` | Лимит времени или сессий истек раньше, чем кандидат закончил; результат не подтверждает грейд | ничего | -| `insufficient_bank` | Банк не смог обеспечить покрытие в пределах лимита; результат не подтверждает грейд | ничего | - -- Дополнительная практика (FR04 в PRD): при 0.50 <= P_G < 0.80 в демо-политике первое завершение adaptive-попытки ничего не решает. Оно добавляет в `practices` практику вида `additional`, переводит попытку в `additional_practice_pending` и возвращает попытку. Практика продолжает ту же попытку, сохраняет ее лимиты времени и сессий и не расходует новую попытку. Следующее завершение после ее вердикта принимает решение; если P_G остается ниже 0.80, итог `not_confirmed`. Завершение без отправки практики отклоняет предложение с тем же итогом. `practices` - список с полем `kind`, а не еще одно nullable-поле, поэтому новые виды практики добавляются без ломающих изменений. -- Поэтому завершение всегда отвечает `AssessmentAttempt`, а не результатом и не `oneOf` из двух схем. Когда состояние `completed`, клиент читает `GetMyAssessmentResult`. Один тип ответа делает сгенерированные клиенты однозначными и оставляет место для незавершающих решений без ломающих изменений. -- Лимиты: `expires_at` и `sessions` (`used`, `max`, `idle_timeout_seconds`; null, если политика не задает лимит сессий) берутся из версии политики; FR04 в PRD допускает две сессии в пределах 72 часов. Создание начинает сессию 1. После простоя кандидат явно вызывает `StartMyAssessmentAttemptSession` с последним `expected_version`; следующая сессия начинается только если позволяют квота и срок. Вызов во время активной сессии ничего не меняет. Начало сессии не продлевает `expires_at` или `chain_deadline`. -- При достижении лимитов практика, уже имеющая статус `pending`, сначала оценивается. Затем команда или фоновый переход завершает `ready_to_finalize` как `completed`, отклоняет неотправленную дополнительную практику (`completed`, `not_confirmed`) или переводит `in_progress` и `practice_pending` в `expired`. GET не фиксирует эти переходы. `GetMyAssessmentResult` отвечает 409, пока назревший переход не сохранен. -- Недостаточный банк - отдельное состояние в двух местах. До старта корневой попытки `GetMyAssessmentAvailability` показывает `insufficient_bank` для грейда без опубликованного банка или достаточного числа невиденных семейств, а `CreateMyAssessmentAttempt` отвечает 409 `state_conflict`, не создавая попытку и не резервируя корневой слот. Корректировка также отклоняется, если срок цепочки истек или безопасного банка недостаточно; новая цепочка не создается. Во время существующей попытки терминальное состояние `insufficient_bank` завершает ее без подтвержденного грейда вместо повтора семейств. -- Подтвержденный грейд. `confirmed_grade` и `confirmed_basis` каждой специализации анкеты читаются из текущей категории вместе, в одном снимке. `confirmed_basis` равен `synthetic_demo` для демонстрационного грейда и null ровно тогда, когда грейд не подтвержден. Попытка напрямую их не задает: меняет их только повышение категории. -- Новый код проблемы не добавлен, поэтому создание попытки получает 409 `state_conflict` и статус доступности вместо кода `bank_unavailable`. Перечисление `ProblemCode` побайтно скопировано в ML-контракт (`test_contract_copies.py`), поэтому новый код изменил бы и ML-контракт, и его сгенерированные модели. Чтение доступности к тому же объясняет клиенту, почему попытка не может начаться, и для `cooldown` - с какого момента; фиксированный detail проблемы этого передать не может. -- Доступность показывает лимиты каждого грейда до старта: `time_limit_seconds`, `max_sessions`, `max_items` и `practice_required`; null, если значение неизвестно. -- Корневая квота и таймеры повторов разделены. Только запуск корневой попытки резервирует один из трех слотов на 180 дней; корректировки этой цепочки не резервируют дополнительные слоты. `insufficient_bank` или недоступность песочницы не создают новую попытку и не открывают бесплатную цепочку. После неудачи, включая первый тест, строго меньший грейд можно проверить в той же цепочке; корректировки не сбрасывают 30-дневный таймер повтора того же грейда или 90-дневный таймер повышения. - -Задания и ответы: - -- У задания есть `id` (экземпляр), `sequence`, `prompt` простым текстом и `content` (`ItemContent`) в одном из форматов `choice`, `number`, `string`, `order`, `find_error`, `configuration` и `practice`. Оно никогда не содержит ключ ответа, правильный вариант, балл, идентификатор семейства или варианта, seed или скрытую проверку, а посевные задания выглядят так же, как оцениваемые. `multiple`, `max_selections` и `max_length` - свойства формата или семейства заданий и никогда не выводятся из ключа. Вариант фиксируется при первой выдаче, поэтому перезагрузка, повтор запроса и возобновление сессии возвращают тот же экземпляр. -- Водяной знак. Реальная попытка (`root` или `corrective`) несет `watermark.code` - ключевой псевдоним попытки вроде `7K3QD-9XM2T`, который клиент показывает вместе со временем бледной плиткой поверх экрана задания; у попытки `demo_express` поля нет. `prompt` реальной попытки также несет невидимую метку и взаимозаменяемые формулировки, выбранные тем же секретом сервера; они не меняют ни смысл, ни эталонный ответ, а клиент держит невидимые символы (пробел нулевой ширины, не-соединитель, соединитель, соединитель слов) вне дерева доступности. Ни код, ни метка не называют кандидата, и ни одна операция не отдает их работодателю. См. [Водяной знак текста задания](../docs/ru/ARCHITECTURE.md#водяной-знак-текста-задания). -- Одно открытое окно. Реальная попытка допускает одну открытую страницу за раз. Страница при загрузке создает случайный идентификатор и отправляет его как `X-Attempt-Client` (от 16 до 64 символов `A-Za-z0-9_-`) в `HoldMyAssessmentWorkSession`, который занимает рабочий сеанс на 120 секунд и просит страницу продлевать его раз в 15 секунд, и в `ReleaseMyAssessmentWorkSession` при закрытии. `StartMyAssessmentAttemptSession` и `SubmitMyAssessmentAnswer` принимают тот же заголовок как необязательный параметр; пока сеанс занят другой страницей, запрос от другой страницы или без заголовка получает 409 `state_conflict` и ничего не меняет, а этот отказ не сохраняется под Idempotency-Key. Попытка, которую никто не держит, освобожденное занятие и переставшее продлеваться пускают любую страницу. Это правило "одна страница за раз", а не граница безопасности, и оно отделено от `sessions` (`used`, `max`, `idle_timeout_seconds`), которые считают последовательные рабочие сеансы. Сервер хранит только ключевые отпечатки идентификатора страницы и User-Agent, привязанные к попытке. Новый код ошибки не добавлялся, поэтому страница читает 409 на этих операциях как "открыто в другом окне". -- Ответ (`AssessmentAnswer`) имеет те же семь форматов и несет только ответ. Неизвестные поля вроде `score`, `duration` или `seed` дают 400. Сервер сам записывает время и оценивает ответ по ключу экземпляра задания; время не входит в решение о грейде. Ответы API никогда не сообщают, был ли ответ правильным. -- Решение практики исполняется в песочнице асинхронно на трех группах скрытых проверок; клиент опрашивает попытку, пока оно `pending`. Вердикт показывает только балл 0-3 и прохождение каждой группы. Любой исход, вызванный самим решением (ошибка компиляции или выполнения, лимит времени или памяти), - это `finished` с непройденными группами. `failed` (`sandbox_busy` или `sandbox_error`) означает только, что инфраструктура не смогла исполнить решение; он ничего не расходует. Так `failed` не становится оракулом для скрытых проверок и не дает бесконечных повторов. После `finished` другое решение не принимается. -- Отладочные прогоны (`CreateMyAssessmentPracticeRun`, `GetMyAssessmentPracticeRun`) исполняют решение на публичных примерах и до десяти тестах кандидата, пока практика - текущий элемент. Они никогда не запускают, не показывают и не оценивают скрытые проверки и не меняют ни состояние практики, ни вердикт, ни версию попытки. Прогон ставится в очередь и читается по своему идентификатору; повтор с тем же Idempotency-Key и телом возвращает сохраненный прогон. Лимит на кандидата и один незавершенный прогон на практику отвечают 429 `rate_limited` с `Retry-After`. Очередь песочницы вмещает один выполняемый и десять ожидающих прогонов и решений вместе; когда она заполнена, прогон получает 503 `service_unavailable` с `Retry-After`, а финальное решение оставляет практику в `failed` с `sandbox_busy`, что ничего не расходует. Без настроенной песочницы операция отвечает 503 `service_unavailable` без `Retry-After`. Отказ ничего не сохраняет. -- Если к истечению лимита последняя отправка все еще `failed`, результат - `not_determined` с причиной `sandbox_unavailable`. Неотправленная практика дает `practice_incomplete`. -- Попытка бывает без практики только в `demo_basic`, пока кодовая практика выключена до проверки изоляции песочницы; результат тогда содержит ограничение `practice_not_included`. - -Команды, повторы и версии: - -- Создание, начало или возобновление сессии, ответ и завершение требуют Idempotency-Key с 24-часовым повтором, описанным выше, поэтому повтор команды возвращает тот же исход. Начало сессии, ответ и завершение также передают `expected_version` - прочитанную клиентом `version` попытки. У создания нет версии для сравнения, оно опирается на ключ; единственную активную реальную попытку по специализации обеспечивает состояние. -- Каждое задание принимает один ответ. Повторная отправка сохраненного ответа, даже с новым ключом или старым `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. Так сохраняется правило репозитория и прецедент анкеты: `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), версия попытки (412, если передана), переходы по сроку или лимиту сессий, затем состояние команды (409 `state_conflict`) и доменные правила (400 с pointer вроде `/answer/option_ids/0`). Команда начала сессии возвращает обновленную попытку, если она зафиксировала наступивший терминальный переход. По соглашению об Idempotency-Key сохраненные 404 и 409 повторяются под ключом; 400, 412, 429 и 5xx не сохраняются. Создание и ответы ограничены по частоте (429 с `Retry-After`), что ограничивает и нагрузку на песочницу. `TestAssessmentSchemaValidationPrecedesImplementation` проверяет отказы схемы через сгенерированный сервер. - -Результат: - -- `GetMyAssessmentResult` отвечает для терминальной попытки и дает 409 `state_conflict` для активной, включая `additional_practice_pending`. `outcome` - это `confirmed`, `not_confirmed` или `not_determined` с `not_determined_reason` (`expired`, `practice_incomplete`, `insufficient_bank`, `sandbox_unavailable`). Результат никогда не понижает подтвержденный грейд: если попытка ничего не подтвердила, действует `previous_confirmed_grade`. -- В ответах попытки и результата есть дискриминатор `kind`: `root`, `corrective` или `demo_express`. Реальный результат всегда содержит пару полей цепочки корректировок: у корневой попытки оба поля null, у корректирующей оба заполнены. Для `demo_express` используется отдельная учебная схема с кратким резюме и `demonstration_only`: категория, целевой и подтвержденный грейды, сила, неопределенность и балл равны null, списки практик, пробелов и следующих шагов пусты. Этот режим не создает квалификационных данных и не виден работодателю. -- `calibration_status` и `limitations` описывают метод. Поля, которые метод не вычисляет, равны null, а не нулю: у `demo_basic` null в `uncertainty` и `strength`, у `adaptive` - null в `basic_score`. `uncertainty` содержит `theta`, `standard_error`, `interval_95` и `p_grade`. `practices` перечисляет вердикты по видам. `durations` - отдельная метка, которая не входит в решение. -- `next_steps` приходят с сервера: `retake_same_grade`, `take_lower_grade`, `accept_lower_grade` (команда запланирована) и `take_higher_grade`. Первое подтверждение - не повышение, поэтому `take_higher_grade` после него имеет null в `available_at`; после повышения следующее ждет 90-дневный интервал повышения. -- Результат никогда не содержит ответы, правильность отдельных заданий, ключи, seed, скрытые проверки или античит-сигналы. -- Категория по результату `demo_basic`. Результат реальной попытки содержит `category_decision`: `status` (`not_eligible`, `not_confirmed`, `assigned`, `unchanged`), грейд, действовавший до попытки и после нее, `method` (`demo_basic_pass_mark`), `source` (`synthetic_demo`) и `calibration_status`. Порог берется из принятой версии политики, закрепленной за попыткой: достижение порога засчитывается, параметр запроса его не задает. Категория присваивается, только если включен `ASSESSMENT_DEMO_CATEGORIES_ENABLED`, версия политики является полной демонстрационной политикой с `demo_basic` (порог - ее собственный `basic_pass_mark_bp`), а для открытия, манифеста и версии политики есть аттестация оператора; иначе `status` равен `not_eligible`, `confirmed_grade` равен null, хотя `outcome` может быть `confirmed`. `confirmed_grade` заполнен, только когда подтверждение принято проверенным источником (`assigned` или `unchanged`). Неудача, равный или более низкий грейд не понижают и не меняют текущую категорию. `demo_express` никогда не получает `category_decision` и не создает категорию. Результат, сохраненный до появления решений о категориях, не содержит `category_decision`: его текущий грейд не восстанавливается задним числом. -- `GET /api/v1/me/assessment-results` возвращает историю только самого кандидата: завершенные `root` и `corrective` результаты от новых к старым по `decided_at` и `attempt_id`. Курсор непрозрачен, привязан к кандидату и содержит только символы `[A-Za-z0-9_-]`; чужой, измененный или некорректный курсор дает 400 `validation_failed` с pointer `/cursor`. Аккаунт работодателя получает 403. Смена текущей политики, банка или категории не меняет ни одну сохраненную запись. Работодатель получает только текущую категорию (специализация, грейд, грубая сила `standard` и основание `basis`) через анонимную карточку, если кандидат опубликовал поле `categories`; ни попытки, ни баллы, ни версии, ни причины неподтверждения в этой проекции нет. - -Запланировано, добавляется без ломающих изменений: краткое описание подхода до 1500 знаков рядом с практикой, которое не определяет грейд (FR05 в PRD); операция отладочных запусков практики; серверные сигналы античит-слоя (время ответа, параллельные сессии, смена адреса); сигналы ведут к перепроверке и апелляции, а не к публичному ярлыку, и работодателю не показываются (FR05 в PRD). - -### Потребности - -Тег `need` описывает потребности организации в найме (FR08 в PRD, с версиями из FR10): требования с состоянием подтверждения и происхождением, неизменяемые версии, готовность и рекомендации категорий. Операции есть в контракте, но их бизнес-логика еще не реализована: гость получает 401 `unauthenticated`, а запрос с подтвержденной сессией достигает 501 `not_implemented` после проверки запроса. Небезопасные защищенные операции также требуют session-bound CSRF-токен и точный Origin. - -| Метод и путь | operationId | Защита | Успех | Конкретные ошибки | -| --- | --- | --- | --- | --- | -| `GET /api/v1/organizations/{org_id}/needs` | `ListOrganizationNeeds` | сессия | 200 `NeedList`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `forbidden`, 404 `not_found` | -| `POST /api/v1/organizations/{org_id}/needs` | `CreateOrganizationNeed` | сессия и CSRF, Idempotency-Key | 201 `Need`, `Cache-Control: no-store` | 400, 401, 403 `csrf_check_failed` или `forbidden`, 404, 409 `idempotency_in_progress`, 422 `idempotency_key_reused`, 429 | -| `GET /api/v1/organizations/{org_id}/needs/{need_id}` | `GetOrganizationNeed` | сессия | 200 `Need`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `forbidden`, 404 `not_found` | -| `PATCH /api/v1/organizations/{org_id}/needs/{need_id}` | `UpdateOrganizationNeed` | сессия и CSRF | 200 `Need`, `Cache-Control: no-store` | 400, 401, 403, 404, 412 `version_conflict`, 429 | - -Каждая операция также объявляет problem-ответ `default`. Некорректные `org_id` или `need_id` дают 400 с pointer на параметр пути. - -Доступ: - -- `org_id` в пути - единственный источник организации, и сервер сверяет его с действующим членством аккаунта сессии; ни один запрос не содержит поля организации, членства или роли. Организации и членства принадлежат контракту организации, который переиспользует тот же параметр пути `parameters.yml#/OrganizationId`. -- Аккаунт без действующего членства в `org_id`, неизвестная организация, неизвестная потребность и потребность другой организации одинаково дают 404 `not_found`, поэтому идентификаторы нельзя перебрать. Аккаунт кандидата получает 403 `forbidden`, как и участник, чья роль не разрешает операцию. -- В MVP с потребностями работает только владелец организации. Остальные роли матрицы FR07 в PRD (рекрутер, нанимающий менеджер и техэксперт для назначенных потребностей) запланированы и не меняют ни одного поля контракта. - -Поля и происхождение: - -- `requirements` (`NeedRequirementSet`) содержит `specialization`, `grade`, `required_skills`, `desired_skills`, `tasks`, `domain`, `work_formats`, `location` и `salary`. Поле в ответе - это `{status, value, source}`; у элемента списка свои `status` и `source`. -- `status` - `confirmed` (участник ввел или подтвердил значение), `extracted` (предложение, ожидающее подтверждения) или `unknown` (значения нет). У неизвестного поля `value` и `source` равны null; сервер никогда не заполняет его значением по умолчанию или догадкой, например Senior, remote или нулевой зарплатой. Только подтвержденные значения влияют на готовность, рекомендации, поиск и приглашения. -- `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 ТК РФ отложено до реализации проверки требований и добавится без ломающих изменений. - -Запросы, подтверждение и изменения: - -- Каждое поле требования в запросе - это решение `{value, status}` (`NeedSpecializationInput`, `NeedGradeInput`, `NeedDomainInput`, `NeedWorkFormatsInput`, `NeedLocationInput`, `NeedSalaryInput`), а каждый элемент списка - `{name или text, status}`. `status` - `confirmed` или `extracted`. Голое значение не проходит валидацию, поэтому подтверждение всегда явное. -- `confirmed` с сохраненным предложенным значением подтверждает его и сохраняет происхождение; `confirmed` с другим значением задает подтвержденное ручное значение. `extracted` оставляет сохраненное предложение открытым и допустим только с точно тем же предложенным значением; любое другое значение, а также поле или элемент без предложения дают 400 с pointer на этот статус, например `/grade/status` или `/required_skills/2/status`. Поэтому клиент, отправивший форму без изменений, ничего не подтверждает случайно: каждое предложение он отправляет с `extracted` или не отправляет поле. -- Потребности никогда не нужна вакансия: обязателен только `title`, а `vacancy_id` необязателен и допускает null. Пока вакансий нет в контракте, любой идентификатор вакансии дает 400 с pointer `/vacancy_id`. -- При создании каждое решение должно быть `confirmed`, потому что у новой потребности нет сохраненных предложений. Отсутствующее поле извлекается из `source_text` или остается неизвестным. Nullable-поле, переданное как null, остается неизвестным, а пустой список навыков или задач остается пустым; ни то ни другое не извлекается. Пустое значение `work_formats` не проходит `minItems`. -- `UpdateOrganizationNeed` использует явную замену полей в `application/json`, а не JSON Merge Patch (RFC 7396): переданное поле заменяется целиком, отсутствующее не меняется, решения и списки не сливаются, а сохраненный элемент, которого нет в переданном списке, удаляется. Null удаляет nullable-поле (оно становится `unknown`, а `vacancy_id` отвязывается); пустой список навыков или задач удаляет все элементы; список, переданный как null, дает 400. ogen генерирует одно необязательное или необязательное nullable значение на решение (`OptNilNeedGradeInput`, `OptNilNeedSalaryInput`). -- Другой `source_text` запускает повторное извлечение. Новые предложения заменяют только значения и элементы со статусом `extracted` в полях, не названных в теле; подтвержденные значения не перезаписываются, предложенный навык с названием, которое уже есть в одном из списков навыков, пропускается, а удаленное участником предложение для этой потребности больше не предлагается. -- Сервер также отклоняет повтор навыка или задачи и навык в обоих списках - 400 с pointer на более поздний элемент, например `/required_skills/1/name`. - -Версии и конкурентность: - -- `version` начинается с 1 и растет ровно на единицу с каждым зафиксированным изменением, включая серверные. Каждая версия - неизменяемый снимок. GET всегда возвращает последнюю версию. -- `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. - -Готовность: - -- `readiness.missing_fields` перечисляет каждое критичное поле без подтвержденного значения: `specialization`, `grade`, `required_skills` (хотя бы один подтвержденный навык), `work_formats`, `salary` и `location`, если подтвержденные форматы включают `office` или `hybrid`. У каждого элемента есть `reason` (`unknown` или `unconfirmed`) и конкретный вопрос `question` на русском. -- Неполная потребность сохраняется (201 или 200), а не отклоняется. `Problem` не допускает полей расширения, поэтому недостающие поля находятся в ресурсе, а не в problem. Каждая следующая операция, например поиск или приглашение, сама указывает, какая готовность ей нужна. - -Зарплата: - -- `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, применение запланировано): задание подтвержденной вилки при создании или изменении учитывается в счетчике, общем для всей организации, всех участников и всех потребностей, поэтому новая потребность его не обнуляет. Не больше трех заданий вилки в сутки; сверх лимита сервер отвечает 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, поэтому фикстура рекомендаций (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, явный статус каждого решения и отсутствие этих полей в типах запросов. - -Запланировано, добавляется без ломающих изменений: чтение и сравнение версий, исключения, подсказка рыночной вилки (P25-P75) из FR08, план проверки "вакансия -> задания", статус потребности для архивации, фильтры списка и назначения на потребность. - -### Обращения - -Тег `support` описывает обращения текущего аккаунта (FR18 в PRD, с ручной оценкой из FR04 и C3): вопросы в поддержку, жалобы, апелляции грейда и античит-решения, запросы ручной оценки. Операции реализованы: гость получает 401 `unauthenticated`, а подтвержденная сессия проходит проверку запроса и доменные правила. Небезопасные защищенные операции также требуют session-bound CSRF-токен и точный Origin. - -| Метод и путь | operationId | Защита | Успех | Конкретные ошибки | -| --- | --- | --- | --- | --- | -| `GET /api/v1/me/support-cases` | `ListMySupportCases` | сессия | 200 `SupportCaseList` из `SupportCaseSummary`, `Cache-Control: no-store` | 400 `validation_failed`, 401 | -| `POST /api/v1/me/support-cases` | `CreateMySupportCase` | сессия и CSRF, Idempotency-Key | 201 `SupportCase`, `Cache-Control: no-store` | 400, 401, 403 `csrf_check_failed` или `forbidden`, 404 `not_found`, 409 `state_conflict` или `idempotency_in_progress`, 422 `idempotency_key_reused`, 429 | -| `GET /api/v1/me/support-cases/{case_id}` | `GetMySupportCase` | сессия | 200 `SupportCase`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 404 `not_found` | - -Каждая операция также объявляет problem-ответ `default`. - -Доступ: - -- Автор - аккаунт сессии; ни один запрос не содержит поля пользователя, аккаунта или организации. FR18 в PRD позволяет обращаться в поддержку и кандидату, и сотруднику компании, поэтому `/me` обслуживает оба сценария: аккаунт работодателя открывает обращения типа `support`, а остальные типы дают ему 403 `forbidden`. Обращение принадлежит создавшему его аккаунту, а не организации: другие участники той же организации его не видят. -- Обращение другого аккаунта дает 404 `not_found`, как и неизвестный идентификатор. Контракт отвечает 404, чтобы идентификаторы нельзя было перебрать, и клиент показывает одно и то же состояние "не найдено" для чужого и неизвестного обращения. Автор читает обращение независимо от того, что потом стало с объектом, поэтому отказ в тесте или отозванный доступ его не скрывают. -- Очереди модерации - отдельные служебные операции со своими DTO; к этим операциям они ничего не добавляют. - -Типы и ссылки на объекты: - -| Тип | Аккаунты | Ссылка на объект | Другие поля | Срок ответа | -| --- | --- | --- | --- | --- | -| `support` | кандидат, работодатель | необязательна; `assessment_attempt` автора, `organization`, которую автор видит, `invitation`, адресованное автору, или другое `support_case` автора | необязательный `assessment_target` | значение политики | -| `complaint` | кандидат | обязательна; `organization`, которую автор видит, или `invitation`, адресованное автору | обязательный `complaint_reason` | значение политики | -| `grade_appeal` | кандидат | обязательна; завершенная `assessment_attempt` автора или `support_case` автора типа `manual_assessment` в статусе `resolved` с исходом `assessed` | нет | 10 рабочих дней | -| `anticheat_appeal` | кандидат | обязательна; `assessment_attempt` автора с решением античит-проверки | нет | 10 рабочих дней | -| `manual_assessment` | кандидат | необязательна; прежняя `assessment_attempt` автора в той же специализации | обязательный `assessment_target`; `rubric_version` фиксирует сервер | 5 рабочих дней | - -- Запрос - `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`. -- Организацию видит кандидат, которого она пригласила или которому контракт организации показывает ее профиль, и аккаунт работодателя с действующим членством в ней. Сервер сверяет каждую ссылку с аккаунтом сессии: неизвестный и чужой объект одинаково дают 404 `not_found`, поэтому ссылка не раскрывает, существует ли чужой объект. Обращение хранит только `{type, id}`. -- Приглашения есть в контракте (см. раздел Приглашения и контактные разрешения ниже), но не реализованы, а решений античит-проверки в контракте пока нет. До их реализации любая ссылка `invitation` дает 404, а любая античит-апелляция - 409 `state_conflict`; форма запроса не меняется. -- Жалобы `offer_content` и `salary_terms_violation` требуют приглашения; другой объект дает 400 с pointer `/object/type` (доменное правило после схемы). -- Неудачный первый тест или отсутствие попыток не блокируют ручную оценку. Создание обращения не дает, не отзывает и не меняет согласие, грейд или попытку; ручная оценка не зависит от C3. Кандидат, отозвавший C3 (`DELETE /api/v1/me/consents/c3`) или не дававший его, создает такой же запрос, а запрос не читает и не меняет журнал согласий. Повтор с тем же `Idempotency-Key` возвращает исходное обращение; новый ключ (например, после перезагрузки страницы) при открытой ручной оценке той же специализации дает 409 `state_conflict`, и открытое обращение остается единственным. `rubric_version` равна `null`, если для цели нет единственной актуальной проверенной категории; сервер не выбирает рубрику наугад, а обращение все равно ожидает эксперта без автоматического результата. - -Содержание и поля, которые клиент не задает: - -- `description` - простой текст длиной 1-4000 символов, в котором есть хотя бы один непробельный символ (`pattern: \S`); переносы строк разрешены. ogen переводит `\S` в набор пробельных символов ECMAScript, поэтому и Go-сервер, и сгенерированный Zod отклоняют пустой текст или текст из пробелов вроде U+00A0 или U+3000 с pointer `/description`. В пробельные символы ECMAScript не входит U+0085 (NEL), который Go `unicode.IsSpace` считает пробелом, поэтому реализация добавляет доменную проверку: описание, в котором каждый символ - `unicode.IsSpace` или U+FEFF, дает 400 с pointer `/description`; Zod такой текст принимает, решает сервер. Сервер хранит текст как есть и никогда не пишет его в журналы и уведомления. -- У каждого варианта `additionalProperties: false`. Клиент не может задать статус, решение или его исход, приоритет, срок ответа, рубрику, исполнителя, модератора или контакт: такие поля, например `status`, `decision`, `moderator_id`, `response_target`, `rubric_version` или `reply_to`, дают 400 с pointer на все тело. - -Обращение: - -- `number` - понятный человеку номер, который присваивается при создании: `SC-<год UTC>-<порядковый номер>` минимум из шести цифр, например `SC-2026-000123`. Последовательность общая и не переиспользуется, поэтому номер уникален и не меняется. API адресует обращение только по UUID `id`; номер нужен для писем и звонков. Общая последовательность раскрывает примерное число созданных обращений, для MVP это допустимо. -- `status` - `submitted`, `in_review`, `waiting_for_user`, `waiting_expert`, `resolved` (терминальный, с `decision`) или `closed` (терминальный, без решения по существу, например дубликат). Меняет его только сервер. `waiting_for_user` есть в перечислении, но пока не выставляется: он появится вместе с запланированной операцией ответа автора. Апелляции и ручная оценка переходят в `waiting_expert` событием `system` в той же транзакции, что и создание, поэтому ответ 201 уже показывает этот статус; в нем они остаются, пока решение не примет человек. -- `response_target` - срок ответа из FR18: `kind` `operational_goal` (цель команды, а не срок, установленный законом), `business_days`, `due_at` по настроенному производственному календарю, `answered_at`, `late` и `policy_version`. Для `support` и `complaint` его выполняет первый публичный ответ, решение или закрытие; для апелляций и `manual_assessment` - только решение или закрытие. Пропуск срока не закрывает обращение и не меняет грейд. -- `decision` равно null до `resolved`, а затем содержит `outcome` (`upheld`, `partially_upheld`, `not_upheld`, `answered` для поддержки, `assessed` для ручной оценки), публичную причину `reason` и `decided_at`. Удовлетворенная апелляция грейда не переписывает исходный результат; исправленный результат - отдельное решение оценки. -- `history` перечисляет все публичные события по порядку, начиная с `created`: `kind` (`created`, `status_changed`, `reply`, `decision`), `actor` только по виду (`user`, `support`, `system`), `occurred_at`, итоговый `status` и публичный `message`. История никогда не обрезается. Инвариант сервера: в обращении не больше 200 событий, и сервер отклоняет ответ или смену статуса сотрудником, если после них не останется места для терминального события, поэтому любое обращение помещается в лимит и его всегда можно решить или закрыть; дальнейшая переписка идет в новом обращении со ссылкой `support_case` на это. Флаг обрезки с постраничными событиями отвергнут: полное обращение зависело бы от второго чтения, а сотрудники на практике не создают 200 публичных событий в одном обращении. -- Обращение никогда не содержит личность модератора, эксперта или сотрудника поддержки, внутренние заметки, доказательства, ответы теста, античит-сигналы и сигналы риска или контакты другого человека. -- Ответы доходят до пользователя через само обращение. Сервер может также уведомить подтвержденный email аккаунта номером и ссылкой, но не описанием, ответом или подробностями оценки; ни одно поле запроса не задает другой адрес, поэтому операция не может отправить письмо на адрес, введенный пользователем. -- `ListMySupportCases` возвращает элементы `SupportCaseSummary`, новые первыми, с курсорной пагинацией: номер, тип, статус, ссылку на объект, категорию, срок ответа, `decision_outcome` и отметки времени, без описания и истории. Полное обращение возвращает только `GetMySupportCase`. - -Команды и ограничения: - -- Создание требует Idempotency-Key с повтором в течение 24 часов: повтор возвращает снимок ответа 201, сохраненный при создании, с тем же обращением и номером, по соглашению репозитория; текущее состояние клиент читает через `GetMySupportCase`. 404 и 409 `state_conflict` сохраняются и повторяются; 400, 403 и 429 - нет. -- Попытка и решенная ручная оценка принимают не больше одной апелляции грейда каждая, а попытка - не больше одной античит-апелляции, в любом статусе; несогласие с решением оформляется обращением в поддержку со ссылкой `support_case` на апелляцию. Специализация принимает одну открытую ручную оценку, объект - одну открытую жалобу. Повторное обращение и апелляция грейда активной попытки дают 409 `state_conflict`. -- Каждое создание, прошедшее аутентификацию, проверку запроса и сценарий аккаунта, учитывается в лимите аккаунта из продуктовой политики, включая повторы, 404 и 409, поэтому лимит ограничивает и перебор ссылок; сверх лимита сервер отвечает 429 с `Retry-After`. -- Порядок проверок при создании: сессия (401), CSRF и Origin (403), проверка запроса (400), сценарий аккаунта (403 `forbidden`), лимит обращений аккаунта (429), Idempotency-Key (422, 409 `idempotency_in_progress`, повтор), доменные правила (400), ссылка на объект (404), затем состояние и ограничения (409 `state_conflict`). Общий лимит частоты может ответить 429 до любой проверки. -- Новый problem-код не добавляется: перечисление `ProblemCode` побайтно копируется в ML-контракт. Недоступная античит-апелляция и повторная апелляция используют 409 `state_conflict`, а причину клиент узнает из обращения или попытки. -- `TestSupportCaseSchemaValidationPrecedesImplementation` проверяет отказы схемы через сгенерированный сервер, а `frontend/src/shared/api/support-contract.test.ts` закрепляет правила сгенерированного Zod, отсутствие полей статуса, решения, модератора и контактов в типах запроса и отсутствие личности модератора и внутренних полей в обращении и в сводке. - -Открытый продуктовый вопрос для ручной оценки: подчиняются ли повторные ручные оценки той же категории правилам пересдачи из FR04 (тот же грейд через 30 дней, не больше трех попыток за 180 дней) или собственному правилу. Контракт разрешает только одну открытую ручную оценку на специализацию и интервал не придумывает. - -Открытые вопросы ручной оценки после отказа от C3: нужна ли структурная причина запроса (например, пометка "отказ от C3") вместо свободного текста `description`; должен ли запрос со второй задачей языка (две актуальные категории для одной специализации и грейда) получать рубрику с выбором языка, а не `null`; нужно ли возвращать существующее открытое обращение вместо 409 при повторе с новым ключом. Контракт ничего из этого не выдумывает. - -Запланировано, добавляется без ломающих изменений (новая операция или необязательное поле): ответы автора, вложения, отзыв обращения, фильтры списка по статусу и типу, итоговая категория ручной оценки в решении, следующий шаг для автора, служебные очереди и решения и правила паузы срока ответа. - -Запланированные изменения контракта (новые значения перечислений; как и коды каталога, сгенерированные клиенты отклоняют неизвестное значение, поэтому каждое выходит вместе с перегенерированными клиентами): типы объектов `vacancy` и `application` для вакансий и защищенных откликов из FR16 и тип объекта для замечаний из анализа профиля. `waiting_for_user` и `support_case` уже есть в перечислениях, поэтому операции ответа и последующим обращениям такое изменение не нужно. Новых видов событий и участников не планируется: ответ автора - это `reply` с участником `user`, пересмотр решения - еще одно событие `decision`, а эксперты и модераторы - это `support`. - -### Приглашения и контактные разрешения - -Тег `invitation` описывает приглашения организации одному кандидату (FR12 в PRD, с правилами вилки FR13 и согласием C4): черновики с полными условиями, неизменяемые версии условий, отправку, входящие кандидата, просмотр, принятие с C4, структурированный отказ, отзыв, отмену участия и контактное разрешение (grant). Сторона организации в черновике реализована: `ListOrganizationInvitations`, `CreateOrganizationInvitation`, `GetOrganizationInvitation` и `UpdateOrganizationInvitation` следуют правилам ниже, но `salary_fit` всегда равен `not_available`, а лимит вилки и счетчик `withheld` пока не применяются ([backend](../backend/README.md#черновики-приглашений)). Реализованы также `SendOrganizationInvitation` и `ListMyInvitations`: отправка проверяет владельца, ключ, версию, состояние, текущую видимость кандидата, предел ожидающих приглашений на потребность и 30-дневную паузу после отказа, и только затем списывает недельную квоту организации; пауза после "сделки нет" пока не проверяется, потому что такого состояния никакая операция не создает; успех означает, что приглашение уже есть в `ListMyInvitations`, а уведомление и письмо идут следом через outbox ([архитектура](../docs/ru/ARCHITECTURE.md#отправка-приглашений)). `GetMyInvitation`, `ViewMyInvitation` и `DeclineMyInvitation` реализованы, как описано ниже, с одним ограничением: отмена участия еще не реализована. Чтение и просмотр в срок или позже сначала переводят ожидающее приглашение в `expired` с причиной `invitation_timeout` (чтение не записывает просмотр), а опоздавший отказ отвечает 409 `state_conflict`; у отказанного приглашения `contact_consent` и `contact_grant` равны null. `AcceptMyInvitation` реализован, как описывают правила ниже, но чтение контактов и отзыв разрешения еще не реализованы ([архитектура](../docs/ru/ARCHITECTURE.md#принятие-кандидатом)). Бизнес-логика остальных операций еще не реализована: гость получает 401 `unauthenticated`, а запрос с подтвержденной сессией достигает 501 `not_implemented` после проверки запроса. Небезопасные защищенные операции также требуют session-bound CSRF-токен и точный Origin. - -| Метод и путь | operationId | Защита | Успех | Конкретные ошибки | -| --- | --- | --- | --- | --- | -| `GET /api/v1/organizations/{org_id}/invitations` | `ListOrganizationInvitations` | сессия | 200 `OrganizationInvitationList` | 400, 401, 403 `forbidden`, 404 | -| `POST /api/v1/organizations/{org_id}/invitations` | `CreateOrganizationInvitation` | сессия и CSRF, Idempotency-Key | 201 `OrganizationInvitation` (`draft`) | 400, 401, 403, 404, 409 `idempotency_in_progress`, 422, 429 | -| `GET /api/v1/organizations/{org_id}/invitations/{invitation_id}` | `GetOrganizationInvitation` | сессия | 200 `OrganizationInvitation` | 400, 401, 403, 404 | -| `PATCH /api/v1/organizations/{org_id}/invitations/{invitation_id}` | `UpdateOrganizationInvitation` | сессия и CSRF | 200 `OrganizationInvitation` | 400, 401, 403, 404, 409 `state_conflict`, 412, 429 | -| `POST .../invitations/{invitation_id}/send` | `SendOrganizationInvitation` | сессия и CSRF, Idempotency-Key | 200 `OrganizationInvitation` (`delivered`) | 400, 401, 403, 404, 409, 412, 422, 429 | -| `POST .../invitations/{invitation_id}/salary-raise` | `RaiseOrganizationInvitationSalary` | сессия и CSRF, Idempotency-Key | 200 `OrganizationInvitation` | 400, 401, 403, 404, 409, 412, 422, 429 | -| `POST .../invitations/{invitation_id}/withdraw` | `WithdrawOrganizationInvitation` | сессия и CSRF, Idempotency-Key | 200 `OrganizationInvitation` (`withdrawn`) | 400, 401, 403, 404, 409, 412, 422, 429 | -| `GET .../invitations/{invitation_id}/contacts` | `GetOrganizationInvitationContacts` | сессия | 200 `ContactDisclosure` | 400, 401, 403, 404 | -| `GET /api/v1/me/invitations` | `ListMyInvitations` | сессия | 200 `CandidateInvitationList` | 400, 401, 403 | -| `GET /api/v1/me/invitations/{invitation_id}` | `GetMyInvitation` | сессия | 200 `CandidateInvitation` | 400, 401, 403, 404 | -| `POST /api/v1/me/invitations/{invitation_id}/view` | `ViewMyInvitation` | сессия и CSRF | 200 `CandidateInvitation` (`viewed`) | 400, 401, 403, 404, 429 | -| `POST /api/v1/me/invitations/{invitation_id}/accept` | `AcceptMyInvitation` | сессия и CSRF, Idempotency-Key | 200 `CandidateInvitation` (`accepted`) | 400, 401, 403, 404, 409, 412, 422, 429 | -| `POST /api/v1/me/invitations/{invitation_id}/decline` | `DeclineMyInvitation` | сессия и CSRF, Idempotency-Key | 200 `CandidateInvitation` (`declined`) | 400, 401, 403, 404, 409, 412, 422, 429 | -| `POST /api/v1/me/invitations/{invitation_id}/cancel` | `CancelMyInvitation` | сессия и CSRF, Idempotency-Key | 200 `CandidateInvitation` (`cancelled_by_candidate`) | 400, 401, 403, 404, 409, 412, 422, 429 | - -Каждый успешный ответ имеет `Cache-Control: no-store`, и каждая операция также объявляет problem-ответ `default`. Пути `...` начинаются с `/api/v1/organizations/{org_id}`. 403 на изменяющей операции - `csrf_check_failed` или `forbidden`; 409 на команде - `state_conflict` или `idempotency_in_progress`; 412 - `version_conflict`; 422 - `idempotency_key_reused`. 429 на команде - общий лимит частоты с Retry-After, который может ответить до любой проверки; на создании, изменении и отправке это также лимит вилки или недельная квота. Чтение контактов и простые чтения собственного 429 не объявляют, как и другие чтения контракта. - -Доступ: - -- Сторона организации: `org_id` в пути - единственный источник организации, сервер сверяет его с действующим членством аккаунта сессии, как для потребностей. Аккаунт без членства, неизвестная организация, неизвестное приглашение и приглашение другой организации одинаково дают 404 `not_found`; аккаунт кандидата и участник, чья роль не разрешает операцию, получают 403 `forbidden`. В MVP с приглашениями работает только владелец; остальные роли FR07 запланированы. -- Сторона кандидата: `/me/invitations` привязаны к аккаунту сессии. Черновик, приглашение другому кандидату и неизвестный идентификатор дают 404 `not_found`; аккаунт работодателя получает 403 `forbidden`. Ни в одном запросе нет поля пользователя, кандидата, организации или роли. -- Кандидат указывается только через `candidate_handle` (`CandidateHandle` в `common_schemas.yml`, общий с результатами поиска FR11), никогда через email, телефон или идентификатор аккаунта либо профиля. Неизвестный handle, handle другой организации и профиль, который организация больше не может видеть, одинаково дают 400 с pointer `/candidate_handle`. - -Условия (`InvitationTerms`): - -- Условия полны с первого черновика, и каждое поле обязательно: `role_title`, `specialization`, `grade`, `offer_type` (`full_time`, `part_time`, `contract`, `internship`), `tasks`, `team`, `tech_stack`, `work_formats`, `location` (null только для полностью удаленной роли; для `office` или `hybrid` обязательно по доменному правилу с pointer `/terms/location`), `communication_method` (`channel` и необязательная заметка), `salary` (`SalaryRange`) и `package`. Поэтому черновик без базы net/gross или способа связи существовать не может: такое тело дает 400 `required` с `/terms/salary/tax_basis` или `/terms/communication_method` (примеры `InvitationWithoutTaxBasis` и `InvitationWithoutCommunicationMethod`). -- `package` содержит `bonus`, `equipment`, `training` и `health_insurance` (ДМС). Каждое поле - `oneOf`: `{status: provided, description}` или `{status: not_provided}` ("Не предусмотрено" в интерфейсе). "Не предусмотрено" - явный выбор: пропущенное условие дает `required` со своим pointer, например `/terms/package/training`; `provided` без описания дает `required` на его `description`; `not_provided` с описанием дает `invalid` на самом условии. Сгенерированный Zod не строгий и отбрасывает такое описание, поэтому отклоняет его только сервер. -- Намеренное отступление от формулировки критериев приемки: пакет в PRD называет формат работы рядом с бонусом, оборудованием, обучением и ДМС, но здесь формат - обязательное условие `work_formats` без варианта "не предусмотрено", потому что у роли всегда есть формат, а индикатор и поиск его сравнивают. Это открытый вопрос к владельцу продукта. -- Одна схема служит полем запроса и сохраненным снимком, поэтому ответ можно отправить обратно без изменений. Условия никогда не содержат данных кандидата. - -Версии и конфликты: - -- `version` растет с каждым зафиксированным изменением, включая просмотр и серверное истечение срока. `terms_version` растет только при изменении условий: изменении `terms` в черновике или единственном повышении верхней границы после отправки. Каждая версия условий неизменяема. -- Каждая команда, кроме просмотра, передает `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. - -Состояния и просмотр: - -- `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` побочных эффектов не имеют; чтение лишь показывает наступивший срок, который сервер применяет в момент дедлайна в любом случае. Команда не дает предзагрузке, повтору или обновлению кеша менять состояние, которое видит организация. -- `withdrawn` - команда организации из любого незавершенного состояния, включая `draft` и `accepted`; существующий grant она сохраняет. `cancelled_by_candidate` - команда кандидата из любого незавершенного состояния после доставки; она отзывает grant этого приглашения. Отказ - структурированный ответ до принятия. -- Дедлайн равен `delivered_at + response_period_days` (3, 7 или 14 дней, по умолчанию 7). Просмотр, письмо или повышение вилки его не сдвигают; команда, принятая в момент дедлайна или позже, опоздала. - -Вилка и скрытый минимум: - -- Условия переиспользуют `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) - и в счетчике `withheld`. Изменение, которое сохраняет вилку, базу и форматы, не учитывается. -- `withheld`: после пяти установок за семь дней индикатор выключается на семь дней с пятой. Ответ на пятую установку уже показывает `withheld`, как и каждый черновик и каждое приглашение организации, включая существующие, до конца периода. -- Переключение базы превращает `not_available` в диапазон или обратно и тем сообщает организации базу минимума; это принято, а переключение учитывается в лимите как любая установка. -- После отправки база фиксирована, а нижняя граница не снижается. `RaiseOrganizationInvitationSalary` поднимает `salary_to` один раз за всю историю приглашения, создает следующую версию условий и отвечает 409 на второе повышение. Оно подчиняется своему однократному правилу и не входит в дневной лимит, но учитывается в счетчике `withheld`, потому что сдвигает верхнюю границу, с которой сравнивает индикатор. - -Согласие 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 (цель, версия и хэш текста, организация, набор полей, приглашение-источник). Разрешение передавать данные в 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`); отзыв C2 или скрытие профиля закрывает их (`visibility_closed`). Отзыв приглашения, `no_deal` и таймаут финала grant не отзывают; новый grant создает только новое явное C4. Отдельная операция отзыва grant относится к контракту согласий. -- Реализация: чтение контактов, отзывы C4 и C2, закрытие публикации и скрытие реализованы, только для владельца, и закрывают разрешения так, как описано в пункте выше (архитектура: [Чтение контактов и отзыв](../docs/ru/ARCHITECTURE.md#чтение-контактов-и-отзыв)). `contact_access` организации выводится при каждом чтении приглашения (`GetOrganizationInvitation`, список и ответы создания, изменения и отправки) теми же проверками, что и чтение контактов, поэтому он показывает `available` только там, где чтение бы прошло, и никогда не называет причину. `CancelMyInvitation` пока не реализован. -- Форматы значений: ФИО одной строкой до 200 символов, телефон в формате E.164 и имя пользователя Telegram с ведущим @. Контракт профиля (FR02) должен хранить контакты в тех же форматах, чтобы раскрытие не преобразовывало и не отбрасывало сохраненное значение. - -Отказ и приватность: - -- `DeclineMyInvitation` принимает `reason` (`salary`, `tasks`, `stack`, `work_format`, `package`, `company`, `not_looking`, `other_offer`, `other`) и необязательный `comment` до 500 символов; для `other` комментарий не нужен. Организация видит только `declined` и `responded_at`, но не причину и не комментарий: причина вроде `salary` сообщила бы ей, что скрытый минимум выше вилки. Причины идут только в агрегаты с минимальным размером группы (запланировано). Кандидат читает их обратно в `decline`. -- Ни один DTO приглашения ни одной стороны не содержит ФИО, email, телефон, Telegram, идентификатор аккаунта или профиля или минимум кандидата; примеры используют только синтетические данные. `TestInvitationSchemaValidationPrecedesImplementation` проверяет отказы схемы и pointer через сгенерированный сервер, `TestInvitationDTOsCarryNoContactOrMinimum` - сгенерированные Go DTO, а `frontend/src/shared/api/invitation-contract.test.ts` закрепляет правила сгенерированного Zod и на уровне типов отсутствие полей контактов, минимума и отказа. - -Открытые продуктовые вопросы: допустимо ли второе незавершенное приглашение той же организации тому же кандидату (PRD об этом молчит, поэтому контракт правила не придумывает), отступление по формату в пакете выше, типы предложения, виды контактов и причины отказа. - -Запланировано, добавляется без ломающих изменений: встречное предложение и ответ компании, чтение прежних версий условий, операции интервью и закрытого финала, фильтры списков, метрики отзывчивости организации для кандидата, ориентировочная сумма в другой базе, агрегаты причин отказа, флаг ATS в C4 и поля ФСП как новые виды контактов (новое значение enum выпускается вместе с перегенерированными клиентами). - -Новый код ошибки не добавлен: enum `ProblemCode` побайтно копируется в ML-контракт, а `version_conflict` и `state_conflict` покрывают устаревшие условия и конфликты состояния. - -### Согласия - -Тег `consent` описывает журнал согласий текущего аккаунта (FR01, FR12 и 7.3 в PRD): независимые согласия C1-C5 с версиями текстов, источниками, состояниями и отзывами. Реализованы публичное чтение C1, чтение текущих текстов настроек и собственной истории, выдача C1/C2/C3/C5, отзыв C2/C3/C5 и отзыв C4 в области одной организации. Запрос C1 создает долговечный запрос на удаление аккаунта; сама запись аккаунта не удаляется синхронно. Эти обработчики требуют действующую подтвержденную PostgreSQL-сессию, а изменяющие операции также требуют session-bound CSRF и единственный `Origin`, совпадающий с `APP_PUBLIC_URL`. Гость получает 401; неподходящая роль, неверный Origin или CSRF получают 403. - -| Метод и путь | operationId | Защита | Успех | Конкретные ошибки | -| --- | --- | --- | --- | --- | -| `GET /api/v1/identity/consent-texts/c1` | `GetConsentText` | публичная | 200 `ConsentText` | 400 `validation_failed` | -| `GET /api/v1/me/consent-texts/{purpose}` | `GetMyConsentText` | сессия | 200 `ConsentText`, `Cache-Control: no-store` | 400, 401 | -| `GET /api/v1/me/consents` | `ListMyConsents` | сессия | 200 `ConsentRecordList`, `Cache-Control: no-store` | 400, 401 | -| `PUT /api/v1/me/consents/{purpose}` | `GrantMyConsent` | сессия и CSRF | 200 `ConsentRecord`, `Cache-Control: no-store` | 400, 401, 403 | -| `DELETE /api/v1/me/consents/{purpose}` | `RevokeMyConsent` | сессия и CSRF | 204 | 401, 403 | -| `DELETE /api/v1/me/consents/c4/organizations/{org_id}` | `RevokeMyOrganizationContactConsent` | сессия и CSRF | 204 | 400, 401, 403 | -| `POST /api/v1/me/account-deletion-requests` | `RequestMyAccountDeletion` | сессия и CSRF | 202 `ConsentDeletionRequest`, `Cache-Control: no-store` | 401, 403 | - -- Цели (`ConsentPurposeCode`): `c1` - обработка персональных данных, `c2` - публикация карточки кандидата, `c3` - автоматическая категоризация, `c4` - передача выбранных контактов одной организации, `c5` - импорт результатов ФСП. Публичный `GetConsentText` остается доступен только для C1; `GetMyConsentText` возвращает текущий текст C1/C2/C3/C5 перед выдачей в настройках. Текст C4 остается частью приглашения с его конкретной областью. -- Субъект берется из сессии; ни один параметр не называет аккаунт, поэтому ответ содержит только собственные записи вызывающего. Страница перечисляет записи от новой выдачи к старой с курсорной пагинацией; необязательный фильтр `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` доказывает согласие с текстом публикации; какие поля и когда опубликованы - доказательства истории публикации ([Видимость кандидата](#видимость-кандидата)), а scope полей в записях `c2` был бы аддитивным изменением. Запись никогда не содержит значения контакта, субъекта или хэш текста: сервер хранит SHA-256 ровно того текста, который видел субъект, а клиент его не отправляет и не получает, как и для C1 при регистрации. -- Выдача в настройках требует явного `accepted: true` и текущую версию прочитанного текста. C1 можно выдать аккаунту кандидата или работодателя; C2/C3/C5 доступны только кандидату. C4 нельзя выдать общей операцией настроек: он выдается только принятием конкретного приглашения. -- Журнал только дополняется. Новая версия текста цели - новая запись, а прежняя становится `superseded` без изменений; отзыв ставит отметку на все неотозванные записи цели, включая прежние версии. Отзыв C4 действует только для одной организации и берет набор полей из сохраненных записей, не из запроса. Повтор отзыва безопасен и не создает второе событие. -- Отзыв C2 в одной транзакции закрывает действующую публикацию, очищает ее поля, добавляет запись privacy history и пишет ограниченный по размеру outbox intent. Новая выдача C2 не открывает прежнюю публикацию. Отзыв C3 не блокирует ручной путь оценки. Отзыв C5 немедленно закрывает consent gate для будущего импорта и пишет stop/delete intent; внешнего адаптера ФСП нет, поэтому фактическое удаление данных во ФСП не заявляется. -- Запрос удаления C1 отзывает C1 и создает или возвращает активный запрос удаления и outbox intent в одной транзакции. Повтор возвращает тот же запрос; последующая выдача C1 его не отменяет. Обработчик будущего удаления аккаунта не синхронен и пока отсутствует. -- Разрешение C4 на передачу данных в ATS и C4 при отклике (Q9 в PRD) запланированы как аддитивный флаг и дополнительное значение `source`. - -Открытый юридический вопрос: является ли `c2` согласием на распространение персональных данных по статье 10.1 152-ФЗ, которое требует отдельного согласия с категориями данных. - -Новый код problem не добавляется: контракт использует `validation_failed`, `unauthenticated`, `forbidden` и `csrf_check_failed`. Контрактные тесты закрепляют security-схемы и порядок валидации, `TestConsentSettingsOverHTTP` проверяет согласия с настоящими PostgreSQL и Redis, а `frontend/src/shared/api/consent-contract.test.ts` закрепляет сгенерированные правила Zod и отсутствие в DTO хэшей, субъекта и контактов. - -### Организации - -Тег `organization` включает реализованные создание, чтение, редактирование и список своих организаций. Подтвержденный работодатель создает организацию с активным владельцем; операции в области организации требуют активного владельца на каждом запросе. Небезопасные операции требуют CSRF-токен сессии и точный Origin. Общий middleware защищает также пока не реализованные потребности и приглашения до ответа 501. Подробности: [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#организации-и-членства). - -| Метод и путь | operationId | Защита | Успех | Конкретные ошибки | -| --- | --- | --- | --- | --- | -| `GET /api/v1/me/organizations` | `ListMyOrganizations` | сессия | 200 `MyOrganizationList`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `forbidden` | -| `POST /api/v1/organizations` | `CreateOrganization` | сессия и CSRF, Idempotency-Key | 201 `Organization`, `Cache-Control: no-store` | 400, 401, 403 `csrf_check_failed` или `forbidden`, 409 `idempotency_in_progress`, 422 `idempotency_key_reused`, 429 | -| `GET /api/v1/organizations/{org_id}` | `GetOrganization` | сессия | 200 `Organization`, `Cache-Control: no-store` | 400, 401, 403 `forbidden`, 404 `not_found` | -| `PATCH /api/v1/organizations/{org_id}` | `UpdateOrganization` | сессия и CSRF | 200 `Organization`, `Cache-Control: no-store` | 400, 401, 403 `csrf_check_failed` или `forbidden`, 404, 412 `version_conflict`, 429 | - -Каждая операция также объявляет problem-ответ `default`. Некорректный `org_id` отвечает 400 с указателем пути. - -Активный контекст организации: - -- Контекст не хранится на сервере. Каждая операция в области организации, включая потребности и приглашения этого контракта, называет организацию в пути `org_id`, а сервер на каждом запросе проверяет этот идентификатор по активному членству аккаунта сессии. Сам идентификатор ничего не дает; переключение между организациями - это другой `org_id` в маршрутах клиента. -- Причина: атрибут сессии был бы кешем членства, который пришлось бы сбрасывать при удалении, приостановке или выходе (нужно закрыть следующее чтение, а не ждать истечения кеша браузера), две вкладки в двух организациях спорили бы за одно значение, а форма с путем уже является контрактом потребностей и приглашений. Переключение организации очищает клиентские запросы с ее областью, что согласуется с клиентским контекстом. -- `ListMyOrganizations` - справочник контекстов: организации, где у вызывающего `active` членство, от нового членства к старому, с ролью и состоянием вызывающего. Клиент выбирает контекст из него, может помнить последний выбор в браузере для удобства и перечитывает список после 404 по пути организации. Человек с несколькими членствами видит все и работает в одной за раз; права и данные организаций остаются раздельными. - -Доступ: - -- Только аккаунт работодателя. Аккаунт кандидата получает 403 `forbidden` на всех четырех операциях, аккаунт без сессии - 401. -- `GetOrganization` и `UpdateOrganization` одинаково отвечают 404 `not_found` аккаунту без активного членства в `org_id` и на неизвестную организацию, а также участнику в состоянии `suspended`, `removed` или `left`, поэтому организации нельзя перечислить, а отозванный участник теряет следующее чтение сразу. Участник, чья роль не управляет организацией, получает 403 `forbidden` на `GetOrganization` и `UpdateOrganization`; матрица FR07 отдает управление компанией и сотрудниками только владельцу. В MVP каждый участник - владелец, потому что операции добавления участников запланированы. -- `CreateOrganization` создает организацию и членство владельца для вызывающего в одной транзакции (роль `owner`, состояние `active`), поэтому организации без владельца не существует; база отказывается фиксировать такую. В теле нет поля владельца, роли, членства или уровня проверки. - -Членства: - -- Членство - это `(пользователь, организация, роль, состояние)`, уникальное для пары в любом состоянии. `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` членство, когда владелец адреса его принимает. Человек может иметь независимые членства в нескольких организациях. -- Применение полной матрицы ролей (рекрутер, нанимающий менеджер, техэксперт) к потребностям, приглашениям и контактам запланировано в ролевом контроле доступа. До этого остальные роли ничего не дают: операции потребностей и приглашений отвечают им 403 `forbidden`, как сказано в их разделах. Список и управление участниками, смена ролей, удаление участников и правило, что последнего владельца удалить нельзя, запланированы в управлении участниками и добавляют в контракт операции, а не поля. - -Профиль: - -- `OrganizationCreate` требует только `name`. Поля профиля: `name` (1-200 символов, без пробелов и переводов строки по краям, потому что запись согласия хранит его копию), `description` (1-2000 символов, nullable, переводы строки разрешены), `sphere` (1-100 символов, nullable, свободный текст: в PRD нет таксономии сферы, а код таксономии был бы аддитивным полем), `contacts` и `representatives`. -- `contacts` - один объект с `website`, `email`, `phone` и `telegram`, все обязательные и nullable, поэтому он одновременно поле запроса и сохраненное значение. Это публичные каналы компании: сайт по https без учетных данных, порта и IP-адреса, почта для вакансий, телефон в формате E.164 и имя пользователя Telegram с ведущим `@`. Личных контактов сотрудника в контракте нет, а сервер не отличает личный адрес от адреса компании, поэтому за содержимое отвечает владелец; жалоба на организацию подается через обращение в поддержку. Сервер никогда не обращается по адресу сайта. -- `representatives` - список до десяти записей `{name, job_title}` в порядке, заданном владельцем. Представитель существует только для показа: не участник, без связи с аккаунтом, без контакта и без прав, а участник не становится представителем при вступлении. Имя - персональные данные сотрудника, которые публикует владелец, отсюда открытый вопрос ниже. -- `UpdateOrganization` использует явную замену полей, как `UpdateOrganizationNeed`: присутствующее поле заменяет поле целиком, отсутствующее остается без изменений, а `contacts` и `representatives` никогда не объединяются. `description` и `sphere` со значением null становятся неустановленными; `name`, `contacts` и `representatives` не могут быть null. ogen генерирует `OptNil` для nullable-полей и обычный slice для `representatives`, где nil означает отсутствие, а `[]` - замену пустым списком; обработчик обязан проверять его через `!= nil`, а не через `len` (`TestOrganizationUpdateDecodingKeepsAbsentAndEmptyListsApart`). -- Текст простой: клиенты показывают каждое поле как текст, а не как HTML. Доменные правила, которым нужно больше, чем схема, например правила хоста сайта, отвечают 400 с указателем (`/contacts/website`, `/representatives/0/job_title`); формы показывают примеры. - -Уровень проверки: - -- `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 отводит отдельную политику. Применение квот - отдельная запланированная функция. - -Карточка кандидата и версии: - -- `Organization.candidate_card` - карточка так, как ее видит кандидат; сервер строит ее из профиля и уровня: предпросмотр FR07 в PRD. Ее видит только кандидат, получивший приглашение от организации; это не публичная страница, и ни одна операция не показывает ее другим, пока не решен вопрос об именах представителей ниже. Она повторяет поля профиля и добавляет только уровень; в ней нет членства, роли, аккаунта, версии и основания. Ее `representatives` необязательно и допускает null: отсутствие или null означает, что представители не опубликованы, а не что их нет. Контракт приглашения называет организацию через `InvitationOrganization` и планирует аддитивно отдавать эту карточку кандидату. -- `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` и ссылаются на него ограничивающим внешним ключом в миграции, создающей записи приглашений, потому что для области C4 нужны сразу обе ссылки, а тесты журнала согласий используют синтетические идентификаторы организаций. Приложение никогда не удаляет организацию. - -Открытые вопросы к владельцу продукта: - -- Представители: может ли карточка показывать их имена любому кандидату до принятия приглашения и кто отвечает за право публиковать имя сотрудника (152-ФЗ)? Альтернатива - показывать представителей только в приглашении, отправленном их организацией. -- Сфера: пока свободный текст; таксономия сферы, согласованная с доменами потребностей, - решение для поисковых фильтров. -- Контакты: нужен ли в карточке пятый вид, например страница вакансий, и должна ли почта совпадать с доменом сайта. - -Решение владельца продукта: число организаций на аккаунт не ограничено. Организации одного аккаунта образуют холдинг, а E0-квоты (в демо-политике 10 приглашений за 7 дней и 50 уникальных просмотров карточек за 24 часа) общие для E0-организаций этого холдинга; организация на E1 и выше считает свои квоты отдельно. Контракт не меняется: холдинг внутренний, и ни одна операция его не показывает. - -Запланировано, аддитивно: приглашения участников, список, смена ролей и удаление, полная матрица ролей, процессы проверки и их история, квоты по уровню, карточка в приглашении кандидата, и код сферы. - -Новый код 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). Операции есть в контракте, но их бизнес-логика еще не реализована: гость получает 401 `unauthenticated`, а запрос с подтвержденной сессией достигает 501 `not_implemented` после проверки запроса. Небезопасные защищенные операции также требуют session-bound CSRF-токен и точный Origin. Хранение за ними уже есть (миграция 00015, см. [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#видимость-кандидата)). - -| Метод и путь | operationId | Защита | Успех | Конкретные ошибки | -| --- | --- | --- | --- | --- | -| `GET /api/v1/me/privacy` | `GetMyPrivacySettings` | сессия | 200 `PrivacySettings`, `Cache-Control: no-store` | 401, 403 `forbidden` | -| `PUT /api/v1/me/privacy/publication` | `SetMyPublication` | сессия и CSRF | 200 `Publication`, `Cache-Control: no-store` | 400, 401, 403 `csrf_check_failed` или `forbidden`, 409 `state_conflict`, 412 `version_conflict` | -| `GET /api/v1/me/privacy/preview` | `GetMyCardPreview` | сессия | 200 `CardPreview`, `Cache-Control: no-store` | 401, 403 | -| `PUT /api/v1/me/privacy/search-status` | `SetMySearchStatus` | сессия и CSRF | 200 `SearchStatus`, `Cache-Control: no-store` | 400, 401, 403, 412 | -| `GET /api/v1/me/privacy/hidden-organizations` | `ListMyHiddenOrganizations` | сессия | 200 `HiddenOrganizationList`, `Cache-Control: no-store` | 400, 401, 403 | -| `PUT /api/v1/me/privacy/hidden-organizations/{org_id}` | `HideOrganization` | сессия и CSRF | 200 `HiddenOrganization`, `Cache-Control: no-store` | 400, 401, 403, 404 `not_found`, 409 `state_conflict`, 429 | -| `DELETE /api/v1/me/privacy/hidden-organizations/{org_id}` | `UnhideOrganization` | сессия и CSRF | 204 | 400, 401, 403 | -| `GET /api/v1/me/privacy/history` | `ListMyPrivacyHistory` | сессия | 200 `PrivacyEventList`, `Cache-Control: no-store` | 400, 401, 403 | -| `GET /api/v1/me/privacy/access-history` | `ListMyCardAccessHistory` | сессия | 200 `CardAccessList`, `Cache-Control: no-store` | 400, 401, 403 | - -Каждая операция также объявляет problem-ответ `default`. Новый код problem не добавляется: контракт использует `validation_failed`, `unauthenticated`, `forbidden`, `csrf_check_failed`, `not_found`, `state_conflict`, `version_conflict` и `rate_limited`. Аккаунт работодателя получает 403 `forbidden` на всех девяти операциях. - -Закрыто по умолчанию и три независимые настройки: - -- Профиль закрыт по умолчанию. Кандидат, который никогда не публиковал, читает `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; операция выдачи запланирована в настройках согласий). -- Статус поиска - не согласие. В `SearchStatus` и `SearchStatusUpdate` нет свойств согласия, публикации или организации, схемы одного семейства не достигают другого (тест обходит ссылки), а `SetMySearchStatus` не меняет ничего, кроме статуса. Кандидат с закрытым профилем, который задал `looking`, не становится видимым никому. -- Скрытые организации - записи кандидата (`HiddenOrganization`: организация с ее текущим названием и `hidden_at`). Одна запись на кандидата и организацию, не более 1000 на кандидата. Организация их не читает, не узнает, что скрыта, и видит скрывшего кандидата так же, как неопубликованного. Скрытие и его снятие не меняют ни C2, ни публикацию, ни статус поиска. -- Скрытие - это PUT состояния, поэтому оно идемпотентно и не требует Idempotency-Key: повторное скрытие отвечает 200 с исходной записью и не пишет историю. Снятие - DELETE, который отвечает 204, была организация скрыта или нет. - -Статус поиска и его 30 дней: - -- `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` на появление опубликованной карточки в выдаче поиска - решение контракта поиска, здесь не принято. - -Анонимная карточка и предпросмотр: - -- `CardField` - закрытый набор групп значений карточки, которые кандидат выбирает публиковать: `categories` (категории, подтвержденные результатами оценки), `stack`, `experience` (суммарно в месяцах), `soft_skills`, `location` и `relocation`. У полного имени, любого контакта и минимальной зарплаты значения нет, поэтому ни один запрос не может их опубликовать; контакты доходят до организации только через контактное разрешение принятого приглашения (C4), а минимальная зарплата не доходит никогда. Самооценка грейда не категория и никогда не публикуется. Сервер хранит и отдает набор в порядке возрастания кодов. -- `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 сам закрывает сохраненную публикацию и отзывает разрешения в своей транзакции. Публикации, скрытию и истории нужен подтвержденный 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` в той же транзакции, что и изменение (запланировано вместе с операциями; причину задает контракт приглашений). Снятие скрытия и повторная публикация разрешение не возвращают. Статус поиска разрешение никогда не отзывает. - -История: - -- `ListMyPrivacyHistory` возвращает журнал изменений настроек только для добавления, от новых к старым (история хранит только идентификатор организации, а текущее название определяется при чтении): `publication_opened`, `publication_changed` (с опубликованными полями и `consent_id` за ними), `publication_closed`, `search_status_confirmed`, `search_status_cleared`, `organization_hidden` и `organization_unhidden` (с текущим названием организации). Это доказательство набора опубликованных полей и его изменений со временем, которого нет в записи C2. Отзыв C2 и истечение статуса вычисляются и событиями не являются; отзыв показывает история согласий. Значений профиля в истории нет. -- `ListMyCardAccessHistory` возвращает обращения организаций к карточке: `card_viewed` и `contact_read`. У просмотра организацией, не связанной с кандидатом приглашением, `organization` равно null; чтение контактов всегда называет организацию. Записи не несут запроса или ранга. Хранение для них придет с задачами поиска и чтения контактов, поэтому операция только в контракте. - -Открытые вопросы к владельцу продукта и юристу: - -- Значения статуса поиска: в контракте `looking` и `not_looking`. Нужен ли по PRD третий статус, например "открыт к предложениям", не решено; значение - аддитивное изменение. -- Влияет ли `looking` на появление опубликованной карточки в поиске (организация видит только ищущих) или это только метка. Это определяет смысл истечения для видимости и относится к контракту поиска. -- Набор полей карточки. Шесть значений - предложение, согласованное с профилем; карточка в PRD (FR11) может добавить, разделить или убрать часть, например обобщенную отрасль и размер работодателя вместо работодателей, и каждое изменение аддитивно для контракта. -- Нужен ли для публикации минимум: хотя бы одна подтвержденная категория или сохраненный профиль. Контракт требует только одно поле карточки и действующую C2. -- Должно ли сужение опубликованных полей, а не только закрытие публикации или скрытие организации, отзывать контактные разрешения. Контракт приглашений говорит, что любое изменение видимости после разрешения его отзывает; этот контракт отзывает только при закрытии и скрытии. -- Как кандидат находит организацию, чтобы скрыть ее до любого приглашения. Контракт скрывает по идентификатору и отвечает 404 на организацию, которую кандидат не видит, поэтому заранее скрыть текущего работодателя можно только при поиске организаций для кандидата (по названию или домену), который сам должен быть защищен от перебора (минимальная длина запроса, лимит, только публичные данные). Без него скрытие работает только для организаций, которые уже написали кандидату. -- Должен ли кандидат узнавать название организации, которая смотрела карточку без приглашения (`CardAccess.organization`), и сколько хранятся обращения. -- Предел скрытых организаций (сейчас 1000) и срок хранения настроек и их истории вместе с доказательствами согласий (152-ФЗ, PRD 7.3). История ссылается на аккаунт с `ON DELETE CASCADE` под защитой двух триггеров: UPDATE запрещен всегда, а DELETE (и удаление аккаунта) запрещен, пока аккаунт подтвержден, как у журнала согласий; очистка неподтвержденных аккаунтов удаляет историю удаляемого аккаунта, а процедура удаления аккаунта расширит условие. -- Свободный текст в карточке (теги стека, софт-скиллы, место) защищает только `CardTextLooksLikeContact`, который ошибается в сторону отбрасывания (Socket.io отбрасывается, а простая обфускация все же может пройти); для устранения остаточного риска построителю карточки еще нужна закрытая таксономия вместо свободного текста. -- Является ли C2 согласием на распространение персональных данных по статье 10.1 152-ФЗ и нужна ли ей собственная область полей (см. Согласия); пока поля и времена хранит история. -- Требует ли новая версия текста C2 повторного согласия кандидата для уже существующей публикации. Сейчас публикация действует, пока ее запись C2 не отозвана, поэтому более новая версия текста, которую кандидат не принимал, ее не закрывает. -- Квазиидентификаторы и k-анонимность карточки: редкое сочетание места, стека и опыта может идентифицировать кандидата и без имени. Обобщение редких признаков и минимальный размер группы - критерии приемки построителя карточки; здесь контракт фиксирует только закрытый набор полей, правило "только подтвержденные значения" и отбрасывание свободного текста, похожего на контакт. -- Хранение и право на удаление истории настроек. Записи о скрытии и снятии скрытия чувствительны (они говорят, каких работодателей кандидат избегает). История хранится как доказательства согласий и не удаляется, пока аккаунт подтвержден; может ли кандидат стереть ее, когда и как это согласуется с трехлетним хранением согласий (PRD 7.3) - открытый юридический вопрос. Процедура удаления аккаунта расширит условие удаления таблицы. - -Новый код problem не добавляется. `TestPrivacyOperationsFollowTheConventions`, `TestPublicationAndSearchStatusAreNotConsents`, `TestAnonymousCardReachesNoProfileOrContactSchema`, `TestGeneratedPrivacyDTOsCarryNoServerOwnedFields`, `TestPrivacySchemaValidationPrecedesImplementation` и `TestPrivacyAccessBeforeImplementation` закрепляют сгенерированный сервер и бандл, а `frontend/src/shared/api/privacy-contract.test.ts` - сгенерированные правила Zod, отсутствие согласия, времени, контакта и зарплаты в типах запросов и карточки и отсутствие настроек в файлах организации, приглашения, потребности, профиля и согласий. - -### Доказательства навыков - -Тег `evidence` описывает факты, которые подтвержденные оценки оставляют о навыках кандидата (FR06 в PRD). В нем две операции чтения; логика за ними реализована (см. [архитектуру](../docs/ru/ARCHITECTURE.md#доказательства-навыков)). - -| Метод и путь | operationId | Защита | Успех | Специфичные ошибки | -| --- | --- | --- | --- | --- | -| `GET /api/v1/me/evidence` | `ListMyEvidence` | сессия | 200 `EvidenceFactList`, `Cache-Control: no-store` | 400, 401, 403 `forbidden` | -| `GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}/evidence` | `GetOrganizationCandidateEvidence` | сессия | 200 `OrganizationEvidence`, `Cache-Control: no-store` | 400, 401, 403, 404 `not_found`, 429 | - -Каждая операция также объявляет проблемный ответ `default`. Новых кодов проблем нет. - -- Одно событие - один факт. `EvidenceFact` - это событие-источник; `skills` - теги этого события (непустое множество), поэтому второй тег не создает второй факт. `source` называет событие и неизменяемый результат (`event_id` и `result_id`, для оценки они равны, так как результат ключуется попыткой; кандидат открывает его через `GetMyAssessmentResult`). -- Заявление не равно измерению. `kind` равен `claim` (доверие 0) или `measurement` (доверие 1-3). `EvidenceTrustLevel` - целое от 0 до 3; онлайн-оценка без надежного подтверждения личности имеет доверие 1 и повторами не растет. Сейчас создаются только измерения из оценок. -- Что говорит факт, лежит в `result`: пройденный грейд, `basis` (`synthetic_demo`) и `calibration_status` (`uncalibrated`), поэтому кандидат не принимает демонстрационную категорию за проверенное измерение. Проекция для организации и предпросмотр тоже несут обе метки. В факте нет балла, ответа, задания, проваленной попытки и античит-данных; проваленная попытка, результат без проверенного источника категории и прогон `demo_express` фактов не создают. -- `ListMyEvidence` возвращает только факты вызывающего, новые события первыми, включая скрытые (`visibility` `hidden`), с общим `limit` (1-100, по умолчанию 20) и непрозрачным `cursor`, привязанным к кандидату. Неверный или чужой курсор и `limit` вне диапазона дают 400; аккаунт работодателя получает 403. -- `GetOrganizationCandidateEvidence` - раздел анонимной карточки. Он отвечает, только пока на тот же handle ответил бы `GetOrganizationCandidateCard` и карточка показывает хотя бы одну категорию; любой другой случай (неизвестный handle, handle другой организации, закрытая или отозванная публикация, скрытая организация, минимальная когорта, карточка без категорий) дает один и тот же 404, поэтому ответ не раскрывает то, чего не раскрывает карточка. На каждую категорию карточки возвращается один `OrganizationEvidenceFact`: самая ранняя видимая оценка, прошедшая ровно подтвержденный грейд, и только `skill`, `grade`, `trust`, `observed_year` (год, UTC), а также `basis` и `calibration_status` (`synthetic_demo`, `uncalibrated`; одинаковы для всех кандидатов, поэтому отпечатка не добавляют и сообщают, что факт - демонстрация). Более низкий грейд, пересдача, остальные теги, источник, основание, месяц и все идентификаторы остаются у кандидата; не более девяти фактов, по порядку навыков; скрытого факта нет. Ключа, который привязывает ответ к человеку, нет, но он не является несвязываемым: вместе с другими значениями карточки навык, грейд, доверие и год могут сузить малый пул, а минимальная когорта год не покрывает. Чтение расходует квоту просмотров карточек и попадает в историю доступа с полем `categories`. -- Предпросмотр. `CardPreview.evidence` - тот же раздел, посчитанный для кандидата (`OrganizationEvidence`, либо null ровно тогда, когда `card` равен null), поэтому кандидат видит, что организация прочтет вместе с полем `categories`. Организация и когорта не применяются, так что организация может получить меньше. -- Закрытые схемы и обход приватности. У каждого объекта доказательств `additionalProperties: false`, и все его свойства обязательны. `TestNoOrganizationOperationReachesRawAssessmentData` (Go) и `test_evidence_is_closed_and_no_organization_operation_reaches_raw_assessment_data` (Python) обходят все организационные операции и `ListMyEvidence` по всем ссылкам и падают на схеме оценки, сигнала или проверки и на свойстве с сырым ответом, баллом или провалом. - -Открытые вопросы: нужна ли новая версия текста согласия C2, раз публикация `categories` теперь отправляет организации еще один подтверждающий факт оценки (навык, грейд, уровень доверия, год) - решение владельца продукта и юриста, тексты согласий здесь не меняются; нужно ли доказательствам собственное поле карточки вместо поля `categories`; подходит ли работодателю точность в один год; операция скрыть или показать факт для кандидата (сохраненная видимость есть, операции для ее изменения нет); когда в список добавятся заявления профиля и факты из других источников. - -### Подбор - -В теге `organization` одна операция поиска по банку кандидатов, видимому организации (PRD FR09). Она реализована как детерминированный поиск без ML; модель, группы и читаемые данные описаны в [архитектуре](../docs/ru/ARCHITECTURE.md#подбор-и-объяснение). - -| Метод и путь | operationId | Защита | Успех | Специфичные ошибки | -| --- | --- | --- | --- | --- | -| `POST /api/v1/organizations/{org_id}/matches` | `SearchOrganizationMatches` | сессия, CSRF, `Origin`, действующий владелец | 200 `MatchSearchResponse`, `Cache-Control: no-store` | 400, 401, 403, 404 `not_found` | - -Операция ничего не меняет и не требует Idempotency-Key; `POST` нужен для тела. Ответ 200 также не объявляет 429. - -- Доступ. Организация берется из пути и действующего членства владельца аккаунта сессии. Отсутствие сессии дает 401; аккаунт кандидата, участник не владелец, отсутствие CSRF-токена и чужой `Origin` дают 403; неизвестная организация, организация без действующего членства, потребность другой организации, неизвестная потребность и `requirements_version`, которую не создавало изменение подтвержденных требований, дают 404. Скрытые профили, отозванная или отсутствующая публикация C2, скрытие именно этой организации и минимальная когорта карточки применяются до появления любой записи: handle в результате - это handle, который `GetOrganizationCandidateCard` открывает в тот же момент. -- Основание. `MatchSearchByNeed` ищет по неизменяемому снимку `requirements_version` (не по общей `version`), необязательные `filters` сужают его; `MatchSearchByBank` ищет по всем записям, видимым организации, с явными фильтрами. `source` в ответе повторяет основание: ссылку на потребность либо фильтры банка, где присутствует каждый ключ, а неотправленный фильтр равен null (стек отсортирован). -- Записи. Каждая запись - одна специализация кандидата под организационным `candidate_handle`. В `main` и `near` лежат подтвержденные категории (`near`, если обязательный навык запроса дает меньше 0.25), в `unconfirmed` - заявленные специализации, отсортированные по Fit, затем Coverage, затем по внутреннему идентификатору, который не возвращается. У неподтвержденной записи `category: null`, `strength: null` и только `fit` и `coverage`. Группы - не одна шкала, и один handle может быть подтвержден по одной специализации и не подтвержден по другой. -- Основание категории. Каждая подтвержденная категория записи несет `basis` (`synthetic_demo` для демонстрационной категории). Организация видит демонстрацию как таковую, а не как стандартное подтверждение; поле обязательно в `MatchCategory`. -- Нейтральные и неизвестные значения. Семантика - калиброванный косинус сохраненных векторов потребности и карточки, а без них 0.5 с `ml_unavailable`; `percentile` равен null с `cohort_below_30`, а T равен 0.5 (сопоставимой реальной когорты нет, демонстрационные результаты ее не образуют); домен, свежесть и своевременность равны 0.5 со своими признаками; соревновательный вклад равен 0 и не является ни штрафом, ни неизвестностью; неопубликованное значение карточки - `null` в `public_context` с `not_in_public_card`. -- Поиск оплачивается как чтение карточек, потому что запись несет содержимое карточки. Ранжируется весь видимый банк, а каждая группа возвращает не более `max_results_per_group` записей версии политики (демо 10, то есть не более 30 показов за один поиск, меньше 50 просмотров в сутки для уровня E0); итог не возвращается. В порядке `main`, `near`, `unconfirmed` каждый впервые показанный кандидат считается одним уникальным просмотром карточки организации (то же резервирование, что у `GetOrganizationCandidateCard`: кандидат, уже просмотренный в окне, второй раз ничего не стоит, и повтор поиска или последующее открытие карточки не списывает дважды) и получает по одной записи `card_viewed` в истории доступа за поиск с фактически возвращенными полями. Когда лимит заканчивается, возвращаются уже оплаченные записи с `truncated: true`, для остальных ничего не пишется, ошибка и новый код проблемы не возвращаются. `truncated` также истинно, когда группа превысила предел, и никогда не несет число. В ответе `truncated` обязателен. -- Ни в одной записи нет контакта, локации кандидата, суммы или минимума зарплаты, сырого ответа, проваленной попытки и причины скрытых данных; объяснение использует только ограниченные значения `MatchEvidenceCode` и `MatchEvidenceState`. -- `semantic_evidence` (до 12, по умолчанию 6) объясняет поиск по потребности: требование потребности, ближайший элемент опубликованной карточки (`project`, `stack`, `roles`), полоса `high` или `medium` и `repository_verified`. Проект назван только опубликованным названием (поле карточки `projects`), без адреса и владельца репозитория; текст модели в объяснение не входит ([архитектура](../docs/ru/ARCHITECTURE.md#семантический-слой-и-объяснения)). Развертывание, действующая политика которого не содержит раздела `matching`, отвечает внутренней ошибкой и не ранжирует по умолчаниям. - -Принятые остаточные риски: `truncated` - один бит о размере видимого банка, и время ответа растет вместе с ним; оба ограничены пределом группы и не несут числа. Когда реальная сопоставимая когорта категории достигает минимума политики, перцентиль все равно null с причиной `percentile_not_computed`, и поиск не падает. Изменение видимой когорты во время поиска повторяет его до трех раз; два одновременных поиска одной организации сериализуются ее блокировкой квоты. - -Открытые вопросы: демонстрационное значение 10 для `max_results_per_group` и нужна ли постраничная выдача сверх него; должен ли поиск списывать кандидата за краткую запись по цене полного просмотра карточки; должен ли грейд потребности быть неявным фильтром или только объяснением; должны ли значения PRD оставлять онлайн-результат Backend (доверие 0.6 на широкую связь 0.4 дает 0.24) ниже порога близости 0.25, тогда как заявленный тег (0.25) его достигает, так что кандидат, у которого единственное доказательство нужной технологии - оценка специализации, всегда попадает для нее в `near`; должен ли фильтр `stack` требовать каждый тег (как реализовано) или любой; и является ли демонстрационная связь специализаций с технологиями (Backend над Go, PostgreSQL, Kafka и Docker; DevOps над Docker) таксономией, которую хочет владелец продукта. - -### Уведомления - -Тег `notification` описывает внутренний inbox текущего аккаунта в кабинете кандидата и в кабинете одной организации. В нем четыре операции; логика за ними реализована, но настоящие уведомления пока не создает ни один продуктовый модуль (см. [архитектуру](../docs/ru/ARCHITECTURE.md#внутренние-уведомления)). - -| Метод и путь | operationId | Защита | Успех | Специфичные ошибки | -| --- | --- | --- | --- | --- | -| `GET /api/v1/me/notifications` | `ListMyNotifications` | сессия | 200 `NotificationList`, `Cache-Control: no-store` | 400, 401, 403 `forbidden` (аккаунт работодателя) | -| `POST /api/v1/me/notifications/{notification_id}/read` | `MarkMyNotificationRead` | сессия и CSRF | 200 `NotificationReadReceipt`, `Cache-Control: no-store` | 400, 401, 403, 404 `not_found`, 429 | -| `GET /api/v1/organizations/{org_id}/notifications` | `ListOrganizationNotifications` | сессия | 200 `NotificationList`, `Cache-Control: no-store` | 400, 401, 403 `forbidden` (аккаунт кандидата) или `email_not_verified`, 404 `not_found` | -| `POST /api/v1/organizations/{org_id}/notifications/{notification_id}/read` | `MarkOrganizationNotificationRead` | сессия и CSRF | 200 `NotificationReadReceipt`, `Cache-Control: no-store` | 400, 401, 403, 404 `not_found`, 429 | - -Каждая операция также объявляет проблемный ответ `default`. Новый код problem не добавляется. - -- Inbox - состояние доставки внутри платформы. Элемент существует, как только событие дошло до платформы, независимо от того, отправлено ли письмо, и неудачное или отсутствующее письмо его не блокирует. Повторная доставка того же события - тот же элемент (`id` - идентификатор события). -- Inbox хранит ссылки, а не текст. `content` вычисляется из текущего источника для получателя при каждом чтении и равен `null`, когда источника нет или получатель сейчас не вправе его видеть (например, кандидат скрыл организацию); элемент остается в списке, его можно отметить, а клиент показывает общую строку и никогда не показывает прежнюю копию. `content.link_path` - абсолютный путь того же origin (`^/[A-Za-z0-9/_-]{0,255}$`) или `null`. -- Получатель - аккаунт сессии. Маршрут организации дополнительно требует активное членство любой роли в `org_id` и показывает только элементы вызывающего в этой организации. Кандидат на маршруте организации и работодатель на маршруте кандидата получают 403 `forbidden`, а работодатель с неподтвержденной почтой на маршруте организации - 403 `email_not_verified`. Нет членства, неизвестная организация, элемент другого аккаунта или другой организации и неизвестный идентификатор дают один и тот же 404 `not_found`, поэтому идентификаторы нельзя перебирать. -- Пагинация использует общие `limit` (1-100, по умолчанию 20) и `cursor`, новые доставки первыми, идентификатор разрешает равенство. Курсор привязан к аккаунту и кабинету; курсор другого аккаунта или кабинета дает 400. -- Отметка идемпотентна по эффекту и не требует Idempotency-Key: первое время прочтения сохраняется, и каждый повтор возвращает его. Она не читает источник и не возвращает содержимое. `kind` равен `invitation_delivered` (пока его не создает ни один модуль) или `synthetic` (уведомление без продуктового смысла, которое проверяет путь). -- Закрытые схемы и проверки. У каждого объекта уведомлений `additionalProperties: false`, и все свойства обязательны. `TestNotificationOperationsFollowTheConventions` и `TestNotificationSchemasAreClosedAndKeepTextInTheContent` (Go) проверяют тег, защиту чтений и отметок, статусы, no-store, параметры и то, что у элемента нет текста, названия и контакта вне `content`. - -### Проверки генераторов - -`testdata/openapi-3.2.0.yml` содержит тестовые операции с перечисленными компонентами: пагинацией, Idempotency-Key, If-Match, ETag и problem-ответами. ogen не разрешает внешние ссылки, поэтому фикстура хранит копии компонентов api/core; `scripts/test_contract_copies.py` (входит в `make -C api check`) проверяет, что они, ответы фикстуры и ML-копия `Problem` совпадают с api/core. - -`make -C api check-toolchain` проверяет фикстуру линтером и запускает на ней три генератора; нужны Go toolchain backend, pnpm и uv, поэтому передавайте тот же `UV` override, что и для `make generate`. - -| Target | Генератор | Проверяемые соглашения | -| --- | --- | --- | -| `make -C backend check-ogen-compat` | ogen | Все: Problem, PageInfo, Timestamp, PageLimit, PageCursor, IdempotencyKey, IfMatch, ETag. Тесты проверяют ошибки валидации, сценарий повтора, предусловия и лимит тела 413 вместе с backend-маппингом problem | -| `make -C frontend check-orval-compat` | Orval | Problem, PageInfo, Timestamp, PageLimit, PageCursor, IdempotencyKey, IfMatch. Результат проходит проверку типов с настройками компилятора frontend | -| `make -C ml check-pydantic-compat` | datamodel-code-generator | Problem, PageInfo, Timestamp, PageLimit, PageCursor. Модели проходят `mypy --strict` и скрипт валидации | - -Каждый target пишет результат во временный каталог и удаляет его. - -Известные ограничения генераторов: - -- Orval 8.40 не создает Zod-схемы для `components/responses`, но импортирует тип `Response` для каждой ссылки. Поэтому `frontend/codegen/orval.config.ts` встраивает ссылки на ответы перед генерацией. -- Orval передает header-параметры типизированным аргументом только с `headers: true`. С `exactOptionalPropertyTypes` необязательный заголовок, например `If-Match`, совместим с `RequestInit` только при точных необязательных свойствах Zod, поэтому конфигурация также задает `override.zod.exactOptional`. -- Orval не генерирует типы заголовков ответа, а `apiRequest` возвращает только тело, поэтому сгенерированный клиент пока не может прочитать `ETag`. Первая операция с версионируемым ресурсом должна открыть его, например через тело ответа или mutator. -- datamodel-code-generator 0.83.0 создает модели только для схем и query- и path-параметров; header-параметры и заголовки ответа (Idempotency-Key, If-Match, ETag) не дают Python-моделей. -- Orval не генерирует методы для `additionalOperations`. -- ogen записывает имя заголовка в канонической Go-форме (`Etag`); имена HTTP-заголовков не зависят от регистра. -- ogen требует `SecurityHandler`, как только в контракте есть схемы защиты, и проверяет схемы в порядке имен их сгенерированных типов, поэтому переименование схемы может изменить порядок; тогда `TestGeneratedServerSecurityOrder` упадет. Сбои защиты попадают в `NewError` без заголовков ответа, поэтому удаление cookie при 401 от `Logout` требует ручного кода. -- Orval не делает значения схем защиты типизированными аргументами, поэтому `X-CSRF-Token` не является сгенерированным параметром; его планируется добавлять к изменяющим запросам в общем API-клиенте. Тип для `Set-Cookie` Orval тоже не генерирует, этот заголовок обрабатывает браузер. -- Zod-схемы Orval игнорируют `uniqueItems` и не отклоняют неизвестные поля объектов с `additionalProperties: false`; в обоих случаях решает сервер. -- ogen генерирует необязательное nullable-поле как `OptNil`, которое различает отсутствие (`IsSet` false), null (`IsNull`) и значение. Необязательный массив без null, напротив, - обычный slice, где nil и `[]` значат разное: отсутствующее поле декодируется в nil (без изменений), `[]` - в пустой slice, не равный nil (удалить все элементы), а null не декодируется. Поэтому обработчик `UpdateOrganizationNeed` должен проверять списки через `!= nil`, а не через `len`; это закрепляет `TestNeedUpdateDecodingKeepsAbsentAndEmptyListsApart`. -- Orval очищает `src/shared/api/endpoints/` и `src/shared/api/schemas/` перед генерацией (`clean: true`), потому что схема, используемая несколькими тегами, переезжает из каталога тега в корень схем. -- Шаг после Orval `frontend/codegen/mock-patterns.ts` ищет границы длины строки с pattern по имени свойства и pattern, поэтому два свойства с одинаковыми именем и pattern должны иметь одинаковые границы. Поэтому технологии в условиях приглашения называются `tech_stack` (`SkillName`, до 100 символов) рядом с `stack` анкеты (`StackTag`, до 50), а условие пакета передает `description`, а не `value`, которое решения потребности используют с другими границами. - -#### Объединения форматов - -- Объединения форматов, например `ItemContent` и `AssessmentAnswer`, - это `oneOf` без объекта `discriminator`. Redocly разрешает значения `discriminator.mapping` как ссылки, а `scripts/merge-schemas.py` переписывает только `$ref`, поэтому mapping из отдельного файла схем не разрешается в объединенном `components/schemas.yml`. Каждый вариант фиксирует `format` перечислением из одного значения; ogen различает варианты по этому значению и по полям, уникальным для варианта, и отклоняет тело, подходящее под несколько вариантов, а Orval генерирует Zod-объединение. -- Orval называет константы встроенного свойства ``, поэтому имя свойства, повторяющее имя другой схемы, дает конфликт в `index.ts` (TS2308). Поэтому объединение форматов задания называется `ItemContent`, а не `AssessmentItemContent`, рядом со свойством `AssessmentItem.content`, а части `Need` называются `NeedRequirementSet`, `NeedReadinessReport` и `NeedCategoryRecommendations`, а не `NeedRequirements`, `NeedReadiness` и `NeedRecommendations`. Срок ответа обращения называется `SupportResponseTarget`, а не `SupportCaseResponseTarget`, рядом со свойством `SupportCase.response_target`. - -Сгенерированный Zod не строгий. Тело, смешивающее поля двух форматов или содержащее лишние `score` или `seed`, принимается после молчаливого удаления неизвестных ключей, а `uniqueItems` не проверяется; такие тела отклоняет только сервер. `frontend/src/shared/api/assessment-contract.test.ts` закрепляет принимаемые форматы и отсутствие в DTO ответа и задания полей балла, ключа, seed или правильности. - -Подробнее: [разработка](../docs/ru/DEVELOPMENT.md). +Процесс изменения контрактов: [DEVELOPMENT.md](../docs/ru/DEVELOPMENT.md). Проверки: [TESTING.md](../docs/ru/TESTING.md). diff --git a/backend/db/migrations/00027_expand_candidate_card_fields.sql b/backend/db/migrations/00027_expand_candidate_card_fields.sql index 2e36258..9beaeca 100644 --- a/backend/db/migrations/00027_expand_candidate_card_fields.sql +++ b/backend/db/migrations/00027_expand_candidate_card_fields.sql @@ -1,5 +1,5 @@ -- +goose Up --- TASK-089 adds separately chosen opt-in groups to the anonymous card. The +-- Add separately chosen opt-in groups to the anonymous card. The -- publication and event constraints call this function, so replacing it -- changes the accepted contract without rewriting any saved field set. -- +goose StatementBegin diff --git a/backend/testdata/assessment/BUNDLE_STATUS.md b/backend/testdata/assessment/BUNDLE_STATUS.md index 34e4ed3..8ada7dc 100644 --- a/backend/testdata/assessment/BUNDLE_STATUS.md +++ b/backend/testdata/assessment/BUNDLE_STATUS.md @@ -1,42 +1,16 @@ -# Assessment demo bundle status +# Assessment demo bundle -`backend_demo_bundle.json` is the input of the assessment bank loader -(`internal/usecase/assessment`) for the category `backend`. It holds four -families of original practice problems with deterministic seed generators, -reference solutions, and rubrics. +`backend_demo_bundle.json` contains four draft families for testing the assessment +bank loader. Each has a deterministic generator, reference solution, and rubric. -## Status: AI-generated draft, pending human review +The bundle records its author and a pending review. Keep those provenance fields +accurate: the content has not received independent human review or difficulty +calibration. Importing it creates drafts; publication requires an approved review +by someone other than the author. This fixture alone cannot open a category. -- Author: `ai:claude-draft`. The problems were written by an AI assistant for - the loader task; they are not copies or paraphrases of problems from any - coding-practice site. -- Review: `pending`. The reviewer field is empty on purpose. No human has - checked the statements, the reference solutions, the rubrics, or the - difficulty. Do not fill the field to make the bundle pass. -- Consequences, which the integration tests rely on: - - The loader imports every family as a `draft`. - - A family without a reviewer cannot be published - (`reviewer_missing`). - - The category `backend` cannot be opened: it has no published family, and - four families are below the coverage that the grading policy requires. -- The bundle makes no claim about difficulty, validity, or grade - calibration. +Category opening also requires a separate versioned grading policy and sufficient +published coverage. The fixture's rubrics do not supply grade thresholds. -## What the bundle does not contain - -- No grading policy. A category opens only under a versioned grading policy - that is referenced by `policy_versions.id` when the category is opened. The - rubrics list criteria without points or thresholds. -- No reviewer. A real review produces a new bundle version in which the - family versions carry an approved review by an operator who is not the - author; stored versions are never edited. - -## Format - -Documented by the types `assessment.Bundle` and `domain.AssessmentFamily`. -Seed algorithms are registered in `internal/domain/assessment_algorithms.go` -under versioned names (`rate_limit_window.v1`, `dedup_window.v1`, -`lru_hits.v1`, `lru_hits_choice.v1`, `dependency_order.v1`); the statement -templates use the parameter names and the data names of the chosen algorithm. -A family can instead declare a `table` of variants with their answers in its -`seed_generator`; this bundle uses only algorithms. +The format is defined by `assessment.Bundle` and `domain.AssessmentFamily`. +Generator implementations live in `internal/domain/assessment_algorithms.go`. +Families may use algorithmic or table variants; this fixture uses algorithms. diff --git a/deploy/README.en.md b/deploy/README.en.md index 79a19fb..2e514b6 100644 --- a/deploy/README.en.md +++ b/deploy/README.en.md @@ -2,21 +2,28 @@ [Русский](README.md) | English -Configuration for running the application with Docker Compose and Nginx. +Docker Compose, Nginx, and startup tools. Dockerfiles live in service directories; the shared `.env.example` is at the repository root. -- `docker/docker-compose.yml` starts the core stack with PostgreSQL, Redis, SeaweedFS, and Kafka. -- `docker/docker-compose.ml.yml` and `docker/docker-compose.monitoring.yml` run ML and monitoring as separate projects. -- `nginx/` configures frontend serving and API proxying. -- `docker/docker-compose.e2e.yml` is an overlay used only by the browser suite: it removes the frontend host port and adds the Playwright runner. -- `docker/docker-compose.release.yml`, `docker/docker-compose.demo.release.yml`, and `docker/docker-compose.ml.release.yml` are overlays that name the release images `lincodex.invalid/:` (the demo seed image included) and never pull them from a registry. -- `docker/docker-compose.demo.yml` and `demo/` belong to the isolated demo stand with synthetic data: `make -C deploy demo-seed DEMO_MODE=isolated` starts and seeds it, `demo-reset` rebuilds it only when it holds no ordinary account, and `demo-down` stops it; see the [isolated demo stand](../docs/en/DEPLOY.md#isolated-demo-stand). -- `scripts/` contains the isolated stack smoke check, the browser E2E runner, and `release_manifest.py`, which builds, describes, and checks release images. -- `edge/` holds the public edge proxy: nginx and tunnel templates, certbot renewal hook, systemd drop-ins, and the scripts that render and check them. `make -C deploy edge-config` renders the nginx configuration and runs `nginx -t` in a container; see the [edge proxy runbook](../docs/en/DEPLOY.md#edge-proxy-https-and-tunnel). -- `labs/` holds the LXD layout of the app host for the isolated runner and the labs (`lxd-preseed.yaml`, `acls.sh`) and `runner-vm.sh`, which builds, updates, and checks the production runner VM: `make -C deploy runner-vm-up`, `runner-vm-a16`, and `runner-vm-check` on the app host, and `check-runner-vm` anywhere; see [the runner VM](../docs/en/DEPLOY.md#production-the-runner-vm). -- `make -C deploy check-perimeter` checks the published ports, denied paths, limits, and the trusted peer of Nginx from the files; `make -C deploy perimeter-test` checks the same over HTTP on throwaway Nginx containers; see [Public perimeter and client address](../docs/en/DEPLOY.md#public-perimeter-and-client-address). +| Directory | Purpose | +| --- | --- | +| `docker/` | Core stack and separate Compose files for ML, monitoring, demo, E2E, and the dev runner | +| `nginx/` | SPA serving and API proxy to Go | +| `edge/` | Public HTTPS proxy and private tunnel templates | +| `labs/` | LXD networks, code runner VM, and labd systemd configuration | +| `ml-gpu/` | ML on a GPU host through systemd | +| `demo/`, `scripts/` | Synthetic data, checks, and release tooling | +| `release/` | Local release manifests, excluded from Git | -Dockerfiles live in service directories and `.env.example` at the repository root. From the root, `make -C deploy config` checks Compose and `make -C deploy up` starts the core stack after `.env` is prepared. Start monitoring separately with `make -C deploy monitoring-up`. `make -C deploy test-e2e` runs the Playwright suite against a throwaway stack under a unique project name and removes it afterwards; `make -C deploy test-e2e-registration` enables a local Resend-compatible inbox only for registration browser tests. See [TESTING.md](../docs/en/TESTING.md#browser-e2e-suite) for details. +From the repository root: -`make -C deploy release-build`, `release-smoke`, `release-e2e`, and `release-manifest` build the release images with pinned base image digests, check them, and publish an immutable manifest to `deploy/release//`, which Git ignores; a new `RELEASE_ID` gives the next stage its own manifest. `make -C deploy release-manifest-check` scans the manifest for secrets and machine data, `release-manifest-verify` compares running containers with it, `release-up` restores the core stack and `demo-seed DEMO_MODE=isolated RELEASE_ID=` the demo stand from its exact images, and `release-clean` removes release images that no manifest retains. See the [release manifest](../docs/en/DEPLOY.md#release-manifest). +```sh +make -C deploy help +make -C deploy config +make -C deploy up +``` -See the [deployment guide](../docs/en/DEPLOY.md). +`config` validates examples; `up` requires a prepared `.env` and starts core only. ML and monitoring start separately; monitoring and local ML need the existing core network. `down` preserves volumes. + +For a demonstration: `make -C deploy demo-seed DEMO_MODE=isolated`. For checks: `make -C deploy check`, `smoke`, or `test-e2e`. The latter two create and remove their own stands. + +Secrets, HTTPS, runner, and release instructions: [DEPLOYMENT.md](../docs/en/DEPLOYMENT.md). Test scenarios: [TESTING.md](../docs/en/TESTING.md). diff --git a/deploy/README.md b/deploy/README.md index dff2ddd..bb4ead8 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -2,21 +2,28 @@ Русский | [English](README.en.md) -Конфигурация запуска через Docker Compose и Nginx. +Docker Compose, Nginx и инструменты запуска. Dockerfile лежат в каталогах сервисов, общий пример настроек - в `.env.example` в корне. -- `docker/docker-compose.yml` поднимает основной стек с PostgreSQL, Redis, SeaweedFS и Kafka. -- `docker/docker-compose.ml.yml` и `docker/docker-compose.monitoring.yml` запускают ML и мониторинг отдельными проектами. -- `nginx/` содержит конфигурацию раздачи frontend и проксирования API. -- `docker/docker-compose.e2e.yml` - overlay только для браузерного набора: убирает host-порт frontend и добавляет запуск Playwright. -- `docker/docker-compose.release.yml`, `docker/docker-compose.demo.release.yml` и `docker/docker-compose.ml.release.yml` - overlay с именами образов выпуска `lincodex.invalid/:` (включая образ demo seed) без скачивания из registry. -- `docker/docker-compose.demo.yml` и `demo/` относятся к изолированному демонстрационному стенду с синтетическими данными: `make -C deploy demo-seed DEMO_MODE=isolated` запускает и заполняет его, `demo-reset` пересоздает его, только если в нем нет обычных аккаунтов, а `demo-down` останавливает; см. [изолированный демонстрационный стенд](../docs/ru/DEPLOY.md#изолированный-демонстрационный-стенд). -- `scripts/` содержит smoke-проверку изолированного стека, запуск браузерных E2E и `release_manifest.py` для сборки, описания и сверки образов выпуска. -- `edge/` содержит публичный edge proxy: шаблоны nginx и туннеля, hook продления certbot, drop-in systemd и скрипты, которые их отрисовывают и проверяют. `make -C deploy edge-config` отрисовывает конфигурацию nginx и выполняет `nginx -t` в контейнере; см. [runbook edge proxy](../docs/ru/DEPLOY.md#edge-proxy-https-и-туннель). -- `labs/` содержит раскладку LXD хоста приложения для изолированного исполнителя и лабораторий (`lxd-preseed.yaml`, `acls.sh`) и `runner-vm.sh`, который собирает, обновляет и проверяет production VM исполнителя: `make -C deploy runner-vm-up`, `runner-vm-a16` и `runner-vm-check` на хосте приложения и `check-runner-vm` где угодно; см. [VM исполнителя](../docs/ru/DEPLOY.md#production-vm-исполнителя). -- `make -C deploy check-perimeter` проверяет по файлам опубликованные порты, запрещенные пути, лимиты и доверенного пира Nginx; `make -C deploy perimeter-test` проверяет то же по HTTP на одноразовых контейнерах Nginx; см. [Публичный периметр и адрес клиента](../docs/ru/DEPLOY.md#публичный-периметр-и-адрес-клиента). +| Каталог | Назначение | +| --- | --- | +| `docker/` | Основной стек и отдельные Compose для ML, мониторинга, demo, E2E и dev-runner | +| `nginx/` | Раздача SPA и проксирование API в Go | +| `edge/` | Шаблоны публичного HTTPS-прокси и приватного туннеля | +| `labs/` | LXD-сети, VM исполнителя кода и systemd-конфигурация labd | +| `ml-gpu/` | Запуск ML на GPU-хосте через systemd | +| `demo/`, `scripts/` | Синтетические данные, проверки и сборка выпуска | +| `release/` | Локальные манифесты выпуска, вне Git | -Dockerfile лежат в каталогах сервисов, `.env.example` - в корне репозитория. Из корня: `make -C deploy config` проверяет Compose, `make -C deploy up` запускает основной стек после подготовки `.env`. Мониторинг включается отдельно через `make -C deploy monitoring-up`. `make -C deploy test-e2e` запускает набор Playwright на одноразовом стеке с уникальным именем проекта и удаляет его после прогона; `make -C deploy test-e2e-registration` включает локальный Resend-compatible inbox только для браузерных тестов регистрации. Подробности см. в [TESTING.md](../docs/ru/TESTING.md#браузерный-e2e-набор). +Из корня репозитория: -`make -C deploy release-build`, `release-smoke`, `release-e2e` и `release-manifest` собирают образы выпуска с закрепленными digest базовых образов, проверяют их и публикуют неизменяемый манифест в `deploy/release//` (игнорируется Git); новый `RELEASE_ID` дает следующему этапу собственный манифест. `make -C deploy release-manifest-check` ищет в манифесте секреты и данные машины, `release-manifest-verify` сверяет с ним запущенные контейнеры, `release-up` восстанавливает основной стек, а `demo-seed DEMO_MODE=isolated RELEASE_ID=` - демонстрационный стенд из точных образов, и `release-clean` удаляет образы выпуска, которые не удерживает ни один манифест. См. [манифест выпуска](../docs/ru/DEPLOY.md#манифест-выпуска). +```sh +make -C deploy help +make -C deploy config +make -C deploy up +``` -Подробнее: [развертывание](../docs/ru/DEPLOY.md). +`config` проверяет примеры, `up` требует подготовленный `.env` и запускает только core. ML и мониторинг включаются отдельно; мониторинг и локальный ML требуют уже созданной сети core. `down` сохраняет тома. + +Для демонстрации: `make -C deploy demo-seed DEMO_MODE=isolated`. Для проверок: `make -C deploy check`, `smoke` или `test-e2e`. Последние две цели создают и удаляют свои стенды. + +Инструкции по секретам, HTTPS, runner и выпуску: [DEPLOYMENT.md](../docs/ru/DEPLOYMENT.md). Сценарии проверок: [TESTING.md](../docs/ru/TESTING.md). diff --git a/deploy/docker/docker-compose.runner.dev.yml b/deploy/docker/docker-compose.runner.dev.yml index 4701169..1b2a84d 100644 --- a/deploy/docker/docker-compose.runner.dev.yml +++ b/deploy/docker/docker-compose.runner.dev.yml @@ -5,7 +5,7 @@ # writable cgroup v2 tree inside the Docker Desktop VM, and it serves plain # HTTP on loopback. A privileged container on the core application host is # forbidden; production runs the runner image only inside its dedicated VM -# with TLS and without these switches (see docs/en/DEPLOY.md). +# with TLS and without these switches (see docs/en/DEPLOYMENT.md). # # Use it through make -C deploy runner-dev-up, which creates the local token # file named by RUNNER_DEV_TOKEN_FILE. diff --git a/deploy/docker/docker-compose.yml b/deploy/docker/docker-compose.yml index a7b2323..a28c4be 100644 --- a/deploy/docker/docker-compose.yml +++ b/deploy/docker/docker-compose.yml @@ -242,7 +242,7 @@ services: IDENTITY_SESSION_IDLE_TIMEOUT: ${IDENTITY_SESSION_IDLE_TIMEOUT:-24h} IDENTITY_SESSION_ABSOLUTE_LIFETIME: ${IDENTITY_SESSION_ABSOLUTE_LIFETIME:-168h} ASSESSMENT_DEMO_CATEGORIES_ENABLED: ${ASSESSMENT_DEMO_CATEGORIES_ENABLED:-false} - # Semantic matching (see docs/en/DEPLOY.md#semantic-matching). Off by + # Semantic matching (see docs/en/DEPLOYMENT.md#semantic-matching). Off by # default: searches then use the neutral Sem. When on, vector jobs call # the separate ML project, which joins this network as "ml". SEMANTIC_MATCHING_ENABLED: ${SEMANTIC_MATCHING_ENABLED:-false} @@ -259,7 +259,7 @@ services: GITHUB_TOKEN: ${GITHUB_TOKEN:-} GITHUB_TIMEOUT: ${GITHUB_TIMEOUT:-10s} REPOSITORY_CHECK_INTERVAL: ${REPOSITORY_CHECK_INTERVAL:-10m} - # Own code runner (see docs/en/DEPLOY.md#code-runner-client). Off while + # Own code runner (see docs/en/DEPLOYMENT.md#code-runner-client). Off while # CODE_RUNNER_URL is empty: practice then reports the runner as # unavailable and runs nothing. The token and the run key are secrets; # pass the CA inline (CODE_RUNNER_CA_PEM) or mount a file and set its @@ -294,7 +294,7 @@ services: expose: - "8080" - "9090" - # Shutdown budget with the defaults (see docs/en/DEPLOY.md): + # Shutdown budget with the defaults (see docs/en/DEPLOYMENT.md): # - in parallel: the HTTP shutdown (SHUTDOWN_TIMEOUT, 10s), the relay # pass (10s plus a 5s rollback), and each event consumer # (CONSUMER_SHUTDOWN_GRACE 5s, a 5s rollback, CONSUMER_COMMIT_TIMEOUT @@ -328,7 +328,7 @@ services: ipv4_address: ${APP_FRONTEND_IP:-172.29.79.10} ports: # Loopback by default. On the app host behind the edge proxy, - # APP_HTTP_BIND is the tunnel address (see docs/en/DEPLOY.md); never + # APP_HTTP_BIND is the tunnel address (see docs/en/DEPLOYMENT.md); never # set it to 0.0.0.0, because Docker publishing bypasses ufw. - "${APP_HTTP_BIND:-127.0.0.1}:${APP_HTTP_PORT:-8080}:8080" healthcheck: diff --git a/deploy/edge/systemd/awg-quick-userspace.conf b/deploy/edge/systemd/awg-quick-userspace.conf index 1c9adde..0dc35bc 100644 --- a/deploy/edge/systemd/awg-quick-userspace.conf +++ b/deploy/edge/systemd/awg-quick-userspace.conf @@ -2,7 +2,7 @@ # /etc/systemd/system/awg-quick@awg-lincodex.service.d/userspace.conf. # # The kernel module is not used: awg-quick falls back to the userspace -# daemon, which is installed from a pinned build (see docs/en/DEPLOY.md). +# daemon, which is installed from a pinned build (see docs/en/DEPLOYMENT.md). # The daemon is one process per interface and is not restarted by systemd # on its own; check the handshake with `awg show` after incidents. [Service] diff --git a/deploy/labs/acls.sh b/deploy/labs/acls.sh index bbf5527..308f270 100755 --- a/deploy/labs/acls.sh +++ b/deploy/labs/acls.sh @@ -1,5 +1,5 @@ #!/usr/bin/env bash -# Creates the network ACLs referenced by lxd-preseed.yaml (TASK-592). +# Creates the network ACLs referenced by lxd-preseed.yaml. # Run before the preseed. Rules are stateful: replies to allowed traffic pass. set -euo pipefail diff --git a/deploy/labs/lxd-preseed.yaml b/deploy/labs/lxd-preseed.yaml index d1d9f25..2fc668c 100644 --- a/deploy/labs/lxd-preseed.yaml +++ b/deploy/labs/lxd-preseed.yaml @@ -1,4 +1,4 @@ -# LXD host layout for the isolated runner and the practical labs (TASK-592). +# LXD host layout for the isolated runner and the practical labs. # Applied once on the app host with: lxd init --preseed < lxd-preseed.yaml # It only adds objects; it does not touch Docker, wg0 or the awg-lincodex tunnel. storage_pools: diff --git a/deploy/ml-gpu/lincodex-ml.service b/deploy/ml-gpu/lincodex-ml.service index df38d4b..6c15404 100644 --- a/deploy/ml-gpu/lincodex-ml.service +++ b/deploy/ml-gpu/lincodex-ml.service @@ -1,7 +1,7 @@ # systemd user unit of the ML service on a GPU host without Docker. Install it # as ~/.config/systemd/user/lincodex-ml.service of the service user (with # lingering enabled) and keep the settings and the token in the environment -# file, mode 600; see docs/en/DEPLOY.md#ml-service-on-a-gpu-host. +# file, mode 600; see docs/en/DEPLOYMENT.md#ml-service-on-a-gpu-host. # # %h is the home directory of the user: the layout below is # %h/lincodex-ml/app/ml the ml/ directory of the release diff --git a/deploy/ml-gpu/ml.env.example b/deploy/ml-gpu/ml.env.example index ae075ee..3ae53af 100644 --- a/deploy/ml-gpu/ml.env.example +++ b/deploy/ml-gpu/ml.env.example @@ -6,7 +6,7 @@ ML_EMBEDDER=giga,qwen3 ML_DEVICE=cuda # float16 fits both models in about 2.4 GiB of VRAM; see the precision note in -# docs/en/DEPLOY.md#ml-service-on-a-gpu-host before changing it. +# docs/en/DEPLOYMENT.md#ml-service-on-a-gpu-host before changing it. ML_DTYPE=float16 # Allocator cap of the process; the CUDA context adds about 130 MiB. ML_CUDA_MEMORY_LIMIT_MB=2300 diff --git a/docs/README.en.md b/docs/README.en.md index aa66796..c2f060c 100644 --- a/docs/README.en.md +++ b/docs/README.en.md @@ -4,11 +4,10 @@ Guides to the project's structure and development workflow. Russian documents live in `ru/`, with English translations in `en/`. -- [ARCHITECTURE](en/ARCHITECTURE.md) covers service boundaries, layers, and planned product workflows. +- [ARCHITECTURE](en/ARCHITECTURE.md) covers components, data flows, and implementation boundaries. - [DEVELOPMENT](en/DEVELOPMENT.md) covers project structure, code generation, and development rules. -- [DEPLOY](en/DEPLOY.md) covers the MVP quick start and the demo stand, startup, environment settings, and monitoring. +- [DEPLOYMENT](en/DEPLOYMENT.md) covers the MVP quick start and the demo stand, startup, environment settings, and monitoring. - [TESTING](en/TESTING.md) describes test types, commands, and check boundaries. - [SECURITY](en/SECURITY.md) describes scanners, reports, and security exceptions. -- [MVP](en/MVP.md) is the submission package of the minimal release: what is implemented, how to run it, limits, what is not implemented, and checks. Update both language versions together. From the repository root, `make docs-check` checks documentation structure and local links. Source requirements and brand assets live in [requirements/](../requirements/README.en.md). diff --git a/docs/README.md b/docs/README.md index 962f6f7..c27a3a0 100644 --- a/docs/README.md +++ b/docs/README.md @@ -4,11 +4,10 @@ Руководства по устройству проекта и работе с ним. Русские документы находятся в `ru/`, английские переводы - в `en/`. -- [ARCHITECTURE](ru/ARCHITECTURE.md) - границы сервисов, слои и запланированные продуктовые сценарии. +- [ARCHITECTURE](ru/ARCHITECTURE.md) - компоненты, потоки данных и границы реализации. - [DEVELOPMENT](ru/DEVELOPMENT.md) - структура проекта, кодогенерация и правила разработки. -- [DEPLOY](ru/DEPLOY.md) - быстрый старт MVP и демонстрационный стенд, запуск, настройки окружения и мониторинг. +- [DEPLOYMENT](ru/DEPLOYMENT.md) - быстрый старт MVP и демонстрационный стенд, запуск, настройки окружения и мониторинг. - [TESTING](ru/TESTING.md) - виды тестов, команды и границы проверок. - [SECURITY](ru/SECURITY.md) - сканеры, отчеты и исключения безопасности. -- [MVP](ru/MVP.md) - пакет сдачи минимального выпуска: что реализовано, запуск, ограничения, нереализованное и проверки. Обе языковые версии обновляются вместе. Из корня репозитория: `make docs-check` проверяет структуру документации и локальные ссылки. Исходные ТЗ и брендбук находятся в [requirements/](../requirements/README.md). diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md index 4ff7c44..4846fa7 100644 --- a/docs/en/ARCHITECTURE.md +++ b/docs/en/ARCHITECTURE.md @@ -1,1351 +1,171 @@ # Lincodex architecture -This document separates the target product architecture from the technical scaffold in the repository. The requirements source is the [specification](../../requirements/specification.pdf). Page references in the coverage table use the printed pagination without the cover page. The [brandbook](../../requirements/brandbook/) is stored alongside the specification. The team supplied October 11 and October 30, 2026, as project milestones. +Lincodex helps employers find candidates by skills and invite them to work. Candidates control profile publication and disclose selected contacts only after accepting an invitation. This document describes the current code; limitations are listed separately. -## Current scaffold +## Components -The repository contains a Go HTTP service with PostgreSQL, Redis, and SeaweedFS checks, cache and S3 storage adapters, a React interface with public pages and two cabinets (working screens for the workflows described below), a separate Python ML service with health and readiness routes, two OpenAPI contracts, code generation, Compose files, and monitoring configuration. The public API health route is under /api/v1/healthz. The web container uses /healthz. The internal Go /readyz checks PostgreSQL, Redis, and the SeaweedFS bucket. ML uses /healthz and /readyz; readiness returns 503 while inference is unavailable. Go exposes the standard /metrics endpoint on an internal port. +```text +Browser -> Nginx -> Go API -> PostgreSQL + | -> Redis + | -> SeaweedFS + | -> outbox -> Kafka -> consumers + | -> scheduled jobs -> ML service + | -> practice queue -> runner VM +``` -Registration, email confirmation, login, and basic current-session operations work through the backend API and the frontend screens; local browser E2E covers candidate and employer accounts. The backend API and the cabinet screens also cover consents C1-C5 and the account deletion request; organizations, memberships, and employer needs; the manual candidate profile and the questionnaire with specializations and self-assessment; the public specialization catalog; assessment attempts (create, answers, finalize, result history, server signals, and skill evidence), where the task bank and the categories are demonstration data and uncalibrated; privacy settings and publication of the anonymous card; the internal notification inbox of both cabinets (see [Internal notifications](#internal-notifications)); and support cases. The manual assessment request is implemented as a support case of that type (`usecase/supportcase`, `frontend/src/features/request-manual-assessment`): it does not depend on consent C3, creates no attempt, changes no category, and only puts the case into the expert queue; the API has no operation for the expert side of that queue. The deterministic basic match search of the organization-visible bank works through the backend API without ML, competition data, or search snapshots (see [Matching and explanations](#matching-and-explanations)); category recommendations for a need are not computed, and the response carries an empty list (`domain/need_response.go`). +| Component | Responsibility | +| --- | --- | +| `frontend/` | React, TypeScript, Vite: public pages and candidate and company workspaces | +| `backend/` | Go, chi, Clean Architecture: authorization, profiles, assessment, matching, invitations and background loops | +| `ml/` | Python/FastAPI: embeddings for semantic matching in a separate process | +| `runner/` | Go: program judging in an isolated environment outside the core application | +| `labd/` | Network lab provisioner foundation; its user flow is not connected yet | +| `api/` | Shared OpenAPI contracts for core, ML, runner and labd | +| `deploy/`, `observability/` | Compose, Nginx, releases and a separate monitoring stack | -Invitations are implemented end to end (see [Invitation drafts](#invitation-drafts), [Sending invitations](#sending-invitations), [Candidate view and decline](#candidate-view-and-decline), [Candidate acceptance](#candidate-acceptance), [Pending limit, cooldown, and expiry](#pending-limit-cooldown-and-expiry), and [Contact reads and revocation](#contact-reads-and-revocation)): an organization creates and updates a draft with versioned terms and sends it; the invitation reaches the candidate's inbox and produces an internal notification; the candidate reads it, marks it viewed, declines it, or accepts it with consent C4 for the chosen contacts; after acceptance the organization reads the shared contacts, and the candidate can revoke the contact grant. The pending limit per need, the cooldown of the organization-candidate pair after a decline, and the expiry at the response deadline apply. The frontend has the invitation composer reached from a search result, the organization's invitation list (`pages/employer-invitations`), and the candidate inbox. The operations for withdrawal by the organization (`WithdrawOrganizationInvitation`), cancellation by the candidate (`CancelMyInvitation`), and the salary raise (`RaiseOrganizationInvitationSalary`) are in the contract but not implemented, and answer 501 `not_implemented`. +The main deployment is one application node with Docker Compose. ML and code execution can run separately. The current implementation does not need Kubernetes or a separate vector database. -Not implemented: counter-offers and the stages after acceptance (interviews), password reset, resume upload and analysis, PDF, search snapshots and refinement, ML inference and semantic search (the backend does not call the ML client), FSP integration (the `adapter/secondary/fsp` directory is empty), the SMTP transport (the backend fails to start with `EMAIL_PROVIDER=smtp`; only Resend sends mail), PDF generation (the `adapter/secondary/pdf` directory is empty), and ATS adapters. ML does not return invented results. Health checks and the technical smoke do not verify a product workflow. +## Go backend -See [development](DEVELOPMENT.md), [deployment](DEPLOY.md), and [testing](TESTING.md) for source layout, commands, and current check coverage. +`cmd/app/main.go` calls `bootstrap.Run()`. Bootstrap reads `backend/config/`, assembles dependencies, applies migrations and manages HTTP servers and workers. Wire generates dependency wiring during development; there is no runtime DI container. -## Target system +| Directory under `backend/` | Purpose | +| --- | --- | +| `internal/domain/` | Types, states and business rules, with files directly in the package | +| `internal/usecase/` | Application flows and transaction coordination | +| `internal/port/` | Inbound and outbound interfaces | +| `internal/adapter/primary/http/` | `router.go`, middleware, generated `api/` and `v1/` handlers | +| `internal/adapter/primary/cli/` | Operator commands | +| `internal/adapter/secondary/` | PostgreSQL, Redis, SeaweedFS, Kafka, ML, mail and Prometheus | +| `internal/worker/` | Relay, consumers, scheduled jobs, mail and the practice queue | +| `internal/bootstrap/` | Application composition and lifecycle | +| `pkg/` | Shared technical helpers without product logic | +| `db/`, `codegen/` | Migrations, SQL queries and generator configuration | -The target is a modular Go backend with Clean Architecture, a React SPA using Vite and FSD, and a separate ML HTTP service in one repository. The planned Go process runs the HTTP API and background worker together. PostgreSQL stores product records and jobs; Redis provides the cache. Private S3-compatible SeaweedFS storage is selected for resumes and generated PDFs; the file workflows are not implemented yet. The initial target uses Docker Compose on one application host, with ML in a separate environment. +HTTP translates DTOs into usecase commands. Usecases depend on domain and ports; bootstrap supplies their implementations. SQL, ML and HTTP handlers do not decide who may see contacts. Workers call application flows instead of replacing them. -Go owns authorization, verified categories, invitations, contact grants, and final search results. ML proposes resume fields, helps interpret employer needs, and can take part in semantic search experiments. Model outages must leave manual profiles, assessments, filter-based search, and invitations available. - -Combining API and worker simplifies the demo deployment, while sharing process lifecycle, memory limits, and metrics registry. The worker can move to its own process when independent scaling is needed without moving usecases or ports. That worker is planned. - -The project brief assigns 35% of its score to matching, 25% to assessment and categorization, and 7% to technical implementation. The October 11 milestone calls for a working prototype flow. Technical work alone does not provide that flow. +API and background loops share a process but use separate bounded PostgreSQL pools. Workers can become a separate process later without moving business rules. ## Contracts and code generation -The contract roots are split by boundary: api/core/ contains browser-to-Go operations, api/ml/ contains internal Go-to-ML operations, and api/runner/ contains internal operations between Go and the code runner. The shared Makefile, package.json, and Redocly configuration stay under api/. Python schema tools live in the repository-level scripts/ directory. Each contract is assembled from small source YAML files. +OpenAPI 3.2.0 specifications are split into `routes/` and `components/` under `api/core/`, `api/ml/`, `api/runner/` and `api/labd/`. Bundling combines source YAML files. Compatibility checks cover the features in use, not the entire OpenAPI specification. -The public Go handler is generated by ogen from backend/codegen/ogen.yml and mounted in chi. Orval independently generates the TypeScript client, TanStack Query hooks, Zod schemas, and MSW handlers. The ML Go client is configured at backend/codegen/ogen-ml.yml and generated into backend/internal/adapter/secondary/ml/api/, and the code runner Go client is configured at backend/codegen/ogen-code-runner.yml and generated into backend/internal/adapter/secondary/code_runner/api/. datamodel-code-generator produces Pydantic v2 models from the same ML bundle in ml/src/lincodex_ml/api/models.py; the health/readiness handlers use these models. Python generator settings live in ml/codegen/pyproject.toml, while dependencies remain in ml/pyproject.toml. Backend sqlc configuration is backend/codegen/sqlc.yml and its generated SQL adapter is under backend/internal/adapter/secondary/postgres/sqlc/. Frontend configuration is frontend/codegen/orval.config.ts. There are three codegen directories: backend/codegen/, frontend/codegen/, and ml/codegen/. Configuration belongs to the service that uses the generated code. +- ogen generates Go servers and internal clients; chi mounts the public server under `/api/v1`. +- Orval generates the frontend client, TanStack Query hooks, Zod schemas and MSW handlers under `frontend/src/shared/api/`. +- datamodel-code-generator produces the ML Pydantic models. +- sqlc generates code from SQL under `adapter/secondary/postgres/sqlc/`; mockery generates selected mocks. +- Generator configuration belongs to the component that consumes its output. -OpenAPI 3.2.0 is the target version. Verify the subset used here across bundling and lint, ogen, the chi adapter, the API runtime path, Orval, Python Pydantic models, and documentation. A parser version or one fixture does not prove support for every OpenAPI 3.2.0 feature. +From the root, run `make generate`, then `make check-generated`. Change source contracts together with their consumers; never edit generated files manually. An operation in a contract is not proof of implementation: unconnected operations return 501. -The public API prefix /api/v1 is applied once. The internal /metrics endpoint remains separate. Health operations use names ending in z: healthz and readyz. Generated types and request validation do not implement ownership checks, company membership, consent, or valid product state transitions. +## Storage and background work -Generate bundles from contract sources, then regenerate each Go, TypeScript, and Python consumer through its Make target. A contract change includes generation and drift checks for every consumer. Never edit generated files by hand. +PostgreSQL owns business state, server sessions, consent history, policy versions, jobs and the outbox. Goose applies embedded migrations under a lock before listeners open; a failure stops startup. Startup migrations require DDL privileges for the configured database role. -## Service and data boundaries +Redis provides caching and technical limits, not a queue or a source of business permissions. Core Compose does not persist its data. Losing Redis must not restore revoked access; an unavailable limiter refuses the protected operation. -The planned backend boundaries are: - -- Primary adapters receive HTTP requests and translate them into inbound ports. -- Usecases implement application flows and depend on domain rules and ports. -- Secondary adapters implement storage, ML, email, and file operations. -- Bootstrap wires implementations and controls process startup and shutdown. -- Product rules stay in domain and usecase code, away from chi handlers, workers, SQL, and ML. - -Shared Go configuration belongs in backend/config/ outside internal. wahrwelt-kit logkit 0.6.0, httpkit 0.7.0, and cachekit 0.7.0 currently provide technical functions. Metrics use bounded custom collector/middleware code, and pgxpool collection must not block startup. pgkit and httpkit/metrics are not currently used. Technical libraries do not own product rules. Do not add unselected JWT or WebSocket dependencies for hypothetical features. - -PostgreSQL with pgx, sqlc, and goose is the database stack. Developers own SQL; sqlc generates typed adapters. goose manages versioned migrations: the SQL files are embedded in the binary, and the backend applies them at startup under a PostgreSQL advisory lock before it opens its listeners. wire provides compile-time dependency construction in bootstrap, with no runtime DI container. API and worker share the database pool in the planned single-process deployment. - -Redis is part of the core Compose project and connects through `backend/internal/adapter/secondary/redis/` to the outbound cache port. The adapter provides Get/Set/Del with TTL; bootstrap manages client construction and cleanup. The internal /readyz requires PostgreSQL, Redis, and the SeaweedFS bucket to be available. The cache is not a source of truth: future consumers must tolerate key eviction and Redis restarts. Profile, search, resume, and other product caching rules are not implemented yet. - -SeaweedFS runs as a separate server in the core Compose project. `backend/internal/adapter/secondary/seaweedfs/` implements the outbound `ObjectStorage` port through AWS SDK for Go v2: streaming Put/Get and object deletion. SDK and S3 types remain inside the adapter. Bootstrap creates the client; readiness checks the bucket through HeadBucket. Storage stays private to the Docker network; Nginx does not serve its files directly. The shared file layer and the access controls of the SeaweedFS container are described in [Private file storage](#private-file-storage). Resume uploads, authorization, product content rules, and PDF delivery remain future product workflows. The single-node Compose setup persists data and metadata in a volume but provides no HA or off-host backup. - -The MVP does not add a separate vector database, Kubernetes, or a search microservice. Apache Kafka in KRaft mode with a transactional outbox is the selected event broker; the core Compose project runs one internal Kafka node, the `outbox_events` table has its transactional writer, and the [outbox relay](#outbox-relay) publishes committed events to Kafka. The [event consumer](#event-consumers) runtime applies events idempotently; two product consumers are registered, `notification_delivery` for mail deliveries and `notification_inbox` for the [internal notifications](#internal-notifications). Redis is not used as a queue. Initial search uses PostgreSQL filters and full-text search over an allowed projection. Consider pgvector only if evaluation shows embeddings help. - -### HTTP 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. Registration, resend, and confirmation use client-address limits (see Registration, email verification, and resend); the router mounts `ClientIP`. +Product policy versions hold deadlines, quotas, assessment and matching rules. Published versions are immutable; attempts pin their versions while access always checks current permissions. Initial seeding supplies a demonstration policy, not a configured full product. ### Private file storage -`backend/internal/usecase/files/` is the shared private file layer over the `ObjectStorage` port. It holds technical rules only. A feature package (resume upload, import, PDF generation, document jobs, exports) defines a `Policy` with a namespace, a size limit in bytes, and exact media types, and owns every product rule: who may read or delete a file, page counts, content inspection, parsing, and retention. The layer is not wired into bootstrap until the first such feature uses it. Namespaces are declared in one place, `namespace.go`, and `NewPolicy` accepts no other value, so two features cannot share a namespace by accident. +The SeaweedFS secondary adapter uses AWS SDK for Go v2 for S3. It can read, write and delete objects; user-facing resume import and delivery are not connected yet. -- 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 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. +Only backend and Prometheus join the `storage` network. S3 keys remain on the server, and Nginx does not expose objects directly. Some internal SeaweedFS interfaces do not enforce S3 authentication, so the network remains the primary boundary. One volume provides neither HA nor an external backup. -SeaweedFS access. The primary control is the network: SeaweedFS joins only the internal `storage` Compose network, which the backend and the monitoring Prometheus (for the metrics on port 9327) also join. The frontend, PostgreSQL, Redis, Kafka, and other containers cannot resolve or reach it. This matters because `mini` serves much more than S3. The S3 gateway requires SigV4 credentials: the container's `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` create its only identity, `-s3.iam=false` removes only the IAM management API, and Compose refuses empty credentials because SeaweedFS without any identity accepts anonymous S3 requests. The other listeners do not use S3 credentials: the filer (8888), master (9333), and volume (9340) HTTP APIs; unauthenticated gRPC on 18888, 19333, 19340, and 18333 with server reflection; and an admin server on 23646 with worker gRPC on 33646 that `-admin.ui=false` does not stop and that `mini` cannot disable. Defense in depth inside the storage network: each start sets fresh random JWT signing keys for the filer and volume HTTP APIs, and `-ip=127.0.0.1` with `-whiteList=127.0.0.1,@` limits master and volume HTTP to callers inside the container. The upstream filer ignores its IP whitelist, so the JWT is its only HTTP control. +### Events, jobs and mail -Remaining risk, limited to members of the storage network, which today means the backend (and Prometheus): they can reach the unauthenticated gRPC ports 19333, 18888, and 18333 and the admin ports 23646 and 33646. Master gRPC `Assign` returns a file ID with a signed volume write token, filer gRPC `ListEntries` returns object metadata, and entry changes through filer gRPC should be treated as possible. Volume gRPC 19340 refuses such callers. Integration tests verify that a volume write with a token from `Assign` is refused from outside the container (HTTP 401, whitelist) and that a volume read without a token is refused; this was not verified for the admin and worker ports. Low-priority disclosure inside the same network: the master UI and `/cluster/status` and the volume `/status` reveal topology and disk usage. A compromised backend already holds the S3 credentials, so these paths add little for it; any new member of the storage network widens the risk. gRPC mutual TLS would close the gRPC paths and is not configured. +1. A usecase writes its state change and outbox event in one PostgreSQL transaction. +2. The relay publishes to Kafka and marks acknowledged records. At-least-once delivery permits duplicates. +3. Consumers apply events idempotently; retries and failures must not create a second product action. +4. Scheduled jobs use leases, delayed retries and persisted state. Network calls stay outside user HTTP transactions. -### Transactional outbox +Mail uses delivery records and separate sender loops. `resend` and `disabled` are connected; SMTP is not implemented. Service mail retains reserved quota, and notifications recheck recipient rights before sending. An unknown sending outcome must be accounted for instead of blindly retried. The inbox is populated separately from the invitation-delivered event. -Implemented: migration `backend/db/migrations/00001_create_outbox_events.sql` creates `outbox_events`. Columns: - -- `position`: a bigint identity, unique and monotonic in insertion order; the relay scans by it. -- `event_id`: uuid primary key, a UUIDv7 generated in Go. -- `event_type`: a lowercase dotted name of at most 128 bytes. -- `schema_version`: an integer above zero. -- `aggregate_type`: snake_case, at most 64 bytes. -- `aggregate_id`: a uuid. -- `aggregate_version`: a bigint above zero. -- `payload`: a jsonb object. -- `occurred_at`: `clock_timestamp()` at insert. It is informational only and does not define order. -- `published_at`: null until the relay publishes the row. - -A unique key on aggregate type, aggregate ID, aggregate version, and event type rejects a second event of the same type for the same aggregate version. A partial index on `position` where `published_at` is null serves the relay scan. CHECK constraints repeat the domain rules for versions, names, and the object payload as a backstop. The payload size limit lives only in Go, because the jsonb text and binary sizes differ from the compact input and a database length check could reject an event the domain accepted. - -A usecase writes through outbound ports. `Transactor.WithinTransaction(ctx, fn)` opens one READ COMMITTED transaction and passes a `UnitOfWork`; every repository it returns, including `Outbox().Append(ctx, events...)`, uses that transaction. The transaction commits when fn returns nil and rolls back when fn returns an error, panics, or its context is canceled. Calling `WithinTransaction` again with the callback context returns `outbound.ErrNestedTransaction` instead of opening a second connection. A conflict on the event ID or the unique key returns an error that wraps `outbound.ErrOutboxEventConflict` and names the constraint. A network error during commit leaves the outcome unknown, so callers that retry must be idempotent. - -The outbox uniqueness rule is a backstop, not concurrency control. Aggregate updates still check the expected version (`UPDATE ... WHERE version = $n`), so a stale writer fails before it records an event. - -`domain.NewDomainEvent` validates the event. The compact JSON payload is limited to 16 KiB and 32 nesting levels; numbers must fit a float64; NUL characters are rejected because jsonb cannot store them. jsonb normalizes the stored payload (key order, whitespace, duplicate keys), so consumers compare JSON values rather than bytes. Payloads carry identifiers and minimal facts only, never contact data, tokens, passwords, or resume and document contents. - -The relay that publishes these rows is described in [Outbox relay](#outbox-relay). Idempotent consumers are described in [Event consumers](#event-consumers). Still planned: retry bookkeeping columns (attempt count and last error) and retention of published rows. Bootstrap does not wire the transactor yet because no product usecase uses it; the first business transaction wires it together with a shared pool. - -### 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: - -1. `SetRelayTransactionTimeouts` sets `statement_timeout` to `RELAY_STATEMENT_TIMEOUT` and `idle_in_transaction_session_timeout` to `RELAY_PRODUCE_TIMEOUT + RELAY_STATEMENT_TIMEOUT` for this transaction only (`SET LOCAL` through `set_config`). The pass context already cancels a slow pass of a live process; these server-side limits also hold when the process freezes or loses the network without closing the connection, so the server ends the transaction and releases its row locks instead of waiting for TCP keepalive. -2. `LockPendingOutboxEvents` selects rows with `published_at IS NULL` in `position` order, at most `RELAY_BATCH_SIZE`, with `FOR UPDATE OF pending SKIP LOCKED`. A row qualifies only when it is the earliest unpublished event of its aggregate (lowest `aggregate_version`, then `position`). There is no `position` or `occurred_at` watermark; every pass scans the unpublished rows again. -3. The relay publishes the batch and waits for the broker acknowledgements, at most `RELAY_PRODUCE_TIMEOUT`. -4. `MarkOutboxEventsPublished` sets `published_at` for exactly the acknowledged event IDs, and the transaction commits. - -Several relays, for example several backend instances, can run against one database. SKIP LOCKED lets them take different rows without waiting. Plain SKIP LOCKED would let a second relay skip a locked version 1 and publish version 2 first; the earliest-event rule prevents that, because version 2 does not qualify while version 1 is unpublished, whether another relay holds it, a failed pass left it pending, or a pass rolled back. The rule relies on aggregate writers checking the expected version: version 2 then commits only after version 1, so a statement that sees version 2 also sees version 1. Migration `00004_add_outbox_relay_index.sql` adds the partial index `(aggregate_type, aggregate_id, aggregate_version, position) WHERE published_at IS NULL` for this check. Trade-off: a pass publishes at most one event per aggregate, so a burst of N events of one aggregate needs N passes. A pass that found events starts the next one immediately, and different aggregates share a batch and spread across relays. - -Selection cost. The plan is a nested-loop anti join: an index scan of `outbox_events_unpublished_idx` in `position` order, one probe of `outbox_events_unpublished_aggregate_idx` per scanned row, and LIMIT on top, with no sort over the backlog; the generic plan of the prepared statement is the same. A pass reads rows until it has found `RELAY_BATCH_SIZE` aggregate heads, so it reads every non-head row in front of them. Measured with `EXPLAIN ANALYZE` on PostgreSQL in a scratch container with 100,000 pending rows and a batch of 100: 0.2 ms and 100 rows read when versions of 1,000 aggregates interleave; 16 ms and 9,901 rows read when each aggregate's 100 versions are contiguous; 225 ms and about 50,000 rows read when one aggregate has 50,000 pending versions ahead of 1,000 other aggregates. In the last case the hot aggregate drains one version per pass and every pass reads its remaining versions again, so draining k pending versions of one aggregate costs O(k²) row reads. Product aggregates change a few times per business action, so k stays small; a large k appears only when a writer emits many versions of one aggregate during a long Kafka outage. Publishing several consecutive versions of an aggregate whose head a pass has locked would remove that cost and is a possible later change. - -Kafka record: - -- Topic: `KAFKA_EVENTS_TOPIC`, `lincodex.domain.events` by default. All events go to one topic; consumers filter by `event_type`. One topic is enough while consumers are few, and per-aggregate order needs only the key. -- Key: `:`. The default franz-go partitioner hashes the key, so all events of an aggregate land in one partition in publication order. -- Value: a compact JSON envelope with `envelope_version` (currently 1; changes only with the envelope fields), `event_id`, `event_type`, `schema_version` (the payload layout version of that event type), `aggregate_type`, `aggregate_id`, `aggregate_version`, `occurred_at` (RFC 3339 in UTC, informational), and `payload` (the stored jsonb object, so key order can differ from what the writer appended). -- Headers: `event_id`, `event_type`, `schema_version`, so a consumer can deduplicate and route without decoding the value. - -The producer uses acks from all in-sync replicas and idempotent writes (the franz-go default). By default franz-go cannot fail an in-flight idempotent record until the broker answers, so behind a frozen broker the record and every later record of its partition would wait indefinitely. The relay enables `AllowIdempotentProduceCancellation`, which lets the delivery timeout and the pass deadline fail such a record, and `Publish` stops waiting at the deadline in any case. The client retries a record at most five times within one publish; later attempts belong to the next pass. Kafka does not create topics on demand: before its first pass the relay calls `Prepare`, which creates `KAFKA_EVENTS_TOPIC` through `kadm` with `KAFKA_EVENTS_TOPIC_PARTITIONS`, `KAFKA_EVENTS_TOPIC_REPLICATION_FACTOR` (-1 by default, the broker's `default.replication.factor`), and, when set, `min.insync.replicas` from `KAFKA_EVENTS_TOPIC_MIN_INSYNC_REPLICAS` (otherwise the broker default). It accepts an existing topic without changing it and logs one warning when that topic has another partition count or, with an explicit replication factor, another replication factor. A failed `Prepare` does not block startup: the relay retries it with backoff and events stay pending. When a publish reports an unknown topic, for example after the topic was deleted, the relay calls `Prepare` again before its next pass. With acks from all in-sync replicas, a write is durable only on `min.insync.replicas` brokers; the production requirement is in [DEPLOY.md](DEPLOY.md#outbox-relay). With `KAFKA_PROVISION_TOPICS=false` the topic is managed outside the backend. Adding partitions later moves keys to other partitions, so per-aggregate order is not guaranteed across that change. - -Failure semantics: - -- Kafka unavailable: the publish fails within `RELAY_PRODUCE_TIMEOUT`, nothing is marked, and the rows stay pending. The relay logs a warning with counts and the error (event IDs and broker errors, never payloads), waits a backoff, and retries indefinitely. The backoff starts at `RELAY_BACKOFF_INITIAL`, doubles with every consecutive failure up to `RELAY_BACKOFF_MAX`, and waits half the current value plus a random share of the other half. Business transactions write only to PostgreSQL, so an outage never rolls back a saved business action. -- Partial acknowledgement: only acknowledged events are marked; the rest are retried on later passes. Because a pass holds at most one event per aggregate, a failed event never lets a later version of its aggregate through. A pass that published at least one event resets the backoff and is followed by the next pass at once, so a failing event does not slow down the others; the backoff grows only across passes that published nothing. -- A failure after publish and before commit, including a crash or a lost database connection: the rows stay unpublished and a later pass publishes them again with the same `event_id`. A record whose publish timed out can also reach the broker later. Delivery is at least once: consumers must deduplicate by `event_id` and ignore an `aggregate_version` they already applied, because a late duplicate of an earlier version can follow a later version. -- Shutdown: when the process receives SIGTERM, the relay starts no new pass. A pass in progress has `SHUTDOWN_TIMEOUT` to finish and commit; after that it is canceled and its transaction rolls back. An unacknowledged event is never marked. Bootstrap closes the producer and the relay's pool only after the relay stopped. -- The transaction stays open during the publish, holding row locks on at most `RELAY_BATCH_SIZE` outbox rows and one connection for at most `RELAY_PRODUCE_TIMEOUT`. Business writes only insert new rows and are not blocked; the bound also limits how long the open transaction delays vacuum. A smaller batch or timeout shortens it. -- An event the broker rejects every time (a poison event; not expected, because the payload is at most 16 KiB and the topic is provisioned) blocks its own aggregate. While a pass still publishes other events, the relay keeps going at full speed. Because `ORDER BY position` returns the oldest heads first, every pass claims the poison heads again; when `RELAY_BATCH_SIZE` or more aggregate heads are poison, they fill the whole batch, no pass publishes anything, and the relay stalls at one pass per `RELAY_BACKOFF_MAX` while the backlog grows. An operator sees `failed` in `lincodex_outbox_relay_events_total` rising while `published` stays flat, `lincodex_outbox_relay_oldest_pending_age_seconds` growing, and warnings with the event IDs of the batch. The usual causes are on the Kafka side (the topic, its ACLs, or `min.insync.replicas` above the live replicas); after that is fixed, the next pass publishes everything. A raised `RELAY_BATCH_SIZE` lets other aggregates through meanwhile. There is no dead-letter path: an event that can never be published needs a decision by the owners of its consumers, and marking it published by hand skips it for every consumer. - -The metric `lincodex_outbox_relay_events_total{outcome}` counts published and failed events; a pending event is counted as failed on every attempt. The gauges `lincodex_outbox_relay_pending_events` and `lincodex_outbox_relay_oldest_pending_age_seconds` show the unpublished events and the age of the earliest one by `position`, measured by the database clock. The relay reads them with `GetOutboxBacklog`, which uses the partial index, at most once every 15 seconds, also while it retries `Prepare`, so a busy relay does not count the outbox on every pass. Every backend instance reports the same database-wide values; aggregate them with `max`. `/readyz` does not check Kafka, so a Kafka outage does not take the API out of service. - -### 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. Two product handlers are registered: `eventHandlers()` in `backend/internal/bootstrap/consumers.go` returns the mail delivery handler `notification_delivery` described in [Mail deliveries](#mail-deliveries) and the inbox handler `notification_inbox` described in [Internal notifications](#internal-notifications), so a backend with `CONSUMER_ENABLED` and `DATABASE_URL` runs one consumer in each of the groups `.notification_delivery` and `.notification_inbox`. 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: - -- `ConsumerName()`: a snake_case name of at most 64 characters. It names the Kafka consumer group `.` and scopes deduplication, so renaming a consumer makes it process every retained event again. -- `Handles(eventType)`: events of other types are counted as `ignored` and committed without a transaction. -- `Handle(ctx, unit, event)`: receives the decoded envelope and an `outbound.UnitOfWork` bound to the transaction that holds the dedup marker. The effect must use only that unit. An error that wraps `inbound.ErrEventRejected` is final; any other error is retried. Errors must not quote the payload or personal data, because their text is logged and stored with a dead letter. - -Deduplication uses `event_id` only. Order by `aggregate_version` stays with the handler: a replayed dead letter can arrive after a later version of its aggregate, so a handler that keeps aggregate state ignores a version it has already passed. - -One record is processed as follows: - -1. The Kafka adapter decodes the envelope. It requires `envelope_version` 1, a non-nil `event_id`, the domain rules of `domain.NewDomainEvent` for type, schema version, aggregate type, ID, and version, a non-zero `occurred_at`, a JSON object `payload`, and an `event_id` header, when present, equal to the envelope field. A record that breaks a rule is an invalid record; the handler never sees it. The error names the broken rule and never quotes the value. -2. One READ COMMITTED transaction sets `statement_timeout` and `idle_in_transaction_session_timeout` to `CONSUMER_HANDLER_TIMEOUT` for this transaction only, runs `INSERT INTO consumer_processed_events (consumer_name, event_id) ... ON CONFLICT DO NOTHING`, and checks the row count. Zero rows means the event was applied before: the transaction rolls back and the record is a `duplicate`. One row means the handler runs in the same transaction, and the effect commits together with the marker. -3. The offset is committed only after that commit, or after the dead letter row is stored. - -Why `ON CONFLICT DO NOTHING` in the same transaction as the effect. The marker is inserted before the effect, so the effect runs only while its transaction holds the uncommitted marker. A concurrent delivery of the same event, from another instance or after a rebalance, waits on that unique key until the first transaction ends: after a commit its insert affects zero rows and it skips the effect; after a rollback its insert succeeds and it applies the event itself. The effect therefore never runs twice or in parallel, and the outcome does not depend on timing. A plain `INSERT` that fails on the unique key waits the same way, but a duplicate then aborts the transaction with SQLSTATE 23505, puts an expected case into the PostgreSQL error log, and drives control flow by error. Checking with a `SELECT` before the insert leaves a race window under READ COMMITTED. The server-side timeouts end the transaction of a frozen process, so its marker cannot block a duplicate indefinitely. - -Offsets and partitions. Each consumer is one member of its group with autocommit off and franz-go `BlockRebalanceOnPoll`. It polls at most `CONSUMER_MAX_POLL_RECORDS` records and processes them one at a time in poll order, which keeps the order within every partition. After the batch it commits, for each partition, the position after the last finished record (with its leader epoch), and only then allows a rebalance. Because rebalances wait for that point, a commit never lands on a partition the member no longer owns. A failed commit is logged; the position is retried with the next commit and when the partition is revoked, and dropped when the partition is lost, in which case the next owner receives the records again and the markers turn them into duplicates. A new group starts at the earliest retained record, so a new consumer never skips an event. The adapter refuses a commit whose finished records are not, per partition, the first records of the last poll without a gap, so a commit can never move past an unfinished record. - -Rebalance budget. A batch holds rebalancing while it runs. If it takes longer than the rebalance timeout, the broker removes the member, its commit fails, and the new owner reprocesses from the last committed offset; deduplication makes that harmless, but the work is repeated. The timeout is set explicitly from `CONSUMER_REBALANCE_TIMEOUT` (60 seconds by default), and configuration refuses to start when the slowest record does not fit in it with a 5-second margin. The slowest record without a database outage is `CONSUMER_MAX_ATTEMPTS` handler attempts, the longest backoff before each retry, one dead letter write (each bounded by `CONSUMER_HANDLER_TIMEOUT`), and one offset commit (`CONSUMER_COMMIT_TIMEOUT`): 42.5 seconds with the defaults. A record is the unit because the consumer commits the finished prefix of a batch right after every record that needed a retry or a dead letter, so a member removed during the next slow record does not make its successor repeat the earlier ones. A database outage is not part of the budget: store failures are retried without a bound, and the removal they can cause only repeats work. The alternative, stopping a batch early when franz-go reports a blocked rebalance (`OnPartitionsCallbackBlocked`), would leave polled but unprocessed records behind on the partitions the member keeps; they would be skipped unless the fetch position were rewound with `SetOffsets`, which franz-go documents as prone to odd interactions inside a poll loop. The static budget is simpler and testable. - -Failures, retries, and dead letters: - -- Handler error: up to `CONSUMER_MAX_ATTEMPTS` attempts with the same backoff as the relay: the wait starts at `CONSUMER_BACKOFF_INITIAL`, doubles up to `CONSUMER_BACKOFF_MAX`, and is half the current value plus a random share of the other half. Each attempt is bounded by `CONSUMER_HANDLER_TIMEOUT` and rolls back its effect and marker. When the attempts run out, the record becomes a dead letter of class `retries_exhausted`. `inbound.ErrEventRejected` gives `handler_rejected` after one attempt. A handler panic is recovered, the transaction rolls back, the stack is logged without the panic value, and the record becomes `handler_panic`, so one event cannot crash the process on every delivery. -- Invalid record: a dead letter of class `invalid_record` with zero attempts. -- Refused commit: when the handler returns nil but PostgreSQL refuses the commit, the event is at fault, not the database. `pgx.ErrTxCommitRollback` (the handler ignored a failed statement, so the transaction was aborted) and SQLSTATE class 23 (a deferred integrity constraint) match `outbound.ErrEventEffectRejected`; class 40 (serialization failure or deadlock) matches `outbound.ErrTransactionConflict`. Both count as a handler attempt and are retried with backoff, so a deterministic refusal ends in `retries_exhausted` instead of a retry loop without end. Class 40 is transient by nature and usually succeeds on the next attempt; it still uses up an attempt so that a handler that deadlocks every time cannot retry forever. The same applies to a panic in `Handles`, which gives `handler_panic` without an attempt. -- Store failure (begin, marker, a commit lost in transport, or the dead letter write): it does not use up the handler's attempts, because the event is not at fault. The consumer retries with the same backoff until the database answers or shutdown begins, and never dead-letters a record because the database was down. The offset stays uncommitted meanwhile, so a database outage stops the partition without a hot loop and loses nothing. -- After the dead letter row exists, the offset is committed and the partition continues with the next record. A dead letter writes no marker, so a later replay of the event is applied. - -`consumer_dead_letters` stores the consumer name, topic, partition, offset, `event_id` (from the envelope, or from the `event_id` header of an invalid record; NULL when neither is a UUID), `event_type` (NULL for an invalid record), the class, a reason of at most 256 printable characters, the attempt count, the value size, its SHA-256, and the time. A unique key on consumer, topic, partition, offset, and value digest keeps one row per record: when the same record fails again, after a crash before its offset commit or a rewind of the group, the row gets the new class, reason, attempt count, and time. The digest is part of the key because a topic that was deleted and created again reuses offsets; a different value at a reused position is another record and keeps its own row instead of being dropped. Handler errors reach the reason and the logs only after the store replaced the text of any PostgreSQL error in them with its SQLSTATE and constraint, because a PostgreSQL message can quote row values. The record value itself is not stored. A valid event is still in `outbox_events` under its `event_id`, which is also the replay source, so a second copy would only duplicate data that events may carry later and that a dead letter table would keep without a retention rule. An invalid record did not come from the relay; while the topic retains it, an operator can read it by topic, partition, and offset, and the SHA-256 confirms it is the same value. The replay procedure is in [DEPLOY.md](DEPLOY.md#dead-letters-and-replay). - -Lifecycle. Startup runs the migrations, then wire builds the consumers: one PostgreSQL pool shared by all of them with one connection per consumer (a consumer holds one transaction at a time and writes a dead letter only after it ended) and one franz-go client per consumer. Nothing connects at that point, so an unavailable Kafka or database does not block startup. The application opens its listeners, starts the relay and every consumer next to the HTTP servers, and serves. On SIGTERM the HTTP servers, the relay, and the consumers stop at the same time; none depends on another. A consumer starts no new record and abandons any backoff wait at once. An attempt in progress has `CONSUMER_SHUTDOWN_GRACE` to commit; after that it is canceled and its transaction rolls back. Finished records are committed within `CONSUMER_COMMIT_TIMEOUT`; unfinished records are never committed, so the next member of the group processes them. Bootstrap waits for all workers before the cleanup, in which the members leave their groups in parallel, each within `CONSUMER_COMMIT_TIMEOUT` plus 2 seconds (the final revocation commits only finished positions), and then the pool closes. The whole shutdown budget is in [DEPLOY.md](DEPLOY.md#event-consumers). - -Trade-offs: one consumer processes one record at a time on one connection. Parallel processing comes from more backend instances in the same group, up to the partition count of the topic (3 by default). Markers are kept indefinitely; their retention is planned and must outlast the replay horizon, because deleting a marker lets a replay of that event apply again. The retention task also adds the index on `processed_at` that it needs; until then every applied event would pay for an index that nothing reads. - -The metric `lincodex_event_consumer_records_total{consumer,outcome}` counts finished records by `applied`, `duplicate`, `ignored`, or `dead_lettered`; `lincodex_event_consumer_failures_total{consumer,stage}` counts every failed operation, including the last handler attempt before a dead letter, by `handler`, `store`, `poll` (a failed poll of the event bus), or `commit` (a failed offset commit). The consumer label comes from the registered names in code, so the series are bounded. Every series of a consumer exists from its start at zero. Logs carry the consumer, group, topic, partition, offset, event ID, and event type, never the value or payload. - -### 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. Two product handlers are registered in `jobHandlers()` (`backend/internal/bootstrap/jobs.go`): `assessment.signal_review`, which computes the [assessment review band](#assessment-signals-and-the-review-band), and `invitation.response_deadline`, which moves an invitation to `expired` when its response deadline passes ([Pending limit, cooldown, and expiry](#pending-limit-cooldown-and-expiry)). The tests also use a test-only kind. 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 `:`. - -States. `due_at` is the deadline the job stands for and never changes; `available_at` is when a worker may claim the job next, `due_at` at first and the retry time after a failed attempt. `pending` waits for `available_at`; `failed` waits for its retry after a failed attempt; `running` is claimed under a lease; `done`, `dead`, and `cancelled` are final. Finished rows are kept, so their key stays reserved; their retention is not implemented yet. - -Claim and lease. The worker claims up to `JOBS_BATCH_SIZE` jobs in one statement: a CTE selects waiting jobs whose `available_at` passed and running jobs whose `lease_expires_at` passed, of the kinds that have a handler in this process, in `available_at` order, with `FOR UPDATE SKIP LOCKED`, and the same statement sets `status = running`, `lease_owner` (a random ID per worker instance), and `lease_expires_at = now + JOBS_LEASE_DURATION`, and counts the attempt. Two partial indexes serve the claim, one on waiting rows and one on running rows; the kind filter applies after the index, so when many waiting jobs belong to kinds that the claiming process has no handler for, an index on `(kind, available_at, id)` is the next step. `now` is passed from the injected application clock; the database clock never decides whether a job is due or a lease expired, so tests move a fake clock instead of waiting days. Jobs of a kind without a handler stay untouched, so an older instance during a rolling deployment leaves them to the instances that have the handler. Right before its handler transaction, each job is started: a separately committed, guarded `UPDATE` renews its lease from now and sets `started_at`, but only while the lease of the claim has not expired. The attempt is counted at the claim, so a job that crashes its process while its handler runs cannot loop forever: when the lease of a started attempt expires on the last allowed attempt, the claim marks the job `dead` with `lease_expired` instead of running it again. A claim whose attempt never started (the worker stopped or was busy before the job's turn) is not the job's fault: the next claim reuses that attempt without counting another one and records no error class. - -Run and completion. Each job runs in its own READ COMMITTED transaction: it sets `statement_timeout` and `idle_in_transaction_session_timeout` to the lease duration, locks the job row with a guard on `status = running`, the lease owner, and the attempt number, calls the handler with an `outbound.UnitOfWork` of the same transaction, marks the job `done` with the same guard, and commits. The handler effect and the completion therefore commit together: for an effect that stays in PostgreSQL a job is applied exactly once even when workers race, restart, or a lease expires. While the handler runs the row is locked, so another worker's claim skips it even after the lease expired by the clock; when the guard fails because the job was canceled or reclaimed, the handler is not called and nothing commits (`lease_lost`). A handler may cancel its own job through the unit, for example an expiry that also cancels the deadline job it stands for: the completion then finds the job `cancelled` in its own transaction, treats it as finished, and commits the effect, and the job stays `cancelled`. Any other change of its own job by the handler rolls back and makes the job `dead` with `completion_conflict`, because it would repeat on every attempt. A handler whose effect leaves the database, such as a call to another service, can repeat after a crash between that call and the commit and must be idempotent itself. The handler context ends with the renewed lease. A handler decides by `job.DueAt`, the deadline the job stands for, which a retry keeps, not by when it happens to run. - -Lock order. The handler holds the job row lock and may then lock product rows. A business transaction that cancels a job should call `Cancel` before it locks those product rows. A candidate's answer does not cancel the response deadline job: the run finds the answered invitation and changes nothing ([Pending limit, cooldown, and expiry](#pending-limit-cooldown-and-expiry)). `Cancel` waits for a handler transaction in progress: after its commit the job is done and `Cancel` reports `false`, so the caller sees the finished job; otherwise the job is canceled and the worker finds its lease gone. The opposite order can deadlock, which PostgreSQL resolves by aborting one side with `ErrTransactionConflict`; the job side counts a failed attempt and retries. - -Failures. A failed attempt rolls back its effect; a second statement, guarded the same way, records it. A handler error, a lease timeout, a deadlock or serialization failure (`conflict`), or a commit that PostgreSQL refuses (`effect_rejected`, for a handler that ignored a failed statement or a deferred constraint) moves the job to `failed` with `available_at = now + backoff`, where the backoff is the shared `worker/retry` delay from `JOBS_BACKOFF_INITIAL`, doubling up to `JOBS_BACKOFF_MAX`, with jitter. `inbound.ErrJobRejected`, a handler panic, and `completion_conflict` are final, also when they happen during shutdown. After the last allowed attempt (the job's own limit or `JOBS_MAX_ATTEMPTS`) the job is `dead`: it is logged at error level and counted as `dead`, and it needs an operator. `last_error_class` stores only a bounded class; a sanitized reason appears only in the log. A database failure outside the handler is not the job's fault: the worker releases its unfinished jobs without counting the attempt and backs off before the next claim, so an outage causes no hot loop. When the failure record itself cannot be written, the job keeps its started lease; a later claim then counts it as `lease_expired`, which on the last attempt makes it dead. - -Shutdown. When the context ends, the worker claims nothing more. A job in progress has `JOBS_SHUTDOWN_GRACE` to commit; after that it is canceled and its transaction rolls back, so an unfinished job is never marked done. The worker then releases it, and the claimed jobs of the batch it did not start, explicitly: back to `pending` or `failed`, without counting the attempt, guarded by owner and attempt so a job that another worker reclaimed or a caller canceled meanwhile is left alone. Release makes the jobs claimable at once by another instance instead of after up to one lease, which matters during a rolling deployment; if the release cannot reach the database, the lease expires and a later claim takes the jobs, so the release is only a shortcut and never needed for correctness. Bootstrap starts the worker next to the HTTP servers, the relay, and the consumers, and runs the cleanup that closes its pool only after it stopped. - -Trade-offs: one worker runs one job at a time on a pool of two connections; more throughput comes from more backend instances. The jobs of one batch are claimed together but each renews its lease when it starts, so a slow job ahead costs the next ones only waiting time: a job whose claim lease expired before its turn is not started and is released with its attempt intact, or, when another worker already took it over, that worker runs it on the same attempt. Due times are honored with a delay of up to `JOBS_POLL_INTERVAL` plus the batch ahead of it. There is no separate `cmd/worker`: the worker is a goroutine of the backend process, and migrations run as before. - -Metrics: `lincodex_scheduled_jobs_total{kind,outcome}` counts claimed jobs by `done`, `retry`, `dead`, `lease_lost`, or `released`; the kind label comes from the registered handlers, and every series exists at zero from the start. `lincodex_scheduled_jobs_due`, `lincodex_scheduled_jobs_oldest_due_age_seconds`, and `lincodex_scheduled_jobs_dead` describe all kinds at the last backlog read, at most every 15 seconds. Logs carry the job ID, kind, attempt, and error class, never the key or payload. - -### 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/`, outside the MVP); until it exists, `smtp` fails startup after its settings are validated. The callers are the sending workers: the service worker for identity mail (see [Sending service mail](#sending-service-mail)) and the notification worker (see [Sending product notifications](#sending-product-notifications)). 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: - -- `accepted`: the provider accepted the request and returned `ProviderMessageID`. This is not delivery or reading. -- `rejected`: the provider did not take the message. Either it answered and refused, or the transport failed before the request was completely written (DNS, connect, or TLS), so no complete request reached the provider; the second case is always `temporary`, and a retry cannot duplicate the message. `Rejection` is `permanent`, `invalid_request`, `rate_limited`, `quota_exhausted`, or `temporary`. -- `unknown`: the request may have reached the provider but no conclusive answer came back (`delivery_uncertain`), for example a timeout, a connection lost after the request was written, or a provider error raised while handling it. It is not "not sent": a retry reuses the idempotency key and the same content. Resend keeps an idempotency key for 24 hours. The worker stops automatic retries at 23 hours, leaving a one-hour safety margin; after that an operator must decide whether to retry because the old key may no longer prevent a duplicate. - -`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. The transport makes one request; the worker owns retries, backoff, and outcome storage. 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. - -| Resend answer | Result | -| --- | --- | -| 2xx with an `id` of up to 128 letters, digits, `-`, or `_` | `accepted` with `ProviderMessageID` | -| 2xx without a valid `id`, truncated, or over 64 KiB | `unknown`: the request may have been accepted | -| 3xx, not followed | `rejected`, `invalid_request`: the API documents no redirect, and a repeat gets the same one | -| 403 `validation_error` (unverified sender domain: without one Resend sends only testing emails to the account's own address) | `rejected`, `permanent` | -| Other 4xx: 400, 422, key and permission errors (401, 403), 404, 405 | `rejected`, `invalid_request` | -| 408; 409 `resource_locked` | `rejected`, `temporary`, `RetryAfter` from `Retry-After` | -| 409 `concurrent_idempotent_requests` | `unknown`: another request with the same key is in progress and may be accepted; retry later with the same key | -| 409 `invalid_idempotent_request` | `unknown`: the key was used with another body, so an earlier request may have been accepted; repeating cannot succeed, so the delivery layer stops and escalates | -| 409 without a known name | `unknown` | -| 429 `rate_limit_exceeded` or unnamed | `rejected`, `rate_limited`, `RetryAfter` from `Retry-After` (seconds or a future HTTP date), otherwise from `ratelimit-reset` | -| 429 `daily_quota_exceeded` | `rejected`, `quota_exhausted`, `QuotaPeriod` `day`, `RetryAfter` until the next 00:00 UTC | -| 429 `monthly_quota_exceeded` | `rejected`, `quota_exhausted`, `QuotaPeriod` `month`, no `RetryAfter`: the reset follows the billing cycle | -| 503 `service_unavailable` | `rejected`, `temporary`, `RetryAfter` from `Retry-After` | -| Other 5xx, including 500 `application_error` and `internal_server_error`, a truncated body, or a proxy or gateway answer | `unknown`: the API may have accepted the message before it failed | -| No answer after the request was written: timeout, reset, or closed connection | `unknown` | -| 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, the sending worker applies the minimum schedule described in [Sending service mail](#sending-service-mail), and automatic retries of uncertain sends stop at 23 hours, one hour before Resend's 24-hour key window ends. Waiting for a quota reset is decided by the quota gate described in [Mail quotas](#mail-quotas). - -### Mail deliveries - -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 service-mail worker, bounded retries, the unknown-outcome cutoff, and the audited local operator command, with migrations `00012_add_delivery_sending.sql` and `00017_retry_unknown_mail.sql`; see [Sending service mail](#sending-service-mail). Sending product notifications, with the rights check before each send, is implemented; see [Sending product notifications](#sending-product-notifications). The delivery state gauges are implemented; see [Metrics, telemetry, and alerts](#metrics-telemetry-and-alerts). The invitation send is the first product caller of `MailRequester`. Registration and resend create verification mail through `ServiceMailer`; password reset is not implemented. - -A delivery is the durable state of sending one message to one recipient. A `deliveries` row holds: - -- `id`: the stable ID of the logical request, so a repeated request maps to the same row. The idempotency key sent to the provider with every attempt is `delivery/` (`idempotency_key`, unique); it contains no personal data. -- `source_event_id`: the domain event the delivery was created from, or NULL for a delivery created directly in a business transaction. -- The recipient: `recipient_user_id`, a foreign key to `users` with `ON DELETE CASCADE`, and `recipient_email`, the delivery form of the account address when the delivery was created. -- The content: `kind` (`verification`, `password_reset`, or `notification`), `template_version` (`.v`), `subject`, `text_body`, `html_body`, and `content_sha256` over the version, subject, and both parts, the same digest as the mail templates (`domain.MailContentHash`). -- The provider account: `provider` and `provider_account`, the values of `EMAIL_PROVIDER` and `EMAIL_ACCOUNT` at creation. They are configuration identity, never a credential. -- The attempt state: `status`, `attempt_count`, `next_attempt_at`, `last_attempt_at`, `provider_message_id`, the optimistic `version`, `created_at`, and `updated_at`, all from the application clock. - -Creation path: - -1. A usecase calls `MailRequester.RequestNotification(ctx, unit, request)` inside its own transaction with the recipient account ID and the notification data. The usecase checks the data with the current template, so a bad request fails its own transaction instead of becoming a dead letter, and assigns a UUIDv7 request ID. In the caller's transaction it inserts a `mail_requests` row with that ID, the recipient, the kind, the raw subject, body, and link path, the subject the notice concerns (for an invitation, the invitation and its organization), and the request time, and appends `notification.mail_requested` with schema version 1: aggregate type `mail_request`, aggregate ID equal to the request ID, aggregate version 1, and the payload `{"mail_request_id": , "kind": "notification"}` and nothing else. -2. The relay publishes the event, and the consumer `notification_delivery` applies it in the transaction of its dedup marker. It checks the envelope and that `mail_request_id` equals the aggregate ID, refuses trailing data after the payload object, and locks the request row (`FOR UPDATE`). It reads the account, renders the notification once with the current template version, inserts the delivery under the request ID with `source_event_id` set, and deletes the request row, all in that transaction. -3. A redelivered event is a `duplicate` of the consumer marker. A replay under another consumer name, a replayed dead letter after success, or a concurrent second consumer finds the request row gone (the second consumer waits on its lock) and skips. When an insert finds a delivery under the request ID already, the handler accepts it only for the same recipient and kind, and rejects the event otherwise. -4. Skips: a request that no longer exists, because it was handled or its account was deleted, and a notification to an account whose address is not verified (`email_verified_at` NULL). The unverified case deletes the request; notifications go only to confirmed addresses. Skips are logged at info level with the delivery and event IDs only. An unknown schema version, a payload that breaks the contract, or text that the template refuses is rejected for good and becomes a `handler_rejected` dead letter; storage errors are retried. An account deleted after the handler read it makes the insert fail on the foreign key; the transaction is aborted, so the error is retried, and the retry finds the request deleted with the account and skips. - -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`, which uses `domain.NewDelivery` and `DeliveryRepository.Create` and binds the delivery to the token. Registration and resend create verification mail; password reset is a future flow. - -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. - -Personal data at rest. A delivery row holds the recipient address and the bodies, and a pending `mail_requests` row holds the raw notification text. The body of a token mail holds a live bearer token until it is used, replaced, or expires (at most 7 days by policy), so read access to `deliveries` is access to that account's confirmation or reset link, and database dumps and backups carry it. The consequences: - -- 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 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: - -| Status | Meaning | `next_attempt_at` | -| --- | --- | --- | -| `pending` | Waits for its first attempt, or for a retry after a `temporary` or `rate_limited` rejection | Required: when it is due | -| `accepted` | The provider accepted the message and returned `provider_message_id`: "accepted by the provider". Not delivery to or reading by a person; no status claims that | None; terminal | -| `rejected` | A `permanent` or `invalid_request` rejection; the cause must be fixed | None; terminal | -| `unknown` | The attempt may have reached the provider (`delivery_uncertain`). Never "not sent": an eligible automatic or operator-approved retry uses the pinned key and stored body | Optional; none means operator review is required | -| `cancelled` | The message was deliberately not sent and never will be: the token or the account no longer matches, a notification's rights no longer hold, or the stored message is unsendable. `cancel_reason` says why; no attempt is recorded | None; terminal | -| `waiting_quota` | A provider quota or the local quota is used up | Optional: the expected reset (see [Mail quotas](#mail-quotas)); none when the reset is unknown, for example after a provider quota answer that names neither a window nor a wait, and an operator decides | - -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 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`, `processing_failed`, `rights_revoked`, `recipient_ineligible`, or `source_closed`. 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 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 first provider-call start is recorded by the database clock and is the age source for the automatic cutoff. Operator decisions are kept separately in `delivery_retry_decisions`, including the delivery ID, current attempt count, actor handle, explicit duplicate-risk acknowledgement, whether an expired lease was recovered, and decision time. It has no foreign key, so deleting the account does not erase the audit; row-level UPDATE/DELETE and statement-level TRUNCATE are refused. 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`). 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` 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 workers `ClaimDue` (one statement per lane, selected by `ClaimScope`), `ReleaseClaim`, and `ServiceMailState`. The notification rights reader is `UnitOfWork.NotificationRights()`. Migrations `00044_add_notification_subject.sql` and `00045_send_product_notifications.sql` add the subject columns, the product due index `deliveries_product_due_idx`, and the cancel reasons of the rights checks. Migration `00017_retry_unknown_mail.sql` adds the manual-cycle markers, the append-only decision journal, and `unknown` to the due index predicate. It drops and recreates the partial due index, which takes a table lock while it rebuilds. Rolling this migration back drops the decision journal and its audit data; preserve an export first if rollback is required. - -### Mail quotas - -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. Both lanes count against the quota: a product notification is admitted only while the windows keep the service reserve free (see [Sending product notifications](#sending-product-notifications)). - -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. - -Tables. Neither table has a foreign key to users or deliveries: deleting an account deletes its deliveries and attempts by cascade, but the provider has already counted those messages, so the usage stays. Neither holds personal data; `delivery_id` is an opaque ID. - -- `mail_quota_usage`: one row per provider, provider account, period kind (`day` or `month`), and period start (a UTC date; the first day for a month), with `used_recipients`, `provider_exhausted_at`, and `updated_at`. An account accrues about 400 rows a year. -- `mail_quota_reservations`: a journal with one row per admitted send: the delivery, the account, the day and month windows it was counted in, the recipients, `reserved_at`, `released_at` (set once), and the last `settled_outcome` (`accepted`, `unknown`, `rejected`, or `not_sent`) with `settled_at`. A row without an outcome is a send in flight, or one whose process stopped before settling. A partial index serves the lookup of a delivery's open reservations. There is no retention rule for either table yet; journal rows are needed only within the reuse window and for the audit of a month. - -Lock order. Every write first creates and locks all the usage rows it will touch with one statement, sorted by `(period_kind, period_start)`, and only then updates them or the journal; later `UPDATE` statements find their rows locked already. The order therefore never depends on the query plan. An `UPDATE ... WHERE (day) OR (month)` alone locks rows in scan order, which with a bitmap or sequential scan is heap order, and deadlocked against a reservation that locked the day first; the integration test reproduces that interleaving and checks that it no longer deadlocks. A settlement that releases yesterday's windows and marks today's locks all three rows in the same sorted statement. The guarantee covers the quota rows only: a caller that also locks other rows in the same transaction, such as the delivery, keeps its own consistent order for them. - -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. -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, 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. - -Settlement. `QuotaGate.SettleSend(ctx, unit, permit, result, sendErr)` runs in the transaction that stores the attempt or, after a `Send` error, the delivery's next state. It always journals the outcome, and: - -- `accepted` and `unknown` keep the reservation. An unknown attempt may have been sent, and counting it errs on the safe side. -- A `Send` error, where nothing left the process, and every `rejected` outcome release a new reservation: the provider did not take the message, so it did not count it. Without the release, a provider outage would use up the daily quota with failed retries. The journal sets `released_at` only on an open row, so a repeated settlement, for example after a commit whose answer was lost, releases nothing a second time, independently of the delivery's version. A reused reservation is never released: the earlier attempt under it may have been sent. A reservation that is never settled, for example after a crash between the two transactions, stays counted, which only over-counts. -- `rejected` with `quota_exhausted` also refines the count from the provider's answer. The window comes from `SendResult.QuotaPeriod`, which the transport fills from the provider's own error name (Resend `daily_quota_exceeded` gives `day`, `monthly_quota_exceeded` gives `month`), not from the wait hint. The window is the one current at settlement, because the provider answered about it, even when the reservation was made before midnight. The day mark raises that day's usage to the daily limit and the delivery waits for the next 00:00 UTC; the month mark raises the month's usage to the monthly limit and the delivery waits for the next UTC month start. A daily refusal on the last day of a month marks only the day. Resend's monthly quota follows the account's billing cycle; if that cycle resets later than the calendar month, the retry at the month start is refused again and waits another month unless an operator decides otherwise. Without a named window nothing is marked: the delivery waits for the provider's hint, or, without one, for an operator. A marked row records `provider_exhausted_at`, and a release no longer lowers it, so the local count stays at the provider's answer until the window resets. Raising the limit reopens the window; that is the operator's decision. `SettleSend` returns the time to store as the attempt's `next_attempt_at`. - -No purchase, plan switch, or transport change. The gate only defers. Nothing buys a plan, moves the account to a paid tier, or sends a waiting delivery through another transport, provider, or account; the delivery stays pinned (see [Mail deliveries](#mail-deliveries)). Switching `EMAIL_PROVIDER` is an operator decision, and the gate applies to the new transport too: it runs in the usecase before any transport is called, `smtp` needs stated limits, and deliveries pinned to the old account are refused instead of being sent without a limit. Counters are kept per provider and account label, so a new transport or a new `EMAIL_ACCOUNT` label starts with its own count. A transport that reaches the same provider account by another route, for example Resend's own SMTP endpoint, shares the provider's quota but not the local count, and so does a relabeled account: the provider's refusal then refines the count as above, the startup report warns about other labels with usage this month, and the operator should set the limits to what the account has left. - -Startup report. After the startup migrations, unless `EMAIL_PROVIDER=disabled`, bootstrap logs `mail quota usage` with the provider, account, and the day and month usage and limits, and warns `other accounts of this mail provider have quota usage this month; renaming EMAIL_ACCOUNT without changing the provider account resets the local count` when other account labels of the same provider have usage this month. A failed read is a warning and never stops startup. - -What the user sees. `notification.DeliveryStatusReader.LatestForUser(ctx, userID, kind)` returns the status of the newest delivery of a kind addressed to the account: the kind, the status, `WaitingUntil` for `waiting_quota` (the stored `next_attempt_at`), and the time of the last change. It returns no address, subject, body, provider, or delivery ID, and false when there is none. The query is scoped to deliveries addressed to the given account, so the caller must pass the authenticated account's own ID, never an ID from request input. No HTTP route calls it yet; the identity flows and a later API show it. A user interface maps the statuses as follows: - -| Status | What the user is told | -| --- | --- | -| `waiting_quota` with `WaitingUntil` | Your email is waiting until `` | -| `waiting_quota` without `WaitingUntil` | Your email is waiting; the time is not known yet | -| `pending`, `unknown` | Your email is being sent. `unknown` is not shown as a failure: the message may have been accepted | -| `accepted` | Your email was handed to the email provider, which accepted it. We cannot confirm that it reached your inbox | -| `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 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: the sending usecase `ServiceMailSender` (`backend/internal/usecase/notification/service_sender.go`), the enqueue usecase `ServiceMailer` (`service_mail.go`), the retry schedule `RetryPolicy` (`send_retry.go`), bounded retries of unknown Resend outcomes, audited operator decisions through `DeliveryRetryOperator`, and the local command `backend/cmd/mail-retry/`. `Delivery.CheckServiceMail` and `Delivery.Cancel` hold the cancel reasons (`backend/internal/domain/delivery.go`, `delivery_guard.go`), the loop is in `backend/internal/worker/mailsender/`, and the inbound port is `inbound.MailPass` (`port/inbound/mail_sender.go`). The repository and migrations `00012_add_delivery_sending.sql` and `00017_retry_unknown_mail.sql` store attempts, leases, retry cutoffs, and operator decisions. Registration queues a verification email, and `ConfirmEmail` consumes its link. The password reset flow is not implemented. - -Scope. The service worker claims only the kinds `verification` and `password_reset`. A product notification is never claimed here, whatever its state; the notification lane is described in [Sending product notifications](#sending-product-notifications). 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. - -Enqueue. `ServiceMailer.EnqueueVerification` and `EnqueuePasswordReset` run in the transaction that inserts the token, with the token record, the raw token, the recipient address, and the lifetime in hours. They check that the token purpose fits the message, render the message once with the current template version, and store a `pending` delivery bound to the token (`email_token_id`) under the token's ID as the delivery ID. A repeated call for the same token stores nothing new, and the stored body stays as it was. - -Links. The token travels only in the URL fragment: `/verify-email#token=` and `/reset-password#token=`, built by `mailtemplate` (`tokenLink`). A browser never sends the fragment to a server, so the token stays out of the nginx access log, which records `$uri`, out of Referer headers, and out of the Go request log; it is not in the path and not in the query. The frontend reads and removes the fragment, waits for explicit confirmation, then sends the token and registration password in the API request. It also consumes a new link opened in the same tab and ignores results from an older in-flight request. The password reset route and API are not implemented. The renderer rejects a token in any other place, its golden files and tests fix the format, and the delivery tests check that the stored body holds the link with the fragment and no `?token=`. The body in `deliveries` holds the live token until the mail is sent or cancelled; see Personal data at rest. - -Codes. Each verification message also carries a six-digit code: in the text part as the line `Код подтверждения: ` (the Russian copy), and in the HTML part as a large block. The code lives 30 minutes, or until its token ends when that is sooner, and the message states that lifetime. The code is an alternative to the link, not a replacement: `ConfirmEmailByCode` checks it (see Registration, email verification, and resend). Like the link, the code stays in the body of the delivery until the mail is sent or cancelled, and is then redacted; the token row keeps only a keyed digest of the code, never the code. Read access to `deliveries` before that point exposes the code too. - -One pass of `ServiceMailSender.ProcessNext` takes one delivery through three steps: - -1. Claim transaction. `DeliveryRepository.ClaimDue` takes the most overdue due delivery with `FOR UPDATE SKIP LOCKED`: kind `verification` or `password_reset` (literals that match the predicate of `deliveries_due_idx`, so the poll reads only that small index), status `pending`, `waiting_quota`, or a scheduled `unknown`, `next_attempt_at` passed, pinned to the configured provider account, and held by no live lease. An initial uncertain result is scheduled only while the delivery is inside the automatic cutoff; terminal unknown rows and unknown rows without a due time wait for an operator. A single-use manual authorization also makes an unknown row due. It sets `claim_owner` and `claimed_until` (the lease) without changing the version or the update time, so several processes never take one delivery. The lease is measured by the database clock (`clock_timestamp()` plus the lease length, and live while `claimed_until` is later than `clock_timestamp()`), never by the clock of an application instance, so instances whose clocks differ cannot take over a live lease or hold a dead one; due times stay on the application clock that wrote them. In the same transaction the sender rebinds mail stored while `EMAIL_PROVIDER=disabled` to the configured account (allowed before the first attempt only, so no provider holds its key), runs the check below, and then `QuotaGate.PrepareSend`, which reserves the recipient or parks the delivery in `waiting_quota`. The transaction commits before the transport is called, so a slow provider never holds a row lock. A failure inside it (a deterministic one, such as a row that cannot be restored) rolls the lease back too, so the failure is then recorded for the row in a transaction of its own; see Failing rows. -2. Check right before the send, one short transaction: it locks the delivery row (only for the lease holder), reads the token and the account again with `ServiceMailState`, so a revocation after the claim committed is honored, and records `first_send_started_at` by the database clock. For an uncertain retry, it rechecks the age against the 23-hour cutoff here, after quota and lease waits, immediately before any network call. A manual authorization is consumed only when this send-start is recorded. A mail that is no longer valid is cancelled and its reservation given back. Then one call to `MailSender.Send` with the stored content and the stable idempotency key `delivery/`. The transport never retries internally. The call is bounded by what is left of the lease after the claim and the settlement budget, and by the shutdown grace. -3. Settlement transaction. It locks the delivery row first (only while this worker still holds the lease), then `QuotaGate.SettleSend` and `DeliveryRepository.RecordClaimedAttempt` commit together, and the lease ends with the attempt. `RecordClaimedAttempt` applies only over the delivery's version and only for the lease owner, so a worker whose lease was taken over cannot record, and if two workers reach this step for one delivery only the first is kept; the other rolls back, including its quota settlement, and reports `lease_lost`. A database failure while storing the answer is repeated up to three times inside a settlement budget, because the answer exists only in memory until it is stored. - -Time budget. The lease is `EMAIL_TIMEOUT` plus one minute. The claim and the check come first; the call gets what remains of the lease minus the settlement budget (20 seconds), so claim, call, and the whole settlement fit inside the lease. When shutdown has begun the settlement budget is the shorter of 5 seconds and `SHUTDOWN_TIMEOUT` minus the 3-second shutdown grace (at least 1 second), so the process stops within its shutdown timeout, which is 10 seconds by default (the Compose stop grace period is 30 seconds). A result that cannot be stored in time is covered by the takeover below. - -Lock order. Every path locks the delivery row first and the quota rows second: the claim locks the row with `FOR UPDATE SKIP LOCKED`, and the check and the settlement start with `LockClaimed` (`SELECT ... FOR UPDATE` of the row of the lease holder), so no two paths can wait for each other in opposite directions. - -Check before sending. In the claim transaction, `Delivery.CheckServiceMail` compares the delivery with a snapshot read in one statement (`ServiceMailState`: the token and the account, no lock, only the address comparison key). The first failure cancels the delivery with `cancelled` and that reason; nothing is reserved and nothing is sent: - -| Order | Rule | Reason | -| --- | --- | --- | -| 1 | A token is bound and its row exists | `token_missing` | -| 2 | Its purpose is the one the mail kind carries (`email_verification` for verification, `password_reset` for reset) | `token_purpose_mismatch` | -| 3 | It belongs to the recipient account | `token_owner_mismatch` | -| 4 | It is not consumed | `token_consumed` | -| 5 | It is not revoked (`invalidated_at`, by a resend or a re-registration) | `token_revoked` | -| 6 | It has not expired | `token_expired` | -| 7 | The account still has the registration version the token was issued for, and a verification mail does not go to an address that is verified already | `account_not_current` | -| 8 | The address in the delivery is still the account's address | `recipient_mismatch` | - -A claimed row whose content no longer matches its hash (only a manual edit can cause that) is cancelled by the claim itself with `content_invalid`, with the bodies cleared like any cancelled token mail, and logged at error level with the delivery ID. Any other failure to restore a row may be transient, so it is not cancelled for good: it is a failing row, below. - -There is no deactivated flag on an account. "Current" is rule 7 and the token rules: a re-registration moves the version and revokes the token, and a deleted account takes its deliveries with it by cascade, so nothing is left to send. A reset mail has no verification-state rule: that the reset applies only to verified accounts is a product decision for the reset flow. The check is a snapshot: a token consumed or revoked after it, before the provider call, still lets the mail go. That is harmless, because the link is checked again when it is used. - -What a provider answer becomes. The delivery state machine of `domain.Delivery` decides; the worker only fills the attempt: - -| Result | Delivery | Next attempt | Quota | -| --- | --- | --- | --- | -| `accepted` | `accepted`, provider message ID stored | none | counted | -| `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` | minimum retry schedule until the 23-hour cutoff; after that, none until an operator decision | 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 | - -The retry schedule has no attempt limit on purpose: the token expires, and the check then cancels the delivery with `token_expired`. Each delay gets bounded jitter, up to a fifth over the schedule, from an injectable source (nil in tests, so times are exact), so deliveries refused together do not return together. Confirmed `temporary` and `rate_limited` refusals are retried with the same pinned account, key, and body; the `Retry-After` value is a lower bound. A confirmed refusal proves that request was not accepted, but it does not clear uncertainty from an earlier unknown attempt. Automatic retries of uncertain Resend outcomes use the same key and exact body only until 23 hours after the database-recorded first send, one hour before Resend's documented 24-hour key expiry. The last storage check repeats this cutoff immediately before the provider call. An unknown answer or a lost lease after send-start ends automatic retries and requires operator review. A pending manual decision permits a potential send; confirmed temporary or 429 refusals may continue under that decision, but an unknown result or lost lease after send-start requires another explicit decision. Recovery records a lost send as an unknown attempt before it schedules the new decision, and does not call the provider. A manual decision does not restart Resend's key window. The local `mail-retry` command uses the database credential as its operator boundary: `make -C backend mail-retry ARGS='inspect --delivery '` shows metadata and the duplicate warning, while `make -C backend mail-retry ARGS='retry --delivery --actor operator: --acknowledge-duplicate-risk'` prints the warning before atomically scheduling and auditing a single-use decision. It never calls a provider. The actor is an audit handle, not an authentication mechanism; there is no HTTP operator endpoint. Reusing an expired key may send a duplicate despite the acknowledgement. The alert `LincodexMailDeliveryUnknownOutcome` fires while an outcome needs review. - -Automatic retry after a lost worker. If a worker stops after a provider call but before storing the answer, another worker may claim that attempt and repeat the request with the same key while the 23-hour cutoff has not passed. A lost result after a manual send-start is recorded as unknown and waits for another operator decision; recovery does not call the provider. Resend answers a repeated key and body with the original result, and the quota gate reuses the open reservation, so the message exists once and counts once. The provider keeps the key for 24 hours from the first request, so the age is counted from `first_send_started_at` (set by the database clock right before the first request), not from the latest lease: however many workers were lost in turn, and whatever the lease length, once that age reaches 23 hours (the window less a one-hour safety margin) the earlier request may be forgotten and repeating it could send twice, so the delivery is recorded as an `unknown` attempt without a next attempt instead. The same applies at once to a transport without provider-side deduplication (window zero, SMTP). A lease that never reached the first request leaves nothing in doubt. - -Failing rows. A fault in one row must not hold the head of the queue. When the claim transaction fails after it took a row, its lease rolls back with it, so the same row would be claimed again at once and every delivery behind it would wait. Only a fault that the row itself causes is counted against it: a domain rule it breaks (`ErrInvalidDelivery`, `ErrDeliveryTransition`, invalid content or address), a row that cannot be restored for a reason other than a hash mismatch, or a data or integrity constraint refusal (SQLSTATE classes 22 and 23, `outbound.ErrRowFault`). Everything else says nothing about the row and is never counted: a context that ended, a timeout, a deadlock, a lost connection (SQLSTATE 08, 40, 53, 57, XX), an I/O error, a missing quota configuration. Such an error is returned to the worker, which backs off like for any global failure, and the lease expires or rolls back. For a counted fault the sender records the failure in a short transaction of its own (`RecordFailure`): `failure_count` is incremented, the lease ends, and the row is due again by `RetryPolicy` (outcome `row_failed`; the next pass takes the delivery behind it). The statement leaves a row alone that another worker holds under a live lease, so a claim that rolled back cannot disturb a row that someone else has just claimed. The count means consecutive failures: a successful claim and preparation (the check before the send) clears it, and so does a recorded attempt. A circuit breaker in the worker stops the counting when failures hit different rows pass after pass: three passes in a row that fail on three different rows are read as a global fault, the worker waits with a growing backoff (a `row_failed` pass never loops at once), and failures are moved back but not counted, and no row is cancelled, until a pass succeeds. After 3 consecutive counted failures the row is cancelled with the reason `processing_failed`, the existing terminal status that fits: it is visible to the operator and the alert below fires, and a new status was not needed. A database outage that also stops this record leaves the row under its lease, which expires. - -`EMAIL_PROVIDER=disabled`. Bootstrap does not start the loop: `newMailSenderWorker` returns no worker and logs `mail sender worker is not started because EMAIL_PROVIDER is disabled; stored deliveries wait`, so `lincodex_mail_sender_running` stays 0 and `LincodexMailDeliveriesOverdue` stays silent. Stored mail waits, pinned to `disabled`; after the stand restarts with a transport the worker rebinds it and sends it, if the token and the account still pass the check. The local operator command is available only with the Resend transport selected. A worker that is run against the disabled transport anyway (tests) gets `ErrMailChannelUnavailable` from every send, records nothing, releases the lease and the reservation, and backs off (5 seconds doubling to 2 minutes) instead of claiming again at once, so it never spins. - -Loop and shutdown. `worker/mailsender` repeats passes: a pass that handled a delivery is followed at once by the next, an idle pass waits 5 seconds, and a database failure, a missing transport, or an interrupted call waits with the growing backoff. When the context ends the worker claims nothing more, lets the send in progress continue for 5 seconds, stores its result, and returns; the gauge is 0 from then on. The loop is a goroutine of the backend process on its own pool of two connections, like the other workers; more throughput comes from more instances, and each handles one delivery at a time, which suits service mail under the Resend Free quota. - -Token at rest. The body of a token mail holds the one-time token, and a reset token is an account takeover primitive for anyone who can read the database or a backup. When a token mail reaches `accepted`, `rejected`, or `cancelled` (by any path: an attempt, a cancellation, the broken-row cancellation, or `processing_failed`), the same statement sets `text_body` and `html_body` to empty and `body_redacted_at`; the subject, the content hash, and the template version stay. The trigger allows exactly that change once, for a terminal row, and refuses any other change of the bodies or of the mark; the CHECK `deliveries_body_present` accepts an empty body only with the mark; the domain restores such a row as redacted content (`RestoreRedactedMailContent`), which cannot be sent. `unknown` keeps its body while it waits for review or a retry, because the worker may need to resend the stored content. The local command does not display or edit the body. Notifications are not redacted. Rolling back migration 00012 puts a placeholder in cleared bodies. - -Privacy. Logs name a delivery only by `delivery_id`, its kind, and closed values (the outcome and the cancel reason); no address, token, link, subject, or body appears in a log line, an error, or a metric label, and the metric has no labels at all. `ServiceMailSender` builds the outgoing message from the stored content and never logs it; `OutgoingMail` and `Delivery` redact themselves. - -Test fixture only. `resendfixture` and `resend.NewLoopbackSender` are never used by production code: `backend/.golangci.yml` forbids importing the fixture and calling the constructor outside `_test.go` files (depguard and forbidigo), and `bootstrap` binds the real transport with `resend.NewSender`. - -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. Notifications 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`); the notification lane has no overdue alert yet. 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. - -### Sending product notifications - -Implemented: the notification lane of the sending loop. `usecase/notification.NewNotificationSender` (`notification_sender.go`) builds a `DeliverySender` (`delivery_sender.go`) for the notification kind. It claims with `ClaimDueProductDelivery` through the partial index `deliveries_product_due_idx` and uses the same transport, quota gate, and settlement as the service lane. A `SubjectRights` implementation decides, per subject kind, whether a notice may still go out. The invitation notice is `invitationNoticeRights` (`invitation_rights.go`), and its rule is `Delivery.CheckInvitationNotice` (`backend/internal/domain/invitation_notice.go`). `bootstrap/notification_sender.go` builds the loop with the service timing and `EMAIL_PROVIDER`. - -Subject. A notification names the record whose rights it depends on: `domain.MailSubject`, stored with the request and copied to the delivery. The invitation send names the invitation and its organization. The subject is fixed with the delivery, and the content trigger refuses to change it (migration `00044_add_notification_subject.sql`). - -Rights check. Before the transport is called, the lane's eligibility runs twice: once in the claim transaction, and again in the check transaction that holds the delivery lock, so a change after the claim is honored. The invitation rule checks, in this order: the recipient account exists and its address is verified; the address of the delivery is still the address of the account; the invitation exists in the organization of the subject; the invitation still awaits an answer (delivered or viewed) and its response deadline has not passed; the candidate has not hidden the organization; and the candidate's publication (C2) is current. The notice declares no allowed fields: its body is fixed text that names neither the organization nor the terms, and it carries no contact, so no field consent (C4) applies. The content was rendered once when the request was handled, so the check is the only work before the transport call. Like the check of service mail, the rights read is a snapshot taken in the sending transaction. - -Contacts. Mail never carries a contact. Contact reads are pull-only, and each read re-checks the consent and the grant, so a contact copied into mail would outlive its grant. A future notice that carries a candidate field or a contact adds its consent check to `SubjectRights` before it can be sent. - -Cancel reasons. A failed check cancels the delivery with no attempt, no provider call, and no change of the provider account, and clears its bodies (`deliveries_body_present` allows the clearing of a cancelled notification). `rights_revoked` covers a hidden organization, a withdrawn publication, and an invitation that was answered, expired, or passed its deadline. `recipient_ineligible` covers a missing account or an unverified address, and `recipient_mismatch` a changed address. `source_closed` covers a notice that names no subject, or an invitation that no longer exists. A subject kind that this build cannot check is neither sent nor cancelled: the claim returns `ErrNoSubjectRights` and the row waits for a build that can check it. None of these reasons counts as a broken cancellation for `LincodexMailCancelledBroken`. - -Reserve. The notification lane's quota gate admits a send only while, after it, each window keeps at least `EMAIL_SERVICE_RESERVE_DAILY` and `EMAIL_SERVICE_RESERVE_MONTHLY` recipients free (`QuotaGate.WithReserve`). The defaults are a fifth of each quota limit: 20 a day and 600 a month on the Resend Free plan. The service lane keeps the full limits, so service mail always has its share of the same windows. A notification that the reserve refuses is parked in `waiting_quota` until the reset, and an idle pass does not claim it again, so the loop does not spin. A provider answer that its quota is used up marks the full window, not the reserve. - -Retention. Every due notice is checked when it is claimed, including one whose invitation ended long ago, so no cancellable row stays due. A cancelled notice loses its bodies. An accepted notice keeps its neutral body, which is an open point. - -Loop and disabled transport. The loop has its own gauge, `lincodex_notification_sender_running`, and its cancellations count in `lincodex_mail_sender_cancelled_total` by reason. With `EMAIL_PROVIDER=disabled` or without a database no loop starts, and a stored notice waits pinned to the transport it was created under, as service mail does. Once a transport runs, the loop rebinds the notice and sends it, if its rights still hold. - -Privacy. Logs name a notice only by its delivery ID, kind, and closed values (the outcome and the cancel reason). The subject, the address, the candidate, and the body never appear in a log line, an error, or a metric label. - -Open points. The invitation notice requires the candidate's publication, so a withdrawn publication cancels a pending notice; the product owner should confirm that choice. Accepted notices keep their neutral bodies, and no retention rule clears them yet. The notification lane has no overdue alert; the `lincodex_mail_deliveries{kind="notification",status="pending"}` gauge shows its backlog. - -### Internal notifications - -Implemented: the inbox of delivered events with a read state, the consumer that fills it, and four operations that list and mark it. The send of an invitation is the first product producer ([Sending invitations](#sending-invitations)); the synthetic event remains for tests and probes. - -Code: migrations `backend/db/migrations/00032_create_notification_inbox.sql` and `00036_allow_synthetic_notification_event.sql`, queries `backend/db/queries/notification_inbox.sql`, the model `backend/internal/domain/notification_inbox.go`, the port `port/outbound/notification_inbox.go` (`UnitOfWork.NotificationInbox()`), the adapter `adapter/secondary/postgres/notification_inbox.go`, the usecase files `usecase/notification/inbox.go`, `inbox_handler.go`, and `inbox_content.go`, the HTTP handler `adapter/primary/http/v1/notifications.go` with its cursor `notification_cursor.go`, the wiring in `bootstrap/notification.go` and `eventHandlers()`, and the frontend feature `frontend/src/features/notifications/` with the page `frontend/src/pages/notifications/`. The operations are in [api/README.en.md](../../api/README.en.md#notifications). - -- The inbox is the delivery state inside the platform. A row means that the notification reached the recipient's cabinet, and `read_at` says that the recipient read it. Mail is another channel with its own state in `deliveries` ([Mail deliveries](#mail-deliveries)), and neither reads the other. The inbox handler never reads `deliveries`, `mail_requests`, or the verification state of an address, so an unverified address, `EMAIL_PROVIDER=disabled`, or a failed send never blocks a notification, and a sent email never counts as seen. The delivered state of an invitation is its own `delivered_at`, written by the send transaction; the inbox row of its notification follows through the consumer. -- A row holds references, not text. `notification_inbox_events` has the key `(recipient_user_id, event_id)` and the columns `organization_id`, `event_type`, `schema_version`, `source_type`, `source_id`, `occurred_at`, and `read_at`. It stores no title, summary, name, contact, or score. Triggers keep the reference immutable (only the first `read_at` may be set) and refuse a direct delete; deleting the recipient's account removes the rows by cascade, and the organization foreign key is `RESTRICT`. A CHECK allows only the pairs of event type and source type that `domain.NotificationInboxSourceFor` allows, both at schema version 1: `invitation.delivered` with `invitation`, and the synthetic `notification.synthetic_delivered` with `organization`. Migration 00032 is deployed and unchanged; 00036 only widened the CHECK, and its rollback refuses while a synthetic row exists. -- Producer contract. A producer appends, in its own transaction, an event of an allowlisted type with the payload `{"recipient_user_id": ..., "organization_id": ...}` (two identifiers, no unknown field, schema version 1) and the aggregate that the type names. For `invitation.delivered` the aggregate is the `invitation`, which is also the content source. The synthetic event uses a one-off `synthetic_notice` aggregate at version 1, and its source is the organization of the payload; `notification.SyntheticNoticeEventPayload` is the single writer of that payload. The invitation module needed no change in the table, the consumer, or the API: the send transaction appends `invitation.delivered` through `notification.InvitationNotifier`, and `notification.ResolveInvitationNotice` is registered for the source `invitation` in `notification.DefaultInboxSourceResolvers()`. -- Synthetic event type. `notification.synthetic_delivered` has no product meaning. It exists so that the whole path (outbox, relay, Kafka, consumer, read-time check, list, read state) can be exercised before a real producer exists and in browser tests. It is off by default: the consumer handles it and the inbox renders it only when `NOTIFICATION_SYNTHETIC_ENABLED=true` (a development or browser-test stand; the e2e overlay sets it). With the switch off the event is acknowledged and ignored and a stored synthetic row is listed without content; the database CHECK allows the type either way, so turning the switch on needs no migration. Only code that can append to the outbox can produce it, and its content is a fixed text that names the sending organization. The browser suite appends it through the `company-fixture` (Go build tag `e2e`), never through a user operation. -- Consumer `notification_inbox`. `InboxHandler` handles the allowlisted types. In the transaction of the dedup marker it checks the envelope and the payload and rejects a broken event for good (`ErrEventRejected`), skips a recipient whose account was deleted, and stores the row with `ON CONFLICT DO NOTHING` on the key. A recipient deleted between the check and the insert aborts the insert with a foreign-key error that names the recipient; the handler returns it as a retryable error, and the retry finds the account gone and skips, while a foreign-key error on the organization is rejected for good. Three layers keep one row per recipient and event ID: the consumer marker, the key, and the comparison of a duplicate with the stored metadata, which rejects an event ID that comes again with other metadata instead of overwriting it. A replay under a renamed consumer therefore stores no second row. `occurred_at` is the informational insert time of the outbox row; it orders the list together with the event ID. The consumer group `.notification_inbox` is new, so it starts at the earliest retained event; events of other types are counted as ignored. -- Content is resolved at read time. `InboxService` lists a page and calls the resolver of each item's source type in the transaction that authorized the viewer; the result is never stored. A resolver returns `ErrInboxContentUnavailable` when the source is gone or the recipient may not see it now. The item then stays in the list with `content` null, the client shows a generic line, and an earlier text is never shown. A source type without a resolver is unavailable, never guessed. The resolver of a delivered invitation reads it only when it is addressed to the recipient and delivered, in the organization of the entry, and names the organization and the role; it shows no candidate value and links to `/candidate/invitations`. The resolver of the synthetic notice uses a fixed Russian text that names the sending organization by its current name, which `OrganizationNameForRecipient` reads under the recipient's current standing. Both read the name that way: a candidate sees the name until they hide the organization, and an employer while their membership is active. A name that does not fit the presentation limits is not shown. A content link is a same-origin path of a narrow alphabet, and the client opens it only inside its own cabinet. -- Scope. The candidate cabinet needs a verified candidate account and lists every organization context of the caller. The cabinet of one organization needs an employer account with a verified email (otherwise 403 `email_not_verified`, like the other organization operations) and an active membership of any role in the organization of the path. The membership is locked `FOR SHARE` with `LockActiveMembership` in the transaction of the list or the mark, like the card reads, so a revocation cannot commit between the check and the read and stops the next request. The recipient always comes from the session; the organization of the path narrows the rows and a path identifier alone grants nothing. A candidate on an organization route and an employer on the candidate route get 403. A missing membership, an unknown organization, an item of another account, an item of another organization, and an unknown ID all get the same 404 `not_found`. The organization routes are not in the owner-only list of `NewCompanyContextMiddleware`; `TestCompanyContextOperationInventoryMatchesOpenAPI` names them as authorized in their own transaction. -- Reading and marking. `GET /api/v1/me/notifications` and `GET /api/v1/organizations/{org_id}/notifications` return a newest-first page with a cursor bound to the account and the cabinet; a cursor of another account or cabinet is a 400. `POST .../{notification_id}/read` stores the first read time and returns it again on every repeat. It reads no source and returns no content, so an item without content can still be marked. All four are `Cache-Control: no-store`; a mark needs the session, the CSRF token, and an allowed Origin, and no Idempotency-Key because it is idempotent by its effect. No problem code was added. -- Frontend. `features/notifications` exports `NotificationInbox` (candidate or one organization) and `OrganizationNotificationInbox` (the chooser of the organization in the `organization_id` parameter plus the inbox). The pages `/candidate/notifications` and `/employer/notifications` and an entry "Уведомления" in each shell use them. The list is read on every visit and never kept (`gcTime: 0`), is keyed by account and cabinet, and is dropped when the account or the session changes or when access is refused. States: loading, empty, error with retry, forbidden, an item without content, and "show more". The read state is a word, not only a style, the mark is a native button, and focus moves to the item's heading after it succeeds. -- Trade-off: eventual consistency. The row is written by the consumer after the relay and Kafka, so a notification appears seconds after the producer committed, not inside the producer's transaction. The alternative, writing the row in the producer's transaction through `UnitOfWork.NotificationInbox()`, would make it immediate but would tie every producer to the inbox and drop the replay and dead-letter handling that the consumer gives. The browser suite therefore waits for the item and then replays the event. -- Tests. Unit: `domain/notification_inbox_test.go`, `usecase/notification/inbox_test.go` and `inbox_handler_test.go` (cabinet checks, membership revocation, resolver fallback, idempotent handler, rejected events, an `invitation.delivered` event under the same contract), `adapter/primary/http/v1/notifications_test.go`, `adapter/primary/http/notification_contract_test.go`, `bootstrap/consumers_test.go`, and the feature tests in `frontend/src/features/notifications/`. Integration: `TestNotificationInboxOverHTTP` and `TestSyntheticNotificationMigration*`. Browser: `frontend/e2e/notifications.spec.ts` in the registration mode ([TESTING.md](TESTING.md#browser-e2e-suite)). -- Not implemented: an unread counter or badge in the shells, live updates (the list is read on a visit and on window focus), archiving or deleting an item, retention of old rows, per-role filtering of employer notifications, a mail preference, and a metric for the inbox. The rows of the synthetic type are never removed by the application. - -### Product policy versions - -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: - -- `id`: uuid primary key, a UUIDv7 generated in Go (`domain.PolicyVersionID`). -- `policy_key`: the policy family. Each family has one document layout and one decoder; `product`, decoded as `domain.ProductPolicy`, is the only family, and both the domain and the `policy_versions_policy_key_known` CHECK reject any other. `version`: an integer above zero, unique within the family (`policy_versions_policy_key_version_key`); the newest publication has the highest number. -- `kind`: `demo` or `calibrated`, the calibration state of the whole version. Consumers read this flag. The `policy_versions_calibrated_kind_matches_document` CHECK and the domain refuse a `calibrated` version whose document marks the assessment section as uncalibrated. -- `created_at`: the publication time from the database clock. The BEFORE INSERT trigger `policy_versions_stamp_creation` sets it to `clock_timestamp()` on every insert and ignores a value from the caller. -- `effective_at`: when the version can start to apply. A NULL in the insert means "at publication", and the same trigger sets it to `created_at`; a scheduled time must not be earlier (`policy_versions_effective_after_creation`, mapped to `outbound.ErrPolicyVersionBackdated`). -- `author`: `system:` or `operator:`, at most 128 bytes of lowercase letters, digits, `.`, `_`, and `-`. It excludes `@`, so it cannot hold an email address. It is text rather than a reference to `users`: the seed has no account, admin roles do not exist yet, and a version must outlive any account, while a cascading or nulling foreign key would conflict with immutability. An admin editor can add an account reference in an additive migration. -- `document`: a jsonb object with the typed policy. `document_sha256`: the SHA-256 of the canonical document, 32 raw bytes. - -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 organization quota enforcement); every organization starts at E0, and the rules that move it between tiers belong to the quota feature. - -The MVP attempt accounting decision is candidate-wide: `MaxAttemptsPerWindow` counts root attempts across specializations in the rolling `AttemptWindow`. A corrective attempt shares its root slot, and training does not consume it. Retry and promotion timers remain independent by specialization. - -Legacy documents use `schema_version` 1 with the sections `invitations`, `organization_quotas`, `assessment`, `identity`, and `search_status`. Schema 2 adds independently optional `assessment.attempt`, `assessment.training`, `assessment.signals`, `support`, and `matching`, and requires at least one of those extensions. Encoding selects schema 1 without extensions and schema 2 otherwise. Each schema has a strict decoder: the legacy decoder rejects extension keys even when null, and an absent optional section never acquires defaults. Required fields reject missing/null values, wrong types, fractions, and values outside int32; both decoders reject unknown fields, unknown schema versions, trailing data, and documents over 64 KiB. Field names carry their unit (`_days`, `_business_days`, `_hours`, `_seconds`, `_bp`). The canonical form is compact Go JSON in field declaration order. `domain.RestorePolicyVersion` decodes, validates, re-encodes, and compares SHA-256 with `document_sha256`; mismatch returns `domain.ErrPolicyDocumentIntegrity`. The schema 1 golden bytes and hash stay unchanged. Deploy readers supporting schema 2 before publishing it; a previous binary cannot read schema 2, so publishing it prevents rollback to that binary. Stored policy documents are never rewritten for compatibility. - -The port `outbound.PolicyRepository` is available through `UnitOfWork.Policies()` and outside a transaction through `postgres.PolicyStore`. Methods that take a family reject an unknown one before reading storage. - -- `Create` stores a numbered `domain.PolicyVersionDraft` and returns the stored `domain.PolicyVersion` with the database times. The insert uses `ON CONFLICT DO NOTHING`, so a taken number or ID returns `ErrPolicyVersionConflict` without aborting a surrounding transaction. -- `GetByID` reads one version. -- `GetEffective(key, at)` returns the newest publication, the highest number, among the versions whose `effective_at` is not after `at`. A version scheduled for later therefore never undoes a version published after it: an urgent correction stays in effect when an earlier scheduled version reaches its time, and the scheduled version is superseded. The unique `(policy_key, version)` index serves this lookup. -- `GetLatest(key)` returns the highest number, effective or not. -- `HasVersions(key)` reports presence without reading a document. -- Misses return `ErrPolicyVersionNotFound`. - -`policy.Publisher` validates the whole input before it reads storage. It takes the application clock only to refuse a scheduled effective time that has already passed; the publication time comes from the database. `Publish` assigns the highest stored number plus one; when a concurrent publication takes the number, it reads again and retries up to 10 times, then returns `policy.ErrPublishContended`. It works on a standalone repository or inside a unit of work. - -Demo and calibrated policy: `domain.DemoProductPolicyV1()` is the accepted initial policy for verifying the product flow. It is published as version 1 of `product` with kind `demo` and author `system:demo-seed`, and its assessment section is marked `uncalibrated_initial`. These values make no calibrated quality claim. The policy holds rules only; assessment content (the task bank, blueprints, and variants) is a separate task. Demo version 1: - -| Section | Values | -| --- | --- | -| `invitations` | response deadline options 3, 7, and 14 days, default 7; at most 20 pending invitations per need; repeat after a decline in 30 days; interview proposal within 5 business days; 30-day pause after no deal | -| `organization_quotas` | rolling windows of 7 days for invitations and 24 hours for distinct card views; E0 10 invitations and 50 views, E1 40 and 150, E2 100 and 400; E2 is inactive until the organization verification that grants it exists; the E0 companies of one holding share one pool, and E1 and above count separately (see [Company quotas](COMPANY_QUOTAS.md#holding-pool)) | -| `assessment`, uncalibrated initial | same-grade retry after 30 days; at most 3 attempts per 180 days; at most one promotion per 90 days; confirmation at P_G >= 0.80, high strength from 0.90; after at least 8 scored items stop at P_G >= 0.90 or <= 0.10 or SE <= 0.25; at most 23 scored items plus 2 seed items; practice is mandatory | -| `identity` | verification token 24 hours; unverified account deleted 7 days after the latest registration; session idle timeout 24 hours, absolute lifetime 7 days | -| `search_status` | the "searching" status is confirmed every 30 days | - -The identity lifetimes in this table are the values of the identity contract ([api/README.en.md](../../api/README.en.md#identity-sessions-cookie-and-csrf)). They come from the versioned product policy, not from configuration: the registration, verification, and session usecases will read them from the effective policy version. The grade rules in [Assessment and grade verification](#assessment-and-grade-verification) use the same assessment values. - -Matching coefficients (`matching`, schema 2, `domain.MatchingPolicy` in `policy_matching.go`, demo version `domain.DemoProductPolicyV4()`): every field is required once the section is present, and the units are basis points except the two skill weights and the cohort size. The demo values are the design values of PRD 4.9 for checking the flow, not measured results; they are published explicitly (the isolated browser fixture publishes V4; startup still seeds V1 only), and a policy version without the section makes the search fail closed instead of ranking with defaults. - -| Field | Demo value | Meaning | -| --- | --- | --- | -| `fit_coverage_weight_bp`, `fit_domain_weight_bp`, `fit_semantics_weight_bp` | 7500, 1500, 1000 | `Fit = 0.75 * Cov + 0.15 * Dom + 0.10 * Sem`; the three add up to 1 | -| `rank_fit_weight_bp`, `rank_strength_weight_bp` | 5000, 5000 | `S = (0.5 * Fit + 0.5 * P) * freshness * responsiveness`; the two add up to 1 | -| `freshness_floor_bp`, `responsiveness_floor_bp` | 9000, 9000 | the multiplier `0.9 + 0.1 * x` of Fr and Rsp; a floor of zero is refused | -| `competition_boost_bp` | 3000 | `P = T + 0.3 * (1 - T) * V` | -| `neutral_unknown_bp` | 5000 | the neutral 0.5 for an unknown component (Dom, Sem, T, Fr, Rsp, and Cov of an empty request) | -| `near_skill_threshold_bp` | 2500 | a required skill that contributes less moves a confirmed profile to the near group | -| `required_skill_weight`, `desired_skill_weight` | 2, 1 | weights of the skills in Cov | -| `trust_stated_bp`, `trust_online_bp`, `trust_identity_bp`, `trust_in_person_bp` | 2500, 6000, 8500, 10000 | coefficients of the evidence trust levels 0 to 3 | -| `attribution_personal_bp`, `attribution_team_role_bp`, `attribution_team_unattributed_bp` | 10000, 8000, 5000 | personal result, team role, team result without a role | -| `relation_exact_bp`, `relation_narrower_bp`, `relation_broader_bp` | 10000, 8000, 4000 | evidence for the same skill, a narrower one, a broader one | -| `percentile_min_cohort` | 30 | the smallest comparable real cohort that allows a percentile; the search compares the real cohort of each returned category with it | -| `max_results_per_group` | 10 | entries of each group that one search may return; the whole bank is ranked and only the output is cut | -| `skill_taxonomy` | backend over docker, go, kafka, postgresql; devops_sre over docker | the technologies inside each specialization, which decide whether evidence is broader or narrower than a requested skill | - -The validation keeps each share in 0..1, the fit and rank weights at a sum of 1, the trust and relation coefficients ordered, and the floors above zero. Not in the policy yet: the competition half-life of 24 months and the embedding-only relation 0.3, because no competition data and no embeddings exist. - -Seeding: at startup, after migrations and under the same condition (`DATABASE_MIGRATE_ON_START` is true and `DATABASE_URL` is set), bootstrap calls `Publisher.EnsureDemoProductPolicy`. It checks only whether `product` has any version and never decodes one, so a stored version of a newer or unknown layout cannot block startup. When the family is empty, it publishes demo version 1 effective at publication; otherwise it changes nothing and logs that the seed was skipped. Instances that start together race for version 1, and the loser skips. The log line names only the key, number, kind, and ID. A database error stops startup. The seed is not a data insert in a migration, so the schema and the policy values change independently. - -Referencing a version (planned): tables that record a decision built under a policy, such as grade decisions, selection snapshots, and invitations, carry `policy_version_id uuid NOT NULL REFERENCES policy_versions (id)` and store the version used when the decision was made. An existing decision reads that version with `GetByID` and is never recomputed through `GetEffective`, whose answer for a given time changes when a scheduled version is superseded. A referenced version cannot be deleted, by the foreign key and by the trigger, and a new version never rewrites past decisions. - -Test fixtures use their own values. Since `product` is the only family, the integration tests give every case its own database, and no fixture stands in for the demo policy. - -## Release artifacts and restoration - -The local release manifest separates core image verification from product data availability. It records immutable release IDs, source and Compose file hashes, exact built image IDs, registry digests for pulled images, and bounded hashes for versioned data artifacts. Restoration checks these references and hashes before Compose starts and never resolves a moving tag again. The bundled demo policy source is version 1, but that does not establish which policy row is active in PostgreSQL. The demo seed is versioned by the hashes of its bundled source, which also holds the synthetic demo bank, and its image is pinned so the isolated demo stand can be restored from the same delivery. The assessment bank remains unavailable until an accepted snapshot exists, so `product_data_status` is partial. Named Compose volumes persist across a release restart, but the manifest is not a database backup or data snapshot. See [DEPLOY.md](DEPLOY.md#release-manifest) for the commands and manifest schema. - -## Repository map and package purpose - -```text -api/core/ public browser-to-Go contract and bundle -api/ml/ internal Go-to-ML contract and bundle -api/runner/ internal Go-to-code-runner contract and bundle -backend/cmd/app/main.go calls bootstrap.Run and reports errors -backend/cmd/migrate/ local migration status, up, and down-one -backend/config/ shared runtime configuration -backend/internal/domain/ product invariants, planned modules -backend/internal/usecase/ application operations and orchestration -backend/internal/port/ inbound and outbound interfaces -backend/internal/adapter/ primary HTTP and secondary integrations -backend/internal/bootstrap/ dependency wiring and process lifecycle -backend/db/ migrations, SQL queries, and the embedded migration set -backend/codegen/ ogen server and ML-client configs, sqlc -frontend/src/ app, pages, widgets, features, entities, shared -frontend/codegen/ Orval configuration -ml/src/ FastAPI service and operational checks -ml/codegen/ Python datamodel-code-generator settings -runner/ Go code runner service: nsjail, cgroup v2, judge, and HTTP API -deploy/ Compose, Nginx, and technical smoke checks -observability/ Prometheus, Loki, Alloy, Grafana provisioning -scripts/ shared documentation and schema tooling -docs/ maintained Russian and English guides -``` - -```text -backend/ - cmd/app/main.go calls bootstrap.Run and reports errors - config/ shared runtime configuration - internal/ - domain/ flat package; DomainEvent, identity types, consent ledger, organizations and memberships, product policy - usecase/health/ operational readiness usecase - port/inbound/ readiness and event handler input boundaries - usecase/identity/ password validation before hashing (Credentials) - usecase/policy/ publication of policy versions and the demo policy seed - usecase/consent/ granting of consents C1-C3 and C5 and the scoped C4 with the current-text check - usecase/files/ shared private file layer: policies, opaque keys, stream limits, checksums - usecase/notification/ mail requests and the consumer that stores them as deliveries, the quota gate, the service mail enqueue (`ServiceMailer`), the senders of service mail (`ServiceMailSender`) and of product notifications (`NewNotificationSender`), and their rights checks - usecase/notification/mailtemplate/ pure rendering of versioned service emails; the delivery consumer renders notifications with it - port/outbound/ readiness, cache, object storage, transaction, outbox, outbox relay, event publishing, event consumption, identity, consent ledger, organization and membership, policy, password hashing, mail, and code runner boundaries - adapter/primary/http/ - api/ generated ogen handler - middleware/ request log and request metrics by route template - observe/ request-scoped observations, such as the problem code - problem/ RFC 9457 error responses - v1/ handwritten handlers of the contract operations - router.go chi composition - adapter/secondary/ - argon2id/ Argon2id password hasher with a memory budget - kafka/ franz-go event publisher and consumer group member: record envelope, its decoding, and events topic provisioning - mail/disabled/ mail transport that sends nothing and reports the channel unavailable - mail/resend/ mail transport that sends one request to the Resend HTTP API per message - mail/resend/resendfixture/ local stand-in for the Resend API, for tests only; production never imports it - ml/api/ generated client from backend/codegen/ogen-ml.yml - code_runner/ client of the code runner: TLS 1.3 transport pinned to the configured CA, opaque idempotent run IDs, request and response validation - code_runner/api/ generated client from backend/codegen/ogen-code-runner.yml - code_runner/disabled/ code runner that runs nothing and reports itself unavailable - postgres/ pool, migrator, transactor, outbox writer and relay store, event consumer store, identity, consent ledger, organization, membership, and policy repositories, health check - postgres/sqlc/ generated SQL adapter - redis/ cache adapter and Redis check - seaweedfs/ S3 adapter and bucket check - prometheus/ bounded Go/process, request, problem, outbox, consumer, job, delivery, quota, and answer save metrics - worker/outboxrelay/ outbox relay loop: claim, publish, mark, backoff, and shutdown - worker/eventconsumer/ event consumer runtime: dedup transaction, retries, dead letters, offset commits, and shutdown - worker/jobrunner/ scheduled job runtime: claim under a lease, run with the completion, retries, release, and shutdown - worker/mailsender/ sending loop of the mail lanes (service identity mail and product notifications): repeats passes, waits when idle, backs off on failures, reports its running gauge - worker/retry/ backoff with jitter and a context-aware wait shared by the workers - worker/deliverymetrics/ periodic read of the delivery and mail quota aggregates into the metrics - bootstrap/ configuration, wiring, lifecycle, shutdown - db/ embedded migrations and SQL queries; outbox, identity, policy, event consumer, delivery, mail quota, scheduled job, consent ledger, and organization tables - codegen/ ogen and sqlc configs - pkg/testutil/ fake application clock and identifier scan shared by tests -``` - -Domain types live directly in `backend/internal/domain/`: `user.go`, `candidate.go`, and other files as their models are defined. Do not nest directories by entity or feature. The first type is `DomainEvent` in `domain_event.go`, the validated event that a transaction writes to the outbox. Identity storage types live in `email_address.go`, `secret_token.go`, `user.go`, `email_token.go`, and `session.go`; the normalized password is in `password.go`. The consent ledger types live in `consent.go`. The organization, verification, and membership types live in `organization.go` and `membership.go`. The product policy and its versions live in `policy.go`, `policy_document.go`, `policy_version.go`, and `policy_demo.go`. - -Outside the implemented flows (identity, consents, organizations, profile and questionnaire, assessment, needs and matching, invitations, support cases, notifications), usecases for documents and FSP achievements are not implemented. SMTP and FSP adapters remain planned; the product worker jobs are currently only the computation of the assessment review band and the expiry of an invitation at its response deadline. `main.go` starts bootstrap and handles process errors. The public generated transport uses ogen v1.24.0 and the contracts declare OpenAPI 3.2.0. Verify only the feature subset used by the repository, not every specification feature. - -This is a compact map, not a claim that every planned product package exists. Current Go code includes health usecases and adapters, generated API clients, bootstrap with startup migrations, a PostgreSQL health query, the transactional outbox writer, the outbox relay that publishes committed events to Kafka through the franz-go adapter, the event consumer runtime with the `notification_delivery` and `notification_inbox` handlers, the internal notification inbox with its list and read-state operations, the scheduled job runtime (`worker/jobrunner`) with no registered product job kind, identity usecases for registration, resend, confirmation, and login, PostgreSQL sessions and a security boundary for every operation protected by the API contract, the consent usecase that records C1 during registration, the versioned policy store with its publisher and the demo policy seed at startup, the `PasswordHasher` port with the Argon2id adapter and checks used by registration, confirmation, and login, a Redis cache adapter, a SeaweedFS S3 adapter with the shared private file layer over it, the `MailSender` port with the `disabled` and Resend transports, the mail template renderer, and the identity mail worker used for registration and resend. Profiles, resumes, assessments, invitations, product job kinds, file workflows, the SMTP transport, and FSP adapters remain planned. Do not create empty module directories before a real use case exists. - -`backend/pkg/` is reserved for small technical packages with a justified shared boundary, not product usecases or domain types. `pkg/testutil/` holds `FakeClock`, a concurrency-safe manual clock that the worker, integration, and future usecase tests inject wherever production code takes a `func() time.Time` clock, and `FindPersonalIdentifiers`, which the metrics tests use to find email-like and UUID-like values in an exposition. A `mailer` package remains a candidate. Mail templates live in `internal/usecase/notification/mailtemplate/`: they hold product copy and use domain types such as `SecretToken`. It is a pure rendering package without I/O or logging. The delivery consumer in `internal/usecase/notification/` renders notifications with it; `ServiceMailer` creates verification mail during registration and resend. Password reset mail belongs to the planned reset flow. Templates, versions, and link format are described in [DEPLOY.md](DEPLOY.md#mail-templates). Keep the S3 client in the SeaweedFS adapter. Keep service-specific behavior private under `internal/`. - -`api/` contains contract sources and tools; it is not a runtime hop in the request path. `api/core/` and `api/ml/` each own OpenAPI source, route and component fragments, and a committed bundle. Root `scripts/` merges schema fragments. Generated Go output belongs to its consumer: the public handler under `backend/internal/adapter/primary/http/api/`, the internal ML client under `backend/internal/adapter/secondary/ml/api/`, and sqlc output under `backend/internal/adapter/secondary/postgres/sqlc/`. The first is transport code mounted in chi; the latter two are outbound adapters. `backend/cmd/app/main.go` remains a small process entry point; bootstrap owns dependency wiring and graceful shutdown. - -## Target modules - -| Module | Responsibility | Main data | -| --- | --- | --- | -| identity | Email, verification, sessions, roles | users, email_tokens, sessions, external_identities | -| candidate | Profile, contacts, consent, visibility | profiles, contacts, skills, consents, resume_versions | -| company | Company and its members | organizations, organization_representatives, memberships | -| assessment | Questionnaire, tasks, attempts, scoring, grade | questionnaires, task_templates, attempts, answers, grade_history | -| matching | Needs, filters, ranking, search versions | hiring_needs, search_runs, search_items | -| invitation | Offer and contact permission | invitations, invitation_events, contact_grants | -| document | Files, resume analysis, standard PDF | files, analysis_results, document_jobs | -| achievement | FSP link and achievement provenance | fsp_links, achievements, sync_runs | -| vacancy, later | Vacancies and voluntary applications | vacancies, applications | - -The MVP uses one PostgreSQL database. Keep relational links and constraints explicit. JSONB can hold versioned questionnaire answers and ML results; it does not replace the data model. Skills and specialties use normalized references. Large PDFs stay outside PostgreSQL. Candidate category combines specialty and test-verified grade. Claimed and verified grades remain separate. - -An achievement records its source, external ID, event date, receipt date, and trust status. Missing FSP history, a missing link, and a temporary sync error are distinct states. ML has no direct access to the business database. - -## Target user flow - -Candidate flow: verify email -> complete profile and consent -> answer questionnaire -> select expected grade -> take assessment -> receive a verified category -> publish profile. - -Employer flow: verify email -> create company profile -> describe need -> confirm extracted skills -> choose filters -> review an explainable result set -> send a salary offer -> candidate accepts -> only that company can access contacts. - -An invitation includes the employer, description, contact channel, both salary bounds, and RUB currency. Both salary values are required whole rubles in multiples of 1000 and must satisfy 0 < salary_from < salary_to, with a width (salary_to - salary_from) / ((salary_from + salary_to) / 2) from 10% to 40% inclusive (PRD FR13); the same rule applies to the salary range of a need. Show the pay period and tax basis (net or gross). vacancy_id is optional. Main transitions are draft -> delivered -> viewed -> accepted or declined; the internal sending step is never visible, a send answers with delivered, and direct acceptance from delivered is allowed. The candidate records viewed with an explicit view command; reading an invitation has no side effect. withdrawn (by the organization), expired (a server deadline), and cancelled_by_candidate are terminal states. Retries are idempotent, and transactions protect concurrent state changes. The draft part of this flow is implemented; see [Invitation drafts](#invitation-drafts). - -A contact grant belongs to one candidate-company pair and is created after an accepted invitation or a candidate's own application. The server checks the user, company membership, grant, and current visibility on each read. Before a grant, employers receive no contacts, original PDF, messaging links, or contact fragments from resumes or ML. - -The owner profile, search card, and authorized contacts use separate DTOs. The candidate can receive a complete PDF. A company export is built from its allowed view after another access check. A permanent public file URL does not replace authorized delivery. Revoked consent removes the profile from new and saved search results; it cannot retrieve information another party already received. - -## Assessment and grade verification - -Assessments use reviewed task families and a blueprint for each specialty and grade. The blueprint records competencies, difficulty, task count, and weights. Variants change the prompt and input while keeping the assessed skill; shuffling answer choices is insufficient. Go backend and React frontend at junior/middle level are the initial demo scope. Other specialties need a real task bank. - -Fix the seed, version, and conditions before an attempt. Keep answers and keys on the server. Prefer automatically scored formats that do not execute candidate code in the MVP. Free-form answers can be an additional signal; LLM scoring is never the sole basis for a grade. Team pilots set thresholds, and a high average must not hide a critical-section failure. - -Grade state rules: - -- Before the first passing assessment, status is unverified and a claimed grade does not grant verified category access. -- A failed attempt never lowers an existing verified grade. -- After an initial failure, the candidate may choose a lower-level test; the system does not assign it automatically. -- A promotion after a successful qualification is allowed at most once per 90 days. -- The first lower-level test after failure is outside that interval. A retry of the same grade waits 30 days, and a candidate takes at most 3 attempts in any 180 days. -- A strong result may suggest a higher-level test. Keep the grade history available. - -These intervals are the accepted initial policy, stored as demo version 1 of the [product policy](#product-policy-versions); its thresholds are uncalibrated and are not a validated psychometric model. Task rotation and attempt limits reduce the value of leaked answers but do not prove resistance to hints or LLMs. Difficulty comparability needs measurement. - -### Assessment bank - -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`). Bootstrap creates `assessment.NewBank` once (`bootstrap/catalog.go`, with its own small PostgreSQL pool) and hands it to `CatalogHandler`; HTTP uses only the read `Bank.SpecializationAvailability` for the public specialization catalog (`GET /api/v1/specializations`). HTTP does not call the loader operations (`ImportBundle`, `PublishFamily`, `RetireFamily`, `OpenCategory`): the demonstration seed command (`adapter/primary/cli/demoseed`, `usecase/demoseed`) and `cmd/questionnaire-fixture` call them, so no category is open in a build without the seed. Assessment attempts run through a separate `AttemptService` that reads the bank through the `UnitOfWork.AssessmentBank()` repository, not through `Bank`. - -- 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 an existing scheme) 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 and scheme 2 hashes of fixed inputs. Scheme 1 is the layout of an algorithmic generator and scheme 2 (migration `00047_allow_table_hash_scheme.sql` widens the CHECK to `1, 2`) is the layout of a table generator; a new version gets the scheme of its generator kind, so the content and the hash of every algorithmic version stay what they were, and each scheme refuses the other kind of generator, because a table hashed by scheme 1 would not be covered by the hash. As for `policy_versions`, a role that owns the table can still disable the triggers. -- One published version per family. A partial unique index (`assessment_families_one_published_key`) allows at most one published version of a key. `Bank.PublishFamily` retires the published older version in the same transaction and refuses with `newer_version_published` when a newer version of the key exists in any state, a draft or a retired one included, so superseded content is never put back in the bank (earlier content is published again by importing it as a new version); `Bank.ActiveFamily` reads the single published version. Coverage counts each family once. -- Seed generator and variants. A generator is either algorithmic or a table (see "Table generators" below). An algorithmic generator names a registered algorithm with a versioned name (`rate_limit_window.v1`, `dedup_window.v1`, `lru_hits.v1`, `lru_hits_choice.v1`, `dependency_order.v1`), the ranges of its parameters, and a statement template. A seed selects a variant: the same version and seed always give the same statement and reference answer (the pseudo-random source is SplitMix64 written out in the domain, so variants stay reproducible across Go releases; golden tests pin one statement and answer per algorithm), and the rubric is a property of the family, so no seed changes it. The reference answer comes from the algorithm's solver, which has unit tests with hand-computed cases. The registry only grows: a changed algorithm gets a new name, because stored versions refer to the old one. -- Choice answer format. The answer format `choice` offers options instead of asking for a value. A choice variant stores its options and the key on the server: the frozen variant holds the options in presentation order, each with an opaque ID and a text, and the reference answer is the decimal index of the correct one. The candidate receives the option IDs and texts in that order (`ChoiceItemContent` of the public contract, `multiple` false) and nothing else: not the index, not the seed, and not how a distractor was made (the allowlisted projection and the response snapshot are checked for this). The seed decides the order of the options and the IDs: the order is a seeded Fisher-Yates shuffle, and each ID is drawn after the shuffle, so an ID says nothing about the position or the correctness of its option; the same family version and seed give the same options in the same order. A choice answer names the selected option IDs (`{"format":"choice","option_ids":[...]}`); the server grades it against the key. An ID that is not an option of the item, a second option, or an answer of another format is an invalid answer (400), not a wrong one. Distractors come from the algorithm, not from chance: a choice algorithm returns the correct value and the wrong values of known error models, and the shared code removes duplicates and the correct value, lets the seed choose among the mistakes, and tops up from plausible nearby values only when the mistakes give too few distinct ones. The registered `lru_hits_choice.v1` asks for the number of cache hits and offers wrong counts from an off-by-one count in either direction, counting misses instead of hits, a cache where a hit does not renew a key (FIFO), a cache that evicts the most recently used key, and a capacity off by one in either direction; its parameter bounds guarantee enough distinct values. The signals observe a choice answer as an answer of a small answer space, like an integer (`domain.SignalAnswerFormat`), so the observation column keeps its two classes. A choice variant is stored with an `Options` field in the frozen variant document, which is omitted for the other formats, so stored attempts keep decoding. -- Table generators. A family can declare its variants as data instead of naming an algorithm: `seed_generator.table.rows` is a list of rows, each with `values` (the text of every placeholder), an `answer`, and for the answer format `choice` the `distractors`. The seed selects one row (SplitMix64 under the fixed name `table.v1`, so the selection is reproducible and changes only with a new name), the statement template substitutes the row values exactly as it does for an algorithm (the same text and `{{.name}}` whitelist, so a table cannot carry code), and the answer is the one written in the row: nothing is computed from the table. The table is validated at import, and a failure names the row by its zero-based index in the array (`rows[2]`) without quoting content: 2 to 500 rows, 1 to 16 columns with lowercase names, the same columns in every row, values of 1 to 1000 bytes without control or format characters, no repeated row, every column present in the template and no other placeholder, a rendered statement of at most 8 KiB for every row, at most 64 KiB of text in all, an answer format of `integer` (a canonical decimal integer of at most 15 digits, so a JSON number carries it exactly, and no distractors) or `choice` (a one-line answer of at most 500 bytes and 1 to 9 distinct distractors that do not repeat the answer). The answer key must name the same format. A table family has no algorithm and no parameters, is hashed with scheme 2, and is as immutable as any version. Algorithms in Go remain for tasks whose answer must be computed. The variant keeps the row index as a private parameter `row`. -- Statement templates. A template is plain text with `{{.name}}` placeholders and nothing else: the text/template parser reads it without functions, and a whitelist walk refuses every node except text and a single field action (so `define`, `template`, `block`, `range`, `with`, `if`, variables, pipelines, and calls such as `printf` are refused). The loader renders the placeholders itself, never runs the template engine, and caps the template at 2000 bytes and the rendered statement at 8 KiB. Every placeholder must belong to the algorithm, and the template must contain the placeholders the answer depends on (the input data and the answer-relevant parameters), so a statement always shows the input. A bundle is validated fully at import, with probe renders at the lowest parameter values and, for eight seeds each, at the highest values (the largest inputs) and at drawn values, so a template close to the size cap cannot pass on one lucky seed; reading a stored row does not repeat the probes, because the content hash proves the content is the one that passed them. Titles, templates, and rubric texts refuse control characters, Unicode format characters (for example bidirectional overrides), and the line and paragraph separators U+2028 and U+2029; the title CHECK constraint also refuses the common ones. -- Rubric. A rubric holds a principle and a list of criteria. It has no points, weights, or pass mark; how criteria become a grade is not decided in the bank. -- Lifecycle and the loader. `Bank.ImportBundle` stores every family of a bundle as a draft in one transaction and never publishes, whatever the review says; importing the same bundle again, also concurrently, reports the versions as unchanged. `Bank.PublishFamily` and `Bank.RetireFamily` take the operator, and refuse with a reason (`reviewer_missing`, `review_not_approved`, `not_draft`, `not_published`, `newer_version_published`); the refusal is a `*domain.AssessmentRefusalError` that carries the reason, and the sentinels of a race that the database decided (a lifecycle step that lost to another, a missing approved review, insufficient coverage) become the same refusals. Publishing, retiring, and opening take a transaction-scoped advisory lock of the category first, so they run one after another per category; `LockCategory` works only inside a transaction (the repository of a unit of work takes it, the standalone store returns `ErrAssessmentLockOutsideTransaction`). -- Category availability. `Bank.OpenCategory` records an opening in `assessment_category_openings` under a referenced policy version (`policy_versions.id`); it refuses with `grading_policy_missing` for a missing or unknown reference and with `grading_policy_not_current` unless the version is the one of the `product` family in force now, judged against the database clock of the same transaction (`clock_timestamp()`), the clock that stamps the effective time of a policy version, so the bank defines no thresholds of its own and no application clock enters the decision. The number of distinct published families that a category needs is read from that policy: `RequiredPublishedAssessmentFamilies` returns `assessment.stop_rule.max_scored_items` plus `assessment.stop_rule.seed_items`. The owner accepted this rule as a product decision on 2026-10-06. The reason: one family gives at most one item to an attempt, so a full adaptive attempt, which can run to the maximum of scored items and also carries the seed items, cannot run out of families. The insert trigger derives the same number from the stored policy document itself (the same two JSON paths; an integration test keeps the SQL and the domain equal) and checks both values as plain non-negative integers of at most four digits before the cast, so a malformed document written around the application raises the `assessment_category_openings_policy_thresholds` refusal instead of a cast error. The trigger also counts the published families, and the CHECK constraint refuses the row when they are fewer, so a call written around the usecase cannot open a category with a lower requirement. The opening stores the policy version, the operator (`operator:`), and the required and counted families, and is never edited. Availability is live: `Bank.CategoryAvailability` returns the current opening only while the published families counted now still reach the opening's requirement, and otherwise refuses with `coverage_insufficient` (or `ErrAssessmentCategoryNotOpen` without an opening), so a retirement can close a category. It also refuses with `grading_policy_not_current` when the opening's policy version is no longer the one in force, so a policy change requires a new opening. The table checks the policy reference in the trigger instead of a foreign key, because PostgreSQL refuses TRUNCATE of a referenced table before the `policy_versions` trigger can refuse it with its own error. `ListFamilies` pages by (key, version) cursor with a hard limit of 200. -- Demo bundle. `backend/testdata/assessment/backend_demo_bundle.json` holds four original practice problems for the category `backend`. They are an AI-generated draft (author `ai:claude-draft`) with a pending review and no reviewer, so the loader imports them as drafts, publication is refused, and the category stays closed. No human has reviewed the statements, solutions, rubrics, or difficulty; the bundle makes no validity or calibration claim. A real review produces a new version of the families that carries the approval. -- Not implemented: authorship and review of a real task bank, blueprints per specialty and grade, an HTTP or admin interface of the loader and authenticated reviewer and operator identities (the storage of attempts, answers, and grading exist as separate assessment operations, not as part of the loader). - -### Assessment signals and the review band - -Implemented as server-side signals of a real attempt (root or corrective), a review band computed by a scheduled job under the policy version pinned to the attempt, and an operator-only reader. The band is a hint for a manual check by a person. It does not change the result, the category, or a quota; no candidate or employer operation carries it, and the public contract has no field for it (a test walks every operation, request, response, and header to check this). Until staff roles exist, the only reader is the local command `assessment-review`, which records each read ([DEPLOY.md](DEPLOY.md#assessment-review-band)). Browser signals are described separately by the signal receipt contract; this section covers what the server observes itself. - -Code: migration `backend/db/migrations/00033_create_assessment_signal_review.sql`, queries `backend/db/queries/assessment_signal_review.sql`, the policy section and band rules in `backend/internal/domain/` (`assessment_signal_policy.go`, `assessment_signal_review.go`), the observer, the review job, and `ReviewOperator` in `backend/internal/usecase/assessment/signal_review.go`, the repository in `backend/internal/adapter/secondary/postgres/assessment_signal_review.go`, and the command in `backend/cmd/assessment-review/`. - -- Facts. `assessment_answer_observations` has one row per accepted answer: the family, the seed, the answer format, the server time from the last activity of the attempt (the previous answer or the start of the current work session) to the accepted answer, whether that time starts at the previous answer, and a keyed answer fingerprint. `assessment_attempt_origin_marks` has a row when the login session or the client network of an accepted answer or signal batch differs from the last row (digests of both), so the list stays short however many requests arrive. The browser events of the signal receipt contract only add totals (focus loss time, clipboard events, fullscreen exits). Rows are append-only, removed only by the cascade from the attempt or the account, and written in the same transaction as the answer or the batch, which already holds the attempt row lock. Two maintained counters, `assessment_answer_fingerprint_holders` (answers per family version, key generation, and fingerprint) and `assessment_answer_family_totals` (answers per family version and key generation), are increased by a trigger in the transaction of each observation insert; they only grow, so an answer removed with an account stays counted, and they are derived caches without foreign keys. A transaction touches one row of each, always in the same order. -- No answer text, keyed digests only. The new tables store no answer text; the raw answer already exists in `assessment_attempt_items` and is untouched. Fingerprints and digests are HMAC-SHA-256 values under purpose keys derived from `IDENTITY_KEY_SECRET` with their own domain labels (`Keyring.AssessmentAnswerFingerprint`, `AssessmentSessionDigest`, `AssessmentNetworkDigest`); no new secret exists. Each stored value carries a `key_version` (now 1) and only values of one generation are compared, so a future key rotation is an explicit step. The answer fingerprint covers the family version and the canonical answer and is the same for every candidate and seed. The session and network digests also bind the attempt, so they cannot be linked between attempts. The HTTP adapter passes the session ID and the limiter key of the client address (an IPv6 address reduced to its /64) to the usecase, which hashes them; no address, session ID, token, or answer text is logged or stored. The digests live as long as the attempt (the retention period is an open question). Changing `IDENTITY_KEY_SECRET` makes old and new fingerprints incomparable. -- Server signals. Response time: an answer faster than the per-format floor of the policy is fast, and within one format an answer more than the policy ratio below the median of the attempt is an anomalous deviation (only the fast side; a slow answer is not suspicious, and a format needs enough answers of its own). One answer counts once: an answer under its floor is fast and not also a deviation. The first item of a work session is measured from the session start, which only bounds when the item was shown, so it is excluded from both. Parallel sessions: requests that return to an earlier login session after another session was used (a single move to a new session is not counted). Networks: the number of distinct client networks beyond the first, so a move to another network and back counts once. Parallel sessions and extra networks are weak and correlated (a phone and a laptop produce both), so they form one group: alone it reaches attention at most, and review only together with a strong signal (fast, deviating, or duplicate answers) at attention or above. Client time only complements server time: it is never the source of a response time, and client signals can raise a normal band to attention but never to review. -- Identical answers of different candidates, compared pairwise. For one attempt the comparison looks at every other attempt separately: matched answers are equal fingerprints of the same family version and key generation, given by another candidate to a different seed variant, so an expected agreement on one seed is not a signal and a candidate never matches their own attempt. A matched answer carries -log2 of the share of answers that hold that fingerprint among the answers of the family version and key generation, read from the maintained counters (so a rotation does not skew the share), between zero and the cap of its format (`duplicate_integer_cap_bits`, `duplicate_sequence_cap_bits`). A popular value, such as the correct answer of a variant, therefore carries little, and so does a population of a few attempts. The bits of one pair add up, the strongest pair decides, and `duplicate_bits_attention` and `duplicate_bits_review` are thresholds on that sum. The list of pairs is bounded and never leaves the usecase; nothing identifies the other attempt or candidate in any output, and the operator output holds counts only. -- Why the demo thresholds are 48 and 64 bits, and what the figure means. `TestDemoDuplicateThresholdsKeepThePerAttemptFalseFlagRateLow` samples 4000 seeds of each of the four demo families (the three integer families have 36 to 47 distinct answers, the dependency order about 2250), builds the distribution of shared values and their bits, and computes the probability that one pair of honest candidates who answer a 23-item attempt correctly reaches each threshold. Multiplied by 10,000 rivals (union bound), the per-attempt false flag rate is about 4e-5 for attention and 3e-9 for review, against test targets of 1e-3 and 1e-8. The model uses the distribution of reference answers: it does not model the distribution of wrong answers or correlated mistakes (candidates who make the same common error, or a shared tutorial), which can make honest coincidences more likely than computed. These are demo values pending calibration on a real bank, with four AI-drafted families. In the other direction, `TestDemoThresholdsNeedAPopulationBeforeACopiedPairIsFlagged` calculates how many answers per family a copied pair needs before the demo thresholds flag it, when the pair copies every answer and nobody else holds those values: for an attempt of 13 items, attention from 26 answers per family and review from 61; for 23 items, from 9 and from 14. A stand with fewer attempts flags nothing by design. To try the feature on a small stand, publish a policy version with lower thresholds in `assessment.signals` (the integration tests do this with 4 and 6 bits); the demo policy is not changed for that. -- Policy. The optional section `assessment.signals` of a schema 2 policy document holds every threshold (`domain.AssessmentSignalPolicy`); a version without it computes no band. `DemoProductPolicyV3` is `DemoProductPolicyV2` plus `DemoAssessmentSignalPolicy`; `DemoProductPolicyV1` and `DemoProductPolicyV2` and the startup seed are unchanged, and a stored version is never rewritten. The band uses the thresholds of the product policy version in `assessment_attempts.product_policy_version_id`, so a policy published later does not change an attempt in progress or a stored review; `assessment_attempt_reviews.policy_version_id` records the version, and a trigger refuses to change it. A matched attempt is re-evaluated under its own pinned version; pairs are selected with the attention level of the evaluating attempt, so across versions with different levels a pair can be missed on the side with the lower level. -- When and how. The review never runs in a candidate's transaction. The first accepted answer schedules the job `assessment.signal_review` with the key `:deadline`, due one minute after the deadline of the attempt (so an answer committed right at the deadline is in its facts), and finalization schedules `:ended`, due at once; both are inserts into `scheduled_jobs` in the transaction of the answer or the finalization, and repeats do nothing. The deadline job also covers an attempt that expires or is abandoned, however and whenever its state changes. A review is a point-in-time evaluation: it describes the facts committed when its job ran, and the job at the deadline runs it again for a finalized attempt, which picks up later matches. The job computes the review of its attempt and refreshes the review of every other attempt that has ended (terminal state or past its deadline) and shares answers with it at the attention level or above, at most 50 per job; a ring of more than 50 attempts that share answers is covered because each member runs its own deadline job and sees the others. An attempt that is still running is flagged by its own job when it ends and sees the other facts then. Writers are ordered by a transaction-scoped advisory lock per review: the job locks the review of every attempt it will write, in ascending attempt order, before it reads any fact, so the later of two jobs over one attempt waits and then reads what the earlier committed (no lost update, and no lock cycle). The times of a review come from the database clock inside the upsert and the update time never falls behind the stored times. Nothing else is locked: the facts are append-only and a job is scheduled after its facts are committed. A failure is retried by the runner with backoff and can never block or change a result; without the worker (`JOBS_ENABLED=false`) reviews wait with their jobs. The only review statement in a candidate's transaction is the insert of the job (and the two counter updates of the answer). The job logs one line with the number of reviews it wrote and its duration, and no answer, address, or candidate. Applicability bound: the share is read from the counters in constant time, but the comparison joins the answers of the attempt with the answers that hold the same values, so its cost grows with the number of holders of popular values, at most 23 items times the holders of each; it is fine for background jobs on populations of up to about 100,000 answers per family and needs sampling or a cap above that. -- Limits. Browser signals can be forged or suppressed, so they are a hint only. The client measures of the attempt page (fullscreen, covering the task, blocking copy, selection, print, and paste) stop only the casual route: the task text is in the candidate's browser, so a screenshot, a second device, or an extension takes it out, and they change no score by themselves. A helper such as an LLM on another device is not visible. False positives are possible: a shared or changing network (mobile data, NAT), a reload, two tabs, copying the task text, and coinciding answers of a small answer space. The retention period of these facts, whether collecting them needs a separate consent beyond the notice, and who calibrates the thresholds are not decided. - -### Watermark of the task text - -Implemented for real attempts (root and corrective). A training run (`demo_express`) carries no watermark. The watermark ties a leaked statement, a screenshot, or a photo of the screen back to an attempt so that a person can review it; it does not stop any of them. Code: `backend/internal/domain/assessment_watermark.go` and `assessment_wording.go` (the mark and the table of interchangeable phrases), `backend/internal/usecase/assessment/watermark.go` (`Watermarker`), `Keyring.AssessmentWatermarkSeed` in `usecase/identity/keyring.go`, the hook `AssessmentHandler.WithPresenter` in the HTTP adapter, and `frontend/src/features/assessment-watermark/`. - -- Where the mark is made. Only in the response, never in storage: the stored variant, its reference answer, and the retained idempotent responses stay unmarked, and grading reads the stored variant. Every response that carries an attempt (creation, read, session start, answer, finalize) passes the presenter, so one attempt shows the same code and the same marked text on every read and replay. If the mark cannot be made the response is a 500 and never an unmarked task text. -- The key. The seed of an attempt is HMAC-SHA-256 of the attempt identifier under a key derived from `IDENTITY_KEY_SECRET` with its own label (`lincodex/assessment/watermark/v1`); no new secret exists. The code, the invisible mark, and the choice of wordings are all read from this seed on the server, and neither the seed nor the key is sent to a client. Changing `IDENTITY_KEY_SECRET` changes the code and the wordings of every attempt, so a text or a screenshot of an attempt issued before the change can no longer be traced. -- Visible channel. `AssessmentAttempt.watermark.code` is 10 symbols of Crockford base32 (50 bits of the seed) shown as `XXXXX-XXXXX`. It is a pseudonym: it holds no name, contact, or identifier of the account and cannot be computed without the secret. The attempt page draws it with the time (UTC, to the minute, from the clock of the device) as a faint tile over the whole task screen: fixed, opacity 0.07, no pointer events, hidden from assistive technology. It survives a screenshot or a photo and is removed by a tool that edits the page. -- Invisible channel. The statement carries the same code as 25 base-4 digits and one check digit written in four zero-width characters (U+200B, U+200C, U+200D, U+2060), repeated after the first space and at the start of each following sentence (at most 8 copies), so a copy of a paragraph keeps a whole run and a damaged run is ignored. It survives a copy of the page text, a saved page, and an API response. Many chat, mail, and OCR tools drop zero-width characters, and a retyped text has none. -- Wording channel. `assessmentWordingGroups` lists about 18 groups of interchangeable phrases of plain connective prose (`at most` and `no more than` before a number, `is not` and `isn't`, `non-decreasing` and `nondecreasing`, and the like, with Russian groups). Each attempt writes every group in the form its seed picks. The table is append-only because reordering it changes the choice of attempts already served; a group avoids terms that a statement defines and then reuses, and the number groups apply only before a digit. The channel survives retyping and OCR, and it is weak: a statement holds a few groups, and a group is worth about one bit, so it only tells attempts apart that were served the same variant text. -- The meaning does not change. The tests compare the canonical text of two attempts that were served one variant (the mark and the phrases removed or mapped back) and find them equal, check that the reference answer belongs to the variant and is not touched by marking, that marking twice gives the same text, and that the number and data tokens of the statement stay in the accessible text. -- Accessibility. Some speech synthesizers and braille displays may announce zero-width characters or break a word at them; this was not tested with a real screen reader. The page therefore puts every run of invisible characters in an `aria-hidden` element: the accessibility tree holds the words only (a Playwright check reads the tree with `ariaSnapshot`, and a Vitest check strips the hidden elements from the markup), while the document keeps the characters so that anything copied from it carries the mark. The wordings are ordinary words, and no whitespace variants are used, because a non-breaking space is not guaranteed to be silent everywhere. -- What it does not do. A screenshot, a photo of the screen, or retyping cannot be prevented in a browser. The watermark is evidence for a manual review and an appeal, never an automatic decision; no operation shows it to an employer, and the candidate sees only the code of their own attempt. - -### Capture hints, one open window, and what they cannot do - -Implemented for real attempts (root and corrective). A training run (`demo_express`) has none of it. Hardened proctoring here has no camera, no microphone, no screen recording, no screenshots, and no clipboard contents; it consists of weak signals for a manual review and one rule about open windows. Code: `backend/internal/domain/assessment_signal.go`, `assessment_signal_review.go`, `assessment_signal_policy.go`, and `assessment_work_lease.go`; `backend/internal/usecase/assessment/work_session.go` and the observer in `signal_review.go`; migration `backend/db/migrations/00050_add_assessment_work_leases_and_capture_signals.sql`; the operations `HoldMyAssessmentWorkSession` and `ReleaseMyAssessmentWorkSession`; and `frontend/src/features/assessment-signals/` and `frontend/src/features/assessment-work-session/`. - -- A screenshot or a phone photo cannot be prevented. A browser page cannot block the operating system or another program from capturing the screen, cannot see a camera, and cannot see a second device, a remote desktop, or a virtual machine. The page therefore never tries: it does not cancel a key, does not blank the page on a key, and does not read any image. What it can do is report that a screenshot key was pressed, tie a leaked statement or screenshot back to its attempt (see [Watermark of the task text](#watermark-of-the-task-text)), and send both to a manual review. -- Signals lead to a review and an appeal, never to an automatic downgrade. The signals only raise the review band, which changes no result, category, or quota; the employer never sees a signal or a band, and the candidate sees no band. Notice version 4 says all of this plainly. -- Screenshot keys. The page reports `screenshot_key` when it sees PrintScreen (also with Alt), Cmd+Shift+3, 4, or 5 (macOS), or Win+Shift+S, on the key press or release, once per second at most. The operating system takes many of these keys before the page, a key-less screenshot sends nothing, and holding a key is not told from pressing it, so the event proves only that a key was pressed. It carries the item and a client timestamp and no measurement. -- Developer tools. The page reports `devtools_open` when the outer window becomes more than 160 px larger than the page in width or height, which is what a docked panel does, on a resize and on a two-second timer, at most once per minute. It is a heuristic with false positives (a sidebar, zoom, a resized window) and false negatives (a detached panel, other windows), so it too is only a weak hint. -- Policy and band. Both kinds are stored as events (the check constraints of `assessment_signal_events` allow them without a measurement) and counted per attempt (`client_screenshot_keys`, `client_devtools_opens` in `assessment_attempt_reviews`). Thresholds are optional fields of the policy section `assessment.signals`: `client_screenshot_keys_attention` and `client_devtools_attention` are client thresholds, so they raise a normal band to attention and never above it, and `extra_agents_attention` with `extra_agents_review` joins the weak group of parallel sessions and extra networks, which alone reaches attention at most and review only beside a strong signal. A zero or absent threshold leaves the signal out, so a version published before these fields keeps its band, its document, and its content hash (a test checks that its document does not contain the new keys and re-encodes unchanged). The demo policies are not edited; `DemoAssessmentSignalPolicyWithCaptureHints` in `assessment_signal_policy.go` lists agreed starting values (three screenshot keys, one detection, two extra User-Agents), which no study supports, and the integration test publishes them in its own policy version. -- User-Agent digest. The HTTP boundary cuts the User-Agent to 512 bytes and hands it to the usecase, which stores only `HMAC-SHA-256` of it under a key derived from `IDENTITY_KEY_SECRET` (label `lincodex/assessment/signal-agent/v1`) bound to the attempt, in the new column `agent_digest` of `assessment_attempt_origin_marks`. The raw value is never stored or logged. A mark is written when the session, the network, or the User-Agent differs from the last mark, so the list stays short; `extra_agents` counts the distinct digests beyond the first. A browser that updates itself during an attempt, or a candidate who moves to another device, adds one, so it is a weak signal. -- One open window. `assessment_attempt_work_leases` holds one row per real attempt: a keyed digest of an identifier that each open page generates when it loads (`X-Attempt-Client`, 16 to 64 characters of `A-Za-z0-9_-`), when it took the session, when it last renewed it, and when it released it. `PUT .../work-session` holds or renews the session for 120 seconds (`domain.AssessmentWorkLeaseDuration`) and tells the page to renew every 15 seconds; `DELETE .../work-session` releases it and answers 204 whatever it did. The page holds the session before it starts or resumes work, renews it while it works, releases it when it leaves or closes (`pagehide`), and stops with an explanation if a renewal is refused. While another page holds the session, the session start and the answer of any other page, or of a request without the header (one anonymous page), answer 409 `state_conflict` and change nothing; the check runs under the attempt row lock after the database time is read, before any attempt change, and the refusal is not stored under the idempotency key, so the holder can reuse the key. An attempt that nobody holds, a released hold, and a hold that stopped renewing (after at most two minutes) admit every page, and `StartSession` and `SubmitAnswer` of a service built without work sessions are unchanged. -- How it relates to `MaxSessions` and `IdleTimeoutSeconds`. Those attempt policy limits describe the sequential work sessions of an attempt: a new one starts only after the idle timeout, and the count is bounded. The hold is the concurrency dimension inside the current work session. It starts, extends, and consumes no work session of that policy, does not change the attempt version, and is not stored in the attempt row. -- Limits of the rule. It is a one-page-at-a-time rule, not a security boundary: a client that never holds the session is refused only while another page holds it, a candidate can always continue after the hold is released or has expired, and two windows of one candidate are not told from two people. The hold is renewed by a page timer, so a browser that throttles a background tab to one tick a minute still renews within the two minutes. -- Operator reading. `make -C backend assessment-review ARGS='inspect ...'` prints the new counts `extra_agents`, `client_screenshot_keys`, and `client_devtools_opens` next to the old ones; the note at its end repeats that browser signals can be forged and that a screenshot or a phone photo cannot be prevented or seen by the page. - -### Leak trace - -Implemented as a local operator command, `assessment-leak-trace`, that finds the real attempt behind a leaked task text. It reads text and nothing else: a screenshot or a photo must be read by an OCR tool first, and OCR itself is outside this project (the command accepts any UTF-8 text of at most 64 KiB from a file or standard input, and a visible code that the operator read by eye). The result is a hint for a manual review and an appeal. It is never shown to an employer (no HTTP operation serves it), it changes no score, category, or quota (the command writes nothing but its own audit), and it never names an attempt on a guess. Code: `backend/cmd/assessment-leak-trace/`, `backend/internal/adapter/primary/cli/leaktrace/command.go`, `LeakTracer` in `backend/internal/usecase/assessment/leak_trace.go`, `AssessmentLeakAlignment` and `AssessmentTextPiecesBetweenPhrases` in `domain/assessment_wording.go`, `domain/assessment_leak_trace.go`, migration `backend/db/migrations/00051_create_assessment_leak_traces.sql`, and the queries `backend/db/queries/assessment_leak_traces.sql`. - -- Methods, strongest first. (1) The invisible mark: intact runs of zero-width characters decode to the code of an attempt (50 keyed bits), so one attempt behind one code is a finding on its own. (2) The visible code: the code of the tile, found in the text of a screenshot as two groups of five characters (or ten characters followed by the date and time of the tile) or given with `--code`; one character that the recognizer misread is tolerated (45 bits), two are not. The time on the tile is compared with the life of the attempt (an hour of slack) and reported as a note, never as a verdict, because it is the clock of a device. (3) The statement and its wording: the stored, unmarked statements of real attempts are searched for pieces of the text, the attempts that were served that statement are told apart from other variants of the same family by how far the text follows their statement, and among those by the phrase forms the text shows (about one bit per phrase group; only the phrases aligned with the stored statement are read, so words around the statement in a message are ignored). A statement counts only when the text is a copy of it, whole or cut where the text stops: other words where the statement continues mean that another variant of the same family, which shares only its fixed text, is not the source. A statement text that only one attempt was served names that attempt by the variant alone when the text shows no phrase group, and is excluded when the text shows phrases that contradict the attempt, because the leak may come from an attempt that was deleted. -- The code of an attempt is computed, never stored, so no lookup table exists: the command walks every real attempt (5000 per page), computes its code from `IDENTITY_KEY_SECRET`, and compares. The work is linear in the number of attempts and fine for an operator command. The command therefore needs the secret of the server that served the attempts; a rotated secret makes older codes and marks unreadable, and then the search can still use the statement text. -- Outcomes. `found` names one attempt, the method, and the strength in bits, with notes such as whether the statement text matches the attempt (a mark attached to another text is flagged). `ambiguous` means that the evidence leaves several attempts in play (two attempts behind the codes, a mark and a visible code that name different attempts, or attempts that were served the same statement and chose the same phrases) and names none. `not_found` is an honest answer when the data is not enough: no mark, no code, no stretch of at least 24 characters free of interchangeable phrases, no statement that contains the text, a text that more than 200 statements contain (generic), or a wording that contradicts every holder. -- Audit. Every search writes one row to `assessment_leak_traces` in the same transaction as the search, before a result is printed: the operator handle (`operator:`, not authentication), the database time, a keyed digest of the normalized text (HMAC-SHA-256 under a key derived from `IDENTITY_KEY_SECRET`, label `lincodex/assessment/leak-text/v1`), its length, the outcome, the method, the attempt for a found search, and the counts. The text is never stored or printed, the table refuses UPDATE, DELETE, and TRUNCATE, and the attempt is not a foreign key, so the audit outlives an account deletion. Rolling migration 51 back is refused while the audit holds a row. -- What it cannot do. A leak with the mark and the tile gone, retyped in own words, or photographed so that no tile is legible leaves only the wording and the variant, which name one attempt only when few attempts were served the same statement. The text of a screenshot depends on the OCR tool. A text that was edited breaks the alignment. A watermark cannot prevent a leak, and the result is evidence for a person, not a decision. The command and its audit are described in [Operating the leak trace](DEPLOY.md#leak-trace). - -### Skill evidence - -Implemented as a stored projection of the immutable assessment results, with two reads: the candidate's own list and the permitted projection of a currently visible card. The match search reads the organization projection (see [Matching and explanations](#matching-and-explanations)); no percentile reads it yet. - -Code: migration `backend/db/migrations/00035_create_skill_evidence.sql`, queries `backend/db/queries/evidence.sql`, the model in `backend/internal/domain/evidence.go`, the port `port/outbound/evidence.go` (`UnitOfWork.Evidence()`), the adapter `adapter/secondary/postgres/evidence.go`, the usecase `backend/internal/usecase/evidence/read.go`, the handler `adapter/primary/http/v1/evidence.go`, and the operations `ListMyEvidence` and `GetOrganizationCandidateEvidence` ([api/README.en.md](../../api/README.en.md#skill-evidence)). - -- One event is one fact. `skill_evidence_facts` has one row per source event (`UNIQUE (source_type, event_id)`); `skill_evidence_skills` holds the skills of that event as tags (primary key `(fact_id, skill_code)`, a closed set of the nine specialization codes and the four technology codes of the card). A second tag adds a tag, never a fact, so repeated tags cannot multiply a contribution. A fact without a skill cannot be committed (a deferred constraint trigger), tags, once stored, are never rewritten or removed, and a tag joins a fact only in the transaction that created it (`created_txid` and the trigger `skill_evidence_skills_require_new_fact`), so a stored fact is never widened afterwards. -- A fact keeps its source, event, result, attribution, date, visibility, and trust, and tells a claim from a measurement. `kind` is `claim` (trust 0, a statement that nothing confirmed separately) or `measurement` (trust 1 to 3, an observed result); a CHECK ties each kind to its levels. Only measurements are written today, so no claim is stored and the profile claims (trust 0) are not listed. `source_type` is `assessment_result` and the event and the result are the attempt, because a result is keyed by its attempt (`result_id` is a foreign key to `assessment_attempt_results` with the owner, and a cascade removes the fact with its result or account). `attribution` is `personal` (the team values of the PRD are reserved by the CHECK). The result part is the grade that was passed, the basis (`synthetic_demo`), and the calibration (`uncalibrated`), copied from the category decision of the result: a demonstration category is shown as one. -- Trust 1. An online assessment is unproctored and nothing confirms who answered, so the projection writes trust 1 (the PRD level without a reliable confirmation of the identity or authorship). A CHECK allows only 1 or 2 for this source, never the in-person level 3; 2 is reserved for a result tied to a confirmed identity, which no flow produces yet. `domain.EvidenceTrustOnlineUnconfirmed` and the SQL value are kept equal by the integration test. -- Which results qualify. One SQL predicate (`skill_evidence_result_qualifies`) says that a result is evidence: a real result (`root` or `corrective`) of the basic mode, version 2, with the outcome `confirmed`, and a category decision with the status `assigned` or `unchanged`, that is, a reviewed synthetic source. A result that passed but had no reviewed source (`not_eligible`, for example with the demonstration gate off) is not evidence, a failed attempt is not evidence and is never shown as a failure, and an express training run (`demo_express`, a version 1 result of the mode `demo_express`) is never evidence. A lower passing result under a higher category (`unchanged`) is a fact of its own: the grade was passed, and the category stays. -- Why a stored projection written by the database, not a derivation on read. Decision: a trigger on `assessment_attempt_results` calls `skill_evidence_project_assessment_result` after the insert of a result, in the transaction that finalizes the attempt, and the migration projects the results that already exist with the same function. Reasons: the atomicity with the result and the category holds without a change to the finalization code; no write path (a command, a repair, a future import) can store a qualifying result and forget its evidence, or the reverse; a fact needs state that a derivation cannot carry (the candidate's visibility, tags from other events); and every read touches only the projection, so no query of the evidence names a result, an answer, an attempt, or a review (a test reads the query files and fails on it). The cost: the rule lives in SQL as the category guards do, the projection must be rebuilt by the function if the rule changes (the function is idempotent, and an integration test truncates the projection and rebuilds it), and the facts duplicate three values of the result. A guard trigger refuses a fact whose result does not qualify or does not match the fact, even through a direct write, and the table refuses every change but `visibility`. Rolling the migration back drops the projection, which is derived, and applying the migration again rebuilds it; but the rollback refuses (`skill_evidence_retained`) while any fact is hidden, because hiding is the candidate's decision and no result can bring it back. Known risks: a trigger failure rolls the finalization back with it, which is the intended atomicity (a result without its fact is never stored); and a real version 2 result whose specialization is outside the closed skill list would fail the backfill of the migration and the trigger, so a new specialization needs a change of the list in the same migration that admits it. -- The candidate reads `GET /api/v1/me/evidence`: own facts only, newest first, the hidden ones with `visibility` `hidden`, a cursor bound to the candidate (the cursor of the privacy lists), `Cache-Control: no-store`. The fact names the result that the candidate can open at `GetMyAssessmentResult`. -- The organization reads `GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}/evidence`. The evidence is a section of the card, so the read runs the checks of the card read in one transaction: verified employer, active membership, effective C2 publication, the hiding of this organization, the minimum cohort, and the card must show at least one category after the cohort rules (`candidateview.Service.AuthorizeCategoriesSection`, which returns the categories of the card, each with its grade). Then the statement `ListOrganizationVisibleEvidence` repeats the barrier: it selects from `candidate_effective_publications`, excludes the candidates that hide the organization with `NOT EXISTS`, requires the `categories` field in the published fields, and returns only visible measurements. It returns one fact for each category of the card: the earliest fact that passed exactly the confirmed grade of that category, so a lower grade or a retake adds nothing, and only the skill of the category, never the other tags. A closed or revoked publication, a hidden organization, an unknown handle, a suppressed card, and a card without categories answer one 404; a hidden fact gives an empty list, not an error. The answer is an allowlist: the skill, the passed grade, the trust level, the year of the event (`observed_year`), and the basis and calibration of the method (`synthetic_demo`, `uncalibrated`), which are the same for every candidate and tell the organization that the fact is a demonstration, not a validated measurement (they add no fingerprint). It has no identifier of the fact, the event, the result, or the candidate, no month or exact time, no source, and never an answer, score, item, failure, signal, or review band. What can and cannot be linked: no key joins the answer to a person, but it is not unlinkable. The skill, grade, trust, and year, together with the other values of the card, can narrow a small pool of candidates, and the minimum cohort of the card does not cover the year. The read consumes the card-view quota under the distinct-card rule and is recorded in the access history with the field `categories`, so the candidate sees it. -- Scope of the consent C2. Publishing the `categories` field now sends an organization the confirmed category and one supporting assessment fact for it (skill, grade, trust level, year, and the demonstration labels). The candidate sees the same section in `GetMyCardPreview` (`evidence`), which applies no organization or cohort, so an organization can receive less. The C2 consent text was written before this section existed, and whether it needs a new version for it is a decision for the owner and the lawyer; this change does not touch the consent texts. -- Express and failure. Reading the evidence before and after an express run shows the same list, the database refuses a fact whose result is an express run or a failed attempt, and an express run is not in the category, hence not in the card cohort. There is no percentile or ranking cohort in this release; when they appear they must read the same predicate. -- Contract checks. `TestEvidenceOperationsFollowTheConventions`, `TestEvidenceSchemasAreClosedAndSeparateClaimsFromMeasurements`, `TestNoOrganizationOperationReachesRawAssessmentData`, and `TestEvidenceWalkReachesTheEvidenceFamily` (Go) and `test_evidence_is_closed_and_no_organization_operation_reaches_raw_assessment_data` (Python) walk every organization operation and the candidate list through all references and fail on an assessment, signal, or review schema, or on a raw answer, score, or failure property. -- Not implemented: an operation to hide or show a fact (the column and the guard exist; no HTTP operation changes it), claims from the profile as facts, facts from FSP or other sources, revocation of a source, a trust level above 1, the use of evidence in the Passport PDF, and retention. Whether the evidence should need its own card field instead of `categories` is open. - -### Assessment availability and the confirmed grade - -`GET /api/v1/me/assessment-availability` (`GetMyAssessmentAvailability`) only reads. The usecase `backend/internal/usecase/assessment/availability.go` reads the policy, the bank, the questionnaire, the attempts, the quota, and the current categories in one repeatable-read snapshot. For each questionnaire specialization, `confirmed_grade` and its basis `confirmed_basis` come from the current `candidate_assessment_categories` row through the `ListCandidateCategories` port, not from the results. The grade and its basis are therefore read together, and `confirmed_basis` is null exactly when no grade is confirmed. A category of a specialization that the questionnaire no longer lists does not appear in the availability, but the profile shows it. - -The profile (`GetMyProfile`, `SaveMyProfile`) reads the same rows in its own transaction. `confirmed_categories` holds one category per specialization in catalog order, with its `basis`, its assignment time (`confirmed_at`), and the `attempt_id` of the attempt whose result assigned it. An empty list means that no result has confirmed a category. - -A category changes only by a strict grade upgrade (the database trigger and the domain): a result with a higher pass replaces the row, a pass at an equal or lower grade leaves it as it is and the decision gets the status `unchanged`. A failed attempt does not change the category. The domain has no category revocation; the row leaves only through the cascade of an account deletion. - -`basis` is the same value as the `source` of the category decision. Today it is always `synthetic_demo`: the database accepts only the demonstration source and `calibration_status = uncalibrated`. The candidate card and the organization search therefore show such a category as a demonstration, not as a validated measurement. The basis is required in every category object, so a category without a basis cannot look like a standard confirmation. - -### Code runner - -Code practice runs in the own `runner/` service; Judge0 is not used (GPL license, owner decision). The service receives the source, the limits, and the test groups through the internal `api/runner/` contract, runs every test in nsjail, and returns the outcome of every group. The backend computes the 0-3 score from the three hidden groups; the runner only reports which groups passed. - -The A16 boundary. Untrusted code runs only on a separate runner host. The target production placement is a dedicated LXD VM on the app host (2 vCPU, 3 GB, one concurrent run) attached to a private bridge without internet access; the backend reaches it over TLS with a bearer token. A privileged container on the core host is forbidden, and a Docker network alone is not a boundary. The runner host holds no business secrets: only its TLS key and the API token. - -Isolation layers of one run (implemented): - -- nsjail in run-once mode: new network (empty, without loopback), PID, mount, IPC, UTS, user, and cgroup namespaces, `no_new_privs`, dropped capabilities, the user uid/gid 99999 inside and outside the user namespace, and no `/proc`. -- File system: the jail root is a read-only tmpfs; only `/usr` and `/lib` (the interpreter) are mounted read-only, the run directory with the source is mounted read-only as `/box`, plus `/dev/null` and `/dev/urandom`, and the working directory `/tmp` is a size-limited tmpfs. The run directory is removed after the run, and its root is emptied at startup. -- cgroup v2: the supervisor creates the cgroup of every run itself (`memory.max` with a small allowance for nsjail, `memory.swap.max=0`, `pids.max`, `cpu.max` for one CPU) and starts nsjail directly inside it with CLONE_INTO_CGROUP. The limits therefore cover the whole process tree, and the OOM, refused fork, and CPU counters are exact. -- rlimits: CPU, file size, open files, core 0, and address space. -- seccomp (kafel): the process is killed on ptrace, mount and namespace calls, keyrings, bpf, perf, userfaultfd, io_uring, kernel modules, and clock and swap administration; clone with namespace flags kills the process, clone3 answers ENOSYS, and sockets other than AF_UNIX answer EAFNOSUPPORT. -- The supervisor checks CPU, wall clock, OOM, and the process limit every 10 ms and, when a limit fires, kills the jailed processes but keeps nsjail so that it reaps its child; if nsjail does not exit within a second, the whole cgroup is killed. After a run the cgroup is removed only once it is empty. - -The service bounds concurrent runs (1 by default) and answers 503 `runner_busy` when no slot is free; the backend keeps the queue. The contract and the configuration bound the request body, the source, the inputs, and the output. Logs carry only the method, operation, status, duration, run ID, language, group and test counts, and outcome; the source, test data, program output, and token never reach a log. Runs live only in memory and are forgotten after their TTL; the backend resubmits a run lost in a restart. - -Languages. Python 3 runs on the image's interpreter in isolated mode after a syntax check with `compile()`. Go is compiled in a separate phase with its own limits (20 s CPU, 768 MiB, files up to 64 MiB): `go tool compile` and `go tool link` run in separate jails and read a standard library prebuilt into the image through an importcfg, so they need no build cache, modules, cgo, or network, and only the standard library can be imported. A run directory consists of the source (`/box`, read-only) and the build output (`/out`): only compile steps write it, and tests see it read-only. A compile or link error is `compile_error` with the compiler message, and no test runs. - -A checker is set per group: `exact`, `tokens`, `numbers` (numeric tokens are equal within an absolute or relative tolerance), and `custom`. A custom checker is a task family program in Python or Go; it is built once per run and runs in nsjail with the same isolation as the solution and limits of its own (5 s CPU, 256 MiB). It receives the input, the expected output, and the actual output as read-only files in `/check` and answers with its exit status: 0 accepts, 1 rejects, and anything else is a checker failure, that is, `infrastructure_failure`. Its output is discarded. The result is returned per group; hidden test content, program output, and hidden test diagnostics never reach the response. - -Outcomes distinguish `accepted`, `wrong_answer`, `compile_error` (for Python, a syntax check with `compile()` before the tests; for Go, compile and link), `time_limit_exceeded`, `memory_limit_exceeded`, `output_limit_exceeded`, `runtime_error` (including the process limit), and `infrastructure_failure`. Test time is the CPU time of every process of the test, including interpreter startup; memory is the cgroup peak of the test, including nsjail and file cache charged to the test. - -Planned and not implemented: deployment of the runner VM with TLS, firewall, and monitoring; scoring the verdict of a final solution (the port, its client, the stored submissions, and the run queue are implemented, see below); service metrics; running the A16 suite on the runner VM. - -The A16 hostile-program suite (`make -C runner test-a16`, see [checks](TESTING.md#a16-hostile-program-suite)) is implemented and passes locally. Code practice is enabled only after the suite has passed on the runner VM with the verdict `pass`; any failed case blocks enabling it. - -#### Backend port and client - -Implemented: the outbound `CodeRunner` port (`backend/internal/port/outbound/code_runner.go`), its client over HTTPS (`backend/internal/adapter/secondary/code_runner/`, built on the generated client in `api/`), and the disabled runner (`code_runner/disabled/`). Bootstrap selects the runner from `CODE_RUNNER_URL` (`bootstrap/code_runner.go`): an unset URL selects the disabled runner, a set one the client, and an unusable setting stops startup instead of falling back. The practice queue worker calls the port (see [Practice queue](#practice-queue)); scoring is planned. The environment variables are in [DEPLOY.md](DEPLOY.md#code-runner-client). - -- What leaves the backend. A request holds the language, the source, the technical limits, and the test groups with their checkers; the checker program of a task family is part of a group. It holds no account, attempt, task, or company identifier and no name or contact. `CodeRunRequest.Validate` checks the runner contract rules (ranges, unique IDs, checker parameters, the CPU budget of 300000 ms, the payload size) before anything is sent. A request prints as `[redacted code run request]` in every format and in logs, because the source is candidate work and the hidden tests are task secrets. -- Two calls, no hidden retries. `Submit` is idempotent by run key and reports `running`, `finished`, or `busy`; `Poll` reads the run without sending the payload again. Each makes one runner call and neither retries nor sleeps. `busy` is the runner's 503 `runner_busy`: the runner stored nothing, `RetryAfter` carries its `Retry-After`, and the caller keeps the queue and submits again with the same key. When the runner has lost a run (a restart or the retention time), `Poll` returns `ErrCodeRunNotFound` and the caller submits again. -- Opaque idempotent run ID. The run ID is HMAC-SHA256 over the attempt item ID, the submission ID, and a generation counter, keyed with `CODE_RUNNER_RUN_KEY` and domain-separated, formatted as a UUID. A retry of the same submission therefore reuses the run and the runner starts it once, while the runner cannot link an ID to an attempt or a submission and nobody can guess the ID of another submission. The key differs from the service token, which the runner knows. After a run the runner could not evaluate, the caller raises the generation: the runner keeps the stored failure under the old ID. The same key with another payload is refused (`ErrCodeRunKeyReused`). -- Infrastructure failure is never a verdict. `finished` always holds a validated result with the outcomes `accepted`, `wrong_answer`, `compile_error`, `time_limit_exceeded`, `memory_limit_exceeded`, `output_limit_exceeded`, and `runtime_error`, per group and test. Everything else is an error: `ErrCodeRunnerUnavailable` is the umbrella for a disabled runner, an unreachable one, a timeout, a failed TLS check, a rejected token (`ErrCodeRunnerUnauthorized`, HTTP 401), a server error, an answer outside the contract (`ErrCodeRunnerBadResponse`), and a run that finished with `infrastructure_failure` (`ErrCodeRunnerInfrastructureFailure`). With such an error the returned status is empty. A caller must report the practice as unavailable and keep the submission ungraded; it never scores, fails, or accepts it. A request the runner rejects as invalid (400, 413) is `ErrInvalidCodeRunRequest`, a bug of the task content, not of the candidate. -- Response validation. The generated client already checks the schema. The adapter adds the rules the schema cannot express: the run ID equals the one derived, a `running` run has no result, a 202 answer is `running`, the groups and tests of the result are the requested ones in order with the requested counts, a group stops at its first failed test, `passed_tests` equals the accepted tests, and the group, compile, and run outcomes agree with each other (the run outcome is `compile_error` or the outcome of the first failed group). A hidden test never passes on a diagnostic, even if a faulty runner sends one. A body above 4 MiB fails. -- Transport. TLS 1.3 only, the runner certificate is verified against the configured CA alone (the system roots are not trusted; there is no switch that skips verification), the optional `CODE_RUNNER_SERVER_NAME` changes only the name checked, redirects and environment proxies are not followed, one request is limited by `CODE_RUNNER_REQUEST_TIMEOUT`, and the token is sent only in the `Authorization` header and appears in no error or log. Error texts name the failure class, never the URL or the response body. - -What the checks cover: the fixture tests run the client against a local TLS 1.3 stand-in that speaks the `api/runner` protocol (success, every outcome, compile error, runner timeout, busy, 401 and 5xx, malformed and contradictory answers, a stopped service, a foreign CA, TLS 1.2, idempotent retry). They do not prove sandbox isolation or behavior on the production runner VM. The run on a real runner is `make -C backend test-code-runner-live` (see DEPLOY) and has not been performed against the runner VM. - -#### Practice submissions - -Implemented: the storage of practice items, their submissions, and the execution jobs, separate from the attempt snapshot and the result. Code: migration `00052_create_assessment_practice_submissions.sql`, the domain `backend/internal/domain/assessment_practice.go`, the port `outbound.AssessmentPracticeRepository` (`port/outbound/assessment_practice.go`), the repository `adapter/secondary/postgres/assessment_practice.go`, the usecase `backend/internal/usecase/practice/`, the handler `adapter/primary/http/v1/practice.go`, and the wiring `bootstrap/practice.go`. - -- Three tables. `assessment_practices` holds one practice item of an attempt, `main` or `additional` (one of each per attempt), with its private task content in `task` (languages, the source length bound, limits, the checker, the public examples, and exactly three hidden groups) and its state: `not_started`, `pending`, `finished`, or `failed` with `sandbox_busy` or `sandbox_error`. Its ID is the item ID the candidate sees and the attempt item of the run key. `assessment_practice_submissions` holds every submission: the mode `public` (a debug run) or `final` (the graded solution), the language, the source with its SHA-256, the candidate's own tests of a debug run, the idempotency scope, and the result, written once. `assessment_practice_jobs` holds the execution job of every submission. Triggers keep the identity and the task of a practice and the request part of a submission immutable: the database refuses to replace the source or the language of a stored submission, to write a second result, and to delete a submission other than by the cascade of its account, attempt, or practice. -- Transactional queue. A submission and its job (`queued`) are inserted in one transaction, so a job exists exactly when its submission committed, and a worker picks it later. The job table is the outbox of the runner: nothing outside PostgreSQL has to learn about a submission before it runs, so no Kafka event is written. -- Debug runs. `CreateMyAssessmentPracticeRun` (`POST /api/v1/me/assessment-attempts/{attempt_id}/practice-runs`) stores a `public` submission and answers 202 with the queued run; `GetMyAssessmentPracticeRun` reads it. A debug run carries the public examples and up to ten tests of the candidate and never a hidden group: the request built for the runner has none, and the response maps only the public groups of a stored result. The task content, the hidden tests, and the source never reach a response. A debug run changes neither the practice state nor the attempt version. -- Final solutions. `practice.Service.SubmitFinal` stores a `final` submission with its job and marks the practice `pending`. The stored solution sent again (the same language and source) stores nothing; another solution is refused while the practice is `pending` or `finished`, so the source of a graded solution never changes; a practice that failed in the sandbox accepts a solution again. No HTTP operation calls it yet: `SubmitMyAssessmentAnswer` will, once the attempt flow serves practice items, and then the attempt version advances in the same transaction. -- Gates. A practice accepts commands only while it is the current item: its attempt is in `practice_pending` (main) or `additional_practice_pending` (additional) and before its deadline, read under a share lock of the attempt. The account must be a verified candidate. Every read is scoped by the owner, so an attempt, practice, or run of another candidate reads as not found. Without `CODE_RUNNER_URL` the operations answer 503 and store nothing. -- Idempotency. A command reserves the generic idempotency record of its scope (a keyed digest of the operation, the key, and the account) in its transaction. A repeat with the same body within 24 hours returns the stored run or the current practice state, and another body answers `idempotency_key_reused`. Refusals are not stored and are evaluated again. - -The attempt flow does not serve practice items yet, so no practice exists in production; the assignment (`AssessmentPracticeRepository.Create`) is called by tests only. Retention of stored sources is not defined yet. - -#### Practice queue - -Implemented: a durable queue with one running and ten queued jobs. Code: migrations `00053_create_assessment_practice_queue.sql` and `00054_add_practice_job_runner_run.sql`, the port `outbound.PracticeJobStore` (`port/outbound/assessment_practice_queue.go`), the store `adapter/secondary/postgres/assessment_practice_queue.go`, the executor `usecase/practice/execute.go`, the worker `backend/internal/worker/practicequeue/`, and the wiring `bootstrap/practice.go`. It is not the scheduled job runtime: a scheduled job runs its handler inside the transaction that completes it, while a practice try waits seconds or minutes for an external run, and no transaction may stay open that long. - -- States. A job is `queued`, `running` (under a lease of one worker), `finished` (its result is stored), or `failed` (the infrastructure gave up; never a verdict). It records the generation of its run key, the counted attempts, when it may be claimed (`available_at`), the lease, the start of the running try, and the class of the last failure. -- Atomic limits. Admission and the claim take the same transaction-scoped advisory lock and count the unfinished jobs. A command is admitted only while fewer than eleven jobs (one running and ten queued) are unfinished; the claim runs a job only while no other running job holds a live lease, so at most one job runs across all backend instances. A debug run beyond the limit answers 503 with `Retry-After` and stores nothing. A final solution beyond it stores nothing either: the practice becomes `failed` with `sandbox_busy`, which consumes nothing and accepts the solution again. The claim prefers a running job whose lease expired, then final solutions before debug runs, and skips rows that another transaction locks, so it never waits for a row lock while it holds the queue lock. -- One try. The executor builds the runner request from the stored task and submission, submits it, and polls the run every `PRACTICE_POLL_INTERVAL`, renewing the lease each time. A finished run stores the result once (`result IS NULL` guard), finishes the job with the opaque run ID of the runner run (`runner_run_id`, unique, set only on a finished job), and, for the latest final submission of a pending practice, finishes the practice, in one transaction guarded by the lease owner and the start of the try. A busy runner puts the job back for the time it asked for (1 s to 1 min) without counting an attempt. A runner that is unreachable, refuses the token, or answers outside its contract is retried with the same run key after a backoff (2 s doubling to 1 min); a run the runner could not evaluate, or a key it holds with another payload, is retried with the next generation, so the next try is a new run; a lost run is submitted again. After `PRACTICE_JOB_MAX_ATTEMPTS` counted attempts, or for a task that cannot form a valid request, the job fails and a final practice becomes `failed` with `sandbox_error`; nothing is graded. A run that stays unfinished for 10 minutes counts as a failed try. -- Runner isolation. The runner request carries the language, the source, the limits, and the test groups, nothing else: a debug run has the public examples and the candidate's own tests, a final solution the hidden groups only. The attempt item, the submission, and the generation reach the runner only as the opaque run ID, an HMAC under `CODE_RUNNER_RUN_KEY`, so the runner cannot link a run to a candidate. The stored `runner_run_id` is that ID: it lets an operator match a stored result to the runner's own log line without the runner learning who the candidate is. -- Repeats. A response lost or cut after the runner accepted the run, a request timeout, and a restart of the worker all end in a retry with the same run key, so the runner returns the run it already holds (200 instead of 202) and starts none. The result is written under the lease of the try and the `result IS NULL` guard, and the database refuses a second result, so a run has at most one result and one `runner_run_id`. -- Infrastructure failure. A runner that is stopped, unreachable, or answers outside its contract never produces a verdict. While tries remain, a debug run reads as `queued`, which tells the client to read it again; after the last try it reads as `failed` with `sandbox_error` and no result, a final practice becomes `failed` with `sandbox_error`, and neither changes the attempt, its result, or the confirmed category of the candidate. A new debug run or final solution is accepted at once. -- Restart. A worker that stops gives its job back at once without counting. A worker that dies leaves the lease to expire; the next claim takes the job over with the same generation and counts one attempt, the runner returns the run it already has, and the result is stored once. A late completion by the dead worker changes nothing, because the job no longer belongs to its try. -- Debug run limits. Besides the queue, a candidate gets at most `PRACTICE_RUNS_PER_MINUTE` and `PRACTICE_RUNS_PER_HOUR` new debug runs (the Redis limiter, keyed by a keyed digest of the account) and one unfinished run per practice; both answer 429 with `Retry-After`. A limiter failure refuses the run as unavailable. -- Off without a runner. Without `CODE_RUNNER_URL` the worker does not start, and the operations answer 503 and store nothing. Several backend instances may run the worker; the claim keeps one job running among them. - -Logs carry the submission ID, mode, generation, attempts, and error class, never the source, the tests, or the account. Queue metrics are not implemented yet. - -## Matching and explanations - -Implemented as a deterministic search that never calls ML and reads precomputed vectors (see [Semantic layer and explanations](#semantic-layer-and-explanations)): `POST /api/v1/organizations/{org_id}/matches` (`SearchOrganizationMatches`, [api/README.en.md](../../api/README.en.md#match-search)). Code: the usecase `backend/internal/usecase/matching/` (`search.go` the flow, `filter.go` the filters, `score.go` the integer scoring, `explain.go` the explanation), the card list `candidateview.Service.ListVisibleCards`, the policy section `domain.MatchingPolicy` (`policy_matching.go`), the skill relations `domain.RelateEvidenceSkill` (`evidence_relation.go`), the handler `adapter/primary/http/v1/matches.go`, and the wiring `bootstrap/matches.go`. Visibility has no new query: the search reuses the barrier queries that the card and the evidence already use, so there is one copy of the visibility rule. - -- Access before ranking. The search is one transaction. The owner role is checked under the membership lock before any card is read. `ListVisibleCards` then runs the checks of a card read: verified employer, then `ListVisibleCandidateViewSources`, which selects from `candidate_effective_publications` (published and backed by an unrevoked C2) and excludes the candidates that hide the reading organization with `NOT EXISTS` over `candidate_hidden_organizations`; then the account, C2, and publication locks, and the anonymous projection with its minimum cohort of five. The list is therefore exactly the set of handles that `GetOrganizationCandidateCard` opens at that moment: a card that the cohort rules suppress is not searched, a revoked C2, a closed publication, or a hidden organization takes effect on the next request, and nothing is cached or stored. The permitted evidence is read only through the organization-safe batch query `ListOrganizationVisibleEvidenceBatch` (one statement for the whole candidate set, with the barriers of the single read: the effective publication view, `NOT EXISTS` over the hiding, the `categories` field, visible measurements), and only when the request names skills. The locks are those of the card read and nothing else is locked; the writes of the search are limited to the candidates it returns. -- Owner only. For the MVP milestone the active owner of the organization searches. The HTTP boundary refuses every other role (`ownerCompanyOperations`), and the usecase repeats the role check under the membership lock, so a membership alone grants nothing. The full role and assignment matrix is later work and must not widen rights by one membership. -- Charged like card reads. A search returns card content (the confirmed category with its strength and basis, the declared grade, the stack, the experience band, the work formats, and the explanation), so it passes through the same allowance as a card read. The whole visible bank is ranked, and then each group is cut to `max_results_per_group` of the policy version (demo value 10, so at most 30 reveals for one search, below the 50 distinct card views per day of tier E0); no total is returned. Walking the output in the order `main`, `near`, `unconfirmed`, each newly revealed candidate is reserved through the company quota port (`candidateview.SearchViews.Reserve`, the same `ReserveCardView` as a card read: idempotent per organization and candidate inside the window, so repeating the search or opening the card afterwards does not charge twice), and the candidate's access history gets one `card_viewed` entry per search with the fields actually returned (`SearchViews.Record`), all in the transaction of the search. When the allowance ends, the output stops at the first refusal: the entries already paid for are returned, `truncated` is true, nothing is written for the rest, and there is no error. `truncated` is also true when a group exceeded its limit; it carries no count. Opening a card is still the read for the full card. -- One entry per candidate specialization, built from the card the organization is allowed to see. A specialization is confirmed only when the card shows its category (`categories` published and not generalized away); a role that the self-assessment lists as unconfirmed is an unconfirmed entry; a role marked confirmed whose category the card does not show gives no entry, because a result cannot claim a confirmation the candidate did not publish. The same handle can therefore be confirmed in Backend and unconfirmed in Networks, and a Backend confirmation never changes the Networks entry. The status of an entry follows the specialization of the request: a need with a confirmed specialization and a `specialization` filter both restrict it, and two different values leave nothing. A need without a confirmed specialization searches all of them and returns each specialization separately. -- Category basis. Each confirmed category of an entry carries `basis` from the same stored row as the card. Today it is `synthetic_demo`, a demonstration that is not a validated measurement. The organization interface shows it as an ordinary confirmation (standard or strong) while the basis itself stays in the API response; the field is required in `MatchCategory`, so a category without a basis cannot exist. -- Filters, all applied before scoring. `confirmed_grade`, `confirmed_category`, and `confirmation_status: confirmed` keep only confirmed entries; a declared grade never satisfies them. `declared_grade` is a separate claim. `stack` requires every named tag in the card and also counts as a required skill of the request. `conditions.work_formats` needs one common format, and `conditions.salary_compatibility` needs the same value; an unknown card value never satisfies a condition. An unconfirmed category alone hides nothing: without a confirmed filter the declared specializations are listed. -- Requested skills. The skills of the Cov come from the confirmed required (weight 2) and desired (weight 1) skills of the need snapshot, with the tags of the `stack` filter as required. A code is counted once however often it is repeated. A skill without a taxonomy code has no reviewed mapping, matches nothing, and is a gap. An empty request uses the neutral Cov 0.5 instead of dividing by zero. The need is read by `requirements_version` (`GetVersion`); a general version that only changed the title is not a requirements snapshot and answers 404, and the snapshot of an older requirements version stays searchable and unchanged. -- Evidence of a skill. Each requested skill takes the best product of the trust, attribution, and relation coefficients over the permitted evidence, not their sum. The evidence is the stated stack tags of the card (trust 0, a claim) and, for a confirmed entry, the one assessment fact that supports its category (trust 1, personal). The relation is exact for the same code, broader for a specialization over a technology, and narrower the other way, by the `skill_taxonomy` of the policy version (demo: `backend` over `docker`, `go`, `kafka`, `postgresql`; `devops_sre` over `docker`); a version without a taxonomy relates only equal codes, so the version fully determines the result. The taxonomy is a demonstration mapping, not a measured one. An online Backend result is worth 0.6 * 1.0 * 0.4 = 0.24 for a requested Go and a stated Go tag 0.25; the near threshold is 0.25, so a candidate whose only evidence for a required technology is a Backend assessment is always in `near` for it, and a stated tag alone is enough to be in `main`. That consequence of the PRD values is an owner question. Repeating a tag or a skill adds nothing. -- Components and groups. `Cov` is the weighted mean of the contributions; `Dom = 0.5` (the anonymous card carries no domain) and `Sem = 0.5` for an entry without stored vectors, both named in `unknown_flags`; `T = 0.5` with a null percentile and the flag `cohort_below_30`, which the search proves instead of declaring: it counts the candidates who hold each returned category from a source other than a synthetic demonstration (`CountRealComparableCategories`, counts only) and compares the count with `percentile_min_cohort`; today the count is 0 because every stored category is a synthetic demonstration, which is never mixed with real results. A real cohort at the minimum would need the theta of its members, which the organization-safe projection does not carry, so the search never fails for it: T stays the neutral 0.5, the percentile stays null, the reason becomes `percentile_not_computed` instead of `cohort_below_30`, and the search logs one warning for each such category. Only the categories of the entries that passed the filters are counted; `V = 0` because no competition data exists, which is neither a penalty nor an unknown; `Fr = Rsp = 0.5` with the flags `no_freshness_history` and `no_response_history`. A confirmed entry with a required skill below the near threshold (0.25) is in `near`, otherwise in `main`; an unconfirmed entry is in `unconfirmed` with only Fit and Coverage, computed by a separate path that never calculates theta, T, P, a percentile, or S. The absence of FSP is not scored anywhere. -- Order and rounding. Scores are integers in micro units (six decimals), the shares are basis points, and the products are exact integers, so the same data and policy give the same order on every platform. `main` and `near` sort by S, then Cov (both descending), then the internal candidate identifier ascending (then the specialization code, which only separates two entries of one candidate); `unconfirmed` sorts by Fit, then Cov, then the identifier. The identifier never leaves the server, and the groups are not merged on one scale. -- Explanation. The summary and the flags are built from the same computed contributions: per skill group `supports` (every skill carried by a measurement at or above the threshold), `declared_only` (only stated tags), `partial` (a mix, or measurements below the threshold), or `gap` (nothing), plus the confirmed category, the declared grade, the work-format match against the need or the filter, and the salary compatibility. It uses bounded codes only, never free text, a contact, a candidate location, a salary value or minimum, a failed attempt, or a reason for withheld data. An unknown component appears only in `unknown_flags`. -- Policy. The search reads the effective `product` policy at the application time and its `matching` section. A policy without the section fails closed with an internal error (the ProblemCode enum has no code for a temporarily unavailable dependency, and none is added); the error log says that the effective product policy has no matching section and names the `policy-publish` operator command, the backend logs a warning at startup while the section is missing, and [DEPLOY.md](DEPLOY.md#match-search-policy-on-a-stand) describes the command. The response does not name the policy version, and no search is stored. -- Concurrency. The reservations take the exclusive organization lock of the company quota port. A membership check before them holds only a share lock on the same row, and two searches of one organization would deadlock on the upgrade, so the search takes the organization lock first (`CompanyQuotaRepository.LockOrganization`, the documented order; it is FOR NO KEY UPDATE, so readers queue behind each other but the foreign-key lock of a candidate's own hide, which holds the candidate row and then needs the organization row, is not blocked, and the reservation itself still takes FOR UPDATE in the same transaction) and the charges of one organization are serialized. A change of the visible cohort while it is being locked (`ErrConcurrentVisibilityChange`) repeats the whole search up to three times, and its writes roll back with the failed attempt. The card read (`GetOrganizationCard`) and the evidence section (`AuthorizeCategoriesSection`) take the same exclusive lock first, before any share lock, for the same reason: before this order two simultaneous card reads of one organization deadlocked (SQLSTATE 40P01). For an E0 company, `LockOrganization` takes the lock of its holding right after the organization row (the shared E0 pool is described in [Company quotas](COMPANY_QUOTAS.md#holding-pool)), so the order stays the same: the organization, then the holding, and no holding is taken before its organization. `TestMatchSearchOverHTTP` runs concurrent card reads, evidence reads, and searches of one organization and checks for no deadlock and one quota row for each candidate. -- Accepted residual risks. `truncated` is one bit about the size of the visible bank (it says that more than the limit or the allowance exists) and the response time grows with the bank, so both leak a coarse size to the owner. The bit is bounded by the group limit and no count is returned; the risk is accepted for the demonstration and is listed with the owner questions. -- Checks. `internal/usecase/matching` unit tests (formulas with hand-computed values, ties and ordering, filters, explanation, the cut and the charge of the output), `internal/domain/policy_matching_test.go` (document round trip, strictness, validation), `v1/matches_test.go` (mapping and problems), and the integration test `TestMatchSearchOverHTTP` against PostgreSQL: hidden candidates and two organizations, a need and its edited requirements, repeated identical responses, Backend confirmed and Networks unconfirmed for one handle, a profile published without a grade through the real profile, consent, and publication operations and removed by a C2 revocation, a candidate alone in its cohort, no contact or identifier in the body, the charge and the access history of a search, an organization with an allowance smaller than its bank, the group limit, the batch evidence read, two concurrent searches under one allowance, the demo group limit, the policy taxonomy, the denials, and the policy without the section. - -Not implemented: the percentile and a real T (they need the theta of a comparable real cohort of at least 30 people); the competition value V and the FSP data; the domain of a candidate; freshness and responsiveness histories; the stored `search_run` snapshots, refinement, comparison, and the shortlist; paging beyond the group limit; and the use of the grade of a need as a filter. Sending an invitation from a search result is not implemented either, so the revocation of C2 after an invitation is not checked here; the draft of an invitation resolves a handle of the search result through the same visibility barrier (see [Invitation drafts](#invitation-drafts)). - -Before ranking, Go applies hard filters: published profile, specialty, verified grade, required skills, and other selected criteria. A strong resume or achievement cannot compensate for a missing mandatory requirement. Distinguish an unverified skill from evidence that the skill is absent. This is the first model, not an optimized or measured ranking: the plan compares keyword search, the verified-skill baseline, and an ML variant, added the semantic signal after the study (see [Semantic layer and explanations](#semantic-layer-and-explanations)), and never treats its score as a probability of hiring success. - -Store each search as a search_run with its company, original need, filters, ranking version, and parent version. Refinement creates another snapshot. search_items stores order, scores, and profile versions without contacts. An old snapshot does not preserve access: hidden or removed profiles disappear, stale ranking is marked, and retention is bounded. This is planned; the implemented search stores nothing. - -### Semantic layer and explanations - -Implemented: embeddings of needs and published cards, `Sem` in Fit, a structured "why in the selection" explanation, candidate projects, and checks of their GitHub repositories. The basis is the LincodexMatch study (DEV 30 needs, TEST 70, 2594 synthetic profiles); its numbers come from synthetic data and are not product measurements. - -- Model. `ai-sage/Giga-Embeddings-instruct-480M-0826` (MIT) at revision `1763d603adac8057bd6482a708001b0ed2e0a903`, float32, 1024 dimensions, up to 1024 tokens a text. On TEST it is best on indirect matches (nDCG@10 indirect 0.571 against 0.409 for Qwen3-Embedding-0.6B) and meets the CPU targets with 4 threads (profile p95 352 ms, search over 100k 591 ms in the study). The recipe repeats the study: the need and each requirement are encoded with the prompt `Instruct: Given a query, retrieve relevant passages\nQuery: `, the card and its items without a prompt, mean pooling over the attention mask including the prompt tokens, L2 normalization. The remote code of the model repository is neither fetched nor executed: the same bidirectional Qwen3 is written in `ml/src/lincodex_ml/inference/giga.py`, and `make -C ml test-model` compares the vectors with the study's (difference < 1e-6). -- ML service. `POST /v1/embeddings` of the `api/ml` contract (up to 32 texts of 8000 characters, a body up to 2 MiB, an optional model id `model`, a response with id, revision, dimension, and `prompt_version`). The service loads the models of the `ML_EMBEDDER` list (`giga`, `qwen3`; the first answers a request without `model`); a request for a model it did not load gets 400 with the pointer `/model`. Each model is pinned by a lock file (`ml/model/giga-embeddings-480m.lock.json`, `ml/model/qwen3-embedding-0.6b.lock.json`) with SHA-256 verification (safetensors, configs, and the tokenizer only); no remote code runs and the service works offline. The device is `ML_DEVICE` (`cpu` by default or `cuda`), the precision `ML_DTYPE` (`float32`; `float16` and `bfloat16` on CUDA only), and `ML_CUDA_MEMORY_LIMIT_MB` caps the allocator of the process on a shared GPU. A lack of device memory never stops the process: a load is retried with a growing pause (15 s, up to 5 min), a request answers 503 `service_unavailable`, and `/readyz` answers 503 for 30 seconds, after which the service serves again. Readiness turns ready only after every model is loaded and a warm-up encode has finished. Texts are encoded one request at a time in micro-batches of a fixed size (default 1), ordered by length with the request position as the tie-breaker, so the same texts on the same installation, device, precision, and thread count give the same vectors (on CUDA checked by a repeated encode). Every route except `/healthz` and `/readyz` requires `Authorization: Bearer ` (see [SECURITY.md](SECURITY.md#outbound-requests-and-ml)). -- Fields that rank. Only what the anonymous card of the candidate shows before cohort generalization: the roles of `self_assessment` and `categories` (`backend (middle)`), the recognized stack codes, and the published projects with the public metadata of verified repositories. Private profile text (resume, experience `summary`, employers) does not enter ranking, as before for ML ("Go sends only allowed inputs"). The study shows that private experience improves quality (proposal 3 of the report); allowing its server-side use without showing it is an open owner decision and needs an explicit privacy policy decision. -- Vectors. Table `semantic_vectors` (migration `00049`): the subject (`candidate` or `need`), the item key (`whole`, `roles`, `stack`, `project:`, `required_skill:`, `desired_skill:`, `task:`), the SHA-256 of the text with the rendering version `semantic-views-v1`, the model, revision, prompt version, dimension, and the vector as little-endian float32 (4 KiB for 1024 dimensions: exact and the same on every platform; int8 is deferred until size becomes a problem). Rows cascade with the account or the need. A candidate keeps exactly one set per model, a need the set of its latest requirements snapshot. -- Pipeline. A profile save, a publication change, a new requirements snapshot, and a finished repository check schedule a due job (`semantic.candidate`, `semantic.need`) in the same transaction; no user request waits for ML. The handler takes an advisory lock of the subject, renders the current card or snapshot, compares the digests with the stored ones (unchanged texts cost no ML call), encodes the texts, and replaces the set. The job encodes the texts with every model of the policy `members`, passing its id; the first model stores every item, the others store `whole` only. The model of the response (id, revision, prompt version) must equal the policy model, otherwise the job is retried. Up to 20 attempts with backoff outlast an ML outage; the job of an unpublished candidate removes their vectors. A C2 revocation closes the card in another usecase and schedules no job: the vectors stay until the next candidate job or a backfill, but an invisible card never enters a search. The `semantic-backfill` command schedules jobs for every candidate with a profile and every need page by page, idempotent per run label and resumable by cursor. -- Sem and Fit. The search never calls ML: it renders the need snapshot, reads the vectors with matching digests and the `whole` vectors of the visible candidates for every policy model, computes the fused score Σ w·(cos - mean)/std, and turns it into `Sem` with the isotonic calibration of the policy (P(relevant | score) on DEV, ECE 0.015-0.049 against 0.17-0.57 for the raw cosine) by integer interpolation. By default there is one model with weight 1, mean 0, and std 1, so the score is the cosine. Without vectors of the need or the candidate for any policy model, or without ML, `Sem` is the neutral 0.5 with `ml_unavailable` for that entry, as before. The candidate set, filters, visibility, quotas, and cohort rules do not change; BM25 is not mixed into the score (on TEST it cuts indirect from 0.571 to 0.250). -- Policy. `domain.DemoProductPolicyV5()` is V4 with the semantic section `matching.semantics` (`members` - one Giga model with revision, prompt version, weight 1, mean 0, and std 1; 80 calibration points `score_bp`, explanation thresholds, limit, source) and Fit weights 0.4167 / 0.0833 / 0.5. With the PRD weight 0.10 Fit reaches nDCG@10 0.649 on TEST against 0.818 for the encoder alone, with 0.5 it reaches 0.838; Cov and Dom keep the PRD ratio 5:1. V4 stays the previous version (the PRD point). Publication: `make -C backend policy-publish ARGS='semantic --actor operator:'`. -- Ensemble. S5-DE of the study is implemented: `Sem` = calibration(0.4·z(Giga) + 0.6·z(Qwen3-Embedding-0.6B)), `domain.DemoProductPolicyV6()` (V5 with the section `DemoSemanticEnsembleMatchingPolicy`, the same Fit weights). The second model is `Qwen/Qwen3-Embedding-0.6B` (Apache-2.0) at revision `97b0c614be4d77ee51c0cef4e5f07c00f9eb65b3`, a stock Qwen3 without remote code: the need is encoded with the model's prompt `Instruct: Given a web search query, retrieve relevant passages that answer the query\nQuery:` (joined without a separator), the card without a prompt, the tokenizer appends end-of-text, and the vector is the hidden state of the last token, L2-normalized (`prompt_version` `qwen3-card-last-v1`, `ml/src/lincodex_ml/inference/qwen3.py`, compared with the study's vectors by `make -C ml test-model`). The weights 0.4 / 0.6 are the step 5 choice of the study (5-fold CV over the DEV needs, w_giga = 0.4 in four folds of five). The mean and std were computed again on product views: the study's needs and profiles were rendered by the product view builder (`domain.NewNeedSemanticDocument` gives the study's text for all 100 needs; the card has the catalog roles with the declared grade, the card stack codes, and one published project per study experience entry) and encoded by the ML service on CUDA in float16. The mean is over all DEV pairs (Giga 0.2497, Qwen3 0.3636), the std is the pooled within-need deviation (0.0741 and 0.0731), so the fixed z reproduces the study's z over the corpus of each need: DEV nDCG@10 all / indirect 0.809 / 0.518 against 0.809 / 0.518 for the study's form and 0.738 / 0.403 for Giga alone on the same views. The calibration is the isotonic regression of P(consensus >= 2) on the fused score of the 3220 judged DEV pairs (994 positive), computed with the rounded mean and std of the policy; 56 points, 5-fold CV ECE by need 0.025. The explanation thresholds stay those of Giga (the first model, which alone provides item vectors). The provenance is in the policy `source` and in [DEPLOY.md](DEPLOY.md#semantic-matching). Without projects on the card the signal is weak (DEV nDCG@10 0.21 for the ensemble and 0.23 for Giga alone on cards with roles and stack only), so the gain of the ensemble depends on candidates publishing projects. Publication and backfill: `make -C backend policy-publish ARGS='semantic-ensemble --actor operator:'`, then `semantic-backfill` for candidates and needs. Jobs compute vectors for every model of the effective policy, so until the backfill ends, entries without Qwen3 vectors get the neutral `Sem`; switch at a quiet time. The Giga vectors are not recomputed (same digests), and V5 stays the previous version: the vectors of both models stay, so a rollback to Giga needs no recompute. -- Explanation. For a need search every confirmed requirement (required and desired skill, task) is paired with the closest card item by cosine. Thresholds from DEV: P(pair relevant | best cosine of the requirement) 0.5 and 0.7, for skills 0.3673 / 0.4607 (`medium` / `high`), for tasks 0.2997 / 0.4192. The response carries `semantic_evidence` items: the kind and text of the requirement (the organization's own need text), the item kind (`project`, `stack`, `roles`), the project title only when the candidate published the `projects` field and the title did not change since the vectors were computed, `repository_verified`, and the band; ordered `high` first, then by cosine, then by requirement order; at most 6 (policy). The stack and roles explain only while the card shows them to this organization after cohort generalization. No model text enters the explanation. Showing a project title is recorded in the candidate's access history as the `projects` field. The precision of the explanations was not checked: the study's sample of 50 pairs remained unlabeled. - -#### Candidate projects and GitHub repositories - -- Profile. Section `projects` (up to 10): a title up to 100 characters, a description up to 500, up to 10 stack tags, an optional repository address. Only `https://github.com//` is accepted (a trailing slash and `.git` are removed; other hosts, ports, credentials, paths, queries, and fragments are rejected), each repository at most once. Projects are trust level 0 claims in `candidate_profile_claims` (kind `project`, migration `00048`) versioned with the profile through `expected_version`. A body without `projects` keeps them, so an older client never deletes them. -- Card. A new publication field `projects`: the card shows the title, description, tags, and `repository_verified`, never the repository address or owner. The title is the candidate's text and can identify them, so the field is a separate choice, takes no part in cohort generalization, and the client must warn about it (open owner question). -- Check. A new or changed address schedules `profile.repository_check`; `POST /api/v1/me/profile/repository-checks` repeats the checks of all repositories at most once per `REPOSITORY_CHECK_INTERVAL` (default 10 minutes, else 429). The job key and payload carry only a digest of the repository. The handler reads `api.github.com` (metadata, languages, the beginning of the README), stores the state `pending`, `verified`, `not_found`, or `unavailable` in `candidate_project_repositories`, ETags for conditional requests, and the metadata only while the repository is public. The README becomes plain text (no code, HTML, links, or URLs); up to 4000 characters are stored and up to 600 enter the card text for ranking; none of these fields is returned by the API or shown. A GitHub limit (403/429) stores `unavailable` and reschedules the check at the reset time (1 minute to 1 hour); network and server failures are retried by the worker. "Verified" means only "the repository exists and is public": authorship is not proven, and the owner is not compared with an account of the candidate. -- Contacts after C4. The repository address is not added to the C4 disclosure: the C4 consent in the ledger fixes a closed field set (`full_name`, `email`, `phone`, `telegram`, CHECK in `00009` and `00030`), and extending it needs a new consent text version and a ledger migration. Until the owner decides, an organization gets the address neither before nor after C4. - -## ML, documents, and background jobs - -Embeddings for matching are implemented (see [Semantic layer and explanations](#semantic-layer-and-explanations)). Further planned ML operations are resume analysis, need analysis, and limited reranking. Go sends only allowed inputs and a short candidate list. Responses are limited to known IDs and validated against schema and version. ML failure falls back to the baseline. Models cannot set categories or expose contacts. - -Planned PDF flow: limit size, page count, and upload rate; validate file type and owner; save a source version; create a job in the same transaction; extract text in an isolated resource-limited environment; mask contacts; request a structured result; validate its size and versions; show proposed fields for candidate approval. A scan without a text layer reports that state and offers manual entry; OCR is a separate extension. Never log full resume text or traces. - -Resume text is untrusted data, not an instruction to tools. ML does not follow arbitrary links, run commands, or verify whether employment claims are true. Each proposed field records its evidence and limitations. - -A standardized PDF is required in the product even when profile entry is manual. PDFRenderer consumes structured profile data. The planned approach is controlled HTML and isolated headless Chromium with Cyrillic fonts, no external network fetches, and no user-supplied HTML. - -Jobs that only need to run at a due time use the implemented runtime in [Scheduled jobs](#scheduled-jobs). Future ML and document jobs, which a user waits for, use queued, running, succeeded, failed, and cancelled states, an attempt limit, available_at, lease/heartbeat, and a safe error code. Claims are atomic. An expired lease permits retries; operation key, document version, and lease token prevent stale workers from overwriting newer results. Computation may repeat; a business effect must not. Retries are bounded and use backoff. - -Long operations return 202 and a job ID. The UI polls with a widening interval and stops after completion or page exit. The browser never calls ML directly. Routine tests do not download a model or require GPU. Model, license, inference budget, and production latency are unselected. +Events carry minimal identifiers and facts without contacts or secrets; logs exclude secrets and personal data. Mail contains only data allowed for its recipient; a verification message includes the required one-time link and code. See [DEPLOYMENT.md](DEPLOYMENT.md) for startup and configuration. ## Identity, FSP, and privacy -The initial product plan uses email/password, email verification, and server-side PostgreSQL sessions. Browser cookies are Secure, HttpOnly, and SameSite; mutating requests use CSRF protection. Hash passwords with a suitable KDF. Tokens are random and expire; store their hashes. Require email verification before publishing a candidate or sending invitations. +Login uses email/password, Argon2id and PostgreSQL sessions. Email can be verified by link or code. The `__Host-lincodex_session` cookie is `Secure`, `HttpOnly` and `SameSite=Strict`; mutations check Origin, and protected operations also check session-bound CSRF. The identity secret must remain consistent across instances and restarts. -Future FSP identity linking requires provider verification. A manually entered identifier or matching email is not enough to merge accounts. The brief supplies no real FSP API, so development starts with a fixture provider and a project-owned DTO. If organizers provide Keycloak/OIDC, add Authorization Code + PKCE and validate issuer, state, nonce, audience, and redirect URI. Lincodex still owns roles and contact grants. +| Consent | Purpose | +| --- | --- | +| C1 | Basic account data processing | +| C2 | Profile publication for organizations | +| C3 | Automated categorization | +| C4 | Selected contacts for a specific organization | +| C5 | Import of FSP results | -The brief references Russian Federal Law 152-FZ. The system design calls for separate processing/publication consents, revocation, transfer controls for ML, and retention/deletion periods. Architecture documentation does not prove legal compliance. Agree on data handling before using real personal data; use synthetic profiles for the demo. +Consent texts and records are versioned. Built-in texts are marked `demo`; real data requires the actual operator's texts and processing terms. Consent records alone do not establish legal compliance. -### Identity storage +Profiles are closed by default. Organizations receive an allowed anonymous projection only with active C2, publication and no organization hiding. Small-cohort rules generalize fields and withhold cards when an anonymous group cannot be formed. Names, contacts and private profile text are excluded. -Identity storage is implemented in migration `backend/db/migrations/00002_create_identity_tables.sql`, the queries in `backend/db/queries/identity.sql`, the domain types, outbound ports, and the PostgreSQL adapter. The backend API implements registration, verification resend, `ConfirmEmail`, login, and basic current-session operations. The frontend registration and confirmation screens are implemented; see the [API contract](../../api/README.en.md#identity-sessions-cookie-and-csrf). +Accepting an invitation with C4 creates a grant for selected fields and one candidate-organization pair. Every read checks current rights. Revoking C4/C2, closing publication or hiding the company stops access; publishing again does not revive an old grant. -- `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 allowed purposes, so 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`. Migration 00014 adds `pending_password_hash`, `pending_scenario`, and `pending_onboarding_step`, so each token carries its registration data. A CHECK allows at most one of consumed and invalidated. Migration `00046_add_email_verification_codes.sql` adds `code_hash` (HMAC-SHA-256 of the six-digit code under a server key, NULL when the token carries no code or the code has ended), `code_expires_at`, and `code_failed_attempts` (0 to 5). The code expiry is the earlier of the token expiry and the 30-minute code lifetime, and the application checks both on every use. -- `sessions`: a UUIDv7 `id` that never leaves the server, `token_hash` (SHA-256 of the cookie value, unique), `user_id`, `created_at`, `last_seen_at`, the absolute `expires_at`, and `revoked_at`. No IP address or user agent is stored. -- Tokens and sessions reference `users` with `ON DELETE CASCADE`. Consent records reference it with `ON DELETE RESTRICT` instead; see [Consent ledger](#consent-ledger). CHECK constraints repeat the domain rules as a backstop: the ASCII address and its key, the PHC format, and timestamps (verification, consumption, invalidation, and revocation) not earlier than `created_at`. +Organization operations check membership on the server. Search, invitations and contact access currently require the owner; other roles must not be treated as connected. Companies with one founder share the E0 quota pool. -Decisions: +FSP ID and real FSP data are not integrated. Manual profiles and tests do not depend on them. A future integration needs an official provider contract; a manually entered ID or matching email does not prove external identity. -- Email addresses are ASCII only, because the mailer has no SMTPUTF8 support. `domain.NewEmailAddress` rejects any non-ASCII character, including homoglyphs and fullwidth forms, with `ErrInvalidEmailAddress`, which the registration handler answers with 400 `validation_failed` whether or not an account exists. Internationalized domains are accepted only in their punycode form (`xn--...`). The key lowercases A-Z only; the database checks it with `translate()`, which does not depend on the collation, unlike `lower()`. Unicode addresses are future work: they need IDNA ToASCII for the domain, a rule for Unicode local parts, and SMTPUTF8 delivery. Rows are read back with `domain.RestoreEmailAddress`, which checks only that the address and key match, so a stricter rule later does not make existing accounts unreadable. -- 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` returns the token after a reload: the server derives it with domain-separated HMAC-SHA-256 from the cookie token and `IDENTITY_KEY_SECRET`, so it needs no database storage. Comparison is constant-time; the session token itself is stored in the database only as a SHA-256 hash. +### Company quotas -What the ports guarantee: +The current demo policy uses sliding limits: E0 gets 10 invitations per 7 days and 50 distinct cards per 24 hours; E1 gets 40 and 150. E2 has 100 and 400 but is disabled until company verification is connected; E3 cannot reserve quota. The database supplies the level, not the client. -- `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 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` coalesces writes with a cutoff equal to the smaller of one minute and half the idle timeout, so frequent requests do not rewrite the row and even the shortest supported idle timeout can be extended; 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. -- Unique and foreign key violations map to `ErrEmailTaken`, `ErrTokenHashConflict`, and `ErrUserNotFound` by SQLSTATE and constraint name, never by error text. -- Lock order: an operation that changes both an account and its tokens locks the tokens first. A confirmation consumes the token and then verifies the account, so a re-registration or resend calls `InvalidateActive` before it updates the account or inserts a token; the opposite order can deadlock. The cleanup is the only exception: it locks the account before the tokens and sessions, which is safe because each of those locks uses SKIP LOCKED and never waits. A deadlock (SQLSTATE 40P01) or serialization failure (40001) that still happens is reported by `Transactor.WithinTransaction` and the identity repositories as `outbound.ErrTransactionConflict`; nothing was committed, and the usecase or job may retry the whole operation with backoff while staying idempotent. +Sending consumes quota; drafting does not. Repeating an invitation consumes no second slot; decline, acceptance and expiry free the pending-invitation limit but do not refund weekly quota. Repeated views of one candidate by one company within the window are free. A record exactly on the window boundary has expired. -### Password hashing +E0 companies founded by one account share the holding pool; E1 and higher companies have their own. Two companies in one holding viewing the same candidate consume two slots. A promoted company's usage leaves the E0 pool. Holding merges and splits are not implemented. -Implemented and tested: registration and login use the hasher created from configuration. +After permission checks, `companyquota` reserves quota in the same transaction as the business action. Lock order is company, holding for E0, membership, invitation/visibility, then usage. A changed policy or trust snapshot requires reloading and retrying the whole transaction. Refusals record no usage; `RetryAt` indicates the next slot release. -- `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; identity HTTP limits are described in the server-side sessions section. -- `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; login does not yet update such hashes automatically. -- `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 calls it for an unknown email and an invalid stored hash, so those branches also perform a full Argon2id verification. -- Login answers `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 also logs an error and calls `VerifyDummy`. A valid password for an unverified account answers `email_not_verified` and creates no session. Verification time is not uniform: unknown emails and corrupt hashes run `VerifyDummy`, while stored hashes with different Argon2id parameters take different amounts of time. -- `identity.Credentials.HashNewPassword` validates a new password and only then hashes it; registration calls it on every branch before looking 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. +Deleting an invitation does not remove its usage record; cleaning old views does not change logical window boundaries. The holding migration refuses rollback while a holding contains several companies. See [TESTING.md](TESTING.md) for concurrency and retry checks. -### Server-side sessions +## Assessment and grade verification -Login, current-session and current-account reads, and logout are implemented in the backend. Every contract-protected operation passes through the session boundary, which resolves a verified principal from an active PostgreSQL session; consent and organization handlers implement their documented operations. Contract operations without an implemented business handler answer 501 after security and request validation. Every unsafe public identity operation (`RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, and `Login`) requires the sole `Origin` value to exactly match `APP_PUBLIC_URL`. Protected unsafe operations also require the session-bound `X-CSRF-Token`. Origin is checked at the HTTP boundary and does not trust `Host` or forwarded headers. The CSRF value is a domain-separated HMAC-SHA-256 derived from the session token, bound to that token, and compared in constant time. `GetCurrentSession` returns it again after a page reload. GET `/api/v1/identity/sessions/current` returns the current session and account, GET `/api/v1/identity/me` returns the current account, and DELETE `/api/v1/identity/sessions/current` revokes the session. Guests and unverified sessions answer 401; a valid session with missing or wrong Origin or CSRF on a protected unsafe operation answers 403 `csrf_check_failed`. +The bank stores immutable family versions, rubrics, variant generators and review metadata. A version and seed reproduce the variant; answer keys stay on the server. Publishing families and opening categories are operator actions. -The cookie is named `__Host-lincodex_session` and has `Path=/`, `Secure`, `HttpOnly`, and `SameSite=Strict`, with no `Domain`; `Expires` and `Max-Age` point to the absolute session expiry. PostgreSQL stores only the SHA-256 hash of the random cookie token, never its value; IP addresses and user agents are not stored. `IDENTITY_SESSION_IDLE_TIMEOUT` defaults to `24h` and accepts `1m` to `30d`; `IDENTITY_SESSION_ABSOLUTE_LIFETIME` defaults to `168h` and accepts `1m` to `365d`. The idle timeout cannot exceed the absolute lifetime; invalid values stop startup. Active requests extend the idle deadline, not the absolute deadline. +An attempt pins its policy, bank, items and deadlines. Answers are persisted on the server; versions and idempotency protect against duplicate writes and concurrent completion. Attempts, results and skill evidence are distinct from candidate self-assessment. -`IDENTITY_KEY_SECRET` must contain at least 32 bytes and stay the same across backend restarts and instances. It also derives the CSRF key with the purpose label `lincodex/identity/session-csrf/v1`; changing the shared secret invalidates old CSRF values but does not revoke PostgreSQL sessions, and `GetCurrentSession` returns the new value. After a successful password check, creation of a new session and revocation of an incoming active session commit in one transaction. A failed login does not revoke the old session. Logout clears an expired or revoked cookie; an Origin or CSRF failure neither revokes nor clears a valid session. +The current full mode, `demo_basic`, uses a synthetic bank rather than an adaptive psychometric model. Category assignment requires enabled demonstration categories and an attested opening; the API basis is `synthetic_demo`, without calibration. The `demo_express` mode assigns no grade, category or evidence. -### Consent ledger +Server and browser signals, watermarks and a manual-review band help investigate suspicious cases. They do not prove cheating, change a grade automatically or provide screen or camera recordings. -Consent storage, registration C1, and the settings read and mutation handlers are implemented: migration `backend/db/migrations/00009_create_consent_ledger.sql`, the deletion-request table in `00018_create_account_deletion_requests.sql`, queries in `backend/db/queries/consents.sql`, domain types in `backend/internal/domain/consent.go`, ports in `backend/internal/port/outbound/consents.go`, and handlers in `backend/internal/adapter/primary/http/v1/consent.go` ([api/README.en.md](../../api/README.en.md#consents)). Public `GET /api/v1/identity/consent-texts/c1` returns only C1; verified sessions can read C1/C2/C3/C5 text and their own history, grant supported purposes, revoke consent, and request account deletion. Registration records C1 in the account creation or re-registration transaction; confirmation checks the C1 record for the token's registration version. The C4 invitation-acceptance handler and the account-deletion worker are not implemented. +### Code runner -The consents C1-C5 of PRD FR01 are independent purposes: a grant or a revocation of one never changes another. +Backend persists practice submissions and queue state, limits load and calls the runner through TLS with a separate token. The runner judges Go/Python programs in nsjail with process, memory, CPU and time limits; submitted programs have no network. The production boundary is a dedicated VM, not a privileged container on the application node. -`consent_texts` holds the published texts: `purpose`, `version` (the contract's `ConsentTextVersion`), the exact `body`, `body_sha256` checked against the body by a CHECK, `kind` (`demo` for synthetic texts without a legal review, `operator` for texts of the actual operator), and `published_at`. The current text of a purpose is the latest publication not after the grant time. Texts are immutable: a trigger refuses UPDATE, DELETE, and TRUNCATE (`consent_texts_immutable`), and a changed text is a new version. The migration publishes demo version `cN-2026-10-01` of every purpose; the operator's texts arrive as new versions in a later migration before real data are accepted (PRD 7.3). Only the C4 text contains the placeholder `{organization}`; `ConsentText.RenderForOrganization` fills it in. +Without `CODE_RUNNER_URL`, practice execution is unavailable and never treated as a successful judgment. A runner and queue do not imply a calibrated course or an open category: the relevant bank is still required. Network labs have a contract and labd foundation, but the provisioner is not connected to the backend user flow. -`consent_records` is the append-only ledger. One row per grant: UUIDv7 `id`, `subject_id`, `purpose`, `text_version`, `text_hash` (SHA-256 of exactly the text the subject saw, 32 bytes), `source` (`registration` for C1 only, `consent_settings` for C1-C3 and C5, `invitation_acceptance` for C4 only), `registration_version` for registration-source C1 only, `granted_at`, and the one-time revocation stamp `revoked_at` with `revocation_source` (`consent_settings` or `support_request`). A C4 row also has `organization_id`, `organization_name` (the name the shown text carried, a snapshot of 1-200 characters), the canonical `field_set` (one to four distinct `ContactFieldKind` values in ascending byte order), `invitation_id`, and `invitation_terms_version`; every other purpose must leave them NULL (`consent_records_c4_scope`). Request metadata such as IP addresses or user agents is not stored: the PRD asks for the version, hash, time, subject, and revocation event, and the extra data would be personal data without a purpose. +## Matching and explanations -Decisions: +Go selects only visible cards, applies hard constraints and ranks within `main`, `near` and `unconfirmed` groups. A claimed grade does not replace a confirmed grade. Explanations use the same components that determined the order and identify unknown values. -- 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` 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. C1's `POST /api/v1/me/account-deletion-requests` stores one durable active request, revokes C1, and appends an outbox event in one transaction; repeating it returns the same request, and a later C1 grant does not cancel it. Account deletion is not synchronous. C2 revocation locks a publication only when it still references one of the records revoked in that transaction, then writes a privacy-history event atomically. The stored publication remains linked to that immutable C2 record; the read model hides its fields and reports the effective state as closed with reason `consent_revoked`, and a later C2 grant cannot reopen it. Repeating a revoke or revoking a later C2 record does not create another closure event for the old publication. C3 revocation does not block account or profile use; a separate manual-assessment request is planned but is not implemented. C4 revocation is scoped to the requested organization, and each bounded outbox intent contains organization and fields copied from the revoked records. C5 revocation makes `HasCurrentConsent` fail closed and writes a stop intent, but there is no external FSP adapter and no external deletion is claimed. -- 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. The durable C1 request record and event are implemented, but the worker that performs account deletion and the policy for ledger retention after that deletion are not; the request does not delete an account or ledger by itself. -- 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 invitation-acceptance handler is not implemented. When it is added, it must call this port in the transaction that accepts the invitation and writes its audit event; a repeated acceptance must compare the existing scope, and an invitation whose C4 belongs to another subject must return `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. +Baseline matching works without a model. Missing suitable vectors leave a neutral semantic contribution (`0.5`, with `ml_unavailable`). Small cohorts cannot supply reliable percentiles. A scoring formula does not demonstrate matching quality on real candidates. -Legal check items, not decided by this storage: deleting the C1 of never-confirmed accounts against the three-year retention of consents in PRD 7.3; 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 and may need a field scope on the C2 record; and the operator texts that replace the demo texts. - -What the ports guarantee (`outbound.ConsentRepositories`, available on `UnitOfWork` and as `postgres.ConsentStore` outside a transaction): - -- `ConsentTexts().Get` and `Current` read published texts and verify the stored hash on every read. -- `ConsentLedger().Grant` and `GrantContact` return the new record with `created` true or the existing one with `created` false. An unknown subject returns `ErrUserNotFound`, an unknown version `ErrConsentTextNotFound`, a version published later `ErrConsentTextNotPublished`, and a hash that does not match the published text (for C4 with the stored name) `ErrConsentTextMismatch`; these come from the database and abort a surrounding transaction. A duplicate does not. A grant whose conflicting record was revoked between its two statements returns `ErrTransactionConflict`. -- `Revoke` returns the rows it stamped. `Current` returns the newest unrevoked C1-C3 or C5 record or `ErrConsentNotFound`; `CurrentContact` returns the unrevoked C4 records of one organization. `List` pages the subject's ledger newest first, optionally by state. -- `ConsentRevocationEffects.Apply` runs in the same `UnitOfWork` transaction as the ledger revocation. It closes the current publication's effective C2 access only when that publication references one of the revoked records, appends its privacy-history event once, and writes bounded outbox intents from the exact revoked records. The contact grants of the revoked records are closed in this transaction (C4 by record, C2 for every grant of the candidate; see [Contact reads and revocation](#contact-reads-and-revocation)); a later grant may open only a new record-bound grant, never reopen an old one. C5 readers and importers must check the current ledger and fail closed; an outbox message alone does not authorize access or prove that an external system deleted data. - -### Consent usecase - -`consent.Service` in `backend/internal/usecase/consent/` is wired through bootstrap and used by registration to check the text version and grant C1 in the create or re-registration transaction. It is built with `consent.NewService(transactor, clock)`, the `Transactor` and application clock the other usecases receive. A nil transactor or clock panics at construction. - -- Entry points fix the source. `GrantAtRegistration` records C1 with source `registration`; settings grants record C1, C2, C3, or C5 with source `consent_settings`. `RevokeInSettingsInNewTransaction` stamps the subject-scoped ledger rows and applies the publication/history and outbox effects in the same transaction. `RequestAccountDeletionInNewTransaction` stores or returns the one active durable request, revokes C1, and appends its event atomically; a later C1 grant does not cancel that request. Neither operation accepts a source or time from the client. `GrantInSettingsInNewTransaction` and the mutation operations retry transaction conflicts up to three attempts with a short jittered wait, ending immediately 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. -- C1 registration version. Migration `00016_bind_registration_consent.sql` adds `registration_version` only to registration-source C1; other grants must leave it NULL. It backfills old C1 rows from the current account version without using tokens. Re-registration deletes the prior registration C1, so an older grant time or multiple active registration C1 rows for one account are inconsistent and stop the migration. The partial unique index `consent_records_registration_version_key` allows at most one unrevoked registration C1 for an account and version. The insert trigger fills the current version when an old backend omits it and rejects a mismatch from the new backend; the immutability trigger also protects the version during revocation. -- 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: 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 implemented account or profile operation requires active C3. A subject without C3 has no C3 record, and `Current` returns `ErrConsentNotFound`; this is not an account error. A separate manual-assessment request is planned, but its endpoint is not implemented. -- Revocation and deletion request. `RevokeInSettingsInNewTransaction` applies all consent effects inside the transaction that stamps the ledger; repeating an already completed revocation does not append another event. C1 deletion requests are durable and idempotent, but they do not synchronously delete the account or cancel on a later C1 grant. -- 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, email verification, and resend - -Implemented: `RegisterAccount` and `ResendEmailVerification` are served by `backend/internal/usecase/identity/register.go` (`identity.Registration`) behind the handler `backend/internal/adapter/primary/http/v1/auth.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, the keyed digest of its six-digit code, 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. - -Email confirmation (`ConfirmEmail`) is implemented. It requires the password saved with that token's registration and checks it against the pending hash. In one transaction the backend checks the current registration version and its C1 record, consumes the token, verifies the address, applies the token's password hash, scenario, and onboarding step to the account, clears `pending_*`, and records exactly one secret-free `identity.email_verified` event. Any refusal leaves the account and token unchanged. Unknown, used, replaced, or superseded tokens, a wrong password, and missing pending credentials answer `verification_token_invalid`; an expired token answers `verification_token_expired`. The Origin must match exactly `APP_PUBLIC_URL`. Confirmation does not create a session. The frontend confirmation screen is implemented and covered by the local registration browser flow. - -Confirmation by code (`ConfirmEmailByCode`) is implemented in `backend/internal/usecase/identity/code_confirmation.go`. It takes the address, the six-digit code, and the password chosen for the registration. The checks run in this order. First the rate limits: per client (`IDENTITY_CLIENT_HOURLY_LIMIT`) and per normalized address, which shares the login counter (`IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT`). Then the newest open verification token of the unverified account at that address, with the current registration version and a code. Then the password against the token's pending hash, then the keyed digest of the code (compared in constant time) and the code expiry. The password is checked on every branch with the same hashing work; with no open code a dummy hash is used, so the response time does not reveal the account. A successful check runs the same transaction as the link confirmation, so one token is consumed once: a code after the link is refused, and a link after the code is refused. Every failed check of an open code (a wrong code, a wrong password, or an expired code) adds one to `code_failed_attempts` in a single conditional UPDATE. The database serializes these updates, so concurrent wrong attempts never count more than five. The fifth failure invalidates the token and clears its code and pending credentials, so the link stops working too, and the user must request a new message. A resend invalidates the earlier codes together with the earlier tokens. Every refusal (an unknown address, no open code, a wrong code, an expired code, a wrong password, or an invalidated token) answers 400 `verification_token_invalid` with the same body, so the answer does not show which addresses have a pending registration. Success answers the same body as the link confirmation and creates no session. The verification message uses the template `verification.v2`; the earlier link-only template `verification.v1` is no longer rendered. - -Login accepts only a verified email and checks the account's stored password, never pending registration credentials. An unknown address, wrong password, and invalid stored hash receive the same `invalid_credentials`; unknown addresses and invalid hashes also run `VerifyDummy`, and an invalid stored hash is logged without the email or hash. A correct password for an unverified account answers `email_not_verified` and creates no session. Successful login creates a new session; if the request carried a valid session cookie, the backend revokes it and creates the new session in one transaction. Failed login does not revoke an existing session, and a malformed cookie cannot become a principal. - -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. - -Idempotency. The key is scoped by `HMAC(secret, operation | key | normalized email)` and the request is fingerprinted by `HMAC(secret, canonical body)` (`identity.Keyring`, secret `IDENTITY_KEY_SECRET`; required; a development stand may set `IDENTITY_ALLOW_EPHEMERAL_KEY=true` to draw a random one per process, which loses records and counters on restart). The record lives in `idempotency_records` (migration 00014) for 24 hours and is written in the registration transaction, so a visible record always belongs to a committed registration. A retry with the same key and body replays the neutral 202 and consumes no limit; the same key with another body answers 422 `idempotency_key_reused`. A concurrent identical request waits on the row of the first and is then replayed, so this implementation never answers 409 `idempotency_in_progress`. Each registration purges up to 10 expired records, which keeps the table bounded without a job. - -Rate limits (Redis, fixed windows, `outbound.RateLimiter`, `redis.Cache.Take`, one atomic Lua script per take). The counters are keyed by the HMAC of the normalized address and count every request whether or not an account exists, so a 429 reveals nothing about the account. Registration and every resend share the per-address counters: at least `VERIFICATION_MAIL_MIN_INTERVAL` (default 60 s) between two messages and at most `VERIFICATION_MAIL_DAILY_LIMIT` (default 5) per window of 24 hours that starts with the first. Confirmation allows five attempts per token per hour. A per-client counter, `IDENTITY_CLIENT_HOURLY_LIMIT` (default 30 per hour), applies to registration, confirmation, resend, and login; it is keyed by `middleware.LimiterKey` of `ClientAddr`, hashed with the secret, and is skipped when the address is unknown (a shared bucket would let one client lock out everyone). Login also uses `IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT` (default 10 per hour) for normalized email, whether or not an account exists. Both configurable identity limits accept values from 1 to 10000. A rejected `Take` does not increase its own counter; if an earlier limit check passed, its counter already records the attempt even when the next check refuses it. A refusal answers 429 `rate_limited` with `Retry-After` in whole seconds rounded up. Counters are ephemeral: a Redis restart resets them, and the mail provider quota remains the last bound. A Redis failure answers 500 and never lets the request through. Neither address nor token is logged. - -Token replacement policy. Every issue of a verification token (registration, re-registration, resend) first invalidates all unused verification tokens of the account and then stores the new one, so at most one link works at a time. A resend keeps the password, the scenario, the consent record, and the registration version; only the token changes. The message of an invalidated token is cancelled by the sending worker, so only the current link is delivered. The token lifetime comes from the product policy (`identity.verification_token_lifetime_hours`, 24 in the demo version), not from configuration. - -Targeted lockout. Because the per-address counters count every request whether or not the account exists, anyone can use up the address's 5 messages per 24 hours and so block the owner's registration and resend for up to 24 hours without knowing the address's state. This is the price of answering 429 identically for every address; it is accepted as a known limitation of the anti-enumeration design. It is bounded (the per-client limit slows one source), and visible: `lincodex_identity_rate_limit_refusals_total{scope="address"}` rises. A large share of `scope="client"` refusals instead hints at a broken proxy chain (every client resolved to the proxy address); alert on the ratio of client to address refusals and check `TRUSTED_PROXY_CIDRS`. The label has two fixed values and never holds an address. No alerting rule is shipped yet. - -Without a resolved client address (the `ClientIP` middleware did not run) the per-client limit is skipped and only the per-address limits apply: a shared "unknown" bucket would let one client lock out everyone, the worse failure. `IDENTITY_KEY_SECRET` is required; `IDENTITY_ALLOW_EPHEMERAL_KEY=true` lets a development stand draw a random one. The limiter keys carry a Redis hash tag (`{key}`), so the multi-key script is cluster safe. - -Known limits. A resend for an unknown or verified address skips the token and message work, so its time differs from an unverified account by a few database statements; registration hides the difference behind the password hash. The password blocklist of the contract is not implemented yet; only the length rules of `domain.NewPassword` apply. - -### Organizations and memberships - -Organization creation, reads, and owner edits are implemented in `backend/internal/usecase/organization/`, `backend/internal/adapter/primary/http/v1/organization.go`, and `backend/internal/bootstrap/organization.go`. Storage and membership ports remain in `backend/internal/port/outbound/organizations.go` and the PostgreSQL adapter. Migration `00019_create_organization_creation_results.sql` preserves the original create result. General tenant context and the paginated directory of the current account's organizations are also implemented. See [backend documentation](../../backend/README.en.md#organizations) for behavior and validation. - -The middleware in `backend/internal/adapter/primary/http/company_context.go` checks the verified employer account and active `owner` membership after session, CSRF, and parameter decoding, before the business handler or its 501 fallback. All 14 organization, need, and invitation operations are classified explicitly; a contract test requires new paths with `org_id` to be classified. Candidate-owned company hiding and C4 revocation retain their separate authorization. Request context is not cached and never replaces authorization repeated inside a business transaction. Other roles receive 403; foreign or ended memberships receive 404. `ListMyOrganizations` returns only the current employer's active memberships; a company appearing in that directory does not itself grant owner authority. - -Tables: - -- `organizations`: UUIDv7 `id` (the `org_id` of every organization path), `name` (1-200 characters, the bound of the consent snapshot), `description`, `sphere` (free text; the PRD has no taxonomy), four public contact columns (`contact_website`, `contact_email`, `contact_phone`, `contact_telegram`), the verification columns `verification_level`, `verification_basis`, and `verification_changed_at`, the profile `version`, and the times. Every text column has a CHECK for the same format and bounds as the contract (no surrounding whitespace, no control characters, `https` website without credentials). -- `organization_representatives`: `organization_id`, `ordinal` (0 to 9, so at most ten), `name`, and `job_title`; deleted with the organization row. The list is replaced as a whole with a profile update. -- `memberships`: UUIDv7 `id`, `organization_id`, `user_id`, `role`, `state`, and the times. `UNIQUE (user_id, organization_id)` allows one membership per pair in any state, and `UNIQUE (organization_id, id)` is the target of the composite foreign keys that later tables (the assignments of needs) use to bind a membership to its organization. Both foreign keys are `ON DELETE RESTRICT`. -- `holdings`: UUIDv7 `id` (internal; the API never shows it), `founder_account_id`, the account that created the first organization of the holding, with `UNIQUE` and a foreign key to `users` with `ON DELETE RESTRICT`, and `created_at`. The column `organizations.holding_id` is required, references the holding with `ON DELETE RESTRICT`, and has an index; migration `00041_create_holdings.sql` fills it from the account of the earliest membership of each organization. - -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 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). -- Holding. The organizations of one founder account form a holding. `CreateWithOwner` stores the organization in the holding of its owner account in the same transaction, and creates the holding with the first organization of the account (`INSERT ... ON CONFLICT (founder_account_id) DO NOTHING`, then a read), so concurrent creations of one account end in one holding. A holding carries no profile and no right: it only defines the scope of the shared E0 quota pool (invitations and card views). The number of organizations per account is not limited; merging holdings of different owners is not modelled. The pool and lock rules are in [Company quotas](COMPANY_QUOTAS.md#holding-pool). -- 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 `invitation_id` key needs real invitations; both arrive with the acceptance of an invitation, the first writer of C4 rows that name a real invitation. The invitation tables (migration 00037) and the needs reference organizations, accounts, and policy versions with `ON DELETE RESTRICT`, so an organization with 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 remove it through bounded opportunistic cleanup after the replay window; physical deletion may happen later when create traffic resumes; 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 owner's decision on the number of organizations per account (no limit; the E0 quotas of a holding are shared) 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): - -- `Organizations().CreateWithOwner` stores the organization and its owner membership and validates that the owner is the active owner membership of that organization. The organization joins the holding of the owner account, and the holding is created in the same transaction when none exists yet. An unknown account returns `ErrUserNotFound` and aborts the surrounding transaction. -- `GetForMember` reads the organization, its representatives (aggregated as JSON in the same statement), and the caller's active membership from one snapshot, and returns them or `ErrOrganizationNotFound` for an unknown organization, an account without a membership, and a `suspended`, `removed`, or `left` member alike. `ListForUser` pages the active organizations of one account, newest membership first, with the organization identifier as the tie-breaker. `UpdateProfile` is described above. -- `Memberships().Insert` returns `ErrMembershipExists` for a repeated pair in any state, `ErrOrganizationNotFound` for an unknown organization, and `ErrUserNotFound` for an unknown account; `Get` returns the membership in any state or `ErrMembershipNotFound`, and the caller checks `GrantsAccess`. There is no method that changes a role or a state yet. - -### Candidate profile - -Own `GetMyProfile` and `SaveMyProfile` operations are implemented through `backend/internal/usecase/profile/`, the transactional `CandidateProfileRepository` port, `backend/internal/adapter/secondary/postgres/candidate.go`, and `backend/internal/adapter/primary/http/v1/profile.go`. The use case rechecks the verified candidate account inside the transaction; the owner identifier comes only from the server session. Without DATABASE_URL, the operations retain their 501 fallback. Schemas and full-replacement rules live in `api/core/components/schemas/candidate_schemas.yml` and `api/core/routes/candidate_profile.yml`. No ML service, resume file, or FSP account is required. - -Migration `00020_create_candidate_profile_history.sql` adds overlapping-period confirmations and version history. `experience_overlaps` lists intersections of inclusive calendar months. An explicit confirmation binds two indices to their exact dates in the current request and its `expected_version`; an earlier confirmation carries forward only for the same indices and dates. Editing an employer or description alone does not invalidate the confirmed periods. A stored unconfirmed overlap permits only an exact no-op; a changed profile requires confirmation or corrected dates. - -The changed version, complete claim set, period confirmations, and private history snapshot commit in one transaction. Each snapshot is bounded to 256 KiB; a trigger refuses history UPDATE, and deleting the profile cascades to its history. There is no automatic retention expiry. A no-op creates no history. A successful save, including a no-op, advances only `candidate_profile` to `candidate_questionnaire`, leaving later steps unchanged. Confirmed categories are read in the same transaction as the profile (`GetMyProfile`, `SaveMyProfile`): one per specialization in catalog order, from `candidate_assessment_categories`. The profile form never writes them. - -Tables: - -- `candidate_profiles`: `user_id` (the primary key and a foreign key to `users` with `ON DELETE CASCADE`), `version` (positive; the first save creates version 1, and the contract's version 0 is the absence of a row), and times. The profile is personal data of the account and goes with it; retention rules are an open legal question. -- `candidate_profile_claims`: one row per stored claim - a single field (`full_name`, `contact_email`, `contact_phone`, `contact_telegram`, `terms_location`, `terms_relocation`, `terms_salary_minimum` at `ordinal` 0) or a list item (`stack` up to 30, `role` up to 9, `experience` up to 20, `soft_skill` up to 10, `project` up to 10, by position; projects are described in [Candidate projects and GitHub repositories](#candidate-projects-and-github-repositories)). Columns: `value` jsonb, `status` (`confirmed` or `extracted`), `origin` (`manual`, `extracted_from_resume`, `imported`), `trust_level`, `quote`, `extraction_version`, and `confirmed_at`. A field without a value has no row, so the contract's `unknown` is the absence of a row. The foreign key points at `candidate_profiles` with `ON DELETE CASCADE`. - -Decisions: - -- Claims, not columns. Every value has a status, a source, and a confirmation time, so one claims table replaces fifty columns; jsonb holds the shape of the value (a string, a boolean, or an object), and each kind has its own CHECK for the format and bounds of the contract (E.164 for the phone, the `@` of a Telegram name, a multiple of 1000 for the salary, `YYYY-MM` and the order of the period for experience, the known specialization and grade codes). The domain validates a value in full before it is written, and `RestoreCandidateProfileContent` applies the same rules on read, so a row changed outside the application is rejected. -- Trust level 0 in the schema. `trust_level` is stored in a column with `CHECK (trust_level = 0)`, and the insert statement supplies 0 itself and takes no level from the caller. A confirmed value requires `confirmed_at`, an unconfirmed suggestion does not and is always an import (`extraction_version` is not NULL); a manual value is always confirmed and carries no quote. Raising trust is a property of evidence, which is not stored here. -- No confirmed category. The tables have no column for a confirmed grade or a category, and the value of a role admits only the keys `specialization` and `self_assessed_grade`, so neither a form nor an import can write a confirmed category; it is read from the `candidate_assessment_categories` rows, which only an assessment result writes (`confirmed_categories`, with its `basis`). -- No mandatory link to a file, ML, or FSP. The tables have no column or foreign key to a resume file, the object storage, ML, or an FSP account, and the only foreign keys point at `users` and `candidate_profiles`. A profile typed by hand is complete; a future import adds its own columns or tables additively (`TestCandidateProfileStorage` checks the set of columns and foreign keys). -- Version. `AdvanceCandidateProfileVersion` is one statement that advances the version only when the stored one equals the one the caller read; for a stale version no row returns, and the caller answers 412 `version_conflict`. The update time is `GREATEST(stored, application clock)`, so an instance clock that runs behind never violates the CHECK `candidate_profiles_updated_after_creation` (which would be a 500). Version monotonicity is enforced by these queries only: there is no trigger, so no other code may write `version`. `InsertCandidateProfile` with `ON CONFLICT DO NOTHING` tells a lost first save apart (concurrent first saves: one wins, the rest get a version conflict). Replacing the set of claims (delete all, insert the new ones) runs in one transaction with the version advance. `domain.CandidateProfile.Replace(input, expectedVersion, at)` fixes the order: a version above the current one is a conflict; body rules are 400; a decision `extracted` that depends on the stored claims, against a stale version, is `ErrCandidateProfileVersionConflict` rather than 400; a body that changes nothing does not advance the version; any other change over a stale version is a conflict. -- Consistent read. `ReadCandidateProfile` reads the profile row and every claim in one statement (a LEFT JOIN), that is, from one snapshot; two separate queries could return version N with the claims of N+1 when a save commits between them. The adapter must use only this query and never replace it with two; a write reads the profile in the same transaction as the replacement, and the version condition protects against a lost edit. -- Privacy. The values are personal data of the candidate: `ProfileClaim`, `ProfileExperience`, `ProfileSalaryMinimum`, `CandidateProfileContent`, and `CandidateProfile` hide themselves in `fmt` and `slog` output, `CandidateProfile` logs only the account identifier and the version, domain errors name the field and the rule but never the value, and metric labels are never taken from the profile. No query selects the profile of another account: every statement is scoped by `user_id`. The adapter must never log or wrap `pgconn.PgError.Detail` (it contains the failing row with names and phones) and reports only the SQLSTATE and the constraint name, as the organizations adapter does. - -### Candidate visibility - -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: - -- `candidate_publications`: one row per candidate, created by the first explicit publication, so a new profile has no row and is closed. Columns: `state` (`published` or `closed`), `fields` (a canonical array of card field codes, empty exactly when closed), `consent_record_id`, `published_at`, `closed_at`, `version`, and times. The card field codes are a closed set (`categories`, `stack`, `experience`, `soft_skills`, `location`, `relocation`); the full name, a contact, and the lowest salary have no code, and the function `candidate_card_fields_are_canonical` with a CHECK refuses anything else, so no row can publish them. -- `candidate_search_statuses`: one row per candidate who ever set the status. `status` is `looking` or `not_looking`; `looking` stores `confirmed_at`, `lapses_at`, and `policy_version_id`, and `not_looking` stores none of them (a CHECK ties the three together). The only foreign key is `users`, and a trigger checks `policy_version_id` against `policy_versions` (SQLSTATE 23503, constraint name `candidate_search_statuses_policy_fkey`), because a real foreign key would make PostgreSQL refuse TRUNCATE of the immutable policy table before its own trigger could answer: the table has no consent column and no reference to the ledger, and a test reads the catalog to prove it. -- `candidate_hidden_organizations`: the primary key `(user_id, organization_id)` makes a hiding unique per candidate and organization; `organization_id` references `organizations` with `ON DELETE RESTRICT`. A BEFORE INSERT trigger (`candidate_hidden_organizations_enforce_limit`) bounds one candidate to 1000 records, serializing the inserts of one candidate through a no-key-update lock on the account row, and fails with SQLSTATE 23514 and the constraint name `candidate_hidden_organizations_limit`. The index on `(organization_id, user_id)` serves the organization side, which has to exclude hidden candidates without learning who hid it. -- `candidate_privacy_events`: the append-only history (a trigger refuses every UPDATE with `candidate_privacy_events_immutable`, and refuses DELETE only while the account is verified, with `candidate_privacy_events_retained`; TRUNCATE stays allowed for test isolation). It holds the kind, the time, the published field set and the C2 record of a publication event, and only the organization identifier for a hiding event (the candidate's read joins the current name, so the table holds no text about an organization); a CHECK fixes the shape of every kind. It never holds a profile value or a name. A trigger refuses DELETE while the account is confirmed (`candidate_privacy_events_retained`, the same condition as `consent_records_refuse_delete`, to be extended by the retention rule and the account deletion procedure), a trigger on `users` refuses deleting a confirmed account that has history with the same constraint name (the cascade runs after the account row is gone, so the row trigger alone cannot see it), and the account reference cascades, so the unverified account cleanup removes the rows of an account it deletes. The hide and unhide records are sensitive: they say which employer a candidate avoids. - -Decisions: - -- A profile is closed by default. Nothing in the account, the profile, the questionnaire, or an assessment creates a row, and the integration test saves a profile and checks that all four tables stay empty. The domain reads a missing row as version 0, closed with the reason `never_published`, not looking, and hiding nobody. -- C2 stays in the consent ledger; the publication references it. Duplicating the consent state would let two tables disagree about whether a candidate agreed. `candidate_publications` therefore holds only what the ledger deliberately does not carry (which fields and when) and a reference to the C2 record behind them. The composite foreign key `(consent_record_id, user_id, consent_purpose)` over the unique index `consent_records_id_subject_purpose_key` (added by this migration; the record id is already unique, so it restricts nothing) accepts only a C2 record of the same account, and a record that a publication refers to cannot be deleted. The effective state is computed: `ReadCandidatePublication` joins the revocation stamp of the record in one statement, and the card is `published` only while the stored state is `published` and the record is unrevoked. A revocation of C2 closes the card at once without any write here, and a later C2 grant opens nothing: the publication stays bound to the revoked record, so the candidate publishes again explicitly and the new publication binds to the new record. The body of the publish operation carries no consent identifier; the usecase binds the account's current unrevoked C2 record in the same transaction as the write, and it MUST take it with the port method that issues `LockCurrentC2Record` (`SELECT ... FOR SHARE`), not with `ConsentLedger().Current`, otherwise the race with a revocation returns, and without one answers 409 `state_conflict`. -- The search status is not a consent. It has its own table, its own version, and no reference to the ledger, and `domain.SearchStatus` knows neither the publication nor the hidden organizations, so applying a status cannot change them. The integration test sets, confirms, and clears the status in a fixture and compares the raw rows of the consent ledger, the publication, and the hidden organizations before and after: they are equal. -- The lapse of `looking` comes from the versioned policy and only narrows. The 30 days are `search_status.searching_confirmation_interval_days` of the effective `product` policy version (demo version 1: 30), so the owner changes them by publishing a new policy version, not by a constant or configuration. A confirmation fixes `lapses_at` and stores `policy_version_id`, so a later policy change moves no stored time and every row names the policy it was made under, as the policy section requires. The lapse itself is computed (`SearchStatus.Effective(now)` is `looking` only while `now` is before `lapses_at`) and never written: no process, job, or clock skew can turn an expired status into anything more public, the stored row keeps what the candidate said, and the read model shows `value` `not_looking` with `lapsed` true. The candidate confirms again with `looking`, which replaces `confirmed_at`. A reminder before the lapse is a planned notification, not part of this task. -- Versions. Each setting has its own `version` (0 is the absence of a row), checked in the statement like the profile: `UpdateCandidatePublication` and `UpdateCandidateSearchStatus` change a row only when the stored version equals the one the caller read, and no row returns for a stale one (412 `version_conflict`). The domain order is the contract's: a version above the current one is a conflict, an unchanged effective setting is a success even over a stale version, any other change over a stale version is a conflict, and a publication needs an active C2. Because the settings are independent, a change of one never makes another stale. -- Hidden organizations belong to the candidate and are safe against enumeration. The record is the candidate's: no organization-visible query selects it, and an organization cannot tell a hidden candidate from an unpublished one. Hiding by identifier must not become a way to ask whether an organization exists. The foreign key refuses an unknown organization (SQLSTATE 23503), and the usecase must answer that exactly like an organization the candidate cannot see: the same 404 `not_found` with the same body, without a different timing or code. The candidate can see an organization that has sent them an invitation, and the organizations that a candidate lookup lists (planned, an open question), so a hiding reveals nothing the candidate could not already read. Lifting a hiding is a DELETE that answers 204 for any well-formed identifier, so it reveals nothing at all, and its history event is written only when a row was deleted. The identifiers are random UUIDv7 values, and the general rate limit covers the probing that remains. -- Contact grants. Closing the publication, and hiding an organization that holds an active contact grant, revoke the grant with the reason `visibility_closed` in the same transaction as the change (the invitation contract fixes the reason). The closing is implemented; see [Contact reads and revocation](#contact-reads-and-revocation). The search status never closes a grant. -- 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) 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 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 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 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. - -### Invitation drafts - -Implemented: the organization side of the invitation draft, that is `ListOrganizationInvitations`, `CreateOrganizationInvitation`, `GetOrganizationInvitation`, and `UpdateOrganizationInvitation` ([contract](../../api/README.en.md#invitations-and-contact-grants)). A draft is invisible to the candidate and produces no inbox entry, no event, and no quota charge; the send is described in [Sending invitations](#sending-invitations). Withdrawal, the salary raise, and the cancellation still answer 501 after the common checks; the contact read is described in [Contact reads and revocation](#contact-reads-and-revocation); the candidate's read, view, decline, and acceptance are described in [Candidate view and decline](#candidate-view-and-decline) and [Candidate acceptance](#candidate-acceptance). Code: `domain/salary_range.go`, `domain/invitation_terms.go`, `domain/invitation.go`, `usecase/invitation/`, `adapter/primary/http/v1/invitation.go`, the PostgreSQL adapter `adapter/secondary/postgres/invitations.go` with `db/queries/invitations.sql`, and migration `00037_create_invitations.sql`. - -Tables: - -- `invitations`: UUIDv7 `id`, `organization_id`, the internal `candidate_id` (never serialized, logged, or printed), the optional need link (`need_id` with `need_requirements_version`, bound by composite foreign keys to a stored version of a need of the same organization), `state` (all fourteen states of the contract, so the later operations need no constraint change), `expiry_reason`, `version`, `terms_version`, `response_period_days` (3, 7, or 14), `policy_version_id` (the product policy version that allowed the period), `response_deadline_at`, `salary_raise_used`, `created_by`, and `created_at`, `updated_at`, `delivered_at`, `viewed_at`, `responded_at`. CHECK constraints tie the deadline to the delivery (both set or both null), keep a draft free of delivery, view, answer, and raise, and tie the expiry reason to the state. A trigger keeps the identity columns, makes every UPDATE advance `version` by exactly one and `terms_version` by at most one, and refuses to undo a raise or to move the delivery, the deadline, or the period after a delivery. A second trigger refuses DELETE. The foreign keys to organizations, accounts, and policy versions are `ON DELETE RESTRICT`, so an account with invitations is undeletable until a deletion procedure settles them. -- `invitation_terms_versions`: `(invitation_id, version)`, the terms as a JSONB snapshot, and the salary again in typed columns (`salary_from`, `salary_to`, `salary_currency`, `salary_period`, `salary_tax_basis`). Constraints repeat the money rules in integers: both bounds from 1000 to 100 000 000 rubles in steps of 1000, `salary_from < salary_to`, `20 * (B - A) >= A + B` and `5 * (B - A) <= A + B` (a width of 10% to 40% of the midpoint), RUB, month, and `net` or `gross`. The snapshot must hold all twelve terms and its salary must equal the typed columns. A trigger refuses UPDATE and DELETE: a version of the terms is immutable, and a change appends the next version. The invitation points at its current version by a deferred composite foreign key, so the first version is inserted in the same transaction. -- `invitation_events`: one audit event for each committed invitation version (`UNIQUE (invitation_id, version)`) with the kind (`draft_created`, `draft_updated`, since migration 00038 `delivered`, and since migration 00039 `viewed` and `declined`, and since migration 00040 `accepted`), the version and terms version, the actor, the parts that changed (`terms`, `need`, `response_period_days`), and the time. It holds no content and is append-only. -- `invitation_creation_results`: the original response of an idempotent create, bound to the generic idempotency record and removed with it. It holds the terms, the alias, and no candidate identifier. - -Decisions: - -- Money. Amounts are whole rubles in `bigint`, as in the contract: there are no minor units and no floating-point column or comparison. `domain.SalaryRange.Validate` is the single implementation of the rule for needs and invitations; it checks the bounds, the step, the currency, the period, the base, `A < B`, and the width with the integer pair above. A violation of the order or the width is attributed to `salary_to`. The database repeats the rule, so another writer cannot store a range the API would refuse. -- Terms are complete from the first draft. `InvitationTerms.Validate` repeats the schema rules a stored value must also satisfy and adds the cross-field rules: a place of work for the `office` or `hybrid` format, a technology that is not repeated ignoring letter case, and a package in which every condition is either provided with a description or explicitly not provided. Text fields reject control characters, including NUL, which JSONB cannot store. A stored snapshot is decoded strictly and validated again on every read. -- The candidate. A draft names the candidate only by the card handle. `candidateview.Service.ResolveCandidateHandle` resolves it in the create transaction with the checks of a card read: the active membership, the effective C2 publication, the hiding of this organization, the locks of the visible cohort, and the minimum cohort of five. An unknown handle, a handle of another organization, a candidate who revoked C2 or hid the profile from the organization, and a card that the cohort rules suppress all fail with the same 400 at `/candidate_handle`. The resolution charges no card-view quota and writes no access history, because it returns an identifier to the server only and shows no card content. Responses derive the alias again with the key of the cards, so the handle of an invitation is the handle of the card; the same candidate has another alias in every organization. -- Owner only. The HTTP boundary lists the operations in `ownerCompanyOperations`, and the usecase repeats the check in its transaction: a verified employer account with an active `owner` membership. Another role gets 403; an outsider, an unknown organization, an unknown invitation, and an invitation of another organization get the same 404. A membership alone grants nothing. -- Idempotent create. The scope of `Idempotency-Key` is the operation, the key, the account, and the organization; the fingerprint is that of the canonical request body. The original 201 is stored in `invitation_creation_results` and replayed for 24 hours, even after the draft changed or the candidate stopped being visible. A different body under the same key gives 422 `idempotency_key_reused`. Every failure rolls the whole transaction back, so a 400 is never stored. -- Update. The body replaces the fields it sets, and `terms` is always replaced as a whole. The order is the one of the contract: a body that changes nothing returns the current invitation with 200 even when the version is stale, then the version (412 `version_conflict`), then the state (409 `state_conflict`, only a draft changes), then the rules (400 with a pointer). A change of the terms appends the next terms version; a change of the period or the need keeps it. A new period is checked against the policy in force and records its version. -- Response period. The options and the default come from the `invitations` section of the effective product policy (3, 7, 14; default 7), and the draft stores the version it used. -- Locks. A create and an update both take the exclusive organization lock first (`CompanyQuotaRepository.LockOrganization`), like a card read and a search, and only then the share lock of the membership check, the cohort locks of a create, or the invitation row lock of an update, so commands of one organization queue instead of deadlocking on a lock upgrade, and a later command that also charges the organization, such as sending, keeps the same order. An update locks the invitation row with a statement of its own (`LockInvitation`) and reads it afterwards: a locking read joined to the terms table would, after waiting for a concurrent commit, pair the new `terms_version` with the terms row it fetched before the wait and find nothing. A create repeats a bounded number of times when the visible cohort changed while it was locked. -- The indicator. `salary_fit` is always `not_available`; `contact_access` is derived from the grant ([Contact reads and revocation](#contact-reads-and-revocation)). The indicator needs the candidate's minimum, and computing it before the limit of three settings a day and the seven-day withholding exist would let an organization probe the minimum by editing a draft, so neither is computed or enforced yet. - -How the later operations plug in: the pair rules read the index on the organization and the candidate. The contact grant arrives with the acceptance ([Candidate acceptance](#candidate-acceptance)). The C4 columns of the consent ledger still have no foreign keys to `organizations` and `invitations`; that is a follow-up. - -Not implemented: the salary limit and the withheld counter, the indicator against the candidate's minimum, the raise, the withdrawal, the candidate side beyond the list of invitations, the card of the organization for the candidate, the reading of earlier terms versions, and the handling of invitations when an account is deleted. The role and assignment matrix beyond the owner is planned. - -Tests: `domain/salary_range_test.go` and `domain/invitation_test.go` (exact width at 10% and 40%, steps, caps, terms rules with pointers, versions, immutability of earlier values, redaction), `usecase/invitation/service_test.go` (owner policy, handle refusals, order of checks, replay, rollback, versions), `adapter/primary/http/v1/invitation_test.go` (mapping, no candidate field, failure statuses, cursor), and the integration tests `TestOrganizationInvitationDraftsOverHTTP`, `TestInvitationRepositoryStoresVersionsAndRefusesLostUpdates`, `TestInvitationTablesRefuseMoneyAndHistoryViolations`, and `TestInvitationMigrationRollbackKeepsStoredInvitations` against a real PostgreSQL. - -### Sending invitations - -Implemented: `SendOrganizationInvitation` and the candidate's list of invitations `ListMyInvitations` ([contract](../../api/README.en.md#invitations-and-contact-grants)). Code: `domain/invitation_delivery.go`, `usecase/invitation/send.go` and `candidate_inbox.go`, `usecase/notification/invitation.go`, the HTTP handler `adapter/primary/http/v1/invitation.go` with the cursor in `invitation_cursor.go`, the adapter `adapter/secondary/postgres/invitation_delivery.go` with `db/queries/invitation_delivery.sql`, the wiring in `bootstrap/invitation.go`, and migration `00038_send_invitations.sql`. - -- One transaction. A send takes the organization lock (`CompanyQuotaRepository.LockOrganization`), the owner check of the membership, the Idempotency-Key, and the invitation row lock, in the order of every invitation command, and then the locks of the visible cohort. It runs the visibility barrier of the card read again, spends one invitation of the organization quota, moves the draft to `delivered` with one conditional UPDATE (`state`, `version` plus one, `delivered_at`, `response_deadline_at`, `updated_at`; the terms version stays), appends the audit event `delivered`, and writes the outbox events: `invitation.delivered` for the in-platform notification and `notification.mail_requested` with its `mail_requests` row for the email. The internal sending step is never stored: when the answer arrives, the invitation is `delivered`, it is in the candidate's list, and the charge is recorded. A failure of any step rolls everything back. -- The candidate's inbox entry is the delivered invitation itself. `ListMyInvitations` reads the rows with the candidate of the session and a `delivered_at`, newest first by `(delivered_at, id)` over the partial index of migration 00037, with the current name of the sending organization; a draft has no delivery and is never listed, and listing records no view. The notification of `notification_inbox_events` is written by the inbox consumer from the outbox event, seconds later ([Internal notifications](#internal-notifications)); the invitation does not wait for it. -- Deadline. `response_deadline_at = delivered_at + response_period_days` in whole days, set by the same UPDATE as the first delivery. The trigger of migration 00037 refuses to change the delivery, the deadline, or the period afterwards, and the mail path never touches the invitation, so neither an email nor its retries move the deadline. The mail request becomes a delivery when the delivery consumer handles it; sending notification email is planned. An unverified address, a stopped transport (`EMAIL_PROVIDER=disabled`), or a failed attempt never affects the invitation or the answer of the send. -- Content. The email says only that an employer sent an invitation and links to `/candidate/invitations`: it names neither the organization nor the terms and holds no contact or identifier of the candidate. The notification shows the organization and the role while the candidate has not hidden the organization. The payload of `invitation.delivered` names the recipient and the organization, as the inbox contract requires, and stays on the internal event bus. -- Visibility. A draft keeps its candidate after a C2 revocation, a hiding, or a cohort that fell below its minimum. The send derives the card handle of the stored candidate and resolves it through `candidateview.Service.ResolveCandidateHandle` again; a candidate the organization may no longer see answers 409 `state_conflict` without saying which rule applied. -- Quota. The charge goes through the existing company quota port (`companyquota.Service.ReserveInvitation`) into `company_invitation_quota_usage`, keyed by the invitation, so it is written once. Migration 00038 adds the composite foreign key `(organization_id, invitation_id)` to `invitations`. An exhausted quota answers 429 with `Retry-After`, nothing is stored, and the draft stays. The port counts the pool of one organization; the shared E0 pool of a holding is not implemented in the port yet. -- Idempotency. The scope is the operation, the key, the account, and the organization; the fingerprint covers the invitation of the path and `expected_version`. `invitation_send_results` keeps the outcome under the key for 24 hours together with the generic idempotency record: the original 200, a 404 of an unknown invitation, and a 409. A 400, a 412, and a 429 are not stored, so the corrected request can reuse the key. A send of an invitation that is already delivered answers 200 with its current state even with a new key or an older version and charges nothing. -- Access. Owner only, as for drafts: `ownerCompanyOperations` at the HTTP boundary and the same check in the transaction; no other role may send. The candidate's list requires a verified candidate account, and an employer gets 403. -- Order of checks after the boundary: the owner, the key (422 or a replay), the invitation (404), a completed send (200), the version (412), the state and the visibility (409), then the quota (429). - -Not implemented: the pause after a no deal (no operation produces the `no_deal` state yet), the cancellation (the view, the decline, and the acceptance are in [Candidate view and decline](#candidate-view-and-decline) and [Candidate acceptance](#candidate-acceptance)), the sending of notification email, the shared E0 pool of a holding in the quota port, and the role and assignment matrix beyond the owner. The pending limit and the pause after a decline are in [Pending limit, cooldown, and expiry](#pending-limit-cooldown-and-expiry). - -Tests: `domain/invitation_delivery_test.go`, `usecase/invitation/send_test.go`, `usecase/notification/inbox_test.go` (the invitation notice), `adapter/primary/http/v1/invitation_test.go` (statuses, `Retry-After`, the candidate cursor), and the integration tests `TestOrganizationInvitationSendOverHTTP` (the inbox before any email, repeats with one row of each kind and one charge, a 3-day deadline with the mail stopped and its job retried, visibility, a stale version, owner only, the quota, paging) and `TestInvitationSendMigrationKeepsDeliveriesAndKeysQuotaUsage`. - -### Candidate view and decline - -Implemented: `GetMyInvitation`, `ViewMyInvitation`, and `DeclineMyInvitation` ([contract](../../api/README.en.md#invitations-and-contact-grants)). Code: `domain/invitation_answer.go`, `usecase/invitation/view.go` and `decline.go`, the HTTP handler `adapter/primary/http/v1/invitation_candidate.go`, the adapter `adapter/secondary/postgres/invitation_answer.go` with `db/queries/invitation_answers.sql`, and migration `00039_answer_invitations.sql`. - -- Read without a side effect. `GetMyInvitation` reads a delivered invitation by the candidate of the session and the invitation, with the current terms and the current name of the sending organization, and it records no view. The one change a read can cause is the expiry: a read at the deadline or later first moves the invitation to `expired` ([Pending limit, cooldown, and expiry](#pending-limit-cooldown-and-expiry)). The view is the explicit command `ViewMyInvitation`, as the contract requires, so a prefetch, a retry, or a cache refresh never changes what the organization sees. A draft, an invitation of another candidate, and an unknown identifier answer the same 404; an employer account answers 403. -- View. In `delivered` before the deadline the command moves the invitation to `viewed` with one conditional UPDATE (`state`, `version` plus one, `viewed_at`, `updated_at`), keeps `response_deadline_at`, and appends the audit event `viewed`. At the deadline or later the due expiry is applied first, and the 200 answer shows `expired` with no view recorded; in every other state the command changes nothing and answers 200 with the invitation as it is. It takes neither a key nor a version; concurrent views queue on the row lock, and the first one wins. -- Decline. Allowed from `delivered`, `viewed`, and the planned `counter` before the deadline. One transaction moves the invitation to the terminal `declined` (`responded_at`, `version` plus one), stores the reason and the optional comment in `invitation_declines`, appends the audit event `declined`, and keeps the outcome under the key. It writes no consent, no contact grant, and no outbox event. The comment follows the schema rule with the Unicode notion of white space and refuses control characters other than a line break or a tab, because PostgreSQL text cannot hold NUL (400 at `/comment`). -- Responsiveness. The `declined` event (`kind`, `version`, the candidate as `actor_id`, `occurred_at`) is the candidate's answer that the planned responsiveness metrics of the organization count. It is always in time, since a late decline is refused, and it is never a consent or a hire. It holds neither the reason nor the comment. -- Privacy of the decline. The organization reads only `declined` and `responded_at`: none of its operations reads `invitation_declines`, and the audit event names no reason. The comment is never logged, notified, or copied into the stored outcome; the candidate reads both back in `decline`. -- Order of checks after the boundary: the candidate (403), the key (422 or a replay), the invitation (404, stored), the same decline of a declined invitation (200 with a new key or an older version), another reason or comment on a declined invitation, any other terminal state, or a passed deadline (409 whatever the version, stored), the version (412, not stored), then a state without an open answer (409, stored). `invitation_decline_results` keeps only the outcome and the invitation: a declined invitation and its decline never change, so a replay rebuilds the same answer and the comment is stored once. -- Deadline. A command at the deadline or later first applies the due expiry: the invitation moves to `expired` with the reason `invitation_timeout`, and only then are the state and the version checked. A decline at the deadline or later answers 409 `state_conflict`, as the contract requires for a late command. The conditional UPDATEs repeat the deadline, so a command cannot cross it between the check and the write. The lock order and the expiry rules are in [Pending limit, cooldown, and expiry](#pending-limit-cooldown-and-expiry). -- Consent and grant. A decline creates neither a consent nor a grant, so `contact_consent` and `contact_grant` are null after it. The acceptance is described in [Candidate acceptance](#candidate-acceptance). -- Hiding. The candidate's read shows the sending organization even after the candidate hid the profile from it: the hiding keeps the organization from seeing the candidate, while the candidate must know who sent the offer to answer it. The pushed content follows the hiding instead: the inbox notice of the invitation loses its content (`ResolveInvitationNotice`). -- Locks. A candidate command locks the invitation row (`LockCandidateInvitation`) after the candidate's own idempotency record. A decline also takes the organization lock before the row, because it changes the pause of the pair; it never takes that lock after the row. An organization command takes the organization lock first and the invitation row afterwards, so the orders never cross. A view and an acceptance do not lock the organization. -- Database rules of migration 00039: the event kinds `viewed` and `declined` without changed fields; `invitations_answer_matches_state` (a delivered invitation has no view or answer, a viewed one has its view, a declined one its answer, and neither precedes the delivery); the trigger `invitations_guard_answer`, which refuses to move or undo a view or an answer and to leave `declined`; `invitation_declines` with the known reasons, the comment bound, a trigger that ties the row to a declined invitation answered at the same moment, and a refusal of UPDATE and DELETE; and the deferred constraint trigger `invitations_require_decline`, so a declined invitation without its decline cannot commit. The down migration refuses while a view, a decline, or a stored outcome exists. -- Notification. The contract has no notification kind for an answer, so the organization gets no inbox entry for a view or a decline yet; it sees the state in its invitation list. A notice of the answer is planned as a contract change. - -Not implemented: the cancellation, the counter offer that would produce `counter`, the decline aggregates with a minimum group size, the responsiveness metrics, and a notification of the organization about an answer. - -Tests: `domain/invitation_answer_test.go` (the view only from `delivered` before the deadline, the decline from `delivered`, `viewed`, and `counter`, the refusal of terminal and late invitations, the comment rules, the stored answer rules, redaction), `usecase/invitation/answer_test.go` (no side effect of a read, the deadline kept, repeats, order of checks, foreign callers, invalid comments), `adapter/primary/http/v1/invitation_candidate_test.go` (statuses and a response without candidate data), and the integration tests `TestCandidateInvitationViewAndDeclineOverHTTP` (the read and the view with the same deadline, concurrent views with one event, a decline with `other` and no comment without a C4 consent, the stored answer event, replays and conflicts, the comment kept from the organization and the audit, foreign candidates and employers, CSRF and Origin, the hiding, a stale version, a late command) and `TestInvitationAnswerMigrationGuardsAnswersAndRefusesRollback`. - -### Candidate acceptance - -Implemented: `AcceptMyInvitation` ([contract](../../api/README.en.md#invitations-and-contact-grants)). Code: `domain/invitation_answer.go` (`Accept`), `domain/contact_grant.go`, `usecase/invitation/accept.go` and `view.go` (the candidate's view with the consent offer and the grant), `usecase/consent` (`GrantContact`, the C4 record), the HTTP handler `adapter/primary/http/v1/invitation_candidate.go`, the adapter `adapter/secondary/postgres/invitation_accept.go` with `db/queries/invitation_answers.sql` and `db/queries/contact_grants.sql`, and migration `00040_accept_invitations.sql`. - -- One transaction. The candidate accepts the current terms with the consent C4 from `delivered` or `viewed`, before the deadline, at the invitation version and the terms version that the candidate read. The transaction takes its own idempotency record, then only the invitation row (`LockCandidateInvitation`), and then, in order: it moves the invitation to `accepted` with one conditional UPDATE (`responded_at` is the answer time, `version` plus one; the deadline and the terms stay), records the consent C4 in the consent ledger through `consent.Service.GrantContact` (the published text, the organization name as it was shown, the selected fields, the invitation, and its terms version), stores the contact grant of exactly those fields, and appends the audit event `accepted`, which names no field. A failure of any step rolls the whole transaction back. -- Order of checks. The contract order: the candidate (403), the key (422 or a replay), the invitation (404, stored), a repeat of an accepted invitation (200), a terminal state or a passed deadline (409 `state_conflict`, stored), the versions (412 `version_conflict`, not stored), any state other than `delivered` or `viewed` (409, stored), and the consent rules (400 at `/consent_c4/text_version` for a text that is not the published one, and at `/consent_c4/fields/N` for a kind that the profile does not hold). A kind is held when the profile has it as a confirmed claim; a suggestion that nobody confirmed is never disclosed. -- Repeats. An accepted invitation whose grant has the same terms version and the same set of fields answers 200 with the same invitation, under the same key or a new one and with an older `expected_version`, and records nothing. Another terms version or set of fields answers 409 `state_conflict`, stored under the key. The outcomes under a key are `accepted`, `not_found`, and `state_conflict`; a stale version and a consent refusal are not stored. -- The grant. `contact_grants` holds the organization, the candidate, the source invitation (one grant per invitation), the consent record (one per grant), the canonical field set, the terms version, the consent text version, the grant time, and the revocation stamp (`revoked_at` and `revocation_reason`). This change never sets the stamp; the revocation is a later operation. Composite foreign keys tie the grant to its invitation of the same organization and candidate, and to its C4 record of the same subject, organization, invitation, and terms version. A trigger checks that the fields, the text version, and the grant time equal those of the record; a second trigger refuses DELETE and every change other than the one stamp. A deferred constraint trigger refuses to commit an accepted invitation without its grant. The grant holds kinds only, never contact values. -- The candidate's view. While an acceptance is possible, `contact_consent` holds the rendered C4 text and the kinds that the profile holds, in the order of the contract, with nothing preselected; it is null when the profile holds no confirmed kind. After the acceptance, `contact_grant` holds the selected kinds, the status, the terms version, the consent text version, and `readable`. `readable` is true only while the organization may read the profile: the publication is effective and the candidate has not hidden the organization. Otherwise `blocked_by` is `visibility`. A declined invitation keeps both fields null. -- Visibility decision. The acceptance is allowed while the profile is hidden from the organization or not published, as the contract's example of a blocked grant shows. It never publishes the profile, never changes the publication, and never lifts or adds a hiding. The grant stays stored and becomes readable when the candidate publishes the profile or unhides the organization; `readable` is recomputed on every read, so the grant itself never changes. The organization sees `contact_access` as `closed` while the grant is blocked, and as `available` once it becomes readable (see [Contact reads and revocation](#contact-reads-and-revocation)). -- Concurrency. The candidate command never takes the organization lock. Two concurrent acceptances of one version make one transition: the second waits for the row and then answers as a repeat, which is 200 with the same answer for identical terms and fields and 409 for another field set. -- Clocks. The answer time comes from the invitation service and the grant time from the consent service. In production both read the process clock, so they can differ by microseconds; the grant keeps the consent time. A replay of a stored acceptance rebuilds the response from the invitation and the grant. The outcome table keeps no copy of the response, so a later state change would show in a replay, as it would for a decline. -- Ledger keys. The C4 columns of the consent ledger still have no foreign keys to `organizations` and `invitations`: the ledger tests write C4 records with synthetic identifiers. The composite keys of the grant keep an acceptance consistent without that change; the ledger keys need fixtures with real invitations and are a follow-up. - -Not implemented: the counter offer and the cancellation, including the revocation of a grant after the participation is cancelled (the other revocations are in [Contact reads and revocation](#contact-reads-and-revocation)). - -Tests: `domain/contact_grant_test.go` (the grant from its record, the scope and revocation rules, the visibility view, the offer rendering, and `Accept`), `usecase/invitation/accept_test.go` (the order of checks, repeats, stale terms, late commands, consent pointers, visibility without a change of the publication), `adapter/primary/http/v1/invitation_candidate_test.go` (failure statuses), and the integration tests `TestCandidateInvitationAcceptOverHTTP` (an email-only grant, repeats and conflicts, a stale terms version and the raised terms, concurrent acceptances, a hidden profile, a late acceptance, consent and kind checks, the server log) and `TestInvitationAcceptMigrationGuardsAcceptancesAndRefusesRollback` against a real PostgreSQL. - -### Pending limit, cooldown, and expiry - -Implemented: the limit of invitations that wait for an answer per need, the pause of the organization and candidate pair after a decline, and the expiry of an invitation at its response deadline. Code: `usecase/invitation/pending_limit.go` (the send checks), `usecase/invitation/expire.go` (the handler of the job `invitation.response_deadline`, the shared expiry function, and the scheduling at delivery), `domain/invitation_expiry.go` (`Expire` and `ExpiryEvent`), `usecase/invitation/send.go`, `decline.go`, `accept.go`, and `view.go` (the expiry before a candidate answer), the adapter `adapter/secondary/postgres/invitation_expiry.go` with `db/queries/invitation_pending.sql`, `invitation_cooldowns.sql`, and `invitation_expiry.sql`, the registration in `jobHandlers()` (`bootstrap/jobs.go`), and migration `00043_expire_invitations.sql`. - -- Limit. A send counts the invitations of the need that wait for an answer (`delivered`, `viewed`, `counter`) and answers 409 `state_conflict` when there are already `max_pending_per_need` of them in the effective policy (20 in the demo policy). The count is exact: the send takes the organization lock before anything else, and only a send can move an invitation into the waiting states. An invitation without a need has no need limit; the quota bounds it. Leaving the waiting states (a decline, an expiry, an acceptance) frees the place but never returns the weekly quota: the quota is charged at the send and does not change. -- Pause. A send answers 409 `state_conflict` until `repeat_after_decline_days` (30 days) have passed since the latest decline of the candidate by this organization. The pause belongs to the pair of the organization and the candidate, not to a need and not to a member: another need or another owner of the same organization gets the same refusal. The pause after a no deal does not apply yet: no operation produces the `no_deal` state. -- Lock order. A candidate's decline takes the organization lock before the invitation row, like every command that can change the pause of a pair. The decline and a send of the same pair are therefore ordered: a send never misses a decline that committed before its check. The order is the same as in [sending](#sending-invitations): the organization, then the invitation rows. -- Deadline. A send schedules the job `invitation.response_deadline` in the same transaction as the delivery: the key is the invitation identifier, the due time is `response_deadline_at`, and the payload holds only the identifier. The handler `ResponseDeadlineJob` runs in a transaction that locks the invitation row. If the invitation still waits for an answer, it moves to `expired` with the reason `invitation_timeout`; otherwise the handler changes nothing. A repeat of the job is safe: a second run finds no invitation that waits for an answer. -- Candidate commands at or after the deadline. The view, the decline, and the acceptance lock the row and read the time while they hold the lock; the read (`GetMyInvitation`) locks the row only when the deadline has passed. In both cases, when the deadline has passed, the expiry is applied first with the same conditional UPDATE and the same audit event. The read and the view then answer with the invitation in the state `expired`, with no view recorded; the decline and the acceptance answer 409 `state_conflict` and keep the outcome under the key. The list of the candidate's inbox and the organization's reads do not apply the expiry: they show the stored state until the job or the next candidate command applies it. -- What the expiry writes. The transition writes only the audit event `expired` with its version, no field, and no actor (`actor_id` is empty, because the server made the change). No consent C4, contact grant, decline record, or quota change is created or changed. The deadline and the terms are kept. The constraint `invitation_events_system_actor` allows an empty actor only for `expired`, the trigger `invitations_guard_expiry` allows the transition only from `delivered` or `viewed` and not before the deadline, and `invitations_expiry_reason` requires the reason. -- Race with the acceptance. An acceptance at or after the deadline always refuses: the acceptance and the job both decide by a time that is known while the row is held. Whichever path takes the row first, the outcome is one: an `expired` invitation with no grant. An acceptance before the deadline that commits before the job leaves the job without effect. The tests `TestInvitationAcceptAtTheDeadlineRacesTheExpiryJobOverPostgres` (the race) and `TestInvitationDeadlineJobFirstLeavesALateAcceptanceWithoutAGrantOverPostgres` (the job first) check it. -- Clock. The deadline and the limits are decided by the application clock, injected into the usecases and into the job handler; the database clock decides nothing. A handler whose clock has not reached the deadline returns an error, so the job is retried with backoff instead of completing without the expiry. -- Running. The worker that runs the job is the one enabled by `JOBS_ENABLED`; without it the job waits in the database. The candidate commands apply the expiry without the worker, so the candidate's answer stays correct. -- Migration 00043. The new event kind `expired`; the constraints `invitation_events_expiry_changes_no_field` and `invitation_events_system_actor`; the trigger `invitations_guard_expiry`; the partial indexes `invitations_pending_need_idx` (the waiting invitations of a need) and `invitations_declined_pair_idx` (the declines of a pair); and the backfill of the expiry jobs for invitations delivered before the migration, keyed by the identifier with `ON CONFLICT DO NOTHING`. The rollback refuses while expired invitations exist and removes the jobs of this kind. - -Not implemented: the pause after a no deal (it needs an operation that moves an invitation to `no_deal` and sets the end of the pause), the expiry of the `counter` state (no operation produces it yet), the reason `negotiation_timeout`, and a limit for invitations without a need, should one be introduced. - -Tests: `domain/invitation_expiry_test.go` (the expiry of a waiting invitation only after its deadline, the kept deadline and terms, and the event without an actor); `usecase/invitation/pending_limit_test.go` (the limit at 20 waiting and the 21st, two concurrent sends at 19, the freed place without a quota return, the pause at day 29 and day 30 for another owner and another need, and no pause for another candidate or an expired invitation); `usecase/invitation/expire_test.go` (the expiry by a read, a view, an acceptance, and a decline at the deadline, the job and its repeat, and the job refusal of a payload that names no invitation); the integration tests `TestInvitationPendingLimitAdmitsOneOfTwoConcurrentSendsOverPostgres`, `TestInvitationPauseAfterADeclineHoldsForThirtyDaysOverPostgres`, `TestInvitationAcceptAtTheDeadlineRacesTheExpiryJobOverPostgres`, `TestInvitationDeadlineJobFirstLeavesALateAcceptanceWithoutAGrantOverPostgres`, and `TestInvitationExpiryMigrationBackfillsDeadlineJobsAndGuardsExpiries` in `integration_test/invitation_expiry_test.go`. - -### Contact reads and revocation - -Implemented: `GetOrganizationInvitationContacts` ([contract](../../api/README.en.md#invitations-and-contact-grants)) in `usecase/invitation/contacts.go` and `adapter/primary/http/v1/contacts.go`; the disclosure type in `domain/contact_disclosure.go`; the grant lock `ContactGrantRepository.LockForRead` in `adapter/secondary/postgres/invitation_accept.go`; the closings in `consent_revocation.go` (`ConsentRevocationEffects.Apply`), `privacy_view.go` (`CloseForVisibility`), and `contact_grant_closure.go`; the queries in `db/queries/contact_grants.sql`; and migration `00042_index_contact_grants_by_candidate.sql`, which adds the candidate-wide index that the candidate-wide closings use. The organization's `contact_access` is derived in `usecase/invitation/contact_access.go`, through the same `readableContactGrant` check that the read uses (`usecase/invitation/contacts.go`). - -- Access. The company middleware checks the session, the active owner membership, and the path before the handler. A non-owner member answers 403, an account without a membership answers 404, and a candidate account answers 403. The usecase repeats the owner check inside its transaction. In the MVP no other role reads contacts. -- Lock order. The read takes, in this order: the organization and the membership (`LockActiveMembership`, share locks), the candidate account, the newest active C2 record, the publication with its C2 record (which also applies the organization's hiding), the C4 record of the grant, and the grant itself. The unlocked grant read before the locks only names the candidate, which a grant never changes. A C4 revocation locks the record and then the grant in the same order, so the two cannot wait for each other in opposite orders. The visibility locks come first, so a hiding or a C2 revocation that commits first is seen, and one that waits runs after the read commits. -- Decision. The read answers 200 only when the grant is active, its C4 record is unrevoked, and the organization may read the publication now. Every other case answers 404 `not_found` and does not say which one applies: no grant of this invitation for this organization, a revoked grant or C4 record, or a profile that is closed or hidden from the organization. A kind returns its value only when the profile holds it as a confirmed claim; any other kind is null, and a suggestion that nobody confirmed is never disclosed. The response has `Cache-Control: no-store`. -- Closings. Each closing runs in the transaction of the change, stamps the revocation time and its reason, and never reopens a grant: - - Revoking C4 for an organization (`consent_revoked`) closes the grants that name the revoked records. The grants of other organizations and of other invitations stay open. - - Revoking C2 (`visibility_closed`) closes every active grant of the candidate, including when the candidate has no publication row to close. - - Closing the publication (`visibility_closed`) closes every active grant of the candidate. - - Hiding an organization (`visibility_closed`) closes the active grants of that organization, including on a repeated hide. Unhiding and publishing again close nothing and reopen nothing: a closed grant keeps its first stamp, which the guard trigger allows once. - - A grant stored while the profile is not readable is not closed by that state. It stays active and blocked by visibility, becomes readable when the candidate publishes or unhides, and the next closing event closes it. - - Withdrawing an invitation by the organization changes no grant. Cancellation of the participation by the candidate (`participation_cancelled`) is not implemented. A C1 revocation closes no grant, because the contract names no reason for it. -- Organization view. Each organization response that carries `contact_access` derives it from the grant of the invitation, in the transaction of the request: `GetOrganizationInvitation`, `ListOrganizationInvitations`, and the responses of the draft create, update, and send. No grant answers `not_granted`, and a revoked grant answers `closed`. An active grant runs the read's visibility locks and checks, then its C4 record and the grant, so the view says `available` exactly when a read would succeed at that moment, and `closed` otherwise. The view lists the granted kinds only while it is `available`; `closed` carries no reason, and no contact value is ever part of the view. The derivation reads the grant of every state, so a withdrawn invitation keeps the state of its grant, as the contract requires. A declined or expired invitation has no grant and answers `not_granted`. The idempotent replays of a create and of a send return the stored original response, so their `contact_access` is the state at the first answer. The derivation costs one grant lookup per invitation, and it takes the share locks only for an invitation with a grant. -- Quota and audit. A successful read writes one `contact_read` row to `candidate_card_access_events` in the same transaction, with the granted kinds and never a value. It does not consume the card-view quota, because the contract does not count contact reads against it. The candidate's own history read stays a contract-only operation. -- Not implemented: the candidate's cancellation, and the organization's withdrawal. `CurrentContactFields` in `usecase/candidateview` stays closed, because the card-handle read has no contract operation. - -Tests: `domain/contact_disclosure_test.go` (confirmed values only, refused revoked grants, redacted formatting), `usecase/invitation/contacts_test.go` (owner and role checks, visibility, revoked grant and C4 record, unknown invitations), `usecase/invitation/contact_access_test.go` (the organization's states, their agreement with the read in each closing state, a blocked grant that opens once it is visible, and a revoked grant that never reopens), and the integration test `TestOrganizationContactReadsAndRevocationOverHTTP` over the real router and PostgreSQL. It covers the email-only read, the repeated read, the refusals of another organization, a recruiter, and a candidate, C4 revocation with an independent organization, hiding and unhiding without reopening, C2 revocation with republication, closing the publication, and the index. It also checks `contact_access` of the single read and of the list after each change, a declined invitation, and an expired one, which runs last because it moves the clock. `TestCompanyIsolationAndRevocationOverHTTP` walks every organization-scoped operation of the minimal path with the valid session of another company, on the path of the owning company and on its own path with the identifiers from the owner's responses, and checks that each one answers the documented refusal, the same as for an identifier that does not exist, and changes nothing. It does the same for a candidate with the invitation and the notification of another candidate. It also checks that hiding the organization, revoking C4, and withdrawing C2 close the next card, evidence, draft, search, and contact read through the handles of an earlier search, that neither a new C2 nor a new publication revives a grant that C4 revocation closed, that the MVP serves no PDF, selection snapshot, or stored search result, and that the server log, the outbox payloads, the inbox rows, and the stored email requests carry no contact, name, or profile value of the candidates. +The semantic layer is enabled separately: background jobs encode the allowed candidate projection and current company requirements. Search reads stored vectors with matching versions and hashes; it makes no synchronous ML request. PostgreSQL stores vectors; policy versions hold ensemble and calibration parameters. +ML supports Giga-Embeddings-instruct-480M and Qwen3-Embedding-0.6B. Lockfiles pin locally loaded weights; `fake` is for tests. Contacts and private profile text are not sent. Public GitHub repository checks are enabled separately and use only the allowed GitHub API. Generative resume analysis is not implemented. ## Frontend -The target FSD structure has app for router and providers, pages for screens, widgets for larger UI blocks, features for actions, entities for product concepts, and shared for API, UI, and utilities. Imports point down; generated DTOs do not import product entities. TanStack Query owns server state, forms own drafts, and URL parameters own filters and search IDs. Add Zustand only for a specific shared client-state need. +FSD separates `app`, `pages`, `widgets`, `features`, `entities` and `shared`. TanStack Query holds server state, local forms hold drafts, and React Router owns navigation. Styling uses CSS Modules and CSS variables. Vite builds static assets for Nginx; production does not need a Node server. -The shared API wrapper owns base URL, cookies, AbortSignal, and error parsing. MSW is for development and tests; it is not a real integration check. Logout/account switch clears private query cache. Screens need loading, empty, error, retry, and forbidden states. +The API wrapper sends cookies, adds CSRF and decodes contract errors. Account changes clear private caches. MSW supports tests; Playwright exercises the real backend path. Hiding a button does not replace server authorization. -The target screen stack is React Router, TanStack Query, React Hook Form, and Zod, with CSS Modules and CSS variables. Radix UI can be added for complex accessible menus and dialogs. Add Next.js only for a demonstrated SSR or indexable-catalog need; Bun does not replace the selected stable Node and pnpm setup. Vite builds static assets served by Nginx, so production does not need a Node frontend process. These are target choices, not a claim that product libraries are already wired into the scaffold. +## Operations and validation -## Future extensions +Nginx serves the SPA and proxies `/api/v1/`. Internal `/readyz`, `/metrics` and administration interfaces are not public. Client addresses are accepted only through trusted proxies; external headers are not evidence of client identity. -Apache Kafka in KRaft mode is the selected event bus for domain events, mail, ATS webhooks, recomputation, and FSP sync. PostgreSQL remains the source of truth: it keeps product facts and durable job and scheduling state. Events reach Kafka only through a transactional outbox written in the same PostgreSQL transaction as the fact; a relay publishes outbox rows, and consumers are idempotent and tolerate redelivery, reordering across partitions, and retries with deduplication. Redis is not a queue. The core Compose project already runs one internal Kafka node. The outbox table, its transactional writer, the relay, and the consumer runtime are implemented (see "Transactional outbox", "Outbox relay", and "Event consumers" above); one product consumer, `notification_delivery`, is registered; further consumers and additional topics are planned. Extract search, assessment, or notification only for an independent scale or lifecycle need. gRPC is useful when several internal services benefit from protobuf or streaming; it does not replace browser-facing OpenAPI. +Grafana, Prometheus, Loki and Alloy run in a separate Compose project. Configuration collects metrics and logs; alert rules do not mean notifications are configured. ML also requires bearer authentication for `/metrics`; the current ML scrape still needs authentication configuration. A browser telemetry receiver does not imply an installed frontend SDK. -k3s is outside the critical path. Consider it only with an operated cluster or measured multi-node need. A single-node cluster does not provide HA. A transition needs probes and resource limits, secrets, storage backup, ingress, and verified NetworkPolicy. +Run `make docs-check` and the component, integration and E2E targets in [TESTING.md](TESTING.md). Earlier results do not certify a new checkout. Releases record images and configuration in local manifests; restoration and checks are described in [DEPLOYMENT.md](DEPLOYMENT.md). -Vacancies and voluntary applications, recurring assessments, employer complaints/verification, ATS adapters, and deeper matching are future scope. Employer verification and ATS integration are not implemented or required for the first prototype. +Matching quality needs a baseline/model comparison on labeled data and a report with sample size. Synthetic test-retest repeats the same profile with different items and measures agreement; it does not establish human validity. Team deadlines and limits must not be presented as measured results or organizer requirements. -## First product API slice +## Limitations and next steps -| Group | Initial target | -| --- | --- | -| identity | register, verify/resend email, login, logout, me; password reset can wait until the final phase | -| candidate | own profile, questionnaire, consent, publish and hide | -| documents | resume upload, analysis request, job status, confirmation of proposed fields, PDF retrieval | -| assessment | available tests, attempt start, answer save, submit, history, and eligibility | -| company | company profile and current user membership | -| matching | need, confirmation of extracted fields, search create/refine/read | -| invitation | send, list, view, accept/decline, withdraw, and authorized contact access | -| achievement | FSP link state and achievement history; fixture provider for demos | +- Adaptive assessment, subject-matter bank calibration and independent quality evaluation remain separate work. +- Resume import/analysis, standardized PDF, live FSP ID and ATS are not connected. +- Contract operations for salary increases, invitation withdrawal/cancellation and network labs return 501; full negotiation and interviews are not ready. +- Hiring-need requirement versions are retained, but persisted search-result snapshots are not implemented. +- Single-node PostgreSQL, Kafka and SeaweedFS do not provide high availability; verified backups and restoration procedures are needed. +- Access rules and scanners need current checks. A tool list is not an audit report or evidence of successful deployment. -Examples of stable operations are `POST /api/v1/searches`, `POST /api/v1/searches/{id}/refinements`, `POST /api/v1/candidates/{id}/invitations`, and `POST /api/v1/invitations/{id}/accept`. These are target examples, not implemented endpoints. Every business operation, response, and error belongs in OpenAPI with a stable `operationId`. - -Contract rules: UUID identifiers, UTC date-time, explicit enums, integer RUB amounts for the MVP, and bounded cursor pagination. Distinguish null from absent fields. Errors have a stable `code`, safe message, optional field errors, and request ID. Use idempotency keys for invitation creation, analysis start, and assessment submission; scope keys by actor and operation, and reject reuse with a different body. Check access for every object ID, job, search run, and PDF. Never include contacts in common errors or public examples. The contract fixes the error model, Idempotency-Key, If-Match, pagination, and time format in [api/README.en.md](../../api/README.en.md#contract-conventions); of these, only the problem-based error mapping is implemented. - -## Metrics, telemetry, and alerts - -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`. -- Mail: `lincodex_mail_deliveries{kind,status}` for every kind and the statuses `pending`, `waiting_quota`, `unknown`, `accepted`, `rejected`, and `cancelled`, zero included; `lincodex_mail_sender_running`, 1 while this process's mail sending loop runs and 0 otherwise (per process, so aggregate it with `max`; it stays 0 with `EMAIL_PROVIDER=disabled`, where no loop starts); `lincodex_notification_sender_running` reports the same for the notification loop; `lincodex_mail_delivery_oldest_due_pending_age_seconds`, which counts only service mail (`domain.ServiceMailKinds`), so a notification backlog never looks overdue; `lincodex_mail_sender_cancelled_total{reason}`, deliveries the sending worker ended without sending, by the closed set of cancel reasons, zero included; and, for an active transport, `lincodex_mail_quota_used_recipients`, `lincodex_mail_quota_limit_recipients`, and `lincodex_mail_quota_provider_exhausted`, each with `provider` and `window` (`day` or `month`). The sampler in `backend/internal/worker/deliverymetrics/` reads them every 30 seconds on its own one-connection pool: `postgres.DeliveryStatisticsStore` aggregates `deliveries` by kind and status, and `MailQuotaUsageReader.Usage` reads the current windows of the configured account. The delivery aggregate is the sqlc query `GetDeliveryStatistics` in `db/queries/delivery.sql`. It scans the table, which suits the current volume; add an index or per-status counters before the table holds millions of rows. `EMAIL_ACCOUNT` is not a label: it is free operator text that can name a person, and each process reports only its own account. Every instance reports the same database-wide values; aggregate them with `max`. A failed read keeps the previous values and logs `delivery metrics could not be read; the gauges are stale`; `lincodex_mail_metrics_last_success_timestamp_seconds` shows the last read in which every aggregate was read (0 from the sampler start until the first one), and the age gauge exists only after the first successful read. There is no attempt outcome counter yet; the delivery states, the logs of the sending worker, and the `delivery_attempts` history show outcomes. -- Assessment answers: `lincodex_assessment_answer_saves_total{format,outcome}` with the outcomes `stored`, `unchanged`, `rejected`, and `failed`. PRD 6.6 asks to observe the saving of answers; this is read as the assessment answer command `SubmitMyAssessmentAnswer`. The command is implemented, but nothing calls the hook `Metrics.ObserveAssessmentAnswerSave` yet, and no series appears until the usecase calls it once per command. A value outside the closed sets becomes `other`. The HTTP latency and errors of the command already appear under the route `/api/v1/me/assessment-attempts/{attempt_id}/answers`. - -Do not use user, candidate, delivery, or request IDs, full URLs or query strings, addresses, or resume content as labels. Unit tests drive the real router and every metric hook with email and UUID fixtures and fail when the exposition contains an email-like or UUID-like value. Go runtime, PostgreSQL, Redis, SeaweedFS, Linux, and Lincodex product dashboard JSON files are maintained project sources, not imported dashboard IDs. Inference metrics are not implemented in the current scaffold. - -Planned observability work includes bounded measurements for queued jobs, oldest ready age, wait and run duration, retries, and terminal failures; pgxpool state should use bounded nonblocking reads inside Go. Nginx `stub_status` does not provide latency by HTTP status; access logs can provide `request_time` and `upstream_response_time`. cAdvisor is optional if the selected runtime supports it. Redis exporter is included in the separate monitoring Compose project; Prometheus scrapes its internal port 9121. SeaweedFS metrics are scraped directly on internal port 9327, retaining only selected aggregate series without object paths. DCGM exporter is only needed with a local NVIDIA model. - -The planned browser path is Faro Web SDK -> same-origin `/telemetry` -> Alloy `faro.receiver` -> Loki. The React SDK is not connected yet. Collect cleaned Web Vitals, JavaScript errors, release, and normalized route; exclude console logs, form content, resume text, and session replay. Remove query strings, fragments, and identifiers from URLs. Limit receiver size, rate, and origin. Request/trace IDs remain log fields, not labels; complete span storage needs a separate backend such as Tempo and is not currently supported. - -Alert rules in `observability/prometheus/rules/lincodex.yml` cover an unavailable backend target, a 5xx share above 5% with at least 15 requests in 5 minutes, outbox lag, dead letters and stalled consumers, dead and lagging scheduled jobs, deliveries with an unknown outcome, stale delivery and quota gauges, a used-up mail quota, and overdue deliveries; the last one also requires `lincodex_mail_sender_running` to be 1 on some instance, so it stays silent where no sending loop runs, for example with `EMAIL_PROVIDER=disabled`. It counts only service mail, the kinds the worker sends, so a due notification does not fire it. `LincodexMailCancelledBroken` fires on an increase of `lincodex_mail_sender_cancelled_total` with the reason `content_invalid` or `processing_failed`, the cancellations that mean a broken row or a defect rather than a user action; the rights reasons of notifications (`rights_revoked`, `recipient_ineligible`, `source_closed`) are normal and do not fire it. `promtool test rules` gives every alert a firing case and every guard a silent one. Prometheus evaluates them and shows their state on its /alerts page and in Grafana; no Alertmanager or notification channel is configured, so no alert reaches a person. Future alerts cover latency budget breaches, disk pressure, ML errors, and dropped logs. Low traffic needs a window and minimum event count to avoid unstable rates and percentiles. Configure `No Data` and datasource-error behavior explicitly. A monitoring stack cannot reliably report a host failure on that same host; that requires an independent external health check. Compose and dashboard smoke checks do not verify alert delivery. Document alert rules and notification channels as implemented only after they have been tested. - -## Requirements coverage - -| Brief requirement | Target decision | State | -| --- | --- | --- | -| Two portals and verified email, pp. 3-4 | identity, roles, company, access checks | Implemented (no password reset) | -| Manual or PDF resume, p. 3 | Manual profile first; PDF and ML extend it | Manual profile implemented; PDF and ML import are not | -| Standard PDF, p. 3 | PDFRenderer with Cyrillic and access checks | Not implemented | -| Questionnaire, grade, test, category, pp. 1-3 | assessment, variants, grade history | Implemented on a demonstration bank; categories are uncalibrated | -| Comparable tests and leak resistance, pp. 1-2 | Families, blueprint, rubrics, rotation, pilot | Planned | -| No forced grade decrease and change frequency, pp. 2-3 | verified/claimed, retry, cooldown, eligibility | Planned | -| Candidate search and explanation, pp. 3-4 | Hard filters, matching evidence, score components | Basic deterministic search implemented; ML, competition data, and snapshots are not | -| Refine search without losing prior results, p. 4 | Versioned search runs and server snapshots | Planned | -| Invitation without a vacancy, p. 3 | Optional vacancy_id | Not implemented | -| RUB salary range and employer contact, p. 4 | Required bounds and explicit period/tax basis | Implemented | -| Status for both sides, p. 4 | State machine and event history | Partial: draft, delivered, viewed, accepted, declined, expired; later stages, withdrawal, and cancellation are not | -| Contacts after acceptance/application, pp. 3-4 | Contact grant, separate DTOs, file access check | Contacts after acceptance implemented; files and candidate applications are not | -| Privacy and access to own records, pp. 3, 6 | Consent, object/company authorization, cache and snapshot checks | Consents, publication, hidden organizations, history, and access checks implemented; no match snapshots | -| FSP ID and missing history, pp. 2, 6 | External identity and fixture provider; empty history allowed | Real API unknown | -| Real FSP integration | Port and separate DTO until API is supplied | Not implemented | -| Recurring assessments, p. 3 | Consent, scheduled worker job, freshness signal | After MVP | -| Vacancies and applications, pp. 3-4 | vacancy/application and contact grant | After core flow | -| Unreliable employers and ATS, pp. 2-3 | Verification, complaints, limits, provider adapters | Future plan | -| Open source, API, launch, pp. 5-6 | Repository, OpenAPI, Compose, instructions | Technical scaffold | -| Dozens of users, p. 6 | Worker limits, indexes, pagination | No load test | -| Documentation and validation results, pp. 5-7 | RU/EN docs, API, separate evaluation report | Docs exist; evaluation absent | -| Presentation and prototype access, pp. 5-8 | Demo environment and backup recording | Unverified | - -## Quality evaluation and numerical limits - -The initial matching evaluation proposes 60-100 synthetic candidates and 8-12 varied employer needs. Two people label candidate-need pairs independently and resolve disagreements. Holdout is split by need; near-duplicate profiles do not appear in both tuning and evaluation. - -Compare keyword search, verified-skill baseline, and ML. Metrics are Precision@5, nDCG@5, hard-filter violations, category coverage, and share of relevant results without FSP history. Define the denominator in advance when fewer than five candidates qualify and report result-set size. A small synthetic sample does not prove quality for the real labor market. - -Assessment pilot uses equivalent forms and varies their order for part of the participants. Measure grade agreement, score spread, task-level decisions, and separation between stronger and weaker groups against independent expert assessment. Synthetic weak/strong answers help debug scoring but do not replace a human pilot. - -ML evaluation uses a fixed resume set with labeled fields. Measure extraction errors and invented facts, recommendation usefulness under a human rubric, schema-valid rate, latency, and failures. Record model, prompt/schema version, parameters, and date. Compare with a simple baseline and use lawfully handled, de-identified inputs. - -These are proposed acceptance targets, not results: 30 concurrent users; p95 profile reads under 500 ms; baseline search under 1 second on demo data, excluding external network time. Set a separate ML budget. Quality and load runs have not been performed. - -## Future critical checks - -- No contact data appears before a grant in API, search, PDF, errors, or employer-facing ML explanations. Another company never receives it after acceptance. -- Candidates cannot read other users' invitations, documents, jobs, or attempts. Companies cannot read other companies' needs or search runs. -- Failure never lowers grade; first lower-level retry is permitted; concurrent requests cannot bypass the 90-day promotion limit. -- Repeated submit/accept does not create duplicate results; concurrent state transitions are consistent. -- The manual path works when ML is off; a worker recovers an expired lease; an old response cannot overwrite a newer document version. -- Empty FSP history differs from an integration error and does not exclude a candidate. -- Refinement keeps the earlier snapshot; hidden profiles disappear from older snapshots. - -## Team milestones - -The October 11 critical path is email -> profile/questionnaire -> grade selection -> assessment -> category -> search -> salary offer -> acceptance -> contacts. Include a demo candidate with no FSP history. If schedule slips, cut specialty count, AI depth, and decorative screens while preserving the core flow and privacy. - -Team plan: October 5 - contract, data model, scaffold, and frontend foundation; October 6-9 - identity, profiles, assessments, search, invitations, UI, and ML work in parallel; October 10 - integration and fixes; October 11 - demo. October 12-16 - PDF, grade history, worker reliability, and privacy checks; October 17-22 - assessment pilot and search evaluation; October 23-26 - vacancies or recurring assessments if core work passes; October 27-29 - feature freeze, load test, backup recovery, and presentation; October 30 - final handoff. - -The application host, ML resources, inference budget, SMTP/domain, and pilot participants remain undecided. Without them, the team cannot promise a public demo, model speed, or categorization quality. The current task creates a technical scaffold; product logic is separate work. +See [DEPLOYMENT.md](DEPLOYMENT.md) for demo startup and the scenario, [TESTING.md](TESTING.md) for acceptance, and [SECURITY.md](SECURITY.md) for security rules. diff --git a/docs/en/COMPANY_QUOTAS.md b/docs/en/COMPANY_QUOTAS.md deleted file mode 100644 index 4565424..0000000 --- a/docs/en/COMPANY_QUOTAS.md +++ /dev/null @@ -1,47 +0,0 @@ -# Company quotas - -Company quota reservations are implemented in the domain, `companyquota` usecase, and PostgreSQL adapter. They provide a transaction-bound storage port for invitation and candidate-card usage. An invitation spends one place of the weekly quota when it is sent (`SendOrganizationInvitation`): a draft spends nothing, and a repeat of the send of the same invitation does not spend a second place. An invitation that leaves the waiting state (a decline, an expiry, an acceptance) frees its place in the per-need pending limit, but never returns the weekly quota; see [Pending limit, cooldown, and expiry](ARCHITECTURE.md#pending-limit-cooldown-and-expiry). - -## Policy and trusted organization level - -Each operation takes one UTC application-clock snapshot and reads the effective version of `ProductPolicyKey`. Limits come from that versioned policy. The bundled demo policy currently enables E0 at 10 invitations per rolling 7 days and 50 distinct candidate-card views per rolling 24 hours. E1 is 40 invitations per 7 days and 150 distinct views per 24 hours. - -E2 has configured limits of 100 invitations and 400 distinct views, but its tier is inactive in the bundled demo policy. E2 can be used only when an effective policy activates it and the organization loaded from storage has the corresponding verified level and basis. E3 has no quota tier and is denied. The caller cannot choose or raise a tier. - -The quota snapshot captures the policy version and the stored organization verification level, basis, and change time. Before writing, the PostgreSQL adapter locks the organization and checks those values and the effective policy version again. If either changed, it returns `outbound.ErrCompanyQuotaSnapshotChanged` without writing usage. The caller must reload policy and organization state, then retry the whole transaction. - -## Reservation and transaction order - -Call `companyquota.Service.ReserveInvitation` or `ReserveCardView` with repositories from the current `outbound.UnitOfWork`. The repository returned by `UnitOfWork.CompanyQuotas()` is transaction-scoped and must not be retained. Make the quota reservation and its eventual business change in the same transaction so rollback removes both. The service is constructed with the application clock and reads the effective policy once per operation. - -Tenant authorization remains the caller's responsibility. Recheck active membership and owner permission inside the same transaction. Writers follow this order: organization, then for an E0 organization its holding (see [Holding pool](#holding-pool)), active membership, invitation or visibility record, then quota usage. The quota adapter locks the organization row first and, for an E0 organization, the holding row right after it; a caller that already holds those rows may lock them again in the same transaction. Do not reverse this order. - -The organization lock serializes concurrent reservations of one organization, and the holding lock serializes the shared E0 pool. The adapter checks existing usage, counts the active window, and inserts or refreshes usage while those locks are held. A decision is either allowed or denied; reuse implies allowed. A denied reservation writes no usage and includes `RetryAt`, the earliest active usage expiry that can free capacity. - -## Windows and retries - -An invitation is keyed by `(organization_id, invitation_id)`. Repeating the same invitation ID is allowed as reused, even with a different request idempotency key and after the rolling window. Its usage evidence remains for the organization's lifetime, so removing an invitation in a future workflow will not refund quota. - -A card view is keyed by `(organization_id, candidate_id)`, so viewing the same candidate again during the active window does not consume another distinct-view slot. The repeat refreshes `last_seen_at` monotonically: a backdated application clock cannot move the stored time backward. - -The active-window query uses a strict comparison with the cutoff. A row exactly at `now - window` has expired. Invitation usage is counted over seven rolling days; card views are counted over 24 rolling hours. The limits apply across requests and users of the organization, except that an E0 organization shares its limits with the other E0 organizations of its holding (see [Holding pool](#holding-pool)). - -Expired card-view rows are deleted in batches of at most 100 after a successful allowed reservation. Window expiry is logical; this cleanup does not promise deletion at an exact time. Deleting a candidate account cascades its card-view usage row. Deleting an organization cascades both quota tables. Invitation usage has no invitation foreign key, so future invitation withdrawal cannot erase its idempotency evidence. - -## Holding pool - -A holding groups the organizations that one founder account created; the `holdings` table and the migration `00041_create_holdings.sql` store it. `CreateWithOwner` stores each new organization in the holding of its owner account in the same transaction. The holding of an account is created with its first organization, and concurrent creations of one account end in one holding, because the insert ignores an existing founder key and the transaction then reads the stored holding. A holding carries no profile and no right; its only effect is the shared E0 pool. - -The E0 limits (10 invitations per 7 days and 50 distinct card views per 24 hours in the bundled demo policy) are shared by the E0 organizations of a holding. An E0 reservation counts the usage rows of every organization of its holding whose trust level is E0 when the count runs. Each usage row stays attributed to the organization that consumed it, and usage of an organization that is no longer E0 leaves the shared pool. An organization at E1 or above counts only its own usage and keeps its own pool, so its usage does not count toward the E0 pool. - -Idempotency stays per organization. The same invitation ID, or a repeated view of one candidate by the same organization inside the window, is not charged twice. The same candidate viewed by two organizations of one holding is two charges of the shared pool. - -Locks: for an E0 organization, `CompanyQuotaRepository.LockOrganization` and each reservation take the holding row with `FOR NO KEY UPDATE` right after the organization row. Reservations of one pool therefore run one after another, and the second one counts the usage that the first one committed, because it counts only after the holding lock. Every writer takes the organization lock before the holding lock, and no code takes an organization lock while it holds a holding lock, so the holding lock adds no cycle to the documented order. The cost is that E0 searches, card reads, and invitation drafts or sends of one holding wait for one another while their transactions are open; a search holds the lock for its whole ranking transaction. - -The migration gives each founder one holding: the founder of an organization is the account of its earliest membership, which is the creator's owner membership, and the holding is dated by its first organization. The rollback refuses while a holding groups several organizations, because the schema without holdings could not keep their E0 pool together. Merging holdings of different owners is out of scope. - -## Verification - -`TestHoldings` in `backend/integration_test/holding_test.go` covers the shared E0 pool of two organizations of one account with a verified organization apart, a second account's own holding, usage leaving the pool when its organization is raised, concurrent reservations from two organizations that never exceed the shared limits, concurrent creations ending in one holding, and a refused creation of an unknown founder. `TestHoldingsMigrationBackfillsFoundersAndGuardsRollback` in `backend/integration_test/holding_migration_test.go` covers the backfill and the guarded rollback. - -`TestCompanyQuota` in `backend/integration_test/company_quota_test.go` exercises the real PostgreSQL adapter in an isolated database. It checks concurrent E0 reservations, E0/E1 boundaries, exact window cutoffs and `RetryAt`, same-ID invitation reuse, cross-request card-view reuse, monotonic refresh, rollback, policy or organization snapshot changes, an allowed reservation with an active E2 policy and stored E2 verification, rejection of a forged E2 snapshot for a stored E0 company, inactive E2 and E3 denial, and candidate-deletion cleanup. It does not test a delivered invitation because that workflow is not implemented. diff --git a/docs/en/DEPLOY.md b/docs/en/DEPLOY.md deleted file mode 100644 index 03d96c2..0000000 --- a/docs/en/DEPLOY.md +++ /dev/null @@ -1,1047 +0,0 @@ -# Local deployment and Compose - -This guide describes the checked-in configuration. Compose provides a local technical stack; it does not establish a production deployment. - -## Running the MVP: quick start - -This section is for anyone who starts the MVP on their own machine: the jury, the team, or a reviewer. Run the commands from the repository root; the other sections of this guide describe each setting in detail. The scenarios below were run on a fresh clone with the example files `.env.example` and `deploy/demo/demo.env.example`. - -### Implemented and planned - -Implemented in this build (backend API and frontend screens): - -- Candidate and employer registration with consent C1, email confirmation with the six-digit code or the link from the message, sign-in, sign-out, and resuming from the saved step. Mail is sent only with `EMAIL_PROVIDER=resend`. -- Candidate cabinet: consents C1-C5, a manual profile without a resume and without an FSP ID, the questionnaire with specializations and self-assessment, and the home page with the next step. -- Skill assessment: the `demo_express` demonstration express run without a grade and the `demo_basic` full test with a result, result history, and skill evidence. On the demo stand a passed full test receives an uncalibrated synthetic category. The operator can read the [review band](#assessment-review-band). -- Privacy: publication of the anonymous card (C2), preview, search status, hidden organizations, and the history of changes and card views. -- Employer cabinet: organizations (one account can own several and be a recruiter in others), the company profile, needs with a salary range, deterministic candidate search over the bank or by a need without ML, with an explanation of the components, and the anonymous card with its evidence. Only an organization owner can search. -- Support cases in both cabinets, including a manual assessment request after a C3 refusal. -- The notification inbox in both cabinets. A delivered invitation creates a notification for the candidate; the mail about it is sent only with `EMAIL_PROVIDER=resend`. -- Invitations: the organization creates a draft from a search result, changes the terms with versions, and sends the invitation. The candidate sees it in the incoming list and accepts it with the consent C4, choosing the contacts, or declines it. After the acceptance the organization reads the disclosed contacts on the invitation page. The company's invitation list is still a placeholder. - -Planned and not working: withdrawing an invitation and the candidate's cancellation of participation, salary raise (the API answers 501 `not_implemented`), password reset, mail for other product notifications, resume upload and parsing, PDF, FSP integration, ML inference and semantic search, the adaptive test, sandbox practice, percentiles and calibrated grades, and the SMTP transport. - -### Requirements - -Docker Engine with the Compose plugin, GNU make, python3 (the `deploy` targets run check scripts), and openssl to generate a secret. No GPU, external inference key, or FSP access is needed: no target reads one. The first start builds the backend and frontend images and pulls base images, so it takes several minutes; later starts use the cache. - -### Stand parameters - -| Stand | Command | Compose project | Address | Data | -| --- | --- | --- | --- | --- | -| Core | `make -C deploy up` | `APP_PROJECT`, default `app` | http://localhost:8080 (`APP_HTTP_PORT`, bound to `APP_HTTP_BIND=127.0.0.1`) | Migrations and the startup policy version 1; no assessment bank, matching section, or accounts | -| Demo | `make -C deploy demo-seed DEMO_MODE=isolated` | `DEMO_PROJECT`, default `lincodex-demo` | http://localhost:8090 (`DEMO_HTTP_PORT`, `DEMO_PUBLIC_URL`) | Synthetic accounts, organizations, assessment bank, and prepared attempts | -| Technical smoke | `make -C deploy smoke` | `lincodex-smoke`, removed after the run | 127.0.0.1:18080 during the check | None | -| ML | `make -C deploy ml-up` | `ML_PROJECT`, default `ml` | http://127.0.0.1:8000 (`ML_HTTP_PORT`) | No model; `/readyz` answers 503 | -| Monitoring | `make -C deploy monitoring-up` | `MONITORING_PROJECT`, default `monitoring` | Grafana http://127.0.0.1:3000 | Metrics and logs of the core stack | - -- Open a stand exactly at the address in `APP_PUBLIC_URL` or `DEMO_PUBLIC_URL`, that is through `localhost`. The backend compares the Origin of every changing request with this address, so signing in from a page at http://127.0.0.1:8090 is refused with 403 `csrf_check_failed`. The session cookie has the `Secure` flag; browsers accept it at http://localhost, and another host needs HTTPS (see [Edge proxy, HTTPS and tunnel](#edge-proxy-https-and-tunnel)). -- Make takes the project name from the command line or the environment, not from `.env`. To run a stack under another name, pass the same value to every target: `make -C deploy up APP_PROJECT=`, then `logs` and `down` with that value. The port and bind address come from `.env`. -- The core and demo stands use different subnets and ports and can run at the same time. - -### 1. Core stack - - cp .env.example .env - # replace every replace-this-... value with your own; - # POSTGRES_PASSWORD takes URL-safe characters only, for example hex - # IDENTITY_KEY_SECRET= paste the output of: openssl rand -base64 48 - make -C deploy config - make -C deploy up - curl http://localhost:8080/api/v1/healthz - -The last command answers `{"status":"ok"}`; then open http://localhost:8080. Compose does not start with an empty `IDENTITY_KEY_SECRET`, and the backend refuses a value that starts with `replace-this`. `make -C deploy smoke` is a separate throwaway technical check: it starts its own stack with the values of `.env.example`, checks the health routes, dependency failures, and storage isolation, and removes its containers and volumes. It does not check the running stack and does not prove a business workflow. - -The core stack is a clean base for a working stand. Without further steps it serves the public pages, registration, and the health checks. No assessment bank is loaded, so a test cannot start, and search answers 500 until an operator publishes the matching section (see [Match search policy on a stand](#match-search-policy-on-a-stand)). Use the demo stand to show the product. - -### 2. Mail: Resend or disabled - -- `EMAIL_PROVIDER=disabled` (the `.env.example` value) sends nothing. Registration is accepted (202), but the address cannot be confirmed, so signing in with such an account answers 403 `email_not_verified`. The prepared accounts of the demo stand need no mail. -- `EMAIL_PROVIDER=resend` sends confirmation mail through Resend. Set `RESEND_API_KEY` in the server environment only and never commit it, set `EMAIL_FROM` to an address on a domain verified in the Resend account, and set `APP_PUBLIC_URL` to the origin the user opens, because the link in the message leads there. Then run `make -C deploy up` again. Only confirmation mail and the mail about a new invitation are sent; the default quotas are 100 recipients per day and 3000 per month (see [Mail](#mail) and [Mail quotas](#mail-quotas)). The repository does not test real Resend: the browser test `make -C deploy test-e2e-registration` registers through a local Resend-compatible inbox. -- `EMAIL_PROVIDER=smtp` stops the backend at startup in this build. - -### 3. Demo stand - - make -C deploy demo-seed DEMO_MODE=isolated - -The target needs the root `.env` from step 1: the stand takes the secrets and the mail transport from it and overrides the project name, port, address, and subnet. The command starts a separate project, waits for backend readiness, fills the database with synthetic data, and prints the list of logins; a repeated run creates nothing and prints the same list. Open http://localhost:8090; the jury guide is at http://localhost:8090/demo. - -Every prepared account uses `DEMO_ACCOUNT_PASSWORD` from `deploy/demo/demo.env`, or from `deploy/demo/demo.env.example` when that file does not exist. The example value is a published demo credential of synthetic accounts, not a secret. For a stand reachable from outside, copy the example to `demo.env`, set a new password, run `make -C deploy demo-reset DEMO_MODE=isolated`, and give the password to the jury separately. - -| Login | Purpose | -| --- | --- | -| `candidate@demo.lincodex.test` | Self-guided run: the express run and the Backend Junior full test with Go | -| `prepared-1@demo.lincodex.test` - `prepared-6@demo.lincodex.test` | Candidates with a completed full test, a synthetic Backend Junior category, evidence, and a published card | -| `employer-alpha@demo.lincodex.test` | Owner of the "Alpha" organization and recruiter in "Beta" | -| `employer-beta@demo.lincodex.test` | Owner of the "Beta" organization | - -The full inventory and the seed rules are in [Isolated demo stand](#isolated-demo-stand). - -### 4. Demonstration route - -1. Candidate: sign in as `candidate@demo.lincodex.test` and open the skill assessment (`/candidate/assessment`). The express test has three items and ends with the result "Экспресс-тест без грейда" (express test without a grade): no grade, category, percentile, or evidence, and it does not appear in the real result history. This is the express run without a grade. -2. On the same page start the Backend Junior full test with Go: 25 items, a 72-hour deadline, two work sessions, no practice. After it completes, the result is compared with the pass mark of the demo policy; a passed test receives an uncalibrated synthetic category, a failed one the result `not_confirmed`. The result and the history open at `/candidate/results`. -3. Prepared candidate: sign in as `prepared-1@demo.lincodex.test` and open the results, the skill evidence, and the privacy settings with the published card. -4. Employer: sign in as `employer-alpha@demo.lincodex.test`, select "Alpha", create a need, and open the search (`/employer/candidates`). The main group holds the six prepared cards with the flags `ml_unavailable` and `cohort_below_30`; a card and its evidence open from the results. In "Beta" the same account is a recruiter, and search answers 403: in the minimal release only the owner can search. -5. Invitations: the company creates an invitation with the "Invite" button of the first card of the main group, fills in the tasks and the team description (the need does not fill them), sends it, and keeps the address of the invitation page: it holds `invitation_id`. Equal cards keep a fixed order, and the first one belongs to `prepared-1@demo.lincodex.test`. This candidate accepts the invitation at `/candidate/invitations`, choosing the contacts and the consent C4, and the company reads the disclosed contacts on the same invitation page. The company's invitation list is still a placeholder, so keep the page address. - -The eight-minute step-by-step guide with links to the screens and the logins is on the stand at `/demo`; the start page has the button "Open the jury guide". The guide exists only in the demonstration stand build. - -### 5. FSP, ML, and data - -- FSP: there is no integration in any mode. This build has no off or mock switch, no fixture provider, and no call to an external API. The profile is filled in manually, linking an FSP ID is optional and not available yet, and the path to a category goes through the questionnaire and the test. The project has no official access to FSP data and does not promise it; an FSP link through a fixture provider is planned (see [ARCHITECTURE.md](ARCHITECTURE.md#identity-fsp-and-privacy)). -- ML: by default the core and demo stands do not start ML and do not call it; search uses the neutral semantic similarity 0.5 with the `ml_unavailable` flag. Semantic matching is enabled separately: the ML service with the Giga-Embeddings-instruct-480M and Qwen3-Embedding-0.6B models (the ML Compose project on CPU or the [ML service on a GPU host](#ml-service-on-a-gpu-host)), the shared token `ML_SERVICE_TOKEN`, `SEMANTIC_MATCHING_ENABLED`, the semantic policy, and a backfill (see [Semantic matching](#semantic-matching)). No external inference keys are needed or read. -- Data: the demo stand holds synthetic data only. Addresses on the reserved domain `@demo.lincodex.test` never receive mail, names are marked as synthetic, categories have the source `synthetic_demo` and are uncalibrated, and the item families are synthetic and had no subject review. Do not register real people on this stand. Synthetic categories are enabled (`ASSESSMENT_DEMO_CATEGORIES_ENABLED=true`) only by the demo overlay and by the overlay of the isolated registration browser suite (see [TESTING.md](TESTING.md#minimal-path-from-registration-to-disclosed-contacts)); `.env.example` sets `false`. - -### 6. Checks - -| Command | What it shows | -| --- | --- | -| `make docs-check` | Documentation structure and local links | -| `make -C deploy config` | Rendering of every Compose file without starting it | -| `make -C deploy smoke` | Technical smoke on a throwaway stack | -| `make -C frontend install`, then `make -C deploy test-e2e` | The Playwright browser suite on a throwaway stack | -| `make -C deploy test-e2e-registration` | Browser registration, confirmation, and sign-in through a local Resend-compatible inbox | -| `make -C deploy check-demo` | The guards of the demo stand targets without starting services | -| `make test`, `make check`, `make verify` | The full check set, see [TESTING.md](TESTING.md#commands) | - -The smoke and the browser suites do not start the demo stand; an integration test covers its seed (see [Demo seed tests](TESTING.md#demo-seed-tests)). - -### 7. Stop and clean up - - make -C deploy down - make -C deploy demo-down DEMO_MODE=isolated - make -C deploy ml-down - make -C deploy monitoring-down - -These targets stop the containers and keep the volumes. `make -C deploy demo-reset DEMO_MODE=isolated` recreates the demo stand with its initial data only when it holds no ordinary account; otherwise the reset refuses and deletes nothing. Removing a demo project together with its data is a deliberate manual decision only: `docker compose -p lincodex-demo down --volumes` with the name of your project. The `-backend`, `-frontend`, and `-demo-seed` images built by these targets stay local; remove them with `docker image rm` when they are not needed. - -## Core application - -Install Docker Engine and the Docker Compose plugin. At the repository root, copy .env.example to .env, replace every placeholder password, and keep the file local. Then run: - - make -C deploy config - make -C deploy up - -deploy/docker/docker-compose.yml starts PostgreSQL, Redis, SeaweedFS, Kafka, the Go backend, and the frontend container. Nginx in the frontend container serves static assets and proxies /api to Go. PostgreSQL, Redis, SeaweedFS, Kafka, Go, and Nginx communicate on the Compose network. - -Before it opens its listeners, the backend applies the database migrations embedded in its binary; a migration error stops the container. Compose does not pass `DATABASE_MIGRATE_ON_START`, so the deployed backend always migrates at startup, and the PostgreSQL role in `DATABASE_URL` needs DDL rights on the application schema. That flag is a local development option; a separate least-privilege migration role is future work. Right after the migrations, and only when they run, the backend seeds the demo product policy: when the `product` policy family has no version, it publishes version 1 and logs `demo product policy published`; otherwise it logs that the seed was skipped and changes nothing. With `DATABASE_MIGRATE_ON_START=false` the seed is skipped too. A database error during the seed stops the container like a migration error. See [DEVELOPMENT.md](DEVELOPMENT.md#database-migrations) and [ARCHITECTURE.md](ARCHITECTURE.md#product-policy-versions). - -Consent texts are published by migrations, not at startup: migration 00009 publishes the demo texts `c1-2026-10-01` to `c5-2026-10-01` with `kind` `demo`. The database refuses to change or delete a published text, so a new text is a new version in a new migration, and the texts of the actual operator must be published that way before real personal data are accepted. An account with consent history cannot be deleted with a plain `DELETE FROM users` (SQLSTATE 23001 on `consent_records_subject_id_fkey`), and the consent records of a confirmed account cannot be deleted at all (SQLSTATE 23000, `consent_records_retained`); only the unverified account cleanup and the re-registration of an unverified account remove consent records. See [ARCHITECTURE.md](ARCHITECTURE.md#consent-ledger). - -The backend build context is `backend/`, so Docker applies `backend/.dockerignore`. Local tools, caches, environment files, and build outputs are excluded from that context. - -The current `postgres:alpine` volume mounts at `/var/lib/postgresql`; the image stores data in a subdirectory for its major version. When the tag advances to a new major version, migrate an existing database with `pg_upgrade` or backup/restore. Updating the image alone does not convert the data. - -Open http://localhost:8080, the address in `APP_PUBLIC_URL`: from another origin, changing requests, including sign-in, are refused. The host port binds to loopback. Nginx handles /healthz, proxies /api/v1/ to Go, and uses the SPA fallback for other paths; see [Public perimeter and client address](#public-perimeter-and-client-address). The public API health route is /api/v1/healthz through Nginx /api/v1/. On the internal port 8080, Go also serves /healthz for the process and /readyz, which checks PostgreSQL with SELECT 1, Redis with PING, and the SeaweedFS bucket with HeadBucket; any dependency being unavailable produces 503. The internal backend port 9090 serves /metrics. - -This Nginx configuration has no production TLS. The current bind does not expose the app directly to the public network. Remote access needs a selected TLS reverse proxy, firewall rules, and environment-specific configuration. - -Useful commands: - - make -C deploy config - make -C deploy up - make -C deploy logs - make -C deploy down - make -C deploy smoke - -Redis uses `redis:alpine`, the `REDIS_PASSWORD` value from `.env`, and the internal `redis:6379` address; it publishes no host port. Data is limited to 128 MB with `allkeys-lru` eviction, and the container memory limit is 256 MB. RDB and AOF are disabled with no persistent volume: restarting Redis clears the cache. Do not keep the only copy of a record there. The backend and Redis exporter both require its password. - -Backend settings are `REDIS_ADDR`, `REDIS_PASSWORD`, `REDIS_DB`, and `REDIS_TIMEOUT`. Compose supplies `redis:6379`; a directly launched Go process defaults to `localhost:6379`, DB 0, and a 1s timeout. Provide a separately reachable Redis address for direct execution because the current Compose does not publish Redis outside its network. - -SeaweedFS uses `chrislusf/seaweedfs:latest` with `weed mini`: master, volume, filer, and S3 API share one container. The named `seaweedfs_data` volume mounts at `/data` and preserves object content and metadata. S3 is reachable only inside the network at `http://seaweedfs:8333`, with no published host port. WebDAV, Admin UI, IAM API, Iceberg, and Lance are disabled. Nginx continues to serve the frontend and `/api`; there is no direct object route. - -Set `SEAWEEDFS_ACCESS_KEY` and `SEAWEEDFS_SECRET_KEY` in `.env`, replacing the example values. Compose passes them to the server as `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY`, and passes `SEAWEEDFS_BUCKET` as `S3_BUCKET` to initialize the bucket at startup. This is one administrative credential pair for the local stack, not production service-level access separation. Never provide it to browser clients. - -SeaweedFS joins only the internal `storage` network (`APP_STORAGE_NETWORK`, by default `_storage`). The backend joins it and the default network; the monitoring Prometheus joins it to scrape port 9327, so start the core project before monitoring. No other container can resolve or reach SeaweedFS. This network is the primary control, because the container also serves filer, master, volume, and admin APIs and unauthenticated gRPC that ignore S3 credentials; see [ARCHITECTURE.md](ARCHITECTURE.md#private-file-storage) for the list and the remaining risk. Do not add other services to the storage network. - -The S3 credentials make S3 itself private: SeaweedFS answers unsigned S3 requests with 403, and Compose refuses to start with empty values because SeaweedFS without any identity accepts anonymous S3 requests. `-s3.iam=false` removes only the IAM management API. As defense in depth, the service entrypoint exports fresh random `WEED_JWT_*` signing keys at every start, so filer and volume HTTP requests need a token that never leaves the container, and `-ip=127.0.0.1` with `-whiteList=127.0.0.1,@` limits master and volume HTTP to in-container callers. The keys are not configuration and need no rotation; restarting the container replaces them. Smoke checks that the frontend cannot reach SeaweedFS by name or by its storage address, that S3 refuses an unsigned request, and that the filer, master, and volume HTTP APIs refuse a caller that is not inside the container. - -The stack publishes no object URLs. The bucket has no public read policy or anonymous ACL, and the backend creates no public or presigned links; future downloads go through an authenticated backend endpoint that streams the file. Size and content type limits are per feature policy in `backend/internal/usecase/files/` rather than deployment settings, so there is no extra environment variable. Keep the Nginx request body limit from the upload route aligned with the largest policy when such a route is added. - -Backend settings are `SEAWEEDFS_ENDPOINT`, `SEAWEEDFS_ACCESS_KEY`, `SEAWEEDFS_SECRET_KEY`, `SEAWEEDFS_BUCKET`, `SEAWEEDFS_REGION`, and `SEAWEEDFS_TIMEOUT`. Compose supplies endpoint `http://seaweedfs:8333`; a directly launched Go process defaults to `http://localhost:8333`, bucket `lincodex`, region `us-east-1`, and timeout `10s`. `SEAWEEDFS_TIMEOUT` bounds connection setup, the TLS handshake, the wait for response headers, and whole deletion and readiness calls; it does not bound object upload or download bodies, which follow the caller's context. Credentials are required. Direct execution needs a separately reachable private endpoint. Readiness checks the bucket; the backend does not create it. - -Ordinary `down` preserves the SeaweedFS volume. Losing the volume loses both objects and metadata; prepare a verified backup before changing the image or deleting the volume. This is one node without HA, cross-node replication, or configured off-host backups. - -Kafka uses the official `apache/kafka:latest` image as one KRaft node that combines the broker and controller roles; there is no ZooKeeper. Clients use the PLAINTEXT listener at `kafka:9092`, which is reachable only inside the Compose network and publishes no host port. The controller listener binds to `127.0.0.1:9093` inside the container, so other containers cannot reach it. The client listener has no TLS, authentication, or ACLs: any container attached to the Compose network, including monitoring services that join it, can produce and consume. Keep the network private and do not publish the port. - -The named `kafka_data` volume mounts at `/var/lib/kafka/data` and stores topic logs, consumer offsets, and KRaft metadata, so events survive container restarts and an ordinary `down`. `KAFKA_HEAP_OPTS` bounds the JVM heap to `-Xms256m -Xmx512m`, and the container memory limit is 1 GB. The image's default JMX agent is disabled, so no JMX port is open. Topic data is kept for 7 days or up to 1 GiB per partition, whichever limit is reached first, in 128 MiB segments. Replication factors and the minimum in-sync replica count are 1 because there is one node. This node provides no HA or replication; losing the volume loses all events and consumer offsets. - -`KAFKA_CLUSTER_ID` in `.env` is required. It identifies the KRaft cluster that formatted the volume. It is not a credential and grants no access, so `.env.example` contains a sample value. Generate your own value once before the first start: - - docker run --rm apache/kafka:latest /opt/kafka/bin/kafka-storage.sh random-uuid - -Changing the value after the volume is formatted stops Kafka from starting with that volume. - -Automatic topic creation is disabled: writing to a missing topic fails instead of creating it. The backend creates its events topic itself (see [Outbox relay](#outbox-relay)); create any other topic explicitly. Kafka CLI tools inherit the broker's `KAFKA_HEAP_OPTS`, so give them a small heap when running them in the container. For example, a manual technical check with the default `app` project: - - docker compose --env-file .env -p app -f deploy/docker/docker-compose.yml \ - exec -e KAFKA_HEAP_OPTS=-Xmx128m kafka /opt/kafka/bin/kafka-topics.sh \ - --bootstrap-server localhost:9092 --create --topic lincodex.technical.probe \ - --partitions 1 --replication-factor 1 - -The Compose health check runs `kafka-broker-api-versions.sh` against `localhost:9092`, so Kafka is healthy only after the broker answers API requests. `make -C deploy smoke` waits for that health check together with the other core services; it does not check the relay or read events. - -The backend receives `KAFKA_BROKERS`, a comma-separated list of `host:port` bootstrap addresses. Compose supplies `kafka:9092`; a directly launched Go process defaults to `localhost:9092`. An explicitly empty value, an empty list entry, a missing or zero port, or a URL scheme fails configuration. The outbox relay connects to these brokers in the background: the backend does not wait for Kafka at startup, and `/readyz` does not check Kafka. The advertised address `kafka:9092` resolves only inside the Compose network, so direct execution needs a separately reachable broker. Redis stays a cache and is not used as a queue. - -`PASSWORD_HASH_CONCURRENCY` sets the Argon2id memory budget in derivations of 64 MiB and four lanes each (from 1 to 4). Compose passes the value from `.env`, default 1, because the backend container has 1 CPU and 768 MB: a second derivation would only add 64 MiB while sharing the CPU. A directly launched backend without the variable uses the smaller of 2 and GOMAXPROCS. Further registrations and logins wait for memory until their request context ends. Compose also sets `GOMEMLIMIT=600MiB`, about 78% of the container limit, so the Go collector reclaims finished derivations before the container runs out of memory; change it together with the memory limit. The value is read and validated at startup; registration and login use it. See [ARCHITECTURE.md](ARCHITECTURE.md#password-hashing). - -`IDENTITY_KEY_SECRET` is required in the production `.env` (at least 32 bytes; generate it with `openssl rand -base64 48` and keep it between restarts and across instances). It keys idempotency records and rate limits, and derives the session CSRF key; Compose refuses to start without it, and the backend refuses to start without it unless `IDENTITY_ALLOW_EPHEMERAL_KEY=true`, which is for development stands only. Changing it changes the lookup keys for the last 24 hours of counters and idempotency records and invalidates existing CSRF values, but it does not revoke sessions stored in PostgreSQL. `VERIFICATION_MAIL_MIN_INTERVAL` (default `1m`) and `VERIFICATION_MAIL_DAILY_LIMIT` (default `5`) bound verification mail per address; an empty value means the default. `IDENTITY_CLIENT_HOURLY_LIMIT` defaults to `30` and accepts `1` to `10000`; it limits registration, confirmation, resend, and login attempts per client address when that address is resolved through the trusted proxy chain. `IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT` defaults to `10` and accepts `1` to `10000`; it limits login attempts per normalized email whether or not an account exists. Confirmation is also limited to 5 attempts per token per hour. `IDENTITY_SESSION_IDLE_TIMEOUT` defaults to `24h` and accepts `1m` to `30d`; `IDENTITY_SESSION_ABSOLUTE_LIFETIME` defaults to `168h` and accepts `1m` to `365d`. The idle timeout must not exceed the absolute lifetime; invalid values stop backend startup. The metric `lincodex_identity_rate_limit_refusals_total{scope}` counts refusals; a large share of `scope="client"` hints at a broken proxy chain (see `TRUSTED_PROXY_CIDRS`). See [ARCHITECTURE.md](ARCHITECTURE.md#registration-email-verification-and-resend) and [server-side sessions](ARCHITECTURE.md#server-side-sessions). - -down stops containers and keeps named volumes. Do not delete database or file volumes during an ordinary stop. - -### Public perimeter and client address - -Only three things are reachable through the frontend container: the SPA (static files and the `index.html` fallback, so a refresh of a deep link works), the versioned API under `/api/v1/`, and the same-origin `/telemetry` receiver (POST only, 1 MB, 30 requests per minute per client; the React SDK does not send to it yet). Everything else is refused: `/metrics`, `/readyz`, `/debug/`, `/actuator/`, dotfiles, `/api`, `/api/v1`, and any other path under `/api/` answer 404 and are never proxied. Backend `/metrics` listens on port 9090, which no Nginx location reaches. The only host port of the core project is the frontend bind (`APP_HTTP_BIND`, loopback by default); PostgreSQL, Redis, Kafka, SeaweedFS, and the backend publish nothing. Grafana and ML publish on loopback only (the monitoring and ML projects). - -- Headers (`deploy/nginx/snippets/security-headers.conf`): `Content-Security-Policy` with `default-src 'none'`, same-origin scripts, styles, fonts, images, and `connect-src`, no inline code, `frame-ancestors 'none'`, `base-uri 'none'`, `object-src 'none'`; `X-Content-Type-Options: nosniff`; `Referrer-Policy: strict-origin-when-cross-origin`; `X-Frame-Options: DENY`; `Cross-Origin-Opener-Policy` and `Cross-Origin-Resource-Policy` `same-origin`; `Permissions-Policy` denying camera, microphone, geolocation, payment, and USB. `index.html` and the deep-link fallback carry `Cache-Control: no-cache`, so a release is picked up at once; `/assets/` (hashed names) carries `public, max-age=31536000, immutable`, and a missing asset is a 404, never the fallback page. Redirects are relative (`absolute_redirect off`, `port_in_redirect off`), so a forged `Host` cannot steer them. If the SPA later needs an external host (analytics, fonts, a map), add that host to the matching CSP directive in the same change. No CORS header is sent: the API is same-origin and a browser refuses cross-origin reads; the backend still checks `Origin` on unsafe methods. -- Body limits: `client_max_body_size` is 1 MB for `/api/v1/` (the contract's JSON bodies are small). The contract has no upload operation yet, so there is no 5 MB resume route; the change that adds it raises the limit in that route's own `location` in `deploy/nginx/conf.d/app.conf` and keeps `EDGE_MAX_BODY` at or above it. A larger body gets 413 with an `application/problem+json` body (`payload_too_large`, with `trace_id` equal to the `X-Request-ID` response header) from Nginx, in the same shape as the backend's own 413. -- Timeouts: edge read 60 s, then app Nginx read 30 s, then the backend (storage and mail calls time out after 10 s, `Redis` after 1 s, the header read after 5 s). Each outer hop waits longer than the inner one, so the backend answers first. -- Coarse rate limits in the app Nginx: 20 requests per second per client with a burst of 60 and 40 concurrent connections on `/api/v1/`. They exist to absorb floods and are far above normal use. They do not replace the domain quotas (per-account, per-route, per-email limits), which the backend owns and which keep counting on their own. The limiter key is the client address, with an IPv6 address folded to its /64 (as `middleware.LimiterKey` does). A limited request gets 429 with `Retry-After: 1` and the contract's `rate_limited` problem (with `trace_id`). Rejections are logged at `notice`, below the `warn` threshold of the Nginx error log, because a rejection line names the client address. -- Client address chain: the edge replaces `X-Forwarded-For` with the connecting address; the frontend container trusts only the edge tunnel address (`set_real_ip_from`, equal to `AWG_EDGE_IP`) and takes the client from the right end of the header, so a value put in front by the client is never reached. For a peer that is not the edge it ignores the header altogether. `X-Forwarded-Proto: https` is likewise believed only from that peer. It then sends the backend a single `X-Forwarded-For` entry, the resolved client, replacing the header, and drops `Forwarded`. The core Docker network has a pinned subnet (`APP_SUBNET`, default `172.29.79.0/24`) and the frontend container a fixed address on it (`APP_FRONTEND_IP`, default `172.29.79.10`; change both together if the range collides, and recreate an existing network with `make -C deploy down` and `up`). The backend trusts `X-Forwarded-For` only from `TRUSTED_PROXY_CIDRS`, which defaults to that one address as a /32, so no other container of the network (Prometheus, exporters, Alloy) is trusted; leave the variable unset, and an empty value trusts nobody. The throwaway smoke, e2e, and metrics-check stacks use their own subnets (172.29.81 to 83) so they can run next to a development stack. The backend walks the header from the right, skipping trusted proxies; the first untrusted entry is the client. If the edge reaches the container under another address than `AWG_EDGE_IP`, the header is ignored and clients share one limiter bucket (fail closed); see the rollout checklist below. -- The client address is used only to key limiters, in Nginx shared memory and in the backend's limiter keys (`middleware.LimiterKey`, IPv6 reduced to /64, expiring with the window). It is not logged and not stored. The app Nginx log format and the backend request log have no address field; the edge access log records `$remote_addr`, as before, and is rotated by logrotate. - -Check it with `make -C deploy check-perimeter` (renders the Compose files and asserts the published ports; reads the Nginx files for denied paths, limit order, headers, and the trusted peer; runs inside `make -C deploy check`) and `make -C deploy perimeter-test` (starts throwaway Nginx containers on a private Docker network with stub upstreams, publishes on 127.0.0.1 only, and checks over HTTP: SPA refresh, denied paths, headers, no CORS, 413 and 429 problems, spoofed `X-Forwarded-For` from an untrusted and from a trusted peer, and that the Nginx log has no client address). It also checks the cache and cross-origin headers, relative redirects, encoded and dot-segment variants of denied paths, and per-/64 IPv6 buckets. It runs `nginx -t` on the committed files unchanged. It does not start the Compose stack, so it does not exercise the real backend or the TLS edge. Rollout checklist for the first deployment behind the edge (not done yet; the tests above cannot prove it): (1) from two external client addresses, request `/api/v1/healthz` in a loop until one gets 429 and confirm the other still gets 200, which shows that the app Nginx sees the edge as `10.79.0.1` and resolves real clients; if both are limited together, the peer address differs from `AWG_EDGE_IP` and the header is being ignored; (2) confirm `X-Forwarded-Proto: https` reaches the backend (the session cookie carries `Secure`); (3) confirm `curl http://:8080/metrics` answers 404. Manual browser step on a running stack: open a deep link and refresh it (the SPA loads), open the developer tools and confirm the response headers and no CSP violations in the console, and send a file larger than the limit with `curl -i -X POST --data-binary @big.bin -H 'Content-Type: application/octet-stream' http://127.0.0.1:8080/api/v1/` to see 413. - -### Outbox relay - -The backend runs the outbox relay in its own process next to the HTTP servers. The relay publishes committed outbox events to Kafka; its design is in [ARCHITECTURE.md](ARCHITECTURE.md#outbox-relay). Compose passes none of the settings below, so the stack uses the defaults; to change one, add it to the backend `environment` in `deploy/docker/docker-compose.yml`. A directly launched backend reads them from its environment. An invalid value stops startup. - -| Variable | Default | Meaning | -| --- | --- | --- | -| `RELAY_ENABLED` | `true` | `true` or `false`. With `false`, or without `DATABASE_URL`, the relay does not run and events stay in the outbox. | -| `RELAY_BATCH_SIZE` | `100` | Events one pass locks and publishes, from 1 to 1000. | -| `RELAY_POLL_INTERVAL` | `1s` | Wait after a pass that found no pending event, from 10ms to 5m. | -| `RELAY_PRODUCE_TIMEOUT` | `10s` | Longest wait for the broker acknowledgements of one pass and for topic creation, from 1s to 2m. The pass keeps its transaction open for that long at most. | -| `RELAY_STATEMENT_TIMEOUT` | `5s` | Server-side `statement_timeout` of each SQL statement of a pass, from 100ms to 1m. The pass transaction also gets `idle_in_transaction_session_timeout` of `RELAY_PRODUCE_TIMEOUT` plus this value, so PostgreSQL ends the transaction of a frozen or disconnected backend and releases its locks. | -| `RELAY_BACKOFF_INITIAL` | `500ms` | Wait after the first failed pass; it doubles with each consecutive failure. | -| `RELAY_BACKOFF_MAX` | `30s` | Longest wait between retries, from `RELAY_BACKOFF_INITIAL` to 10m. | -| `KAFKA_EVENTS_TOPIC` | `lincodex.domain.events` | Topic for all domain events: up to 249 letters, digits, dots, underscores, or hyphens. | -| `KAFKA_EVENTS_TOPIC_PARTITIONS` | `3` | Partitions of a topic the relay creates, from 1 to 1000. | -| `KAFKA_EVENTS_TOPIC_REPLICATION_FACTOR` | `-1` | Replication factor of a topic the relay creates: -1 takes the broker's `default.replication.factor`, otherwise from 1 to the broker count. | -| `KAFKA_EVENTS_TOPIC_MIN_INSYNC_REPLICAS` | unset | `min.insync.replicas` of a topic the relay creates, at least 1 and not above an explicit replication factor. Unset leaves the broker default. | -| `KAFKA_PROVISION_TOPICS` | `true` | With `false` the relay never creates the topic, and every publish fails until the topic exists. | - -`SHUTDOWN_TIMEOUT` also bounds the relay: a pass in progress at shutdown has that long to finish, otherwise it rolls back and its events stay pending. Compose gives the backend `stop_grace_period: 30s`, which covers the whole shutdown budget described under [Event consumers](#event-consumers), so Docker does not kill the process while a pass commits; raise it together with `SHUTDOWN_TIMEOUT`. - -The single-node stand creates the topic with the broker defaults of the Compose Kafka: replication factor 1 and `min.insync.replicas` 1. That is acceptable only for this stand: one broker cannot replicate, and losing its volume loses the events. A production cluster needs at least three brokers, a replication factor of at least 3, and `min.insync.replicas` 2, either as broker defaults or through `KAFKA_EVENTS_TOPIC_REPLICATION_FACTOR=3` and `KAFKA_EVENTS_TOPIC_MIN_INSYNC_REPLICAS=2`. The producer always uses acks from all in-sync replicas, so with these values an acknowledged event survives the loss of one broker, and writes stop rather than land on a single replica when two of three brokers are down. - -The relay creates a missing topic and never changes an existing one; when the existing topic has another partition count or replication factor than configured, the relay logs one warning. Adding partitions to the topic later moves aggregate keys to other partitions, so per-aggregate order is not guaranteed across that change. - -When Kafka is unavailable, the backend still starts and serves the API. The relay logs warnings such as `outbox relay could not prepare the event bus` or `outbox relay pass failed` with the retry delay and keeps retrying; events stay in `outbox_events` until Kafka answers. In Compose the backend does not wait for the Kafka health check, so these warnings are expected during the first seconds after `make -C deploy up`. Relay logs carry the `outbox_relay` component and contain event IDs, counts, and broker errors, never payloads. - -The internal /metrics endpoint shows the backlog: `lincodex_outbox_relay_pending_events` and `lincodex_outbox_relay_oldest_pending_age_seconds` are refreshed at most every 15 seconds, and `lincodex_outbox_relay_events_total` counts the `published` and `failed` outcomes. A growing age with a flat `published` count means the relay is stuck; the relay warnings name the event IDs, and [ARCHITECTURE.md](ARCHITECTURE.md#outbox-relay) describes the causes. Every backend instance reports the same backlog, so aggregate it with `max`. Published rows stay in `outbox_events`; their retention is not implemented yet. - -### Event consumers - -The backend runs one event consumer per registered handler in its own process next to the HTTP servers and the relay. A consumer reads `KAFKA_EVENTS_TOPIC` as a member of the group `.`, applies each event once, and commits its offset only after the effect committed in PostgreSQL. The design is in [ARCHITECTURE.md](ARCHITECTURE.md#event-consumers). Current state: two product handlers are registered, `notification_delivery` (mail deliveries) and `notification_inbox` (internal notifications), so the backend runs one consumer in each of the groups `.notification_delivery` and `.notification_inbox` (`lincodex.notification_delivery` and `lincodex.notification_inbox` by default) when `CONSUMER_ENABLED` is true and `DATABASE_URL` is set. A new group starts at the earliest retained event of the topic, so the first start of `notification_inbox` after a deployment reads the retained events and ignores those of other types. Compose passes none of them, so the stack uses the defaults; to change one, add it to the backend `environment` in `deploy/docker/docker-compose.yml`. An invalid value stops startup, also with consumers disabled. - -| Variable | Default | Meaning | -| --- | --- | --- | -| `CONSUMER_ENABLED` | `true` | `true` or `false`. With `false`, or without `DATABASE_URL`, no consumer runs, and events wait in Kafka for as long as the topic retains them. | -| `NOTIFICATION_SYNTHETIC_ENABLED` | `false` | `true` or `false`. Turns on the synthetic inbox event `notification.synthetic_delivered`: the `notification_inbox` consumer stores it and the inbox renders its fixed text. Leave it off in production; the browser E2E stand sets it. With `false` such an event is acknowledged and ignored, and a stored synthetic row is listed without content. The database CHECK allows the type either way. | -| `CONSUMER_GROUP_PREFIX` | `lincodex` | Prefix of every consumer group ID, up to 128 letters, digits, dots, underscores, or hyphens. Changing it starts new groups that read the topic from its earliest retained record; the dedup markers turn events that were already applied into duplicates. | -| `CONSUMER_MAX_ATTEMPTS` | `5` | Handler attempts for one event before it becomes a dead letter, from 1 to 20. Database failures outside the handler do not count. Must fit the rebalance budget below. | -| `CONSUMER_BACKOFF_INITIAL` | `500ms` | Wait after the first failed attempt; it doubles with each consecutive failure. | -| `CONSUMER_BACKOFF_MAX` | `10s` | Longest wait between attempts, from `CONSUMER_BACKOFF_INITIAL` to 5m. | -| `CONSUMER_HANDLER_TIMEOUT` | `5s` | Bound of one attempt and of one dead letter write, from 100ms to 5m. It is also the server-side `statement_timeout` and `idle_in_transaction_session_timeout` of the consumer transaction. | -| `CONSUMER_MAX_POLL_RECORDS` | `100` | Records of one poll, from 1 to 10000. A consumer processes them while it holds group rebalancing, so a smaller value shortens that hold. | -| `CONSUMER_COMMIT_TIMEOUT` | `5s` | Bound of one offset commit, from 100ms to 1m. | -| `CONSUMER_SHUTDOWN_GRACE` | `5s` | Time the record in progress has to commit after shutdown begins; at most `SHUTDOWN_TIMEOUT`. After it the transaction rolls back, the offset stays uncommitted, and the next member processes the record. | -| `CONSUMER_REBALANCE_TIMEOUT` | `60s` | Kafka rebalance timeout of every consumer group member, from 10s to 30m. Startup fails unless it exceeds the slowest record by 5 seconds. | - -Rebalance budget. A consumer holds group rebalancing while it processes a poll, and a member that holds it longer than `CONSUMER_REBALANCE_TIMEOUT` is removed from the group, so its records are processed again by the next owner. The slowest record without a database outage takes `CONSUMER_MAX_ATTEMPTS` + 1 times `CONSUMER_HANDLER_TIMEOUT` (the attempts and the dead letter write), the longest backoff before each retry, and one `CONSUMER_COMMIT_TIMEOUT`. With the defaults that is 6 x 5s + (0.5 + 1 + 2 + 4)s + 5s = 42.5s, below 60s - 5s. A configuration that does not fit fails at startup with the computed value; lower the attempts or timeouts, or raise `CONSUMER_REBALANCE_TIMEOUT`, which also makes the group wait longer for a member that stopped responding. After every record that needed a retry or a dead letter the consumer commits at once, so only one slow record has to fit, not a whole poll. - -Shutdown budget with the defaults: - -1. In parallel: the HTTP servers drain within `SHUTDOWN_TIMEOUT` (10s); a relay pass gets the same 10s and up to 5s to roll back; every consumer gets `CONSUMER_SHUTDOWN_GRACE` (5s) for the record in progress, up to 5s to roll back a canceled transaction, and `CONSUMER_COMMIT_TIMEOUT` (5s) for its offsets. This phase ends after at most 15s. -2. Then all consumers leave their groups in parallel, each within `CONSUMER_COMMIT_TIMEOUT` plus 2s (7s), and the clients and pools close in about 1s. - -That is about 23s regardless of the number of consumers. Compose gives the backend `stop_grace_period: 30s`, so Docker does not kill the process while a transaction commits; raise it when you raise `SHUTDOWN_TIMEOUT`, `CONSUMER_SHUTDOWN_GRACE`, or `CONSUMER_COMMIT_TIMEOUT`. - -A consumer needs one PostgreSQL connection; all consumers of a process share one pool sized to their count. Several backend instances share a group's partitions, so at most `KAFKA_EVENTS_TOPIC_PARTITIONS` instances process a consumer's events at once; the others stay idle members. - -Operators watch two counters on the internal /metrics endpoint. `lincodex_event_consumer_records_total{consumer,outcome}` counts finished records: `applied`, `duplicate` (expected after a redelivery), `ignored` (another event type), and `dead_lettered`. Alert on any increase of `dead_lettered`; every series exists at zero from the consumer's start, so `increase(...[15m]) > 0` fires on the first dead letter. `lincodex_event_consumer_failures_total{consumer,stage}` counts every failed operation, including the last handler attempt before a dead letter: a rising `store` count with flat `applied` means the consumer cannot reach PostgreSQL and its partition waits; a rising `handler` count means events keep failing; a rising `poll` count means the consumer cannot read Kafka (broker down, missing topic, or a group error); a rising `commit` count means offsets are not stored, so records will be delivered again after a restart or rebalance. Alert on `poll` or `commit` failures that continue for several minutes, for example `increase(...{stage=~"poll|commit"}[5m]) > 0` held for 10 minutes. Consumer logs carry the `event_consumer` component, the group, topic, partition, offset, event ID, and event type, never the record value. A dead letter is logged at error level as `event dead-lettered; the offset is committed and the record needs an operator` with the class and reason. - -#### Dead letters and replay - -A dead letter is a record the consumer gave up on so that its partition can continue. `error_class` says why: - -- `invalid_record`: the value is not a valid event envelope. It did not come from the relay; find the producer that writes to the topic. It cannot be replayed as it is. -- `handler_rejected`: the handler reported that the event can never be applied, for example an unknown `schema_version`. -- `handler_panic`: the handler panicked; the log line `event handler panicked` with the same event ID holds the stack. -- `retries_exhausted`: the handler failed `CONSUMER_MAX_ATTEMPTS` times, for example because of a bug or a dependency it calls. - -List them with psql in the database container (default `app` project): - - docker compose --env-file .env -p app -f deploy/docker/docker-compose.yml \ - exec postgres sh -c 'psql -U "$POSTGRES_USER" -d "$POSTGRES_DB"' - - SELECT id, consumer_name, error_class, event_id, event_type, topic, - kafka_partition, kafka_offset, attempts, reason, dead_lettered_at - FROM consumer_dead_letters ORDER BY id; - -The table holds no record value; `value_size` and `value_sha256` identify the value. Replay a dead letter only after its cause is fixed, usually by deploying a corrected handler: - -1. Replay one event from the outbox. For a dead letter with an `event_id` and a class other than `invalid_record`, publish the event again: - - UPDATE outbox_events SET published_at = NULL WHERE event_id = ''; - - The relay publishes it again with the same `event_id` at a new offset. Every consumer receives it: those that applied it find their marker and count a `duplicate`, and the consumer that failed applies it, because a dead letter writes no marker. This works as long as the outbox row exists (published rows are not deleted yet), also after Kafka dropped the original record. The event can arrive after later versions of its aggregate; handlers ignore versions they have already passed. -2. Or rewind the group while Kafka still retains the record. Kafka resets offsets only for an empty group, so stop every member first (stop the backend instances or set `CONSUMER_ENABLED=false`). A member that was killed instead of stopped stays in the group until its session timeout (45 seconds by default) ends; run the command below with `--describe` instead of the reset options and wait until it lists no active member. Then: - - docker compose --env-file .env -p app -f deploy/docker/docker-compose.yml \ - exec -e KAFKA_HEAP_OPTS=-Xmx128m kafka /opt/kafka/bin/kafka-consumer-groups.sh \ - --bootstrap-server localhost:9092 --group lincodex. \ - --topic lincodex.domain.events: --reset-offsets --to-offset --execute - - The group then reads that partition again from the offset. Records it already applied are duplicates; other dead letters in the range are attempted again, and one that fails again updates its row with the new class, reason, and attempt count instead of adding another. `--describe` also shows the group's offsets and lag. -3. Check the result and close the dead letter: the event is applied when `SELECT 1 FROM consumer_processed_events WHERE consumer_name = '' AND event_id = ''` returns a row. Then delete the row with `DELETE FROM consumer_dead_letters WHERE id = `, or keep it as a record of the incident. - -To inspect an `invalid_record` while the topic retains it, read exactly that record with `kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic --partition --offset --max-messages 1` and compare its SHA-256 with `value_sha256`. The value can contain personal data, so do not paste it into tickets or chats. - -### Scheduled jobs - -The backend runs the scheduled job worker as a goroutine of the backend process next to the HTTP servers, the relay, and the consumers. It runs jobs that usecases scheduled in their transactions once they fall due; the design is in [ARCHITECTURE.md](ARCHITECTURE.md#scheduled-jobs). Current state: one product kind is registered, `assessment.signal_review` (see [Assessment review band](#assessment-review-band)), so the worker runs when `JOBS_ENABLED` is true and `DATABASE_URL` is set; the settings below are validated in any case. Compose passes none of the settings, so the stack uses the defaults; to change one, add it to the backend `environment` in `deploy/docker/docker-compose.yml`. A directly launched backend reads them from its environment. An invalid value stops startup, also with the worker disabled. - -| Variable | Default | Meaning | -| --- | --- | --- | -| `JOBS_ENABLED` | `true` | `true` or `false`. With `false`, or without `DATABASE_URL`, no job runs; due jobs wait in `scheduled_jobs` and run after the worker starts again, with their original `due_at`. | -| `JOBS_POLL_INTERVAL` | `1s` | Wait after a pass that claimed less than a full batch, from 10ms to 5m. It is also the usual delay of a job after its due time. | -| `JOBS_BATCH_SIZE` | `10` | Jobs one claim leases, from 1 to 100. They run one after another under leases taken together, so a batch should finish well within one lease. | -| `JOBS_LEASE_DURATION` | `1m` | How long a claimed job belongs to one worker, from 1s to 1h. It bounds one handler attempt and is the server-side `statement_timeout` and `idle_in_transaction_session_timeout` of the job transaction. A worker that crashed delays its jobs by at most this long. | -| `JOBS_MAX_ATTEMPTS` | `5` | Attempts of a job scheduled without its own limit before it is dead, from 1 to 100. Database failures outside the handler and shutdown do not count. | -| `JOBS_BACKOFF_INITIAL` | `1s` | Delay before the first retry of a failed job; it doubles with each failed attempt. The same backoff spaces claims while the database fails. | -| `JOBS_BACKOFF_MAX` | `5m` | Longest delay before a retry, from `JOBS_BACKOFF_INITIAL` to 24h. | -| `JOBS_SHUTDOWN_GRACE` | `5s` | Time the job in progress has to commit after shutdown begins; at most `SHUTDOWN_TIMEOUT`. After it the transaction rolls back and the job is released unfinished. | - -Due times and leases are compared with the backend clock, not the database clock, so keep the hosts of all backend instances synchronized with NTP. A clock ahead runs jobs early and takes over leases early; the row lock still prevents a second run while a handler is in progress. - -Shutdown budget. The worker stops in parallel with the other workers: `JOBS_SHUTDOWN_GRACE` (5s) for the job in progress, up to 5s to roll back a canceled transaction, and up to 5s to release the unfinished jobs, 15s at most. This fits the first phase of the budget under [Event consumers](#event-consumers), so the total stays about 23s within `stop_grace_period: 30s`; raise that together with `JOBS_SHUTDOWN_GRACE`. If the backend is killed instead, its jobs stay `running` until their leases expire and then run on another instance or after the restart. - -The worker uses its own PostgreSQL pool of at most two connections. Several backend instances share the jobs: each claim skips rows that another instance locks, and every instance can run every registered kind. - -Operators watch `lincodex_scheduled_jobs_total{kind,outcome}` on the internal /metrics endpoint: `done`, `retry` (an attempt failed and the job waits for its backoff), `dead`, `lease_lost` (the job was canceled or reclaimed while this instance held it), and `released` (given back unfinished at shutdown or after a database failure). Every series exists at zero from the start, so alert on `increase(lincodex_scheduled_jobs_total{outcome="dead"}[15m]) > 0`. `lincodex_scheduled_jobs_due` and `lincodex_scheduled_jobs_oldest_due_age_seconds` describe due jobs that wait for a worker; an age that keeps growing beyond a few poll intervals means no instance claims them, for example because the worker is disabled, the database fails, or no running instance has the handler of their kind. `lincodex_scheduled_jobs_dead` counts dead jobs. Every instance reports the same database-wide gauges, so aggregate them with `max`. During a rolling deployment that adds a new kind, its jobs that already fell due wait until an instance with the handler runs, and the age can briefly look like a stuck worker; hold an age alert for longer than a deployment takes. Logs carry the `scheduled_jobs` component, the lease owner, job ID, kind, attempt, and error class, never the key or payload; a dead job is logged at error level as `scheduled job is dead; it needs an operator`. - -#### Dead jobs - -`last_error_class` says why a job is dead: `handler_rejected` (the handler can never run it), `handler_panic` (the log line `scheduled job handler panicked` with the same job ID holds the stack), `lease_expired` (its last started attempt stopped without finishing, usually a crash or a kill, or its failure could not be recorded because the database failed at that moment), or the class of the last failed attempt after the attempts ran out: `handler_failed`, `timeout`, `conflict`, or `effect_rejected`. `completion_conflict` means the handler changed its own job other than by canceling it. List dead jobs and jobs that are overdue with psql in the database container (see [Dead letters and replay](#dead-letters-and-replay) for the command that opens it): - - SELECT id, kind, dedup_key, attempts, max_attempts, last_error_class, - due_at, available_at, updated_at - FROM scheduled_jobs WHERE status = 'dead' ORDER BY updated_at; - - SELECT kind, status, count(*), min(available_at) - FROM scheduled_jobs - WHERE status IN ('pending', 'failed', 'running') AND available_at <= now() - GROUP BY kind, status; - -The key identifies a product record, such as an invitation ID; the payload holds identifiers only. After the cause is fixed, usually by deploying a corrected handler, run a dead job again. Change only `available_at`, never `due_at`: the handler decides by the deadline in `due_at`. - - UPDATE scheduled_jobs - SET status = 'failed', attempts = 0, available_at = now(), updated_at = clock_timestamp() - WHERE id = AND status = 'dead'; - -A worker claims it within one poll interval and runs it with fresh attempts. To give a dead job up, set `status = 'cancelled'` with the same guard; its key stays reserved, so the product flow cannot schedule it again. Do not delete rows: a deleted key can be scheduled again and run a second time. - -## Mail - -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. With `EMAIL_PROVIDER=resend`, the backend runs a worker for service identity mail (email verification and password reset), and registration queues a verification email. Password reset is not implemented. Product notifications are sent by a separate notification worker: it leaves a quota reserve to service mail and checks the recipient's rights again before every send (see [ARCHITECTURE.md](ARCHITECTURE.md)). See [Sending service mail](#sending-service-mail). - -Release compatibility: `ConfirmEmail` requires both `token` and the password selected for that registration. Clients that send only the token must be updated. Migration `00016_bind_registration_consent.sql` adds the registration version to C1 and backfills legacy records from the current account version without requiring a live token. It checks that a registration C1 is not older than the latest registration and that an account has at most one active registration C1; on inconsistency, the migration stops without partial changes. A trigger fills the version when an old backend omits it and rejects a mismatched version sent by the new backend. A partial unique index allows at most one unrevoked registration C1 per account and registration version. Apply the migration before updating the backend. To roll back, deploy the old backend before reverting the migration. No new environment variable is needed. `APP_PUBLIC_URL` also defines the Origin that confirmation requests must send. The new `ConfirmEmailByCode` operation (`POST /api/v1/identity/email-verifications/code`) and migration `00046_add_email_verification_codes.sql` are additive: existing clients keep confirming by link. The migration can be rolled back once no usable code is left; its down step refuses until then. - -`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; the sending worker owns retries, backoff, rate-limit pacing, and outcome records, while the quota gate schedules a known daily or monthly reset (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). - -`disabled` sends nothing. Every send returns `ErrMailChannelUnavailable` without a provider message ID and is never reported as accepted or delivered. It does not confirm an email address, mark an account verified, or skip an account check. The startup log contains `mail transport selected` with `email_provider` and, for `disabled`, a `mail delivery is disabled` warning. - -| Variable | Default | Validation | -| --- | --- | --- | -| `EMAIL_PROVIDER` | none, required | `resend`, `smtp`, or `disabled`, case-insensitive | -| `EMAIL_FROM` | none, required | One mailbox: `no-reply@example.com` or `Lincodex `. Printable ASCII only. The address follows the account address rules: unquoted local part and a DNS domain with at least two labels, no IP literal. | -| `EMAIL_ACCOUNT` | `default` | Label of the provider account that new deliveries are pinned to and that the quota is counted under: 1 to 64 lowercase letters, digits, `.`, `_`, or `-`, starting with a letter or digit. Never the key. Change it only with a real account change; renaming it resets the local quota count. | -| `EMAIL_TIMEOUT` | `10s` | Go duration from `1s` to `1m`; limits one transport attempt | -| `EMAIL_QUOTA_DAILY` | `100` for `resend` and `disabled`; none for `smtp`, where it is required | Recipients per UTC day through the configured provider account: an integer from 1 to 1000000000. Empty counts as unset. No value turns the quota off. | -| `EMAIL_QUOTA_MONTHLY` | `3000` for `resend` and `disabled`; none for `smtp`, where it is required | Recipients per UTC calendar month: an integer from 1 to 1000000000, not below `EMAIL_QUOTA_DAILY`. Empty counts as unset. | -| `EMAIL_SERVICE_RESERVE_DAILY` | A fifth of `EMAIL_QUOTA_DAILY`, for example 20 on the Resend Free plan | Recipients per UTC day that product notifications leave free for service mail: an integer from 0 to below `EMAIL_QUOTA_DAILY`. Empty counts as unset. A notification is admitted only while the day keeps this many recipients free after it. | -| `EMAIL_SERVICE_RESERVE_MONTHLY` | A fifth of `EMAIL_QUOTA_MONTHLY`, for example 600 on the Resend Free plan | The same for the UTC calendar month: an integer from 0 to below `EMAIL_QUOTA_MONTHLY`. Empty counts as unset. | -| `APP_PUBLIC_URL` | none, required | Public origin for mail links and exact Origin checks on unsafe public identity and protected operations: `https://host[:port]`, or `http` only for `localhost`, `127.0.0.1`, or `[::1]`. No credentials, path, query, or fragment; one trailing `/` is dropped. | -| `RESEND_API_KEY` | empty | Read only for `resend`, where it is required. Printable ASCII without whitespace. The `re_` prefix shown in Resend examples is not enforced. | -| `SMTP_HOST` | empty | Read only for `smtp`, where it is required. Hostname or IP address without a port. | -| `SMTP_PORT` | empty | Required for `smtp`. Integer from 1 to 65535. | -| `SMTP_USERNAME`, `SMTP_PASSWORD` | empty | Required for `smtp`; an anonymous relay is not supported. | -| `SMTP_TLS_MODE` | empty | Required for `smtp`. `starttls` (upgrade with STARTTLS, usually port 587) or `tls` (TLS from the start, usually port 465). Plaintext SMTP is not supported. | - -Compose passes these variables from the root `.env`; it passes an unset `EMAIL_QUOTA_DAILY` or `EMAIL_QUOTA_MONTHLY` as an empty value, which the backend reads as unset. The same holds for `EMAIL_SERVICE_RESERVE_DAILY` and `EMAIL_SERVICE_RESERVE_MONTHLY`. `EMAIL_PROVIDER`, `EMAIL_FROM`, and `APP_PUBLIC_URL` are required, so Compose refuses to render the project without them; copy the mail block from `.env.example` into an existing `.env`. Keep `RESEND_API_KEY` and `SMTP_PASSWORD` in the server environment or a deployment secret store and never commit them. Configuration errors name the setting but never print its value, and the startup log names only the selected provider. - -### 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; migration 00017 adds the unknown-outcome decision journal and rebuilds the due partial index under a table lock. Rolling 00017 back drops that journal and its audit history, so export the decisions before rollback. Neither migration needs a setting. Notification deliveries are sent by a separate notification worker through its own queue; the service mail worker still claims verification and password reset mail only. 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. Product notifications follow the same rule, and their loop rebinds them the same way. -- 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 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 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. The service reserve (`EMAIL_SERVICE_RESERVE_DAILY` and `EMAIL_SERVICE_RESERVE_MONTHLY`) keeps part of each window for service mail: product notifications are admitted only while the window keeps the reserve free after them, and they take a fifth of each limit by default. -- 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. -- When a quota is used up, deliveries wait in `waiting_quota` until `next_attempt_at`: the next 00:00 UTC for the day, the first day of the next month at 00:00 UTC for the month. Nothing buys a plan, switches the account to a paid tier, or moves mail to another transport or account. The account itself can see that its mail waits and until when through the status reader described in [ARCHITECTURE.md](ARCHITECTURE.md#mail-quotas); no HTTP route shows it yet. -- To see the state, select only counters and metadata, for example `SELECT provider, provider_account, period_kind, period_start, used_recipients, provider_exhausted_at FROM mail_quota_usage ORDER BY period_start DESC, period_kind LIMIT 10`, `SELECT count(*), min(next_attempt_at) FROM deliveries WHERE status = 'waiting_quota'`, and, for sends that were counted but never settled, `SELECT count(*), min(reserved_at) FROM mail_quota_reservations WHERE settled_outcome IS NULL AND released_at IS NULL`. Logs show `mail quota is used up; the delivery waits for the reset` and, when the provider itself refused, `the mail provider reported its quota used up; local sending stops until the reset`. -- 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. `lincodex_mail_sender_running` reports the service loop of the process, and `lincodex_notification_sender_running` the product notification loop; both are 0 with `EMAIL_PROVIDER=disabled`. -- 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. The local operator command is for terminal unknown outcomes, not quota-waiting deliveries. -- 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 - -The backend process runs one sending loop for service identity mail (email verification and password reset). It starts with the backend when `EMAIL_PROVIDER` is `resend` and `DATABASE_URL` is set, shares the database with the other workers on a pool of two connections, and needs no setting of its own: the poll interval (5 seconds), the lease on a claimed delivery (`EMAIL_TIMEOUT` plus one minute), the shutdown grace (5 seconds), the retry schedule (1 minute doubling to 30 minutes), and the failure backoff (5 seconds doubling to 2 minutes) are constants in `backend/internal/bootstrap/mail_sender.go`. Migration 00012 adds its columns; the model, the checks, and the outcomes are in [ARCHITECTURE.md](ARCHITECTURE.md#sending-service-mail). - -- Several backend instances may run at once. Each claims a delivery with `FOR UPDATE SKIP LOCKED` and a lease, so one delivery is sent by one instance, and the provider call carries the stable idempotency key `delivery/`. During a rolling deployment the instance that stops finishes its send within 5 seconds, stores the result, and exits. -- 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 confirmed temporary or 429 refusal means the provider did not accept the message: it leaves the delivery `pending` with a later `next_attempt_at`, and the retry reuses the pinned account, key, and body. Resend's `Retry-After` is a lower bound. Such a refusal does not erase uncertainty from an earlier unknown attempt. After the 23-hour cutoff, confirmed refusals continue only under a pending manual decision; without it, the worker stops and leaves the earlier unknown for operator review. 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). -- An uncertain Resend outcome is retried automatically with the same pinned account, key, and stored body only until 23 hours after the database-recorded first send, one hour before the provider's documented 24-hour idempotency expiry. The worker checks this cutoff again immediately before the network call. After the cutoff, or after a manually authorized send-start whose result is lost, automatic retries stop and the alert `LincodexMailDeliveryUnknownOutcome` asks for review. Check the provider's own log first. For a terminal `unknown` row, use `make -C backend mail-retry ARGS='inspect --delivery '` to see metadata and the duplicate warning, then `make -C backend mail-retry ARGS='retry --delivery --actor operator: --acknowledge-duplicate-risk'` to schedule one audited decision. The command requires the local database credential, is available only with `EMAIL_PROVIDER=resend`, prints its warning before changing state, and never sends mail. The actor is an audit handle rather than authentication, and there is no HTTP operator endpoint. A manual decision does not restart the provider's key window: after another unknown or lost manual send result, the worker stops and requires another decision. An expired idempotency key may produce a duplicate despite the warning. -- 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. The retry command displays no address, body, key, or token. Do not copy bodies of waiting mail anywhere. -- The lease is measured by the database clock, so clock differences between instances do not matter; only the database's clock does. The call to the provider is bounded by what is left of the lease; with `SHUTDOWN_TIMEOUT` at its default of 10 seconds a stopping instance finishes within 3 seconds of grace plus 5 seconds to store the answer. Lowering `SHUTDOWN_TIMEOUT` shortens the second part (at least 1 second); a result that cannot be stored in time is covered by the takeover. -- Logs name a delivery only by `delivery_id`, its kind, and the outcome or cancel reason, for example `service mail was not sent because it is no longer valid`; never an address, a token, a link, or a body. If a token or link appears in a log, treat it as a defect. -- The internal /metrics endpoint shows `lincodex_mail_sender_running` (1 while this instance's loop runs, 0 otherwise; no labels) and `lincodex_mail_sender_cancelled_total{reason}` (a counter per cancel reason, zero included) next to the delivery gauges, which also have the status `cancelled`. - -### Mail templates - -Implemented: the renderer in `backend/internal/usecase/notification/mailtemplate/` with templates for email verification, password reset, and a short notification. The delivery consumer renders notifications when it stores a delivery, and `ServiceMailer` creates verification mail during registration. Email confirmation is implemented in the API and frontend. The password reset flow is still planned. - -- Templates are embedded in the binary with `go:embed` and parsed once when the renderer is created; a broken template fails its creation. Each version has three files: `.v.subject.tmpl`, `.v.txt.tmpl`, and `.v.html.tmpl`. The HTML part uses `html/template`, the plain-text part and the subject use `text/template`. Every transport sends the same rendering; templates hold no provider settings, keys, or sender address. -- Links start with `APP_PUBLIC_URL`, which the renderer checks again with the same rules. Verification: `/verify-email#token=`; password reset: `/reset-password#token=` (the page and the API for the reset are planned). The token is only in the URL fragment, never in the path or the query: a browser does not send the fragment to a server, so the nginx access log (which records `$uri`) and Referer headers never hold it. The frontend reads and removes the fragment, waits for explicit user action, then sends the token and registration password to the API. A notification link is a path inside the application, such as `/candidate/invitations`; an absolute URL, `//host`, a scheme such as `javascript:`, a query, a fragment, a percent sign, and `.` or `..` segments are rejected. -- Messages contain no name, email address, or other contact. Caller text in a notification is escaped in the HTML part; control and bidirectional characters are removed from the plain-text part, and the subject becomes one line, so CR and LF cannot add header lines. The notification subject is limited to 100 characters and the body to 2000. -- The HTML part uses table layout with inline styles only: no `