Files
lincodex/docs/en/DEVELOPMENT.md
T

252 lines
42 KiB
Markdown

# Development
This guide describes implemented components and repository commands. Current business workflows are listed below; see [ARCHITECTURE.md](ARCHITECTURE.md) for the target design.
## Stack and version sources
| Component | Version source |
| --- | --- |
| Go | exact 1.26.9 in backend/go.mod, toolchain, and Go build image |
| Node.js | frontend/.node-version |
| Frontend dependencies | current stable releases in package manifests and pnpm-lock.yaml |
| Python and uv | ML toolchain declarations and uv.lock |
Select current stable frontend dependency releases and keep pnpm-lock.yaml committed for repeatable installs. ML dependencies are locked in uv.lock; Go dependencies are in backend/go.mod. An update must change its lock/configuration and pass checks for that service. Container images use the requested moving `latest` or `alpine` tags; inspect their current Compose/Dockerfile references instead of treating the tag as a fixed version.
## Implementation status
MVP implementation is ongoing. Values below are read from the named files; when updating a dependency, change its source and lockfile and update this table in both languages.
| Component | Pinned version | Source |
| --- | --- | --- |
| Go | 1.26.9 (`go` directive; no separate `toolchain` line) | backend/go.mod; build image `golang:1.26.9-alpine` in backend/Dockerfile |
| Node.js | 26.11.1 | frontend/.node-version |
| pnpm | 12.9.1 | `packageManager` in frontend/package.json, frontend/pnpm-lock.yaml |
| React, React DOM | 19.3.0 | frontend/package.json, frontend/pnpm-lock.yaml |
| React Router (`react-router-dom`) | 7.18.4 | frontend/package.json, frontend/pnpm-lock.yaml |
| TanStack Query (`@tanstack/react-query`) | 5.104.1 | frontend/package.json, frontend/pnpm-lock.yaml |
| Zod | 4.6.5 | frontend/package.json, frontend/pnpm-lock.yaml |
| Vite | 8.3.2 | frontend/package.json, frontend/pnpm-lock.yaml |
| TypeScript | 7.0.2 (`@typescript/native`, `tsc`); 6.0.2 API (`typescript` alias of `@typescript/typescript6`) for ESLint | frontend/package.json, frontend/pnpm-lock.yaml |
| Vitest | 5.0.3 | frontend/package.json, frontend/pnpm-lock.yaml |
| Orval | 8.40.0 | frontend/package.json, frontend/pnpm-lock.yaml |
| Python | 3.14.8 (`requires-python >=3.14,<3.15`) | ml/.python-version, ml/pyproject.toml |
| uv | 0.12.22 | `[tool.uv] required-version` in ml/pyproject.toml; `setup-uv` in .github/workflows/ci.yml |
| FastAPI | 0.142.2 | ml/pyproject.toml, ml/uv.lock |
| Pydantic | 2.13.5 | ml/pyproject.toml, ml/uv.lock |
| uvicorn | 0.54.0 | ml/pyproject.toml, ml/uv.lock |
| ogen | v1.24.0 | backend/go.mod (`require` and `tool`) |
| sqlc | v1.31.1 | backend/go.mod (`tool`) |
| wire (`github.com/goforj/wire`) | v1.2.0 | backend/go.mod (`require` and `tool`) |
| mockery | v3.8.0 | backend/go.mod (`tool`) |
| golangci-lint | v2.14.0 | backend/go.mod (`tool`) |
| goose | v3.28.0 | backend/go.mod (`require` and `tool`) |
| chi | v5.3.2 | backend/go.mod |
| pgx | v5.11.0 | backend/go.mod |
| testcontainers-go | v0.44.0, including modules/postgres | backend/go.mod |
| franz-go (`kgo`, `kadm`) | v1.22.1, kadm v1.19.0; outbox relay producer, event consumer group members, and integration tests | backend/go.mod |
What exists now:
- Health and readiness routes. Nginx answers `GET /healthz` itself and proxies only `/api/` to Go (deploy/nginx/conf.d/app.conf). Go serves `GET /healthz` (`ok`) and `GET /readyz` (`ready` or 503 `not_ready` after checking PostgreSQL, Redis, and SeaweedFS) on its internal port 8080 outside the OpenAPI contract, plus `GET /api/v1/healthz` from api/core/routes/healthz.yml through the ogen handler (backend/internal/adapter/primary/http). The Go metrics listener uses port 9090 (`METRICS_ADDR`) and Prometheus scrapes `/metrics`. ML serves `GET /healthz`, `GET /readyz` (always 503 `not_ready` because no model is connected), and `/metrics` (ml/src/lincodex_ml, api/ml/routes). deploy/scripts/smoke.sh checks Nginx `/healthz`, `/api/v1/healthz`, Go `/readyz` from inside the Compose network, a 404 for an unknown API route, and that the backend started with `EMAIL_PROVIDER=disabled`; it does not start ML or send mail.
- Adapters: PostgreSQL through pgxpool with a generated `SELECT 1` query, a goose migration runner applied at startup, a transactor with the transactional outbox writer, sqlc-backed identity repositories for accounts, email tokens, and sessions, and the versioned policy repository with the demo policy seed at startup; Redis through go-cachekit, and SeaweedFS through the S3 API. The Argon2id password hasher and `identity.Credentials` are wired for registration and email confirmation. A generated Go client for the ML contract exists but is not wired into bootstrap.
- Mail: the outbound `MailSender` port, the `disabled` and `resend` transports, and the `EMAIL_PROVIDER` selection in bootstrap; `smtp` stops startup after its settings are validated. Product notification requests (`mail_requests`) are turned into deliveries (`deliveries`, `delivery_attempts`) by the `notification_delivery` consumer, but notification sending is not implemented. With `resend`, the backend runs a worker for identity service mail: registration and resend queue verification messages bound to their tokens; the worker checks the token and account before sending and uses a quota gate and stable idempotency key. Password reset is not implemented yet. See [DEPLOY.md](DEPLOY.md#mail) and [ARCHITECTURE.md](ARCHITECTURE.md#mail-deliveries).
- OpenAPI contracts api/core/, api/ml/, and api/runner/ with schema merge, bundles, lint, and generation for Go (ogen), TypeScript (Orval), and Python (datamodel-code-generator). The SPA uses the generated API client; MSW handlers provide test data. Implemented forms are listed below, while remaining routes still show placeholders.
- Compose projects: core (`deploy/docker/docker-compose.yml`: PostgreSQL, Redis, SeaweedFS, Kafka, backend, frontend), ML (`docker-compose.ml.yml`), and monitoring (`docker-compose.monitoring.yml`).
- Kafka: one KRaft node in the core Compose project with an internal-only listener, a named volume, a health check, and a memory limit. The backend runs the outbox relay, which creates the `lincodex.domain.events` topic and publishes committed outbox events to it through a franz-go producer; see [Outbox relay](#outbox-relay). Readiness does not check Kafka. The event consumer runtime runs two product handlers, the mail delivery consumer and the inbox consumer, and no product flow emits their events yet; see [Event consumers](#event-consumers).
- CI jobs in .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix of two shards), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke`, `e2e` (Playwright suite on an isolated stand), and the required `aggregate` result, which fails when any of them fails, is cancelled, or is skipped. See [TESTING.md](TESTING.md) for sharding and the browser suite.
- Observability: Prometheus, Loki, Alloy, Grafana with provisioned datasources and dashboards, and PostgreSQL, Redis, and node exporters. The React app does not send telemetry yet.
The API and SPA implement registration, email confirmation, sign-in, consents, the private candidate profile and questionnaire, company profiles, needs, and account-owned support cases. The API also creates and resumes assessment attempts; answer submission and result calculation are not connected yet. Matching, invitations, contact disclosure, and product notification delivery remain in development. The worker sends identity service mail through Resend; SMTP is not implemented. Each workflow's boundaries are described in the [backend README](../../backend/README.en.md) and [frontend README](../../frontend/README.en.md).
`make -C deploy test-e2e` checks the technical shell on a disposable stack. `make -C deploy test-e2e-registration` also exercises business workflows with an isolated local mail receiver and synthetic data; it does not prove real Resend delivery. See [TESTING.md](TESTING.md#browser-e2e-suite).
## Install and work loop
The frontend uses TypeScript 7.0.2 (`tsc`) for type checking. The `@typescript/native` npm alias points to that compiler, while `typescript` points to the compatible `@typescript/typescript6` API for ESLint. This follows [Microsoft's side-by-side setup](https://devblogs.microsoft.com/typescript/announcing-typescript-7-0/#running-side-by-side-with-typescript-6.0): current typescript-eslint does not support the TS7 API yet. Type checking covers source files, Vite configuration, and the TypeScript files in `codegen/`.
Orval writes directly to `frontend/src/shared/api/endpoints/` and `schemas/`, without an extra `generated/` directory. The adjacent `client.ts` and root `shared/api/index.ts` are handwritten. A Node test exercises the generated MSW handler together with the generated client. After Orval, the `frontend/codegen/mock-patterns.ts` step replaces `faker.helpers.fromRegExp` in the MSW mocks with `fakeFromPattern` and the length bounds from the contract, and `mock-validity.test.ts` checks every response mock with its Zod schema; see [frontend/README.en.md](../../frontend/README.en.md#api-client-generation). Vitest still reports a peer warning expecting MSW 2; the current Node path is tested with MSW 3, and browser mode is not used.
Ignore rules belong to each component's `.gitignore`; root rules cover only root files. CI installs pnpm from frontend/package.json's `packageManager` declaration and does not require bundled Corepack. To check ML locally with a different global uv version, pass `UV='uv tool run --from uv==0.12.22 uv'` to Make.
Run make help at the repository root for the current target list. Main targets:
- make install installs dependencies for api, frontend, ML, and backend.
- make generate bundles both OpenAPI contracts and updates generated Go/TypeScript/Python output.
- make fmt and make fmt-check format or check formatting.
- make lint runs configured linters.
- make test runs backend, frontend, and ML unit/component/service tests.
- make check checks api, backend, frontend, ML, deploy, observability, and documentation.
- make verify runs generation, drift checks, root check, API/backend validation, and a technical Compose smoke.
- make docs-check validates RU/EN docs, local links, routes, and imports.
Use each area's Makefile for its focused loop, for example make -C backend help, make -C frontend help, make -C ml help, make -C api help, make -C deploy help, and make -C observability help.
make check is not a business end-to-end suite. make verify runs a deployment smoke with Docker and a backend integration target. See [TESTING.md](TESTING.md) for validation scope and [DEPLOY.md](DEPLOY.md) for the local stack.
Security tools have a separate install and work loop: `make -C security install`, then `make -C security check`. Use `make -C security test` after changing local rules or scanner integration and `make -C security images` to build and scan service images. These checks are separate from the ordinary root `make check`; see [SECURITY.md](SECURITY.md) for prerequisites, policies, and reports.
### Sessions on local HTTP
The session cookie is `__Host-lincodex_session` with `Secure`, `HttpOnly`, and `SameSite=Strict` (see [api/README.en.md](../../api/README.en.md#identity-sessions-cookie-and-csrf)). The local stack serves plain HTTP. Chromium and Firefox treat `http://localhost` and `http://127.0.0.1` as secure contexts and keep a `Secure` cookie there; WebKit and Safari may reject it. Use Chromium or Firefox for local sign-in, or put a local TLS proxy in front. The project adds no flag that drops `Secure` or the `__Host-` prefix, so the local cookie never differs from production.
`ConfirmEmail` requires Origin to match `APP_PUBLIC_URL` exactly; a missing Origin, the literal value `null`, or any other value answers 403 `csrf_check_failed`. The same check applies to other unsafe identity operations and protected session requests; the latter also require the session-bound CSRF token. The server does not use Host to derive an allowed Origin.
## Layout
Each top-level directory except `.github/` has a short Russian `README.md` and an English `README.en.md`. A README and its translation are optional in `.github/`. Detailed guides live in `docs/ru/` and `docs/en/`; READMEs are not added below the first directory level. `make docs-check` validates language pairs and links and runs the checker's own tests.
| Directory | Purpose |
| --- | --- |
| api/core/ | Public browser-to-Go OpenAPI contract |
| api/ml/ | Internal Go-to-ML OpenAPI contract |
| api/runner/ | Internal OpenAPI contract between Go and the code runner |
| scripts/ | Shared schema merge, generated drift, and docs-check |
| backend/ | Go HTTP service, adapters, bootstrap, SQL, and consumer codegen |
| backend/config/ | Shared Go configuration outside internal |
| frontend/ | Vite SPA, Orval configuration, generated TypeScript |
| ml/ | Python service, lockfile, and Pydantic model generator |
| runner/ | Go code runner service: nsjail, cgroup v2, judge, ogen server, and isolation tests |
| deploy/ | Compose, Nginx, and smoke script |
| observability/ | Prometheus, Loki, Alloy, provisioning, and dashboard JSON |
| security/ | Scanner configuration, installation, Make targets, and local reports |
| .agents/ | Canonical project instructions and working standards |
| docs/ru/, docs/en/ | User documentation in Russian and English |
Codegen directories belong to the services that use the generated code: backend/codegen/, frontend/codegen/, and ml/codegen/. The Go client for the internal ML API is generated from backend/codegen/ogen-ml.yml and consumed at backend/internal/adapter/secondary/ml/api/. The Go client for the code runner is generated from backend/codegen/ogen-code-runner.yml into backend/internal/adapter/secondary/code_runner/api/. The public Go handler is generated from backend/codegen/ogen.yml and mounted in chi. sqlc configuration is backend/codegen/sqlc.yml, with generated SQL under backend/internal/adapter/secondary/postgres/sqlc/. Orval reads the public bundle from frontend/codegen/orval.config.ts. backend/cmd/app/main.go calls bootstrap.Run() and handles its error; startup, dependency wiring, and lifecycle logic live in backend/internal/bootstrap/app.go.
## Contracts and generation
Source YAML stays beside its contract. Run make -C api bundle to merge schemas separately for api/core/, api/ml/, and api/runner/ and then bundle each input. The public and internal APIs remain separate contracts.
Root make generate prepares both bundles once, then runs Go, TypeScript, and Python consumers. Merged schemas, bundles, and generated clients are tracked derived files; change their sources and regenerate them. After changing a contract, regenerate every consumer and check drift. A service-local Make target can generate one consumer when its inputs are ready and the shared contract owner has agreed.
The target is OpenAPI 3.2.0, with ogen for Go, Orval for TypeScript, and datamodel-code-generator for Python/Pydantic v2. Verify the actual feature subset used by the project through pinned tools and the runtime path. A version string does not prove full specification support.
datamodel-code-generator 0.83.0 reads api/ml/openapi.bundle.yml and writes ml/src/lincodex_ml/api/models.py. Settings live in ml/codegen/pyproject.toml; this file configures the tool, while dependencies remain in ml/pyproject.toml and uv.lock. Health/readiness handlers import the generated models instead of maintaining handwritten schema copies. make -C ml generate bundles the API first; when called by root make generate, API_PREPARED=1 reuses the prepared bundle. make -C ml check-generated compares output with --check without rewriting the file. CI uses the shared make generate target, which includes the Python models.
Errors, retries, versions, pagination, and time follow the [contract conventions](../../api/README.en.md#contract-conventions). Implemented: every error of the public Go API and of the ML service is an RFC 9457 problem (`application/problem+json`) with a stable `code`. The Go mapping of ogen errors lives in backend/internal/adapter/primary/http/problem/: request validation gives 400, unknown routes under /api 404, unimplemented operations 501, and other errors and panics 500 without internal text; errors are logged at that boundary, panics only by type and stack. The frontend API client throws `ApiRequestError` for problems, network failures (`network_error`), and invalid 2xx bodies (`invalid_response`); a caller's abort propagates unchanged. The ML service maps FastAPI errors in ml/src/lincodex_ml/api/problems.py and routes uvicorn logs through its JSON format without exception text. Idempotency-Key storage, If-Match checks, and pagination are planned: the contract defines their components, and the first business operation that needs them implements them.
## Code boundaries
SQL linter dependencies are listed in `backend/requirements-quality.txt` beside `.sqlfluff`. The `make -C backend lint-sql` command installs them in the local `.venv-quality` environment and checks migrations and queries. Running the Go service does not require this environment.
Go follows domain, usecase, port, adapter, and bootstrap boundaries. The HTTP adapter mounts the generated ogen handler in chi. SQL belongs in backend/db/queries/; schema changes belong in backend/db/migrations/. sqlc output and wire_gen.go are generated.
Shared backend settings live in backend/config/. The service uses go-logkit 0.6.0 through its slog bridge and go-httpkit 0.7.0 for request IDs and panic recovery. Request logging is the service's own `middleware.RequestLog`: the go-httpkit logger writes the raw path and every query value not on its fixed redaction list, so an address in a path or query would reach the logs. It retains custom Prometheus middleware because it bounds method labels and uses chi route patterns; go-httpkit/metrics accepts the raw method name as a label.
PostgreSQL uses pgxpool.NewWithConfig, and a generated SELECT 1 readiness query checks connectivity. Pool construction must not wait for the database during startup. go-pgkit 1.4.0 is not used because its constructor probes and retries before returning a pool, coupling service startup to database availability. Health handlers remain explicit: go-httpkit's helper returns ok/degraded with check details, while the shared contract uses ok/ready/not_ready. Do not add pgkit, httpkit/metrics, JWT or WebSocket without a concrete need and a check of the pinned version's behavior.
Redis connects through the outbound cache port and `backend/internal/adapter/secondary/redis/`. The adapter uses `go-cachekit` 0.7.0 for key/value operations over go-redis; library details stay behind this boundary. Bootstrap constructs the client without waiting for connectivity and closes it on shutdown; shared /readyz checks PostgreSQL, Redis, and SeaweedFS. Use Get/Set/Del with a positive TTL and distinguish a missing key from a Redis error. This is a technical adapter; product cache consumers have not been added. Connection settings are described in [DEPLOY.md](DEPLOY.md).
S3 storage connects through the outbound `ObjectStorage` port and `backend/internal/adapter/secondary/seaweedfs/`. SeaweedFS is a separate server; AWS SDK for Go v2 is the Go client inside the adapter. Put/Get stream content; Put requires a known byte length, and callers must close the body returned by Get. The Get timeout covers reading the response body. The adapter bounds operation time and distinguishes a missing object from a service error. The container initializes its bucket; Go checks it with HeadBucket instead of creating infrastructure while handling requests. Do not add direct Nginx delivery of private files or product upload/download endpoints without access rules.
The frontend is a React/Vite SPA. Keep FSD boundaries as product screens are added.
Implemented frontend scaffold: a React Router data router with public routes and separate candidate and employer cabinet shells, a TanStack Query client over the shared same-origin `apiRequest`, dark graphite theme tokens in CSS variables, and shared primitives for loading, empty, error, forbidden, and saving states. JetBrains Mono, Inter, and Unbounded (for the Lincodex wordmark) are self-hosted with their OFL licenses. Sign-in, registration, email confirmation, support, and cabinet screens are placeholders; business screens are later tasks. /status is a technical API liveness page, not product readiness. Vitest runs in the Node environment without a DOM. The Playwright suite in `frontend/e2e/` loads pages in Chromium but does not yet test interactions, so clicks and keyboard focus are verified manually in a browser until it covers them. See [frontend/README.en.md](../../frontend/README.en.md). Generated transport types are not automatically entity models. MSW supports UI development; its fixtures do not prove that the API is implemented.
ML runs as a separate FastAPI process. It currently provides operational health/readiness only. Readiness stays at 503 without a model. Do not add placeholder inference that looks like a real result.
Write all source comments and docstrings in English. Keep canonical agent instructions in one English version; maintain user documentation in Russian and English.
### Database migrations
Migrations are goose SQL files in `backend/db/migrations/` named `NNNNN_description.sql` with sequential five-digit versions. Each file has a `-- +goose Up` section and a working `-- +goose Down` section. sqlc reads the same directory as its schema, and `make -C backend lint-sql` lints it. `backend/db/migrations.go` embeds the files, so the binary applies exactly the schema it was built with. `make -C backend check` loads the embedded set without a database and fails on a malformed name, a missing Down section, or a duplicate version. A deployed migration is immutable; change the schema with a new file. Two branches that add the same version must renumber before merging. To create a file with the next sequential number, run `go tool goose -dir db/migrations -s create <name> sql` in `backend/`.
goose runs each migration in its own transaction. A statement that cannot run in a transaction, such as `CREATE INDEX CONCURRENTLY`, needs a file of its own with the `-- +goose NO TRANSACTION` annotation. Every migration connection sets `lock_timeout` to 10 seconds, so DDL fails instead of queueing behind long transactions and blocking later queries on the table, and `statement_timeout` to 4 minutes.
At startup bootstrap applies pending migrations after configuration validation and before the HTTP and metrics listeners open. The runner in `backend/internal/adapter/secondary/postgres/migrator.go` uses the goose v3 Provider API with the pgx database/sql driver and a PostgreSQL session advisory lock, so instances that start together apply migrations one at a time. Lock waiting and migration work are limited to five minutes. A migration error stops startup; the error omits the connection string and the password. Without `DATABASE_URL` the step is skipped with a warning, and readiness stays `not_ready` as before.
`DATABASE_MIGRATE_ON_START` accepts only `true` or `false` (case-insensitive, surrounding spaces ignored); the default is `true`. It is a local and development option, for example to start the service against a database that a developer migrates by hand. The Compose stack does not pass it, and the backend image contains no separate migration command, so a deployed backend always migrates at startup and its database role needs DDL rights on the application schema. A separate migration role and job with a least-privilege runtime role is future work.
For a local database, export `DATABASE_URL` in your shell and use these targets:
- `make -C backend migrate-status` lists each embedded migration as applied, with its time, or pending.
- `make -C backend migrate-up` applies pending migrations.
- `make -C backend migrate-down-one` rolls back the latest applied migration.
The targets run `backend/cmd/migrate` with the same runner, lock, and timeouts as startup. The Makefile contains no connection strings; keep credentials out of committed files. Integration tests apply all migrations to the PostgreSQL container from the shared bootstrap; see [TESTING.md](TESTING.md).
### Identity storage
Migration `00002_create_identity_tables.sql` creates `users`, `email_tokens`, and `sessions`; the queries are in `backend/db/queries/identity.sql`. Migration 00014 adds the password hash, scenario, and onboarding step for each registration to its token. Migration 00016 binds registration C1 to the account registration version and backfills existing records without using live tokens. The identity ports are used by registration, verification resend, and email confirmation; login and the session principal are not implemented.
The database never receives a password, a raw email token, or a raw session token. Repositories take a `domain.PasswordHash` (an Argon2id v19 PHC string) and a `domain.SecretTokenHash` (the SHA-256 of a `domain.SecretToken`). Email addresses are ASCII only for now; IDN and SMTPUTF8 support is future work that needs IDNA ToASCII for the domain. `SecretToken`, `PasswordHash`, and `EmailAddress` redact themselves in `fmt` and `slog` output; `SecretToken.Reveal` and `EmailAddress.Address` return the real values where they are needed. Every stored time comes from the application clock that the caller passes, and PostgreSQL keeps microseconds. A deadlock or serialization failure is reported as `outbound.ErrTransactionConflict`, and the caller may retry the whole operation. The schema and its decisions are described in [ARCHITECTURE.md](ARCHITECTURE.md#identity-storage).
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).
### Assessment bank
Migration `00011_create_assessment_bank.sql` creates `assessment_families` (immutable family versions) and `assessment_category_openings`; the queries are in `backend/db/queries/assessment_bank.sql`. `outbound.AssessmentBankRepository` is available through `UnitOfWork.AssessmentBank()` and `postgres.AssessmentBankStore` outside a transaction; `assessment.Bank` imports a `Bundle`, publishes a version as an operator (retiring the published older one), retires it, opens a category under the policy version in force, reports live availability, and generates a variant of a seed. To change a family, import a new version; a stored version is never edited, and a pending draft is approved by importing a new version that carries the review. A new seed algorithm gets a new versioned name in `domain/assessment_algorithms.go`, its required placeholders, a solver test with hand-computed cases, and a golden test; never change a registered algorithm. An algorithm with the answer format `choice` sets `generateChoice` instead of `generate` and returns the correct value with the wrong values of named error models (`lru_hits_choice.v1` is the example); its tests recompute the error models from the statement. A family whose variants are fixed data uses a table generator instead of an algorithm: `seed_generator.table.rows` with `values`, `answer`, and for `choice` the `distractors`, validated at import with the row index in the error and stored with hash scheme 2; use a Go algorithm when the answer must be computed. Migration `00047_allow_table_hash_scheme.sql` allows scheme 2. Statement templates are plain text with `{{.name}}` placeholders only. The demo bundle in `backend/testdata/assessment/` is an unreviewed AI draft: do not fill in its reviewer to open the category. See [ARCHITECTURE.md](ARCHITECTURE.md#assessment-bank).
### Outbox relay
The relay moves committed `outbox_events` rows to Kafka. The loop lives in `backend/internal/worker/outboxrelay/` and its backoff in `backend/internal/worker/retry/`; it depends on the `outbound.OutboxRelayStore` and `outbound.EventPublisher` ports in `backend/internal/port/outbound/outbox_relay.go`. `postgres.OutboxRelayStore` runs the claim transaction with the `LockPendingOutboxEvents` and `MarkOutboxEventsPublished` queries from `backend/db/queries/outbox.sql`, and `kafka.Publisher` in `backend/internal/adapter/secondary/kafka/` builds the record envelope, provisions the topic, and produces with franz-go. `bootstrap.newOutboxRelay` creates the relay with its own PostgreSQL pool of at most two connections and its own Kafka client, and the application runs it while the HTTP servers run. Product code never calls the relay: a usecase only appends events with `UnitOfWork.Outbox()` in its business transaction.
A directly launched backend with `DATABASE_URL` set runs the relay against `KAFKA_BROKERS` (`localhost:9092` by default). Without a reachable broker it keeps logging retry warnings and the events stay pending; set `RELAY_ENABLED=false` when you do not need publication. Selection, ordering, envelope, and failure semantics are in [ARCHITECTURE.md](ARCHITECTURE.md#outbox-relay); settings are in [DEPLOY.md](DEPLOY.md#outbox-relay); tests are in [TESTING.md](TESTING.md#outbox-relay-tests).
### Event consumers
The consumer runtime applies events from Kafka to this service's own state, once per consumer. The loop lives in `backend/internal/worker/eventconsumer/`; it depends on the `inbound.EventHandler` port (`backend/internal/port/inbound/event_handler.go`) and on the `outbound.EventSource` and `outbound.EventConsumerStore` ports (`backend/internal/port/outbound/event_consumer.go`). `kafka.EventSource` is the franz-go group member that decodes the envelope and commits offsets, and `postgres.EventConsumerStore` runs the dedup transaction with the queries in `backend/db/queries/event_consumer.sql`. The backoff is shared with the relay in `backend/internal/worker/retry/`.
Two product handlers are registered: `notification.DeliveryHandler` stores mail deliveries (see [Mail deliveries](#mail-deliveries)) and `notification.InboxHandler` stores inbox references (see [Internal notifications](#internal-notifications)). To add another, implement `inbound.EventHandler` in the module's usecase package: return a stable snake_case `ConsumerName()`, accept only the event types it applies in `Handles`, and write the effect in `Handle` only through the `UnitOfWork` it receives. Return an error that wraps `inbound.ErrEventRejected` for an event that can never be applied, such as an unknown `schema_version`; any other error is retried. Then add the handler to `eventHandlers()` in `backend/internal/bootstrap/consumers.go`. Bootstrap gives it a consumer group, a share of the consumer pool, and a lifecycle next to the HTTP servers. Test the effect with a real PostgreSQL through the store, as `TestEventConsumer` does.
A directly launched backend with a registered handler and `DATABASE_URL` set consumes from `KAFKA_BROKERS`; set `CONSUMER_ENABLED=false` when you do not need it. Design and failure semantics are in [ARCHITECTURE.md](ARCHITECTURE.md#event-consumers); settings, metrics, and the dead letter procedure are in [DEPLOY.md](DEPLOY.md#event-consumers); tests are in [TESTING.md](TESTING.md#event-consumer-tests).
### Mail deliveries
To send a notification from a usecase, call `notification.MailRequester.RequestNotification(ctx, unit, request)` with the usecase's `UnitOfWork`, the recipient account ID, and `mailtemplate.NotificationData`; it returns the delivery ID. It stores the text in `mail_requests` and appends an event that carries only the request ID and kind, both in the usecase's transaction. The consumer `notification_delivery` then stores the delivery with the address read from the account and the rendered content, and deletes the request; it skips accounts whose address is not verified. Never put an email address, a token, notification text, or another person's contact into any event payload, and never put a token or another person's contact into a request. Verification and password reset mail carry a token and cannot use the event: the identity flows create those deliveries with `domain.NewDelivery` and `UnitOfWork.Deliveries().Create` in the transaction that issues the token. A new template version changes new deliveries only; never update a stored delivery's content. The model is in [ARCHITECTURE.md](ARCHITECTURE.md#mail-deliveries), operations in [DEPLOY.md](DEPLOY.md#mail-deliveries), and tests in [TESTING.md](TESTING.md#mail-delivery-tests).
Every send must pass `notification.QuotaGate`: build it with the configured account and limits and the transport's idempotency window (`resend.IdempotencyWindow`, or zero for SMTP); call `PrepareSend` in the transaction that claims the delivery and commit before calling `MailSender.Send`; then call `SettleSend` in the transaction that records the attempt, and use the time it returns as the attempt's `next_attempt_at` for a `quota_exhausted` rejection. A transport sets `SendResult.QuotaPeriod` from the provider's own error name for a quota rejection. Never call a transport without a permit, and never fall back to another transport or account when the quota is used up. To show an account its own mail status, call `notification.DeliveryStatusReader.LatestForUser` with the authenticated account's ID only. The rules are in [ARCHITECTURE.md](ARCHITECTURE.md#mail-quotas).
### Internal notifications
To put a notification into a recipient's inbox, append an event with `unit.Outbox().Append` in the usecase's own transaction. The type must be allowlisted (`domain.NotificationInboxSourceFor`), the payload must be exactly `recipient_user_id` and `organization_id`, and the aggregate must be the one the type names (`invitation` for `invitation.delivered`). Never put text or contacts in the payload. The `notification_inbox` consumer stores a reference. The text is produced when the recipient reads the list, by a resolver that you register for your source type in `notification.DefaultInboxSourceResolvers()`: an `InboxSourceResolver` that reads the current state through the `UnitOfWork`, applies the recipient's current visibility, and returns `ErrInboxContentUnavailable` when the content must not be shown. For a new event type add the pair to `domain.NotificationInboxSourceFor`, the entry to `inboxProjections` in `usecase/notification/inbox_handler.go`, a migration that widens the CHECK constraint of `notification_inbox_events` (never edit a deployed migration), a `NotificationKind` value to the contract, and the mapping in `adapter/primary/http/v1/notifications.go`. A producer needs no email: mail is requested separately with `MailRequester`, and the inbox state does not depend on it. The path can be tried end to end with the synthetic event `notification.synthetic_delivered` (`notification.SyntheticNoticeEventPayload` builds its payload); it has no product meaning and is handled only when `NOTIFICATION_SYNTHETIC_ENABLED=true`. See [Internal notifications](ARCHITECTURE.md#internal-notifications).
### Scheduled jobs
To run something when it falls due, such as an expiry or a reminder, schedule a job in the usecase's own transaction: build it with `domain.NewScheduledJob` (a kind such as `invitation.response_deadline`, a key that identifies the logical job, for example the aggregate ID, the due time from the injected clock, and a payload of identifiers only) and call `unit.ScheduledJobs().Schedule(ctx, job)`. The first schedule of a kind and key wins and a repeat is ignored, so use a new key, for example `<id>:<version>`, for a new occurrence. Cancel with `unit.ScheduledJobs().Cancel(ctx, kind, key)` before locking the product rows that the handler touches.
Then implement `inbound.JobHandler` in the module's usecase package: return the kind from `JobKind()` and write the effect in `Handle` only through the `UnitOfWork` it receives, deciding by `job.DueAt` and the current product state, so the handler is a no-op when the state already moved on. A handler may cancel its own job through the unit, for example from a shared helper that cancels the deadline; the job then counts as finished. It must not change its own job in any other way. Return an error that wraps `inbound.ErrJobRejected` for a job that can never run; any other error is retried. Add the handler to `jobHandlers()` in `backend/internal/bootstrap/jobs.go`. Take the clock as a `func() time.Time` and test deadlines with `testutil.FakeClock` from `backend/pkg/testutil/` and `Worker.RunDue`, which runs the due jobs once without polling, as `TestScheduledJobs` does. Design and failure semantics are in [ARCHITECTURE.md](ARCHITECTURE.md#scheduled-jobs); settings, metrics, and the dead job procedure are in [DEPLOY.md](DEPLOY.md#scheduled-jobs); tests are in [TESTING.md](TESTING.md#scheduled-job-tests).
## 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.
- Name non-obvious limits, timeouts, retry settings, protocol bounds, and shared fixture values with constants in the owning package. Derive counts with `len` when they depend on data. Equal numbers with different meanings need separate names. Obvious zero values, indexes, and clear test inputs can stay inline.
- Environment settings belong in config with named defaults and validation. Parse each value once; distinguish an unset variable from an explicitly invalid value.
- Give each function one clear purpose. Prefer early returns, shallow nesting, and named complex conditions. Do not add generic helpers, interfaces, or layers without consumers.
- Pass `context.Context` first. Keep resource ownership and dependencies explicit; register cleanup immediately after acquisition, including partial startup. Helpers must not hide goroutines or global mutable state.
- Check errors and explain non-obvious discarded results. Do not use error-string comparisons for control flow or expose internal errors in HTTP responses.
- Write English comments explaining constraints and decisions. Use gofmt/goimports. Refactors preserve behavior; tests cover meaningful boundaries and edge cases rather than constant names or helper internals.
## Error format
Handwritten Go errors use `Component.Method - operation: %w` when wrapping a cause and `Component.Method - reason` without a cause. For a free function, use `package.Function`. For example:
```go
if err != nil {
return fmt.Errorf("EmailUseCase.Send - read ctf_name: %w", err)
}
```
Create a static error without a cause using `errors.New("EmailUseCase.Send - ctf_name is empty")`. The prefix identifies the actual method; descriptions are in English without trailing punctuation. Preserve `errors.Is/As` and sentinel identities, adding context at the error's origin. Avoid redundant wrappers for pass-through returns. Sanitize external SDK errors before wrapping to exclude secrets, URLs, and private object keys. Do not edit generated code. Log errors at the handling boundary rather than at every layer.
## Change rules
- Inspect current code and ownership before editing a shared file.
- Preserve other contributors' current changes.
- Coordinate changes to OpenAPI, migrations, shared Makefiles, lockfiles, and generated output with one owner of that shared surface.
- Regenerate derived files through Make targets.
- Label current behavior and intended behavior separately.
- Do not commit local paths, secrets, or personal developer settings.
For backend, frontend, ML, API, database, and infrastructure tasks, use the routes in the root [AGENTS_ROUTING.md](../../AGENTS_ROUTING.md).