initial commit

This commit is contained in:
TakuyaYagam1 committed 2026-10-05 14:23:31 +03:00
commit 88c14b627e
224 files changed
+17204

No files matched your search

+294
View File
@@ -0,0 +1,294 @@
# Lincodex architecture
This document separates the target product architecture from the technical scaffold in the repository. The requirements source is ФСП спец. трек ТЗ.pdf at the repository root. Page references in the coverage table use the printed pagination without the cover page. The team supplied October 11 and October 30, 2026, as project milestones.
## Current scaffold
The repository contains a Go HTTP service with a PostgreSQL check, a minimal React status page, a separate Python ML service with health and readiness routes, two OpenAPI contracts, code generation, Compose files, and monitoring configuration. The public API health route is under /api/v1/healthz. The web container uses /healthz. ML uses /healthz and /readyz; readiness returns 503 while inference is unavailable. Go exposes the standard /metrics endpoint on an internal port.
This is an operational scaffold. It has no registration, roles, profiles, assessments, grades, candidate search, invitations, resume processing, PDF generation, or FSP integration. ML does not return invented results. Health checks and the technical smoke do not verify a product workflow.
See [development](DEVELOPMENT.md), [deployment](DEPLOY.md), and [testing](TESTING.md) for source layout, commands, and current check coverage.
## Target system
The target is a modular Go backend with Clean Architecture, a React SPA using Vite and FSD, and a separate ML HTTP service in one repository. The planned Go process runs the HTTP API and background worker together. PostgreSQL stores product records and jobs. Private file storage holds resumes and generated PDFs. The initial target uses Docker Compose on one application host, with ML in a separate environment.
Go owns authorization, verified categories, invitations, contact grants, and final search results. ML proposes resume fields, helps interpret employer needs, and can take part in semantic search experiments. Model outages must leave manual profiles, assessments, filter-based search, and invitations available.
Combining API and worker simplifies the demo deployment, while sharing process lifecycle, memory limits, and metrics registry. The worker can move to its own process when independent scaling is needed without moving usecases or ports. That worker is planned.
The project brief assigns 35% of its score to matching, 25% to assessment and categorization, and 7% to technical implementation. The October 11 milestone calls for a working prototype flow. Technical work alone does not provide that flow.
## Contracts and code generation
The contract roots are split by boundary: api/core/ contains browser-to-Go operations, and api/ml/ contains internal Go-to-ML operations. The shared Makefile, package.json, and Redocly configuration stay under api/. Python schema tools live in the repository-level scripts/ directory. Each contract is assembled from small source YAML files.
The public Go handler is generated by ogen from backend/codegen/ogen.yml and mounted in chi. Orval independently generates the TypeScript client, TanStack Query hooks, Zod schemas, and MSW handlers. The ML Go client is configured at backend/codegen/ogen-ml.yml and generated into backend/internal/adapter/secondary/ml/api/. datamodel-code-generator produces Pydantic v2 models from the same ML bundle in ml/src/lincodex_ml/api/models.py; the health/readiness handlers use these models. Python generator settings live in ml/codegen/pyproject.toml, while dependencies remain in ml/pyproject.toml. Backend sqlc configuration is backend/codegen/sqlc.yml and its generated SQL adapter is under backend/internal/adapter/secondary/postgres/sqlc/. Frontend configuration is frontend/codegen/orval.config.ts. There are three codegen directories: backend/codegen/, frontend/codegen/, and ml/codegen/. Configuration belongs to the service that uses the generated code.
OpenAPI 3.2.0 is the target version. Verify the subset used here across bundling and lint, ogen, the chi adapter, the API runtime path, Orval, Python Pydantic models, and documentation. A parser version or one fixture does not prove support for every OpenAPI 3.2.0 feature.
The public API prefix /api/v1 is applied once. The internal /metrics endpoint remains separate. Health operations use names ending in z: healthz and readyz. Generated types and request validation do not implement ownership checks, company membership, consent, or valid product state transitions.
Generate bundles from contract sources, then regenerate each Go, TypeScript, and Python consumer through its Make target. A contract change includes generation and drift checks for every consumer. Never edit generated files by hand.
## Service and data boundaries
The planned backend boundaries are:
- Primary adapters receive HTTP requests and translate them into inbound ports.
- Usecases implement application flows and depend on domain rules and ports.
- Secondary adapters implement storage, ML, email, and file operations.
- Bootstrap wires implementations and controls process startup and shutdown.
- Product rules stay in domain and usecase code, away from chi handlers, workers, SQL, and ML.
Shared Go configuration belongs in backend/config/ outside internal. wahrwelt-kit logkit 0.6.0 and httpkit 0.7.0 currently provide technical functions. Metrics use bounded custom collector/middleware code, and pgxpool collection must not block startup. pgkit and httpkit/metrics are not currently used. Technical libraries do not own product rules. Do not add unselected JWT, cache, or WebSocket dependencies for hypothetical features.
PostgreSQL with pgx, sqlc, and goose remains the planned database stack. Developers own SQL; sqlc generates typed adapters. goose manages versioned migrations. wire provides compile-time dependency construction in bootstrap, with no runtime DI container. API and worker share the database pool in the planned single-process deployment.
The MVP does not add Redis, a separate vector database, a broker, Kubernetes, or a search microservice. Initial search uses PostgreSQL filters and full-text search over an allowed projection. Consider pgvector only if evaluation shows embeddings help.
## Repository map and package purpose
```text
api/core/ public browser-to-Go contract and bundle
api/ml/ internal Go-to-ML contract and bundle
backend/cmd/app/main.go calls bootstrap.Run and reports errors
backend/config/ shared runtime configuration
backend/internal/domain/ product invariants, planned modules
backend/internal/usecase/ application operations and orchestration
backend/internal/port/ inbound and outbound interfaces
backend/internal/adapter/ primary HTTP and secondary integrations
backend/internal/bootstrap/ dependency wiring and process lifecycle
backend/db/ migrations and SQL queries
backend/codegen/ ogen server and ML-client configs, sqlc
frontend/src/ app, pages, widgets, features, entities, shared
frontend/codegen/ Orval configuration
ml/src/ FastAPI service and operational checks
ml/codegen/ Python datamodel-code-generator settings
deploy/ Compose, Nginx, and technical smoke checks
observability/ Prometheus, Loki, Alloy, Grafana provisioning
scripts/ shared documentation and schema tooling
docs/ maintained Russian and English guides
```
```text
backend/
cmd/app/main.go calls bootstrap.Run and reports errors
config/ shared runtime configuration
internal/
domain/ flat package; currently only .gitkeep
usecase/health/ operational readiness usecase
port/inbound/ readiness input boundary
port/outbound/ database readiness boundary
adapter/primary/http/
api/ generated ogen handler
middleware/ request metrics
v1/ handwritten health endpoint
router.go chi composition
adapter/secondary/
ml/api/ generated client from backend/codegen/ogen-ml.yml
postgres/sqlc/ generated SQL adapter
prometheus/ bounded Go/process and request metrics
bootstrap/ configuration, wiring, lifecycle, shutdown
db/ migrations and SQL queries; no product schema yet
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. Until the types are defined, the directory contains only `.gitkeep`.
Product domain types and usecase modules, file/mail/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, and a PostgreSQL health query. Accounts, resumes, assessments, invitations, worker jobs, storage, mail, 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; a `storagepath` helper is optional if local file storage is selected. Keep service-specific behavior private under `internal/`.
`api/` contains contract sources and tools; it is not a runtime hop in the request path. `api/core/` and `api/ml/` each own OpenAPI source, route and component fragments, and a committed bundle. Root `scripts/` merges schema fragments. Generated Go output belongs to its consumer: the public handler under `backend/internal/adapter/primary/http/api/`, the internal ML client under `backend/internal/adapter/secondary/ml/api/`, and sqlc output under `backend/internal/adapter/secondary/postgres/sqlc/`. The first is transport code mounted in chi; the latter two are outbound adapters. `backend/cmd/app/main.go` remains a small process entry point; bootstrap owns dependency wiring and graceful shutdown.
## Target modules
| Module | Responsibility | Main data |
| --- | --- | --- |
| identity | Email, verification, sessions, roles | users, email_tokens, sessions, external_identities |
| candidate | Profile, contacts, consent, visibility | profiles, contacts, skills, consents, resume_versions |
| company | Company and its members | companies, company_members |
| assessment | Questionnaire, tasks, attempts, scoring, grade | questionnaires, task_templates, attempts, answers, grade_history |
| matching | Needs, filters, ranking, search versions | hiring_needs, search_runs, search_items |
| invitation | Offer and contact permission | invitations, invitation_events, contact_grants |
| document | Files, resume analysis, standard PDF | files, analysis_results, document_jobs |
| achievement | FSP link and achievement provenance | fsp_links, achievements, sync_runs |
| vacancy, later | Vacancies and voluntary applications | vacancies, applications |
The MVP uses one PostgreSQL database. Keep relational links and constraints explicit. JSONB can hold versioned questionnaire answers and ML results; it does not replace the data model. Skills and specialties use normalized references. Large PDFs stay outside PostgreSQL. Candidate category combines specialty and test-verified grade. Claimed and verified grades remain separate.
An achievement records its source, external ID, event date, receipt date, and trust status. Missing FSP history, a missing link, and a temporary sync error are distinct states. ML has no direct access to the business database.
## Target user flow
Candidate flow: verify email -> complete profile and consent -> answer questionnaire -> select expected grade -> take assessment -> receive a verified category -> publish profile.
Employer flow: verify email -> create company profile -> describe need -> confirm extracted skills -> choose filters -> review an explainable result set -> send a salary offer -> candidate accepts -> only that company can access contacts.
An invitation includes the employer, description, contact channel, both salary bounds, and RUB currency. Both salary values are required and must satisfy 0 < salary_from <= salary_to. Show the pay period and tax basis. vacancy_id is optional. Main transitions are sent -> viewed -> accepted or declined; direct acceptance from sent is allowed. withdrawn and expired are additional states. Retries are idempotent, and transactions protect concurrent state changes.
A contact grant belongs to one candidate-company pair and is created after an accepted invitation or a candidate's own application. The server checks the user, company membership, grant, and current visibility on each read. Before a grant, employers receive no contacts, original PDF, messaging links, or contact fragments from resumes or ML.
The owner profile, search card, and authorized contacts use separate DTOs. The candidate can receive a complete PDF. A company export is built from its allowed view after another access check. A permanent public file URL does not replace authorized delivery. Revoked consent removes the profile from new and saved search results; it cannot retrieve information another party already received.
## Assessment and grade verification
Assessments use reviewed task families and a blueprint for each specialty and grade. The blueprint records competencies, difficulty, task count, and weights. Variants change the prompt and input while keeping the assessed skill; shuffling answer choices is insufficient. Go backend and React frontend at junior/middle level are the initial demo scope. Other specialties need a real task bank.
Fix the seed, version, and conditions before an attempt. Keep answers and keys on the server. Prefer automatically scored formats that do not execute candidate code in the MVP. Free-form answers can be an additional signal; LLM scoring is never the sole basis for a grade. Team pilots set thresholds, and a high average must not hide a critical-section failure.
Grade state rules:
- Before the first passing assessment, status is unverified and a claimed grade does not grant verified category access.
- A failed attempt never lowers an existing verified grade.
- After an initial failure, the candidate may choose a lower-level test; the system does not assign it automatically.
- 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 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.
## Matching and explanations
Before ranking, Go applies hard filters: published profile, specialty, verified grade, required skills, and other selected criteria. A strong resume or achievement cannot compensate for a missing mandatory requirement. Distinguish an unverified skill from evidence that the skill is absent.
Initial baseline after filtering:
score = 0.50 * skill_fit
+ 0.40 * assessment_score
+ 0.10 * fsp_evidence
Each component ranges from 0 to 1. skill_fit is weighted coverage of verified requested skills. assessment_score is the result for relevant assessment sections. fsp_evidence is a small bonus for relevant verified achievements. An empty skill set uses a predefined neutral value and avoids division by zero. Use a stable ID tie-break, never personal characteristics.
No FSP history gives a zero bonus without excluding the candidate. Synthetic achievements are marked and affect demo data only. Results include score_components, reason_codes, evidence, and gaps. A candidate with a verified Middle grade and 4 of 5 covered skills still fails a filter that requires confirmation of all five.
This is an initial baseline, not an optimized or measured ranking model. The plan compares keyword search, the verified-skill baseline, and an ML variant. Add a semantic signal only after an experiment; never treat its score as a probability of hiring success.
Store each search as a search_run with its company, original need, filters, ranking version, and parent version. Refinement creates another snapshot. search_items stores order, scores, and profile versions without contacts. An old snapshot does not preserve access: hidden or removed profiles disappear, stale ranking is marked, and retention is bounded.
## ML, documents, and background jobs
Planned ML operations are resume analysis, need analysis, and, after the baseline, embeddings and limited reranking. Go sends only allowed inputs and a short candidate list. Responses are limited to known IDs and validated against schema and version. ML failure falls back to the baseline. Models cannot set categories or expose contacts.
Planned PDF flow: limit size, page count, and upload rate; validate file type and owner; save a source version; create a job in the same transaction; extract text in an isolated resource-limited environment; mask contacts; request a structured result; validate its size and versions; show proposed fields for candidate approval. A scan without a text layer reports that state and offers manual entry; OCR is a separate extension. Never log full resume text or traces.
Resume text is untrusted data, not an instruction to tools. ML does not follow arbitrary links, run commands, or verify whether employment claims are true. Each proposed field records its evidence and limitations.
A standardized PDF is required in the product even when profile entry is manual. PDFRenderer consumes structured profile data. The planned approach is controlled HTML and isolated headless Chromium with Cyrillic fonts, no external network fetches, and no user-supplied HTML.
Future jobs use queued, running, succeeded, failed, and cancelled states, an attempt limit, available_at, lease/heartbeat, and a safe error code. Claims are atomic. An expired lease permits retries; operation key, document version, and lease token prevent stale workers from overwriting newer results. Computation may repeat; a business effect must not. Retries are bounded and use backoff.
Long operations return 202 and a job ID. The UI polls with a widening interval and stops after completion or page exit. The browser never calls ML directly. Routine tests do not download a model or require GPU. Model, license, inference budget, and production latency are unselected.
## Identity, FSP, and privacy
The initial product plan uses email/password, email verification, and server-side PostgreSQL sessions. Browser cookies are Secure, HttpOnly, and SameSite; mutating requests use CSRF protection. Hash passwords with a suitable KDF. Tokens are random and expire; store their hashes. Require email verification before publishing a candidate or sending invitations.
Future FSP identity linking requires provider verification. A manually entered identifier or matching email is not enough to merge accounts. The brief supplies no real FSP API, so development starts with a fixture provider and a project-owned DTO. If organizers provide Keycloak/OIDC, add Authorization Code + PKCE and validate issuer, state, nonce, audience, and redirect URI. Lincodex still owns roles and contact grants.
The brief references Russian Federal Law 152-FZ. The system design calls for separate processing/publication consents, revocation, transfer controls for ML, and retention/deletion periods. Architecture documentation does not prove legal compliance. Agree on data handling before using real personal data; use synthetic profiles for the demo.
## Frontend
The target FSD structure has app for router and providers, pages for screens, widgets for larger UI blocks, features for actions, entities for product concepts, and shared for API, UI, and utilities. Imports point down; generated DTOs do not import product entities. TanStack Query owns server state, forms own drafts, and URL parameters own filters and search IDs. Add Zustand only for a specific shared client-state need.
The shared API wrapper owns base URL, cookies, AbortSignal, and error parsing. MSW is for development and tests; it is not a real integration check. Logout/account switch clears private query cache. Screens need loading, empty, error, retry, and forbidden states.
The target screen stack is React Router, TanStack Query, React Hook Form, and Zod, with CSS Modules and CSS variables. Radix UI can be added for complex accessible menus and dialogs. Add Next.js only for a demonstrated SSR or indexable-catalog need; Bun does not replace the selected stable Node and pnpm setup. Vite builds static assets served by Nginx, so production does not need a Node frontend process. These are target choices, not a claim that product libraries are already wired into the scaffold.
## Future extensions
PostgreSQL jobs are enough for the MVP. A broker needs an outbox, idempotency, ordering, retries, and deduplication. RabbitMQ/NATS fit independent consumers and routing. Kafka needs a durable stream with multiple consumers and a measured volume. Extract search, assessment, or notification only for an independent scale or lifecycle need. gRPC is useful when several internal services benefit from protobuf or streaming; it does not replace browser-facing OpenAPI.
k3s is outside the critical path. Consider it only with an operated cluster or measured multi-node need. A single-node cluster does not provide HA. A transition needs probes and resource limits, secrets, storage backup, ingress, and verified NetworkPolicy.
Vacancies and voluntary applications, recurring assessments, employer complaints/verification, ATS adapters, and deeper matching are future scope. Employer verification and ATS integration are not implemented or required for the first prototype.
## First product API slice
| Group | Initial target |
| --- | --- |
| identity | register, verify/resend email, login, logout, me; password reset can wait until the final phase |
| candidate | own profile, questionnaire, consent, publish and hide |
| documents | resume upload, analysis request, job status, confirmation of proposed fields, PDF retrieval |
| assessment | available tests, attempt start, answer save, submit, history, and eligibility |
| company | company profile and current user membership |
| matching | need, confirmation of extracted fields, search create/refine/read |
| invitation | send, list, view, accept/decline, withdraw, and authorized contact access |
| achievement | FSP link state and achievement history; fixture provider for demos |
Examples of stable operations are `POST /api/v1/searches`, `POST /api/v1/searches/{id}/refinements`, `POST /api/v1/candidates/{id}/invitations`, and `POST /api/v1/invitations/{id}/accept`. These are target examples, not implemented endpoints. Every business operation, response, and error belongs in OpenAPI with a stable `operationId`.
Contract rules: UUID identifiers, UTC date-time, explicit enums, integer RUB amounts for the MVP, and bounded cursor pagination. Distinguish null from absent fields. Errors have a stable `code`, safe message, optional field errors, and request ID. Use idempotency keys for invitation creation, analysis start, and assessment submission; scope keys by actor and operation, and reject reuse with a different body. Check access for every object ID, job, search run, and PDF. Never include contacts in common errors or public examples.
## Metrics, telemetry, and alerts
The current Go service exports standard Go/process metrics, `lincodex_http_requests_total` with bounded `method`, route-template `route`, and `status` labels, and `lincodex_http_request_duration_seconds`. Do not use user, candidate, request IDs, full URLs, addresses, or resume content as labels. `/metrics` uses an internal listener outside `/api/v1`. Go runtime, PostgreSQL, and Linux dashboard JSON files are maintained project sources, not imported dashboard IDs. Queue, inference, and product-event metrics are not implemented in the current scaffold.
Planned observability work includes bounded measurements for queued jobs, oldest ready age, wait and run duration, retries, and terminal failures; pgxpool state should use bounded nonblocking reads inside Go. Nginx `stub_status` does not provide latency by HTTP status; access logs can provide `request_time` and `upstream_response_time`. cAdvisor is optional if the selected runtime supports it. Redis and DCGM exporters belong only with actual Redis or a local NVIDIA model.
The planned browser path is Faro Web SDK -> same-origin `/telemetry` -> Alloy `faro.receiver` -> Loki. The React SDK is not connected yet. Collect cleaned Web Vitals, JavaScript errors, release, and normalized route; exclude console logs, form content, resume text, and session replay. Remove query strings, fragments, and identifiers from URLs. Limit receiver size, rate, and origin. Request/trace IDs remain log fields, not labels; complete span storage needs a separate backend such as Tempo and is not currently supported.
Future alerts cover unavailable targets, elevated 5xx rate with enough requests, latency budget breaches, old or terminally failed jobs, disk pressure, ML errors, and dropped logs. Low traffic needs a window and minimum event count to avoid unstable rates and percentiles. Configure `No Data` and datasource-error behavior explicitly. A monitoring stack cannot reliably report a host failure on that same host; that requires an independent external health check. Compose and dashboard smoke checks do not verify alert delivery. Document alert rules and notification channels as implemented only after they have been tested.
## Requirements coverage
| Brief requirement | Target decision | State |
| --- | --- | --- |
| Two portals and verified email, pp. 3-4 | identity, roles, company, access checks | Not implemented |
| Manual or PDF resume, p. 3 | Manual profile first; PDF and ML extend it | Not implemented |
| Standard PDF, p. 3 | PDFRenderer with Cyrillic and access checks | Not implemented |
| Questionnaire, grade, test, category, pp. 1-3 | assessment, variants, grade history | Not implemented |
| Comparable tests and leak resistance, pp. 1-2 | Families, blueprint, rubrics, rotation, pilot | Planned |
| No forced grade decrease and change frequency, pp. 2-3 | verified/claimed, retry, cooldown, eligibility | Planned |
| Candidate search and explanation, pp. 3-4 | Hard filters, matching evidence, score components | Not implemented |
| Refine search without losing prior results, p. 4 | Versioned search runs and server snapshots | Planned |
| Invitation without a vacancy, p. 3 | Optional vacancy_id | Not implemented |
| RUB salary range and employer contact, p. 4 | Required bounds and explicit period/tax basis | Not implemented |
| Status for both sides, p. 4 | State machine and event history | Not implemented |
| Contacts after acceptance/application, pp. 3-4 | Contact grant, separate DTOs, file access check | Not implemented |
| Privacy and access to own records, pp. 3, 6 | Consent, object/company authorization, cache and snapshot checks | Required, no implementation |
| FSP ID and missing history, pp. 2, 6 | External identity and fixture provider; empty history allowed | Real API unknown |
| Real FSP integration | Port and separate DTO until API is supplied | Not implemented |
| Recurring assessments, p. 3 | Consent, scheduled worker job, freshness signal | After MVP |
| Vacancies and applications, pp. 3-4 | vacancy/application and contact grant | After core flow |
| Unreliable employers and ATS, pp. 2-3 | Verification, complaints, limits, provider adapters | Future plan |
| Open source, API, launch, pp. 5-6 | Repository, OpenAPI, Compose, instructions | Technical scaffold |
| Dozens of users, p. 6 | Worker limits, indexes, pagination | No load test |
| Documentation and validation results, pp. 5-7 | RU/EN docs, API, separate evaluation report | Docs exist; evaluation absent |
| Presentation and prototype access, pp. 5-8 | Demo environment and backup recording | Unverified |
## Quality evaluation and numerical limits
The initial matching evaluation proposes 60-100 synthetic candidates and 8-12 varied employer needs. Two people label candidate-need pairs independently and resolve disagreements. Holdout is split by need; near-duplicate profiles do not appear in both tuning and evaluation.
Compare keyword search, verified-skill baseline, and ML. Metrics are Precision@5, nDCG@5, hard-filter violations, category coverage, and share of relevant results without FSP history. Define the denominator in advance when fewer than five candidates qualify and report result-set size. A small synthetic sample does not prove quality for the real labor market.
Assessment pilot uses equivalent forms and varies their order for part of the participants. Measure grade agreement, score spread, task-level decisions, and separation between stronger and weaker groups against independent expert assessment. Synthetic weak/strong answers help debug scoring but do not replace a human pilot.
ML evaluation uses a fixed resume set with labeled fields. Measure extraction errors and invented facts, recommendation usefulness under a human rubric, schema-valid rate, latency, and failures. Record model, prompt/schema version, parameters, and date. Compare with a simple baseline and use lawfully handled, de-identified inputs.
These are proposed acceptance targets, not results: 30 concurrent users; p95 profile reads under 500 ms; baseline search under 1 second on demo data, excluding external network time. Set a separate ML budget. Quality and load runs have not been performed.
## Future critical checks
- No contact data appears before a grant in API, search, PDF, errors, or employer-facing ML explanations. Another company never receives it after acceptance.
- Candidates cannot read other users' invitations, documents, jobs, or attempts. Companies cannot read other companies' needs or search runs.
- Failure never lowers grade; first lower-level retry is permitted; concurrent requests cannot bypass the proposed 90-day limit.
- Repeated submit/accept does not create duplicate results; concurrent state transitions are consistent.
- The manual path works when ML is off; a worker recovers an expired lease; an old response cannot overwrite a newer document version.
- Empty FSP history differs from an integration error and does not exclude a candidate.
- Refinement keeps the earlier snapshot; hidden profiles disappear from older snapshots.
## Team milestones
The October 11 critical path is email -> profile/questionnaire -> grade selection -> assessment -> category -> search -> salary offer -> acceptance -> contacts. Include a demo candidate with no FSP history. If schedule slips, cut specialty count, AI depth, and decorative screens while preserving the core flow and privacy.
Team plan: October 5 - contract, data model, scaffold, and frontend foundation; October 6-9 - identity, profiles, assessments, search, invitations, UI, and ML work in parallel; October 10 - integration and fixes; October 11 - demo. October 12-16 - PDF, grade history, worker reliability, and privacy checks; October 17-22 - assessment pilot and search evaluation; October 23-26 - vacancies or recurring assessments if core work passes; October 27-29 - feature freeze, load test, backup recovery, and presentation; October 30 - final handoff.
The application host, ML resources, inference budget, SMTP/domain, and pilot participants remain undecided. Without them, the team cannot promise a public demo, model speed, or categorization quality. The current task creates a technical scaffold; product logic is separate work.
+94
View File
@@ -0,0 +1,94 @@
# Local deployment and Compose
This guide describes the checked-in configuration. Compose provides a local technical stack; it does not establish a production deployment.
## Core application
Install Docker Engine and the Docker Compose plugin. At the repository root, copy .env.example to .env, replace every placeholder password, and keep the file local. Then run:
make -C deploy config
make -C deploy up
deploy/docker/docker-compose.yml starts PostgreSQL, the Go backend, and the frontend container. Nginx in the frontend container serves static assets and proxies /api to Go. PostgreSQL, Go, and Nginx communicate on the Compose network.
The backend build context is `backend/`, so Docker applies `backend/.dockerignore`. Local tools, caches, environment files, and build outputs are excluded from that context.
The current `postgres:alpine` volume mounts at `/var/lib/postgresql`; the image stores data in a subdirectory for its major version. When the tag advances to a new major version, migrate an existing database with `pg_upgrade` or backup/restore. Updating the image alone does not convert the data.
Open http://127.0.0.1:8080. The host port binds to loopback. Nginx handles /healthz, proxies /api/ to Go, and uses the SPA fallback for other paths. The Go health endpoint is /api/v1/healthz; Go readiness checks PostgreSQL with SELECT 1. The internal backend port 9090 serves /metrics.
This Nginx configuration has no production TLS. The current bind does not expose the app directly to the public network. Remote access needs a selected TLS reverse proxy, firewall rules, and environment-specific configuration.
Useful commands:
make -C deploy config
make -C deploy up
make -C deploy logs
make -C deploy down
make -C deploy smoke
down stops containers and keeps named volumes. Do not delete database or file volumes during an ordinary stop.
## Separate ML Compose project
ML uses a separate Compose file and project. Its default host bind is 127.0.0.1:8000. Set ML_BIND_ADDRESS only after choosing a private address and preparing firewall rules. Prometheus does not scrape remote ML while ML_METRICS_TARGET is empty.
make -C deploy ml-config
make -C deploy ml-up
make -C deploy ml-logs
make -C deploy ml-down
GET /healthz checks the process. GET /readyz checks inference readiness and returns 503 while a model is unavailable. The current scaffold has no working model. Readiness does not measure model quality or inference behavior.
## Separate monitoring Compose project
Start the core project first. Monitoring joins its Docker network. Monitoring starts separately and is not required to run the app:
make -C deploy monitoring-config
make -C deploy monitoring-up
make -C deploy monitoring-logs
make -C deploy monitoring-down
Grafana is available at http://127.0.0.1:3000. Credentials come from GRAFANA_ADMIN_USER and GRAFANA_ADMIN_PASSWORD in .env. Prometheus, Loki, exporters, and backend metrics publish no host ports.
Prometheus retains metrics for 14 days with a 4 GB size limit. Loki retains logs for 7 days. Alloy discovery filters by Compose project and collects logs only from backend, frontend, and postgres. Loki labels are limited to service and environment; do not add user IDs, addresses, resume text, request bodies, or full URLs.
Frontend telemetry is not connected in the React app yet. Nginx and Alloy provide a restricted /telemetry receiver and Faro configuration, but the UI SDK and end-to-end event check are absent.
Alloy uses docker-socket-proxy for container discovery. The proxy enables only the needed Docker API sections for containers, events, ping, and version; POST is disabled. Set the socket path with DOCKER_SOCKET_PATH. Rootless Docker may use a path such as /run/user/<uid>/docker.sock; use the path on your own host instead of copying another developer's local path. The proxy restricts API sections, but access to the Docker socket remains privileged and its exact configuration needs review.
PostgreSQL creates a separate exporter role only while initializing an empty volume and when POSTGRES_EXPORTER_USER and POSTGRES_EXPORTER_PASSWORD are set. Set both before the first make -C deploy up. Changing them after the volume exists does not rerun the init script.
For remote ML scraping, set ML_METRICS_TARGET to hostname:port or IPv4:port and verify private routing and firewall rules. The standalone ML host does not yet have a separate Alloy config for forwarding its container logs to Loki.
## Services and images
Container images use moving `latest` or `alpine` tags where the upstream publishes them. Check the current Compose references when updating the stack. These tags can move; resolve and record actual image digests and an SBOM for a release. Application dependency lockfiles remain checked in separately.
| Component | Current image source | Principal upstream license |
| --- | --- | --- |
| PostgreSQL | Docker Official Image, docker-library/postgres | PostgreSQL License for the server; packaging repository is MIT |
| Prometheus | prom/prometheus | Apache-2.0 |
| Loki | grafana/loki | AGPL-3.0-only by default; see LICENSING.md exceptions |
| Grafana Alloy | grafana/alloy | Apache-2.0 by default |
| Grafana | grafana/grafana | AGPL-3.0-only by default |
| Node exporter | prometheus/node_exporter | Apache-2.0 |
| PostgreSQL exporter | prometheus-community/postgres_exporter | Apache-2.0 |
| Docker socket proxy | Tecnativa/docker-socket-proxy | Apache-2.0 |
| BusyBox | busybox | GPL-2.0-only |
Upstream references: [PostgreSQL image](https://github.com/docker-library/postgres), [Prometheus](https://github.com/prometheus/prometheus/blob/main/LICENSE), [Loki license details](https://github.com/grafana/loki/blob/main/LICENSING.md), [Alloy license details](https://github.com/grafana/alloy/blob/main/LICENSING.md), [Grafana license details](https://github.com/grafana/grafana/blob/main/LICENSING.md), [node_exporter](https://github.com/prometheus/node_exporter/blob/master/LICENSE), [postgres_exporter](https://github.com/prometheus-community/postgres_exporter/blob/master/LICENSE), [socket proxy](https://github.com/Tecnativa/docker-socket-proxy), [BusyBox license](https://busybox.net/license.html).
These entries name the principal upstream project's license; they are not a complete inventory of every file in an image. Base OS packages and bundled dependencies may have separate terms. Before redistribution, inspect the exact image tag or digest, its notices, and an SBOM. This repository has no project-wide license.
The backend builds with Go 1.26.8; its runtime image is selected in backend/Dockerfile. Frontend and ML base images are selected in their Dockerfiles. Upstream sources include [Docker Official Images](https://github.com/docker-library), [Distroless](https://github.com/GoogleContainerTools/distroless), and [NGINX unprivileged images](https://github.com/nginxinc/docker-nginx-unprivileged); inspect exact tags and layers before distribution.
## Observability configuration
Prometheus scrapes backend /metrics on port 9090, PostgreSQL exporter, node exporter, itself, and the optional ML target. Loki uses a single-binary filesystem store with 168-hour retention. Grafana provisions Prometheus and Loki datasources from observability/grafana/provisioning/.
The three checked-in dashboard JSON files are maintained as project dashboards: Go runtime, PostgreSQL, and Linux system. They were not copied from Grafana dashboard IDs. No external dashboard provenance or license is claimed for them.
The local monitoring stack is a single-node development/demo setup and provides no HA. Compose validation does not establish production retention, off-host backups, public access control, alert delivery, or core application behavior.
Workflow files exist in .github/workflows/. Their presence does not mean they have run on GitHub. See the testing guide for the difference between configuration validation, an infrastructure smoke, and product-flow tests.
+90
View File
@@ -0,0 +1,90 @@
# Development
This guide describes the current technical scaffold and the commands declared in the repository. Product workflows remain planned; see [ARCHITECTURE.md](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.
## 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 `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](TESTING.md) for validation scope and [DEPLOY.md](DEPLOY.md) for the local stack.
## Layout
| 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 |
| .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.
## Code boundaries
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, cache, or WebSocket without a concrete need and a check of the pinned version's behavior.
The frontend is a React/Vite SPA. Keep FSD boundaries as product screens are added. 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.
## 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).
+71
View File
@@ -0,0 +1,71 @@
# Checks and quality evaluation
Routine checks prove individual code properties. They do not establish ranking accuracy, grade validity, production latency, or complete product readiness.
## Commands
Use the root Make targets:
make test
make check
make verify
make docs-check
make test runs backend, frontend, and ML tests. make check also runs API contract, formatting, lint, type, build, Compose, observability, and documentation checks. make verify sequentially generates contracts, checks generated drift, runs root check, API toolchain/backend race and integration checks, and then starts an isolated deployment smoke. It uses Docker.
Useful focused commands:
| Command | Coverage |
| --- | --- |
| make -C api check | Schema merge, bundles, OpenAPI lint, merge-script tests |
| make -C backend test | Go unit suite with race detector |
| make -C backend test-fast | Faster Go tests without race instrumentation |
| make -C backend test-int | Go integration tests with Testcontainers/PostgreSQL |
| make -C frontend check | Prettier, ESLint, Stylelint, TypeScript, Vitest, FSD boundaries, build |
| make -C ml check | Ruff, mypy, pytest, and wheel build |
| make -C ml check-generated | Pydantic models match the ML bundle without rewriting files |
| make -C deploy config | Render Compose configurations without starting them |
| make -C deploy smoke | Isolated technical smoke of service health routes |
| make -C observability check | Validate Prometheus, Loki, Alloy, and dashboard JSON |
make -C deploy test-e2e is reserved and currently exits nonzero with a message that the business-flow suite is deferred. Do not count this as a passing E2E run.
make -C ml check-generated uses datamodel-code-generator --check: a mismatch fails the check and leaves the models file unchanged. Prepare the bundle with make -C api bundle before checking; use make -C ml generate to update Python models. Generated models do not establish inference functionality or support for every OpenAPI 3.2 feature.
## Current scaffold coverage
Existing checks cover health/readiness, backend PostgreSQL connectivity, metrics, the API client, ML schemas, and current endpoint availability. There are no accounts, assessments, search results, invitations, file workflows, or real model inference to validate as product behavior.
API verification checks the OpenAPI subset exercised by pinned tools, fixtures, and contracts that actually ran. Its result applies only to those inputs. CI YAML in the repository does not mean a workflow has run on GitHub.
Deployment smoke checks infrastructure routes and Compose startup. It does not check contact release, protection of product data, ML robustness, ranking quality, PDF export, or the two-role flow. A separate monitoring check does not verify the core database or end-to-end telemetry from the application.
## Future software validation
Go unit tests should exercise domain/usecase rules with explicit inputs, results, and errors. Integration tests should use a real PostgreSQL at the same major version, apply goose migrations, and exercise sqlc, constraints, transactions, rollback, and concurrent transitions. The HTTP path should use chi, middleware, usecases, and the database; replace external ML with a controlled HTTP fake and email with a test adapter.
Isolate test data by database/schema or run scenarios with a sequential reset. Do not run parallel cases against shared truncation. Start containers per suite, use dynamic ports, and clean them up. Integration CI must not silently skip tests when its container runtime is unavailable.
Validate contract changes with bundle, lint, codegen for every Go, TypeScript, and Python consumer, and generated drift, including new untracked files. Frontend component tests do not replace browser tests of the complete flow. After product implementation, add Playwright for both roles and a synthetic candidate without FSP history.
Critical future checks:
- Before offer acceptance, another company sees no contacts through API, search, PDF, errors, or ML explanations.
- A candidate cannot access another user's invitations, files, jobs, or attempts; a company cannot access another company's needs or search runs.
- Assessment failure does not lower grade; the first lower-level retry is allowed; concurrent requests cannot bypass cooldown.
- Repeated submission or acceptance is idempotent; concurrent status transitions are serialized.
- The manual path works with ML off; expired worker leases recover; stale results do not overwrite a newer profile.
- Missing FSP history differs from an integration error and does not exclude the candidate.
- Search refinement preserves an earlier snapshot; a withdrawn profile disappears from it.
## Future quality evaluation
Evaluate ranking separately from functional tests. Initial plan: 60-100 synthetic candidates, 8-12 needs, two independent labelers, disagreement review, and a holdout split by need. Near-duplicate profiles must not appear in both tuning and holdout.
Compare keyword search, verified skills, and ML. Measure Precision@5, nDCG@5, hard-filter violations, category coverage, and the share of relevant results without FSP history. Define the denominator before the run when fewer than five candidates qualify and report result-set size. Synthetic data does not prove quality for the real market.
Assessment evaluation needs a human pilot and independent expert skill ratings. Compare equivalent forms, vary their order, and measure grade agreement, score spread, task-level decisions, and group separation. Synthetic answers help debug a rubric; they do not replace a pilot.
ML evaluation records a fixed document set and field labels, extraction precision, invented facts, recommendation usefulness, schema-valid rate, latency, and failures. Record model, prompt/schema version, parameters, and date. Compare against a simple baseline and use lawfully handled de-identified documents.
Proposed targets are 30 concurrent users, p95 profile reads under 500 ms, and baseline search under one second on demo data excluding external network time. These are future acceptance criteria; no results are available. Set a separate ML latency budget.
+294
View File
@@ -0,0 +1,294 @@
# Архитектура Lincodex
Документ описывает целевую платформу и отделяет ее от технического каркаса, который уже есть в репозитории. Основание требований - файл "ФСП спец. трек ТЗ.pdf" в корне; номера страниц в матрице относятся к печатной нумерации без обложки. Сроки 11 и 30 октября 2026 года переданы командой.
## Что работает сейчас
Репозиторий содержит Go HTTP-сервис с проверкой PostgreSQL, минимальную React-страницу состояния, отдельный Python ML-сервис с health/readiness маршрутами, два OpenAPI-контракта, codegen, Compose и конфигурацию мониторинга. Публичный health endpoint API находится под /api/v1/healthz. /healthz используется для проверки веб-контейнера, /readyz - для готовности ML; ML отвечает 503 на readiness, пока inference не готов. Метрики Go доступны по стандартному /metrics на внутреннем порту.
Это технический каркас. В нем нет регистрации, ролей, профилей, тестов, грейдов, поиска, приглашений, загрузки/анализа резюме, PDF или интеграции с ФСП. ML не возвращает вымышленные результаты. Проверки доступности и технический smoke не подтверждают бизнес-сценарий.
Подробности запуска, дерева исходников и проверки собраны в [руководстве разработки](DEVELOPMENT.md), [руководстве по развертыванию](DEPLOY.md) и [руководстве по проверкам](TESTING.md).
## Целевая система
Один репозиторий, модульный Go backend с Clean Architecture, React SPA на Vite с FSD и отдельный ML HTTP-сервис. Целевой Go-процесс объединяет HTTP API и worker; PostgreSQL хранит бизнес-данные и задания. Резюме и выданные PDF хранятся в закрытом файловом хранилище. Начальная среда - Docker Compose на одном узле приложения и отдельная среда ML.
Go владеет авторизацией, подтвержденными категориями, приглашениями, правами на контакты и итоговой выдачей. ML предлагает поля резюме, помогает разобрать потребность работодателя и участвует в экспериментах смыслового поиска. Недоступность модели не должна блокировать ручное заполнение профиля, тестирование, поиск по подтвержденным полям и приглашения.
Общий процесс API и worker упрощает демонстрационный деплой, но дает им общий lifecycle, лимиты памяти и registry метрик. Для независимого масштабирования worker можно выделить в отдельный процесс, сохранив usecase и порты. Это план, а не существующий worker.
ТЗ дает подбору 35% оценки, тестированию и категоризации 25%, технической проработке 7%. К 11 октября заявлен сквозной прототип, к 30 октября - финальная сдача. Техническая проработка не заменяет продуктовый сценарий.
## Контракты и генерация
Каталоги контрактов симметричны: api/core/ содержит публичный контракт браузер-Go, api/ml/ - внутренний контракт Go-ML. Общие Makefile, package.json и Redocly config находятся в api/; Python-скрипты сборки лежат в корневом scripts/. Обе спеки состоят из небольших исходных YAML-файлов, которые собираются в bundles.
Публичный Go handler генерируется ogen из backend/codegen/ogen.yml и монтируется в chi. Orval независимо генерирует TypeScript client, TanStack Query hooks, Zod schemas и MSW handlers. Go-клиент ML API генерируется по backend/codegen/ogen-ml.yml в backend/internal/adapter/secondary/ml/api/. Python-модели Pydantic v2 генерируются datamodel-code-generator из того же ML bundle в ml/src/lincodex_ml/api/models.py; их используют health/readiness handlers. Настройки Python-генератора находятся в ml/codegen/pyproject.toml, зависимости - в ml/pyproject.toml. Backend конфигурация sqlc находится в backend/codegen/sqlc.yml, generated SQL adapter - в backend/internal/adapter/secondary/postgres/sqlc/. Frontend config - в frontend/codegen/orval.config.ts. Всего три каталога codegen: backend/codegen/, frontend/codegen/ и ml/codegen/; конфигурация принадлежит сервису, который использует сгенерированный код.
Целевая версия OpenAPI - 3.2.0. Проверяется только используемое подмножество: bundling/lint, ogen, chi adapter, runtime путь API, Orval, Python-модели Pydantic и документация. Проверка одной fixture или чтение версии parser не доказывает поддержку всех возможностей OpenAPI 3.2.0.
В публичном API префикс /api/v1 применяется один раз. Служебный /metrics остается отдельным внутренним маршрутом. Health операции именуются с суффиксом z: healthz и readyz. DTO генераторов не заменяют проверку владельца, членства в компании, согласия или допустимости перехода бизнес-состояния.
Генерация идет из исходных контрактов. Core и ML bundles создаются отдельно; затем Go, TypeScript и Python потребители обновляются из своих Make targets. Изменения контракта включают regeneration и проверку generated drift для всех потребителей. Сгенерированные файлы не редактируются вручную.
## Границы сервисов и данных
Целевая схема backend:
- primary adapters принимают HTTP и передают команды в inbound ports;
- usecases выполняют прикладные сценарии и зависят от domain и портов;
- secondary adapters реализуют хранилище, ML, почту и файловые операции;
- bootstrap собирает реализации, запускает процесс и управляет остановкой;
- бизнес-правила остаются в domain/usecase, а не в chi handler, worker, SQL или ML.
Общие настройки Go принадлежат backend/config/ вне internal. Сейчас logkit 0.6.0 и httpkit 0.7.0 из wahrwelt-kit используются для технических функций. Метрики реализованы ограниченным собственным collector/middleware, а pgxpool state не должен блокировать startup. pgkit и httpkit/metrics пока не используются; технические библиотеки не владеют бизнес-логикой. Не добавлять невыбранные JWT, cache или WebSocket зависимости ради предполагаемых будущих сценариев.
PostgreSQL с pgx, sqlc и goose остается основной базой. SQL написан вручную, sqlc генерирует типизированный адаптер. goose управляет версионными миграциями. wire в bootstrap - compile-time сборка зависимостей; во время выполнения DI-контейнера нет. Worker и API используют один пул БД в целевом однопроцессном варианте.
Для MVP не вводятся Redis, отдельная vector DB, брокер, Kubernetes или микросервисы поиска. Начальный поиск использует PostgreSQL фильтры/full-text по разрешенной проекции. pgvector можно рассмотреть после eval, если embeddings дают подтвержденную пользу.
## Структура репозитория и назначение пакетов
```text
api/core/ публичный контракт браузер-Go и bundle
api/ml/ внутренний контракт Go-ML и bundle
backend/cmd/app/main.go вызывает bootstrap.Run и обрабатывает ошибку
backend/config/ общая конфигурация runtime
backend/internal/domain/ продуктовые правила, планируемые модули
backend/internal/usecase/ операции приложения и orchestration
backend/internal/port/ inbound и outbound интерфейсы
backend/internal/adapter/ primary HTTP и secondary интеграции
backend/internal/bootstrap/ wiring зависимостей и lifecycle процесса
backend/db/ миграции и SQL-запросы
backend/codegen/ конфигурация ogen для сервера и ML-клиента, sqlc
frontend/src/ app, pages, widgets, features, entities, shared
frontend/codegen/ конфигурация Orval
ml/src/ FastAPI сервис и operational checks
ml/codegen/ настройки Python datamodel-code-generator
deploy/ Compose, Nginx и технические smoke checks
observability/ Prometheus, Loki, Alloy и Grafana provisioning
scripts/ общие инструменты для документации и схем
docs/ руководства на русском и английском
```
```text
backend/
cmd/app/main.go вызывает bootstrap.Run и обрабатывает ошибку
config/ общая конфигурация runtime
internal/
domain/ плоский пакет; пока только .gitkeep
usecase/health/ operational readiness usecase
port/inbound/ inbound граница readiness
port/outbound/ outbound граница проверки БД
adapter/primary/http/
api/ generated ogen handler
middleware/ метрики запросов
v1/ написанный вручную health endpoint
router.go сборка chi router
adapter/secondary/
ml/api/ generated client из backend/codegen/ogen-ml.yml
postgres/sqlc/ generated SQL adapter
prometheus/ ограниченные Go/process и request metrics
bootstrap/ конфигурация, wiring, lifecycle, shutdown
db/ миграции и SQL-запросы; продуктовой схемы пока нет
codegen/ конфигурация ogen и sqlc
pkg/ резерв для обоснованных общих технических helpers
```
Доменные типы лежат непосредственно в `backend/internal/domain/`: `user.go`, `candidate.go` и другие файлы по мере определения моделей. Вложенных каталогов по сущностям или модулям здесь нет. Пока типы не определены, каталог содержит только `.gitkeep`.
`domain/`, продуктовые `usecase/`, адаптеры файлов, почты и 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. Аккаунты, резюме, оценивание, приглашения, worker jobs, storage, mail и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей.
`backend/pkg/` зарезервирован для небольших технических пакетов с оправданной общей границей, а не для продуктовых usecase или domain types. Возможные пакеты на будущее: `emailtemplate`, `mailer` и тестовые helpers; `storagepath` нужен только если выбран локальный file storage. Поведение, специфичное для этого сервиса, остается внутри `internal/`.
`api/` хранит контракты и инструменты и не является runtime hop в пути запроса. `api/core/` и `api/ml/` владеют исходным OpenAPI, fragments маршрутов и компонентов, а также коммитируемыми bundles. Схемы объединяет корневой `scripts/`. Сгенерированный Go-код лежит у потребителя: публичный handler - в `backend/internal/adapter/primary/http/api/`, внутренний ML client - в `backend/internal/adapter/secondary/ml/api/`, sqlc output - в `backend/internal/adapter/secondary/postgres/sqlc/`. Первый пакет монтируется в chi; два последних реализуют outbound adapters. `backend/cmd/app/main.go` остается точкой входа, а bootstrap отвечает за wiring и graceful shutdown.
## Целевые модули
| Модуль | Ответственность | Основные данные |
| --- | --- | --- |
| identity | Email, подтверждение, сессии и роли | users, email_tokens, sessions, external_identities |
| candidate | Профиль, контакты, согласия и видимость | profiles, contacts, skills, consents, resume_versions |
| company | Компания и ее сотрудники | companies, company_members |
| assessment | Опрос, задания, попытки, оценка и грейд | questionnaires, task_templates, attempts, answers, grade_history |
| matching | Потребности, фильтры, ранжирование и версии подборок | hiring_needs, search_runs, search_items |
| invitation | Предложение и право раскрыть контакты | invitations, invitation_events, contact_grants |
| document | Файлы, разбор резюме и стандартизированный PDF | files, analysis_results, document_jobs |
| achievement | Связь с ФСП и источник достижений | fsp_links, achievements, sync_runs |
| vacancy, позже | Вакансии и добровольные отклики | vacancies, applications |
Одна PostgreSQL используется на MVP. Реляционные связи и ограничения остаются явными. JSONB допустим для версионированных ответов опроса и ML, но не заменяет модель. Навыки и специализации нормализованы. Большие PDF в PostgreSQL не хранятся. Категория включает специализацию и грейд, подтвержденный тестом; отрасль приходит из опроса. Заявленный и подтвержденный грейды разделены.
Достижение хранит источник, внешний ID, дату события, дату получения и достоверность. Отсутствие истории ФСП, отсутствие связи и временная ошибка синхронизации - разные состояния. ML не получает прямой доступ к бизнес-БД.
## Сквозной пользовательский путь
Целевой сценарий кандидата: подтверждение email -> профиль и согласия -> опрос -> выбор ожидаемого грейда -> тест -> подтвержденная категория -> публикация профиля.
Целевой сценарий работодателя: подтверждение email -> профиль компании -> описание потребности -> выбор или подтверждение извлеченных навыков -> фильтры и объяснимая подборка -> предложение с диапазоном зарплаты -> принятие кандидатом -> контактный доступ только этой компании.
Приглашение содержит работодателя, описание, способ связи, обе границы зарплаты и валюту RUB. 0 < salary_from <= salary_to; период и налоги показываются явно. vacancy_id необязателен. Базовые переходы: sent -> viewed -> accepted или declined; принять можно также из sent. withdraw и expire - дополнительные состояния. Повторные операции идемпотентны, конкурирующие переходы защищены транзакцией и текущей версией.
contact_grant относится к паре кандидат-компания и создается после принятого приглашения или собственного отклика кандидата. Сервер проверяет пользователя, компанию, grant и актуальную видимость при каждом чтении. До grant работодатель не получает контакты, оригинальный PDF, мессенджеры или контактные фрагменты из резюме и ML.
Собственный профиль, карточка поиска и разрешенные контакты - разные DTO. PDF владельца полный. Экспорт для компании создается из разрешенного представления с повторной проверкой прав. Публичный постоянный URL не заменяет авторизованную выдачу. Отзыв согласия исключает профиль из новой и сохраненной выдачи, но не может отозвать данные, уже полученные другой стороной.
## Оценивание и подтверждение грейда
Тесты строятся из проверенных семейств задач с blueprint по специализации и уровню. Blueprint фиксирует компетенции, сложность, число задач и веса. Варианты меняют условие и входные данные, сохраняя проверяемый навык; простая перестановка вариантов ответа недостаточна. Для демонстрации предлагаются Go backend и React frontend junior/middle; остальные направления добавляются с содержательным банком заданий.
До попытки фиксируются seed, версия и условия. Ответы и эталоны остаются на сервере. В MVP предпочтительны автоматически проверяемые форматы без запуска кода кандидата. Свободный ответ может быть дополнительным сигналом; оценка LLM не является единственным основанием грейда. Начальные пороги утверждаются после пилота, а средний балл не скрывает провал критического раздела.
Правила состояния грейда:
- до первого успешного теста статус unverified, заявленный грейд не дает подтвержденную категорию;
- неудача не снижает подтвержденный грейд;
- после первой неудачи кандидат сам выбирает тест более низкого уровня; система не назначает его автоматически;
- изменение грейда после успешной квалификации ограничено, исходный ориентир - 90 дней;
- первое понижение после неудачи не блокируется этим интервалом; повтор на том же уровне может иметь отдельный cooldown, исходный ориентир - 24 часа;
- уверенный результат может предложить тест выше; история изменений доступна.
Пороги и интервалы - проектные решения для пилота, не проверенная психометрическая модель. Ротация задач и лимиты попыток уменьшают пользу утечки, но не доказывают защиту от подсказок или LLM. Уровни сложности нужно измерить.
## Подбор и объяснение
До ранжирования Go применяет жесткие фильтры: опубликованный профиль, специализация, подтвержденный грейд, обязательные навыки и другие выбранные требования. Хорошее резюме или достижение не компенсирует отсутствующий обязательный критерий. Отсутствие подтверждения навыка нужно отличать от подтвержденного отсутствия.
Начальная baseline формула после фильтров:
score = 0.50 * skill_fit
+ 0.40 * assessment_score
+ 0.10 * fsp_evidence
Все компоненты лежат в диапазоне 0..1. skill_fit - взвешенное покрытие подтвержденных навыков. assessment_score - результат по соответствующим разделам теста. fsp_evidence - небольшой бонус за релевантные проверенные достижения. При пустом наборе навыков применяется заранее определенное нейтральное значение, без деления на ноль. Равные значения сортируются стабильным tie-break по ID, а не по персональным признакам.
Нет истории ФСП - нулевой бонус, но кандидат остается в выдаче. Синтетические достижения помечаются и влияют только на демонстрационный набор. Результат включает score_components, reason_codes, подтверждающие факты и пробелы. Например, кандидат может иметь подтвержденный Middle и покрыть 4 из 5 навыков, но не пройдет фильтр, требующий все пять подтверждений.
Формула - исходная baseline, не оптимальная или измеренная модель. До финала планируется сравнить ключевые слова, baseline подтвержденных навыков и ML-вариант. Семантический сигнал добавляется только после эксперимента и не становится вероятностью успешного найма.
Каждая подборка сохраняется как search_run с компанией, исходной потребностью, фильтрами, версией ранжирования и родительской версией. Уточнение создает новый снимок. search_items фиксирует позиции, score и версии профилей без контактов. Старый снимок не сохраняет доступ: скрытые/удаленные профили из него исключаются, устаревший расчет помечается, срок хранения ограничен.
## ML, документы и фоновые задания
Целевые ML операции: анализ резюме, разбор потребности, а после baseline - embeddings и ограниченный rerank. Go передает только разрешенные данные и короткий shortlist. Ответы ограничены известными ID, проверяются по схеме и версии. Неудача ML включает baseline. Модель не назначает категории и не раскрывает контакты.
План импорта PDF: ограничить размер, число страниц и частоту; проверить тип и владельца; сохранить версию исходника; в одной транзакции создать job; извлечь текст в изолированной среде с лимитами; замаскировать контакты; запросить структурированный результат; проверить его размер и версии; показать кандидату предложенные поля на подтверждение. Скан без текстового слоя сообщает об ошибке/ручном вводе; OCR - отдельное расширение. Полный текст не пишется в логи или traces.
Текст резюме считается недоверенными данными, а не инструкциями для инструментов. ML не переходит по произвольным ссылкам, не запускает команды и не подтверждает истинность опыта. Результат анализа связывает каждое предложение с основанием и ограничениями.
Стандартизированный PDF обязателен в продуктовой версии, даже при ручном вводе. PDFRenderer получает структурированный профиль; предполагаемый подход - контролируемый HTML и изолированный headless Chromium с кириллическими шрифтами, без внешних сетевых загрузок и пользовательского HTML.
Будущие jobs имеют состояния queued, running, succeeded, failed, cancelled, лимит попыток, available_at, lease/heartbeat и безопасный код ошибки. Взятие атомарно. Истекший lease разрешает повтор; уникальный ключ операции, версия документа и lease token не дают старому worker перезаписать новый результат. Вычисление может повториться, бизнес-эффект - нет. Retry ограничен и использует backoff.
Для долгой обработки API возвращает 202 и job ID, интерфейс опрашивает статус с увеличивающимся интервалом и прекращает опрос после завершения или ухода со страницы. Браузер не обращается к ML напрямую. Обычные тесты не загружают модель и не требуют GPU. Модель, лицензия, бюджет inference и реальные сроки отклика пока не выбраны.
## Идентификация, ФСП и приватность
Целевой первый способ входа - email/password, подтверждение email и серверная сессия в PostgreSQL. Cookie: Secure, HttpOnly, SameSite; изменяющие запросы защищены от CSRF. Пароли хешируются подходящим KDF, токены случайные с ограниченным сроком, в БД хранится их хеш. Подтверждение email требуется перед публикацией кандидата или отправкой приглашения.
Будущая связь ФСП ID - external identity с проверкой у провайдера; ручного ввода ID или совпадения email недостаточно для объединения аккаунтов. В ТЗ не предоставлен реальный API ФСП, поэтому сначала используется fixture provider и собственный DTO. Если организаторы предоставят Keycloak/OIDC, добавляются Authorization Code + PKCE и проверки issuer, state, nonce, audience, redirect URI; роли и контактные grants остаются в Lincodex.
ТЗ ссылается на 152-ФЗ. Система должна иметь раздельные согласия на обработку и публикацию, отзыв, контроль передачи документов ML и сроки хранения/удаления. Описание архитектуры не является подтверждением юридического соответствия. До работы с настоящими данными нужны согласованные условия хранения и обработки; демонстрация использует синтетические профили.
## Frontend
Целевая FSD-структура: app композирует router/providers, pages задают экраны, widgets - крупные блоки, features - действия, entities - понятия продукта, shared - API, UI и утилиты. Импорты направлены вниз; generated DTO не импортируют product entities. TanStack Query владеет server state; формы владеют черновиками; фильтры и ID поиска живут в URL. Zustand добавляется только при конкретной потребности.
Общий API wrapper задает URL, cookie, AbortSignal и разбор ошибок. MSW используется в dev/test, но не подменяет реальные интеграционные проверки. Logout/account switch очищает приватный query cache. У страниц должны быть состояния загрузки, пустой результат, ошибка, повтор и запрет доступа.
Для продуктовых экранов выбраны React Router, TanStack Query, React Hook Form и Zod; стили - CSS Modules и CSS variables. Radix UI можно добавить для доступных сложных меню и диалогов. Next.js нужен только при подтвержденной потребности в SSR или индексируемом каталоге; Bun не заменяет выбранную связку стабильного Node и pnpm. Vite собирает статику, которую обслуживает Nginx; production Node process не нужен. Это целевой UI стек, а не перечень уже подключенных бизнес-библиотек.
## Будущее расширение
PostgreSQL jobs остаются достаточными на MVP. При необходимости брокера сначала проектируются outbox, идемпотентность, порядок, retry и дедупликация. RabbitMQ/NATS требуют независимых consumers/маршрутизации; Kafka - долговечного потока с несколькими потребителями и измеримым объемом. Отдельный search, assessment или notification сервис выделяется только при собственном масштабе или lifecycle. gRPC нужен при нескольких внутренних сервисах и конкретной пользе protobuf/streaming; он не заменяет OpenAPI для браузера.
k3s не входит в критический путь. Его можно рассмотреть при готовом обслуживаемом кластере или измеренной потребности в нескольких узлах. Один узел k3s не дает HA. Переход требует probes/resources, секретов, storage backup, ingress и проверенных NetworkPolicy.
После обязательного сценария можно добавлять вакансии и добровольные отклики, регулярные задания, жалобы и проверки работодателей, ATS adapters, более глубокий matching. Верификация работодателя и ATS интеграции пока не реализованы и не обязательны для первого прототипа.
## API первого продуктового среза
| Группа | Первый целевой набор |
| --- | --- |
| identity | register, verify/resend email, login, logout, me; password reset можно отложить до финала |
| candidate | свой профиль, опрос, согласия, публикация и скрытие |
| documents | загрузка резюме, запрос анализа, чтение job, подтверждение предлагаемых полей, получение PDF |
| assessment | доступные тесты, начало попытки, сохранение ответов, submit, история и eligibility |
| company | профиль компании и принадлежность пользователя |
| matching | потребность, подтверждение извлеченных полей, создание, уточнение и чтение подборки |
| invitation | отправка, списки, просмотр, принятие/отказ, отмена и доступ к контактам с grant |
| achievement | состояние связи FSP и история достижений; fixture provider для демонстрации |
Примеры стабильных операций: `POST /api/v1/searches`, `POST /api/v1/searches/{id}/refinements`, `POST /api/v1/candidates/{id}/invitations`, `POST /api/v1/invitations/{id}/accept`. Это целевые примеры, они пока не реализованы. Все бизнес-операции, ответы и ошибки должны входить в OpenAPI и иметь стабильные `operationId`.
Правила контракта: UUID для идентификаторов, UTC date-time, явные enums, целые рубли для MVP, ограниченная cursor pagination. Различать null и отсутствующее поле. Ошибка содержит стабильный `code`, безопасное сообщение, опциональные field errors и request ID. Idempotency keys нужны для создания invitation, запуска анализа и отправки assessment; ключ ограничен actor и операцией, повтор с другим телом отклоняется. Проверять доступ для каждого object ID, job, search run и PDF. Контакты не включаются в общие ошибки и публичные примеры.
## Метрики, телеметрия и alerts
Сейчас Go экспортирует стандартные Go/process метрики, `lincodex_http_requests_total` с ограниченными labels `method`, шаблоном маршрута `route` и `status`, а также `lincodex_http_request_duration_seconds`. В labels нельзя помещать user/candidate/request IDs, полный URL, адреса или содержимое резюме. `/metrics` слушает на внутреннем listener и не входит в `/api/v1`. JSON dashboards Go runtime, PostgreSQL и Linux поддерживаются в проекте; это не импортированные Grafana dashboard IDs. Метрики очереди, inference и бизнес-событий пока не реализованы.
План наблюдаемости включает метрики jobs: очередь, возраст старейшего готового задания, время ожидания и выполнения, retries и окончательные ошибки; состояние pgxpool должно собираться внутри Go ограниченными неблокирующими запросами. Nginx `stub_status` не дает latency по HTTP статусам; access logs могут измерять `request_time` и `upstream_response_time`. cAdvisor можно добавить при поддержке выбранного runtime. Redis exporter и DCGM exporter нужны только если появятся Redis или локальная NVIDIA модель.
План браузерного пути: Faro Web SDK -> same-origin `/telemetry` -> Alloy `faro.receiver` -> Loki. React SDK пока не подключен. Собирать очищенные Web Vitals, JS errors, release и нормализованный маршрут; исключить console logs, формы, текст резюме и session replay. Удалять query string, fragment и ID из URL. Ограничить размер, частоту и origin приемника. Request/trace IDs остаются полями логов, не labels; хранение spans требует отдельного backend, например Tempo, и пока не поддерживается.
Планируемые alerts: недоступный target, высокая доля 5xx при достаточном числе запросов, превышение latency budget, старые или окончательно упавшие jobs, заполнение диска, ошибки ML и отброшенные логи. При низком трафике нужны окно и минимальное число событий, иначе процентили нестабильны. Настроить поведение `No Data` и ошибки datasource. Стек на том же хосте не может надежно сообщить о его остановке; для этого нужен внешний health check. Compose и dashboard smoke не проверяют доставку alerts. Правила и канал уведомления следует описывать как внедренные только после отдельной проверки.
## Покрытие требований ТЗ
| Требование ТЗ | Целевое решение | Состояние |
| --- | --- | --- |
| Два кабинета, email confirmation, с. 3-4 | identity, роли, компания и проверки доступа | Не реализовано |
| Резюме вручную или PDF, с. 3 | Ручной профиль обязателен; PDF и ML импорт расширяют его | Не реализовано |
| Стандартизированный PDF, с. 3 | PDFRenderer по структурированному профилю, кириллица и права доступа | Не реализовано |
| Опрос, грейд, тест и категория, с. 1-3 | assessment, варианты задач, grade history | Не реализовано |
| Сопоставимость тестов и защита от утечек, с. 1-2 | Семейства, blueprint, рубрики, ротация и пилот | Только план |
| Не понижать грейд при провале, частота изменений, с. 2-3 | verified/claimed, retry правила, cooldown и eligibility | Только план |
| Поиск и объяснение, с. 3-4 | Жесткие фильтры, matching, evidence и score components | Не реализовано |
| Уточнение поиска без потери старой выдачи, с. 4 | Версионные search_run и серверные снимки | Только план |
| Приглашение без вакансии, с. 3 | Необязательный vacancy_id | Не реализовано |
| Зарплата от-до в RUB, компания и связь, с. 4 | Обязательные границы зарплаты и явный формат периода/налогов | Не реализовано |
| Статусы для обеих сторон, с. 4 | State machine и журнал событий | Не реализовано |
| Контакты после принятия/отклика, с. 3-4 | contact_grant, отдельные DTO и проверка доступа к файлу | Не реализовано |
| Приватность и доступ к своим данным, с. 3, 6 | Согласия, object/company authorization, проверки cache и старых подборок | Требование, реализация отсутствует |
| ФСП ID и отсутствие истории, с. 2, 6 | external identity и fixture provider; пустая история допустима | Реальный API неизвестен |
| Интеграция с ФСП | Порт и отдельный DTO до получения схемы API | Не реализовано |
| Регулярные задания, с. 3 | Согласие, периодическое задание worker и сигнал свежести | После MVP |
| Вакансии и самостоятельные отклики, с. 3-4 | vacancy/application и contact grant | После основного пути |
| Недобросовестные работодатели и ATS, с. 2-3 | Статусы проверки, жалобы, лимиты; адаптеры конкретных ATS | План расширения |
| Open source, API и запуск, с. 5-6 | Репозиторий, OpenAPI, Compose и инструкции | Технический scaffold |
| Десятки пользователей, с. 6 | Worker limits, индексы и пагинация | Нагрузочный тест не выполнен |
| Документация и результаты валидации, с. 5-7 | RU/EN docs, API и отдельный eval report | Документация есть; eval отсутствует |
| Презентация и доступ к прототипу, с. 5-8 | Стенд, сценарий демонстрации и резервная запись | Не проверено |
## Оценка качества и численные ограничения
Для подбора планировалось 60-100 синтетических кандидатов и 8-12 описаний потребности с разными стеками, грейдами и ограничениями. Два человека независимо размечают пары, спорные случаи обсуждаются. Holdout делится по потребности, близкие копии одного профиля не попадают одновременно в настройку и проверку.
Сравнить keyword search, baseline подтвержденных навыков и ML вариант. Метрики: Precision@5, nDCG@5, число нарушений жестких фильтров, покрытие категорий и доля кандидатов без ФСП в релевантных результатах. При выдаче менее пяти кандидатов заранее определить знаменатель и всегда показывать размер выборки. Малый синтетический набор не доказывает качество на реальном рынке.
Пилот тестов сравнивает эквивалентные формы и меняет порядок их прохождения у части участников. Измеряются согласованность грейда, разброс баллов, доля решений по заданиям и разделение более сильной/слабой группы относительно независимой экспертной оценки. Синтетические ответы подходят для отладки, но не заменяют пилот с людьми.
ML eval фиксирует размеченные поля резюме, ошибочные/выдуманные факты, полезность рекомендаций по человеческой рубрике, schema-valid rate, задержку и ошибки. Записываются модель, prompt/schema version, параметры и дата. Результат сравнивается с простым baseline; входные документы используются правомерно и обезличенно.
Проектные ориентиры, а не результаты: 30 одновременных пользователей; p95 чтения профиля до 500 мс и baseline-поиска до 1 секунды на демонстрационном объеме без внешней сети. Для ML задается отдельный budget. Нагрузочные прогоны и показатели качества пока не выполнены.
## Критические будущие проверки
- Контакты отсутствуют до grant в API, поиске, PDF, ошибках и ML объяснении; другая компания не получает их после принятия.
- Кандидат не читает чужие приглашения, документы, jobs и попытки; компания не читает чужие потребности и подборки.
- Провал не понижает грейд; первый переход на уровень ниже разрешен; 90-дневное ограничение не обходится конкурентными запросами.
- Повтор submit/accept не создает второй результат; конкурентные переходы статусов согласованы.
- Отключенный ML оставляет основной ручной путь; worker восстанавливает истекший lease; старый ответ не перезаписывает новую версию.
- Пустая история ФСП отличается от ошибки; отсутствие истории не исключает кандидата.
- Уточнение сохраняет предыдущий снимок; скрытый профиль исчезает и из старого снимка.
## План команды и сроки
Критический путь к 11 октября: email -> профиль/опрос -> выбранный грейд -> тест -> категория -> поиск -> предложение с зарплатой -> принятие -> контакты. Нужен демонстрационный кандидат без ФСП. Если времени не хватает, сокращается число специализаций, глубина AI и декоративные экраны; основной путь и приватность сохраняются.
План дат команды: 5 октября - контракт, модель данных, scaffold и фронтенд каркас; 6-9 октября - identity, профили, тест, поиск и приглашения с параллельной работой над UI/ML; 10 октября - интеграция и исправления; 11 октября - демонстрация. 12-16 октября - PDF, история грейдов, надежность worker и privacy; 17-22 октября - пилоты и eval; 23-26 октября - вакансии или регулярные задания при готовности обязательной части; 27-29 октября - freeze, нагрузка, восстановление backup и презентация; 30 октября - финальная сдача.
Организационно не определены хост, ресурсы ML, бюджет inference, SMTP/домен и участники пилота. Без них нельзя обещать публичный стенд, скорость модели или точность категоризации. В рамках этого этапа создан только технический scaffold; product logic остается отдельной задачей.
+96
View File
@@ -0,0 +1,96 @@
# Локальный запуск и Compose
Руководство описывает конфигурацию в репозитории. Compose files создают локальный технический стенд; они не подтверждают готовый production deploy.
## Core сервис
Установите Docker Engine и Docker Compose plugin. В корне репозитория скопируйте .env.example в .env, замените все placeholder passwords и сохраните файл локально. Затем выполните:
make -C deploy config
make -C deploy up
В текущем Compose `POSTGRES_PASSWORD` без URL-кодирования подставляется в `DATABASE_URL`. Используйте пароль из URL-safe символов, например случайную hex-строку. Символы `@`, `/`, `:`, `?`, `#` и `%` пока нельзя вводить в значение без доработки кодирования URI.
Основной файл deploy/docker/docker-compose.yml запускает PostgreSQL, Go backend и frontend контейнер. Frontend контейнер раздает статические файлы через Nginx и проксирует /api в backend. PostgreSQL, backend и Nginx общаются по выделенной Compose сети.
Контекст сборки backend - каталог `backend/`, поэтому Docker применяет `backend/.dockerignore`. Локальные инструменты, кеши, файлы окружения и результаты сборки не отправляются в этот build context.
Для текущего `postgres:alpine` volume монтируется в `/var/lib/postgresql`; образ размещает данные в подкаталоге своей major-версии. При переходе тега на новую major-версию существующую базу нужно мигрировать через `pg_upgrade` или backup/restore. Обновление образа само по себе не преобразует данные.
Откройте http://127.0.0.1:8080. Порт привязан к loopback. Nginx отвечает на /healthz, перенаправляет /api/ в Go и использует SPA fallback для остальных путей. Go health endpoint находится на /api/v1/healthz; Go readiness проверяет PostgreSQL через SELECT 1. Служебный /metrics слушает на внутреннем порту backend 9090.
Этот Nginx конфиг не настраивает production TLS. Текущий bind не открывает приложение напрямую во внешнюю сеть. Для удаленного доступа требуется отдельно выбранный TLS reverse proxy, firewall и конфигурация целевого окружения.
Полезные команды:
make -C deploy config
make -C deploy up
make -C deploy logs
make -C deploy down
make -C deploy smoke
down останавливает контейнеры, сохраняя именованные volumes. Не удаляйте volume с базой или файлами в рамках обычного останова.
## Отдельный ML Compose
ML имеет отдельный Compose-файл и проект. По умолчанию он слушает на 127.0.0.1:8000. Настройте ML_BIND_ADDRESS только если выбранный приватный адрес и firewall уже подготовлены. Метрики удаленного ML target не собираются, пока ML_METRICS_TARGET пуст.
make -C deploy ml-config
make -C deploy ml-up
make -C deploy ml-logs
make -C deploy ml-down
GET /healthz проверяет процесс. GET /readyz проверяет готовность к inference и возвращает 503, пока модель не доступна. В текущем scaffold рабочей модели нет. Не принимайте readiness за качество или работоспособность ML inference.
## Отдельный monitoring Compose
Сначала запустите core проект: monitoring присоединяется к созданной им Docker сети. Стек мониторинга поднимается отдельно и не нужен для запуска приложения:
make -C deploy monitoring-config
make -C deploy monitoring-up
make -C deploy monitoring-logs
make -C deploy monitoring-down
Grafana доступна на http://127.0.0.1:3000. Учетные данные берутся из GRAFANA_ADMIN_USER и GRAFANA_ADMIN_PASSWORD в .env. Prometheus, Loki, exporters и backend metrics не публикуют host ports.
Prometheus хранит метрики 14 дней с лимитом 4 GB. Loki хранит логи 7 дней. Alloy discovery отфильтровывает Compose project и принимает логи только backend, frontend и postgres. Разрешенные Loki labels ограничены service и environment; не добавляйте user ID, адреса, resume content, request body или полный URL в labels.
Frontend телеметрия пока не подключена в React-приложении. Nginx и Alloy имеют ограниченный /telemetry приемник и конфигурацию Faro, однако UI SDK и сквозная проверка событий отсутствуют.
Для обнаружения контейнеров Alloy использует docker-socket-proxy. Разрешены только нужные разделы Docker API для containers, events, ping и version; POST отключен. Путь к сокету задается DOCKER_SOCKET_PATH. На rootless Docker он может выглядеть как /run/user/<uid>/docker.sock; указывайте путь, действующий на вашем хосте, не копируйте чужой локальный путь. Прокси ограничивает API, но доступ к Docker socket все равно считайте привилегированным и проверяйте его точную конфигурацию.
База PostgreSQL создает отдельную роль postgres exporter только при инициализации пустого volume и наличии POSTGRES_EXPORTER_USER и POSTGRES_EXPORTER_PASSWORD. Задайте эти значения до первого make -C deploy up. Установка переменных после создания volume не запускает init script повторно.
Для удаленного ML scrape задайте ML_METRICS_TARGET в формате hostname:port или IPv4:port и проверьте private routing/firewall. Standalone ML host пока не имеет отдельного Alloy config для доставки своих контейнерных логов в Loki.
## Сервисы и образы
Для контейнерных образов выбраны moving tags `latest` или `alpine`, если upstream публикует такой вариант. При обновлении Compose сверяйте актуальные ссылки на образы. Теги `latest` и `alpine` могут перемещаться; для выпуска фиксируйте фактические image digests и SBOM. Lockfiles прикладных зависимостей сохраняются отдельно.
| Компонент | Текущий источник образа | Основной upstream license |
| --- | --- | --- |
| PostgreSQL | Docker Official Image, docker-library/postgres | PostgreSQL License для сервера; packaging repo MIT |
| Prometheus | prom/prometheus | Apache-2.0 |
| Loki | grafana/loki | AGPL-3.0-only по умолчанию; см. LICENSING.md исключения |
| Grafana Alloy | grafana/alloy | Apache-2.0 по умолчанию |
| Grafana | grafana/grafana | AGPL-3.0-only по умолчанию |
| Node exporter | prometheus/node_exporter | Apache-2.0 |
| PostgreSQL exporter | prometheus-community/postgres_exporter | Apache-2.0 |
| Docker socket proxy | Tecnativa/docker-socket-proxy | Apache-2.0 |
| BusyBox | busybox | GPL-2.0-only |
Ссылки на upstream: [PostgreSQL image](https://github.com/docker-library/postgres), [Prometheus](https://github.com/prometheus/prometheus/blob/main/LICENSE), [Loki license details](https://github.com/grafana/loki/blob/main/LICENSING.md), [Alloy license details](https://github.com/grafana/alloy/blob/main/LICENSING.md), [Grafana license details](https://github.com/grafana/grafana/blob/main/LICENSING.md), [node_exporter](https://github.com/prometheus/node_exporter/blob/master/LICENSE), [postgres_exporter](https://github.com/prometheus-community/postgres_exporter/blob/master/LICENSE), [socket proxy](https://github.com/Tecnativa/docker-socket-proxy), [BusyBox license](https://busybox.net/license.html).
Указанная лицензия относится к основному upstream проекту и не описывает все файлы внутри образа. Базовые пакеты ОС и встроенные зависимости могут иметь отдельные условия. Перед распространением проверьте конкретный tag/digest образа, его notices и SBOM. В репозитории не назначена общая лицензия проекта.
Backend строится с Go 1.26.8; образ runtime выбран в backend/Dockerfile. Базовые образы frontend и ML описаны в соответствующих Dockerfiles. Исходники: [Docker Official Images](https://github.com/docker-library), [Distroless](https://github.com/GoogleContainerTools/distroless) и [NGINX unprivileged images](https://github.com/nginxinc/docker-nginx-unprivileged); перед распространением проверьте точные tags и слои.
## Observability configuration
Prometheus опрашивает backend /metrics на порту 9090, PostgreSQL exporter, node exporter, себя и необязательный ML target. Loki использует файловое хранилище в single-binary режиме с хранением 168 часов. Grafana загружает datasource Prometheus и Loki из observability/grafana/provisioning/.
Три JSON dashboard в репозитории поддерживаются как панели проекта: Go runtime, PostgreSQL и Linux system. Они не скопированы по Grafana dashboard ID. Для них не заявляется внешнее происхождение или лицензия.
Локальный стек мониторинга рассчитан на разработку и демонстрацию на одном узле и не обеспечивает HA. Проверка Compose валидирует конфигурацию, но не подтверждает production retention, backup вне узла, контроль публичного доступа, доставку alerts или поведение core приложения.
Файлы CI workflow находятся в .github/workflows/. Их наличие не подтверждает запуск на GitHub. В руководстве по проверкам описана разница между проверкой конфигурации, infrastructure smoke и проверкой продуктового сценария.
+90
View File
@@ -0,0 +1,90 @@
# Разработка
Эта страница описывает текущий технический каркас и команды, закрепленные в репозитории. Продуктовые сценарии остаются планом; подробная целевая архитектура находится в [ARCHITECTURE.md](ARCHITECTURE.md).
## Стек и источники версий
| Компонент | Источник выбранной версии |
| --- | --- |
| Go | точная версия 1.26.8 в backend/go.mod, toolchain и Go build image |
| Node.js | frontend/.node-version |
| Frontend dependencies | актуальные stable releases в package manifests и pnpm-lock.yaml |
| Python и uv | версии ML toolchain и uv.lock |
Frontend зависимости выбираются из актуальных stable releases; сохраняйте pnpm-lock.yaml для повторяемой установки. ML зависимости фиксируются в uv.lock, Go dependencies - в backend/go.mod. При обновлении меняйте соответствующий lock/config и запускайте checks области. Образы используют заданные moving `latest` или `alpine` tags; сверяйте ссылки в Compose/Dockerfiles и не считайте их стабильными номерами версии.
## Установка и цикл работы
Frontend проверяется компилятором TypeScript 7.0.2 (`tsc`). Пакет `@typescript/native` ссылается на него через npm alias, а `typescript` ссылается на совместимый API `@typescript/typescript6` для ESLint. Это [рекомендованная Microsoft схема совместного использования](https://devblogs.microsoft.com/typescript/announcing-typescript-7-0/#running-side-by-side-with-typescript-6.0): текущий typescript-eslint еще не работает с API TS7. В проверку типов входят исходники, Vite config и `codegen/orval.config.ts`.
Orval создает `frontend/src/shared/api/endpoints/` и `schemas/` без дополнительного каталога `generated/`. `client.ts` и корневой `index.ts` в `shared/api/` поддерживаются вручную. Generated MSW handler проверяется вместе с generated client в Node-тесте. Vitest пока сообщает peer warning об ожидаемом MSW 2; текущий Node-путь проверен с MSW 3, browser mode не используется.
Игноры находятся в `.gitignore` соответствующего компонента. Корневой файл содержит только правила для файлов самого корня. В CI pnpm устанавливается по `packageManager` из frontend/package.json; встроенный Corepack не требуется. Для локальной проверки ML с другой глобальной версией uv можно передать `UV='uv tool run --from uv==0.12.22 uv'` в Make.
В корне используйте make help для актуального списка. Основные targets:
- make install - поставить зависимости для api, frontend, ml и backend;
- make generate - собрать оба OpenAPI bundle и обновить Go/TypeScript/Python generated output;
- make fmt и make fmt-check - отформатировать или проверить форматирование;
- make lint - запустить настроенные линтеры;
- make test - unit/component/service tests для backend, frontend и ML;
- make check - проверки api, backend, frontend, ML, deploy, observability и документации;
- make verify - generation, drift checks, root check, api/backend проверки и технический Compose smoke;
- make docs-check - проверить RU/EN документы, локальные ссылки, маршруты и импорты.
Локальный цикл для одной области описан Makefile этой области. Например, make -C backend help, make -C frontend help, make -C ml help, make -C api help, make -C deploy help, make -C observability help.
make check не является бизнес-E2E проверкой. make verify запускает deployment smoke с Docker и integration target backend. Для подробностей см. [TESTING.md](TESTING.md); для локального стенда см. [DEPLOY.md](DEPLOY.md).
## Структура
| Каталог | Назначение |
| --- | --- |
| api/core/ | Публичный OpenAPI контракт браузер-Go |
| api/ml/ | Внутренний OpenAPI контракт Go-ML |
| scripts/ | Общее объединение схем, generated drift и docs-check |
| backend/ | Go HTTP service, adapters, bootstrap, SQL и codegen потребителя |
| backend/config/ | Общая конфигурация Go вне internal |
| frontend/ | Vite SPA, Orval config и generated TypeScript |
| ml/ | Python service, lockfile и генератор Pydantic-моделей |
| deploy/ | Compose, Nginx и smoke |
| observability/ | Prometheus, Loki, Alloy и provisioning/dashboard JSON |
| .agents/ | Канонические проектные инструкции и рабочие стандарты |
| docs/ru/, docs/en/ | Пользовательские документы на русском и английском |
Папки codegen принадлежат сервисам, которые используют сгенерированный код: backend/codegen/, frontend/codegen/ и ml/codegen/. Go client внутреннего ML API создается из backend/codegen/ogen-ml.yml и потребляется в backend/internal/adapter/secondary/ml/api/. Публичный generated Go handler создается из backend/codegen/ogen.yml и монтируется в chi. sqlc config находится в backend/codegen/sqlc.yml, generated SQL - в backend/internal/adapter/secondary/postgres/sqlc/. Orval читает публичный bundle через frontend/codegen/orval.config.ts. В backend/cmd/app/main.go остаются вызов bootstrap.Run() и обработка ошибки; запуск, сборка зависимостей и lifecycle находятся в backend/internal/bootstrap/app.go.
## Контракты и генерация
Исходные YAML находятся рядом с соответствующим контрактом. Для общей сборки используйте make -C api bundle; он собирает схемы для api/core/ и api/ml/, затем bundles для обоих входов. Публичный и внутренний API не объединяются в одну спецификацию.
Корневой make generate подготавливает API bundles один раз, затем запускает потребителей Go, TypeScript и Python. Merged schemas, bundles и generated clients являются отслеживаемыми derived files; меняйте исходники и пересоздавайте их генератором. После контракта перегенерируйте всех потребителей и запустите drift check. Отдельный Make target можно использовать для генерации одной части, если ее вход готов и shared contract owner согласовал его.
Целевое решение - OpenAPI 3.2.0, ogen для Go, Orval для TypeScript и datamodel-code-generator для Python/Pydantic v2. Проверяйте только реальные конструкции, которые использует проект, через pinned tools и runtime path. Название версии в заголовке не является подтверждением поддержки полной спецификации.
Python-генератор datamodel-code-generator 0.83.0 читает api/ml/openapi.bundle.yml и создает ml/src/lincodex_ml/api/models.py. Настройки хранятся в ml/codegen/pyproject.toml; это конфигурация инструмента, а зависимости остаются в ml/pyproject.toml и uv.lock. Health/readiness handlers импортируют сгенерированные модели вместо ручных копий схем. make -C ml generate сначала собирает API; при вызове из корневого make generate параметр API_PREPARED=1 использует уже собранный bundle. make -C ml check-generated сравнивает результат через --check без перезаписи файла. CI использует общий make generate, который включает Python-модели.
## Код и слои
Go следует границам domain, usecase, port, adapter и bootstrap. HTTP adapter монтирует generated ogen handler в chi. SQL принадлежит backend/db/queries/, изменения схемы - backend/db/migrations/. sqlc output и wire_gen.go сгенерированы.
Общие backend параметры находятся в backend/config/. Используются go-logkit 0.6.0 через slog bridge и go-httpkit 0.7.0 для request ID, request logging и panic recovery. Собственный Prometheus middleware сохраняется: он ограничивает method labels и использует chi route patterns; go-httpkit/metrics принимает исходное имя метода как label.
Подключение к PostgreSQL создается через pgxpool.NewWithConfig, а generated SELECT 1 readiness query проверяет доступность БД. Pool constructor не должен ждать доступность БД при startup. go-pgkit 1.4.0 не используется: его constructor проверяет подключение и повторяет попытки до возврата pool, что связывало бы запуск сервиса с доступностью БД. Health handlers остаются явными: helper go-httpkit возвращает ok/degraded и детали проверок, а общий контракт использует ok/ready/not_ready. Не добавляйте pgkit, httpkit/metrics, JWT, cache или WebSocket без конкретной потребности и проверки поведения закрепленной версии.
Frontend строится как React/Vite SPA. При разработке продуктовых экранов соблюдайте FSD границы. Generated API transport не превращается в entity model сам по себе. MSW полезен для интерфейсной разработки, но его fixture не подтверждает API реализации.
ML - отдельный FastAPI процесс. Сейчас он предоставляет только operational health/readiness. Readiness остается 503 без модели. Не добавляйте placeholder inference, который выглядит как рабочий результат.
Все комментарии и docstrings в коде пишутся на английском. Инструкции для агентов в корне и .agents также ведутся в единой английской версии; документация команды поддерживается на русском и английском.
## Правила изменений
- Проверяйте текущий код и назначенный ownership перед правкой общего файла.
- Сохраняйте существующие изменения других участников.
- Изменения OpenAPI, миграций, shared Makefile, lockfile и генерации согласуются с одним владельцем общей поверхности.
- Generated files обновляйте только через Make targets.
- Документируйте разницу между работающим сейчас и целевым поведением.
- Не добавляйте локальные пути, секреты и персональные настройки разработчика.
Для задач по backend, frontend, ML, API, базе и инфраструктуре используйте маршруты в корневом [AGENTS_ROUTING.md](../../AGENTS_ROUTING.md).
+71
View File
@@ -0,0 +1,71 @@
# Проверки и оценка качества
Обычные проверки подтверждают отдельные свойства кода. Они не доказывают точность подбора, валидность грейдов, production latency или готовность продукта целиком.
## Команды
Используйте Make targets из корня:
make test
make check
make verify
make docs-check
make test запускает backend, frontend и ML тесты. make check также выполняет проверки API контрактов, форматирование, линтеры, типы, build, Compose, observability и docs-check. make verify последовательно генерирует контракты, проверяет generated drift, запускает root check, API toolchain/backend race и integration проверки, а затем изолированный deployment smoke. Он использует Docker.
Полезные узкие команды:
| Команда | Что проверяет |
| --- | --- |
| make -C api check | Объединение схем, bundles, OpenAPI lint и тесты merge script |
| make -C backend test | Go unit suite с race detector |
| make -C backend test-fast | Быстрый Go test без race instrumentation |
| make -C backend test-int | Go integration tests с Testcontainers/PostgreSQL |
| make -C frontend check | Prettier, ESLint, Stylelint, TypeScript, Vitest, FSD boundaries и build |
| make -C ml check | Ruff, mypy, pytest и сборку wheel |
| make -C ml check-generated | Соответствие Pydantic-моделей ML bundle без перезаписи файлов |
| make -C deploy config | Рендер Compose конфигураций без запуска |
| make -C deploy smoke | Изолированный технический smoke по service health routes |
| make -C observability check | Проверку Prometheus, Loki, Alloy и dashboard JSON |
make -C deploy test-e2e сейчас зарезервирован и завершается ненулевым кодом с сообщением о том, что бизнес flow suite отложен. Не считайте это успешным E2E запуском.
make -C ml check-generated использует datamodel-code-generator --check: расхождение завершает проверку ошибкой, а файл моделей остается неизменным. Перед проверкой обновите bundle через make -C api bundle; для обновления Python-моделей используйте make -C ml generate. Сгенерированные модели не подтверждают наличие inference или поддержку всех возможностей OpenAPI 3.2.
## Что покрывает текущий каркас
Существующие проверки относятся к health/readiness, проверке соединения backend с PostgreSQL, метрикам, API client, ML schema и доступности текущих endpoint. В каркасе нет пользователей, тестовых заданий, поисковой выдачи, приглашений, файлового workflow или реального model inference, которые можно было бы проверить как бизнес-результат.
API verify проверяет выбранный OpenAPI subset через pinned toolchain; его результат относится только к реально запущенным fixture и контрактам. CI YAML в репозитории не означает, что workflow уже выполнился на GitHub.
Deployment smoke проверяет инфраструктурные маршруты и запуск Compose. Он не проверяет получение контактов, защищенность бизнес-данных, устойчивость ML, точность ранжирования, PDF экспорт или сценарий двух ролей. Отдельная проверка мониторинга не подтверждает core database или end-to-end доставку данных от приложения.
## Будущая программная валидация
Для Go unit tests нужны правила domain/usecase с конкретными входами, результатами и ошибками. Интеграционные тесты используют настоящую PostgreSQL той же major версии, применяют goose migrations и проверяют sqlc, ограничения, транзакции, rollback и конкурентные переходы. Для HTTP путь собирается через chi, middleware, usecase и БД; внешний ML заменяется контролируемым HTTP fake, почта - тестовым адаптером.
Общие тестовые данные должны быть изолированы по БД/схеме или сбрасываться последовательно. Не запускайте параллельные сценарии с общим truncate. Контейнер поднимается на suite, порты динамические, cleanup обязателен. Integration job не должен молча пропускать тесты при отсутствии runtime.
Контракты проверяются через bundle, lint, codegen всех Go, TypeScript и Python потребителей и generated drift, включая новые untracked файлы. Frontend component tests не заменяют браузерный тест сквозного пути. После реализации продукта добавить Playwright для двух ролей и явно синтетического кандидата без ФСП.
Критические будущие проверки:
- До принятия предложения контакты не видны другой компании ни через API, поиск, PDF, ошибки или ML объяснения.
- Кандидат не получает доступ к чужим приглашениям, файлам, jobs или попыткам; компания не получает чужие потребности и подборки.
- Отказ по тесту не понижает грейд; первый переход на более низкий уровень разрешен; cooldown не обходится параллельными запросами.
- Повторная отправка результата и принятия идемпотентна; конкурентные status transitions сериализованы.
- Выключенный ML сохраняет ручной путь; истекший worker lease восстанавливается; устаревший ответ не заменяет новый профиль.
- Нет истории ФСП и ошибка интеграции различаются; отсутствие истории не исключает кандидата.
- Уточнение поиска сохраняет прежний снимок; отозванный профиль исключается и из него.
## Будущая оценка качества
Подбор оценивается отдельно от функциональных тестов. Начальный план: 60-100 синтетических кандидатов, 8-12 запросов, два независимых разметчика, разбор разногласий и holdout по потребностям. Не помещать близкие копии одного профиля одновременно в настройку и holdout.
Сравнить keyword search, подтвержденные навыки и ML. Считать Precision@5, nDCG@5, нарушения жестких фильтров, покрытие категорий и долю релевантных результатов без ФСП истории. При выдаче короче пяти зафиксировать знаменатель до прогона и показать размер выборки. Синтетический набор не доказывает качество на реальном рынке.
Оценка тестов требует пилота на людях с независимой экспертной оценкой навыков. Сравнить эквивалентные формы, менять порядок, измерить agreement грейда, разброс баллов, решения по заданиям и разделение групп. Синтетические ответы годятся для отладки rubric, но не заменяют пилот.
ML оценка фиксирует набор документов и разметку полей, precision извлечения, выдуманные факты, полезность рекомендаций, schema-valid rate, latency и ошибки. Сохраняются модель, prompt/schema version, параметры и дата. Сравнить с простым baseline и правомерно использовать обезличенные документы.
Проектные ориентиры: 30 одновременных пользователей; p95 чтения профиля до 500 мс; baseline поиск до 1 секунды на демонстрационных данных без учета внешней сети. Это будущие критерии прогона, фактических результатов пока нет. ML получает отдельный latency budget.