33 KiB
Development
This guide describes the current technical scaffold and the commands declared in the repository. Product workflows remain planned; see ARCHITECTURE.md for the target design.
Stack and version sources
| Component | Version source |
|---|---|
| Go | exact 1.26.8 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.
Scaffold status
The repository contains a verifiable technical scaffold, not a product. 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.8 (go directive; no separate toolchain line) |
backend/go.mod; build image golang:1.26.8-alpine in backend/Dockerfile |
| Node.js | 26.10.0 | 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 /healthzitself and proxies only/api/to Go (deploy/nginx/conf.d/app.conf). Go servesGET /healthz(ok) andGET /readyz(readyor 503not_readyafter checking PostgreSQL, Redis, and SeaweedFS) on its internal port 8080 outside the OpenAPI contract, plusGET /api/v1/healthzfrom 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 servesGET /healthz,GET /readyz(always 503not_readybecause no model is connected), and/metrics(ml/src/lincodex_ml, api/ml/routes). deploy/scripts/smoke.sh checks Nginx/healthz,/api/v1/healthz, Go/readyzfrom inside the Compose network, a 404 for an unknown API route, and that the backend started withEMAIL_PROVIDER=disabled; it does not start ML or send mail. - Adapters: PostgreSQL through pgxpool with a generated
SELECT 1query, 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 theidentity.Credentialspassword 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
MailSenderport, thedisabledtransport, and theEMAIL_PROVIDERselection in bootstrap. Onlydisabledworks in this build;resendandsmtpfail startup after their settings are validated. Nothing sends mail yet. See DEPLOY.md and ARCHITECTURE.md. - OpenAPI contracts api/core/ and api/ml/ with schema merge, bundles, lint, and generation for Go (ogen), TypeScript (Orval), and Python (datamodel-code-generator). The SPA has an interface scaffold with placeholder screens, a generated API client, and MSW handlers.
- Compose projects: core (
deploy/docker/docker-compose.yml: PostgreSQL, Redis, SeaweedFS, Kafka, backend, frontend), ML (docker-compose.ml.yml), and monitoring (docker-compose.monitoring.yml). - Kafka: one KRaft node in the core Compose project with an internal-only listener, a named volume, a health check, and a memory limit. The backend runs the outbox relay, which creates the
lincodex.domain.eventstopic and publishes committed outbox events to it through a franz-go producer; see Outbox relay. Readiness does not check Kafka. The event consumer runtime exists, but no product handler is registered, so nothing consumes the events yet; see 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 requiredaggregateresult, which fails when any of them fails, is cancelled, or is skipped. See 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.
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, product event consumers, notifications, support, and an end-to-end business suite. backend/db/migrations/ contains the outbox table with its relay index, the identity storage tables (users, email_tokens, sessions), the policy_versions table, and the event consumer tables (consumer_processed_events, consumer_dead_letters) 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 runs only a technical Playwright smoke of the SPA, API health, and error routes on a throwaway stack, not a business flow (see TESTING.md). The target design is in ARCHITECTURE.md.
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: current typescript-eslint does not support the TS7 API yet. Type checking covers source files, Vite configuration, and codegen/orval.config.ts.
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. 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 for validation scope and 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 for prerequisites, policies, and reports.
Sessions on local HTTP
The planned session cookie is __Host-lincodex_session with Secure, HttpOnly, and SameSite=Strict (see api/README.en.md). The local stack serves plain HTTP. Chromium and Firefox treat http://localhost and http://127.0.0.1 as secure contexts and keep a Secure cookie there; WebKit and Safari may reject it. Use Chromium or Firefox for local sign-in, or put a local TLS proxy in front. The project adds no flag that drops Secure or the __Host- prefix, so the local cookie never differs from production.
Planned Origin rule (TASK-056): every unsafe request (POST, PUT, PATCH, DELETE), including public ones such as login, must carry an Origin from an allowlist in the backend configuration, for example the Nginx origin and the Vite dev origin. The server does not compare Origin with Host. An unsafe request without Origin or with another value answers 403 csrf_check_failed.
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 |
| 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 |
| 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 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/ and api/ml/ and then bundle both inputs. 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. 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, request logging, and panic recovery. 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.
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, brand tokens in CSS variables, and shared primitives for loading, empty, error, forbidden, and saving states. JetBrains Mono 2.304 is self-hosted from the brandbook with its OFL license. 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. 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-statuslists each embedded migration as applied, with its time, or pending.make -C backend migrate-upapplies pending migrations.make -C backend migrate-down-onerolls 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.
Identity storage
Migration 00002_create_identity_tables.sql creates users, email_tokens, and sessions; the queries are in backend/db/queries/identity.sql. The outbound.UserRepository, EmailTokenRepository, and SessionRepository ports are available through UnitOfWork inside Transactor.WithinTransaction and through postgres.IdentityStore outside a transaction. Nothing in bootstrap or the HTTP handlers uses them yet; registration, verification, login, and the session principal come in later tasks.
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.
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.
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.
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; settings are in DEPLOY.md; tests are in TESTING.md.
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/.
No product handler is registered yet. To add one, 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; settings, metrics, and the dead letter procedure are in DEPLOY.md; tests are in TESTING.md.
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
lenwhen 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.Contextfirst. 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:
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.