feat(assessment): report planned bank coverage

This commit is contained in:
TakuyaYagam1 committed 2026-10-11 22:25:25 +03:00
1 parent 76d32bb79f
commit a69b1a79bb
9 files changed
+1208 -285

No files matched your search

+7
View File
@@ -49,6 +49,13 @@ assessment-review-build: ## Build the local assessment review operator command
@mkdir -p bin
$(GO) build -buildvcs=false -trimpath -o bin/assessment-review ./cmd/assessment-review
.PHONY: bank-coverage bank-coverage-check
bank-coverage: ## Report planned assessment bank coverage from bundle files (set ARGS)
$(GO) run ./cmd/assessment-bank-coverage $(ARGS)
bank-coverage-check: ## Fail when planned family keys, reviewer declarations, or implementation paths are missing
$(GO) run ./cmd/assessment-bank-coverage --strict $(ARGS)
.PHONY: assessment-leak-trace assessment-leak-trace-build
assessment-leak-trace: ## Find the attempt behind a leaked task text; the search is audited (set ARGS)
$(GO) run ./cmd/assessment-leak-trace $(ARGS)
+38 -143
View File
@@ -1,160 +1,55 @@
# Go backend
# Backend
[Русский](README.md) | English
The main service uses Go, chi, and Clean Architecture. It currently provides health checks, identity and server-side sessions, the consent ledger and settings, and PostgreSQL, Redis, and SeaweedFS adapters; the remaining hiring workflows are still to be implemented.
The core Go service handles accounts, profiles, skill assessments, organization needs, search, invitations, and notifications. chi and the generated ogen server serve HTTP. Background handlers run within the application process.
- `cmd/app/` is the entry point; `internal/bootstrap/` wires dependencies and manages startup.
- `internal/` contains domain types, use cases, ports, and primary/secondary adapters.
- `config/` holds application settings; `pkg/` is for shared helper packages.
- `db/` and `codegen/` hold SQL queries, migrations, and generator configuration.
- `integration_test/` checks real dependencies through Testcontainers.
## Structure
From the repository root, `make -C backend check` runs the main checks and `make -C backend test-int` runs integration tests with Docker. Use `make -C backend help` for all commands.
| Directory | Purpose |
| --- | --- |
| `cmd/app/` | Entry point calling `bootstrap.Run` |
| `config/` | Environment loading and validation |
| `internal/bootstrap/` | Dependency assembly, startup, and shutdown |
| `internal/domain/` | Domain types and rules |
| `internal/usecase/` | Application workflows |
| `internal/port/` | Inbound and outbound interfaces |
| `internal/adapter/primary/http/` | Router, middleware, `v1/` handlers, ogen output in `api/` |
| `internal/adapter/secondary/` | PostgreSQL, Redis, SeaweedFS, Kafka, mail, and external services |
| `internal/worker/` | Outbox, events, jobs, and mail delivery |
| `db/` | Migrations and SQL queries |
| `codegen/` | ogen, sqlc, wire, and mockery |
| `pkg/` | Reusable libraries |
| `integration_test/` | Tests against real infrastructure |
## Server sessions
## Development
Registration, email confirmation, login, `GET /api/v1/identity/me`, `GET /api/v1/identity/sessions/current`, and `DELETE /api/v1/identity/sessions/current` are implemented. The session boundary authenticates every operation protected by the OpenAPI contract; handwritten handlers can read a principal containing the user ID and verified-email state resolved from the PostgreSQL session. Unknown, expired, revoked, or unverified sessions answer `401 unauthenticated`. Contract operations without an implemented business handler answer 501 after the security boundary and request validation succeed. An unknown email and an incorrect password return the same `401 invalid_credentials`; correct credentials for an unverified account return `403 email_not_verified` at login.
[go.mod](go.mod) declares the Go version. From the repository root:
Sessions are stored in PostgreSQL. The browser receives a `__Host-lincodex_session` cookie with `Secure`, `HttpOnly`, `SameSite=Strict`, `Path=/`, and no `Domain`; the database stores only the token hash. The default idle timeout is 24 hours and the absolute lifetime is 168 hours. Configure them with `IDENTITY_SESSION_IDLE_TIMEOUT` and `IDENTITY_SESSION_ABSOLUTE_LIFETIME`; the idle timeout cannot exceed the absolute lifetime.
```sh
make -C backend deps
make -C backend build
make -C backend test-fast
make -C backend check
```
Every unsafe public identity operation (`RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, `ConfirmEmailByCode`, and `Login`) requires exactly one `Origin` header matching `APP_PUBLIC_URL`. Unsafe session operations also require the session-bound HMAC token in `X-CSRF-Token`; all API instances must use the same `IDENTITY_KEY_SECRET`. Origin checks do not trust `Host` or forwarded headers. A wrong Origin or CSRF token returns `403` and leaves a valid session intact; successful logout revokes it on the server and clears the cookie. Login limits apply separately by client address and normalized email: `IDENTITY_CLIENT_HOURLY_LIMIT` defaults to 30 attempts per hour and `IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT` defaults to 10 attempts per hour.
Use `make generate` to regenerate all dependent components. Backend targets include `gen-openapi`, `gen-ml`, `gen-code-runner`, `gen-lab-provisioner`, `gen-sqlc`, `gen-wire`, and `mocks`. Do not edit generated files by hand.
HTTP-flow tests with PostgreSQL and Redis are part of `make -C backend test-int`; compile the integration suite without starting containers with `make -C backend test-int-compile`.
`make -C backend run` reads process environment variables and does not load `.env` automatically. Use [Compose](../docs/en/DEPLOYMENT.md) to run with its dependencies. Migrations run before HTTP starts by default; separate commands are `migrate-status`, `migrate-up`, and `migrate-down-one`.
## Consent ledger and settings
## Operational routes
Only the current C1 text is public for registration. A verified user can read current C1/C2/C3/C5 texts before granting them in settings and can page through their own consent history. C1 can be granted by either account scenario; C2, C3, and C5 are candidate-only. Mutations require explicit acceptance, the exact Origin, and session-bound CSRF.
- `GET /healthz`: the process is alive.
- `GET /readyz`: PostgreSQL, Redis, and SeaweedFS are available; Kafka is not checked here.
- `GET /api/v1/healthz`: health through the public API.
- `GET /metrics`: a separate `METRICS_ADDR` listener, default `:9090`.
Revoking C2 makes the publication effectively closed and hides its fields through the ledger-backed read in the same transaction; the stored publication stays linked to the revoked record, so a later C2 grant cannot reopen it. Revoking C3 does not block account, profile, or manual-assessment requests through support. Revoking C5 immediately closes the gate for future imports and writes an outbox intent; there is no external FSP adapter yet. C4 revocation is limited to one organization and uses the stored contact scope; in the same transaction it closes the grants that name the revoked records, and C2 revocation closes every contact grant of the candidate. A C1 request revokes consent and creates a durable deletion-request record with an outbox intent; repeats return the same active record, and the account is not deleted synchronously.
Mail supports `disabled` and `resend`. SMTP configuration exists, but selecting `smtp` currently stops startup because its transport is not implemented. ML and runner require separately configured services. The labd client is generated but not yet wired into bootstrap.
`make -C backend test-int` runs the full HTTP flow with PostgreSQL and Redis. `TestConsentSettingsOverHTTP` covers texts, history, grants, revocation effects, and the C1 deletion request.
## Checks
## Organizations
`make -C backend test` runs unit tests with the race detector. `test-int` uses Testcontainers and requires Docker; `test-int-compile` only compiles integration tests. [TESTING.md](../docs/en/TESTING.md) covers shards and the shared bootstrap.
`POST /api/v1/organizations`, `GET /api/v1/organizations/{org_id}`, and `PATCH /api/v1/organizations/{org_id}` are implemented. A verified employer creates the organization and its active owner membership in one transaction, starting at `e0` with basis `confirmed_email`. Every read checks active owner membership. Only the active owner can edit; the version advances on change and the verification level is preserved.
List commands with `make -C backend help`. See [DEVELOPMENT.md](../docs/en/DEVELOPMENT.md) and [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md) for layer boundaries and change rules.
The same `Idempotency-Key` and body replay the original `201` snapshot within 24 hours, even after profile edits. Migration `00019_create_organization_creation_results.sql` stores that snapshot separately from the live organization. The 24 hours define the logical replay window. Bounded opportunistic cleanup runs on successful creates; physical deletion can occur later, and removes the snapshot with its generic idempotency record. `GET /api/v1/me/organizations` paginates the current employer's active memberships. Invitation routes enforce the common owner check; the draft operations and the send are described under [Invitation drafts](#invitation-drafts), and the other organization invitation operations answer 501 after that check.
`TestOrganizationCreationAndOwnerEditingOverHTTP` checks concurrent replay, rollback on owner insertion failure, cross-account denial, persisted reads after rebuilding the API, and reuse of an expired key against PostgreSQL.
The organization joins the holding of the owner account: `CreateWithOwner` creates the holding (table `holdings`, migration `00041_create_holdings.sql`) in the same transaction when the account creates its first organization. The E0 invitation and card-view limits are shared by all E0 organizations of the holding; the pool and lock rules are described in [Company quotas](../docs/en/COMPANY_QUOTAS.md#holding-pool). `TestHoldings` covers the shared pool, account isolation, concurrent reservations, and concurrent creation, and `TestHoldingsMigrationBackfillsFoundersAndGuardsRollback` covers the backfill and the guarded rollback.
`TestCompanyContextChecksLiveOwnerMembershipAndListsOwnOrganizations` covers company isolation, candidate denial even with a manually inserted membership, denial for other roles, pagination, and owner revocation with the same cookie. A company in the active-membership directory does not grant owner authority; the server checks the role on every request.
## Organization needs
Organization needs have transaction-bound PostgreSQL storage through `UnitOfWork.Needs()`. Migration `00023_create_organization_needs.sql` adds a current-version pointer and immutable snapshots scoped by organization. Creation starts at version 1. A changed snapshot advances the version with compare-and-swap; a losing writer gets a version conflict. The HTTP contract uses 412 for that conflict.
The owner-scoped create, read, list, and update operations live in `internal/adapter/primary/http/v1/need.go`. Every operation checks the current verified employer account and locks its active owner membership in the transaction. List cursors carry both account and organization scope. Creates retain the original public response for the 24-hour idempotency window, even after a later edit.
Source text is parsed locally by deterministic rules into unconfirmed suggestions. Unknown or ambiguous values remain unknown. Confirming a stored suggestion preserves its origin; a manual replacement records a manual origin. Editing source text preserves confirmed values, and removing a suggestion prevents later extraction from silently restoring it. Readiness is derived from confirmed requirements. Category recommendations currently report `not_available` without confirmed skills and `pending` otherwise; the category recommendation calculator is not implemented yet.
`requirements_version` identifies the snapshot where confirmed requirements last changed. Editing only the title, source text, or unconfirmed suggestions leaves that reference unchanged. Domain no-ops preserve both versions. Snapshots preserve provenance, reject oversized content, and use UTC microsecond timestamps. Current and historical reads require the organization ID; immutable history rejects ordinary UPDATE and DELETE. Down migration removes both tables and their history, so it is destructive after data has been written.
`TestOrganizationNeedsStorage` exercises actual PostgreSQL isolation, history, concurrent updates, transaction rollback, immutable snapshots, and storage bounds. The caller must perform the existing active-owner check in the same business operation; storage scope alone does not grant company access.
Migration `00026_create_organization_need_creation_results.sql` adds create-response storage and 8 KiB of database representation headroom for JSONB whitespace. The compact domain snapshot limit remains 256 KiB. Its down migration refuses to discard live replay results or restore the previous database bound over larger stored snapshots. Check those conditions before rollback; it does not remove need history to make a downgrade succeed.
## Invitation drafts
The organization side of the invitation draft is implemented: `GET` and `POST /api/v1/organizations/{org_id}/invitations` and `GET` and `PATCH /api/v1/organizations/{org_id}/invitations/{invitation_id}` (`usecase/invitation/`, `adapter/primary/http/v1/invitation.go`). Withdrawal, the salary raise, the contact read, the acceptance, and the cancellation still answer 501 after the common checks. A draft is invisible to the candidate and writes no inbox entry, event, or quota usage.
Migration `00037_create_invitations.sql` adds `invitations`, the immutable `invitation_terms_versions`, the append-only `invitation_events` (one audit event for each committed version), and `invitation_creation_results` (the original response of an idempotent create). Money is whole rubles in `bigint`; `domain.SalaryRange` is the one implementation of the range rule for needs and invitations, and the terms table repeats it in constraints (bounds and step, `A < B`, a width of 10% to 40% in integer arithmetic), so no other writer can store a range the API refuses. A change of the terms appends the next terms version; the earlier one cannot be updated or deleted. The candidate is stored as an internal `candidate_id` and shown only as the organization-scoped card handle. The down migration refuses while any invitation exists and never deletes one. The tables, decisions, locks, and what is not implemented are in [architecture](../docs/en/ARCHITECTURE.md#invitation-drafts); the contract is in [api/README.en.md](../api/README.en.md#invitations-and-contact-grants).
`candidateview.Service.ResolveCandidateHandle` resolves the handle in the create transaction with the checks of a card read (membership, effective C2 publication, hiding of the organization, minimum cohort) and charges no quota. An unknown handle, a handle of another organization, a hidden or unpublished candidate, and a suppressed card give the same 400 at `/candidate_handle`. The create is idempotent for 24 hours and replays the stored 201. An update answers 200 for a body that changes nothing, then compares the version (412), then the state (409), then the rules (400). Both commands take the organization lock before the membership and invitation locks. `salary_fit` is `not_available` until the limit against probing the minimum exists.
The integration tests `TestOrganizationInvitationDraftsOverHTTP` (the router, sessions, CSRF, cohort and hiding fixtures, money boundaries, package conditions, handle refusals, replay, anti-enumeration, listing and cursors, versions and immutable terms, need links, the state conflict, concurrent updates, concurrent creates and updates of one organization without a deadlock, and no candidate value in responses, stored terms, or logs), `TestInvitationRepositoryStoresVersionsAndRefusesLostUpdates`, `TestInvitationTablesRefuseMoneyAndHistoryViolations` (the constraints and triggers by direct SQL), and `TestInvitationMigrationRollbackKeepsStoredInvitations` run against a real PostgreSQL.
Sending is implemented: `POST /api/v1/organizations/{org_id}/invitations/{invitation_id}/send` (`usecase/invitation/send.go`) and the candidate's list `GET /api/v1/me/invitations` (`usecase/invitation/candidate_inbox.go`). One transaction takes the organization lock, the owner membership, the key, and the invitation row, checks the version and the state, resolves the stored candidate through the card visibility barrier again (409 when hidden, C2 revoked, or suppressed), charges the organization quota through `companyquota.Service.ReserveInvitation` (429 with `Retry-After`), moves the draft to `delivered` with `response_deadline_at = delivered_at + response_period_days`, appends the `delivered` audit event, and writes the outbox events `invitation.delivered` and `notification.mail_requested` (`usecase/notification/invitation.go`). A success therefore means the invitation is already in the candidate's list; the notification and the email follow through the consumers, and neither they nor their retries change the deadline. A repeat with the same key replays the stored outcome, and a send of a delivered invitation answers 200 with its current state without a second charge. Migration `00038_send_invitations.sql` adds the `delivered` event kind, `invitation_send_results` (the 200, 404, or 409 kept under the key), and the foreign key from `company_invitation_quota_usage` to `invitations`; its rollback refuses while a delivery event or a stored outcome exists. Details are in [architecture](../docs/en/ARCHITECTURE.md#sending-invitations). `TestOrganizationInvitationSendOverHTTP` and `TestInvitationSendMigrationKeepsDeliveriesAndKeysQuotaUsage` cover it against a real PostgreSQL.
The limit of invitations that wait for an answer per need, the 30-day pause after a decline, and the expiry at the deadline are implemented. The send checks the limit (`max_pending_per_need`) and the pause (`repeat_after_decline_days`) of the effective policy before it charges the quota, and answers 409 `state_conflict`; in the same transaction it schedules the job `invitation.response_deadline` at the response deadline. The handler `usecase/invitation/expire.go` moves a waiting invitation to `expired` with the reason `invitation_timeout`, and the candidate commands apply the due expiry first at or after the deadline. Migration `00043_expire_invitations.sql` adds the event kind `expired` without an actor, the trigger `invitations_guard_expiry`, the partial indexes, and the jobs of invitations that were delivered before it. Details are in the [architecture](../docs/en/ARCHITECTURE.md#pending-limit-cooldown-and-expiry). `TestInvitationPendingLimitAdmitsOneOfTwoConcurrentSendsOverPostgres`, `TestInvitationPauseAfterADeclineHoldsForThirtyDaysOverPostgres`, `TestInvitationAcceptAtTheDeadlineRacesTheExpiryJobOverPostgres`, and `TestInvitationExpiryMigrationBackfillsDeadlineJobsAndGuardsExpiries` cover it against a real PostgreSQL.
The candidate's read, view, decline, and acceptance are implemented: `GET /api/v1/me/invitations/{invitation_id}`, `POST .../view`, and `POST .../decline` (`usecase/invitation/view.go` and `decline.go`). The read records no view and applies only the due expiry; the view moves `delivered` to `viewed` before the deadline, keeps the deadline, applies the due expiry at or after it, and otherwise answers with the invitation as it is; the decline moves `delivered`, `viewed`, or the planned `counter` to `declined` before the deadline with a reason and an optional comment and creates no consent or grant. The view and the acceptance lock only the invitation row; the decline also takes the organization lock to order the pause of the pair. The commands append the audit events `viewed` and `declined`. A late decline answers 409 after the due expiry, and a declined invitation has `contact_consent` and `contact_grant` null. Migration `00039_answer_invitations.sql` adds the event kinds, the state rules of the view and the answer, `invitation_declines` (the reason and the comment, which the organization never reads), and `invitation_decline_results` (the outcome under the key); its rollback refuses while a view, a decline, or an outcome exists. Details are in [architecture](../docs/en/ARCHITECTURE.md#candidate-view-and-decline). `TestCandidateInvitationViewAndDeclineOverHTTP` and `TestInvitationAnswerMigrationGuardsAnswersAndRefusesRollback` cover it against a real PostgreSQL.
The candidate's acceptance is implemented: `POST /api/v1/me/invitations/{invitation_id}/accept` (`usecase/invitation/accept.go`). One transaction locks the invitation row, moves a delivered or viewed invitation before its deadline to `accepted` at the invitation version and the terms version that the candidate read, records the consent C4 through `consent.Service.GrantContact` (the published text and the selected fields), stores the contact grant of exactly the selected fields in `contact_grants`, and appends the audit event `accepted`. A stale version answers 412 and is not stored; the consent rules answer 400 with a pointer under `/consent_c4`; a repeat answers the stored acceptance, and another field set answers 409 `state_conflict`. Acceptance never publishes the profile or lifts a hiding: the grant is readable only while the organization may read the profile. Migration `00040_accept_invitations.sql` adds the event kind, the grant table with composite keys that tie it to the invitation, the candidate, and the C4 record, the outcome table, and a refusal of rollback while an acceptance exists. Details are in [architecture](../docs/en/ARCHITECTURE.md#candidate-acceptance). `TestCandidateInvitationAcceptOverHTTP` and `TestInvitationAcceptMigrationGuardsAcceptancesAndRefusesRollback` cover it against a real PostgreSQL.
The contact read is implemented: `GET /api/v1/organizations/{org_id}/invitations/{invitation_id}/contacts` (`usecase/invitation/contacts.go`, handler `adapter/primary/http/v1/contacts.go`). It is owner only. Each request rechecks, under locks, the membership, the C4 record, the grant and its fields, and the visibility of the publication, and every closed case answers 404 `not_found`. A successful read writes one `contact_read` row to `candidate_card_access_events` and consumes no card-view quota. Revoking C4 closes the grants that name its records, revoking C2 or closing the publication closes every grant of the candidate, and hiding an organization closes its grants; unhiding or publishing again never reopens them. Migration `00042_index_contact_grants_by_candidate.sql` adds the index of those closings. Details are in [architecture](../docs/en/ARCHITECTURE.md#contact-reads-and-revocation). `TestOrganizationContactReadsAndRevocationOverHTTP` covers it against a real PostgreSQL.
## Support cases
Verified accounts can create and list their own cases at `/api/v1/me/support-cases` and read a case by its ID. Ownership is independent of access to a disputed action. Object references contain only a type and ID; the server checks their scope and does not copy private object content. Employers can submit general support requests. Candidates can also request manual assessment without a prior attempt or C3 consent. Such a request waits for an expert and does not assign a grade or grant consent.
A manual request pins the current published rubric for its specialization and grade. The API shows the grading-policy version; private references retain the exact category opening and immutable family-version manifest. Later publications do not change an existing case's rubric. Without one unambiguous current rubric, the version remains `null` and the case waits for an expert.
Creation requires an explicit support section in the effective product policy. `DemoProductPolicyV2` includes it; normal startup still seeds only the immutable V1 policy. The demo targets are five business days for support, complaints, and manual assessment, and ten for appeals. The versioned calendar counts UTC weekdays without public holidays and does not pause while waiting for the user. These are operational targets, not legal deadlines.
The account-wide rolling request limit is checked under a database lock before idempotent replay. Valid retries consume that request budget and return the original creation response during the 24-hour window. A 429 response includes `Retry-After`. GET and list show the current status, public history, and current overdue flag. Migration `00025_create_support_cases.sql` stores immutable events and replay results; rollback removes these records and is destructive.
The manual assessment rules live in `internal/usecase/supportcase/manual_assessment.go`: the request neither reads nor changes consent, creates no attempt, and writes no grade or category, and a prior attempt is optional and may have failed.
`TestManualAssessmentRequestAfterC3Refusal` goes through the real router: granting and revoking C3, a request before the first test with a pinned rubric, a request without a published rubric (`rubric_version` is `null`), and requests after a failed and after a confirmed attempt. The test compares the consent ledger and events, attempts, and immutable results before and after the request, and checks that a repeat with a new key leaves one open case.
`TestSupportCasesOverHTTP` covers real sessions, owner isolation, typed-reference checks, replay, manual assessment without C3, and request limits. `TestSupportCaseRequestBudgetSerializesTimestampWithOwnerLock` checks concurrent requests and clock ordering. Expert processing and references to not-yet-implemented invitations or anti-cheat reviews remain unavailable.
## Candidate questionnaire
Verified candidates can read and replace their own questionnaire through `GET/PUT /api/v1/me/questionnaire`. The questionnaire has a separate version and stores self-assessment, work formats, optional experience totals, and one or two specializations. It cannot assign confirmed grades. An identical retry returns the saved record without advancing its version; a stale changed body returns 412, as specified by the API contract. Concurrent identical writes also return the same winning record.
Saving advances onboarding only from `candidate_questionnaire` to `candidate_assessment`, in the same transaction. Other saved steps stay unchanged. Consent settings do not yet complete the consent onboarding step.
The public specialization catalog derives readiness from the current published bank, current policy, and an immutable reviewed mapping tied to the exact category opening and published-family manifest. Legacy openings without a mapping remain unavailable. Policy changes or family retirement invalidate readiness until a new reviewed opening is made; previously saved answers remain readable. Operator names are self-declared review metadata, not an authenticated operator identity.
`TestCandidateQuestionnaireOverHTTP` covers persistence, account isolation, version races, rollback, conditional onboarding, and changing bank availability. Company quota storage and its calling contract are described in [Company quotas](../docs/en/COMPANY_QUOTAS.md).
## Assessment attempts
A candidate creates an attempt through `POST /api/v1/me/assessment-attempts`, reads it by ID, and resumes work through `POST /api/v1/me/assessment-attempts/{attempt_id}/sessions`. Real assessment requires current C3 consent; the owner's attempt history remains readable after revocation. GET neither consumes sessions nor changes state. A command with a stale version returns 412.
Creation pins the policy, bank and algorithm versions, the published family manifest, and generated question instances. The API response excludes answer keys, seeds, and private rubrics. Root-attempt quota is candidate-wide; retry and promotion intervals apply per specialization. A corrective attempt retains its root and the original chain deadline. Training `demo_express` uses a separate explicitly published bank and consumes no real-assessment quota.
Repeating a command with the same key and body returns its stored response for 24 hours. Reusing a key with another body returns 422; an unavailable bank or exhausted quota returns 409 `state_conflict`. PostgreSQL serializes quota checks and session updates, and domain time is read after lock waits. Migration 24 adds attempts, question instances, training bindings, and stored command responses; rolling it back deletes these records.
Answer submission evaluates the frozen server key and stores each answer once. Numeric comparison preserves the JSON number token without floating-point rounding; order answers must include every task exactly once. Finalization rejects unfinished required questions with their IDs, then stores the raw basic score, policy rationale, version pins, and result projection in one transaction. Reads use that immutable result. Duration does not add points, trailing seed items are unscored, and express results contain no qualification score. Migration 29 refuses rollback while command or result records depend on it. A basic threshold is not evidence of calibration.
Demonstration category. Finalizing a real attempt writes a version 2 result: the immutable document gains a category decision and the grade in force at the moment of the decision (migration 31). A `demo_express` result stays a version 1 record without these fields and never creates a category. The decision depends on the `basic_pass_mark_bp` threshold of the policy version pinned to the attempt; the HTTP handler sets no parameter. A current category row (`candidate_assessment_categories`, one per candidate and specialization) appears only when all of the following hold: `ASSESSMENT_DEMO_CATEGORIES_ENABLED` is on (off by default; turn it on only on a synthetic stand), the pinned policy is a complete demonstration policy with `demo_basic` (its threshold is the policy's own `basic_pass_mark_bp`), the result is confirmed, and an operator attestation exists for the exact category opening, catalog manifest, and policy version (`assessment_synthetic_category_reviews`, `source = synthetic_demo`). Otherwise the decision is stored as `not_eligible` or `not_confirmed`. A candidate and specialization lock serializes promotions; the database accepts only a strict upgrade, forbids deletion and manual replacement of the source, and a current category always points at a stored version 2 result of the same candidate. A failure, an equal grade, or a lower grade keep the category in force, and both attempts stay in the history.
The candidate reads the history through `GET /api/v1/me/assessment-results` (`usecase/assessment/category_history.go`): own `root` and `corrective` results only, paged by a cursor that a server HMAC binds to the candidate. An employer gets no history; a separate projection of the current category is part of the visible-candidate query (`privacy_cohort.sql`) and selects only the specialization and grade, so the anonymous card shows the category with strength `standard` when the candidate published the `categories` field. A change of the current policy changes no stored result or category; opened categories are bound to the policy they were opened under, so no attempt is created after a new policy version until the categories are opened again. The attestation is created by the local command `make -C backend assessment-category-attest` (see [DEPLOY.md](../docs/en/DEPLOY.md#demonstration-categories-on-a-stand)). Calibration of the threshold is not implemented.
## Assessment signals
The candidate-only `POST /api/v1/me/assessment-attempts/{attempt_id}/signals` accepts batches of focus-loss durations, clipboard event byte counts, and fullscreen exits. It stores no clipboard or answer content (`size_bytes` is the UTF-8 byte count of the pasted text plus file sizes, computed on the device, for a paste, and an approximate selection length in UTF-16 code units, with the text unread, for copy and cut) and supports no camera, microphone, screenshot, or screen recording. Events are bound to the owned real attempt and one of its frozen items; training attempts do not accept them. New batches require current C3 and an active attempt.
The operation limits the body to 32 KiB, each batch to 50 events, new receipts to 30 per minute per attempt, and stored events to 10,000 per attempt. Capacity is checked for the whole batch. A saturated receipt accepts zero events; idempotent replay returns the original receipt without consuming the receipt budget. Client timestamps are untrusted metadata: a timestamp outside five minutes before the attempt's creation to five minutes after database time rejects the whole batch with 400, so the client moves its timestamps to server time using the `Date` header; rate windows use database time. Migration 28 cascades event, batch, and receipt deletion with the attempt. Existing consent retention constraints still prevent physical account deletion; this cascade does not implement account erasure. Interpretation of these signals is separate work.
The notice about the collected signals is stored separately. `GET` and `PUT /api/v1/me/assessment-signal-notice` read and write the candidate's acknowledgement of a text version (`usecase/assessment/signal_notice.go`, table `assessment_signal_notice_acknowledgements`, migration 34). The server sets the text version (`CurrentSignalNoticeVersion`, now 4: version 2 added the measures the page applies during an attempt to the signal list, version 3 described the watermark of the task screen and text, and version 4 added the capture hints, the User-Agent digest, and the one-window rule); an acknowledgement is stored per version, so one given for an earlier version stays stored but never counts for the current one and a new text needs no migration. A `PUT` with another version answers 409 and stores nothing, and a repeat keeps the time of the first acknowledgement. The acknowledgement is not a consent: the signal operation does not read it and still requires current C3, so the notice cannot be used to hide a consent. Attempt creation does not check the acknowledgement on the server; the candidate screen enforces the requirement. Rows are deleted by cascade with the user.
## Anonymous profile projection
The organization-scoped projection uses purpose-separated HMAC aliases, a closed skill taxonomy, coarse experience bands, and explicitly selected publication fields. Confirmed categories and self-assessed grades remain separate. It excludes contacts, employer names, free text, exact salary, and account identifiers. Overlapping work periods count once.
The repository filters current C2 publication and hidden organizations before building the cohort. Complete visible feature combinations with fewer than five candidates are generalized or suppressed. This reduces identification risk; it does not guarantee anonymity. The private owner-preview alias uses a separate purpose. Category and salary compatibility inputs remain absent until their authoritative source supplies them; missing evidence is never inferred from a claimed grade.
Candidates read settings at `GET /api/v1/me/privacy`, preview at `GET /api/v1/me/privacy/preview`, change history at `GET /api/v1/me/privacy/history`, and card views at `GET /api/v1/me/privacy/access-history`. Hidden organizations are listed at `GET /api/v1/me/privacy/hidden-organizations` and changed through `PUT/DELETE /api/v1/me/privacy/hidden-organizations/{org_id}`. Publication and search status use `PUT /api/v1/me/privacy/publication` and `PUT /api/v1/me/privacy/search-status`. The data is scoped to the candidate in the current session, responses use `Cache-Control: no-store`, and writes require the session CSRF token and an exact allowed Origin. C2, publication, search status, and hidden organizations are independent: changing one does not enable another. Search status is a statement by the candidate, not consent.
An employer with a verified account and active membership reads a card through `GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}`. Each request rechecks membership, current C2, publication, organization hiding, and the minimum cohort; a successful view and quota use are recorded in one transaction. A closed, revoked, hidden, or suppressed card is indistinguishable from an unknown handle. Candidates can see successful card views in their access history. Contact reads and C4 grant management are not available yet; cards never contain contact details.
## Skill evidence
A confirmed real assessment result leaves one fact of skill evidence per attempt, written by the database in the same transaction that stores the result (migration 35, the trigger on `assessment_attempt_results`, and the function `skill_evidence_project_assessment_result`). The migration also projects the results that already exist. An express run, a failed attempt, and a result without a reviewed category source leave no fact. The skills of an event are tags of its fact, so several tags are still one fact, and an online assessment without a reliable identity confirmation has trust 1.
The candidate reads the facts at `GET /api/v1/me/evidence` (`usecase/evidence/read.go`, query `ListCandidateEvidenceFacts`); an employer reads the permitted projection at `GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}/evidence`, which runs the checks of the card read (`candidateview.Service.AuthorizeCategoriesSection`: membership, effective C2 publication, hiding, minimum cohort, quota, access audit) and then the statement `ListOrganizationVisibleEvidence` (effective publication view, `NOT EXISTS` over the hidden organizations, the `categories` field, visible measurements, one fact for each category of the card that supports its confirmed grade, an allowlist of six columns: skill, grade, trust, basis, calibration, year). The preview of the candidate (`GetMyCardPreview`) shows the same section through `ListCandidatePreviewEvidence`. The reads touch only the two evidence tables; `backend/db/evidence_queries_test.go` fails when an evidence query names a result, attempt, answer, signal, or review table. The facts, the tags, and the rules are described in [architecture](../docs/en/ARCHITECTURE.md#skill-evidence). The integration test `TestSkillEvidenceOverHTTP` runs against a real PostgreSQL and covers the fact tied to its result with trust 1, two more tags on one event, an express run and a failed attempt, paging, the organization projection with C2 granted and revoked, a hidden organization, a hidden fact, a card without categories, tags that can join a fact only in its creating transaction, the erasure of an account with facts through both cascade paths, the refusal to roll the migration back while a fact is hidden, and the rebuild after the migration is rolled back and applied again.
## Match search
`POST /api/v1/organizations/{org_id}/matches` ranks the organization-visible candidate bank without ML (`usecase/matching/`). It runs in one transaction: `candidateview.Service.ListVisibleCards` applies the checks of a card read (verified employer, locked active membership, `ListVisibleCandidateViewSources` over `candidate_effective_publications` with `NOT EXISTS` over the hidden organizations, the account, C2, and publication locks, and the anonymous projection with its minimum cohort of five), the need snapshot is read by `requirements_version`, and the permitted evidence comes only from `ListOrganizationFacts`. The usecase repeats the owner role check; the HTTP boundary lists the operation in `ownerCompanyOperations`. A search is charged like card reads: each group is cut to the policy limit, and each candidate returned is reserved through the company quota port and recorded in the access history with the returned fields (`candidateview.SearchViews`); when the allowance ends the response is cut and flagged `truncated`. The operator publishes the matching section with `make policy-publish ARGS='matching --actor operator:<handle>'` (`cmd/policy-publish`), the semantic section with `ARGS='semantic --actor operator:<handle>'`, the Giga + Qwen3-Embedding ensemble with `ARGS='semantic-ensemble --actor operator:<handle>'`, and schedules vectors for existing data with `make semantic-backfill ARGS='all --run <label>'` (`cmd/semantic-backfill`), see [DEPLOY](../docs/en/DEPLOY.md#match-search-policy-on-a-stand) and [semantic matching](../docs/en/DEPLOY.md#semantic-matching). The search itself never calls ML: it reads the vectors that the `semantic.candidate` and `semantic.need` jobs compute (`usecase/semantic/`).
Each entry is one candidate specialization. Scores use the `matching` section of the effective product policy (`domain.MatchingPolicy`, demo version `DemoProductPolicyV4`); a policy without the section makes the search fail closed. The arithmetic is integer (micro units for components, basis points for shares), so the order is reproducible: confirmed groups sort by S, then coverage, then the internal candidate identifier; the unconfirmed group by Fit, then coverage, then the identifier, and it never computes theta, T, P, a percentile, or S. The explanation and the unknown flags are built from the same computed contributions. The model, the neutral values, and what is not implemented are described in [architecture](../docs/en/ARCHITECTURE.md#matching-and-explanations).
The integration test `TestMatchSearchOverHTTP` runs against a real PostgreSQL through the real router, the profile, consent, publication, need, organization, and assessment operations: hidden candidates and two organizations, a need and its edited requirements, repeated identical responses, one handle confirmed in Backend and unconfirmed in Networks, a profile published without a grade and removed by a C2 revocation, a candidate alone in its cohort, no contact or identifier in the body, the charge and the access history of a search, an organization with an allowance smaller than its bank, the group limit, the access denials, and the policy without the section. The browser fixture `questionnaire-fixture` publishes `DemoProductPolicyV4`, so a local stand has the matching section.
See [architecture](../docs/en/ARCHITECTURE.md) and [development](../docs/en/DEVELOPMENT.md).
## Internal notifications
The inbox stores a reference to a delivered event for one recipient (`notification_inbox_events`, migrations 32 and 36), never its text. The consumer `notification_inbox` (`usecase/notification/inbox_handler.go`) writes the row in the transaction of its dedup marker; the key `(recipient_user_id, event_id)` keeps one row per recipient and event, and an event ID that returns with other metadata is rejected. The row exists whether or not an email was sent, and nothing in the handler reads mail state.
The text is resolved when the list is read (`usecase/notification/inbox.go`, `inbox_content.go`): `InboxService` authorizes the cabinet in the read transaction (a verified candidate for `GET /api/v1/me/notifications`; a verified employer with an active membership for `GET /api/v1/organizations/{org_id}/notifications`), then asks the resolver of each item's source type for the content that the recipient may see now. A source that is gone or hidden leaves the item in the list without content. The mark (`POST .../{notification_id}/read`) keeps the first read time and reads no source. A foreign, cross-organization, or unknown item answers 404.
A producer appends an `invitation.delivered` event with the payload `recipient_user_id` and `organization_id` and registers a resolver for its source; the send of an invitation does so, and the synthetic `notification.synthetic_delivered` event exercises the path and has no product meaning. The contract is in [docs/en/ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#internal-notifications) and [api/README.en.md](../api/README.en.md#notifications).
Report planned assessment bank coverage with `make -C backend bank-coverage`. The command matches valid families from JSON bundles against the manifest and checks for Go/Python paths for Backend families. Report mode shows incomplete coverage without failing; `make -C backend bank-coverage-check` enables strict checks. File presence does not confirm implementation equivalence, reviewer independence, or calibration; those remain separate external checks.
+38 -142
View File
@@ -1,159 +1,55 @@
# Go backend
# Backend
Русский | [English](README.en.md)
Основной сервис на Go и chi с Clean Architecture. Сейчас реализованы проверки состояния, identity и серверные сессии, журнал и настройки согласий, а также адаптеры PostgreSQL, Redis и SeaweedFS; остальные продуктовые сценарии найма еще предстоит добавить.
Основной Go-сервис: аккаунты, профили, оценка навыков, потребности организаций, поиск, приглашения и уведомления. HTTP обслуживают chi и сгенерированный ogen-сервер. Фоновые обработчики запускаются вместе с приложением.
- `cmd/app/` - точка входа; `internal/bootstrap/` собирает зависимости и управляет запуском.
- `internal/` - доменные типы, use case, порты и primary/secondary адаптеры.
- `config/` - настройки приложения; `pkg/` - общие вспомогательные пакеты.
- `db/` и `codegen/` - SQL-запросы, миграции и настройки генераторов.
- `integration_test/` - проверки с настоящими зависимостями через Testcontainers.
## Структура
Из корня: `make -C backend check` запускает основные проверки, `make -C backend test-int` - интеграционные тесты с Docker. Все команды доступны через `make -C backend help`.
| Каталог | Назначение |
| --- | --- |
| `cmd/app/` | Точка входа, вызывает `bootstrap.Run` |
| `config/` | Чтение и проверка окружения |
| `internal/bootstrap/` | Сборка зависимостей, запуск и остановка |
| `internal/domain/` | Предметные типы и правила |
| `internal/usecase/` | Прикладные сценарии |
| `internal/port/` | Входные и выходные интерфейсы |
| `internal/adapter/primary/http/` | Роутер, middleware, обработчики `v1/`, ogen-код `api/` |
| `internal/adapter/secondary/` | PostgreSQL, Redis, SeaweedFS, Kafka, почта и внешние сервисы |
| `internal/worker/` | Outbox, события, задания и отправка писем |
| `db/` | Миграции и SQL-запросы |
| `codegen/` | ogen, sqlc, wire и mockery |
| `pkg/` | Повторно используемые библиотеки |
| `integration_test/` | Проверки с реальной инфраструктурой |
## Серверные сессии
## Работа
Реализованы регистрация, подтверждение email, вход, `GET /api/v1/identity/me`, `GET /api/v1/identity/sessions/current` и `DELETE /api/v1/identity/sessions/current`. Session boundary аутентифицирует каждую операцию, для которой OpenAPI требует сессию; principal для handwritten handlers содержит ID и подтвержденный email из PostgreSQL-сессии. Неизвестная, истекшая, отозванная сессия и аккаунт без подтвержденного email получают `401 unauthenticated`. Защищенные бизнес-операции, для которых еще нет handler, отвечают 501 после успешной проверки security и запроса. Неизвестный email и неверный пароль возвращают одинаковый `401 invalid_credentials`; правильный пароль неподтвержденной учетной записи при входе дает `403 email_not_verified`.
Нужная версия Go указана в [go.mod](go.mod). Из корня репозитория:
Сессия хранится в PostgreSQL. Браузер получает cookie `__Host-lincodex_session` с атрибутами `Secure`, `HttpOnly`, `SameSite=Strict`, `Path=/` и без `Domain`; в базе хранится только хеш токена. Время бездействия по умолчанию - 24 часа, абсолютный срок - 168 часов. Эти значения задаются через `IDENTITY_SESSION_IDLE_TIMEOUT` и `IDENTITY_SESSION_ABSOLUTE_LIFETIME`; время бездействия не может превышать абсолютный срок.
```sh
make -C backend deps
make -C backend build
make -C backend test-fast
make -C backend check
```
Каждая небезопасная публичная identity-операция (`RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, `ConfirmEmailByCode`, `Login`) требует ровно один заголовок `Origin`, в точности совпадающий с `APP_PUBLIC_URL`. Небезопасные операции сессии также требуют `X-CSRF-Token`, HMAC-токен, связанный с текущей сессией; все API-инстансы должны использовать один `IDENTITY_KEY_SECRET`. Проверка Origin не доверяет `Host` или forwarded-заголовкам. Неверный Origin или CSRF отвечает `403` и сохраняет действующую сессию; успешный выход отзывает ее на сервере и очищает cookie. Лимит входа действует отдельно по адресу клиента и нормализованному email: `IDENTITY_CLIENT_HOURLY_LIMIT` по умолчанию 30 попыток в час и `IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT` - 10 попыток в час.
Для генерации всех зависимых частей используйте `make generate`. Отдельные цели backend: `gen-openapi`, `gen-ml`, `gen-code-runner`, `gen-lab-provisioner`, `gen-sqlc`, `gen-wire`, `mocks`. Сгенерированные файлы вручную не исправляются.
Проверки HTTP-сценариев с PostgreSQL и Redis входят в `make -C backend test-int`; компиляция integration suite без запуска контейнеров выполняется через `make -C backend test-int-compile`.
`make -C backend run` читает переменные процесса и не загружает `.env` автоматически. Для запуска со всеми зависимостями используйте [Compose](../docs/ru/DEPLOYMENT.md). Миграции по умолчанию применяются до открытия HTTP-порта; отдельные команды - `migrate-status`, `migrate-up`, `migrate-down-one`.
## Журнал и настройки согласий
## Служебные маршруты
Публично доступен только текущий текст C1 для регистрации. Подтвержденный пользователь может прочитать текущие тексты C1/C2/C3/C5 перед выдачей в настройках и постранично получить только собственный журнал согласий. C1 можно выдать аккаунту любого сценария; C2, C3 и C5 доступны кандидату. Изменения требуют явного подтверждения, exact Origin и session-bound CSRF.
- `GET /healthz` - процесс работает.
- `GET /readyz` - доступны PostgreSQL, Redis и SeaweedFS; Kafka в эту проверку не входит.
- `GET /api/v1/healthz` - health через публичный API.
- `GET /metrics` - отдельный listener `METRICS_ADDR`, по умолчанию `:9090`.
Отзыв C2 закрывает публикацию в модели чтения и скрывает поля в той же транзакции; сохраненная публикация остается связанной с отозванной записью, поэтому повторная выдача C2 не открывает ее снова. Отзыв C3 не блокирует аккаунт, профиль или запрос ручной оценки через поддержку. Отзыв C5 немедленно закрывает gate будущего импорта и пишет intent в outbox; внешнего адаптера ФСП пока нет. Отзыв C4 ограничен одной организацией и использует сохраненную область контактов; в той же транзакции он закрывает разрешения, которые ссылаются на отозванные записи, а отзыв C2 закрывает все разрешения контактов кандидата. Запрос C1 отзывает согласие и создает долговечную запись запроса удаления с outbox intent; повтор возвращает ту же активную запись, а сама учетная запись не удаляется синхронно.
Почта поддерживает `disabled` и `resend`. Конфигурация SMTP предусмотрена, но выбор `smtp` пока останавливает запуск: транспорта нет. ML и runner требуют отдельных настроенных сервисов. Клиент labd сгенерирован, но в bootstrap еще не подключен.
Проверку полного HTTP-пути с PostgreSQL и Redis запускает `make -C backend test-int`; тест `TestConsentSettingsOverHTTP` покрывает тексты, журнал, grants, revocation effects и C1 deletion request.
## Проверки
## Организации
`make -C backend test` запускает unit-тесты с race detector. `test-int` запускает Testcontainers и требует Docker; `test-int-compile` только компилирует интеграционные тесты. Шарды и общий bootstrap описаны в [TESTING.md](../docs/ru/TESTING.md).
Реализованы `POST /api/v1/organizations`, `GET /api/v1/organizations/{org_id}` и `PATCH /api/v1/organizations/{org_id}`. Подтвержденный работодатель создает организацию и активное членство владельца одной транзакцией; начальный уровень - `e0` с основанием `confirmed_email`. Каждое чтение проверяет активное членство владельца. Изменять профиль может только активный владелец; версия повышается при изменении, уровень проверки сохраняется.
Полный список команд: `make -C backend help`. Границы слоев и правила изменений: [DEVELOPMENT.md](../docs/ru/DEVELOPMENT.md) и [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md).
Одинаковые `Idempotency-Key` и тело возвращают исходный снимок `201` в течение 24 часов, даже после редактирования профиля. Миграция `00019_create_organization_creation_results.sql` хранит снимок отдельно от действующей организации. 24 часа задают логическое окно повтора. Ограниченная очистка запускается при успешных созданиях; физическое удаление может произойти позже и удаляет снимок вместе с общей записью idempotency. `GET /api/v1/me/organizations` постранично возвращает активные членства текущего работодателя. Пути приглашений защищены общей проверкой владельца; операции с черновиками и отправка описаны в разделе [Черновики приглашений](#черновики-приглашений), остальные операции приглашений организации после этой проверки отвечают 501.
`TestOrganizationCreationAndOwnerEditingOverHTTP` проверяет в PostgreSQL параллельный повтор, откат при ошибке вставки владельца, запрет чужого доступа, сохранение данных после пересоздания API и повторное использование истекшего ключа.
Организация сохраняется в холдинге аккаунта-владельца: `CreateWithOwner` создает холдинг (таблица `holdings`, миграция `00041_create_holdings.sql`) в той же транзакции при первой организации аккаунта. E0-лимиты приглашений и просмотров карточек общие для всех E0-организаций холдинга; правила пула и блокировок описаны в [квотах компании](../docs/ru/COMPANY_QUOTAS.md#пул-холдинга). `TestHoldings` проверяет общий пул, изоляцию аккаунтов, конкурентные резервирования и параллельное создание, а `TestHoldingsMigrationBackfillsFoundersAndGuardsRollback` - заполнение миграции и защищенный откат.
`TestCompanyContextChecksLiveOwnerMembershipAndListsOwnOrganizations` проверяет изоляцию компаний, отказ кандидату даже с вручную добавленным членством, отказ другим ролям, пагинацию и отзыв доступа владельца с той же cookie. Компания в справочнике активных членств не дает права владельца; сервер проверяет роль на каждом запросе.
## Потребности организаций
Потребности организаций сохраняются в PostgreSQL через связанный с транзакцией `UnitOfWork.Needs()`. Миграция `00023_create_organization_needs.sql` добавляет указатель текущей версии и неизменяемые снимки в области организации. Создание начинается с версии 1. Измененный снимок повышает версию через compare-and-swap; проигравший конкурентный запрос получает конфликт версии. Контракт HTTP использует для него 412.
Операции создания, чтения, списка и изменения доступны владельцу и находятся в `internal/adapter/primary/http/v1/need.go`. Каждая операция проверяет текущую подтвержденную учетную запись работодателя и блокирует активное членство владельца в транзакции. Курсор списка содержит область учетной записи и организации. Создание сохраняет исходный публичный ответ на 24 часа для повторов с тем же ключом, даже после последующего изменения.
Исходный текст разбирается локально детерминированными правилами в неподтвержденные предложения. Неизвестные и неоднозначные значения остаются неизвестными. Подтверждение сохраненного предложения сохраняет его происхождение; ручная замена получает ручное происхождение. Изменение исходного текста сохраняет подтвержденные значения, а удаление предложения запрещает разбору незаметно восстановить его позднее. Готовность вычисляется по подтвержденным требованиям. Рекомендации категорий пока возвращают `not_available` без подтвержденных навыков и `pending` в остальных случаях; вычисление рекомендаций категорий еще не реализовано.
`requirements_version` указывает на снимок последнего изменения подтвержденных требований. Правка только названия, исходного текста или неподтвержденных предложений сохраняет эту ссылку. Доменный no-op сохраняет обе версии. Снимки сохраняют происхождение полей, отклоняют слишком большой объем данных и используют время UTC с точностью до микросекунд. Чтение текущей и исторической версии требует ID организации; обычные UPDATE и DELETE истории запрещены. Откат миграции удаляет обе таблицы вместе с историей, поэтому после записи данных он приводит к их потере.
`TestOrganizationNeedsStorage` проверяет на настоящем PostgreSQL изоляцию, историю, конкурентные обновления, откат транзакции, неизменяемость снимков и ограничения объема. Вызывающая бизнес-операция должна применять существующую проверку активного владельца; область организации в хранилище сама по себе не дает доступа к компании.
Миграция `00026_create_organization_need_creation_results.sql` добавляет хранение ответа создания и запас 8 KiB для пробелов в представлении JSONB. Ограничение компактного доменного снимка остается 256 KiB. Обратная миграция отказывается удалять действующие результаты повторов или восстанавливать прежний предел БД поверх более крупных сохраненных снимков. Перед откатом нужно проверить эти условия; история потребностей не удаляется ради успешного отката.
## Черновики приглашений
Реализована сторона организации в черновике приглашения: `GET` и `POST /api/v1/organizations/{org_id}/invitations` и `GET` и `PATCH /api/v1/organizations/{org_id}/invitations/{invitation_id}` (`usecase/invitation/`, `adapter/primary/http/v1/invitation.go`). Отзыв, повышение вилки, чтение контактов, принятие и отмена участия после общих проверок по-прежнему отвечают 501. Кандидат черновик не видит, входящую запись, событие и использование квоты он не пишет.
Миграция `00037_create_invitations.sql` добавляет `invitations`, неизменяемые `invitation_terms_versions`, добавляемые только в конец `invitation_events` (одно событие аудита на каждую зафиксированную версию) и `invitation_creation_results` (исходный ответ идемпотентного создания). Деньги - целые рубли в `bigint`; `domain.SalaryRange` - единственная реализация правила вилки для потребностей и приглашений, а таблица условий повторяет ее в ограничениях (границы и шаг, `A < B`, ширина 10-40% в целых числах), поэтому другой писатель не сохранит вилку, которую API отклоняет. Изменение условий добавляет следующую версию условий; прежнюю нельзя изменить или удалить. Кандидат хранится как внутренний `candidate_id`, а показывается только handle карточки, привязанным к организации. Откат миграции отказывает, пока есть хотя бы одно приглашение, и ничего не удаляет. Таблицы, решения, блокировки и нереализованное описаны в [архитектуре](../docs/ru/ARCHITECTURE.md#черновики-приглашений), контракт - в [api/README.md](../api/README.md#приглашения-и-контактные-разрешения).
`candidateview.Service.ResolveCandidateHandle` разрешает handle в транзакции создания проверками чтения карточки (членство, действующая публикация C2, скрытие организации, минимальная когорта) и не списывает квоту. Неизвестный handle, handle другой организации, скрытый или неопубликованный кандидат и подавленная карточка дают один и тот же 400 на `/candidate_handle`. Создание идемпотентно 24 часа и повторяет сохраненный 201. Изменение отвечает 200 на тело, которое ничего не меняет, затем сравнивает версию (412), затем состояние (409), затем правила (400). Обе команды берут блокировку организации до блокировок членства и приглашения. `salary_fit` равен `not_available`, пока нет лимита против подбора минимума.
Интеграционные тесты `TestOrganizationInvitationDraftsOverHTTP` (роутер, сессии, CSRF, фикстуры когорты и скрытия, границы денег, условия пакета, отказы по handle, повтор, защита от перебора, список и курсоры, версии и неизменяемые условия, связь с потребностью, конфликт состояния, конкурентные изменения, конкурентные создания и изменения одной организации без взаимной блокировки и отсутствие значений кандидата в ответах, сохраненных условиях и логах), `TestInvitationRepositoryStoresVersionsAndRefusesLostUpdates`, `TestInvitationTablesRefuseMoneyAndHistoryViolations` (ограничения и триггеры прямым SQL) и `TestInvitationMigrationRollbackKeepsStoredInvitations` работают на настоящем PostgreSQL.
Реализована отправка: `POST /api/v1/organizations/{org_id}/invitations/{invitation_id}/send` (`usecase/invitation/send.go`) и список кандидата `GET /api/v1/me/invitations` (`usecase/invitation/candidate_inbox.go`). Одна транзакция берет блокировку организации, членство владельца, ключ и строку приглашения, проверяет версию и состояние, снова разрешает сохраненного кандидата через барьер видимости карточки (409 при скрытии, отзыве C2 или подавлении), списывает квоту организации через `companyquota.Service.ReserveInvitation` (429 с `Retry-After`), переводит черновик в `delivered` с `response_deadline_at = delivered_at + response_period_days`, добавляет событие аудита `delivered` и пишет события outbox `invitation.delivered` и `notification.mail_requested` (`usecase/notification/invitation.go`). Поэтому успех означает, что приглашение уже в списке кандидата; уведомление и письмо идут следом через обработчики, и ни они, ни их повторы срок не меняют. Повтор с тем же ключом возвращает сохраненный исход, а отправка доставленного приглашения отвечает 200 с текущим состоянием без второго списания. Миграция `00038_send_invitations.sql` добавляет вид события `delivered`, `invitation_send_results` (200, 404 или 409 под ключом) и внешний ключ из `company_invitation_quota_usage` на `invitations`; ее откат отказывает, пока есть событие доставки или сохраненный исход. Подробности - в [архитектуре](../docs/ru/ARCHITECTURE.md#отправка-приглашений). `TestOrganizationInvitationSendOverHTTP` и `TestInvitationSendMigrationKeepsDeliveriesAndKeysQuotaUsage` проверяют это на настоящем PostgreSQL.
Предел ожидающих приглашений на потребность, 30-дневная пауза после отказа и истечение по сроку реализованы. Отправка проверяет предел (`max_pending_per_need`) и паузу (`repeat_after_decline_days`) из эффективной политики до списания квоты и отвечает 409 `state_conflict`; в той же транзакции она ставит задание `invitation.response_deadline` на срок ответа. Обработчик `usecase/invitation/expire.go` переводит ожидающее приглашение в `expired` с причиной `invitation_timeout`, а команды кандидата в срок или позже применяют истечение первыми. Миграция `00043_expire_invitations.sql` добавляет вид события `expired` без актора, триггер `invitations_guard_expiry`, частичные индексы и задания для уже доставленных приглашений. Подробности - в [архитектуре](../docs/ru/ARCHITECTURE.md#предел-ожидающих-пауза-и-истечение). `TestInvitationPendingLimitAdmitsOneOfTwoConcurrentSendsOverPostgres`, `TestInvitationPauseAfterADeclineHoldsForThirtyDaysOverPostgres`, `TestInvitationAcceptAtTheDeadlineRacesTheExpiryJobOverPostgres` и `TestInvitationExpiryMigrationBackfillsDeadlineJobsAndGuardsExpiries` проверяют это на настоящем PostgreSQL.
Реализованы чтение, просмотр, отказ и принятие кандидата: `GET /api/v1/me/invitations/{invitation_id}`, `POST .../view` и `POST .../decline` (`usecase/invitation/view.go` и `decline.go`). Чтение ничего не записывает, кроме истечения срока; просмотр переводит `delivered` в `viewed` до срока, сохраняет срок, в срок или позже сначала применяет истечение, а иначе отвечает приглашением как есть; отказ переводит `delivered`, `viewed` или запланированное `counter` в `declined` до срока с причиной и необязательным комментарием и не создает ни согласия, ни разрешения. Просмотр и принятие блокируют только строку приглашения, а отказ дополнительно берет блокировку организации, чтобы упорядочить паузу пары; команды добавляют события аудита `viewed` и `declined`. Опоздавший отказ отвечает 409 после применения истечения, а у отказанного приглашения `contact_consent` и `contact_grant` равны null. Миграция `00039_answer_invitations.sql` добавляет виды событий, правила состояния для просмотра и ответа, `invitation_declines` (причина и комментарий, которые организация никогда не читает) и `invitation_decline_results` (исход под ключом); ее откат отказывает, пока есть просмотр, отказ или исход. Подробности - в [архитектуре](../docs/ru/ARCHITECTURE.md#просмотр-и-отказ-кандидата). `TestCandidateInvitationViewAndDeclineOverHTTP` и `TestInvitationAnswerMigrationGuardsAnswersAndRefusesRollback` проверяют это на настоящем PostgreSQL.
Принятие кандидатом реализовано: `POST /api/v1/me/invitations/{invitation_id}/accept` (`usecase/invitation/accept.go`). Одна транзакция блокирует строку приглашения, переводит доставленное или просмотренное приглашение до срока в `accepted` при версии приглашения и версии условий, которые прочитал кандидат, записывает согласие C4 через `consent.Service.GrantContact` (опубликованный текст и выбранные поля), сохраняет разрешение ровно на выбранные поля в `contact_grants` и добавляет событие аудита `accepted`. Устаревшая версия отвечает 412 и не сохраняется; правила согласия отвечают 400 с указателем под `/consent_c4`; повтор отвечает сохраненным принятием, другой набор полей отвечает 409 `state_conflict`. Принятие никогда не публикует профиль и не снимает скрытие: разрешение читается только пока организация может читать профиль. Миграция `00040_accept_invitations.sql` добавляет вид события, таблицу разрешений с составными ключами на приглашение, кандидата и запись C4, таблицу исходов и отказ отката, пока принятие существует. Подробности - в [архитектуре](../docs/ru/ARCHITECTURE.md#принятие-кандидатом). `TestCandidateInvitationAcceptOverHTTP` и `TestInvitationAcceptMigrationGuardsAcceptancesAndRefusesRollback` проверяют это на настоящем PostgreSQL.
Чтение контактов реализовано: `GET /api/v1/organizations/{org_id}/invitations/{invitation_id}/contacts` (`usecase/invitation/contacts.go`, обработчик `adapter/primary/http/v1/contacts.go`). Операция доступна только владельцу. Каждый запрос заново проверяет под блокировками членство, запись C4, разрешение с его видами и видимость публикации, а любой закрытый случай отвечает 404 `not_found`. Успешное чтение пишет одну строку `contact_read` в `candidate_card_access_events` и не расходует квоту просмотров карточек. Отзыв C4 закрывает разрешения, которые ссылаются на его записи, отзыв C2 или закрытие публикации закрывают все разрешения кандидата, а скрытие организации закрывает ее разрешения; снятие скрытия и повторная публикация их никогда не открывают. Миграция `00042_index_contact_grants_by_candidate.sql` добавляет индекс для этих закрытий. Подробности в [архитектуре](../docs/ru/ARCHITECTURE.md#чтение-контактов-и-отзыв). `TestOrganizationContactReadsAndRevocationOverHTTP` покрывает это на настоящем PostgreSQL.
## Обращения в поддержку
Подтвержденные аккаунты создают и просматривают список собственных обращений через `/api/v1/me/support-cases`, а отдельное дело читают по его ID. Владение обращением не зависит от доступа к спорному действию. Ссылка на объект содержит только тип и ID; сервер проверяет область доступа и не копирует приватное содержимое объекта. Работодатели отправляют общие запросы поддержки. Кандидаты также могут запросить ручную оценку без предыдущей попытки и согласия C3. Такой запрос ожидает эксперта, не назначает грейд и не выдает согласие.
Ручной запрос фиксирует текущую опубликованную рубрику для выбранных специализации и грейда. API показывает версию политики оценивания; внутренние ссылки сохраняют точное открытие категории и неизменяемый набор версий семейств. Последующие публикации не меняют рубрику существующего обращения. При отсутствии однозначной актуальной рубрики версия остается `null`, а обращение ожидает эксперта.
Для создания нужен явный раздел поддержки в действующей продуктовой политике. Он есть в `DemoProductPolicyV2`; обычный запуск по-прежнему создает только неизменяемую политику V1. Демо-срок составляет пять рабочих дней для поддержки, жалоб и ручной оценки и десять для апелляций. Версионированный календарь считает будни UTC без государственных праздников и не приостанавливает срок при ожидании пользователя. Это операционные ориентиры, а не юридические сроки.
Скользящий лимит запросов аккаунта проверяется под блокировкой БД до идемпотентного повтора. Корректные повторы расходуют этот бюджет и возвращают исходный ответ создания в течение 24 часов. Ответ 429 содержит `Retry-After`. GET и список показывают актуальный статус, публичную историю и текущий признак просрочки. Миграция `00025_create_support_cases.sql` хранит неизменяемые события и результаты повторов; откат удаляет эти записи и является разрушительным.
Правила ручной оценки лежат в `internal/usecase/supportcase/manual_assessment.go`: запрос не читает и не меняет согласия, не создает попытку и не пишет грейд или категорию, а предыдущая попытка нужна не всегда и может быть неудачной.
`TestManualAssessmentRequestAfterC3Refusal` проходит через настоящий роутер: выдача и отзыв C3, запрос до первого теста с зафиксированной рубрикой, запрос без опубликованной рубрики (`rubric_version` равна `null`), запрос после неудачной и после подтвержденной попытки. Тест сравнивает журнал согласий и события, попытки и неизменяемые результаты до и после запроса и проверяет, что повтор с новым ключом оставляет одно открытое обращение.
`TestSupportCasesOverHTTP` проверяет настоящие сессии, изоляцию владельцев, типизированные ссылки, повторы, ручную оценку без C3 и лимиты запросов. `TestSupportCaseRequestBudgetSerializesTimestampWithOwnerLock` проверяет конкурентные запросы и порядок времени. Обработка экспертом и ссылки на еще не реализованные приглашения или античит-проверки остаются недоступны.
## Анкета кандидата
Подтвержденный кандидат читает и заменяет собственную анкету через `GET/PUT /api/v1/me/questionnaire`. Анкета имеет отдельную версию и хранит самооценку, форматы работы, необязательные суммы опыта и одну или две специализации. Она не назначает подтвержденные грейды. Идентичный повтор возвращает сохраненную запись без повышения версии; измененное тело с устаревшей версией получает 412 согласно контракту API. Одновременные одинаковые записи также возвращают одну победившую запись.
Сохранение переводит onboarding только из `candidate_questionnaire` в `candidate_assessment` в той же транзакции. Другие сохраненные шаги не меняются. Настройки согласий пока не завершают шаг согласий в onboarding.
Публичный каталог специализаций определяет готовность по текущему опубликованному банку, текущей политике и неизменяемому решению проверки, связанному с конкретным открытием категории и составом опубликованных семейств. Старые открытия без такой связи остаются недоступными. Смена политики или отзыв семейства закрывает готовность до нового проверенного открытия; сохраненные ответы остаются читаемыми. Имена операторов являются заявленными метаданными проверки, а не аутентифицированной личностью оператора.
`TestCandidateQuestionnaireOverHTTP` проверяет сохранность, изоляцию аккаунтов, конкурентные версии, откат, условный переход шага и изменение доступности банка. Хранилище квот компании и порядок его вызова описаны в [квотах компании](../docs/ru/COMPANY_QUOTAS.md).
## Попытки оценки
Кандидат создает попытку через `POST /api/v1/me/assessment-attempts`, читает ее по ID и возобновляет работу командой `POST /api/v1/me/assessment-attempts/{attempt_id}/sessions`. Реальная оценка требует действующего C3; история собственной попытки остается доступной после его отзыва. GET не расходует сессии и не меняет состояние. Команда с устаревшей версией возвращает 412.
Создание фиксирует версии политики, банка и алгоритма, опубликованный набор семейств и сгенерированные экземпляры вопросов. Ответ API не содержит ключей ответов, seed или приватных рубрик. Квота корневых попыток общая для кандидата, а ограничения повторов и повышения грейда действуют по специализации. Корректирующая попытка сохраняет корень и исходный срок цепочки. Учебный `demo_express` использует отдельный явно опубликованный банк и не расходует квоту реальной оценки.
Повтор команды с тем же ключом и телом возвращает сохраненный ответ в течение 24 часов. Повтор ключа с другим телом возвращает 422; недоступный банк или исчерпанная квота - 409 `state_conflict`. PostgreSQL сериализует проверку квоты и изменения сессии, а доменное время берется после ожидания блокировок. Миграция 24 добавляет попытки, экземпляры вопросов, учебные привязки и сохраненные ответы команд; ее откат удаляет эти данные.
Прием ответа проверяет закрепленный серверный ключ и сохраняет каждый ответ один раз. Сравнение чисел сохраняет исходную числовую запись JSON без округления через плавающую точку; ответ с порядком должен содержать каждую задачу ровно один раз. Завершение отклоняет неотвеченные обязательные вопросы с перечнем их ID, затем сохраняет сырой базовый балл, правило политики, закрепленные версии и представление результата в одной транзакции. Чтение использует этот неизменяемый результат. Длительность не добавляет баллы, последние seed-вопросы не оцениваются, а экспресс-результат не содержит квалификационного балла. Миграция 29 запрещает откат при наличии зависящих от нее записей команд или результатов. Базовый порог не подтверждает калибровку.
Демонстрационная категория. Завершение реальной попытки записывает результат версии 2: к неизменяемому документу добавляются решение о категории и грейд, действовавший на момент решения (миграция 31). Результат `demo_express` остается записью версии 1 без этих полей и никогда не создает категорию. Решение зависит от порога `basic_pass_mark_bp` версии политики, закрепленной за попыткой; обработчик HTTP параметров не задает. Строка текущей категории (`candidate_assessment_categories`, по одной на кандидата и специализацию) появляется, только если одновременно выполнено следующее: включен `ASSESSMENT_DEMO_CATEGORIES_ENABLED` (по умолчанию выключен; включать только на синтетическом стенде), закрепленная политика является полной демонстрационной политикой с `demo_basic` (порог берется из ее `basic_pass_mark_bp`), результат подтвержден, а для точного открытия категории, манифеста каталога и версии политики есть аттестация оператора (`assessment_synthetic_category_reviews`, `source = synthetic_demo`). Иначе решение записывается как `not_eligible` или `not_confirmed`. Блокировка кандидата и специализации сериализует повышения; база принимает только строгое повышение, запрещает удаление и ручную подмену источника, а текущая категория всегда ссылается на сохраненный результат версии 2 того же кандидата. Неудача, равный или более низкий грейд сохраняют действующую категорию, а обе попытки остаются в истории.
История кандидата читается через `GET /api/v1/me/assessment-results` (`usecase/assessment/category_history.go`): только собственные `root` и `corrective` результаты, постранично, с курсором, привязанным к кандидату серверным HMAC. Работодатель историю не получает; отдельная проекция текущей категории входит в запрос видимых кандидатов (`privacy_cohort.sql`) и выбирает только специализацию и грейд, поэтому анонимная карточка показывает категорию с силой `standard`, если кандидат опубликовал поле `categories`. Смена текущей политики не меняет сохраненные результаты и категории; открытые категории привязаны к политике, под которой их открыли, поэтому после новой версии политики попытки не создаются, пока категории не открыты заново. Аттестацию создает локальная команда `make -C backend assessment-category-attest` (см. [DEPLOY.md](../docs/ru/DEPLOY.md#демонстрационные-категории-на-стенде)). Не реализована калибровка порога.
## Сигналы прохождения оценки
Доступный только кандидату `POST /api/v1/me/assessment-attempts/{attempt_id}/signals` принимает пакеты длительностей потери фокуса, размеров событий буфера обмена и выходов из полноэкранного режима. Содержимое буфера и ответов не сохраняется; `size_bytes` для вставки - байты UTF-8 вставленного текста плюс размер файлов, посчитанные на устройстве, а для копирования и вырезания - приблизительная длина выделения в единицах UTF-16 (текст не читается); камера, микрофон, скриншоты и запись экрана не поддерживаются. События привязаны к собственной реальной попытке и одному из ее закрепленных вопросов; учебные попытки их не принимают. Новый пакет требует действующего C3 и активной попытки.
Операция ограничивает тело 32 КиБ, пакет 50 событиями, новые квитанции приема 30 в минуту на попытку, а хранение 10 000 событиями на попытку. Вместимость проверяется для всего пакета. При заполнении принимается ноль событий; идемпотентный повтор возвращает исходную квитанцию без расходования лимита. Клиентское время считается недоверенными метаданными: метка вне окна от создания попытки минус пять минут до времени БД плюс пять минут отклоняет весь пакет с 400, поэтому клиент приводит метки к серверному времени по заголовку `Date`; окна частоты используют время БД. Миграция 28 каскадно удаляет события, пакеты и квитанции вместе с попыткой. Действующие ограничения хранения согласий по-прежнему запрещают физическое удаление аккаунта; этот каскад не реализует удаление аккаунта. Интерпретация сигналов относится к отдельной работе.
Уведомление о собираемых сигналах хранится отдельно. `GET` и `PUT /api/v1/me/assessment-signal-notice` читают и записывают подтверждение ознакомления кандидата с версией текста (`usecase/assessment/signal_notice.go`, таблица `assessment_signal_notice_acknowledgements`, миграция 34). Версию текста задает сервер (`CurrentSignalNoticeVersion`, сейчас 4: версия 2 добавила к перечню сигналов меры, которые страница применяет во время попытки, версия 3 описала водяной знак экрана и текста задания, а версия 4 добавила подсказки о съемке, отпечаток User-Agent и правило одного окна); подтверждение хранится для каждой версии отдельно, поэтому данное для более ранней версии остается в таблице, но для текущей не засчитывается, а новый текст не требует миграции. `PUT` с другой версией отвечает 409 и ничего не сохраняет, а повтор сохраняет время первого подтверждения. Подтверждение не является согласием: операция приема сигналов его не читает и по-прежнему требует действующего C3, поэтому уведомление нельзя использовать, чтобы скрыть согласие. Создание попытки подтверждение на сервере не проверяет; требование задает экран кандидата. Строки удаляются каскадом вместе с пользователем.
## Анонимная проекция профиля
Проекция для организации использует HMAC-псевдонимы с разделением назначений ключей, закрытый справочник навыков, диапазоны стажа и явно выбранные поля публикации. Подтвержденные категории и самооценка разделены. Контакты, работодатели, свободный текст, точная зарплата и идентификаторы аккаунта исключены. Пересекающиеся периоды работы учитываются один раз.
Репозиторий проверяет актуальную публикацию по C2 и скрытые организации до построения группы. Полные комбинации видимых признаков, которым соответствуют меньше пяти кандидатов, обобщаются или скрываются. Это снижает риск идентификации, но не гарантирует анонимность. Приватный псевдоним предпросмотра владельца использует отдельное назначение. Категория и денежная совместимость отсутствуют до получения данных от авторитетного источника; заявленный грейд не заменяет подтверждение.
Кандидат читает настройки через `GET /api/v1/me/privacy`, предпросмотр - через `GET /api/v1/me/privacy/preview`, историю изменений - через `GET /api/v1/me/privacy/history`, а просмотры карточки - через `GET /api/v1/me/privacy/access-history`. Скрытые компании доступны через `GET /api/v1/me/privacy/hidden-organizations` и меняются через `PUT/DELETE /api/v1/me/privacy/hidden-organizations/{org_id}`. Публикация и статус поиска меняются через `PUT /api/v1/me/privacy/publication` и `PUT /api/v1/me/privacy/search-status`. Данные доступны только из текущей сессии кандидата, ответы имеют `Cache-Control: no-store`, а изменения требуют CSRF-токен сессии и точный разрешенный Origin. C2, публикация, статус поиска и скрытые компании независимы: один параметр не включает остальные. Поиск остается заявлением кандидата, а не согласием.
Работодатель с подтвержденной учетной записью и активным членством читает карточку по `GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}`. Каждый запрос заново проверяет членство, действующее C2, публикацию, скрытие для этой компании и минимальный размер группы; успешный просмотр и расход квоты записываются в одной транзакции. Закрытая, отозванная, скрытая или подавленная карточка не раскрывается и отвечает так же, как неизвестный псевдоним. Кандидат видит записи об успешных просмотрах карточки в своей истории доступа. Операция чтения контактов и управление грантами C4 пока недоступны; карточка контактов не содержит.
## Доказательства навыков
Подтвержденный настоящий результат оценки оставляет один факт доказательства на попытку; его пишет база в той же транзакции, что сохраняет результат (миграция 35, триггер на `assessment_attempt_results` и функция `skill_evidence_project_assessment_result`). Миграция также проецирует уже существующие результаты. Экспресс-прогон, проваленная попытка и результат без проверенного источника категории фактов не оставляют. Навыки события - теги его факта, поэтому несколько тегов остаются одним фактом, а у онлайн-оценки без надежного подтверждения личности доверие 1.
Кандидат читает факты через `GET /api/v1/me/evidence` (`usecase/evidence/read.go`, запрос `ListCandidateEvidenceFacts`); работодатель читает разрешенную проекцию через `GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}/evidence`, которая выполняет проверки чтения карточки (`candidateview.Service.AuthorizeCategoriesSection`: членство, действующая публикация с C2, скрытие, минимальная когорта, квота, аудит доступа), а затем запрос `ListOrganizationVisibleEvidence` (представление действующих публикаций, `NOT EXISTS` по скрытым организациям, поле `categories`, видимые измерения, по одному факту на каждую категорию карточки, подтверждающему ее грейд, белый список из шести колонок: навык, грейд, доверие, основание, калибровка, год). Предпросмотр кандидата (`GetMyCardPreview`) показывает тот же раздел через `ListCandidatePreviewEvidence`. Чтения трогают только две таблицы доказательств; `backend/db/evidence_queries_test.go` падает, если запрос доказательств называет таблицу результатов, попыток, ответов, сигналов или проверок. Факты, теги и правила описаны в [архитектуре](../docs/ru/ARCHITECTURE.md#доказательства-навыков). Интеграционный тест `TestSkillEvidenceOverHTTP` выполняется на настоящем PostgreSQL и проверяет: факт, связанный с результатом, с доверием 1, два дополнительных тега одного события, экспресс-прогон и проваленная попытка, постраничное чтение, проекция организации при выданном и отозванном C2, скрытая организация, скрытый факт, карточка без категорий теги, которые могут присоединиться к факту только в создавшей его транзакции, удаление аккаунта с фактами по обоим каскадным путям, отказ откатывать миграцию, пока есть скрытый факт, и перестроение после отката и повторного применения миграции.
## Подбор
`POST /api/v1/organizations/{org_id}/matches` ранжирует банк кандидатов, видимый организации, без ML (`usecase/matching/`). Он выполняется в одной транзакции: `candidateview.Service.ListVisibleCards` применяет проверки чтения карточки (подтвержденный работодатель, заблокированное действующее членство, `ListVisibleCandidateViewSources` по `candidate_effective_publications` с `NOT EXISTS` по скрытым организациям, блокировки аккаунта, C2 и публикации и анонимная проекция с минимальной когортой из пяти), снимок потребности читается по `requirements_version`, а разрешенные доказательства приходят только из `ListOrganizationFacts`. Usecase повторяет проверку роли владельца; HTTP-граница перечисляет операцию в `ownerCompanyOperations`. Поиск оплачивается как чтение карточек: каждая группа обрезается до предела политики, а каждый возвращенный кандидат резервируется через порт квоты компании и записывается в историю доступа с возвращенными полями (`candidateview.SearchViews`); когда лимит заканчивается, ответ обрезается и получает флаг `truncated`. Раздел подбора оператор публикует командой `make policy-publish ARGS='matching --actor operator:<handle>'` (`cmd/policy-publish`), семантический раздел - `ARGS='semantic --actor operator:<handle>'`, ансамбль Giga + Qwen3-Embedding - `ARGS='semantic-ensemble --actor operator:<handle>'`, а векторы существующих данных ставит `make semantic-backfill ARGS='all --run <метка>'` (`cmd/semantic-backfill`), см. [DEPLOY](../docs/ru/DEPLOY.md#политика-подбора-на-стенде) и [семантический подбор](../docs/ru/DEPLOY.md#семантический-подбор). Поиск сам ML не вызывает: он читает векторы, которые считают задания `semantic.candidate` и `semantic.need` (`usecase/semantic/`).
Каждая запись - одна специализация кандидата. Баллы используют раздел `matching` действующей политики `product` (`domain.MatchingPolicy`, демонстрационная версия `DemoProductPolicyV4`); политика без раздела приводит к закрытому отказу. Арифметика целочисленная (микроединицы для компонентов, базисные пункты для долей), поэтому порядок воспроизводим: подтвержденные группы сортируются по S, затем по покрытию, затем по внутреннему идентификатору кандидата; неподтвержденная - по Fit, затем по покрытию, затем по идентификатору, и она никогда не вычисляет theta, T, P, перцентиль или S. Объяснение и признаки неизвестности строятся из тех же рассчитанных вкладов. Модель, нейтральные значения и нереализованное описаны в [архитектуре](../docs/ru/ARCHITECTURE.md#подбор-и-объяснение).
Интеграционный тест `TestMatchSearchOverHTTP` работает на настоящем PostgreSQL через настоящий маршрутизатор и операции профиля, согласий, публикации, потребностей, организаций и оценки: скрытые кандидаты и две организации, потребность и ее измененные требования, повторные одинаковые ответы, один handle подтвержден по Backend и не подтвержден по сетям, профиль без грейда, опубликованный и убранный отзывом C2, кандидат один в своей когорте, отсутствие контактов и идентификаторов в теле, оплата и история доступа за поиск, организация с лимитом меньше ее банка, предел группы, отказы доступа и политика без раздела. Браузерный стенд `questionnaire-fixture` публикует `DemoProductPolicyV4`, поэтому локальный стенд имеет раздел подбора.
Подробнее: [архитектура](../docs/ru/ARCHITECTURE.md) и [разработка](../docs/ru/DEVELOPMENT.md).
## Внутренние уведомления
Inbox хранит ссылку на доставленное событие для одного получателя (`notification_inbox_events`, миграции 32 и 36), но не его текст. Обработчик `notification_inbox` (`usecase/notification/inbox_handler.go`) пишет строку в транзакции своего dedup-маркера; ключ `(recipient_user_id, event_id)` держит одну строку на получателя и событие, а ID события, пришедший снова с другими метаданными, отклоняется. Строка существует независимо от того, отправлено ли письмо, и обработчик не читает состояние почты.
Текст вычисляется при чтении списка (`usecase/notification/inbox.go`, `inbox_content.go`): `InboxService` проверяет кабинет в транзакции чтения (подтвержденный кандидат для `GET /api/v1/me/notifications`; подтвержденный работодатель с активным членством для `GET /api/v1/organizations/{org_id}/notifications`), затем просит преобразователь типа источника каждого элемента дать содержимое, которое получатель вправе видеть сейчас. Исчезнувший или скрытый источник оставляет элемент в списке без содержимого. Отметка (`POST .../{notification_id}/read`) сохраняет первое время прочтения и не читает источник. Чужой элемент, элемент другой организации и неизвестный элемент дают 404.
Источник добавляет событие `invitation.delivered` с payload `recipient_user_id` и `organization_id` и регистрирует преобразователь для своего источника; так делает отправка приглашения, а синтетическое событие `notification.synthetic_delivered` проверяет путь и продуктового смысла не имеет. Контракт описан в [docs/ru/ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#внутренние-уведомления) и [api/README.md](../api/README.md#уведомления).
Отчет о покрытии запланированных семейств банка оценки: `make -C backend bank-coverage`. Команда сопоставляет валидные семейства из JSON-бандлов с манифестом и проверяет наличие путей Go/Python для backend-семейств. Отчетный режим показывает неполноту без ошибки; `make -C backend bank-coverage-check` включает строгую проверку. Наличие файла не подтверждает эквивалентность реализации, независимость рецензента или калибровку; эти требования остаются отдельными внешними проверками.
@@ -0,0 +1,16 @@
// Command assessment-bank-coverage reports assessment bank inventory coverage.
package main
import (
"fmt"
"os"
"lincodex/backend/internal/adapter/primary/cli/bankcoverage"
)
func main() {
if err := bankcoverage.Run(os.Args[1:], os.Stdout, os.Stderr); err != nil {
_, _ = fmt.Fprintf(os.Stderr, "assessment-bank-coverage: %v\n", err)
os.Exit(1)
}
}
@@ -0,0 +1,225 @@
// Package bankcoverage implements the local assessment bank coverage command.
package bankcoverage
import (
"bytes"
"errors"
"flag"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
assessment "lincodex/backend/internal/usecase/assessment"
)
// Run reports how valid bundle drafts and implementation paths match the bank manifest.
func Run(arguments []string, stdout, stderr io.Writer) error {
const location = "bankcoverage.Run"
flags := flag.NewFlagSet("assessment-bank-coverage", flag.ContinueOnError)
flags.SetOutput(stderr)
manifestPath := flags.String("manifest", "testdata/assessment/bank_manifest.json", "path to the planned bank manifest")
bundleDir := flags.String("bundles", "testdata/assessment", "directory containing bank bundle JSON files and solution files")
strict := flags.Bool("strict", false, "fail when planned families, review declarations, or implementation paths are missing")
if err := flags.Parse(arguments); err != nil {
return fmt.Errorf("%s - parse arguments: %w", location, err)
}
if flags.NArg() != 0 {
return fmt.Errorf("%s - unexpected positional arguments", location)
}
content, err := os.ReadFile(*manifestPath)
if err != nil {
return fmt.Errorf("%s - read manifest: %w", location, err)
}
manifest, err := assessment.ParseBankCoverageManifest(content)
if err != nil {
return err
}
inventory, err := loadBankCoverageInventory(*bundleDir, *manifestPath, manifest)
if err != nil {
return fmt.Errorf("%s - load bundle inventory: %w", location, err)
}
report, err := assessment.BuildBankCoverageReport(manifest, inventory)
if err != nil {
return fmt.Errorf("%s - build report: %w", location, err)
}
if err := printBankCoverageReport(stdout, report); err != nil {
return fmt.Errorf("%s - write report: %w", location, err)
}
if *strict {
return report.StrictError()
}
return nil
}
func loadBankCoverageInventory(bundleDir, manifestPath string, manifest assessment.BankCoverageManifest) (result assessment.BankCoverageInventory, returnErr error) {
const location = "bankcoverage.loadBankCoverageInventory"
manifestPath, err := canonicalPath(manifestPath)
if err != nil {
return assessment.BankCoverageInventory{}, fmt.Errorf("%s - resolve manifest path: %w", location, err)
}
bundleRoot, err := os.OpenRoot(bundleDir)
if err != nil {
return assessment.BankCoverageInventory{}, fmt.Errorf("%s - open bundle directory: %w", location, err)
}
defer func() {
if err := bundleRoot.Close(); err != nil {
returnErr = errors.Join(returnErr, fmt.Errorf("%s - close bundle directory: %w", location, err))
}
}()
inventory := assessment.BankCoverageInventory{}
err = fs.WalkDir(bundleRoot.FS(), ".", func(path string, entry fs.DirEntry, walkErr error) error {
if walkErr != nil {
return fmt.Errorf("%s - scan bundle directory: %w", location, walkErr)
}
if entry.IsDir() || filepath.Ext(path) != ".json" {
return nil
}
candidatePath, err := canonicalPath(filepath.Join(bundleDir, filepath.FromSlash(path)))
if err != nil {
return fmt.Errorf("%s - resolve candidate path %s: %w", location, filepath.ToSlash(path), err)
}
if candidatePath == manifestPath {
return nil
}
content, err := bundleRoot.ReadFile(filepath.FromSlash(path))
if err != nil {
return fmt.Errorf("%s - read bundle %s: %w", location, filepath.ToSlash(path), err)
}
bundle, err := assessment.ParseBundle(bytes.NewReader(content))
if err != nil {
inventory.InvalidBundleFiles = append(inventory.InvalidBundleFiles, fmt.Sprintf("%s: %v", filepath.ToSlash(path), err))
return nil
}
drafts, err := bundle.Drafts()
if err != nil {
inventory.InvalidBundleFiles = append(inventory.InvalidBundleFiles, fmt.Sprintf("%s: %v", filepath.ToSlash(path), err))
return nil
}
for _, draft := range drafts {
core := draft.Core()
inventory.Families = append(inventory.Families, assessment.BankCoverageFamilyRecord{
Key: string(core.Key), Category: string(core.Category), Version: core.Version,
Author: string(core.Author), Reviewer: string(core.Reviewer),
ReviewStatus: string(core.ReviewStatus), Source: filepath.ToSlash(path),
})
}
return nil
})
if err != nil {
return assessment.BankCoverageInventory{}, err
}
if err := collectImplementationPaths(bundleRoot, manifest, &inventory); err != nil {
return assessment.BankCoverageInventory{}, fmt.Errorf("%s - collect implementation paths: %w", location, err)
}
return inventory, nil
}
func collectImplementationPaths(root *os.Root, manifest assessment.BankCoverageManifest, inventory *assessment.BankCoverageInventory) error {
const location = "bankcoverage.collectImplementationPaths"
for _, category := range manifest.Categories {
for _, topic := range category.Topics {
for _, key := range topic.FamilyKeys {
for _, language := range category.RequiredLanguages {
relative := filepath.Join(category.ImplementationsDir, key+implementationExtension(language))
info, err := root.Stat(relative)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
continue
}
return fmt.Errorf("%s - inspect %s: %w", location, filepath.ToSlash(relative), err)
}
if info.Mode().IsRegular() && info.Size() > 0 {
inventory.ImplementationFiles = append(inventory.ImplementationFiles, filepath.ToSlash(relative))
}
}
}
}
}
return nil
}
func canonicalPath(path string) (string, error) {
absPath, err := filepath.Abs(path)
if err != nil {
return "", err
}
resolvedPath, err := filepath.EvalSymlinks(absPath)
if err != nil {
return "", err
}
return filepath.Clean(resolvedPath), nil
}
func implementationExtension(language string) string {
if language == "python" {
return ".py"
}
return ".go"
}
func printBankCoverageReport(writer io.Writer, report assessment.BankCoverageReport) error {
const location = "bankcoverage.printBankCoverageReport"
write := func(format string, values ...any) error {
if _, err := fmt.Fprintf(writer, format, values...); err != nil {
return fmt.Errorf("%s - write output: %w", location, err)
}
return nil
}
if err := write("Assessment bank coverage inventory\n"); err != nil {
return err
}
if err := write("Family records are valid drafts from bundle files; this report does not publish or calibrate them.\n"); err != nil {
return err
}
for _, category := range report.Categories {
if err := write("%s: %d/%d planned family keys present; %d keys inventoried; %d/%d implementation paths present\n",
category.Code, category.PresentFamilies, category.PlannedFamilies, category.InventoriedFamilies,
category.PresentImplementationFiles, category.RequiredImplementationFiles); err != nil {
return err
}
}
if err := write("Review declarations: %d approved, %d pending, %d rejected; %d distinct family keys inventoried\n",
report.DeclaredApprovedReviews, report.PendingReviewDeclarations, report.RejectedReviewDeclarations, report.InventoriedFamilies); err != nil {
return err
}
for _, names := range []struct {
label string
names []string
}{
{"Missing family keys", report.MissingFamilyKeys},
{"Families without an approved independent reviewer declaration", report.MissingIndependentReviews},
{"Missing Go/Python implementation paths", report.MissingImplementationFiles},
{"Unassigned family keys", report.UnassignedFamilyKeys},
{"Unassigned categories", report.UnassignedCategories},
{"Category mismatches", report.CategoryMismatches},
{"Invalid bundle records", report.InvalidBundleFiles},
{"Evidence not verifiable by this check", report.UnverifiableEvidence},
} {
if err := printNames(writer, names.label, names.names); err != nil {
return fmt.Errorf("%s - print %s: %w", location, names.label, err)
}
}
if report.CalibrationMeasurementRequired {
if err := write("Calibration thresholds remain external measurement gates; no quality result is inferred.\n"); err != nil {
return err
}
}
return nil
}
func printNames(writer io.Writer, label string, names []string) error {
if len(names) == 0 {
return nil
}
if _, err := fmt.Fprintf(writer, "%s (%d):\n", label, len(names)); err != nil {
return err
}
for _, name := range names {
if _, err := fmt.Fprintf(writer, " %s\n", name); err != nil {
return err
}
}
return nil
}
@@ -0,0 +1,115 @@
package bankcoverage
import (
"bytes"
"errors"
"os"
"path/filepath"
"strings"
"testing"
)
const assessmentFixturePath = "../../../../../testdata/assessment"
func TestRunReportsIncompleteInventoryWithoutFailing(t *testing.T) {
manifestPath, bundleDir := prepareCoverageFixtures(t)
var output bytes.Buffer
if err := Run([]string{"--manifest", manifestPath, "--bundles", bundleDir}, &output, &output); err != nil {
t.Fatalf("run() error = %v, want informational success", err)
}
if !strings.Contains(output.String(), "backend: 0/25 planned family keys present") ||
!strings.Contains(output.String(), "network: 0/15 planned family keys present") {
t.Fatalf("report omitted incomplete family counts:\n%s", output.String())
}
}
func TestRunStrictRefusesIncompleteInventory(t *testing.T) {
manifestPath, bundleDir := prepareCoverageFixtures(t)
var output bytes.Buffer
err := Run([]string{"--strict", "--manifest", manifestPath, "--bundles", bundleDir}, &output, &output)
if err == nil || !strings.Contains(err.Error(), "assessment.BankCoverageReport.StrictError") {
t.Fatalf("run(--strict) error = %v, want strict incomplete-inventory error", err)
}
if !strings.Contains(output.String(), "Missing family keys (40)") {
t.Fatalf("strict report omitted missing keys:\n%s", output.String())
}
}
func TestRunReportsMalformedBundleAndStrictModeRejectsIt(t *testing.T) {
manifestPath, bundleDir := prepareCoverageFixtures(t)
malformedPath := filepath.Join(bundleDir, "malformed.json")
if err := os.WriteFile(malformedPath, []byte("not a bundle"), 0o600); err != nil {
t.Fatalf("write malformed bundle: %v", err)
}
var output bytes.Buffer
if err := Run([]string{"--manifest", manifestPath, "--bundles", bundleDir}, &output, &output); err != nil {
t.Fatalf("run() error = %v, want informational success", err)
}
if !strings.Contains(output.String(), "Invalid bundle records (1)") || !strings.Contains(output.String(), "malformed.json") {
t.Fatalf("report omitted malformed bundle diagnostic:\n%s", output.String())
}
if err := Run([]string{"--strict", "--manifest", manifestPath, "--bundles", bundleDir}, &output, &output); err == nil {
t.Fatal("run(--strict) error = nil, want malformed bundle refusal")
}
}
func TestRunSkipsTheCustomManifestInsideBundleDirectory(t *testing.T) {
_, bundleDir := prepareCoverageFixtures(t)
manifestPath := filepath.Join(bundleDir, "plan-custom.json")
content, err := os.ReadFile(filepath.Join(assessmentFixturePath, "bank_manifest.json"))
if err != nil {
t.Fatalf("read manifest fixture: %v", err)
}
if err := os.WriteFile(manifestPath, content, 0o600); err != nil {
t.Fatalf("write custom manifest: %v", err)
}
var output bytes.Buffer
if err := Run([]string{"--manifest", manifestPath, "--bundles", bundleDir}, &output, &output); err != nil {
t.Fatalf("run() error = %v, want report success", err)
}
if strings.Contains(output.String(), "plan-custom.json") {
t.Fatalf("custom manifest was parsed as a bundle:\n%s", output.String())
}
}
func TestRunPropagatesOutputWriteFailure(t *testing.T) {
manifestPath, bundleDir := prepareCoverageFixtures(t)
writeErr := errors.New("closed output")
err := Run([]string{"--manifest", manifestPath, "--bundles", bundleDir}, failingCoverageWriter{err: writeErr}, &bytes.Buffer{})
if !errors.Is(err, writeErr) {
t.Fatalf("run() error = %v, want wrapped output error", err)
}
}
func prepareCoverageFixtures(t *testing.T) (string, string) {
t.Helper()
root := t.TempDir()
bundleDir := filepath.Join(root, "bundles")
if err := os.Mkdir(bundleDir, 0o700); err != nil {
t.Fatalf("create bundle directory: %v", err)
}
manifestContent, err := os.ReadFile(filepath.Join(assessmentFixturePath, "bank_manifest.json"))
if err != nil {
t.Fatalf("read manifest fixture: %v", err)
}
manifestPath := filepath.Join(root, "bank-plan.json")
if err := os.WriteFile(manifestPath, manifestContent, 0o600); err != nil {
t.Fatalf("write manifest fixture: %v", err)
}
bundleContent, err := os.ReadFile(filepath.Join(assessmentFixturePath, "backend_demo_bundle.json"))
if err != nil {
t.Fatalf("read demo bundle fixture: %v", err)
}
if err := os.WriteFile(filepath.Join(bundleDir, "backend_demo_bundle.json"), bundleContent, 0o600); err != nil {
t.Fatalf("write demo bundle fixture: %v", err)
}
return manifestPath, bundleDir
}
type failingCoverageWriter struct {
err error
}
func (writer failingCoverageWriter) Write([]byte) (int, error) {
return 0, writer.err
}
@@ -0,0 +1,535 @@
package assessment
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"path/filepath"
"slices"
"strings"
"lincodex/backend/internal/domain"
)
const (
maxBankManifestBytes = 1 << 20
bankCoverageManifestVersion = 1
maximumDifficultySpreadLogits = 0.3
minimumItemDiscrimination = 0.5
minimumPointBiserial = 0.2
)
var requiredBankPlan = map[string]map[string]int{
"backend": {
"algorithms": 5, "data-structures": 4, "http-api": 4,
"sql-transactions": 4, "concurrency": 4, "debugging-testing": 4,
},
"network": {
"addressing-subnetting": 3, "ethernet-vlan": 3, "routing-ospf": 3,
"dns-dhcp-tcp": 3, "configuration-diagnostics": 3,
},
}
var requiredBankLanguages = map[string][]string{
"backend": {"go", "python"},
"network": nil,
}
var requiredBankContent = []string{"answer_key", "rubric", "seed_generator"}
var requiredBankEvidence = []string{"grade_coverage", "independent_review", "reference_seeds"}
// BankCoverageManifest describes the planned bank inventory. It does not mark
// any family as reviewed, calibrated, published, or available to candidates.
type BankCoverageManifest struct {
Version int `json:"version"`
Categories []BankCoverageCategoryPlan `json:"categories"`
RequiredContent []string `json:"required_content"`
RequiredEvidence []string `json:"required_evidence"`
CalibrationGates BankCalibrationGatePlan `json:"calibration_gates"`
}
type BankCoverageCategoryPlan struct {
Code string `json:"code"`
RequiredFamilyCount int `json:"required_family_count"`
RequiredLanguages []string `json:"required_languages"`
ImplementationsDir string `json:"implementations_dir"`
Topics []BankCoverageTopicPlan `json:"topics"`
}
type BankCoverageTopicPlan struct {
Name string `json:"name"`
RequiredFamilyCount int `json:"required_family_count"`
FamilyKeys []string `json:"family_keys"`
}
type BankCalibrationGatePlan struct {
ExternalMeasurementRequired bool `json:"external_measurement_required"`
MaximumDifficultySpreadLogits float64 `json:"maximum_difficulty_spread_logits"`
MinimumDiscrimination float64 `json:"minimum_discrimination"`
MinimumPointBiserial float64 `json:"minimum_point_biserial"`
}
// BankCoverageInventory contains validated family drafts and artifact paths
// collected by a caller such as the assessment operator command.
type BankCoverageInventory struct {
Families []BankCoverageFamilyRecord
ImplementationFiles []string
InvalidBundleFiles []string
}
type BankCoverageFamilyRecord struct {
Key string
Category string
Version int32
Author string
Reviewer string
ReviewStatus string
Source string
}
type BankCoverageCategoryReport struct {
Code string
PlannedFamilies int
PresentFamilies int
InventoriedFamilies int
RequiredImplementationFiles int
PresentImplementationFiles int
}
// BankCoverageReport is a snapshot of planned family keys and artifact paths.
// Review status is reported as bundle metadata only; this report never
// authorizes publication or candidate availability.
type BankCoverageReport struct {
Categories []BankCoverageCategoryReport
InventoriedFamilies int
DeclaredApprovedReviews int
PendingReviewDeclarations int
RejectedReviewDeclarations int
MissingFamilyKeys []string
MissingIndependentReviews []string
CategoryMismatches []string
UnassignedFamilyKeys []string
UnassignedCategories []string
MissingImplementationFiles []string
InvalidBundleFiles []string
UnverifiableEvidence []string
CalibrationMeasurementRequired bool
}
type bankManifestFamily struct {
category string
implementationsDir string
languages []string
}
// ParseBankCoverageManifest strictly decodes and validates the planned bank
// inventory. Its 25 Backend and 15 Network family counts are the initial
// authoring floor within the PRD's wider target ranges.
func ParseBankCoverageManifest(content []byte) (BankCoverageManifest, error) {
const location = "assessment.ParseBankCoverageManifest"
if len(content) > maxBankManifestBytes {
return BankCoverageManifest{}, fmt.Errorf("%s - manifest exceeds %d bytes: %w", location, maxBankManifestBytes, domain.ErrInvalidAssessmentFamily)
}
decoder := json.NewDecoder(bytes.NewReader(content))
decoder.DisallowUnknownFields()
var manifest BankCoverageManifest
if err := decoder.Decode(&manifest); err != nil {
return BankCoverageManifest{}, fmt.Errorf("%s - decode manifest: %w: %w", location, domain.ErrInvalidAssessmentFamily, err)
}
var trailing any
if err := decoder.Decode(&trailing); !errors.Is(err, io.EOF) {
if err == nil {
return BankCoverageManifest{}, fmt.Errorf("%s - trailing data after manifest: %w", location, domain.ErrInvalidAssessmentFamily)
}
return BankCoverageManifest{}, fmt.Errorf("%s - read after manifest: %w: %w", location, domain.ErrInvalidAssessmentFamily, err)
}
if err := validateBankCoverageManifest(manifest); err != nil {
return BankCoverageManifest{}, fmt.Errorf("%s - validate manifest: %w", location, err)
}
return manifest, nil
}
// BuildBankCoverageReport matches validated bundle inventory against the
// planned family keys. Missing content and artifact paths are report data, not
// errors, so incomplete authoring does not fail ordinary backend checks.
func BuildBankCoverageReport(manifest BankCoverageManifest, inventory BankCoverageInventory) (BankCoverageReport, error) {
const location = "assessment.BuildBankCoverageReport"
if err := validateBankCoverageManifest(manifest); err != nil {
return BankCoverageReport{}, fmt.Errorf("%s - validate manifest: %w", location, err)
}
build := newBankCoverageBuild(manifest, inventory)
build.addFamilyRecords(inventory.Families)
build.countObservedFamilies()
build.countMissingRequirements(inventory.ImplementationFiles)
return build.finish(), nil
}
type bankCoverageBuild struct {
report BankCoverageReport
planned map[string]bankManifestFamily
observed map[string]BankCoverageFamilyRecord
unassignedKeys map[string]struct{}
unassignedCategory map[string]struct{}
categoryReports map[string]*BankCoverageCategoryReport
}
func newBankCoverageBuild(manifest BankCoverageManifest, inventory BankCoverageInventory) bankCoverageBuild {
build := bankCoverageBuild{
report: newBankCoverageReport(manifest),
planned: indexBankManifestFamilies(manifest),
observed: make(map[string]BankCoverageFamilyRecord, len(inventory.Families)),
unassignedKeys: make(map[string]struct{}),
unassignedCategory: make(map[string]struct{}),
categoryReports: make(map[string]*BankCoverageCategoryReport, len(manifest.Categories)),
}
build.report.InvalidBundleFiles = slices.Clone(inventory.InvalidBundleFiles)
for index := range build.report.Categories {
build.categoryReports[build.report.Categories[index].Code] = &build.report.Categories[index]
}
return build
}
func (build *bankCoverageBuild) addFamilyRecords(families []BankCoverageFamilyRecord) {
for _, family := range families {
if !validBankCoverageFamilyRecord(family) {
build.report.InvalidBundleFiles = append(build.report.InvalidBundleFiles,
fmt.Sprintf("%s: invalid family record %q", family.Source, family.Key))
continue
}
build.classifyFamily(family)
build.recordFamilyVersion(family)
}
}
func (build *bankCoverageBuild) classifyFamily(family BankCoverageFamilyRecord) {
plannedFamily, isPlanned := build.planned[family.Key]
if !isPlanned {
build.unassignedKeys[family.Key] = struct{}{}
}
if build.categoryReports[family.Category] == nil {
build.unassignedCategory[family.Category] = struct{}{}
}
if isPlanned && family.Category != plannedFamily.category {
build.report.CategoryMismatches = append(build.report.CategoryMismatches,
fmt.Sprintf("%s: expected %s, found %s", family.Key, plannedFamily.category, family.Category))
}
}
func (build *bankCoverageBuild) recordFamilyVersion(family BankCoverageFamilyRecord) {
current, exists := build.observed[family.Key]
if exists && current.Category != family.Category {
build.report.InvalidBundleFiles = append(build.report.InvalidBundleFiles,
fmt.Sprintf("%s: family %s appears under categories %s and %s", family.Source, family.Key, current.Category, family.Category))
return
}
if !exists || family.Version > current.Version {
build.observed[family.Key] = family
return
}
if family.Version == current.Version {
build.report.InvalidBundleFiles = append(build.report.InvalidBundleFiles,
fmt.Sprintf("%s: family %s version %d appears in more than one bundle", family.Source, family.Key, family.Version))
}
}
func (build *bankCoverageBuild) countObservedFamilies() {
for key, family := range build.observed {
build.report.InventoriedFamilies++
if categoryReport := build.categoryReports[family.Category]; categoryReport != nil {
categoryReport.InventoriedFamilies++
}
build.countReviewDeclaration(family)
plannedFamily, isPlanned := build.planned[key]
if !isPlanned || family.Category != plannedFamily.category {
continue
}
build.categoryReports[plannedFamily.category].PresentFamilies++
if family.ReviewStatus != string(domain.AssessmentReviewApproved) || family.Reviewer == "" || family.Reviewer == family.Author {
build.report.MissingIndependentReviews = append(build.report.MissingIndependentReviews, key)
}
}
}
func (build *bankCoverageBuild) countReviewDeclaration(family BankCoverageFamilyRecord) {
switch family.ReviewStatus {
case string(domain.AssessmentReviewApproved):
if family.Reviewer != "" && family.Reviewer != family.Author {
build.report.DeclaredApprovedReviews++
}
case string(domain.AssessmentReviewRejected):
build.report.RejectedReviewDeclarations++
default:
build.report.PendingReviewDeclarations++
}
}
func (build *bankCoverageBuild) countMissingRequirements(paths []string) {
implementationFiles := make(map[string]struct{}, len(paths))
for _, path := range paths {
implementationFiles[filepath.ToSlash(filepath.Clean(path))] = struct{}{}
}
for key, family := range build.planned {
observedFamily, exists := build.observed[key]
if !exists || observedFamily.Category != family.category {
build.report.MissingFamilyKeys = append(build.report.MissingFamilyKeys, key)
}
build.countMissingImplementations(key, family, implementationFiles)
}
}
func (build *bankCoverageBuild) countMissingImplementations(key string, family bankManifestFamily, present map[string]struct{}) {
for _, language := range family.languages {
relative := filepath.ToSlash(filepath.Join(family.implementationsDir, key+implementationExtension(language)))
if _, exists := present[relative]; !exists {
build.report.MissingImplementationFiles = append(build.report.MissingImplementationFiles, relative)
continue
}
build.categoryReports[family.category].PresentImplementationFiles++
}
}
func (build *bankCoverageBuild) finish() BankCoverageReport {
for key := range build.unassignedKeys {
build.report.UnassignedFamilyKeys = append(build.report.UnassignedFamilyKeys, key)
}
for category := range build.unassignedCategory {
build.report.UnassignedCategories = append(build.report.UnassignedCategories, category)
}
slices.Sort(build.report.MissingFamilyKeys)
slices.Sort(build.report.MissingIndependentReviews)
slices.Sort(build.report.CategoryMismatches)
slices.Sort(build.report.UnassignedFamilyKeys)
slices.Sort(build.report.UnassignedCategories)
slices.Sort(build.report.MissingImplementationFiles)
slices.Sort(build.report.InvalidBundleFiles)
return build.report
}
// StrictError reports missing inventory requirements that the checker can
// verify. It does not certify the external review, calibration, or semantic
// equivalence of reference implementations.
func (report BankCoverageReport) StrictError() error {
const location = "assessment.BankCoverageReport.StrictError"
if len(report.MissingFamilyKeys) == 0 && len(report.MissingIndependentReviews) == 0 &&
len(report.MissingImplementationFiles) == 0 && len(report.InvalidBundleFiles) == 0 &&
len(report.CategoryMismatches) == 0 {
return nil
}
return fmt.Errorf("%s - planned bank inventory has %d missing families, %d missing review declarations, %d missing implementation paths, and %d invalid bundle records", location,
len(report.MissingFamilyKeys), len(report.MissingIndependentReviews), len(report.MissingImplementationFiles), len(report.InvalidBundleFiles)+len(report.CategoryMismatches))
}
func validateBankCoverageManifest(manifest BankCoverageManifest) error {
const location = "assessment.validateBankCoverageManifest"
if manifest.Version != bankCoverageManifestVersion {
return fmt.Errorf("%s - version must be %d: %w", location, bankCoverageManifestVersion, domain.ErrInvalidAssessmentFamily)
}
if len(manifest.Categories) != len(requiredBankPlan) {
return fmt.Errorf("%s - exactly backend and network categories are required: %w", location, domain.ErrInvalidAssessmentFamily)
}
if err := validateBankCoverageCategories(manifest.Categories); err != nil {
return fmt.Errorf("%s - validate category plans: %w", location, err)
}
if !sameStringSet(manifest.RequiredContent, requiredBankContent) {
return fmt.Errorf("%s - required content must include seed_generator, answer_key, and rubric: %w", location, domain.ErrInvalidAssessmentFamily)
}
if !sameStringSet(manifest.RequiredEvidence, requiredBankEvidence) {
return fmt.Errorf("%s - required evidence must include grade_coverage, reference_seeds, and independent_review: %w", location, domain.ErrInvalidAssessmentFamily)
}
gates := manifest.CalibrationGates
if !gates.ExternalMeasurementRequired || gates.MaximumDifficultySpreadLogits != maximumDifficultySpreadLogits ||
gates.MinimumDiscrimination != minimumItemDiscrimination || gates.MinimumPointBiserial != minimumPointBiserial {
return fmt.Errorf("%s - calibration thresholds must remain external gates at 0.3, 0.5, and 0.2: %w", location, domain.ErrInvalidAssessmentFamily)
}
return nil
}
func validateBankCoverageCategories(categories []BankCoverageCategoryPlan) error {
const location = "assessment.validateBankCoverageCategories"
seenCategories := make(map[string]struct{}, len(categories))
seenFamilyKeys := make(map[string]struct{})
for _, category := range categories {
expectedTopics, ok := requiredBankPlan[category.Code]
if !ok {
return fmt.Errorf("%s - unknown category %q: %w", location, category.Code, domain.ErrInvalidAssessmentFamily)
}
if _, exists := seenCategories[category.Code]; exists {
return fmt.Errorf("%s - category %q appears twice: %w", location, category.Code, domain.ErrInvalidAssessmentFamily)
}
seenCategories[category.Code] = struct{}{}
if err := validateBankCoverageCategory(category, expectedTopics, seenFamilyKeys); err != nil {
return fmt.Errorf("%s - category %s: %w", location, category.Code, err)
}
}
for category := range requiredBankPlan {
if _, ok := seenCategories[category]; !ok {
return fmt.Errorf("%s - category %s is missing: %w", location, category, domain.ErrInvalidAssessmentFamily)
}
}
return nil
}
func validateBankCoverageCategory(category BankCoverageCategoryPlan, expectedTopics map[string]int, seenFamilyKeys map[string]struct{}) error {
const location = "assessment.validateBankCoverageCategory"
if category.RequiredFamilyCount != sumTopicCounts(expectedTopics) {
return fmt.Errorf("%s - requires %d planned families: %w", location, sumTopicCounts(expectedTopics), domain.ErrInvalidAssessmentFamily)
}
if !sameStringSet(category.RequiredLanguages, requiredBankLanguages[category.Code]) {
return fmt.Errorf("%s - has unsupported required languages: %w", location, domain.ErrInvalidAssessmentFamily)
}
if len(category.RequiredLanguages) > 0 {
if err := validateImplementationDir(category.ImplementationsDir); err != nil {
return fmt.Errorf("%s - implementation directory: %w", location, err)
}
} else if category.ImplementationsDir != "" {
return fmt.Errorf("%s - must not declare implementation files: %w", location, domain.ErrInvalidAssessmentFamily)
}
return validateBankCoverageTopics(category.Code, category.Topics, expectedTopics, seenFamilyKeys)
}
func validateBankCoverageTopics(category string, topics []BankCoverageTopicPlan, expectedTopics map[string]int, seenFamilyKeys map[string]struct{}) error {
const location = "assessment.validateBankCoverageTopics"
if len(topics) != len(expectedTopics) {
return fmt.Errorf("%s - category %s has an unexpected topic set: %w", location, category, domain.ErrInvalidAssessmentFamily)
}
seenTopics := make(map[string]struct{}, len(topics))
for _, topic := range topics {
requiredCount, ok := expectedTopics[topic.Name]
if !ok {
return fmt.Errorf("%s - category %s has unknown topic %q: %w", location, category, topic.Name, domain.ErrInvalidAssessmentFamily)
}
if _, exists := seenTopics[topic.Name]; exists {
return fmt.Errorf("%s - category %s topic %q appears twice: %w", location, category, topic.Name, domain.ErrInvalidAssessmentFamily)
}
seenTopics[topic.Name] = struct{}{}
if err := validateBankCoverageTopic(category, topic, requiredCount, seenFamilyKeys); err != nil {
return err
}
}
for name := range expectedTopics {
if _, ok := seenTopics[name]; !ok {
return fmt.Errorf("%s - category %s is missing topic %q: %w", location, category, name, domain.ErrInvalidAssessmentFamily)
}
}
return nil
}
func validateBankCoverageTopic(category string, topic BankCoverageTopicPlan, requiredCount int, seenFamilyKeys map[string]struct{}) error {
const location = "assessment.validateBankCoverageTopic"
if topic.RequiredFamilyCount != requiredCount || len(topic.FamilyKeys) != requiredCount {
return fmt.Errorf("%s - category %s topic %q requires %d family keys: %w", location, category, topic.Name, requiredCount, domain.ErrInvalidAssessmentFamily)
}
for _, key := range topic.FamilyKeys {
if _, err := domain.ParseAssessmentFamilyKey(key); err != nil {
return fmt.Errorf("%s - category %s topic %s has an invalid family key %q: %w", location, category, topic.Name, key, err)
}
if _, exists := seenFamilyKeys[key]; exists {
return fmt.Errorf("%s - family key %q appears more than once: %w", location, key, domain.ErrInvalidAssessmentFamily)
}
seenFamilyKeys[key] = struct{}{}
}
return nil
}
func validateImplementationDir(value string) error {
if value == "" || filepath.IsAbs(value) {
return fmt.Errorf("must be a non-empty relative path: %w", domain.ErrInvalidAssessmentFamily)
}
for _, part := range strings.Split(filepath.Clean(value), string(filepath.Separator)) {
if part == ".." || part == "." || part == "" {
return fmt.Errorf("must not escape the bundle directory: %w", domain.ErrInvalidAssessmentFamily)
}
}
return nil
}
func validBankCoverageFamilyRecord(family BankCoverageFamilyRecord) bool {
if _, err := domain.ParseAssessmentFamilyKey(family.Key); err != nil || family.Version < 1 {
return false
}
if _, err := domain.ParseAssessmentCategory(family.Category); err != nil {
return false
}
if _, err := domain.ParseAssessmentAuthor(family.Author); err != nil {
return false
}
status, err := domain.ParseAssessmentReviewStatus(family.ReviewStatus)
if err != nil {
return false
}
if status == domain.AssessmentReviewPending {
return family.Reviewer == ""
}
if _, err := domain.ParseAssessmentOperator(family.Reviewer); err != nil {
return false
}
return family.Reviewer != family.Author
}
func implementationExtension(language string) string {
if language == "python" {
return ".py"
}
return ".go"
}
func sameStringSet(actual, expected []string) bool {
if len(actual) != len(expected) {
return false
}
left := slices.Clone(actual)
right := slices.Clone(expected)
slices.Sort(left)
slices.Sort(right)
return slices.Equal(left, right)
}
func sumTopicCounts(topics map[string]int) int {
total := 0
for _, count := range topics {
total += count
}
return total
}
func indexBankManifestFamilies(manifest BankCoverageManifest) map[string]bankManifestFamily {
families := make(map[string]bankManifestFamily)
for _, category := range manifest.Categories {
for _, topic := range category.Topics {
for _, key := range topic.FamilyKeys {
families[key] = bankManifestFamily{
category: category.Code,
implementationsDir: category.ImplementationsDir,
languages: slices.Clone(category.RequiredLanguages),
}
}
}
}
return families
}
func newBankCoverageReport(manifest BankCoverageManifest) BankCoverageReport {
report := BankCoverageReport{
Categories: make([]BankCoverageCategoryReport, 0, len(manifest.Categories)),
CalibrationMeasurementRequired: manifest.CalibrationGates.ExternalMeasurementRequired,
UnverifiableEvidence: []string{
"grade_coverage is not stored in the bundle format",
"reference_seeds are not stored in the bundle format",
"independent_review is declared by the bundle and is not authenticated here",
"implementation files are checked for presence only; semantic parity is not tested here",
},
}
for _, category := range manifest.Categories {
requiredImplementationFiles := 0
for _, topic := range category.Topics {
requiredImplementationFiles += len(topic.FamilyKeys) * len(category.RequiredLanguages)
}
report.Categories = append(report.Categories, BankCoverageCategoryReport{
Code: category.Code, PlannedFamilies: category.RequiredFamilyCount,
RequiredImplementationFiles: requiredImplementationFiles,
})
}
return report
}
@@ -0,0 +1,194 @@
package assessment
import (
"encoding/json"
"errors"
"os"
"path/filepath"
"slices"
"testing"
"lincodex/backend/internal/domain"
)
const bankCoverageManifestPath = "../../../testdata/assessment/bank_manifest.json"
func loadBankCoverageManifest(t *testing.T) BankCoverageManifest {
t.Helper()
content, err := os.ReadFile(filepath.FromSlash(bankCoverageManifestPath))
if err != nil {
t.Fatalf("read bank coverage manifest: %v", err)
}
manifest, err := ParseBankCoverageManifest(content)
if err != nil {
t.Fatalf("ParseBankCoverageManifest() error = %v", err)
}
return manifest
}
func TestBankCoverageManifestMatchesThePlannedTopicCounts(t *testing.T) {
manifest := loadBankCoverageManifest(t)
if len(manifest.Categories) != 2 {
t.Fatalf("manifest has %d categories, want Backend and Network", len(manifest.Categories))
}
if manifest.Categories[0].Code != "backend" || manifest.Categories[0].RequiredFamilyCount != 25 {
t.Fatalf("Backend plan = %+v, want 25 families", manifest.Categories[0])
}
if !sameStringSet(manifest.Categories[0].RequiredLanguages, []string{"go", "python"}) {
t.Fatalf("Backend languages = %v, want Go and Python", manifest.Categories[0].RequiredLanguages)
}
if manifest.Categories[1].Code != "network" || manifest.Categories[1].RequiredFamilyCount != 15 {
t.Fatalf("Network plan = %+v, want 15 families", manifest.Categories[1])
}
if len(manifest.Categories[1].RequiredLanguages) != 0 {
t.Fatalf("Network languages = %v, want no language-specific implementation requirement", manifest.Categories[1].RequiredLanguages)
}
if got := sumTopicCounts(requiredBankPlan["backend"]); got != 25 {
t.Fatalf("Backend topic count = %d, want 25", got)
}
if got := sumTopicCounts(requiredBankPlan["network"]); got != 15 {
t.Fatalf("Network topic count = %d, want 15", got)
}
if !manifest.CalibrationGates.ExternalMeasurementRequired {
t.Fatal("calibration gates must require external measurements")
}
}
func TestBankCoverageRejectsAnIncompleteManifest(t *testing.T) {
manifest := loadBankCoverageManifest(t)
manifest.Categories[0].RequiredLanguages = []string{"python"}
content, err := json.Marshal(manifest)
if err != nil {
t.Fatalf("marshal manifest: %v", err)
}
if _, err := ParseBankCoverageManifest(content); !errors.Is(err, domain.ErrInvalidAssessmentFamily) {
t.Fatalf("ParseBankCoverageManifest(missing Go requirement) error = %v, want invalid manifest", err)
}
}
func TestBankCoverageReportsTheExistingUnreviewedDemoInventory(t *testing.T) {
bundle := loadDemoBundle(t)
inventory := bankCoverageInventoryFromBundle(t, bundle)
report, err := BuildBankCoverageReport(loadBankCoverageManifest(t), inventory)
if err != nil {
t.Fatalf("BuildBankCoverageReport() error = %v", err)
}
if report.InventoriedFamilies != 4 || report.PendingReviewDeclarations != 4 || report.DeclaredApprovedReviews != 0 {
t.Fatalf("demo inventory/review counts = %d/%d/%d, want 4 inventoried, 4 pending, 0 approved declarations",
report.InventoriedFamilies, report.PendingReviewDeclarations, report.DeclaredApprovedReviews)
}
if len(report.UnassignedFamilyKeys) != 4 || len(report.MissingFamilyKeys) != 40 {
t.Fatalf("demo coverage = %d unassigned and %d missing keys, want 4 and 40", len(report.UnassignedFamilyKeys), len(report.MissingFamilyKeys))
}
if report.Categories[0].PresentFamilies != 0 || report.Categories[0].InventoriedFamilies != 4 {
t.Fatalf("Backend coverage = %+v, want 0 planned keys matched and 4 inventoried demo families", report.Categories[0])
}
if report.Categories[0].RequiredImplementationFiles != 50 || report.Categories[1].RequiredImplementationFiles != 0 {
t.Fatalf("implementation requirements = backend %d, network %d, want 50 and 0", report.Categories[0].RequiredImplementationFiles, report.Categories[1].RequiredImplementationFiles)
}
if !report.CalibrationMeasurementRequired || len(report.UnverifiableEvidence) == 0 {
t.Fatalf("report did not preserve external gates and unsupported evidence: %+v", report)
}
if err := report.StrictError(); err == nil {
t.Fatal("StrictError() = nil, want incomplete inventory error")
}
}
func TestBankCoverageReportsThe24And14FamilyGaps(t *testing.T) {
manifest := loadBankCoverageManifest(t)
inventory := BankCoverageInventory{}
for _, category := range manifest.Categories {
remaining := category.RequiredFamilyCount - 1
for _, topic := range category.Topics {
for _, key := range topic.FamilyKeys {
if remaining == 0 {
break
}
inventory.Families = append(inventory.Families, pendingBankFamily(key, category.Code))
remaining--
}
}
}
report, err := BuildBankCoverageReport(manifest, inventory)
if err != nil {
t.Fatalf("BuildBankCoverageReport() error = %v", err)
}
if report.Categories[0].PresentFamilies != 24 || report.Categories[1].PresentFamilies != 14 {
t.Fatalf("coverage = %d/%d and %d/%d, want 24/25 and 14/15",
report.Categories[0].PresentFamilies, report.Categories[0].PlannedFamilies,
report.Categories[1].PresentFamilies, report.Categories[1].PlannedFamilies)
}
if len(report.MissingFamilyKeys) != 2 {
t.Fatalf("missing family keys = %v, want one gap per category", report.MissingFamilyKeys)
}
if len(report.MissingIndependentReviews) != 38 {
t.Fatalf("missing review declarations = %d, want 38 present families with pending review", len(report.MissingIndependentReviews))
}
}
func TestBankCoverageNamesMissingGoVariantAndReviewer(t *testing.T) {
manifest := loadBankCoverageManifest(t)
key := manifest.Categories[0].Topics[0].FamilyKeys[0]
inventory := BankCoverageInventory{
Families: []BankCoverageFamilyRecord{pendingBankFamily(key, "backend")},
ImplementationFiles: []string{filepath.ToSlash(filepath.Join("solutions", key+".py"))},
}
report, err := BuildBankCoverageReport(manifest, inventory)
if err != nil {
t.Fatalf("BuildBankCoverageReport() error = %v", err)
}
goPath := filepath.ToSlash(filepath.Join("solutions", key+".go"))
pythonPath := filepath.ToSlash(filepath.Join("solutions", key+".py"))
if !slices.Contains(report.MissingImplementationFiles, goPath) {
t.Fatalf("missing implementations = %v, want %s", report.MissingImplementationFiles, goPath)
}
if slices.Contains(report.MissingImplementationFiles, pythonPath) {
t.Fatalf("missing implementations = %v, Python path %s is present", report.MissingImplementationFiles, pythonPath)
}
if !slices.Contains(report.MissingIndependentReviews, key) {
t.Fatalf("missing review declarations = %v, want %s", report.MissingIndependentReviews, key)
}
if err := report.StrictError(); err == nil {
t.Fatal("StrictError() = nil, want missing variant and reviewer declaration to fail strict checks")
}
}
func TestBankCoverageReportsFamiliesFromUnplannedCategories(t *testing.T) {
family := pendingBankFamily("other-family", "security")
report, err := BuildBankCoverageReport(loadBankCoverageManifest(t), BankCoverageInventory{
Families: []BankCoverageFamilyRecord{family},
})
if err != nil {
t.Fatalf("BuildBankCoverageReport() error = %v", err)
}
if report.InventoriedFamilies != 1 || !slices.Contains(report.UnassignedCategories, "security") ||
!slices.Contains(report.UnassignedFamilyKeys, "other-family") {
t.Fatalf("unplanned category inventory = %+v", report)
}
}
func bankCoverageInventoryFromBundle(t *testing.T, bundle Bundle) BankCoverageInventory {
t.Helper()
drafts, err := bundle.Drafts()
if err != nil {
t.Fatalf("Bundle.Drafts() error = %v", err)
}
inventory := BankCoverageInventory{}
for _, draft := range drafts {
core := draft.Core()
inventory.Families = append(inventory.Families, BankCoverageFamilyRecord{
Key: string(core.Key), Category: string(core.Category), Version: core.Version,
Author: string(core.Author), Reviewer: string(core.Reviewer),
ReviewStatus: string(core.ReviewStatus), Source: "demo bundle",
})
}
return inventory
}
func pendingBankFamily(key, category string) BankCoverageFamilyRecord {
return BankCoverageFamilyRecord{
Key: key, Category: category, Version: 1,
Author: "operator:author", ReviewStatus: string(domain.AssessmentReviewPending),
Source: "unit bundle",
}
}
+40
View File
@@ -0,0 +1,40 @@
{
"version": 1,
"categories": [
{
"code": "backend",
"required_family_count": 25,
"required_languages": ["go", "python"],
"implementations_dir": "solutions",
"topics": [
{"name": "algorithms", "required_family_count": 5, "family_keys": ["array-search-boundaries", "two-pointers", "sorting-stability", "graph-traversal", "complexity-estimation"]},
{"name": "data-structures", "required_family_count": 4, "family_keys": ["hash-table-collisions", "queue-and-stack", "tree-invariants", "priority-queue"]},
{"name": "http-api", "required_family_count": 4, "family_keys": ["http-method-idempotency", "http-caching", "api-pagination", "http-errors-retries"]},
{"name": "sql-transactions", "required_family_count": 4, "family_keys": ["sql-filtering-and-joins", "sql-aggregation", "sql-index-plans", "sql-transaction-invariants"]},
{"name": "concurrency", "required_family_count": 4, "family_keys": ["concurrent-operation-cancellation", "concurrency-limits", "shared-state-synchronization", "background-task-shutdown"]},
{"name": "debugging-testing", "required_family_count": 4, "family_keys": ["boundary-error-search", "input-error-handling", "timeout-diagnostics", "resource-leak"]}
]
},
{
"code": "network",
"required_family_count": 15,
"required_languages": [],
"implementations_dir": "",
"topics": [
{"name": "addressing-subnetting", "required_family_count": 3, "family_keys": ["ipv4-addressing", "subnetting-and-masks", "vlsm-allocation"]},
{"name": "ethernet-vlan", "required_family_count": 3, "family_keys": ["ethernet-frame-reading", "vlan-segmentation", "vlan-trunk-configuration"]},
{"name": "routing-ospf", "required_family_count": 3, "family_keys": ["static-routing", "longest-prefix-matching", "ospf-neighbor-diagnostics"]},
{"name": "dns-dhcp-tcp", "required_family_count": 3, "family_keys": ["dns-resolution-and-cache", "dhcp-lease", "tcp-retransmission"]},
{"name": "configuration-diagnostics", "required_family_count": 3, "family_keys": ["firewall-config-reading", "network-timeout-diagnostics", "allowed-connection-log-analysis"]}
]
}
],
"required_content": ["seed_generator", "answer_key", "rubric"],
"required_evidence": ["grade_coverage", "reference_seeds", "independent_review"],
"calibration_gates": {
"external_measurement_required": true,
"maximum_difficulty_spread_logits": 0.3,
"minimum_discrimination": 0.5,
"minimum_point_biserial": 0.2
}
}