feat(policy): add immutable versioned product policy store

This commit is contained in:
shira committed 2026-10-06 01:52:39 +03:00
1 parent 0e2a3b02ab
commit 7a5105acc7
30 files changed
+3893 -37

No files matched your search

+62 -10
View File
@@ -89,6 +89,57 @@ Implemented: the outbound `MailSender` port (`backend/internal/port/outbound/mai
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. Retries, backoff, and recording outcomes belong to a single planned delivery layer, not to the transport. The verification flows (TASK-053, TASK-054) must treat `ErrMailChannelUnavailable` as not sent: it never confirms an address or replaces an account check. `OutgoingMail` redacts itself in `fmt` and `slog` output, and transport errors and logs never contain recipients, subjects, bodies, credentials, or raw provider responses.
### Product policy versions
Implemented as storage, a publisher, and a startup seed (TASK-005): migration `backend/db/migrations/00003_create_policy_versions.sql`, queries in `backend/db/queries/policy.sql`, the typed policy in `backend/internal/domain/` (`policy.go`, `policy_document.go`, `policy_version.go`, `policy_demo.go`), the `outbound.PolicyRepository` port (`port/outbound/policy.go`), the sqlc-backed adapter in `backend/internal/adapter/secondary/postgres/policy.go`, and the publisher in `backend/internal/usecase/policy/`. No product rule reads the policy yet; invitations, quotas, assessment, sessions, and the search status will read it as their tasks are implemented.
`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:<name>` or `operator:<handle>`, 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 TASK-087); every organization starts at E0, and the rules that move it between tiers belong to the quota feature.
Open question for the attempt tasks (TASK-157 and TASK-158): `MaxAttemptsPerWindow` stores only the number. Whether the limit counts per grade, per specialty, or across all assessments of a candidate is not decided.
The document has `schema_version` 1 and the sections `invitations`, `organization_quotas`, `assessment`, `identity`, and `search_status`; field names carry their unit (`_days`, `_business_days`, `_hours`, `_bp`). Decoding is strict: it rejects unknown fields, missing or null fields, wrong types, fractions, values outside int32, an unknown schema version, trailing data, and documents over 64 KiB. The canonical form is the compact Go encoding in field declaration order. jsonb normalizes key order, so `domain.RestorePolicyVersion` decodes the stored document, validates it, encodes it again, and compares its SHA-256 with `document_sha256`; a mismatch returns `domain.ErrPolicyDocumentIntegrity`. A golden test pins the canonical form, because a change would make every stored version fail this check; a new layout needs a new schema version and decoder.
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 |
| `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.
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.
## Repository map and package purpose
```text
@@ -119,11 +170,12 @@ backend/
cmd/app/main.go calls bootstrap.Run and reports errors
config/ shared runtime configuration
internal/
domain/ flat package; DomainEvent, identity types
domain/ flat package; DomainEvent, identity types, product policy
usecase/health/ operational readiness usecase
port/inbound/ readiness input boundary
usecase/identity/ password validation before hashing (Credentials)
port/outbound/ readiness, cache, object storage, transaction, outbox, identity, password hashing, and mail boundaries
usecase/policy/ publication of policy versions and the demo policy seed
port/outbound/ readiness, cache, object storage, transaction, outbox, identity, policy, password hashing, and mail boundaries
adapter/primary/http/
api/ generated ogen handler
middleware/ request metrics
@@ -134,22 +186,22 @@ backend/
argon2id/ Argon2id password hasher with a memory budget
mail/disabled/ mail transport that sends nothing and reports the channel unavailable
ml/api/ generated client from backend/codegen/ogen-ml.yml
postgres/ pool, migrator, transactor, outbox writer, identity repositories, health check
postgres/ pool, migrator, transactor, outbox writer, identity 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 and request metrics
bootstrap/ configuration, wiring, lifecycle, shutdown
db/ embedded migrations and SQL queries; outbox and identity tables
db/ embedded migrations and SQL queries; outbox, identity, and policy tables
codegen/ ogen and sqlc configs
pkg/ reserved for justified shared technical helpers
```
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`.
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 product policy and its versions live in `policy.go`, `policy_document.go`, `policy_version.go`, and `policy_demo.go`.
Product domain types and usecase modules, the Resend, SMTP, and FSP adapters, and the worker are reserved areas; their business behavior is not implemented. Keep `main.go` limited to starting bootstrap and handling 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, identity repositories without the usecases that will use them, the `PasswordHasher` port with the Argon2id adapter and the password check that registration will call, a Redis cache adapter, a SeaweedFS S3 adapter, and the `MailSender` port with the `disabled` transport. Account behavior (registration, verification, login, sessions), resumes, assessments, invitations, worker jobs, file workflows, mail delivery, the Resend and SMTP transports, and FSP adapters remain planned. Do not create empty module directories before a real use case exists.
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, identity repositories without the usecases that will use them, the versioned policy store with its publisher and the demo policy seed at startup, the `PasswordHasher` port with the Argon2id adapter and the password check that registration will call, a Redis cache adapter, a SeaweedFS S3 adapter, and the `MailSender` port with the `disabled` transport. Account behavior (registration, verification, login, sessions), resumes, assessments, invitations, worker jobs, file workflows, mail delivery, the Resend and SMTP transports, 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. Candidate future packages are `emailtemplate`, `mailer`, and test helpers. Keep the S3 client in the SeaweedFS adapter. Keep service-specific behavior private under `internal/`.
@@ -196,11 +248,11 @@ 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.
- Changes after a successful qualification are rate limited; 90 days is the initial proposal.
- The first lower-level test after failure is outside that interval. Repeating the same level may use a separate cooldown, initially proposed at 24 hours.
- 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.
Thresholds and intervals are pilot proposals, 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.
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.
## Matching and explanations
@@ -369,7 +421,7 @@ These are proposed acceptance targets, not results: 30 concurrent users; p95 pro
- 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 proposed 90-day limit.
- 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.
+1 -1
View File
@@ -11,7 +11,7 @@ Install Docker Engine and the Docker Compose plugin. At the repository root, cop
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. See [DEVELOPMENT.md](DEVELOPMENT.md#database-migrations).
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).
The backend build context is `backend/`, so Docker applies `backend/.dockerignore`. Local tools, caches, environment files, and build outputs are excluded from that context.
+10 -2
View File
@@ -48,7 +48,7 @@ The repository contains a verifiable technical scaffold, not a product. Values b
What exists now:
- Health and readiness routes. Nginx answers `GET /healthz` itself and proxies only `/api/` to Go (deploy/nginx/conf.d/app.conf). Go serves `GET /healthz` (`ok`) and `GET /readyz` (`ready` or 503 `not_ready` after checking PostgreSQL, Redis, and SeaweedFS) on its internal port 8080 outside the OpenAPI contract, plus `GET /api/v1/healthz` from api/core/routes/healthz.yml through the ogen handler (backend/internal/adapter/primary/http). The Go metrics listener uses port 9090 (`METRICS_ADDR`) and Prometheus scrapes `/metrics`. ML serves `GET /healthz`, `GET /readyz` (always 503 `not_ready` because no model is connected), and `/metrics` (ml/src/lincodex_ml, api/ml/routes). deploy/scripts/smoke.sh checks Nginx `/healthz`, `/api/v1/healthz`, Go `/readyz` from inside the Compose network, a 404 for an unknown API route, and that the backend started with `EMAIL_PROVIDER=disabled`; it does not start ML or send mail.
- Adapters: PostgreSQL through pgxpool with a generated `SELECT 1` query, a goose migration runner applied at startup, a transactor with the transactional outbox writer, and sqlc-backed identity repositories for accounts, email tokens, and sessions; Redis through go-cachekit, and SeaweedFS through the S3 API. The Argon2id password hasher and the `identity.Credentials` password check exist and are tested but are not wired into bootstrap. A generated Go client for the ML contract exists but is not wired into bootstrap.
- Adapters: PostgreSQL through pgxpool with a generated `SELECT 1` query, a goose migration runner applied at startup, a transactor with the transactional outbox writer, sqlc-backed identity repositories for accounts, email tokens, and sessions, and the versioned policy repository with the demo policy seed at startup; Redis through go-cachekit, and SeaweedFS through the S3 API. The Argon2id password hasher and the `identity.Credentials` password check exist and are tested but are not wired into bootstrap. A generated Go client for the ML contract exists but is not wired into bootstrap.
- Mail: the outbound `MailSender` port, the `disabled` transport, and the `EMAIL_PROVIDER` selection in bootstrap. Only `disabled` works in this build; `resend` and `smtp` fail startup after their settings are validated. Nothing sends mail yet. See [DEPLOY.md](DEPLOY.md#mail) and [ARCHITECTURE.md](ARCHITECTURE.md#mail-transport).
- OpenAPI contracts api/core/ and api/ml/ with schema merge, bundles, lint, and generation for Go (ogen), TypeScript (Orval), and Python (datamodel-code-generator). The SPA has an interface scaffold with placeholder screens, a generated API client, and MSW handlers.
- Compose projects: core (`deploy/docker/docker-compose.yml`: PostgreSQL, Redis, SeaweedFS, Kafka, backend, frontend), ML (`docker-compose.ml.yml`), and monitoring (`docker-compose.monitoring.yml`).
@@ -56,7 +56,7 @@ What exists now:
- CI jobs in .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix of two shards), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke`, and the required `aggregate` result. See [TESTING.md](TESTING.md) for sharding.
- Observability: Prometheus, Loki, Alloy, Grafana with provisioned datasources and dashboards, and PostgreSQL, Redis, and node exporters. The React app does not send telemetry yet.
Not implemented yet: registration and login (their contract is declared; the operations answer 501 or 401), consents, profiles, the questionnaire and assessment, the company cabinet, needs and matching, invitations and contacts, the Resend and SMTP transports and mail delivery, the Go Kafka client, the outbox relay, notifications, support, and an end-to-end business suite. backend/db/migrations/ contains the outbox table and the identity storage tables (`users`, `email_tokens`, `sessions`) and no other business schema; registration, verification, and session behavior on top of that storage comes in later tasks, product usecase and adapter directories other than the password hashing pieces contain only placeholders, and `make -C deploy test-e2e` is a deferred placeholder that exits with an error. The target design is in [ARCHITECTURE.md](ARCHITECTURE.md).
Not implemented yet: registration and login (their contract is declared; the operations answer 501 or 401), consents, profiles, the questionnaire and assessment, the company cabinet, needs and matching, invitations and contacts, the Resend and SMTP transports and mail delivery, the Go Kafka client, the outbox relay, notifications, support, and an end-to-end business suite. backend/db/migrations/ contains the outbox table, the identity storage tables (`users`, `email_tokens`, `sessions`), and the `policy_versions` table and no other business schema; no product rule reads the policy yet; registration, verification, and session behavior on top of that storage comes in later tasks, product usecase and adapter directories other than the password hashing and policy pieces contain only placeholders, and `make -C deploy test-e2e` is a deferred placeholder that exits with an error. The target design is in [ARCHITECTURE.md](ARCHITECTURE.md).
## Install and work loop
@@ -170,6 +170,14 @@ The database never receives a password, a raw email token, or a raw session toke
Passwords enter the backend only as `domain.Password`: `domain.NewPassword` for a new password (15 to 128 code points after NFKC) and `domain.ParseLoginPassword` at login (1 to 128). Raw input over 512 bytes or with invalid UTF-8 is rejected before normalization, and every length check runs before hashing. The `argon2id` adapter implements `outbound.PasswordHasher` with m=65536 KiB, t=3, p=4, a memory budget of `PASSWORD_HASH_CONCURRENCY` derivations (1 to 4; unset means the smaller of 2 and GOMAXPROCS), `ErrPasswordMismatch` for a wrong password, `ErrPasswordHashCorrupt` for a malformed or out-of-bounds stored hash, a `needsRehash` result for older parameters, and `VerifyDummy` for unknown accounts. A stored hash that fails parsing or bounds wraps both `ErrPasswordHashCorrupt` and `domain.ErrInvalidPasswordHash`. Unit tests use cheap parameters; the 64 MiB reference vector is skipped with `-short`; `go test -run '^$' -bench . ./internal/adapter/secondary/argon2id/` in `backend/` measures one hash with the production parameters. See [ARCHITECTURE.md](ARCHITECTURE.md#password-hashing).
### Product policy store
Migration `00003_create_policy_versions.sql` creates `policy_versions`, the trigger that stamps `created_at` from the database clock, and the triggers that refuse UPDATE, DELETE, and TRUNCATE; the queries are in `backend/db/queries/policy.sql`. `outbound.PolicyRepository` is available through `UnitOfWork.Policies()` and through `postgres.PolicyStore` outside a transaction; `policy.Publisher` publishes a version under the next free number and seeds the demo policy. To change a value, publish a new version; a stored version is never edited. `product` is the only policy family.
At startup the backend publishes `domain.DemoProductPolicyV1()` as version 1 of `product` when that family has no version. The seed runs right after the startup migrations and only when they run (`DATABASE_MIGRATE_ON_START` is true and `DATABASE_URL` is set). With startup migrations disabled, nothing seeds the policy. The seed checks presence only, never changes or decodes an existing version, and logs only the key, number, kind, and ID. The demo values are the accepted initial policy, not calibrated values.
A record that depends on policy values adds `policy_version_id uuid NOT NULL REFERENCES policy_versions (id)`, stores the version it used, and reads it back by ID; do not recompute an existing record through `GetEffective`. Tests use their own values and do not stand in for the demo policy. Since `product` is the only family and the table refuses TRUNCATE, the integration tests give every case its own database. A new document layout needs a new `schema_version` and decoder; do not edit the golden document in `backend/internal/domain/policy_test.go` to accept a changed canonical form. See [ARCHITECTURE.md](ARCHITECTURE.md#product-policy-versions).
## Go readability
- Extract repeated parsing, setup, and cleanup into small typed helpers near their consumers. Move code to `pkg/` when several packages actually reuse it. Avoid wrappers that only rename a call.
+62 -10
View File
@@ -89,6 +89,57 @@ Usecase пишет через outbound-порты. `Transactor.WithinTransaction
Ненулевая ошибка значит, что письмо точно не покинуло процесс: `ErrMailChannelUnavailable` в режиме `disabled`, `ErrInvalidOutgoingMail` для некорректного письма или ошибка контекста. Повторы, backoff и учет результатов относятся к единому запланированному слою доставки, а не к транспорту. Сценарии подтверждения (TASK-053, TASK-054) обязаны считать `ErrMailChannelUnavailable` неотправкой: он никогда не подтверждает адрес и не заменяет проверку аккаунта. `OutgoingMail` скрывает себя в выводе `fmt` и `slog`, а ошибки и логи транспорта никогда не содержат получателей, темы, тела писем, учетные данные или сырые ответы провайдера.
### Версии продуктовой политики
Реализованы хранение, публикация и начальное заполнение при старте (TASK-005): миграция `backend/db/migrations/00003_create_policy_versions.sql`, запросы в `backend/db/queries/policy.sql`, типизированная политика в `backend/internal/domain/` (`policy.go`, `policy_document.go`, `policy_version.go`, `policy_demo.go`), порт `outbound.PolicyRepository` (`port/outbound/policy.go`), адаптер на sqlc в `backend/internal/adapter/secondary/postgres/policy.go` и публикация в `backend/internal/usecase/policy/`. Ни одно продуктовое правило пока не читает политику; приглашения, квоты, оценивание, сессии и статус поиска начнут читать ее по мере реализации своих задач.
Колонки `policy_versions`:
- `id`: первичный ключ uuid, UUIDv7 из Go (`domain.PolicyVersionID`).
- `policy_key`: семейство политики. У каждого семейства одна структура документа и один декодер; `product`, который разбирается как `domain.ProductPolicy`, - единственное семейство, и любое другое отклоняют и домен, и CHECK `policy_versions_policy_key_known`. `version`: целое больше нуля, уникальное внутри семейства (`policy_versions_policy_key_version_key`); у самой новой публикации наибольший номер.
- `kind`: `demo` или `calibrated`, состояние калибровки всей версии. Потребители читают именно этот признак. CHECK `policy_versions_calibrated_kind_matches_document` и домен отклоняют версию `calibrated`, в документе которой раздел оценивания помечен некалиброванным.
- `created_at`: время публикации по часам базы данных. Триггер BEFORE INSERT `policy_versions_stamp_creation` ставит в него `clock_timestamp()` при каждой вставке и игнорирует значение вызывающего кода.
- `effective_at`: момент, с которого версия может применяться. NULL во вставке означает "с момента публикации", и тот же триггер ставит в него `created_at`; запланированное время не может быть раньше (`policy_versions_effective_after_creation`, сопоставляется с `outbound.ErrPolicyVersionBackdated`).
- `author`: `system:<name>` или `operator:<handle>`, не более 128 байт из строчных букв, цифр, `.`, `_` и `-`. Символ `@` не допускается, поэтому email-адрес сюда не попадет. Это текст, а не ссылка на `users`: у начального заполнения нет аккаунта, ролей администратора еще нет, а версия должна пережить любой аккаунт, тогда как каскадный или обнуляемый внешний ключ противоречил бы неизменяемости. Редактор администратора сможет добавить ссылку на аккаунт аддитивной миграцией.
- `document`: jsonb-объект с типизированной политикой. `document_sha256`: SHA-256 канонического документа, 32 байта.
Неизменяемость обеспечивает база данных. Функция триггера `policy_versions_refuse_change` отклоняет каждый UPDATE и DELETE (строчный триггер) и TRUNCATE (триггер на оператор) с SQLSTATE 23000 и именем ограничения `policy_versions_immutable`; адаптер сопоставляет с `outbound.ErrPolicyVersionImmutable` именно эту пару, а не текст сообщения. В порту нет методов изменения и удаления, поэтому изменение - всегда новая версия. Гарантия покрывает запросы приложения и ручной SQL; роль-владелец таблицы все еще может отключить триггер или удалить таблицу, поэтому runtime-роль с минимальными правами остается будущей работой.
Типизированная политика `domain.ProductPolicy`: каждое значение - именованное поле, тип которого несет единицу измерения: `CalendarDays`, `BusinessDays` (без перевода в длительность; производственный календарь задает использующая функция), `Hours` и `BasisPoints` для вероятностей и стандартной ошибки - целое число долей 0.0001 (0.80 - это 8000). Базисные пункты сравниваются точно, без погрешности чисел с плавающей точкой, и оставляют в документе целые числа. Метод `Validate` каждого раздела отклоняет нулевые, отсутствующие и выходящие за диапазон значения и несогласованные сочетания, например срок по умолчанию вне списка вариантов, более высокий уровень квоты с меньшим лимитом, неактивный E0, активный уровень над неактивным или вероятности остановки, которые не охватывают порог подтверждения. Диапазоны - защита от ошибок в единицах, а не продуктовые решения. Уровни квот E0 < E1 < E2 доступны через `OrganizationQuotaPolicy.Tier(domain.OrganizationTier)` (для TASK-087); каждая организация начинает с E0, а правила перехода между уровнями относятся к функции квот.
Открытый вопрос для задач попыток (TASK-157 и TASK-158): `MaxAttemptsPerWindow` хранит только число. Считается ли лимит по грейду, по специальности или по всем оцениваниям кандидата, не решено.
У документа `schema_version` 1 и разделы `invitations`, `organization_quotas`, `assessment`, `identity` и `search_status`; имена полей несут единицу (`_days`, `_business_days`, `_hours`, `_bp`). Разбор строгий: отклоняются неизвестные поля, отсутствующие поля и null, неверные типы, дробные числа, значения вне int32, неизвестная версия схемы, данные после объекта и документы больше 64 KiB. Каноническая форма - компактная кодировка Go в порядке объявления полей. jsonb нормализует порядок ключей, поэтому `domain.RestorePolicyVersion` разбирает сохраненный документ, проверяет его, кодирует заново и сравнивает SHA-256 с `document_sha256`; при расхождении возвращается `domain.ErrPolicyDocumentIntegrity`. Golden-тест фиксирует каноническую форму, потому что ее изменение сломало бы проверку всех сохраненных версий; новой структуре нужны новая версия схемы и свой декодер.
Порт `outbound.PolicyRepository` доступен через `UnitOfWork.Policies()` и вне транзакции через `postgres.PolicyStore`. Методы, принимающие семейство, отклоняют неизвестное до обращения к хранилищу.
- `Create` сохраняет пронумерованный `domain.PolicyVersionDraft` и возвращает сохраненную `domain.PolicyVersion` со временем из базы данных. Вставка использует `ON CONFLICT DO NOTHING`, поэтому занятый номер или ID дает `ErrPolicyVersionConflict` и не прерывает окружающую транзакцию.
- `GetByID` читает одну версию.
- `GetEffective(key, at)` возвращает самую новую публикацию, то есть наибольший номер, среди версий, у которых `effective_at` не позже `at`. Поэтому версия, запланированная на будущее, никогда не отменяет версию, опубликованную после нее: срочное исправление остается в силе, когда наступает время более ранней запланированной версии, а запланированная версия оказывается замененной. Этот поиск обслуживает уникальный индекс `(policy_key, version)`.
- `GetLatest(key)` возвращает наибольший номер, действует версия или нет.
- `HasVersions(key)` сообщает о наличии версий, не читая документ.
- При отсутствии возвращается `ErrPolicyVersionNotFound`.
`policy.Publisher` проверяет весь ввод до обращения к хранилищу. Часы приложения он использует только для отказа в запланированном времени, которое уже прошло; время публикации берется из базы данных. `Publish` назначает наибольший сохраненный номер плюс один; если параллельная публикация заняла номер, он перечитывает его и повторяет до 10 раз, после чего возвращает `policy.ErrPublishContended`. Он работает и с репозиторием вне транзакции, и внутри unit of work.
Демонстрационная и калиброванная политика: `domain.DemoProductPolicyV1()` - принятая начальная политика для проверки продуктового сценария. Она публикуется как версия 1 семейства `product` с видом `demo` и автором `system:demo-seed`, а ее раздел оценивания помечен `uncalibrated_initial`. Эти значения не являются калиброванными утверждениями о качестве. Политика содержит только правила; содержание оценивания (банк заданий, blueprints и варианты) - отдельная задача. Демонстрационная версия 1:
| Раздел | Значения |
| --- | --- |
| `invitations` | варианты срока ответа 3, 7 и 14 дней, по умолчанию 7; не более 20 ожидающих приглашений на одну потребность; повтор после отказа через 30 дней; предложение интервью в течение 5 рабочих дней; пауза 30 дней после контакта без сделки |
| `organization_quotas` | скользящие окна 7 дней для приглашений и 24 часа для просмотров разных карточек; E0 10 приглашений и 50 просмотров, E1 40 и 150, E2 100 и 400; E2 неактивен, пока нет верификации организаций, которая его дает |
| `assessment`, начальные некалиброванные значения | повтор того же грейда через 30 дней; не более 3 попыток за 180 дней; повышение не чаще одного раза в 90 дней; подтверждение при P_G >= 0.80, высокая уверенность от 0.90; после не менее 8 оцениваемых заданий остановка при P_G >= 0.90 или <= 0.10 или SE <= 0.25; не более 23 оцениваемых заданий плюс 2 seed-задания; практика обязательна |
| `identity` | токен подтверждения 24 часа; неподтвержденный аккаунт удаляется через 7 дней после последней регистрации; сессия без активности 24 часа, абсолютный срок 7 дней |
| `search_status` | статус "ищу работу" подтверждается каждые 30 дней |
Сроки identity в этой таблице - значения контракта identity ([api/README.md](../../api/README.md#identity-сессии-cookie-и-csrf)). Они берутся из версионированной продуктовой политики, а не из конфигурации: usecase регистрации, подтверждения и сессий будут читать их из действующей версии политики. Правила грейда в разделе [Оценивание и подтверждение грейда](#оценивание-и-подтверждение-грейда) используют те же значения оценивания.
Начальное заполнение: при старте, после миграций и при том же условии (`DATABASE_MIGRATE_ON_START` равен true и задан `DATABASE_URL`), bootstrap вызывает `Publisher.EnsureDemoProductPolicy`. Он проверяет только, есть ли у `product` хотя бы одна версия, и никогда не разбирает ее, поэтому сохраненная версия более новой или неизвестной структуры не может остановить запуск. Если семейство пусто, он публикует демонстрационную версию 1, действующую с момента публикации; иначе ничего не меняет и пишет в лог, что заполнение пропущено. Экземпляры, стартующие одновременно, состязаются за версию 1, и проигравший пропускает заполнение. Строка лога содержит только ключ, номер, вид и ID. Ошибка базы данных останавливает запуск. Заполнение не является вставкой данных в миграции, поэтому схема и значения политики меняются независимо.
Ссылка на версию (запланировано): таблицы, которые фиксируют решение по политике, например решения о грейде, снимки подбора и приглашения, получают `policy_version_id uuid NOT NULL REFERENCES policy_versions (id)` и хранят версию, использованную в момент решения. Существующее решение читает эту версию через `GetByID` и никогда не пересчитывается через `GetEffective`, ответ которого для заданного момента меняется, когда запланированную версию заменяет более новая. Удалить версию, на которую есть ссылка, нельзя ни через внешний ключ, ни через триггер, и новая версия не переписывает прошлые решения.
Тестовые фикстуры используют собственные значения. Поскольку `product` - единственное семейство, интеграционные тесты дают каждому случаю отдельную базу данных, и ни одна фикстура не подменяет демонстрационную политику.
## Структура репозитория и назначение пакетов
```text
@@ -119,11 +170,12 @@ backend/
cmd/app/main.go вызывает bootstrap.Run и обрабатывает ошибку
config/ общая конфигурация runtime
internal/
domain/ плоский пакет; DomainEvent, типы identity
domain/ плоский пакет; DomainEvent, типы identity, продуктовая политика
usecase/health/ operational readiness usecase
port/inbound/ inbound граница readiness
usecase/identity/ проверка пароля до хеширования (Credentials)
port/outbound/ границы readiness, кеша, объектного хранилища, транзакции, outbox, identity, хеширования паролей и почты
usecase/policy/ публикация версий политики и начальное заполнение демонстрационной политики
port/outbound/ границы readiness, кеша, объектного хранилища, транзакции, outbox, identity, политики, хеширования паролей и почты
adapter/primary/http/
api/ generated ogen handler
middleware/ метрики запросов
@@ -134,22 +186,22 @@ backend/
argon2id/ hasher паролей Argon2id с бюджетом памяти
mail/disabled/ почтовый транспорт, который ничего не отправляет и сообщает о недоступности канала
ml/api/ generated client из backend/codegen/ogen-ml.yml
postgres/ pool, migrator, transactor, запись outbox, репозитории identity, health check
postgres/ pool, migrator, transactor, запись outbox, репозитории identity и политики, health check
postgres/sqlc/ generated SQL adapter
redis/ адаптер кеша и проверка Redis
seaweedfs/ S3-адаптер и проверка bucket
prometheus/ ограниченные Go/process и request metrics
bootstrap/ конфигурация, wiring, lifecycle, shutdown
db/ встроенные миграции и SQL-запросы; таблицы outbox и identity
db/ встроенные миграции и SQL-запросы; таблицы outbox, identity и политики
codegen/ конфигурация ogen и sqlc
pkg/ резерв для обоснованных общих технических helpers
```
Доменные типы лежат непосредственно в `backend/internal/domain/`: `user.go`, `candidate.go` и другие файлы по мере определения моделей. Вложенных каталогов по сущностям или модулям здесь нет. Первый тип - `DomainEvent` в `domain_event.go`: проверенное событие, которое транзакция записывает в outbox. Типы хранения identity лежат в `email_address.go`, `secret_token.go`, `user.go`, `email_token.go` и `session.go`; нормализованный пароль - в `password.go`.
Доменные типы лежат непосредственно в `backend/internal/domain/`: `user.go`, `candidate.go` и другие файлы по мере определения моделей. Вложенных каталогов по сущностям или модулям здесь нет. Первый тип - `DomainEvent` в `domain_event.go`: проверенное событие, которое транзакция записывает в outbox. Типы хранения identity лежат в `email_address.go`, `secret_token.go`, `user.go`, `email_token.go` и `session.go`; нормализованный пароль - в `password.go`. Продуктовая политика и ее версии лежат в `policy.go`, `policy_document.go`, `policy_version.go` и `policy_demo.go`.
`domain/`, продуктовые `usecase/`, адаптеры Resend, SMTP и FSP, а также worker зарезервированы; их бизнес-логика не реализована. `main.go` только запускает bootstrap и обрабатывает ошибку процесса. Для публичного generated transport выбран ogen v1.24.0, контракты используют OpenAPI 3.2.0. Проверяется только применяемое подмножество, не вся спецификация.
Это компактная карта, а не обещание, что все запланированные продуктовые пакеты уже существуют. Сейчас Go-код включает health usecase/adapters, generated API clients, bootstrap с миграциями при старте, PostgreSQL health query, транзакционную запись outbox, репозитории identity без использующих их usecase, порт `PasswordHasher` с адаптером Argon2id и проверку пароля, которую вызовет регистрация, Redis cache adapter, S3-адаптер SeaweedFS и порт `MailSender` с транспортом `disabled`. Поведение аккаунтов (регистрация, подтверждение, вход, сессии), резюме, оценивание, приглашения, worker jobs, файловые сценарии, отправка почты, транспорты Resend и SMTP и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей.
Это компактная карта, а не обещание, что все запланированные продуктовые пакеты уже существуют. Сейчас Go-код включает health usecase/adapters, generated API clients, bootstrap с миграциями при старте, PostgreSQL health query, транзакционную запись outbox, репозитории identity без использующих их usecase, версионированное хранилище политики с публикацией и начальным заполнением демонстрационной политики при старте, порт `PasswordHasher` с адаптером Argon2id и проверку пароля, которую вызовет регистрация, Redis cache adapter, S3-адаптер SeaweedFS и порт `MailSender` с транспортом `disabled`. Поведение аккаунтов (регистрация, подтверждение, вход, сессии), резюме, оценивание, приглашения, worker jobs, файловые сценарии, отправка почты, транспорты Resend и SMTP и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей.
`backend/pkg/` зарезервирован для небольших технических пакетов с оправданной общей границей, а не для продуктовых usecase или domain types. Возможные пакеты на будущее: `emailtemplate`, `mailer` и тестовые helpers. S3-клиент остается в адаптере SeaweedFS. Поведение, специфичное для этого сервиса, остается внутри `internal/`.
@@ -196,11 +248,11 @@ contact_grant относится к паре кандидат-компания
- до первого успешного теста статус unverified, заявленный грейд не дает подтвержденную категорию;
- неудача не снижает подтвержденный грейд;
- после первой неудачи кандидат сам выбирает тест более низкого уровня; система не назначает его автоматически;
- изменение грейда после успешной квалификации ограничено, исходный ориентир - 90 дней;
- первое понижение после неудачи не блокируется этим интервалом; повтор на том же уровне может иметь отдельный cooldown, исходный ориентир - 24 часа;
- повышение после успешной квалификации возможно не чаще одного раза в 90 дней;
- первое понижение после неудачи не блокируется этим интервалом; повтор того же грейда возможен через 30 дней, и за любые 180 дней кандидат проходит не более 3 попыток;
- уверенный результат может предложить тест выше; история изменений доступна.
Пороги и интервалы - проектные решения для пилота, не проверенная психометрическая модель. Ротация задач и лимиты попыток уменьшают пользу утечки, но не доказывают защиту от подсказок или LLM. Уровни сложности нужно измерить.
Эти интервалы - принятая начальная политика, сохраненная как демонстрационная версия 1 [продуктовой политики](#версии-продуктовой-политики); ее пороги не откалиброваны и не являются проверенной психометрической моделью. Ротация задач и лимиты попыток уменьшают пользу утечки, но не доказывают защиту от подсказок или LLM. Уровни сложности нужно измерить.
## Подбор и объяснение
@@ -369,7 +421,7 @@ ML eval фиксирует размеченные поля резюме, оши
- Контакты отсутствуют до grant в API, поиске, PDF, ошибках и ML объяснении; другая компания не получает их после принятия.
- Кандидат не читает чужие приглашения, документы, jobs и попытки; компания не читает чужие потребности и подборки.
- Провал не понижает грейд; первый переход на уровень ниже разрешен; 90-дневное ограничение не обходится конкурентными запросами.
- Провал не понижает грейд; первый переход на уровень ниже разрешен; 90-дневное ограничение на повышение не обходится конкурентными запросами.
- Повтор submit/accept не создает второй результат; конкурентные переходы статусов согласованы.
- Отключенный ML оставляет основной ручной путь; worker восстанавливает истекший lease; старый ответ не перезаписывает новую версию.
- Пустая история ФСП отличается от ошибки; отсутствие истории не исключает кандидата.
+1 -1
View File
@@ -13,7 +13,7 @@
Основной файл deploy/docker/docker-compose.yml запускает PostgreSQL, Redis, SeaweedFS, Kafka, Go backend и frontend контейнер. Frontend контейнер раздает статические файлы через Nginx и проксирует /api в backend. PostgreSQL, Redis, SeaweedFS, Kafka, backend и Nginx общаются по выделенной Compose сети.
До открытия listeners backend применяет встроенные в бинарник миграции базы данных; ошибка миграции останавливает контейнер. Compose не передает `DATABASE_MIGRATE_ON_START`, поэтому развернутый backend всегда мигрирует при старте, и роли PostgreSQL из `DATABASE_URL` нужны права DDL на схему приложения. Этот флаг - опция локальной разработки; отдельная роль миграций с минимальными правами - будущая работа. См. [DEVELOPMENT.md](DEVELOPMENT.md#миграции-базы-данных).
До открытия listeners backend применяет встроенные в бинарник миграции базы данных; ошибка миграции останавливает контейнер. Compose не передает `DATABASE_MIGRATE_ON_START`, поэтому развернутый backend всегда мигрирует при старте, и роли PostgreSQL из `DATABASE_URL` нужны права DDL на схему приложения. Этот флаг - опция локальной разработки; отдельная роль миграций с минимальными правами - будущая работа. Сразу после миграций и только когда они выполняются backend заполняет демонстрационную продуктовую политику: если у семейства политики `product` нет ни одной версии, он публикует версию 1 и пишет в лог `demo product policy published`, иначе пишет, что заполнение пропущено, и ничего не меняет. При `DATABASE_MIGRATE_ON_START=false` заполнение тоже пропускается. Ошибка базы данных при заполнении останавливает контейнер так же, как ошибка миграции. См. [DEVELOPMENT.md](DEVELOPMENT.md#миграции-базы-данных) и [ARCHITECTURE.md](ARCHITECTURE.md#версии-продуктовой-политики).
Контекст сборки backend - каталог `backend/`, поэтому Docker применяет `backend/.dockerignore`. Локальные инструменты, кеши, файлы окружения и результаты сборки не отправляются в этот build context.
+10 -2
View File
@@ -48,7 +48,7 @@ Frontend зависимости выбираются из актуальных s
Что есть сейчас:
- Маршруты health и readiness. Nginx сам отвечает на `GET /healthz` и проксирует в Go только `/api/` (deploy/nginx/conf.d/app.conf). Go обслуживает `GET /healthz` (`ok`) и `GET /readyz` (`ready` или 503 `not_ready` после проверки PostgreSQL, Redis и SeaweedFS) на внутреннем порту 8080 вне OpenAPI контракта, а также `GET /api/v1/healthz` из api/core/routes/healthz.yml через ogen handler (backend/internal/adapter/primary/http). Метрики Go отдаются на порту 9090 (`METRICS_ADDR`), Prometheus читает `/metrics`. ML обслуживает `GET /healthz`, `GET /readyz` (всегда 503 `not_ready`, потому что модель не подключена) и `/metrics` (ml/src/lincodex_ml, api/ml/routes). deploy/scripts/smoke.sh проверяет `/healthz` Nginx, `/api/v1/healthz`, `/readyz` Go изнутри сети Compose, 404 для неизвестного API маршрута и то, что backend запустился с `EMAIL_PROVIDER=disabled`; ML он не запускает и писем не отправляет.
- Адаптеры: PostgreSQL через pgxpool и generated запрос `SELECT 1`, runner миграций goose, применяемый при старте, transactor с записью transactional outbox и репозитории identity на sqlc для аккаунтов, email-токенов и сессий; Redis через go-cachekit, SeaweedFS через S3 API. Hasher паролей Argon2id и проверка пароля `identity.Credentials` есть и покрыты тестами, но в bootstrap не подключены. Generated Go client для ML контракта есть, но в bootstrap не подключен.
- Адаптеры: PostgreSQL через pgxpool и generated запрос `SELECT 1`, runner миграций goose, применяемый при старте, transactor с записью transactional outbox, репозитории identity на sqlc для аккаунтов, email-токенов и сессий, а также версионированный репозиторий политики, который при старте заполняет демонстрационную политику; Redis через go-cachekit, SeaweedFS через S3 API. Hasher паролей Argon2id и проверка пароля `identity.Credentials` есть и покрыты тестами, но в bootstrap не подключены. Generated Go client для ML контракта есть, но в bootstrap не подключен.
- Почта: outbound порт `MailSender`, транспорт `disabled` и выбор `EMAIL_PROVIDER` в bootstrap. В этой сборке работает только `disabled`; `resend` и `smtp` после проверки своих настроек останавливают запуск. Пока ничто не отправляет письма. См. [DEPLOY.md](DEPLOY.md#почта) и [ARCHITECTURE.md](ARCHITECTURE.md#почтовый-транспорт).
- OpenAPI контракты api/core/ и api/ml/ с объединением схем, bundles, lint и генерацией для Go (ogen), TypeScript (Orval) и Python (datamodel-code-generator). В SPA есть каркас интерфейса с экранами-заготовками, generated API client и MSW handlers.
- Compose проекты: core (`deploy/docker/docker-compose.yml`: PostgreSQL, Redis, SeaweedFS, Kafka, backend, frontend), ML (`docker-compose.ml.yml`) и monitoring (`docker-compose.monitoring.yml`).
@@ -56,7 +56,7 @@ Frontend зависимости выбираются из актуальных s
- CI jobs в .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix из двух шардов), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke` и обязательный итог `aggregate`. Шардирование описано в [TESTING.md](TESTING.md).
- Observability: Prometheus, Loki, Alloy, Grafana с provisioned datasources и dashboards, exporters для PostgreSQL, Redis и node. React-приложение пока не отправляет телеметрию.
Еще не реализованы: регистрация и вход (их контракт объявлен; операции отвечают 501 или 401), согласия, профили, анкета и тестирование, кабинет компании, потребности и подбор, приглашения и контакты, транспорты Resend и SMTP и отправка почты, Go клиент Kafka, relay для outbox, уведомления, поддержка и бизнес-E2E suite. В backend/db/migrations/ есть таблица outbox и таблицы хранения identity (`users`, `email_tokens`, `sessions`), другой бизнес-схемы нет; регистрация, подтверждение и сессии поверх этого хранения появятся в следующих задачах, каталоги продуктовых usecase и адаптеров, кроме частей для хеширования паролей, содержат только заглушки, а `make -C deploy test-e2e` остается отложенной заглушкой и завершается ошибкой. Целевая архитектура описана в [ARCHITECTURE.md](ARCHITECTURE.md).
Еще не реализованы: регистрация и вход (их контракт объявлен; операции отвечают 501 или 401), согласия, профили, анкета и тестирование, кабинет компании, потребности и подбор, приглашения и контакты, транспорты Resend и SMTP и отправка почты, Go клиент Kafka, relay для outbox, уведомления, поддержка и бизнес-E2E suite. В backend/db/migrations/ есть таблица outbox, таблицы хранения identity (`users`, `email_tokens`, `sessions`) и таблица `policy_versions`, другой бизнес-схемы нет; ни одно продуктовое правило пока не читает политику; регистрация, подтверждение и сессии поверх этого хранения появятся в следующих задачах, каталоги продуктовых usecase и адаптеров, кроме частей для хеширования паролей и политики, содержат только заглушки, а `make -C deploy test-e2e` остается отложенной заглушкой и завершается ошибкой. Целевая архитектура описана в [ARCHITECTURE.md](ARCHITECTURE.md).
## Установка и цикл работы
@@ -170,6 +170,14 @@ goose выполняет каждую миграцию в отдельной т
Пароль попадает в backend только как `domain.Password`: `domain.NewPassword` для нового пароля (от 15 до 128 кодовых точек после NFKC) и `domain.ParseLoginPassword` при входе (от 1 до 128). Исходный ввод длиннее 512 байт или с некорректным UTF-8 отклоняется до нормализации, и все проверки длины выполняются до хеширования. Адаптер `argon2id` реализует `outbound.PasswordHasher` с m=65536 KiB, t=3, p=4, бюджетом памяти на `PASSWORD_HASH_CONCURRENCY` вычислений (от 1 до 4; без значения - меньшее из 2 и GOMAXPROCS), `ErrPasswordMismatch` для неверного пароля, `ErrPasswordHashCorrupt` для некорректного или выходящего за границы сохраненного хеша, результатом `needsRehash` для старых параметров и `VerifyDummy` для неизвестных аккаунтов. Сохраненный хеш, не прошедший разбор или границы, оборачивает и `ErrPasswordHashCorrupt`, и `domain.ErrInvalidPasswordHash`. Unit-тесты используют дешевые параметры; эталонный вектор на 64 MiB пропускается с `-short`; `go test -run '^$' -bench . ./internal/adapter/secondary/argon2id/` в `backend/` измеряет один хеш с production-параметрами. См. [ARCHITECTURE.md](ARCHITECTURE.md#хеширование-паролей).
### Хранилище продуктовой политики
Миграция `00003_create_policy_versions.sql` создает `policy_versions`, триггер, который ставит `created_at` по часам базы данных, и триггеры, отклоняющие UPDATE, DELETE и TRUNCATE; запросы лежат в `backend/db/queries/policy.sql`. `outbound.PolicyRepository` доступен через `UnitOfWork.Policies()` и вне транзакции через `postgres.PolicyStore`; `policy.Publisher` публикует версию под следующим свободным номером и выполняет начальное заполнение демонстрационной политики. Чтобы изменить значение, опубликуйте новую версию; сохраненная версия никогда не редактируется. `product` - единственное семейство политики.
При старте backend публикует `domain.DemoProductPolicyV1()` как версию 1 семейства `product`, если у этого семейства нет ни одной версии. Заполнение выполняется сразу после миграций при старте и только вместе с ними: нужно, чтобы `DATABASE_MIGRATE_ON_START` был равен true и был задан `DATABASE_URL`. Если миграции при старте отключены, политику никто не заполняет. Заполнение проверяет только наличие версий, никогда не меняет и не разбирает существующую версию и пишет в лог только ключ, номер, вид и ID. Демонстрационные значения - принятая начальная политика, а не калиброванные значения.
Запись, которая зависит от значений политики, добавляет `policy_version_id uuid NOT NULL REFERENCES policy_versions (id)`, хранит использованную версию и читает ее обратно по ID; не пересчитывайте существующую запись через `GetEffective`. Тесты используют собственные значения и не подменяют демонстрационную политику. Поскольку `product` - единственное семейство, а таблица отклоняет TRUNCATE, интеграционные тесты дают каждому случаю отдельную базу данных. Новой структуре документа нужны новая `schema_version` и свой декодер; не меняйте golden-документ в `backend/internal/domain/policy_test.go`, чтобы принять измененную каноническую форму. См. [ARCHITECTURE.md](ARCHITECTURE.md#версии-продуктовой-политики).
## Читаемость Go-кода
- Повторяющиеся parsing, setup и cleanup выносятся в небольшие типизированные helpers рядом с потребителями. В `pkg/` код переносится при реальном использовании несколькими пакетами. Обертка, которая лишь переименовывает вызов, не нужна.