docs: add the MVP submission package and refresh the status sections
This commit is contained in:
1 parent
0beae4895d
commit
4fa1cf9198
8 files changed
+316
-34
No files matched your search
+2
-2
@@ -53,8 +53,8 @@ Short directory guides:
|
||||
| [.agents/](.agents/README.en.md) | Agent rules |
|
||||
|
||||
- Source materials: [specification](requirements/specification.pdf), [brandbook](requirements/brandbook/).
|
||||
- Russian: [architecture](docs/ru/ARCHITECTURE.md), [development](docs/ru/DEVELOPMENT.md), [deployment](docs/ru/DEPLOY.md), [testing](docs/ru/TESTING.md), [security](docs/ru/SECURITY.md)
|
||||
- English: [architecture](docs/en/ARCHITECTURE.md), [development](docs/en/DEVELOPMENT.md), [deployment](docs/en/DEPLOY.md), [testing](docs/en/TESTING.md), [security](docs/en/SECURITY.md)
|
||||
- Russian: [architecture](docs/ru/ARCHITECTURE.md), [development](docs/ru/DEVELOPMENT.md), [deployment](docs/ru/DEPLOY.md), [testing](docs/ru/TESTING.md), [security](docs/ru/SECURITY.md), [MVP package](docs/ru/MVP.md)
|
||||
- English: [architecture](docs/en/ARCHITECTURE.md), [development](docs/en/DEVELOPMENT.md), [deployment](docs/en/DEPLOY.md), [testing](docs/en/TESTING.md), [security](docs/en/SECURITY.md), [MVP package](docs/en/MVP.md)
|
||||
|
||||
## License
|
||||
|
||||
|
||||
@@ -59,8 +59,8 @@ make -C deploy demo-seed DEMO_MODE=isolated
|
||||
| [.agents/](.agents/README.md) | Правила работы агентов |
|
||||
|
||||
- Исходные материалы: [ТЗ](requirements/specification.pdf), [брендбук](requirements/brandbook/).
|
||||
- На русском: [архитектура](docs/ru/ARCHITECTURE.md), [разработка](docs/ru/DEVELOPMENT.md), [развертывание](docs/ru/DEPLOY.md), [тестирование](docs/ru/TESTING.md), [безопасность](docs/ru/SECURITY.md).
|
||||
- На английском: [архитектура](docs/en/ARCHITECTURE.md), [разработка](docs/en/DEVELOPMENT.md), [развертывание](docs/en/DEPLOY.md), [тестирование](docs/en/TESTING.md), [безопасность](docs/en/SECURITY.md).
|
||||
- На русском: [архитектура](docs/ru/ARCHITECTURE.md), [разработка](docs/ru/DEVELOPMENT.md), [развертывание](docs/ru/DEPLOY.md), [тестирование](docs/ru/TESTING.md), [безопасность](docs/ru/SECURITY.md), [пакет сдачи MVP](docs/ru/MVP.md).
|
||||
- На английском: [архитектура](docs/en/ARCHITECTURE.md), [разработка](docs/en/DEVELOPMENT.md), [развертывание](docs/en/DEPLOY.md), [тестирование](docs/en/TESTING.md), [безопасность](docs/en/SECURITY.md), [пакет сдачи MVP](docs/en/MVP.md).
|
||||
|
||||
## Лицензия
|
||||
|
||||
|
||||
@@ -9,5 +9,6 @@ Guides to the project's structure and development workflow. Russian documents li
|
||||
- [DEPLOY](en/DEPLOY.md) covers the MVP quick start and the demo stand, startup, environment settings, and monitoring.
|
||||
- [TESTING](en/TESTING.md) describes test types, commands, and check boundaries.
|
||||
- [SECURITY](en/SECURITY.md) describes scanners, reports, and security exceptions.
|
||||
- [MVP](en/MVP.md) is the submission package of the minimal release: what is implemented, how to run it, limits, what is not implemented, and checks.
|
||||
|
||||
Update both language versions together. From the repository root, `make docs-check` checks documentation structure and local links. Source requirements and brand assets live in [requirements/](../requirements/README.en.md).
|
||||
@@ -9,5 +9,6 @@
|
||||
- [DEPLOY](ru/DEPLOY.md) - быстрый старт MVP и демонстрационный стенд, запуск, настройки окружения и мониторинг.
|
||||
- [TESTING](ru/TESTING.md) - виды тестов, команды и границы проверок.
|
||||
- [SECURITY](ru/SECURITY.md) - сканеры, отчеты и исключения безопасности.
|
||||
- [MVP](ru/MVP.md) - пакет сдачи минимального выпуска: что реализовано, запуск, ограничения, нереализованное и проверки.
|
||||
|
||||
Обе языковые версии обновляются вместе. Из корня репозитория: `make docs-check` проверяет структуру документации и локальные ссылки. Исходные ТЗ и брендбук находятся в [requirements/](../requirements/README.md).
|
||||
+19
-15
@@ -4,9 +4,13 @@ This document separates the target product architecture from the technical scaff
|
||||
|
||||
## Current scaffold
|
||||
|
||||
The repository contains a Go HTTP service with PostgreSQL, Redis, and SeaweedFS checks, cache and S3 storage adapters, a React interface scaffold with public pages and two cabinet shells of placeholder screens, a separate Python ML service with health and readiness routes, two OpenAPI contracts, code generation, Compose files, and monitoring configuration. The public API health route is under /api/v1/healthz. The web container uses /healthz. The internal Go /readyz checks PostgreSQL, Redis, and the SeaweedFS bucket. ML uses /healthz and /readyz; readiness returns 503 while inference is unavailable. Go exposes the standard /metrics endpoint on an internal port.
|
||||
The repository contains a Go HTTP service with PostgreSQL, Redis, and SeaweedFS checks, cache and S3 storage adapters, a React interface with public pages and two cabinets (working screens for the workflows described below), a separate Python ML service with health and readiness routes, two OpenAPI contracts, code generation, Compose files, and monitoring configuration. The public API health route is under /api/v1/healthz. The web container uses /healthz. The internal Go /readyz checks PostgreSQL, Redis, and the SeaweedFS bucket. ML uses /healthz and /readyz; readiness returns 503 while inference is unavailable. Go exposes the standard /metrics endpoint on an internal port.
|
||||
|
||||
Registration, email confirmation, login, and basic current-session operations work through the backend API. The frontend implements registration, confirmation, sign-in, and continuation from the server-provided scenario step; local browser E2E covers candidate and employer accounts. Consent settings and organization creation/editing work through the backend API. The internal notification inbox of both cabinets lists and marks its notices; a sent invitation is the first product producer (see [Internal notifications](#internal-notifications)). The organization side of the invitation draft (list, create, read, and update with versioned terms) and the send to the candidate's inbox with the candidate's list of invitations work through the backend API; the candidate's answers are not implemented (see [Invitation drafts](#invitation-drafts) and [Sending invitations](#sending-invitations)). Other product workflows are not implemented: roles, profiles, assessments, grades, answering invitations, resume processing, PDF generation, and FSP integration. The deterministic basic match search of the organization-visible bank works through the backend API without ML, competition data, snapshots, or invitations (see [Matching and explanations](#matching-and-explanations)). ML does not return invented results. Health checks and the technical smoke do not verify a product workflow.
|
||||
Registration, email confirmation, login, and basic current-session operations work through the backend API and the frontend screens; local browser E2E covers candidate and employer accounts. The backend API and the cabinet screens also cover consents C1-C5 and the account deletion request; organizations, memberships, and employer needs; the manual candidate profile and the questionnaire with specializations and self-assessment; the public specialization catalog; assessment attempts (create, answers, finalize, result history, server signals, and skill evidence), where the task bank and the categories are demonstration data and uncalibrated; privacy settings and publication of the anonymous card; the internal notification inbox of both cabinets (see [Internal notifications](#internal-notifications)); and support cases. The manual assessment request is implemented as a support case of that type (`usecase/supportcase`, `frontend/src/features/request-manual-assessment`): it does not depend on consent C3, creates no attempt, changes no category, and only puts the case into the expert queue; the API has no operation for the expert side of that queue. The deterministic basic match search of the organization-visible bank works through the backend API without ML, competition data, or search snapshots (see [Matching and explanations](#matching-and-explanations)); category recommendations for a need are not computed, and the response carries an empty list (`domain/need_response.go`).
|
||||
|
||||
Invitations are implemented end to end (see [Invitation drafts](#invitation-drafts), [Sending invitations](#sending-invitations), [Candidate view and decline](#candidate-view-and-decline), [Candidate acceptance](#candidate-acceptance), [Pending limit, cooldown, and expiry](#pending-limit-cooldown-and-expiry), and [Contact reads and revocation](#contact-reads-and-revocation)): an organization creates and updates a draft with versioned terms and sends it; the invitation reaches the candidate's inbox and produces an internal notification; the candidate reads it, marks it viewed, declines it, or accepts it with consent C4 for the chosen contacts; after acceptance the organization reads the shared contacts, and the candidate can revoke the contact grant. The pending limit per need, the cooldown of the organization-candidate pair after a decline, and the expiry at the response deadline apply. The frontend has the invitation composer reached from a search result, the organization's invitation list (`pages/employer-invitations`), and the candidate inbox. The operations for withdrawal by the organization (`WithdrawOrganizationInvitation`), cancellation by the candidate (`CancelMyInvitation`), and the salary raise (`RaiseOrganizationInvitationSalary`) are in the contract but not implemented, and answer 501 `not_implemented`.
|
||||
|
||||
Not implemented: counter-offers and the stages after acceptance (interviews), password reset, resume upload and analysis, PDF, search snapshots and refinement, ML inference and semantic search (the backend does not call the ML client), FSP integration (the `adapter/secondary/fsp` directory is empty), the SMTP transport (the backend fails to start with `EMAIL_PROVIDER=smtp`; only Resend sends mail), PDF generation (the `adapter/secondary/pdf` directory is empty), and ATS adapters. ML does not return invented results. Health checks and the technical smoke do not verify a product workflow.
|
||||
|
||||
See [development](DEVELOPMENT.md), [deployment](DEPLOY.md), and [testing](TESTING.md) for source layout, commands, and current check coverage.
|
||||
|
||||
@@ -573,7 +577,7 @@ backend/
|
||||
middleware/ request log and request metrics by route template
|
||||
observe/ request-scoped observations, such as the problem code
|
||||
problem/ RFC 9457 error responses
|
||||
v1/ handwritten health endpoint
|
||||
v1/ handwritten handlers of the contract operations
|
||||
router.go chi composition
|
||||
adapter/secondary/
|
||||
argon2id/ Argon2id password hasher with a memory budget
|
||||
@@ -601,7 +605,7 @@ backend/
|
||||
|
||||
Domain types live directly in `backend/internal/domain/`: `user.go`, `candidate.go`, and other files as their models are defined. Do not nest directories by entity or feature. The first type is `DomainEvent` in `domain_event.go`, the validated event that a transaction writes to the outbox. Identity storage types live in `email_address.go`, `secret_token.go`, `user.go`, `email_token.go`, and `session.go`; the normalized password is in `password.go`. The consent ledger types live in `consent.go`. The organization, verification, and membership types live in `organization.go` and `membership.go`. The product policy and its versions live in `policy.go`, `policy_document.go`, `policy_version.go`, and `policy_demo.go`.
|
||||
|
||||
Outside the implemented identity and consent flows, domain types and usecases for other product workflows are not implemented. SMTP and FSP adapters, and product worker jobs, remain planned. `main.go` starts bootstrap and handles process errors. The public generated transport uses ogen v1.24.0 and the contracts declare OpenAPI 3.2.0. Verify only the feature subset used by the repository, not every specification feature.
|
||||
Outside the implemented flows (identity, consents, organizations, profile and questionnaire, assessment, needs and matching, invitations, support cases, notifications), usecases for documents and FSP achievements are not implemented. SMTP and FSP adapters remain planned; the product worker jobs are currently only the computation of the assessment review band and the expiry of an invitation at its response deadline. `main.go` starts bootstrap and handles process errors. The public generated transport uses ogen v1.24.0 and the contracts declare OpenAPI 3.2.0. Verify only the feature subset used by the repository, not every specification feature.
|
||||
|
||||
This is a compact map, not a claim that every planned product package exists. Current Go code includes health usecases and adapters, generated API clients, bootstrap with startup migrations, a PostgreSQL health query, the transactional outbox writer, the outbox relay that publishes committed events to Kafka through the franz-go adapter, the event consumer runtime with the `notification_delivery` and `notification_inbox` handlers, the internal notification inbox with its list and read-state operations, the scheduled job runtime (`worker/jobrunner`) with no registered product job kind, identity usecases for registration, resend, confirmation, and login, PostgreSQL sessions and a security boundary for every operation protected by the API contract, the consent usecase that records C1 during registration, the versioned policy store with its publisher and the demo policy seed at startup, the `PasswordHasher` port with the Argon2id adapter and checks used by registration, confirmation, and login, a Redis cache adapter, a SeaweedFS S3 adapter with the shared private file layer over it, the `MailSender` port with the `disabled` and Resend transports, the mail template renderer, and the identity mail worker used for registration and resend. Profiles, resumes, assessments, invitations, product job kinds, file workflows, the SMTP transport, and FSP adapters remain planned. Do not create empty module directories before a real use case exists.
|
||||
|
||||
@@ -658,7 +662,7 @@ These intervals are the accepted initial policy, stored as demo version 1 of the
|
||||
|
||||
### Assessment bank
|
||||
|
||||
Implemented as storage and a loader, not as a candidate-facing feature: migration `backend/db/migrations/00011_create_assessment_bank.sql`, queries in `backend/db/queries/assessment_bank.sql`, the domain types in `backend/internal/domain/` (`assessment_family.go`, `assessment_generator.go`, `assessment_algorithms.go`), the `outbound.AssessmentBankRepository` port (`port/outbound/assessment_bank.go`, reachable through `UnitOfWork.AssessmentBank()`), the sqlc-backed adapter in `backend/internal/adapter/secondary/postgres/assessment_bank.go`, and the loader in `backend/internal/usecase/assessment/` (`Bank`, `Bundle`). Nothing in bootstrap or the HTTP API calls it yet, and no category is open.
|
||||
Implemented as storage and a loader, not as a candidate-facing feature: migration `backend/db/migrations/00011_create_assessment_bank.sql`, queries in `backend/db/queries/assessment_bank.sql`, the domain types in `backend/internal/domain/` (`assessment_family.go`, `assessment_generator.go`, `assessment_algorithms.go`), the `outbound.AssessmentBankRepository` port (`port/outbound/assessment_bank.go`, reachable through `UnitOfWork.AssessmentBank()`), the sqlc-backed adapter in `backend/internal/adapter/secondary/postgres/assessment_bank.go`, and the loader in `backend/internal/usecase/assessment/` (`Bank`, `Bundle`). Bootstrap creates `assessment.NewBank` once (`bootstrap/catalog.go`, with its own small PostgreSQL pool) and hands it to `CatalogHandler`; HTTP uses only the read `Bank.SpecializationAvailability` for the public specialization catalog (`GET /api/v1/specializations`). HTTP does not call the loader operations (`ImportBundle`, `PublishFamily`, `RetireFamily`, `OpenCategory`): the demonstration seed command (`adapter/primary/cli/demoseed`, `usecase/demoseed`) and `cmd/questionnaire-fixture` call them, so no category is open in a build without the seed. Assessment attempts run through a separate `AttemptService` that reads the bank through the `UnitOfWork.AssessmentBank()` repository, not through `Bank`.
|
||||
|
||||
- Family version. One `assessment_families` row is one version of one family (`family_key`, `version`): category, specialization (the domain inside the category), title, author (`ai:<name>` or `operator:<handle>`), reviewer (`operator:<handle>` or NULL), `review_status` (`pending`, `approved`, `rejected`), the seed generator, the answer key, the rubric, a content hash with its `hash_scheme`, a lifecycle (`draft`, `published`, `retired`), and the operators and times of publication and retirement. The reviewer is never the author, and a review is pending exactly while there is no reviewer (CHECK constraints; the domain applies the same rules). The reviewer in a bundle and the operator of a publication are declared values, not authenticated identities, until reviewer and operator accounts exist.
|
||||
- Immutability. The content of a stored version never changes: the trigger `assessment_families_guard_update` refuses every UPDATE that changes a column other than the lifecycle columns (`lifecycle`, `published_at`, `published_by`, `retired_at`, `retired_by`), and `assessment_families_refuse_removal` refuses DELETE and TRUNCATE, all with SQLSTATE 23000 and the constraint name `assessment_families_immutable`, which the adapter maps to `outbound.ErrAssessmentFamilyImmutable`. The lifecycle moves only forward (draft, published, retired), the trigger sets the times and keeps the publisher through a retirement, and a version is published only with an approved review by a reviewer (`assessment_families_published_requires_review`). A change is a new version with the next number; the loader accepts only version 1 for a new family and the successor of the latest version otherwise. A pending draft is never approved in place: its review is recorded by importing a new version of the family that carries the review, and the pending version stays an unpublished draft. The domain recomputes the content hash when it reads a row and returns `ErrAssessmentFamilyIntegrity` for a row changed outside the application. The hash is the SHA-256 of a canonical JSON document that holds the content without the bundle name, ID, lifecycle, and publication fields. The `hash_scheme` column (a smallint with a CHECK of the known values, one of the immutable columns) names the layout: the domain verifies a row with the hash function of the scheme the row was stored with, so a later scheme (a new function and a new CHECK value, never an edit of scheme 1) verifies new rows without invalidating old ones, and a row with an unknown scheme is refused; tests verify a row with its own scheme and pin the scheme 1 hash of a fixed input. As for `policy_versions`, a role that owns the table can still disable the triggers.
|
||||
@@ -669,7 +673,7 @@ Implemented as storage and a loader, not as a candidate-facing feature: migratio
|
||||
- Lifecycle and the loader. `Bank.ImportBundle` stores every family of a bundle as a draft in one transaction and never publishes, whatever the review says; importing the same bundle again, also concurrently, reports the versions as unchanged. `Bank.PublishFamily` and `Bank.RetireFamily` take the operator, and refuse with a reason (`reviewer_missing`, `review_not_approved`, `not_draft`, `not_published`, `newer_version_published`); the refusal is a `*domain.AssessmentRefusalError` that carries the reason, and the sentinels of a race that the database decided (a lifecycle step that lost to another, a missing approved review, insufficient coverage) become the same refusals. Publishing, retiring, and opening take a transaction-scoped advisory lock of the category first, so they run one after another per category; `LockCategory` works only inside a transaction (the repository of a unit of work takes it, the standalone store returns `ErrAssessmentLockOutsideTransaction`).
|
||||
- Category availability. `Bank.OpenCategory` records an opening in `assessment_category_openings` under a referenced policy version (`policy_versions.id`); it refuses with `grading_policy_missing` for a missing or unknown reference and with `grading_policy_not_current` unless the version is the one of the `product` family in force now, judged against the database clock of the same transaction (`clock_timestamp()`), the clock that stamps the effective time of a policy version, so the bank defines no thresholds of its own and no application clock enters the decision. The number of distinct published families that a category needs is read from that policy: `RequiredPublishedAssessmentFamilies` returns `assessment.stop_rule.max_scored_items` plus `assessment.stop_rule.seed_items`. The owner accepted this rule as a product decision on 2026-10-06. The reason: one family gives at most one item to an attempt, so a full adaptive attempt, which can run to the maximum of scored items and also carries the seed items, cannot run out of families. The insert trigger derives the same number from the stored policy document itself (the same two JSON paths; an integration test keeps the SQL and the domain equal) and checks both values as plain non-negative integers of at most four digits before the cast, so a malformed document written around the application raises the `assessment_category_openings_policy_thresholds` refusal instead of a cast error. The trigger also counts the published families, and the CHECK constraint refuses the row when they are fewer, so a call written around the usecase cannot open a category with a lower requirement. The opening stores the policy version, the operator (`operator:<handle>`), and the required and counted families, and is never edited. Availability is live: `Bank.CategoryAvailability` returns the current opening only while the published families counted now still reach the opening's requirement, and otherwise refuses with `coverage_insufficient` (or `ErrAssessmentCategoryNotOpen` without an opening), so a retirement can close a category. It also refuses with `grading_policy_not_current` when the opening's policy version is no longer the one in force, so a policy change requires a new opening. The table checks the policy reference in the trigger instead of a foreign key, because PostgreSQL refuses TRUNCATE of a referenced table before the `policy_versions` trigger can refuse it with its own error. `ListFamilies` pages by (key, version) cursor with a hard limit of 200.
|
||||
- Demo bundle. `backend/testdata/assessment/backend_demo_bundle.json` holds four original practice problems for the category `backend`. They are an AI-generated draft (author `ai:claude-draft`) with a pending review and no reviewer, so the loader imports them as drafts, publication is refused, and the category stays closed. No human has reviewed the statements, solutions, rubrics, or difficulty; the bundle makes no validity or calibration claim. A real review produces a new version of the families that carries the approval.
|
||||
- Not implemented: authorship and review of a real task bank, blueprints per specialty and grade, selection of tasks for an attempt, the storage of attempts and answers, grading, an HTTP or admin interface, authenticated reviewer and operator identities, and a wiring of the loader in bootstrap.
|
||||
- Not implemented: authorship and review of a real task bank, blueprints per specialty and grade, an HTTP or admin interface of the loader and authenticated reviewer and operator identities (the storage of attempts, answers, and grading exist as separate assessment operations, not as part of the loader).
|
||||
|
||||
### Assessment signals and the review band
|
||||
|
||||
@@ -980,7 +984,7 @@ The anonymous card for organizations is not built here: `AnonymousCardContent` i
|
||||
|
||||
### Invitation drafts
|
||||
|
||||
Implemented: the organization side of the invitation draft, that is `ListOrganizationInvitations`, `CreateOrganizationInvitation`, `GetOrganizationInvitation`, and `UpdateOrganizationInvitation` ([contract](../../api/README.en.md#invitations-and-contact-grants)). A draft is invisible to the candidate and produces no inbox entry, no event, and no quota charge; the send is described in [Sending invitations](#sending-invitations). Withdrawal, the salary raise, the contact read, and the cancellation still answer 501 after the common checks; the candidate's read, view, decline, and acceptance are described in [Candidate view and decline](#candidate-view-and-decline) and [Candidate acceptance](#candidate-acceptance). Code: `domain/salary_range.go`, `domain/invitation_terms.go`, `domain/invitation.go`, `usecase/invitation/`, `adapter/primary/http/v1/invitation.go`, the PostgreSQL adapter `adapter/secondary/postgres/invitations.go` with `db/queries/invitations.sql`, and migration `00037_create_invitations.sql`.
|
||||
Implemented: the organization side of the invitation draft, that is `ListOrganizationInvitations`, `CreateOrganizationInvitation`, `GetOrganizationInvitation`, and `UpdateOrganizationInvitation` ([contract](../../api/README.en.md#invitations-and-contact-grants)). A draft is invisible to the candidate and produces no inbox entry, no event, and no quota charge; the send is described in [Sending invitations](#sending-invitations). Withdrawal, the salary raise, and the cancellation still answer 501 after the common checks; the contact read is described in [Contact reads and revocation](#contact-reads-and-revocation); the candidate's read, view, decline, and acceptance are described in [Candidate view and decline](#candidate-view-and-decline) and [Candidate acceptance](#candidate-acceptance). Code: `domain/salary_range.go`, `domain/invitation_terms.go`, `domain/invitation.go`, `usecase/invitation/`, `adapter/primary/http/v1/invitation.go`, the PostgreSQL adapter `adapter/secondary/postgres/invitations.go` with `db/queries/invitations.sql`, and migration `00037_create_invitations.sql`.
|
||||
|
||||
Tables:
|
||||
|
||||
@@ -1144,7 +1148,7 @@ The Go service exports standard Go/process metrics and the product metrics on an
|
||||
- API: `lincodex_http_requests_total{method,route,status}`, `lincodex_http_request_duration_seconds{method,route,status_class}`, and `lincodex_http_problems_total{route,code}`. `route` is the chi route template of an operational route and, under `/api/v1`, the OpenAPI path template of the matched operation, such as `/api/v1/me/invitations/{invitation_id}`, which the router resolves with the generated server's `FindPath`; a path or method without an operation keeps the mount pattern `/api/v1/*` or `/api/*`, and a path outside every route is `unmatched`. `status_class` is `1xx` to `5xx`. `code` is the RFC 9457 problem code: `problem.New` records it from the closed catalogue through the request-scoped `observe` package (`adapter/primary/http/observe/`), the middleware counts it only for a 4xx or 5xx response, and the adapter counts a code outside its mirrored list as `other`. An error without a problem body, such as `/readyz` 503, is counted by status only. The request log (`middleware.RequestLog`, which replaces the go-httpkit logger) uses the same route template and logs the request ID, method, status and class, problem code, latency, response size, and the number of query parameters, never the raw path, a query key or value, a header, the client address, or the user agent; `/healthz` and `/readyz` are not logged.
|
||||
- Outbox and events: the relay, consumer, and scheduled job metrics in [Outbox relay](#outbox-relay), [Event consumers](#event-consumers), and [Scheduled jobs](#scheduled-jobs). Outbox lag is `lincodex_outbox_relay_oldest_pending_age_seconds`.
|
||||
- Mail: `lincodex_mail_deliveries{kind,status}` for every kind and the statuses `pending`, `waiting_quota`, `unknown`, `accepted`, `rejected`, and `cancelled`, zero included; `lincodex_mail_sender_running`, 1 while this process's mail sending loop runs and 0 otherwise (per process, so aggregate it with `max`; it stays 0 with `EMAIL_PROVIDER=disabled`, where no loop starts); `lincodex_notification_sender_running` reports the same for the notification loop; `lincodex_mail_delivery_oldest_due_pending_age_seconds`, which counts only service mail (`domain.ServiceMailKinds`), so a notification backlog never looks overdue; `lincodex_mail_sender_cancelled_total{reason}`, deliveries the sending worker ended without sending, by the closed set of cancel reasons, zero included; and, for an active transport, `lincodex_mail_quota_used_recipients`, `lincodex_mail_quota_limit_recipients`, and `lincodex_mail_quota_provider_exhausted`, each with `provider` and `window` (`day` or `month`). The sampler in `backend/internal/worker/deliverymetrics/` reads them every 30 seconds on its own one-connection pool: `postgres.DeliveryStatisticsStore` aggregates `deliveries` by kind and status, and `MailQuotaUsageReader.Usage` reads the current windows of the configured account. The delivery aggregate is the sqlc query `GetDeliveryStatistics` in `db/queries/delivery.sql`. It scans the table, which suits the current volume; add an index or per-status counters before the table holds millions of rows. `EMAIL_ACCOUNT` is not a label: it is free operator text that can name a person, and each process reports only its own account. Every instance reports the same database-wide values; aggregate them with `max`. A failed read keeps the previous values and logs `delivery metrics could not be read; the gauges are stale`; `lincodex_mail_metrics_last_success_timestamp_seconds` shows the last read in which every aggregate was read (0 from the sampler start until the first one), and the age gauge exists only after the first successful read. There is no attempt outcome counter yet; the delivery states, the logs of the sending worker, and the `delivery_attempts` history show outcomes.
|
||||
- Assessment answers: `lincodex_assessment_answer_saves_total{format,outcome}` with the outcomes `stored`, `unchanged`, `rejected`, and `failed`. PRD 6.6 asks to observe the saving of answers; this is read as the assessment answer command `SubmitMyAssessmentAnswer`. The command is not implemented, so only the hook `Metrics.ObserveAssessmentAnswerSave` exists, and no series appears until the usecase calls it once per command. A value outside the closed sets becomes `other`. The HTTP latency and errors of the command already appear under the route `/api/v1/me/assessment-attempts/{attempt_id}/answers`.
|
||||
- Assessment answers: `lincodex_assessment_answer_saves_total{format,outcome}` with the outcomes `stored`, `unchanged`, `rejected`, and `failed`. PRD 6.6 asks to observe the saving of answers; this is read as the assessment answer command `SubmitMyAssessmentAnswer`. The command is implemented, but nothing calls the hook `Metrics.ObserveAssessmentAnswerSave` yet, and no series appears until the usecase calls it once per command. A value outside the closed sets becomes `other`. The HTTP latency and errors of the command already appear under the route `/api/v1/me/assessment-attempts/{attempt_id}/answers`.
|
||||
|
||||
Do not use user, candidate, delivery, or request IDs, full URLs or query strings, addresses, or resume content as labels. Unit tests drive the real router and every metric hook with email and UUID fixtures and fail when the exposition contains an email-like or UUID-like value. Go runtime, PostgreSQL, Redis, SeaweedFS, Linux, and Lincodex product dashboard JSON files are maintained project sources, not imported dashboard IDs. Inference metrics are not implemented in the current scaffold.
|
||||
|
||||
@@ -1158,19 +1162,19 @@ Alert rules in `observability/prometheus/rules/lincodex.yml` cover an unavailabl
|
||||
|
||||
| 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 |
|
||||
| Two portals and verified email, pp. 3-4 | identity, roles, company, access checks | Implemented (no password reset) |
|
||||
| Manual or PDF resume, p. 3 | Manual profile first; PDF and ML extend it | Manual profile implemented; PDF and ML import are not |
|
||||
| Standard PDF, p. 3 | PDFRenderer with Cyrillic and access checks | Not implemented |
|
||||
| Questionnaire, grade, test, category, pp. 1-3 | assessment, variants, grade history | Not implemented |
|
||||
| Questionnaire, grade, test, category, pp. 1-3 | assessment, variants, grade history | Implemented on a demonstration bank; categories are uncalibrated |
|
||||
| Comparable tests and leak resistance, pp. 1-2 | Families, blueprint, rubrics, rotation, pilot | Planned |
|
||||
| No forced grade decrease and change frequency, pp. 2-3 | verified/claimed, retry, cooldown, eligibility | Planned |
|
||||
| Candidate search and explanation, pp. 3-4 | Hard filters, matching evidence, score components | Basic deterministic search implemented; ML, competition data, and snapshots are not |
|
||||
| Refine search without losing prior results, p. 4 | Versioned search runs and server snapshots | Planned |
|
||||
| Invitation without a vacancy, p. 3 | Optional vacancy_id | Not implemented |
|
||||
| RUB salary range and employer contact, p. 4 | Required bounds and explicit period/tax basis | 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 |
|
||||
| RUB salary range and employer contact, p. 4 | Required bounds and explicit period/tax basis | Implemented |
|
||||
| Status for both sides, p. 4 | State machine and event history | Partial: draft, delivered, viewed, accepted, declined, expired; later stages, withdrawal, and cancellation are not |
|
||||
| Contacts after acceptance/application, pp. 3-4 | Contact grant, separate DTOs, file access check | Contacts after acceptance implemented; files and candidate applications are not |
|
||||
| Privacy and access to own records, pp. 3, 6 | Consent, object/company authorization, cache and snapshot checks | Consents, publication, hidden organizations, history, and access checks implemented; no match snapshots |
|
||||
| FSP ID and missing history, pp. 2, 6 | External identity and fixture provider; empty history allowed | Real API unknown |
|
||||
| Real FSP integration | Port and separate DTO until API is supplied | Not implemented |
|
||||
| Recurring assessments, p. 3 | Consent, scheduled worker job, freshness signal | After MVP |
|
||||
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
# Lincodex MVP: submission package
|
||||
|
||||
Verified commit: `c9f029471ed78ce5ec4583009abdc5a4c8c3bd97` (branch dev, 2026-10-10).
|
||||
|
||||
This document describes what the minimal release contains, how to run it, what limits the demonstration category, what is not implemented, and how the release was checked. Details live in the guides: [ARCHITECTURE](ARCHITECTURE.md), [DEPLOY](DEPLOY.md), [TESTING](TESTING.md), [SECURITY](SECURITY.md), [COMPANY_QUOTAS](COMPANY_QUOTAS.md), and the [frontend guide](../../frontend/README.en.md). The HTTP API contract is in [api/](../../api/README.en.md). The statements below are derived from the code, the contract, and these guides; planned behavior is kept apart from working behavior.
|
||||
|
||||
## 1. What is implemented
|
||||
|
||||
### Registration and sign-in
|
||||
|
||||
- Registration of a candidate and an employer with the C1 consent. The address is confirmed with a link from the email or with a six-digit code from the same email; after confirmation, sign-in returns the user to the saved step. See [registration and confirmation](ARCHITECTURE.md#registration-email-verification-and-resend).
|
||||
- Email is sent only with `EMAIL_PROVIDER=resend`. With `disabled`, registration is accepted but there is no way to confirm the address, and sign-in answers 403 `email_not_verified`. The prepared accounts of the demo stand are confirmed in advance. See [mail](DEPLOY.md#2-mail-resend-or-disabled).
|
||||
|
||||
### Candidate
|
||||
|
||||
- Consents C1-C5 in settings. C3 allows automatic categorization; without it, a manual assessment can be requested through a support case.
|
||||
- The profile is filled in manually, step by step, without a resume and without an FSP ID. The questionnaire holds specializations and self-assessment. The home page shows the next step. See [candidate profile](ARCHITECTURE.md#candidate-profile).
|
||||
- Skill assessment in two modes (see [assessment](ARCHITECTURE.md#assessment-and-grade-verification)):
|
||||
- the full `demo_basic` Backend Junior with Go test: 25 tasks from a synthetic bank, a 72-hour window, two work sessions, no practice. The result is compared with the pass mark of the policy version; on the demo stand a passed test gets a category with the basis `synthetic_demo`, otherwise the result is `not_confirmed`;
|
||||
- the `demo_express` test: three tasks; it never assigns a grade, a category, a percentile, or evidence and does not appear in the result history.
|
||||
- Results, history, and skill evidence are available to the candidate; the declared grade is always kept apart from the confirmed one. See [evidence](ARCHITECTURE.md#skill-evidence).
|
||||
|
||||
### Publication and visibility
|
||||
|
||||
- The anonymous card is published only after an explicit C2 and carries no name, contact, or salary amount. The candidate sees a preview built from the same response that the card for organizations uses.
|
||||
- Search status, hiding of individual organizations, change history, and the history of card views and contact reads. A card is shown to organizations only in a group of at least five. See [visibility](ARCHITECTURE.md#candidate-visibility).
|
||||
|
||||
### Employer
|
||||
|
||||
- Organizations (one account can own several), a company profile, and a step-by-step need with a salary range. A need stores requirement versions; a search by a version does not change after an edit. See [organizations](ARCHITECTURE.md#organizations-and-memberships).
|
||||
- Candidate search by a need or by the bank with filters: specialization, confirmed and declared grade, confirmation status, stack, work format, and salary compatibility. The result is split into the groups `main`, `near`, and `unconfirmed`, and the server builds the explanation (score components and unknown flags).
|
||||
- The baseline match works without ML: semantic similarity is a neutral 0.5 marked with the flag `ml_unavailable`; for a cohort below 30 the flag `cohort_below_30` is added. See [matching and explanations](ARCHITECTURE.md#matching-and-explanations).
|
||||
|
||||
### Invitations and contacts
|
||||
|
||||
- The organization creates a draft from a search result, changes the terms with versions, and sends the invitation with a salary range in rubles. Sending spends one place of the weekly quota; a pending limit applies per need, a pair pause applies after a decline, and an unanswered invitation expires at its deadline. See [drafts](ARCHITECTURE.md#invitation-drafts), [sending](ARCHITECTURE.md#sending-invitations), and [limit and expiry](ARCHITECTURE.md#pending-limit-cooldown-and-expiry).
|
||||
- A delivered invitation reaches the candidate inbox. The candidate marks it viewed, declines it, or accepts it with the C4 consent and a choice of contact fields. See [view and decline](ARCHITECTURE.md#candidate-view-and-decline) and [acceptance](ARCHITECTURE.md#candidate-acceptance).
|
||||
- Acceptance creates a contact grant for exactly this pair. The organization reads the chosen fields on the invitation page, and every read checks the grant and the visibility again. Revoking C4, revoking C2, closing the publication, and hiding the organization close the read at once; republishing does not reopen a closed grant. See [contact reads and revocation](ARCHITECTURE.md#contact-reads-and-revocation).
|
||||
|
||||
### Company isolation and holdings
|
||||
|
||||
- Organization operations answer a foreign identifier with the same refusal as for a random identifier. Search, invitations, and contact reads are available only to the owner of the organization.
|
||||
- Organizations of one account form a holding: E0 companies share common quotas (in the demonstration policy, 10 invitations per 7 days and 50 unique card views per 24 hours). The number of organizations per account is not limited. See [COMPANY_QUOTAS](COMPANY_QUOTAS.md#holding-pool).
|
||||
|
||||
### Notifications and mail
|
||||
|
||||
- An inbox in both cabinets; the only product source is a delivered invitation. The entry appears through the outbox, the relay, and Kafka after the commit, not inside the sending transaction. See [internal notifications](ARCHITECTURE.md#internal-notifications).
|
||||
- The invitation email goes through the outbox and the delivery consumer, and a separate notification loop (a worker in the backend process) sends it; before each send it checks the recipient rights again and leaves a quota reserve for service mail. The body is neutral and holds no contacts. See [sending product notifications](ARCHITECTURE.md#sending-product-notifications).
|
||||
- Support cases in both cabinets.
|
||||
|
||||
### Privacy guarantees
|
||||
|
||||
- Before the C4 record and the grant, the organization receives no contacts; cards, search results, invitation lists, and notifications contain no email, phone, or name.
|
||||
- The server log, outbox payloads, inbox rows, and mail requests carry no contact or profile values (checked by the isolation integration test, see section 5).
|
||||
- Organization responses contain no PDFs and no stored search snapshots: there are no such operations.
|
||||
|
||||
## 2. How to run
|
||||
|
||||
Run all commands from the repository root. You need Docker with Compose, GNU make, python3, and openssl; no GPU or external keys are required. Full instructions: [quick start](DEPLOY.md#running-the-mvp-quick-start).
|
||||
|
||||
### Working stand
|
||||
|
||||
cp .env.example .env # replace every replace-this-... value and set IDENTITY_KEY_SECRET
|
||||
make -C deploy config
|
||||
make -C deploy up
|
||||
curl http://localhost:8080/api/v1/healthz
|
||||
|
||||
Open http://localhost:8080 (the value of `APP_PUBLIC_URL`). For email, set `EMAIL_PROVIDER=resend`, `RESEND_API_KEY`, and `EMAIL_FROM` in the server environment. A clean stand holds migrations and the starting policy; operator steps (`DATABASE_URL` is required):
|
||||
|
||||
1. Publish the matching section; without it the search answers 500: `make -C backend policy-publish ARGS='matching --actor operator:<handle>'`. See [match search policy](DEPLOY.md#match-search-policy-on-a-stand).
|
||||
2. For a passed full test to receive the demonstration category, set `ASSESSMENT_DEMO_CATEGORIES_ENABLED=true`, restart the backend, and attest the category opening with `make -C backend assessment-category-attest ARGS='attest --specialization backend --grade intern --task-language go --actor operator:<handle>'`. Publishing a new policy version requires a new opening and a new attestation, so do step 1 before candidates start attempts. See [demonstration categories](DEPLOY.md#demonstration-categories-on-a-stand).
|
||||
|
||||
The task bank is not loaded on the core stand, and the DEPLOY guide describes loading it only as part of the demo stand seed, so a test cannot be started on the core stand. Use the demo stand to show the full path.
|
||||
|
||||
### Demo stand and the jury route
|
||||
|
||||
make -C deploy demo-seed DEMO_MODE=isolated
|
||||
|
||||
The command starts a separate project at http://localhost:8090, publishes the policy with the matching section, loads the synthetic bank, attests the category, and creates the accounts `candidate@`, `prepared-1@` to `prepared-6@`, `employer-alpha@`, and `employer-beta@` in the domain `demo.lincodex.test`; the password comes from `deploy/demo/demo.env` or `demo.env.example`. The jury guide is at http://localhost:8090/demo; it takes eight minutes and exists only in the build of this stand. The route: the express and full tests of the candidate, prepared candidates with published cards, a need and a search by the owner of "Alpha", an invitation, acceptance with C4, and a contact read. See [demo stand](DEPLOY.md#3-demo-stand), [route](DEPLOY.md#4-demonstration-route), and [isolated stand](DEPLOY.md#isolated-demo-stand). Reset: `make -C deploy demo-reset DEMO_MODE=isolated` (it refuses when the stand holds ordinary accounts).
|
||||
|
||||
### Restoring from a release manifest
|
||||
|
||||
make -C deploy release-build
|
||||
make -C deploy release-smoke
|
||||
make -C deploy release-e2e
|
||||
make -C deploy release-manifest RELEASE_ID=<id>
|
||||
make -C deploy release-up RELEASE_ID=<id>
|
||||
make -C deploy release-manifest-verify RELEASE_ID=<id> RELEASE_VERIFY_PROJECT=<project>
|
||||
make -C deploy demo-seed DEMO_MODE=isolated RELEASE_ID=<id>
|
||||
|
||||
The manifest is immutable: it pins the sources, lockfiles, Compose files, and image IDs, and `release-up` starts those images without building or pulling and checks the hashes. A manifest is published only for a clean tree and after successful smoke and E2E runs on those images. `release-manifest-verify` compares the running containers with the manifest. A demo stand restored from a manifest has no `/demo` guide because it uses the frontend of the main release. The assessment bank is not snapshotted in the manifest (`product_data_status` is `partial`). See [release manifest](DEPLOY.md#release-manifest).
|
||||
|
||||
## 3. Limits of the demonstration category
|
||||
|
||||
- The task bank is small and synthetic: 25 families for the full test and three for the express test. The families go through the regular publication pipeline with author and reviewer labels, but their content did not receive a subject-matter review.
|
||||
- Thresholds are not calibrated, no percentile is computed, and there is no adaptive test. The result shows the mechanics, not a measured qualification.
|
||||
- In the API the category basis is `synthetic_demo`, described in the contract as a demonstration category that is not a validated measurement. By the product owner's decision the interface shows it as an ordinary confirmation (the label "Test result"). The API and this documentation keep the basis.
|
||||
- The express test assigns no grade under any settings.
|
||||
- The consent texts C1-C5 are published by migrations as `demo`, without legal review. Do not register real people on the demo stand.
|
||||
|
||||
## 4. What is not implemented
|
||||
|
||||
The following belongs to the full product and does not work in this release:
|
||||
|
||||
- coding practice (a sandbox) and an adaptive test;
|
||||
- the final bargaining round and counter-offers: no operation creates the `counter` state, and a salary raise answers 501 `not_implemented`;
|
||||
- interview scheduling and reminders;
|
||||
- withdrawal of an invitation by the organization and cancellation by the candidate: both operations answer 501;
|
||||
- roles other than the owner and need assignments: only the owner of an organization can search, invite, and read contacts;
|
||||
- PDF documents and stored search snapshots;
|
||||
- category recommendations for a need: the need response reports the state `pending` or `not_available` with an empty list;
|
||||
- enabled ML inference: the ML service starts separately without a model, and the backend does not call it;
|
||||
- FSP integration: there is no mode, fixture provider, or call to an external API;
|
||||
- the SMTP transport: selecting `EMAIL_PROVIDER=smtp` stops the backend at startup;
|
||||
- ATS integration;
|
||||
- password reset, resume upload and parsing, and emails for events other than confirmation and a new invitation.
|
||||
|
||||
## 5. How it was verified
|
||||
|
||||
Acceptance result on the verified commit (2026-10-10): `make verify` passed, including 110 integration tests and the technical smoke; `make -C deploy test-e2e-registration` - 95 passed, 1 skipped; `make -C deploy test-e2e` - 64 passed, 32 skipped; `make -C security install test check` and `make security-images` passed with no blocking findings (the scanners ran in a Linux container, as in CI, because their installer supports only Linux; the exception for CVE-2026-93687 is valid until 2026-10-19). The boundaries of every check are described in [TESTING](TESTING.md#commands).
|
||||
|
||||
| Check | What it proves |
|
||||
| --- | --- |
|
||||
| `make verify` | Contract generation without drift, formatting, linters, types, build, Compose, documentation, backend with the race detector, integration tests on PostgreSQL, Redis, SeaweedFS, and Kafka, and a technical smoke |
|
||||
| `make -C deploy smoke` | Stack startup, dependency readiness, and dependency failures; it does not check a business flow |
|
||||
| `make -C deploy test-e2e` | The Playwright suite on a throwaway stack with mail disabled, including `mail-unavailable.spec.ts`: the user sees that the email may arrive later and cannot sign in before confirmation |
|
||||
| `make -C deploy test-e2e-registration` | Registration, confirmation by link and by code, and sign-in through the local Resend-compatible inbox, and within it `acceptance-path.spec.ts` |
|
||||
| `acceptance-path.spec.ts` | The minimal path on the real backend: five candidates, the full test with a `synthetic_demo` category, publication, a need, a search with an explanation and a filter, invitations, acceptance with C4, a contact read, a decline, C2 revocation, and no duplicates after a refresh and a double acceptance. See [the path to contacts](TESTING.md#minimal-path-from-registration-to-disclosed-contacts) |
|
||||
| `TestCompanyIsolationAndRevocationOverHTTP` | Isolation of companies and candidates, immediate closure after hiding and after revoking C4 and C2, and no contacts in the log, outbox, inbox, and mail requests. See [organization tests](TESTING.md#organization-tests) |
|
||||
| `TestInvitationNoticesSurviveRelayAndConsumerRestarts` | Exactly one notice and one email per recipient after relay and consumer restarts and a lost offset |
|
||||
| `TestHoldings`, `TestCompanyQuota` | The shared E0 quota pool inside a holding and no overrun under concurrent reservations |
|
||||
| `make -C security check`, `make -C security images` | Dependency vulnerabilities, secrets, dangerous constructs, and images; see [SECURITY](SECURITY.md) |
|
||||
| `make -C deploy check-demo`, `make docs-check` | Guards of the demo stand targets and the documentation structure |
|
||||
| `make -C deploy release-smoke`, `release-e2e` | The same smoke and browser suite on the release images; a passing run produces evidence for the manifest |
|
||||
|
||||
The checks do not prove: assessment calibration, match accuracy, email delivery through the real Resend, operation behind HTTPS, and production load.
|
||||
+19
-15
@@ -4,9 +4,13 @@
|
||||
|
||||
## Что работает сейчас
|
||||
|
||||
Репозиторий содержит Go HTTP-сервис с проверкой PostgreSQL, Redis и SeaweedFS, адаптеры кеша и S3-хранилища, React-каркас интерфейса с публичными страницами и двумя оболочками кабинетов с экранами-заготовками, отдельный Python ML-сервис с health/readiness маршрутами, два OpenAPI-контракта, codegen, Compose и конфигурацию мониторинга. Публичный health endpoint API находится под /api/v1/healthz. /healthz используется для проверки веб-контейнера. Внутренний /readyz Go проверяет PostgreSQL, Redis и доступность bucket SeaweedFS; /readyz ML проверяет готовность модели; ML отвечает 503 на readiness, пока inference не готов. Метрики Go доступны по стандартному /metrics на внутреннем порту.
|
||||
Репозиторий содержит Go HTTP-сервис с проверкой PostgreSQL, Redis и SeaweedFS, адаптеры кеша и S3-хранилища, React-интерфейс с публичными страницами и двумя кабинетами (рабочие экраны описанных ниже сценариев), отдельный Python ML-сервис с health/readiness маршрутами, два OpenAPI-контракта, codegen, Compose и конфигурацию мониторинга. Публичный health endpoint API находится под /api/v1/healthz. /healthz используется для проверки веб-контейнера. Внутренний /readyz Go проверяет PostgreSQL, Redis и доступность bucket SeaweedFS; /readyz ML проверяет готовность модели; ML отвечает 503 на readiness, пока inference не готов. Метрики Go доступны по стандартному /metrics на внутреннем порту.
|
||||
|
||||
Регистрация, подтверждение email, вход и базовые операции с текущей сессией работают через API backend. Во frontend реализованы регистрация, подтверждение, вход и продолжение по серверному шагу сценария; локальный браузерный E2E проверяет кандидата и работодателя. Настройки согласий и создание/редактирование организаций работают через backend API. Внутренний inbox уведомлений в обоих кабинетах показывает и отмечает уведомления; первый продуктовый источник - отправленное приглашение (см. [Внутренние уведомления](#внутренние-уведомления)). Сторона организации в черновике приглашения (список, создание, чтение и изменение с версиями условий), отправка во входящие кандидата и список приглашений кандидата работают через backend API; ответы кандидата не реализованы (см. [Черновики приглашений](#черновики-приглашений) и [Отправка приглашений](#отправка-приглашений)). Остальные продуктовые сценарии пока не реализованы: роли, профили, тесты, грейды, ответ на приглашения, загрузка и анализ резюме, PDF и интеграция с ФСП. Детерминированный базовый подбор по банку, видимому организации, работает через backend API без ML, данных соревнований, снимков и приглашений (см. [Подбор и объяснение](#подбор-и-объяснение)). ML не возвращает вымышленные результаты. Проверки доступности и технический smoke не подтверждают бизнес-сценарий.
|
||||
Регистрация, подтверждение email, вход и базовые операции с текущей сессией работают через API backend и экраны frontend; локальный браузерный E2E проверяет кандидата и работодателя. Через backend API и экраны кабинетов работают также согласия C1-C5 и запрос удаления аккаунта; организации, членства и потребности работодателя; ручной профиль кандидата и анкета со специализациями и самооценкой; публичный каталог специализаций; попытки оценки (создание, ответы, завершение, история результатов, серверные сигналы и доказательства навыков), причем банк заданий и категории демонстрационные и неоткалиброванные; настройки приватности и публикация анонимной карточки; внутренний inbox уведомлений в обоих кабинетах (см. [Внутренние уведомления](#внутренние-уведомления)); обращения в поддержку. Запрос ручной оценки реализован как обращение в поддержку этого типа (`usecase/supportcase`, `frontend/src/features/request-manual-assessment`): он не зависит от согласия C3, не создает попытку, не меняет категорию и только ставит обращение в очередь эксперта; операций эксперта для этой очереди в API нет. Детерминированный базовый подбор по банку, видимому организации, работает через backend API без ML, данных соревнований и снимков поиска (см. [Подбор и объяснение](#подбор-и-объяснение)); рекомендации категорий для потребности не вычисляются, ответ возвращает пустой список (`domain/need_response.go`).
|
||||
|
||||
Приглашения реализованы сквозным путем (см. [Черновики приглашений](#черновики-приглашений), [Отправка приглашений](#отправка-приглашений), [Просмотр и отказ кандидата](#просмотр-и-отказ-кандидата), [Принятие кандидатом](#принятие-кандидатом), [Предел ожидающих, пауза и истечение](#предел-ожидающих-пауза-и-истечение) и [Чтение контактов и отзыв](#чтение-контактов-и-отзыв)): организация создает и изменяет черновик с версиями условий и отправляет его; приглашение попадает во входящие кандидата и порождает внутреннее уведомление; кандидат читает приглашение, отмечает просмотр, отказывается или принимает его с согласием C4 на выбранные контакты; после принятия организация читает переданные контакты, а кандидат может отозвать контактное разрешение. Действуют предел ожидающих приглашений на потребность, пауза пары организации и кандидата после отказа и истечение приглашения в срок ответа. Во frontend есть составление приглашения из результата поиска, список приглашений организации (`pages/employer-invitations`) и входящие кандидата. Операции отзыва приглашения организацией (`WithdrawOrganizationInvitation`), отмены участия кандидатом (`CancelMyInvitation`) и повышения вилки зарплаты (`RaiseOrganizationInvitationSalary`) есть в контракте, но не реализованы и отвечают 501 `not_implemented`.
|
||||
|
||||
Не реализованы: встречные предложения и этапы после принятия (собеседования), сброс пароля, загрузка и разбор резюме, PDF, снимки и уточнение поиска, ML inference и смысловой поиск (backend не вызывает ML-клиент), интеграция с ФСП (каталог `adapter/secondary/fsp` пуст), транспорт SMTP (при `EMAIL_PROVIDER=smtp` backend не стартует; письма отправляет только Resend), генерация PDF (каталог `adapter/secondary/pdf` пуст) и адаптеры ATS. ML не возвращает вымышленные результаты. Проверки доступности и технический smoke не подтверждают бизнес-сценарий.
|
||||
|
||||
Подробности запуска, дерева исходников и проверки собраны в [руководстве разработки](DEVELOPMENT.md), [руководстве по развертыванию](DEPLOY.md) и [руководстве по проверкам](TESTING.md).
|
||||
|
||||
@@ -573,7 +577,7 @@ backend/
|
||||
middleware/ журнал и метрики запросов по шаблону маршрута
|
||||
observe/ наблюдения уровня запроса, например код problem
|
||||
problem/ ответы об ошибках по RFC 9457
|
||||
v1/ написанный вручную health endpoint
|
||||
v1/ вручную написанные обработчики операций контракта
|
||||
router.go сборка chi router
|
||||
adapter/secondary/
|
||||
argon2id/ hasher паролей Argon2id с бюджетом памяти
|
||||
@@ -601,7 +605,7 @@ backend/
|
||||
|
||||
Доменные типы лежат непосредственно в `backend/internal/domain/`: `user.go`, `candidate.go` и другие файлы по мере определения моделей. Вложенных каталогов по сущностям или модулям здесь нет. Первый тип - `DomainEvent` в `domain_event.go`: проверенное событие, которое транзакция записывает в outbox. Типы хранения identity лежат в `email_address.go`, `secret_token.go`, `user.go`, `email_token.go` и `session.go`; нормализованный пароль - в `password.go`. Типы журнала согласий лежат в `consent.go`. Типы организации, проверки и членства лежат в `organization.go` и `membership.go`. Продуктовая политика и ее версии лежат в `policy.go`, `policy_document.go`, `policy_version.go` и `policy_demo.go`.
|
||||
|
||||
За пределами реализованных потоков identity и согласий доменные типы и usecase других продуктовых сценариев пока не реализованы. Адаптеры SMTP и FSP, а также продуктовые задания worker остаются планом. `main.go` запускает bootstrap и обрабатывает ошибку процесса. Для публичного generated transport выбран ogen v1.24.0, контракты используют OpenAPI 3.2.0. Проверяется только применяемое подмножество, не вся спецификация.
|
||||
За пределами реализованных потоков (identity, согласия, организации, профиль и анкета, оценка, потребности и подбор, приглашения, обращения в поддержку, уведомления) usecase документов и достижений ФСП пока не реализованы. Адаптеры SMTP и FSP остаются планом; продуктовые задания worker сейчас только расчет полосы проверки оценки и истечение приглашения в срок ответа. `main.go` запускает bootstrap и обрабатывает ошибку процесса. Для публичного generated transport выбран ogen v1.24.0, контракты используют OpenAPI 3.2.0. Проверяется только применяемое подмножество, не вся спецификация.
|
||||
|
||||
Это компактная карта, а не обещание, что все запланированные продуктовые пакеты уже существуют. Сейчас Go-код включает health usecase/adapters, generated API clients, bootstrap с миграциями при старте, PostgreSQL health query, транзакционную запись outbox, relay outbox, который публикует зафиксированные события в Kafka через адаптер franz-go, runtime обработчиков событий с обработчиками `notification_delivery` и `notification_inbox`, внутренний inbox уведомлений с операциями списка и прочтения, runtime заданий по сроку (`worker/jobrunner`) без зарегистрированного продуктового вида задания, usecase регистрации, повторной отправки, подтверждения и входа identity, PostgreSQL сессии и security boundary для всех операций, защищенных API-контрактом, usecase согласий, который записывает C1 в потоке регистрации, версионированное хранилище политики с публикацией и начальным заполнением демонстрационной политики при старте, порт `PasswordHasher` с адаптером Argon2id и проверкой пароля в регистрации, подтверждении и входе, Redis cache adapter, S3-адаптер SeaweedFS с общим закрытым файловым слоем поверх него, порт `MailSender` с транспортами `disabled` и Resend, renderer шаблонов писем и worker отправки служебной почты identity для регистрации и повторной отправки. Профили, резюме, оценивание, приглашения, продуктовые виды заданий, файловые сценарии, транспорт SMTP и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей.
|
||||
|
||||
@@ -658,7 +662,7 @@ contact_grant относится к паре кандидат-компания
|
||||
|
||||
### Банк заданий оценки
|
||||
|
||||
Реализованы хранилище и загрузчик, а не функция для кандидата: миграция `backend/db/migrations/00011_create_assessment_bank.sql`, запросы в `backend/db/queries/assessment_bank.sql`, доменные типы в `backend/internal/domain/` (`assessment_family.go`, `assessment_generator.go`, `assessment_algorithms.go`), порт `outbound.AssessmentBankRepository` (`port/outbound/assessment_bank.go`, доступен через `UnitOfWork.AssessmentBank()`), адаптер на sqlc в `backend/internal/adapter/secondary/postgres/assessment_bank.go` и загрузчик в `backend/internal/usecase/assessment/` (`Bank`, `Bundle`). Bootstrap и HTTP API его пока не вызывают, и ни одна категория не открыта.
|
||||
Реализованы хранилище и загрузчик, а не функция для кандидата: миграция `backend/db/migrations/00011_create_assessment_bank.sql`, запросы в `backend/db/queries/assessment_bank.sql`, доменные типы в `backend/internal/domain/` (`assessment_family.go`, `assessment_generator.go`, `assessment_algorithms.go`), порт `outbound.AssessmentBankRepository` (`port/outbound/assessment_bank.go`, доступен через `UnitOfWork.AssessmentBank()`), адаптер на sqlc в `backend/internal/adapter/secondary/postgres/assessment_bank.go` и загрузчик в `backend/internal/usecase/assessment/` (`Bank`, `Bundle`). Bootstrap создает `assessment.NewBank` один раз (`bootstrap/catalog.go`, отдельный небольшой пул PostgreSQL) и передает его `CatalogHandler`; HTTP использует только чтение `Bank.SpecializationAvailability` для публичного каталога специализаций (`GET /api/v1/specializations`). Операции загрузчика (`ImportBundle`, `PublishFamily`, `RetireFamily`, `OpenCategory`) HTTP не вызывает: их вызывают команда демонстрационного seed (`adapter/primary/cli/demoseed`, `usecase/demoseed`) и `cmd/questionnaire-fixture`, поэтому в сборке без seed ни одна категория не открыта. Попытки оценки работают через отдельный `AttemptService`, который читает банк через репозиторий `UnitOfWork.AssessmentBank()`, а не через `Bank`.
|
||||
|
||||
- Версия семейства. Одна строка `assessment_families` - одна версия одного семейства (`family_key`, `version`): категория, специализация (область внутри категории), название, автор (`ai:<name>` или `operator:<handle>`), рецензент (`operator:<handle>` или NULL), `review_status` (`pending`, `approved`, `rejected`), генератор по seed, ключ ответа, рубрика, хеш содержимого с его `hash_scheme`, жизненный цикл (`draft`, `published`, `retired`) и операторы и время публикации и вывода из обращения. Рецензент не бывает автором, а рецензия остается `pending`, пока рецензента нет (CHECK-ограничения; домен применяет те же правила). Рецензент в пакете и оператор публикации - заявленные значения, а не аутентифицированные личности, пока нет учетных записей рецензентов и операторов.
|
||||
- Неизменяемость. Содержимое сохраненной версии не меняется: триггер `assessment_families_guard_update` отклоняет любой UPDATE, который меняет колонки кроме колонок жизненного цикла (`lifecycle`, `published_at`, `published_by`, `retired_at`, `retired_by`), а `assessment_families_refuse_removal` отклоняет DELETE и TRUNCATE, все с SQLSTATE 23000 и именем ограничения `assessment_families_immutable`, которое адаптер преобразует в `outbound.ErrAssessmentFamilyImmutable`. Жизненный цикл идет только вперед (draft, published, retired), время ставит триггер и он же сохраняет публикатора при выводе из обращения, а версия публикуется только с одобренной рецензией рецензента (`assessment_families_published_requires_review`). Изменение - это новая версия со следующим номером: загрузчик принимает версию 1 для нового семейства и преемника последней версии для существующего. Черновик с рецензией `pending` никогда не одобряется на месте: рецензия записывается импортом новой версии семейства, которая ее несет, а версия `pending` остается неопубликованным черновиком. Домен пересчитывает хеш содержимого при чтении строки и возвращает `ErrAssessmentFamilyIntegrity`, если строку изменили вне приложения. Хеш - это SHA-256 канонического JSON-документа, который содержит содержимое без имени пакета, ID, жизненного цикла и полей публикации. Колонка `hash_scheme` (smallint с CHECK известных значений, одна из неизменяемых колонок) называет формат: домен проверяет строку хеш-функцией той схемы, с которой строка сохранена, поэтому следующая схема (новая функция и новое значение CHECK, а не правка схемы 1) проверяет новые строки и не ломает старые, а строка с неизвестной схемой отклоняется; тесты проверяют строку ее собственной схемой и фиксируют хеш схемы 1 для заданного входа. Как и для `policy_versions`, роль-владелец таблицы все еще может отключить триггеры.
|
||||
@@ -669,7 +673,7 @@ contact_grant относится к паре кандидат-компания
|
||||
- Жизненный цикл и загрузчик. `Bank.ImportBundle` сохраняет все семейства пакета как черновики в одной транзакции и никогда не публикует, что бы ни говорила рецензия; повторный импорт того же пакета, в том числе одновременный, сообщает версии как неизмененные. `Bank.PublishFamily` и `Bank.RetireFamily` принимают оператора и отказывают с причиной (`reviewer_missing`, `review_not_approved`, `not_draft`, `not_published`, `newer_version_published`); отказ - это `*domain.AssessmentRefusalError` с причиной, а sentinel-ошибки гонки, которую решила база (шаг жизненного цикла проиграл другому, нет одобренной рецензии, недостаточное покрытие), становятся теми же отказами. Публикация, вывод из обращения и открытие сначала берут транзакционную advisory-блокировку категории, поэтому выполняются по очереди в пределах категории; `LockCategory` работает только внутри транзакции (репозиторий единицы работы берет блокировку, автономное хранилище возвращает `ErrAssessmentLockOutsideTransaction`).
|
||||
- Доступность категории. `Bank.OpenCategory` записывает открытие в `assessment_category_openings` под указанной версией политики (`policy_versions.id`); отказ `grading_policy_missing` для отсутствующей или неизвестной ссылки и `grading_policy_not_current`, если версия не действует сейчас для семейства `product`; "сейчас" берется по часам базы данных в той же транзакции (`clock_timestamp()`), теми же часами, которые ставят время вступления в силу версии политики, поэтому банк не задает собственных порогов и часы приложения в решении не участвуют. Число различных опубликованных семейств, которое нужно категории, читается из этой политики: `RequiredPublishedAssessmentFamilies` возвращает `assessment.stop_rule.max_scored_items` плюс `assessment.stop_rule.seed_items`. Это правило принято владельцем как продуктовое решение 2026-10-06. Причина: одно семейство дает в попытку не больше одного задания, поэтому полная адаптивная попытка, которая может дойти до максимума оцениваемых заданий и еще несет seed-задания, не может остаться без семейств. Триггер вставки сам выводит то же число из сохраненного документа политики (те же два JSON-пути; интеграционный тест держит SQL и домен равными) и проверяет оба значения как неотрицательные целые не длиннее четырех цифр до приведения типа, поэтому некорректный документ, записанный в обход приложения, дает отказ `assessment_category_openings_policy_thresholds`, а не ошибку приведения. Триггер также считает опубликованные семейства, а CHECK-ограничение отклоняет строку, если их меньше, поэтому вызов в обход usecase не откроет категорию с заниженным требованием. Открытие хранит версию политики, оператора (`operator:<handle>`), требуемое и посчитанное число семейств и не редактируется. Доступность живая: `Bank.CategoryAvailability` возвращает текущее открытие, только пока опубликованных сейчас семейств все еще не меньше требования открытия, иначе отказ `coverage_insufficient` (или `ErrAssessmentCategoryNotOpen`, если открытия нет), поэтому вывод из обращения может закрыть категорию. Он же отказывает с `grading_policy_not_current`, если версия политики открытия больше не действует, поэтому смена политики требует нового открытия. Таблица проверяет ссылку на политику в триггере, а не внешним ключом, потому что PostgreSQL отклоняет TRUNCATE таблицы, на которую есть ссылка, раньше, чем триггер `policy_versions` успевает отклонить его своей ошибкой. `ListFamilies` листает по курсору (ключ, версия) с жестким пределом 200.
|
||||
- Демонстрационный пакет. `backend/testdata/assessment/backend_demo_bundle.json` содержит четыре оригинальные практические задачи категории `backend`. Это черновик, созданный ИИ (автор `ai:claude-draft`), с рецензией `pending` и без рецензента, поэтому загрузчик импортирует их черновиками, публикация отклоняется, а категория остается закрытой. Условия, решения, рубрики и сложность никто из людей не проверял; пакет не заявляет ни валидности, ни калибровки. Настоящая рецензия порождает новую версию семейств с одобрением.
|
||||
- Не реализовано: авторство и рецензирование настоящего банка, blueprint по специализации и уровню, выбор задач для попытки, хранение попыток и ответов, проверка ответов, HTTP- или административный интерфейс, аутентифицированные личности рецензентов и операторов и подключение загрузчика в bootstrap.
|
||||
- Не реализовано: авторство и рецензирование настоящего банка, blueprint по специализации и уровню, HTTP- или административный интерфейс загрузчика и аутентифицированные личности рецензентов и операторов (хранение попыток, ответы и их проверка реализованы отдельными операциями оценки, не загрузчиком).
|
||||
|
||||
### Серверные сигналы оценки и полоса проверки
|
||||
|
||||
@@ -980,7 +984,7 @@ Middleware `backend/internal/adapter/primary/http/company_context.go` прове
|
||||
|
||||
### Черновики приглашений
|
||||
|
||||
Реализовано: сторона организации в черновике приглашения, то есть `ListOrganizationInvitations`, `CreateOrganizationInvitation`, `GetOrganizationInvitation` и `UpdateOrganizationInvitation` ([контракт](../../api/README.md#приглашения-и-контактные-разрешения)). Кандидат черновик не видит: входящей записи, события и списания квоты нет; отправка описана в [Отправке приглашений](#отправка-приглашений). Отзыв, повышение вилки, чтение контактов и отмена участия после общих проверок по-прежнему отвечают 501; чтение, просмотр, отказ и принятие кандидата описаны в [Просмотре и отказе кандидата](#просмотр-и-отказ-кандидата) и [Принятии кандидатом](#принятие-кандидатом). Код: `domain/salary_range.go`, `domain/invitation_terms.go`, `domain/invitation.go`, `usecase/invitation/`, `adapter/primary/http/v1/invitation.go`, адаптер PostgreSQL `adapter/secondary/postgres/invitations.go` с `db/queries/invitations.sql` и миграция `00037_create_invitations.sql`.
|
||||
Реализовано: сторона организации в черновике приглашения, то есть `ListOrganizationInvitations`, `CreateOrganizationInvitation`, `GetOrganizationInvitation` и `UpdateOrganizationInvitation` ([контракт](../../api/README.md#приглашения-и-контактные-разрешения)). Кандидат черновик не видит: входящей записи, события и списания квоты нет; отправка описана в [Отправке приглашений](#отправка-приглашений). Отзыв, повышение вилки и отмена участия после общих проверок по-прежнему отвечают 501; чтение контактов описано в [Чтении контактов и отзыве](#чтение-контактов-и-отзыв); чтение, просмотр, отказ и принятие кандидата описаны в [Просмотре и отказе кандидата](#просмотр-и-отказ-кандидата) и [Принятии кандидатом](#принятие-кандидатом). Код: `domain/salary_range.go`, `domain/invitation_terms.go`, `domain/invitation.go`, `usecase/invitation/`, `adapter/primary/http/v1/invitation.go`, адаптер PostgreSQL `adapter/secondary/postgres/invitations.go` с `db/queries/invitations.sql` и миграция `00037_create_invitations.sql`.
|
||||
|
||||
Таблицы:
|
||||
|
||||
@@ -1144,7 +1148,7 @@ Go экспортирует стандартные Go/process метрики и
|
||||
- API: `lincodex_http_requests_total{method,route,status}`, `lincodex_http_request_duration_seconds{method,route,status_class}` и `lincodex_http_problems_total{route,code}`. `route` - шаблон маршрута chi для операционных маршрутов, а под `/api/v1` - шаблон пути OpenAPI найденной операции, например `/api/v1/me/invitations/{invitation_id}`; router находит его через `FindPath` сгенерированного сервера. Путь или метод без операции сохраняет шаблон монтирования `/api/v1/*` или `/api/*`, а путь вне всех маршрутов получает `unmatched`. `status_class` - от `1xx` до `5xx`. `code` - код problem по RFC 9457: `problem.New` записывает его из закрытого каталога через пакет `observe` уровня запроса (`adapter/primary/http/observe/`), middleware учитывает его только для ответа 4xx или 5xx, а адаптер считает код вне своего зеркального списка как `other`. Ошибка без тела problem, например 503 от `/readyz`, учитывается только по статусу. Журнал запросов (`middleware.RequestLog`, заменяет logger из go-httpkit) использует тот же шаблон маршрута и пишет request ID, метод, статус и класс, код problem, задержку, размер ответа и число параметров query, но никогда не пишет исходный путь, ключ или значение query, заголовок, адрес клиента и user agent; `/healthz` и `/readyz` не журналируются.
|
||||
- Outbox и события: метрики relay, обработчиков и заданий по сроку описаны в разделах [Relay outbox](#relay-outbox), [Обработчики событий](#обработчики-событий) и [Задания по сроку](#задания-по-сроку). Отставание outbox показывает `lincodex_outbox_relay_oldest_pending_age_seconds`.
|
||||
- Почта: `lincodex_mail_deliveries{kind,status}` для каждого вида и статусов `pending`, `waiting_quota`, `unknown`, `accepted`, `rejected` и `cancelled`, включая нулевые; `lincodex_mail_sender_running` - 1, пока цикл отправки почты этого процесса работает, и 0 иначе (по процессу, поэтому агрегируйте через `max`; при `EMAIL_PROVIDER=disabled` остается 0, цикл не запускается); `lincodex_notification_sender_running` - то же для цикла уведомлений; `lincodex_mail_delivery_oldest_due_pending_age_seconds`, который считает только служебную почту (`domain.ServiceMailKinds`), поэтому очередь уведомлений никогда не выглядит просроченной; `lincodex_mail_sender_cancelled_total{reason}` - доставки, которые worker отправки завершил без отправки, по закрытому набору причин отмены, включая нулевые; для активного транспорта - `lincodex_mail_quota_used_recipients`, `lincodex_mail_quota_limit_recipients` и `lincodex_mail_quota_provider_exhausted` с `provider` и `window` (`day` или `month`). Sampler в `backend/internal/worker/deliverymetrics/` читает их каждые 30 секунд через собственный pool на одно соединение: `postgres.DeliveryStatisticsStore` агрегирует `deliveries` по виду и статусу, а `MailQuotaUsageReader.Usage` читает текущие окна настроенного аккаунта. Агрегат доставок - запрос sqlc `GetDeliveryStatistics` в `db/queries/delivery.sql`. Запрос сканирует таблицу, что подходит для текущего объема; до миллионов строк нужен индекс или счетчики по статусам. `EMAIL_ACCOUNT` не становится label: это свободный текст оператора, который может назвать человека, а каждый процесс сообщает только свой аккаунт. Все экземпляры сообщают одинаковые значения по всей базе; агрегируйте их через `max`. Неудачное чтение сохраняет прежние значения и пишет в журнал `delivery metrics could not be read; the gauges are stale`; `lincodex_mail_metrics_last_success_timestamp_seconds` показывает последнее чтение, в котором прочитаны все агрегаты (0 от запуска sampler до первого такого чтения), а gauge просрочки появляется только после первого успешного чтения. Счетчика исходов попыток пока нет; исходы показывают состояния доставок, журнал worker отправки и история `delivery_attempts`.
|
||||
- Ответы теста: `lincodex_assessment_answer_saves_total{format,outcome}` с исходами `stored`, `unchanged`, `rejected` и `failed`. PRD 6.6 требует наблюдать сохранение ответов; это понимается как команда ответа теста `SubmitMyAssessmentAnswer`. Команда не реализована, поэтому есть только hook `Metrics.ObserveAssessmentAnswerSave`, и серии не появятся, пока usecase не начнет вызывать его один раз на команду. Значение вне закрытых наборов превращается в `other`. Задержка и ошибки HTTP этой команды уже видны под маршрутом `/api/v1/me/assessment-attempts/{attempt_id}/answers`.
|
||||
- Ответы теста: `lincodex_assessment_answer_saves_total{format,outcome}` с исходами `stored`, `unchanged`, `rejected` и `failed`. PRD 6.6 требует наблюдать сохранение ответов; это понимается как команда ответа теста `SubmitMyAssessmentAnswer`. Команда реализована, но hook `Metrics.ObserveAssessmentAnswerSave` пока никто не вызывает, и серии не появятся, пока usecase не начнет вызывать его один раз на команду. Значение вне закрытых наборов превращается в `other`. Задержка и ошибки HTTP этой команды уже видны под маршрутом `/api/v1/me/assessment-attempts/{attempt_id}/answers`.
|
||||
|
||||
В labels нельзя помещать ID пользователя, кандидата, доставки или запроса, полный URL или query string, адреса и содержимое резюме. Unit-тесты прогоняют настоящий router и каждый hook метрик с fixture email и UUID и падают, если в выдаче есть значение, похожее на email или UUID. JSON dashboards Go runtime, PostgreSQL, Redis, SeaweedFS, Linux и продуктовый Lincodex поддерживаются в проекте; это не импортированные Grafana dashboard IDs. Метрики inference пока не реализованы.
|
||||
|
||||
@@ -1158,19 +1162,19 @@ Go экспортирует стандартные Go/process метрики и
|
||||
|
||||
| Требование ТЗ | Целевое решение | Состояние |
|
||||
| --- | --- | --- |
|
||||
| Два кабинета, email confirmation, с. 3-4 | identity, роли, компания и проверки доступа | Не реализовано |
|
||||
| Резюме вручную или PDF, с. 3 | Ручной профиль обязателен; PDF и ML импорт расширяют его | Не реализовано |
|
||||
| Два кабинета, email confirmation, с. 3-4 | identity, роли, компания и проверки доступа | Реализовано (сброс пароля нет) |
|
||||
| Резюме вручную или PDF, с. 3 | Ручной профиль обязателен; PDF и ML импорт расширяют его | Ручной профиль реализован; PDF и ML импорт не реализованы |
|
||||
| Стандартизированный PDF, с. 3 | PDFRenderer по структурированному профилю, кириллица и права доступа | Не реализовано |
|
||||
| Опрос, грейд, тест и категория, с. 1-3 | assessment, варианты задач, grade history | Не реализовано |
|
||||
| Опрос, грейд, тест и категория, с. 1-3 | assessment, варианты задач, grade history | Реализовано на демонстрационном банке, категории неоткалиброваны |
|
||||
| Сопоставимость тестов и защита от утечек, с. 1-2 | Семейства, blueprint, рубрики, ротация и пилот | Только план |
|
||||
| Не понижать грейд при провале, частота изменений, с. 2-3 | verified/claimed, retry правила, cooldown и eligibility | Только план |
|
||||
| Поиск и объяснение, с. 3-4 | Жесткие фильтры, matching, evidence и score components | Реализован базовый детерминированный поиск; ML, данных соревнований и снимков нет |
|
||||
| Уточнение поиска без потери старой выдачи, с. 4 | Версионные search_run и серверные снимки | Только план |
|
||||
| Приглашение без вакансии, с. 3 | Необязательный vacancy_id | Не реализовано |
|
||||
| Зарплата от-до в RUB, компания и связь, с. 4 | Обязательные границы зарплаты и явный формат периода/налогов | Не реализовано |
|
||||
| Статусы для обеих сторон, с. 4 | State machine и журнал событий | Не реализовано |
|
||||
| Контакты после принятия/отклика, с. 3-4 | contact_grant, отдельные DTO и проверка доступа к файлу | Не реализовано |
|
||||
| Приватность и доступ к своим данным, с. 3, 6 | Согласия, object/company authorization, проверки cache и старых подборок | Требование, реализация отсутствует |
|
||||
| Зарплата от-до в RUB, компания и связь, с. 4 | Обязательные границы зарплаты и явный формат периода/налогов | Реализовано |
|
||||
| Статусы для обеих сторон, с. 4 | State machine и журнал событий | Частично: draft, delivered, viewed, accepted, declined, expired; встречные этапы, отзыв и отмена не реализованы |
|
||||
| Контакты после принятия/отклика, с. 3-4 | contact_grant, отдельные DTO и проверка доступа к файлу | Контакты после принятия реализованы; файлы и отклики кандидата не реализованы |
|
||||
| Приватность и доступ к своим данным, с. 3, 6 | Согласия, object/company authorization, проверки cache и старых подборок | Согласия, публикация, скрытие организаций, история и проверки доступа реализованы; снимков подборок нет |
|
||||
| ФСП ID и отсутствие истории, с. 2, 6 | external identity и fixture provider; пустая история допустима | Реальный API неизвестен |
|
||||
| Интеграция с ФСП | Порт и отдельный DTO до получения схемы API | Не реализовано |
|
||||
| Регулярные задания, с. 3 | Согласие, периодическое задание worker и сигнал свежести | После MVP |
|
||||
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
# MVP Lincodex: пакет сдачи
|
||||
|
||||
Проверенный коммит: `c9f029471ed78ce5ec4583009abdc5a4c8c3bd97` (ветка dev, 10.10.2026).
|
||||
|
||||
Документ описывает, что входит в минимальный выпуск, как его запустить, чем ограничена демонстрационная категория, что не реализовано и чем выпуск проверен. Подробности вынесены в руководства: [ARCHITECTURE](ARCHITECTURE.md), [DEPLOY](DEPLOY.md), [TESTING](TESTING.md), [SECURITY](SECURITY.md), [COMPANY_QUOTAS](COMPANY_QUOTAS.md) и [frontend](../../frontend/README.md). Контракт HTTP API находится в [api/](../../api/README.md). Утверждения ниже выведены из кода, контракта и этих руководств; запланированное отделено от работающего.
|
||||
|
||||
## 1. Что реализовано
|
||||
|
||||
### Регистрация и вход
|
||||
|
||||
- Регистрация кандидата и работодателя с согласием C1. Адрес подтверждается ссылкой из письма или шестизначным кодом из того же письма; после подтверждения вход возвращает пользователя на сохраненный шаг. См. [регистрацию и подтверждение](ARCHITECTURE.md#регистрация-подтверждение-и-повторная-отправка).
|
||||
- Письмо уходит только при `EMAIL_PROVIDER=resend`. При `disabled` регистрация принимается, но подтвердить адрес нечем, и вход отвечает 403 `email_not_verified`. Подготовленные аккаунты демонстрационного стенда подтверждены заранее. См. [почту](DEPLOY.md#2-почта-resend-или-disabled).
|
||||
|
||||
### Кандидат
|
||||
|
||||
- Согласия C1-C5 в настройках. C3 разрешает автоматическую категоризацию; без него доступен запрос ручной оценки через обращение в поддержку.
|
||||
- Профиль заполняется вручную по шагам, без резюме и без ФСП ID. Анкета содержит специализации и самооценку. Главная страница показывает следующий шаг. См. [профиль кандидата](ARCHITECTURE.md#профиль-кандидата).
|
||||
- Проверка навыков в двух режимах (см. [оценивание](ARCHITECTURE.md#оценивание-и-подтверждение-грейда)):
|
||||
- полный тест `demo_basic` Backend Junior с Go: 25 заданий из синтетического банка, срок 72 часа, две рабочие сессии, без практики. Результат сравнивается с порогом версии политики; на демонстрационном стенде пройденный тест получает категорию с основанием `synthetic_demo`, иначе результат `not_confirmed`;
|
||||
- экспресс-тест `demo_express`: три задания; он никогда не назначает грейд, категорию, перцентиль или доказательство и не попадает в историю результатов.
|
||||
- Результаты, история и доказательства навыка доступны кандидату; заявленный грейд всегда отделен от подтвержденного. См. [доказательства](ARCHITECTURE.md#доказательства-навыков).
|
||||
|
||||
### Публикация и видимость
|
||||
|
||||
- Анонимная карточка публикуется только после явного C2 и не содержит имени, контактов и суммы зарплаты. Кандидат видит предпросмотр, строящийся из того же ответа, что и карточка для организаций.
|
||||
- Статус поиска, скрытие отдельных организаций, история изменений и история просмотров карточки и чтений контактов. Карточка показывается организациям только в группе не менее пяти. См. [видимость](ARCHITECTURE.md#видимость-кандидата).
|
||||
|
||||
### Работодатель
|
||||
|
||||
- Организации (аккаунт может владеть несколькими), профиль компании и потребность по шагам с вилкой зарплаты. Потребность хранит версии требований; поиск по версии не меняется после правки. См. [организации](ARCHITECTURE.md#организации-и-членства).
|
||||
- Поиск кандидатов по потребности или по банку с фильтрами: специализация, подтвержденный и заявленный грейд, статус подтверждения, стек, формат работы и совместимость по зарплате. Результат разделен на группы `main`, `near`, `unconfirmed`, а объяснение (компоненты оценки и флаги неизвестного) строит сервер.
|
||||
- Базовый подбор работает без ML: смысловая близость равна нейтральным 0.5 и помечена флагом `ml_unavailable`; при когорте меньше 30 добавляется `cohort_below_30`. См. [подбор и объяснение](ARCHITECTURE.md#подбор-и-объяснение).
|
||||
|
||||
### Приглашения и контакты
|
||||
|
||||
- Организация создает черновик из результата поиска, меняет условия с версиями и отправляет приглашение с вилкой зарплаты в рублях. Отправка тратит место недельной квоты; на потребность действует предел ожидающих приглашений, после отказа действует пауза пары, а неотвеченное приглашение истекает по сроку. См. [черновики](ARCHITECTURE.md#черновики-приглашений), [отправку](ARCHITECTURE.md#отправка-приглашений) и [предел и истечение](ARCHITECTURE.md#предел-ожидающих-пауза-и-истечение).
|
||||
- Доставленное приглашение попадает во входящие кандидата. Кандидат отмечает просмотр, отказывается или принимает его с согласием C4, выбрав поля контактов. См. [просмотр и отказ](ARCHITECTURE.md#просмотр-и-отказ-кандидата) и [принятие](ARCHITECTURE.md#принятие-кандидатом).
|
||||
- Принятие создает разрешение на контакты ровно для этой пары. Организация читает выбранные поля на странице приглашения, и каждое чтение заново проверяет разрешение и видимость. Отзыв C4, отзыв C2, закрытие публикации и скрытие организации закрывают чтение сразу; повторная публикация закрытое разрешение не открывает. См. [чтение и отзыв](ARCHITECTURE.md#чтение-контактов-и-отзыв).
|
||||
|
||||
### Изоляция компаний и холдинги
|
||||
|
||||
- Организационные операции отвечают на чужие идентификаторы тем же отказом, что и на случайный идентификатор. Поиск, приглашения и чтение контактов доступны только владельцу организации.
|
||||
- Организации одного аккаунта образуют холдинг: компании на уровне E0 делят общие квоты (в демонстрационной политике 10 приглашений за 7 дней и 50 уникальных просмотров карточек за 24 часа). Число организаций на аккаунт не ограничено. См. [COMPANY_QUOTAS](COMPANY_QUOTAS.md#пул-холдинга).
|
||||
|
||||
### Уведомления и почта
|
||||
|
||||
- Inbox в обоих кабинетах; единственный продуктовый источник - доставленное приглашение. Запись появляется через outbox, relay и Kafka после фиксации, а не внутри транзакции отправки. См. [внутренние уведомления](ARCHITECTURE.md#внутренние-уведомления).
|
||||
- Письмо о приглашении проходит через outbox и обработчик доставки, а отправляет его отдельный цикл уведомлений (worker в процессе backend); перед каждой отправкой он заново проверяет права получателя и оставляет резерв квоты служебной почте. Тело письма нейтрально и не содержит контактов. См. [отправку продуктовых уведомлений](ARCHITECTURE.md#отправка-продуктовых-уведомлений).
|
||||
- Обращения в поддержку в обоих кабинетах.
|
||||
|
||||
### Гарантии приватности
|
||||
|
||||
- До записи C4 и разрешения организация не получает контакты; карточки, результаты поиска, списки приглашений и уведомления не содержат email, телефона и имени.
|
||||
- Логи сервера, payload outbox, строки inbox и запросы писем не содержат значений контактов и профиля (проверяет интеграционный тест изоляции, см. раздел 5).
|
||||
- Ответы организаций не содержат PDF и сохраненных снимков поиска: таких операций нет.
|
||||
|
||||
## 2. Как запустить
|
||||
|
||||
Все команды выполняются из корня репозитория. Требуются Docker с Compose, GNU make, python3 и openssl; GPU и внешние ключи не нужны. Полная инструкция: [быстрый старт](DEPLOY.md#запуск-mvp-быстрый-старт).
|
||||
|
||||
### Рабочий стенд
|
||||
|
||||
cp .env.example .env # замените каждое replace-this-... и задайте IDENTITY_KEY_SECRET
|
||||
make -C deploy config
|
||||
make -C deploy up
|
||||
curl http://localhost:8080/api/v1/healthz
|
||||
|
||||
Открывайте http://localhost:8080 (значение `APP_PUBLIC_URL`). Для писем задайте `EMAIL_PROVIDER=resend`, `RESEND_API_KEY` и `EMAIL_FROM` в окружении сервера. Чистый стенд содержит миграции и стартовую политику; шаги оператора (нужен `DATABASE_URL`):
|
||||
|
||||
1. Опубликовать раздел подбора, без него поиск отвечает 500: `make -C backend policy-publish ARGS='matching --actor operator:<handle>'`. См. [политику подбора](DEPLOY.md#политика-подбора-на-стенде).
|
||||
2. Чтобы пройденный полный тест получал демонстрационную категорию, выставить `ASSESSMENT_DEMO_CATEGORIES_ENABLED=true`, перезапустить backend и аттестовать открытие категории командой `make -C backend assessment-category-attest ARGS='attest --specialization backend --grade intern --task-language go --actor operator:<handle>'`. Публикация новой версии политики требует нового открытия и новой аттестации, поэтому выполняйте шаг 1 до начала попыток. См. [демонстрационные категории](DEPLOY.md#демонстрационные-категории-на-стенде).
|
||||
|
||||
Банк заданий на основном стенде не загружен, и руководство DEPLOY описывает его загрузку только в составе seed демонстрационного стенда, поэтому тест на основном стенде начать нельзя. Для показа полного пути используйте демонстрационный стенд.
|
||||
|
||||
### Демонстрационный стенд и маршрут жюри
|
||||
|
||||
make -C deploy demo-seed DEMO_MODE=isolated
|
||||
|
||||
Команда поднимает отдельный проект на http://localhost:8090, публикует политику с разделом подбора, загружает синтетический банк, аттестует категорию и создает аккаунты `candidate@`, `prepared-1@` - `prepared-6@`, `employer-alpha@` и `employer-beta@` в домене `demo.lincodex.test`; пароль берется из `deploy/demo/demo.env` или `demo.env.example`. Гид жюри открыт по адресу http://localhost:8090/demo; он восьмиминутный и есть только в сборке этого стенда. Маршрут: экспресс-тест и полный тест кандидата, подготовленные кандидаты с опубликованными карточками, потребность и поиск владельца "Альфа", приглашение, принятие с C4 и чтение контактов. См. [демонстрационный стенд](DEPLOY.md#3-демонстрационный-стенд), [маршрут](DEPLOY.md#4-маршрут-демонстрации) и [изолированный стенд](DEPLOY.md#изолированный-демонстрационный-стенд). Сброс: `make -C deploy demo-reset DEMO_MODE=isolated` (отказывает, если на стенде есть обычные аккаунты).
|
||||
|
||||
### Восстановление из манифеста выпуска
|
||||
|
||||
make -C deploy release-build
|
||||
make -C deploy release-smoke
|
||||
make -C deploy release-e2e
|
||||
make -C deploy release-manifest RELEASE_ID=<id>
|
||||
make -C deploy release-up RELEASE_ID=<id>
|
||||
make -C deploy release-manifest-verify RELEASE_ID=<id> RELEASE_VERIFY_PROJECT=<project>
|
||||
make -C deploy demo-seed DEMO_MODE=isolated RELEASE_ID=<id>
|
||||
|
||||
Манифест неизменяем: он фиксирует исходники, lockfiles, Compose-файлы и image ID образов, а `release-up` запускает их без сборки и скачивания и сверяет хеши. Манифест публикуется только для чистого дерева и после успешных smoke и E2E на этих образах. `release-manifest-verify` сравнивает запущенные контейнеры с манифестом. Демонстрационный стенд из манифеста не содержит гида `/demo`, потому что берет фронтенд основного выпуска. Банк оценки в манифесте не снимается (`product_data_status` равен `partial`). См. [манифест выпуска](DEPLOY.md#манифест-выпуска).
|
||||
|
||||
## 3. Ограничения демонстрационной категории
|
||||
|
||||
- Банк заданий небольшой и синтетический: 25 семейств для полного теста и три для экспресс-теста. Семейства проходят штатный конвейер публикации с метками автора и проверяющего, но предметной проверки содержание не проходило.
|
||||
- Пороги не откалиброваны, перцентиль не считается, а адаптивного теста нет. Результат показывает механику, а не измеренную квалификацию.
|
||||
- В API основание категории равно `synthetic_demo` и описано в контракте как демонстрационная категория, не являющаяся проверенным измерением. В интерфейсе по решению владельца продукта она показана как обычное подтверждение (подпись "Результат теста"). API и эта документация сохраняют основание.
|
||||
- Экспресс-тест не назначает грейд ни при каких настройках.
|
||||
- Тексты согласий C1-C5 публикуются миграциями как `demo`, без юридической проверки. Не регистрируйте на демонстрационном стенде реальных людей.
|
||||
|
||||
## 4. Что не реализовано
|
||||
|
||||
Следующее относится к полному продукту и не работает в этом выпуске:
|
||||
|
||||
- практика с кодом (песочница) и адаптивный тест;
|
||||
- финальный раунд торга и встречные предложения: состояние `counter` не создает ни одна операция, повышение зарплаты отвечает 501 `not_implemented`;
|
||||
- назначение интервью и напоминания;
|
||||
- отзыв приглашения организацией и отмена участия кандидатом: обе операции отвечают 501;
|
||||
- роли, кроме владельца, и назначения по потребностям: искать, приглашать и читать контакты может только владелец организации;
|
||||
- PDF-документы и сохраненные снимки выдачи поиска;
|
||||
- рекомендации категорий для потребности: ответ потребности сообщает состояние `pending` или `not_available` с пустым списком;
|
||||
- включенный ML inference: сервис ML запускается отдельно без модели, backend его не вызывает;
|
||||
- интеграция с ФСП: нет ни режима, ни fixture-провайдера, ни обращений к внешнему API;
|
||||
- транспорт SMTP: выбор `EMAIL_PROVIDER=smtp` останавливает backend при запуске;
|
||||
- интеграция с ATS;
|
||||
- сброс пароля, загрузка и разбор резюме, письма о событиях, кроме подтверждения и нового приглашения.
|
||||
|
||||
## 5. Как проверено
|
||||
|
||||
Итог приемки на проверенном коммите (10.10.2026): `make verify` прошел, включая 110 интеграционных тестов и технический smoke; `make -C deploy test-e2e-registration` - 95 passed, 1 skipped; `make -C deploy test-e2e` - 64 passed, 32 skipped; `make -C security install test check` и `make security-images` прошли без блокирующих находок (сканеры запускались в Linux-контейнере, как в CI, потому что их установщик поддерживает только Linux; исключение для CVE-2026-93687 действует до 19.10.2026). Границы каждой проверки описаны в [TESTING](TESTING.md#команды).
|
||||
|
||||
| Проверка | Что подтверждает |
|
||||
| --- | --- |
|
||||
| `make verify` | Генерацию контрактов без расхождений, форматирование, линтеры, типы, сборку, Compose, документацию, backend с race detector, интеграционные тесты на PostgreSQL, Redis, SeaweedFS и Kafka и технический smoke |
|
||||
| `make -C deploy smoke` | Запуск стека, готовность зависимостей и отказы зависимостей; бизнес-сценарий не проверяет |
|
||||
| `make -C deploy test-e2e` | Браузерный набор Playwright на одноразовом стеке с отключенной почтой, включая `mail-unavailable.spec.ts`: пользователь видит, что письмо может прийти позже, и не входит до подтверждения |
|
||||
| `make -C deploy test-e2e-registration` | Регистрацию, подтверждение ссылкой и кодом и вход через локальный Resend-совместимый inbox, а в нем `acceptance-path.spec.ts` |
|
||||
| `acceptance-path.spec.ts` | Минимальный путь на настоящем backend: пять кандидатов, полный тест с категорией `synthetic_demo`, публикация, потребность, поиск с объяснением и фильтром, приглашения, принятие с C4, чтение контактов, отказ, отзыв C2 и отсутствие дубликатов при обновлении и двойном принятии. См. [путь до контактов](TESTING.md#минимальный-путь-от-регистрации-до-раскрытых-контактов) |
|
||||
| `TestCompanyIsolationAndRevocationOverHTTP` | Изоляцию компаний и кандидатов, мгновенное закрытие после скрытия, отзыва C4 и C2 и отсутствие контактов в логе, outbox, inbox и запросах писем. См. [тесты организаций](TESTING.md#тесты-организаций) |
|
||||
| `TestInvitationNoticesSurviveRelayAndConsumerRestarts` | Ровно одно уведомление и одно письмо на получателя после перезапусков relay и потребителей и потери offset |
|
||||
| `TestHoldings`, `TestCompanyQuota` | Общий пул квот E0 внутри холдинга и отсутствие превышения при параллельных резервированиях |
|
||||
| `make -C security check`, `make -C security images` | Уязвимости зависимостей, секреты, опасные конструкции и образы; см. [SECURITY](SECURITY.md) |
|
||||
| `make -C deploy check-demo`, `make docs-check` | Охранные проверки целей демонстрационного стенда и структуру документации |
|
||||
| `make -C deploy release-smoke`, `release-e2e` | Те же smoke и браузерный набор на образах выпуска; успешный прогон дает evidence для манифеста |
|
||||
|
||||
Что проверки не доказывают: калибровку оценки, точность подбора, доставку писем через настоящий Resend, работу за HTTPS и production-нагрузку.
|
||||
Reference in new issue
Block a user