diff --git a/backend/Dockerfile.demo-seed b/backend/Dockerfile.demo-seed new file mode 100644 index 0000000..377dbb8 --- /dev/null +++ b/backend/Dockerfile.demo-seed @@ -0,0 +1,26 @@ +# Image of the demo seed operator command. Only the isolated demo stand +# overlay (deploy/docker/docker-compose.demo.yml) builds it; the backend and +# release images never contain the command. +ARG GO_IMAGE=golang:1.26.8-alpine +ARG RUNTIME_IMAGE=gcr.io/distroless/static-debian12:nonroot + +FROM ${GO_IMAGE} AS build + +ENV GOTOOLCHAIN=local + +WORKDIR /src/backend +COPY go.mod go.sum ./ +RUN go mod download + +COPY . ./ +RUN CGO_ENABLED=0 GOOS=linux go build -buildvcs=false -trimpath -ldflags="-s -w" -o /out/demo-seed ./cmd/demo-seed + +FROM ${RUNTIME_IMAGE} + +LABEL org.opencontainers.image.title="Lincodex demo seed" \ + org.opencontainers.image.description="Operator command that seeds synthetic data on an isolated demo stand" + +WORKDIR / +COPY --from=build /out/demo-seed /demo-seed +USER nonroot:nonroot +ENTRYPOINT ["/demo-seed"] diff --git a/backend/Makefile b/backend/Makefile index 70d2f51..dad117f 100644 --- a/backend/Makefile +++ b/backend/Makefile @@ -65,6 +65,14 @@ policy-publish-build: ## Build the local policy publication operator command @mkdir -p bin $(GO) build -buildvcs=false -trimpath -o bin/policy-publish ./cmd/policy-publish +.PHONY: demo-seed demo-seed-build +demo-seed: ## Seed, check, or count the isolated demo stand; needs DEMO_MODE=isolated (set ARGS) + $(GO) run ./cmd/demo-seed $(ARGS) + +demo-seed-build: ## Build the local demo seed operator command + @mkdir -p bin + $(GO) build -buildvcs=false -trimpath -o bin/demo-seed ./cmd/demo-seed + .PHONY: deps install install-tools deps: ## Download pinned Go module dependencies $(GO) mod download diff --git a/backend/cmd/demo-seed/main.go b/backend/cmd/demo-seed/main.go new file mode 100644 index 0000000..991ba92 --- /dev/null +++ b/backend/cmd/demo-seed/main.go @@ -0,0 +1,29 @@ +// Command demo-seed seeds the synthetic demonstration world of an isolated +// demo stand, checks whether a reset may discard the stand's database, and +// prints an inventory of counts. It requires DEMO_MODE=isolated. +package main + +import ( + "context" + "fmt" + "os" + "os/signal" + "syscall" + "time" + + "lincodex/backend/internal/adapter/primary/cli/demoseed" +) + +func main() { + os.Exit(run()) +} + +func run() int { + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + if err := demoseed.Run(ctx, os.Args[1:], os.LookupEnv, os.Stdout, time.Now); err != nil { + _, _ = fmt.Fprintf(os.Stderr, "demo-seed: %v\n", err) + return 2 + } + return 0 +} diff --git a/backend/integration_test/demo_seed_test.go b/backend/integration_test/demo_seed_test.go new file mode 100644 index 0000000..30c4912 --- /dev/null +++ b/backend/integration_test/demo_seed_test.go @@ -0,0 +1,443 @@ +//go:build integration + +package integration_test + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "net/http" + "strconv" + "strings" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgxpool" + + "lincodex/backend/internal/adapter/primary/cli/demoseed" + "lincodex/backend/internal/adapter/secondary/argon2id" + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/anonymousprofile" + "lincodex/backend/internal/usecase/assessment" + "lincodex/backend/internal/usecase/candidateview" + "lincodex/backend/internal/usecase/companyquota" + seedusecase "lincodex/backend/internal/usecase/demoseed" + "lincodex/backend/internal/usecase/identity" + "lincodex/backend/internal/usecase/policy" +) + +const ( + demoSeedTimeout = 4 * time.Minute + demoSeedActor = "operator:demo-seed-test" + demoSeedPassword = "synthetic demo stand password" + // demoSeedKeySecret keys the in-test attempt and view services only. + demoSeedKeySecret = "demo-seed-integration-key-secret-0123456789" + ordinaryEmail = "visitor@example.test" +) + +// demoSeedStand is one isolated database with the startup policy seeded, as +// a freshly started backend leaves it. +type demoSeedStand struct { + ctx context.Context + pool *pgxpool.Pool + databaseURL string +} + +func newDemoSeedStand(ctx context.Context, t *testing.T, env *testEnvironment) demoSeedStand { + t.Helper() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + pool := newPoolFor(ctx, t, databaseURL) + if _, err := policy.NewPublisher(postgresadapter.NewPolicyStore(pool).Policies(), time.Now).EnsureDemoProductPolicy(ctx); err != nil { + t.Fatalf("EnsureDemoProductPolicy() error = %v", err) + } + return demoSeedStand{ctx: ctx, pool: pool, databaseURL: databaseURL} +} + +// run executes the operator command with the given environment overrides on +// top of the stand's DATABASE_URL, the isolated mode, and the password. +func (stand demoSeedStand) run(t *testing.T, overrides map[string]string, args ...string) (string, error) { + t.Helper() + environment := map[string]string{ + "DATABASE_URL": stand.databaseURL, demoseed.DemoModeName: demoseed.IsolatedDemoMode, + demoseed.PasswordName: demoSeedPassword, + } + for key, value := range overrides { + if value == "" { + delete(environment, key) + continue + } + environment[key] = value + } + lookup := func(key string) (string, bool) { + value, ok := environment[key] + return value, ok + } + var output bytes.Buffer + err := demoseed.Run(stand.ctx, args, lookup, &output, time.Now) + return output.String(), err +} + +func (stand demoSeedStand) inventory(t *testing.T) string { + t.Helper() + output, err := stand.run(t, nil, "inventory") + if err != nil { + t.Fatalf("inventory error = %v (output %q)", err, output) + } + return output +} + +func (stand demoSeedStand) count(t *testing.T, query string, args ...any) int { + t.Helper() + var value int + if err := stand.pool.QueryRow(stand.ctx, query, args...).Scan(&value); err != nil { + t.Fatalf("count %q: %v", query, err) + } + return value +} + +func (stand demoSeedStand) userID(t *testing.T, email string) uuid.UUID { + t.Helper() + var id uuid.UUID + if err := stand.pool.QueryRow(stand.ctx, `SELECT id FROM users WHERE email_normalized = $1`, email).Scan(&id); err != nil { + t.Fatalf("read account %s: %v", email, err) + } + return id +} + +// createOrdinaryAccount stores an unconfirmed registration outside the +// synthetic domain, the way a visitor's own sign-up leaves it. +func (stand demoSeedStand) createOrdinaryAccount(t *testing.T) uuid.UUID { + t.Helper() + hasher, err := argon2id.NewHasher(1) + if err != nil { + t.Fatalf("NewHasher() error = %v", err) + } + password, err := domain.NewPassword("ordinary visitor password") + if err != nil { + t.Fatalf("NewPassword() error = %v", err) + } + hash, err := hasher.Hash(stand.ctx, password) + if err != nil { + t.Fatalf("Hash() error = %v", err) + } + address, err := domain.NewEmailAddress(ordinaryEmail) + if err != nil { + t.Fatalf("NewEmailAddress() error = %v", err) + } + user, err := domain.NewUser(domain.Registration{ + Email: address, PasswordHash: hash, Scenario: domain.ScenarioCandidate, RegisteredAt: time.Now().UTC().Truncate(time.Microsecond), + }) + if err != nil { + t.Fatalf("NewUser() error = %v", err) + } + err = postgresadapter.NewTransactor(stand.pool).WithinTransaction(stand.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + return unit.Users().Create(ctx, user) + }) + if err != nil { + t.Fatalf("create ordinary account: %v", err) + } + return user.ID +} + +func demoEmail(local string) string { return local + "@" + seedusecase.SyntheticDomain } + +func TestDemoSeedCommand(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), demoSeedTimeout) + defer cancel() + + t.Run("refuses without the isolated mode before it connects", func(t *testing.T) { + stand := newDemoSeedStand(ctx, t, env) + for _, args := range [][]string{{"seed", "--actor", demoSeedActor}, {"check-reset"}, {"inventory"}} { + for _, mode := range []string{"", "production", "Isolated"} { + overrides := map[string]string{demoseed.DemoModeName: mode} + if _, err := stand.run(t, overrides, args...); err == nil || !strings.Contains(err.Error(), "DEMO_MODE=isolated") { + t.Errorf("%v with DEMO_MODE=%q error = %v, want the isolated mode refusal", args, mode, err) + } + } + } + // An unreachable database proves that the guard runs before connecting. + if _, err := stand.run(t, map[string]string{demoseed.DemoModeName: "", "DATABASE_URL": "postgres://nobody@127.0.0.1:1/none"}, "check-reset"); err == nil || + !strings.Contains(err.Error(), "DEMO_MODE=isolated") { + t.Errorf("check-reset against an unreachable database error = %v, want the mode refusal first", err) + } + if _, err := stand.run(t, map[string]string{demoseed.PasswordName: "short"}, "seed", "--actor", demoSeedActor); err == nil || + !strings.Contains(err.Error(), demoseed.PasswordName) { + t.Errorf("seed with a short password error = %v, want a password refusal", err) + } + if accounts := stand.count(t, `SELECT count(*) FROM users`); accounts != 0 { + t.Fatalf("accounts after refusals = %d, want none", accounts) + } + if versions := stand.count(t, `SELECT count(*) FROM policy_versions`); versions != 1 { + t.Fatalf("policy versions after refusals = %d, want only the startup version", versions) + } + }) + + t.Run("refuses a stand with ordinary accounts that was never seeded", func(t *testing.T) { + stand := newDemoSeedStand(ctx, t, env) + visitor := stand.createOrdinaryAccount(t) + if output, err := stand.run(t, nil, "seed", "--actor", demoSeedActor); err == nil || !strings.Contains(err.Error(), "never seeded") { + t.Fatalf("seed over an ordinary account = %q, %v, want a refusal", output, err) + } + if output, err := stand.run(t, nil, "check-reset"); err == nil || !strings.Contains(err.Error(), "never deletes ordinary data") { + t.Fatalf("check-reset with an ordinary account = %q, %v, want a refusal", output, err) + } + if accounts := stand.count(t, `SELECT count(*) FROM users`); accounts != 1 || stand.userID(t, ordinaryEmail) != visitor { + t.Fatalf("accounts after the refused seed = %d, want only the visitor", accounts) + } + if versions := stand.count(t, `SELECT count(*) FROM policy_versions`); versions != 1 { + t.Fatalf("policy versions after the refused seed = %d, want the startup version only", versions) + } + }) + + t.Run("seeds once, repeats without change, and keeps ordinary data", func(t *testing.T) { + stand := newDemoSeedStand(ctx, t, env) + if output, err := stand.run(t, nil, "check-reset"); err != nil || !strings.Contains(output, "reset allowed (empty)") { + t.Fatalf("check-reset on an empty stand = %q, %v, want allowed", output, err) + } + first, err := stand.run(t, nil, "seed", "--actor", demoSeedActor) + if err != nil { + t.Fatalf("first seed error = %v (output %q)", err, first) + } + if strings.Contains(first, demoSeedPassword) || !strings.Contains(first, "login: candidate@"+seedusecase.SyntheticDomain) || + !strings.Contains(first, "prepared full attempt: ") || strings.Contains(first, "created 0 records") { + t.Fatalf("first seed output = %q, want logins and prepared attempts without the password", first) + } + afterFirst := stand.inventory(t) + for _, want := range []string{ + "synthetic_accounts=9\n", "verified_synthetic_accounts=9\n", "ordinary_accounts=0\n", "organizations=2\n", + "memberships=3\n", "candidate_profiles=7\n", "questionnaires=7\n", "attempts=6\n", "attempt_results=6\n", + "current_categories=6\n", "published_cards=6\n", "product_policy_versions=2\n", "published_families=28\n", + "category_openings=1\n", "category_attestations=1\n", "training_bindings=1\n", + } { + if !strings.Contains(afterFirst, want) { + t.Errorf("inventory after the first seed lacks %q:\n%s", want, afterFirst) + } + } + if facts := stand.count(t, `SELECT count(*) FROM skill_evidence_facts`); facts < 6 { + t.Errorf("evidence facts after the prepared attempts = %d, want the projection of six results", facts) + } + + second, err := stand.run(t, nil, "seed", "--actor", "operator:another-operator") + if err != nil || !strings.Contains(second, "created 0 records") { + t.Fatalf("second seed = %q, %v, want nothing created", second, err) + } + if afterSecond := stand.inventory(t); afterSecond != afterFirst { + t.Fatalf("inventory changed on the repeat:\nfirst:\n%s\nsecond:\n%s", afterFirst, afterSecond) + } + + assertDemoSeedMarkers(t, stand) + assertDemoSeedPermissions(t, stand) + assertDemoSeedVisibleCohort(t, stand) + assertExpressAssignsNoCategory(t, stand) + + if output, err := stand.run(t, nil, "check-reset"); err != nil || !strings.Contains(output, "reset allowed (synthetic)") { + t.Fatalf("check-reset on the seeded stand = %q, %v, want allowed", output, err) + } + visitor := stand.createOrdinaryAccount(t) + if output, err := stand.run(t, nil, "check-reset"); err == nil || !strings.Contains(err.Error(), "1 accounts outside") { + t.Fatalf("check-reset with a visitor = %q, %v, want a refusal that counts one ordinary account", output, err) + } + // A repeat after a visitor registered is still a no-op and leaves the + // visitor alone. + if output, err := stand.run(t, nil, "seed", "--actor", demoSeedActor); err != nil || !strings.Contains(output, "created 0 records") { + t.Fatalf("seed after a visitor = %q, %v, want nothing created", output, err) + } + if stand.userID(t, ordinaryEmail) != visitor { + t.Fatal("the visitor account changed") + } + }) +} + +// assertDemoSeedMarkers checks that every organization and profile of the seed +// names itself as synthetic and that the categories come from the synthetic +// demonstration source. +func assertDemoSeedMarkers(t *testing.T, stand demoSeedStand) { + t.Helper() + if unmarked := stand.count(t, `SELECT count(*) FROM organizations WHERE name NOT LIKE '%(синтетические данные)'`); unmarked != 0 { + t.Errorf("organizations without the synthetic marker = %d", unmarked) + } + if unmarked := stand.count(t, `SELECT count(*) FROM candidate_profiles AS profile WHERE NOT EXISTS ( + SELECT 1 FROM candidate_profile_claims AS claim + WHERE claim.user_id = profile.user_id AND claim.kind = 'full_name' AND claim.value::text LIKE '%синтетический профиль%')`); unmarked != 0 { + t.Errorf("profiles without the synthetic marker in the name = %d", unmarked) + } + if prepared := stand.count(t, `SELECT count(DISTINCT user_id) FROM candidate_profile_claims + WHERE kind = 'experience' AND value::text LIKE '%подготовлена командой demo-seed%'`); prepared != 6 { + t.Errorf("profiles that label the prepared attempt = %d, want 6", prepared) + } + if other := stand.count(t, `SELECT count(*) FROM candidate_assessment_categories WHERE source <> 'synthetic_demo' OR calibration_status <> 'uncalibrated'`); other != 0 { + t.Errorf("categories outside the uncalibrated synthetic source = %d", other) + } + if outside := stand.count(t, `SELECT count(*) FROM users WHERE email_normalized NOT LIKE '%@' || $1`, seedusecase.SyntheticDomain); outside != 0 { + t.Errorf("seeded accounts outside the synthetic domain = %d", outside) + } +} + +// assertDemoSeedPermissions checks the two organizations: each has its own +// owner, and the owner of Alpha is only a recruiter of Beta. +func assertDemoSeedPermissions(t *testing.T, stand demoSeedStand) { + t.Helper() + rows, err := stand.pool.Query(stand.ctx, ` + SELECT split_part(users.email_normalized, '@', 1), organizations.name, memberships.role, memberships.state + FROM memberships + JOIN users ON users.id = memberships.user_id + JOIN organizations ON organizations.id = memberships.organization_id + ORDER BY 1, 2`) + if err != nil { + t.Fatalf("read memberships: %v", err) + } + defer rows.Close() + var got []string + for rows.Next() { + var account, organization, role, state string + if err := rows.Scan(&account, &organization, &role, &state); err != nil { + t.Fatalf("scan membership: %v", err) + } + got = append(got, fmt.Sprintf("%s|%s|%s|%s", account, strings.Fields(organization)[1], role, state)) + } + want := []string{ + "employer-alpha|«Альфа»|owner|active", + "employer-alpha|«Бета»|recruiter|active", + "employer-beta|«Бета»|owner|active", + } + if strings.Join(got, ",") != strings.Join(want, ",") { + t.Fatalf("memberships = %v, want %v", got, want) + } +} + +func demoSeedKeyring(t *testing.T) *identity.Keyring { + t.Helper() + keyring, err := identity.NewKeyring([]byte(demoSeedKeySecret)) + if err != nil { + t.Fatalf("NewKeyring() error = %v", err) + } + return keyring +} + +// assertDemoSeedVisibleCohort checks that the owner of Alpha sees the six +// prepared cards, which pass the minimum cohort of five, and no card of the +// self-service candidate, who did not publish. +func assertDemoSeedVisibleCohort(t *testing.T, stand demoSeedStand) { + t.Helper() + key, err := demoSeedKeyring(t).CandidateViewPseudonymKey() + if err != nil { + t.Fatalf("CandidateViewPseudonymKey() error = %v", err) + } + transactor := postgresadapter.NewTransactor(stand.pool) + quota := companyquota.NewService(time.Now) + views, err := candidateview.NewService(candidateview.Dependencies{ + Transactor: transactor, Projector: anonymousprofile.NewService(postgresadapter.NewPrivacyCohortStore(stand.pool), key, time.Now), + PseudonymKey: key, Clock: time.Now, + Quota: func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, candidateID uuid.UUID) (outbound.CompanyQuotaDecision, error) { + return quota.ReserveCardView(ctx, unit, organization, candidateID) + }, + }) + if err != nil { + t.Fatalf("candidateview.NewService() error = %v", err) + } + owner := stand.userID(t, demoEmail("employer-alpha")) + var organizationID uuid.UUID + if err := stand.pool.QueryRow(stand.ctx, `SELECT organization_id FROM memberships WHERE user_id = $1 AND role = 'owner'`, owner).Scan(&organizationID); err != nil { + t.Fatalf("read Alpha: %v", err) + } + var cards []domain.VisibleCandidateCard + err = transactor.WithinTransaction(stand.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + var err error + cards, err = views.ListVisibleCards(ctx, unit, owner, organizationID) + return err + }) + if err != nil { + t.Fatalf("ListVisibleCards() error = %v", err) + } + selfService := stand.userID(t, demoEmail("candidate")) + if len(cards) != 6 { + t.Fatalf("visible cards of Alpha = %d, want the six prepared candidates", len(cards)) + } + for _, card := range cards { + if card.CandidateID == selfService { + t.Fatal("the unpublished self-service candidate is visible") + } + } +} + +// assertExpressAssignsNoCategory runs the express as the self-service +// candidate through the ordinary attempt operations, then checks that it +// created no category and no evidence, and that the full test still starts. +func assertExpressAssignsNoCategory(t *testing.T, stand demoSeedStand) { + t.Helper() + transactor := postgresadapter.NewTransactor(stand.pool) + attempts, err := assessment.NewAttemptServiceWithCategorySettings(transactor, transactor, demoSeedKeyring(t), time.Now, + assessment.AssessmentCategoryDecisionSettings{SyntheticDemoAssignmentsEnabled: true}) + if err != nil { + t.Fatalf("NewAttemptServiceWithCategorySettings() error = %v", err) + } + candidateID := stand.userID(t, demoEmail("candidate")) + factsBefore := stand.count(t, `SELECT count(*) FROM skill_evidence_facts`) + created, err := attempts.CreateAttempt(stand.ctx, assessment.CreateAttemptCommand{ + ActorID: candidateID, IdempotencyKey: "express-" + uuid.NewString(), Kind: domain.AssessmentAttemptKindDemoExpress, + }) + if err != nil || created.Outcome.StatusCode != http.StatusCreated { + t.Fatalf("create express = %+v, %v", created.Outcome, err) + } + var express domain.AssessmentAttempt + err = transactor.WithinTransaction(stand.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + var err error + express, err = unit.AssessmentAttempts().GetForCandidate(ctx, candidateID, created.Outcome.Response.ID) + return err + }) + if err != nil { + t.Fatalf("read express attempt: %v", err) + } + snapshot := express.Snapshot() + if len(snapshot.Items) != 3 || snapshot.BankCategory != domain.AssessmentCategory(seedusecase.TrainingCategory) { + t.Fatalf("express has %d items from %q, want 3 from the training category", len(snapshot.Items), snapshot.BankCategory) + } + version := snapshot.Version + for _, item := range snapshot.Items { + reference, err := strconv.ParseInt(item.Variant.ReferenceAnswer, 10, 64) + if err != nil { + t.Fatalf("express reference answer %q: %v", item.Variant.ReferenceAnswer, err) + } + answer, err := json.Marshal(map[string]any{"format": "number", "number": reference}) + if err != nil { + t.Fatalf("marshal express answer: %v", err) + } + result, err := attempts.SubmitAnswer(stand.ctx, assessment.SubmitAttemptAnswerCommand{ + ActorID: candidateID, AttemptID: express.ID(), ItemID: item.ID, ExpectedVersion: version, + IdempotencyKey: "express-answer-" + uuid.NewString(), Answer: answer, + }) + if err != nil || result.Outcome.StatusCode != http.StatusOK { + t.Fatalf("answer express item = %+v, %v", result.Outcome, err) + } + version = result.Outcome.Response.Version + } + finalized, err := attempts.FinalizeAttempt(stand.ctx, assessment.FinalizeAssessmentAttemptCommand{ + ActorID: candidateID, AttemptID: express.ID(), ExpectedVersion: version, IdempotencyKey: "express-finalize-" + uuid.NewString(), + }) + if err != nil || finalized.Outcome.StatusCode != http.StatusOK { + t.Fatalf("finalize express = %+v, %v", finalized.Outcome, err) + } + if categories := stand.count(t, `SELECT count(*) FROM candidate_assessment_categories WHERE candidate_id = $1`, candidateID); categories != 0 { + t.Fatalf("categories after a perfect express = %d, want none", categories) + } + if outcome := stand.count(t, `SELECT count(*) FROM assessment_attempts WHERE id = $1 AND outcome = 'demonstration'`, express.ID().UUID()); outcome != 1 { + t.Fatalf("express outcome rows = %d, want one demonstration outcome", outcome) + } + if facts := stand.count(t, `SELECT count(*) FROM skill_evidence_facts`); facts != factsBefore { + t.Fatalf("evidence facts after the express = %d, want %d", facts, factsBefore) + } + specialization, grade, language := domain.SpecializationBackend, domain.GradeJunior, domain.TaskLanguageGo + full, err := attempts.CreateAttempt(stand.ctx, assessment.CreateAttemptCommand{ + ActorID: candidateID, IdempotencyKey: "full-" + uuid.NewString(), Kind: domain.AssessmentAttemptKindRoot, + Specialization: &specialization, TargetGrade: &grade, TaskLanguage: &language, + }) + if err != nil || full.Outcome.StatusCode != http.StatusCreated { + t.Fatalf("start the full test = %+v, %v, want a new attempt", full.Outcome, err) + } +} diff --git a/backend/internal/adapter/primary/cli/demoseed/command.go b/backend/internal/adapter/primary/cli/demoseed/command.go new file mode 100644 index 0000000..02517f9 --- /dev/null +++ b/backend/internal/adapter/primary/cli/demoseed/command.go @@ -0,0 +1,329 @@ +// Package demoseed implements the local operator command of the isolated +// demonstration stand: it seeds the synthetic demo world, checks whether the +// stand's database may be discarded by a reset, and prints an inventory of +// counts. Every subcommand requires DEMO_MODE=isolated, and the command never +// deletes anything; the reset itself is a deploy target that discards the +// dedicated demo Compose project after this check. +package demoseed + +import ( + "context" + "crypto/rand" + "errors" + "flag" + "fmt" + "io" + "strings" + "time" + + "github.com/jackc/pgx/v5/pgxpool" + + "lincodex/backend/config" + "lincodex/backend/internal/adapter/secondary/argon2id" + "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/assessment" + "lincodex/backend/internal/usecase/candidateprivacy" + "lincodex/backend/internal/usecase/consent" + seedusecase "lincodex/backend/internal/usecase/demoseed" + "lincodex/backend/internal/usecase/identity" + "lincodex/backend/internal/usecase/profile" + "lincodex/backend/internal/usecase/questionnaire" +) + +const ( + usage = "usage: demo-seed seed --actor operator: | demo-seed check-reset | demo-seed inventory" + + // DemoModeName and IsolatedDemoMode are the explicit guard of the command. + DemoModeName = "DEMO_MODE" + IsolatedDemoMode = "isolated" + // PasswordName holds the shared password of the synthetic accounts. It + // comes from the demo env file and is never printed. + PasswordName = "DEMO_ACCOUNT_PASSWORD" //nolint:gosec // The name of an environment variable, not a credential. + + // poolSize covers the seed's sequential transactions and the nested + // reads of the services it drives. + poolSize = 4 + // hashConcurrency is one Argon2id derivation at a time; the seed creates a + // handful of accounts once. + hashConcurrency = 1 + // ephemeralKeyBytes is the size of the per-run idempotency secret. The + // seed is idempotent by the state it reads, so its idempotency records + // need no key shared with the backend. + ephemeralKeyBytes = 48 +) + +const syntheticWarning = "warning: synthetic demonstration data for an isolated demo stand only; never on a stand with real people\n" + +// Subcommand names one action. +type Subcommand string + +const ( + SubcommandSeed Subcommand = "seed" + SubcommandCheckReset Subcommand = "check-reset" + SubcommandInventory Subcommand = "inventory" +) + +// Command is a parsed, validated request. +type Command struct { + Subcommand Subcommand + Actor domain.AssessmentOperator +} + +// Parse validates every argument before Run reads configuration or connects. +func Parse(args []string) (Command, error) { + if len(args) == 0 { + return Command{}, errors.New(usage) + } + switch Subcommand(args[0]) { + case SubcommandCheckReset, SubcommandInventory: + if len(args) != 1 { + return Command{}, errors.New(usage) + } + return Command{Subcommand: Subcommand(args[0])}, nil + case SubcommandSeed: + default: + return Command{}, errors.New(usage) + } + flags := flag.NewFlagSet("demo-seed seed", flag.ContinueOnError) + flags.SetOutput(io.Discard) + actor := flags.String("actor", "", "operator handle") + if err := flags.Parse(args[1:]); err != nil || flags.NArg() != 0 { + return Command{}, errors.New(usage) + } + operator, err := domain.ParseAssessmentOperator(strings.TrimSpace(*actor)) + if err != nil { + return Command{}, errors.New("actor must be operator:") + } + return Command{Subcommand: SubcommandSeed, Actor: operator}, nil +} + +// settings are the validated environment values of one run. +type settings struct { + databaseURL string + password domain.Password +} + +// readSettings checks the demo mode guard, DATABASE_URL, and, for the seed, +// the account password, all before any connection. It loads no dotenv file. +func readSettings(command Command, lookup config.LookupEnv) (settings, error) { + mode, _ := lookup(DemoModeName) + if strings.TrimSpace(mode) != IsolatedDemoMode { + return settings{}, errors.New("DEMO_MODE=isolated is required; the demo seed runs only on an isolated demo stand") + } + databaseURL := config.DatabaseURLFromEnv(lookup) + if databaseURL == "" { + return settings{}, errors.New("DATABASE_URL is not set") + } + result := settings{databaseURL: databaseURL} + if command.Subcommand != SubcommandSeed { + return result, nil + } + raw, _ := lookup(PasswordName) + password, err := domain.NewPassword(raw) + if err != nil { + return settings{}, fmt.Errorf("%s must be a password of at least %d characters", PasswordName, domain.MinNewPasswordCodePoints) + } + result.password = password + return result, nil +} + +// Run parses the command, validates the environment, connects, and executes. +func Run(ctx context.Context, args []string, lookup config.LookupEnv, output io.Writer, clock func() time.Time) error { + command, err := Parse(args) + if err != nil { + return err + } + if lookup == nil || output == nil || clock == nil { + return errors.New("demo seed command dependencies are required") + } + values, err := readSettings(command, lookup) + if err != nil { + return err + } + if _, err := io.WriteString(output, syntheticWarning); err != nil { + return errors.New("could not write the result") + } + pool, err := postgres.NewSizedPool(ctx, values.databaseURL, poolSize) + if err != nil { + return errors.New("database configuration is invalid") + } + defer pool.Close() + if err := pool.Ping(ctx); err != nil { + return errors.New("database is unavailable") + } + store := postgres.NewDemoSeedStore(pool) + inspector, err := seedusecase.NewInspector(store) + if err != nil { + return errors.New("demo seed is unavailable") + } + switch command.Subcommand { + case SubcommandCheckReset: + return ExecuteCheckReset(ctx, inspector, output) + case SubcommandInventory: + return ExecuteInventory(ctx, inspector, output) + case SubcommandSeed: + seeder, err := newSeeder(pool, store, clock) + if err != nil { + return errors.New("demo seed is unavailable") + } + return ExecuteSeed(ctx, seeder, seedusecase.Input{Actor: command.Actor, Password: values.password}, output) + } + return errors.New(usage) +} + +// newSeeder wires the product services the seed drives. Synthetic category +// assignment is on because the command runs only with DEMO_MODE=isolated. +func newSeeder(pool *pgxpool.Pool, store outbound.DemoSeedStore, clock func() time.Time) (*seedusecase.Seeder, error) { + transactor := postgres.NewTransactor(pool) + hasher, err := argon2id.NewHasher(hashConcurrency) + if err != nil { + return nil, fmt.Errorf("demoseed.newSeeder - create hasher: %w", err) + } + secret := make([]byte, ephemeralKeyBytes) + if _, err := rand.Read(secret); err != nil { + return nil, fmt.Errorf("demoseed.newSeeder - draw idempotency secret: %w", err) + } + keyring, err := identity.NewKeyring(secret) + if err != nil { + return nil, fmt.Errorf("demoseed.newSeeder - create keyring: %w", err) + } + attempts, err := assessment.NewAttemptServiceWithCategorySettings(transactor, transactor, keyring, clock, + assessment.AssessmentCategoryDecisionSettings{SyntheticDemoAssignmentsEnabled: true}) + if err != nil { + return nil, fmt.Errorf("demoseed.newSeeder - create attempt service: %w", err) + } + privacy, err := candidateprivacy.NewService(candidateprivacy.Dependencies{Transactor: transactor, Clock: clock}) + if err != nil { + return nil, fmt.Errorf("demoseed.newSeeder - create privacy service: %w", err) + } + attestor, err := assessment.NewCategoryAttestor(transactor) + if err != nil { + return nil, fmt.Errorf("demoseed.newSeeder - create attestor: %w", err) + } + return seedusecase.NewSeeder(seedusecase.Dependencies{ + Transactor: transactor, Store: store, Hasher: hasher, + Consents: consent.NewService(transactor, clock), + Profiles: profile.NewService(transactor, clock), + Questionnaires: questionnaire.NewService(transactor, clock), + Privacy: privacy, Attempts: attempts, + Bank: assessment.NewBank(transactor), Attestor: attestor, Clock: clock, + }) +} + +// Seeder runs the seed. +type Seeder interface { + Seed(ctx context.Context, input seedusecase.Input) (seedusecase.Report, error) +} + +// ExecuteSeed seeds and prints what was created, the logins, and the +// prepared attempts. It prints synthetic addresses and identifiers only; the +// password stays in the demo env file. +func ExecuteSeed(ctx context.Context, seeder Seeder, input seedusecase.Input, output io.Writer) error { + if seeder == nil || output == nil { + return errors.New("demo seed command dependencies are required") + } + report, err := seeder.Seed(ctx, input) + if err != nil { + return safeSeedError(err) + } + var text strings.Builder + fmt.Fprintf(&text, "seeded: product policy version %d; created %d records, found %d already present\n", + report.PolicyVersion, len(report.Created), len(report.Present)) + for _, item := range report.Created { + fmt.Fprintf(&text, "created: %s\n", item) + } + for _, login := range report.Logins { + fmt.Fprintf(&text, "login: %s (%s)\n", login.Email, login.Role) + } + text.WriteString("password: the " + PasswordName + " value of the demo env file; it is not printed\n") + for _, prepared := range report.PreparedAttempts { + fmt.Fprintf(&text, "prepared full attempt: %s of %s\n", prepared.AttemptID, prepared.Email) + } + text.WriteString("note: the prepared attempts were answered by the seed through the ordinary attempt operations; " + + "they are synthetic and no person took them. The express mode has its own policy section and bank and never assigns a category.\n") + if _, err := io.WriteString(output, text.String()); err != nil { + return errors.New("could not write the result") + } + return nil +} + +func safeSeedError(err error) error { + switch { + case errors.Is(err, seedusecase.ErrStandNotFresh): + return errors.New("the stand holds ordinary accounts and was never seeded; seed only a fresh isolated demo stand") + case errors.Is(err, seedusecase.ErrForeignPolicy): + return errors.New("the product policy is neither the initial demo version nor the seeded one; seed only a fresh isolated demo stand") + case errors.Is(err, seedusecase.ErrAccountConflict): + return errors.New("a demo address belongs to an account the seed did not create; reset the isolated demo stand") + case errors.Is(err, seedusecase.ErrPreparedAttemptFailed): + return errors.New("a prepared attempt did not assign its demonstration category; reset the isolated demo stand") + case errors.Is(err, outbound.ErrPolicyVersionNotFound): + return errors.New("the product policy has no version yet; start the backend once so that it seeds the demo policy") + default: + return errors.New("demo seed failed") + } +} + +// Inspector reads the census and the inventory. +type Inspector interface { + CheckReset(ctx context.Context) (seedusecase.ResetCheck, error) + Inventory(ctx context.Context) (outbound.DemoInventory, error) +} + +// ExecuteCheckReset prints the verdict and fails when the database holds an +// account outside the synthetic domain, so the reset target stops before it +// discards anything. +func ExecuteCheckReset(ctx context.Context, inspector Inspector, output io.Writer) error { + if inspector == nil || output == nil { + return errors.New("demo seed command dependencies are required") + } + check, err := inspector.CheckReset(ctx) + if err != nil { + return errors.New("reset check failed") + } + if !check.Verdict.Allowed() { + return fmt.Errorf("reset refused: the stand holds %d accounts outside @%s; the reset never deletes ordinary data", + check.Census.Ordinary(), seedusecase.SyntheticDomain) + } + if _, err := fmt.Fprintf(output, "reset allowed (%s): %d accounts, all on @%s\n", + check.Verdict, check.Census.Total, seedusecase.SyntheticDomain); err != nil { + return errors.New("could not write the result") + } + return nil +} + +// ExecuteInventory prints stable key=value counts, so two runs can be +// compared line by line. +func ExecuteInventory(ctx context.Context, inspector Inspector, output io.Writer) error { + if inspector == nil || output == nil { + return errors.New("demo seed command dependencies are required") + } + inventory, err := inspector.Inventory(ctx) + if err != nil { + return errors.New("inventory failed") + } + lines := []struct { + name string + value int64 + }{ + {"synthetic_accounts", inventory.SyntheticAccounts}, {"verified_synthetic_accounts", inventory.VerifiedSynthetic}, + {"ordinary_accounts", inventory.OrdinaryAccounts}, {"organizations", inventory.Organizations}, + {"memberships", inventory.Memberships}, {"consent_records", inventory.ConsentRecords}, + {"candidate_profiles", inventory.CandidateProfiles}, {"questionnaires", inventory.Questionnaires}, + {"attempts", inventory.Attempts}, {"attempt_results", inventory.AttemptResults}, + {"current_categories", inventory.CurrentCategories}, {"evidence_facts", inventory.EvidenceFacts}, + {"published_cards", inventory.PublishedCards}, {"product_policy_versions", inventory.ProductPolicyVersions}, + {"published_families", inventory.PublishedFamilies}, {"category_openings", inventory.CategoryOpenings}, + {"category_attestations", inventory.CategoryAttestations}, {"training_bindings", inventory.TrainingBindings}, + } + var text strings.Builder + for _, line := range lines { + fmt.Fprintf(&text, "%s=%d\n", line.name, line.value) + } + if _, err := io.WriteString(output, text.String()); err != nil { + return errors.New("could not write the result") + } + return nil +} diff --git a/backend/internal/adapter/primary/cli/demoseed/command_test.go b/backend/internal/adapter/primary/cli/demoseed/command_test.go new file mode 100644 index 0000000..3b10f87 --- /dev/null +++ b/backend/internal/adapter/primary/cli/demoseed/command_test.go @@ -0,0 +1,175 @@ +package demoseed + +import ( + "bytes" + "context" + "errors" + "strings" + "testing" + "time" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + seedusecase "lincodex/backend/internal/usecase/demoseed" +) + +func TestParseAcceptsOnlyTheThreeSubcommands(t *testing.T) { + command, err := Parse([]string{"seed", "--actor", "operator:night"}) + if err != nil || command.Subcommand != SubcommandSeed || command.Actor != "operator:night" { + t.Fatalf("Parse(seed) = %+v, %v", command, err) + } + for _, args := range [][]string{{"check-reset"}, {"inventory"}} { + if command, err := Parse(args); err != nil || string(command.Subcommand) != args[0] { + t.Errorf("Parse(%v) = %+v, %v", args, command, err) + } + } + for _, args := range [][]string{ + nil, {"reset"}, {"seed"}, {"seed", "--actor", "alice"}, {"seed", "--actor", "system:demo-seed"}, + {"seed", "--actor", "operator:night", "extra"}, {"check-reset", "--force"}, {"inventory", "all"}, + } { + if _, err := Parse(args); err == nil { + t.Errorf("Parse(%v) accepted invalid arguments", args) + } + } +} + +func lookupOf(values map[string]string) func(string) (string, bool) { + return func(key string) (string, bool) { + value, ok := values[key] + return value, ok + } +} + +func TestRunRefusesWithoutTheIsolatedModeBeforeReadingAnythingElse(t *testing.T) { + for _, mode := range []string{"", "production", "ISOLATED", "isolated-ish"} { + values := map[string]string{"DATABASE_URL": "postgres://unreachable.invalid/none", PasswordName: "a long synthetic password"} + if mode != "" { + values[DemoModeName] = mode + } + var output bytes.Buffer + err := Run(context.Background(), []string{"check-reset"}, lookupOf(values), &output, time.Now) + if err == nil || !strings.Contains(err.Error(), "DEMO_MODE=isolated") || output.Len() != 0 { + t.Errorf("Run with DEMO_MODE=%q = %v, output %q; want a refusal before any output", mode, err, output.String()) + } + } + err := Run(context.Background(), []string{"seed", "--actor", "operator:night"}, + lookupOf(map[string]string{DemoModeName: IsolatedDemoMode, "DATABASE_URL": "postgres://unreachable.invalid/none", PasswordName: "short"}), + &bytes.Buffer{}, time.Now) + if err == nil || !strings.Contains(err.Error(), PasswordName) || strings.Contains(err.Error(), "short") { + t.Fatalf("Run(seed, short password) = %v, want a refusal that does not echo the value", err) + } + err = Run(context.Background(), []string{"inventory"}, lookupOf(map[string]string{DemoModeName: IsolatedDemoMode}), &bytes.Buffer{}, time.Now) + if err == nil || !strings.Contains(err.Error(), "DATABASE_URL") { + t.Fatalf("Run(inventory) without a database = %v", err) + } +} + +type seederFake struct { + report seedusecase.Report + err error +} + +func (fake seederFake) Seed(context.Context, seedusecase.Input) (seedusecase.Report, error) { + return fake.report, fake.err +} + +func TestExecuteSeedPrintsLoginsAndAttemptsButNeverThePassword(t *testing.T) { + attemptID, err := domain.NewAssessmentAttemptID() + if err != nil { + t.Fatalf("NewAssessmentAttemptID() error = %v", err) + } + report := seedusecase.Report{ + PolicyVersion: 2, Created: []string{"account candidate@demo.lincodex.test"}, + Logins: []seedusecase.Login{{Email: "candidate@demo.lincodex.test", Role: "candidate"}}, + PreparedAttempts: []seedusecase.PreparedAttempt{{Email: "prepared-1@demo.lincodex.test", AttemptID: attemptID}}, + } + var output bytes.Buffer + password, err := domain.NewPassword("a long synthetic password") + if err != nil { + t.Fatalf("NewPassword() error = %v", err) + } + if err := ExecuteSeed(context.Background(), seederFake{report: report}, seedusecase.Input{Password: password}, &output); err != nil { + t.Fatalf("ExecuteSeed() error = %v", err) + } + text := output.String() + for _, want := range []string{ + "created 1 records, found 0", "login: candidate@demo.lincodex.test", "prepared full attempt: " + attemptID.String(), + "no person took them", "never assigns a category", + } { + if !strings.Contains(text, want) { + t.Errorf("output lacks %q:\n%s", want, text) + } + } + if strings.Contains(text, "a long synthetic password") { + t.Fatal("the output contains the password") + } + for _, test := range []struct { + err error + want string + }{ + {seedusecase.ErrStandNotFresh, "never seeded"}, + {seedusecase.ErrForeignPolicy, "neither the initial demo version"}, + {seedusecase.ErrAccountConflict, "did not create"}, + {seedusecase.ErrPreparedAttemptFailed, "did not assign"}, + {outbound.ErrPolicyVersionNotFound, "no version yet"}, + {errors.New("pq: password authentication failed for user x"), "demo seed failed"}, + } { + err := ExecuteSeed(context.Background(), seederFake{err: test.err}, seedusecase.Input{}, &bytes.Buffer{}) + if err == nil || !strings.Contains(err.Error(), test.want) || strings.Contains(err.Error(), "authentication") { + t.Errorf("ExecuteSeed(%v) = %v, want a safe message containing %q", test.err, err, test.want) + } + } +} + +type inspectorFake struct { + census outbound.DemoAccountCensus + err error +} + +func (fake inspectorFake) CheckReset(context.Context) (seedusecase.ResetCheck, error) { + return seedusecase.ResetCheck{Verdict: seedusecase.DecideReset(fake.census), Census: fake.census}, fake.err +} + +func (fake inspectorFake) Inventory(context.Context) (outbound.DemoInventory, error) { + return outbound.DemoInventory{SyntheticAccounts: fake.census.Synthetic, OrdinaryAccounts: fake.census.Ordinary()}, fake.err +} + +func TestExecuteCheckResetFailsOnOrdinaryAccounts(t *testing.T) { + for _, test := range []struct { + census outbound.DemoAccountCensus + want string + fails bool + }{ + {outbound.DemoAccountCensus{}, "reset allowed (empty)", false}, + {outbound.DemoAccountCensus{Total: 9, Synthetic: 9}, "reset allowed (synthetic): 9 accounts", false}, + {outbound.DemoAccountCensus{Total: 10, Synthetic: 9}, "holds 1 accounts outside", true}, + {outbound.DemoAccountCensus{Total: 1}, "holds 1 accounts outside", true}, + } { + var output bytes.Buffer + err := ExecuteCheckReset(context.Background(), inspectorFake{census: test.census}, &output) + if test.fails != (err != nil) { + t.Fatalf("ExecuteCheckReset(%+v) = %v, want failure %v", test.census, err, test.fails) + } + text := output.String() + if err != nil { + text = err.Error() + } + if !strings.Contains(text, test.want) { + t.Errorf("ExecuteCheckReset(%+v) said %q, want %q", test.census, text, test.want) + } + } + if err := ExecuteCheckReset(context.Background(), inspectorFake{err: errors.New("connection reset")}, &bytes.Buffer{}); err == nil || + err.Error() != "reset check failed" { + t.Fatalf("ExecuteCheckReset(store failure) = %v, want a refusal", err) + } +} + +func TestExecuteInventoryPrintsStableCounts(t *testing.T) { + var output bytes.Buffer + if err := ExecuteInventory(context.Background(), inspectorFake{census: outbound.DemoAccountCensus{Total: 10, Synthetic: 9}}, &output); err != nil { + t.Fatalf("ExecuteInventory() error = %v", err) + } + if !strings.HasPrefix(output.String(), "synthetic_accounts=9\nverified_synthetic_accounts=0\nordinary_accounts=1\n") { + t.Fatalf("inventory = %q", output.String()) + } +} diff --git a/backend/internal/adapter/secondary/postgres/demo_seed.go b/backend/internal/adapter/secondary/postgres/demo_seed.go new file mode 100644 index 0000000..37ede9a --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/demo_seed.go @@ -0,0 +1,252 @@ +package postgres + +import ( + "context" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +// DemoSeedStore implements outbound.DemoSeedStore on a pool. Its statements +// read counts and identifiers only. +type DemoSeedStore struct { + pool *pgxpool.Pool +} + +var _ outbound.DemoSeedStore = (*DemoSeedStore)(nil) + +// NewDemoSeedStore returns the store of the demo seed operator command. +func NewDemoSeedStore(pool *pgxpool.Pool) *DemoSeedStore { + return &DemoSeedStore{pool: pool} +} + +// CountAccounts counts every account and those on the synthetic domain. The +// domain is compared on the normalized address, so letter case does not +// matter. +func (store *DemoSeedStore) CountAccounts(ctx context.Context, syntheticDomain string) (outbound.DemoAccountCensus, error) { + const location = "DemoSeedStore.CountAccounts" + var census outbound.DemoAccountCensus + if err := store.pool.QueryRow(ctx, ` + SELECT count(*), count(*) FILTER (WHERE right(email_normalized, char_length($1::text) + 1) = '@' || $1::text) + FROM users`, syntheticDomain).Scan(&census.Total, &census.Synthetic); err != nil { + return outbound.DemoAccountCensus{}, fmt.Errorf("%s - count accounts: %w", location, sanitizeConnectError(err)) + } + return census, nil +} + +// CurrentCategoryAttempt returns the source attempt of the candidate's +// current category of the specialization. +func (store *DemoSeedStore) CurrentCategoryAttempt( + ctx context.Context, + candidateID uuid.UUID, + specialization domain.SpecializationCode, +) (domain.AssessmentAttemptID, bool, error) { + const location = "DemoSeedStore.CurrentCategoryAttempt" + var attemptID uuid.UUID + err := store.pool.QueryRow(ctx, ` + SELECT source_attempt_id FROM candidate_assessment_categories + WHERE candidate_id = $1 AND specialization = $2`, candidateID, string(specialization)).Scan(&attemptID) + if errors.Is(err, pgx.ErrNoRows) { + return domain.AssessmentAttemptID{}, false, nil + } + if err != nil { + return domain.AssessmentAttemptID{}, false, fmt.Errorf("%s - read current category: %w", location, sanitizeConnectError(err)) + } + return domain.AssessmentAttemptID(attemptID), true, nil +} + +// TrainingBindingExists reports whether the category has a binding for the +// policy version. +func (store *DemoSeedStore) TrainingBindingExists( + ctx context.Context, + category string, + policyVersionID domain.PolicyVersionID, +) (bool, error) { + const location = "DemoSeedStore.TrainingBindingExists" + var exists bool + if err := store.pool.QueryRow(ctx, ` + SELECT EXISTS ( + SELECT 1 FROM assessment_training_bank_bindings + WHERE category = $1 AND product_policy_version_id = $2 + )`, category, uuid.UUID(policyVersionID)).Scan(&exists); err != nil { + return false, fmt.Errorf("%s - read training binding: %w", location, sanitizeConnectError(err)) + } + return exists, nil +} + +type demoTrainingFamily struct { + id uuid.UUID + key string + version int32 + hash []byte +} + +type demoTrainingManifestEntry struct { + FamilyKey string `json:"family_key"` + Version int32 `json:"version"` + ContentSHA256 string `json:"content_sha256"` +} + +// BindTrainingBank pins every published family of the training category in +// one transaction. The binding triggers check that the category has no real +// opening, that the item count matches the policy, and that the policy is +// the one in force. +func (store *DemoSeedStore) BindTrainingBank(ctx context.Context, binding outbound.DemoTrainingBinding) error { + const location = "DemoSeedStore.BindTrainingBank" + if binding.Category == "" || binding.ItemCount < 1 || binding.PolicyVersionID == (domain.PolicyVersionID{}) { + return fmt.Errorf("%s - binding is incomplete: %w", location, outbound.ErrDemoTrainingBindingMismatch) + } + if _, err := domain.ParseAssessmentOperator(string(binding.ReviewedBy)); err != nil { + return fmt.Errorf("%s - validate reviewer: %w", location, err) + } + tx, err := store.pool.BeginTx(ctx, transactionOptions) + if err != nil { + return fmt.Errorf("%s - begin transaction: %w", location, sanitizeConnectError(err)) + } + finished := false + defer func() { + if !finished { + _ = rollback(ctx, tx) + } + }() + families, err := readPublishedTrainingFamilies(ctx, tx, binding.Category) + if err != nil { + return fmt.Errorf("%s - %w", location, err) + } + if len(families) != binding.ItemCount { + return fmt.Errorf("%s - %d published families for %d items: %w", + location, len(families), binding.ItemCount, outbound.ErrDemoTrainingBindingMismatch) + } + if err := insertTrainingBinding(ctx, tx, binding, families); err != nil { + return fmt.Errorf("%s - %w", location, err) + } + finished = true + if err := tx.Commit(ctx); err != nil { + return fmt.Errorf("%s - commit transaction: %w", location, markTransactionConflict(err)) + } + return nil +} + +func readPublishedTrainingFamilies(ctx context.Context, tx pgx.Tx, category string) ([]demoTrainingFamily, error) { + rows, err := tx.Query(ctx, ` + SELECT id, family_key, version, content_sha256 + FROM assessment_families + WHERE category = $1 AND lifecycle = 'published' + ORDER BY family_key, version`, category) + if err != nil { + return nil, fmt.Errorf("read published families: %w", sanitizeConnectError(err)) + } + defer rows.Close() + var families []demoTrainingFamily + for rows.Next() { + var family demoTrainingFamily + if err := rows.Scan(&family.id, &family.key, &family.version, &family.hash); err != nil { + return nil, fmt.Errorf("scan published family: %w", err) + } + families = append(families, family) + } + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("iterate published families: %w", sanitizeConnectError(err)) + } + return families, nil +} + +// insertTrainingBinding stores the binding with the JSON manifest and the +// same canonical manifest hash that a category opening uses. +func insertTrainingBinding(ctx context.Context, tx pgx.Tx, binding outbound.DemoTrainingBinding, families []demoTrainingFamily) error { + entries := make([]demoTrainingManifestEntry, len(families)) + canonical := make([]domain.AssessmentCategoryManifestEntry, len(families)) + for index, family := range families { + entries[index] = demoTrainingManifestEntry{ + FamilyKey: family.key, Version: family.version, ContentSHA256: hex.EncodeToString(family.hash), + } + canonical[index] = domain.AssessmentCategoryManifestEntry{ + FamilyKey: domain.AssessmentFamilyKey(family.key), Version: family.version, ContentSHA256: family.hash, + } + } + manifest, err := json.Marshal(entries) + if err != nil { + return fmt.Errorf("encode manifest: %w", err) + } + manifestHash, err := assessmentCategoryManifestFingerprint(canonical) + if err != nil { + return fmt.Errorf("hash manifest: %w", err) + } + bindingID, err := uuid.NewV7() + if err != nil { + return fmt.Errorf("generate binding ID: %w", err) + } + if _, err := tx.Exec(ctx, ` + INSERT INTO assessment_training_bank_bindings ( + id, category, product_policy_version_id, item_count, manifest_sha256, family_manifest, reviewed_by, created_at + ) VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7, clock_timestamp())`, + bindingID, binding.Category, uuid.UUID(binding.PolicyVersionID), binding.ItemCount, + manifestHash[:], manifest, string(binding.ReviewedBy)); err != nil { + return fmt.Errorf("insert binding: %w", sanitizeConnectError(err)) + } + for index, family := range families { + if _, err := tx.Exec(ctx, ` + INSERT INTO assessment_training_bank_binding_families ( + binding_id, ordinal, family_id, family_key, family_version, content_sha256 + ) VALUES ($1, $2, $3, $4, $5, $6)`, + bindingID, index+1, family.id, family.key, family.version, family.hash); err != nil { + return fmt.Errorf("insert binding family: %w", sanitizeConnectError(err)) + } + } + return nil +} + +// Inventory counts the records of synthetic accounts and of the seed's bank +// categories in one read-only statement. +func (store *DemoSeedStore) Inventory( + ctx context.Context, + syntheticDomain string, + categories []string, +) (outbound.DemoInventory, error) { + const location = "DemoSeedStore.Inventory" + inventory := outbound.DemoInventory{SyntheticAccountDomain: syntheticDomain} + if err := store.pool.QueryRow(ctx, ` + WITH synthetic AS ( + SELECT id, email_verified_at FROM users + WHERE right(email_normalized, char_length($1::text) + 1) = '@' || $1::text + ) + SELECT + (SELECT count(*) FROM synthetic), + (SELECT count(*) FROM synthetic WHERE email_verified_at IS NOT NULL), + (SELECT count(DISTINCT organization_id) FROM memberships WHERE user_id IN (SELECT id FROM synthetic)), + (SELECT count(*) FROM memberships WHERE user_id IN (SELECT id FROM synthetic)), + (SELECT count(*) FROM consent_records WHERE subject_id IN (SELECT id FROM synthetic)), + (SELECT count(*) FROM candidate_profiles WHERE user_id IN (SELECT id FROM synthetic)), + (SELECT count(*) FROM candidate_questionnaires WHERE user_id IN (SELECT id FROM synthetic)), + (SELECT count(*) FROM assessment_attempts WHERE user_id IN (SELECT id FROM synthetic)), + (SELECT count(*) FROM assessment_attempt_results WHERE user_id IN (SELECT id FROM synthetic)), + (SELECT count(*) FROM candidate_assessment_categories WHERE candidate_id IN (SELECT id FROM synthetic)), + (SELECT count(*) FROM skill_evidence_facts WHERE candidate_id IN (SELECT id FROM synthetic)), + (SELECT count(*) FROM candidate_effective_publications WHERE user_id IN (SELECT id FROM synthetic)), + (SELECT count(*) FROM policy_versions WHERE policy_key = 'product'), + (SELECT count(*) FROM assessment_families WHERE category = ANY($2::text[]) AND lifecycle = 'published'), + (SELECT count(*) FROM assessment_category_openings WHERE category = ANY($2::text[])), + (SELECT count(*) FROM assessment_synthetic_category_reviews WHERE category = ANY($2::text[])), + (SELECT count(*) FROM assessment_training_bank_bindings WHERE category = ANY($2::text[])), + (SELECT count(*) FROM users)`, + syntheticDomain, categories, + ).Scan( + &inventory.SyntheticAccounts, &inventory.VerifiedSynthetic, &inventory.Organizations, &inventory.Memberships, + &inventory.ConsentRecords, &inventory.CandidateProfiles, &inventory.Questionnaires, &inventory.Attempts, + &inventory.AttemptResults, &inventory.CurrentCategories, &inventory.EvidenceFacts, &inventory.PublishedCards, + &inventory.ProductPolicyVersions, &inventory.PublishedFamilies, &inventory.CategoryOpenings, + &inventory.CategoryAttestations, &inventory.TrainingBindings, &inventory.TotalAccounts, + ); err != nil { + return outbound.DemoInventory{}, fmt.Errorf("%s - count records: %w", location, sanitizeConnectError(err)) + } + inventory.OrdinaryAccounts = inventory.TotalAccounts - inventory.SyntheticAccounts + return inventory, nil +} diff --git a/backend/internal/port/outbound/demo_seed.go b/backend/internal/port/outbound/demo_seed.go new file mode 100644 index 0000000..a0e122e --- /dev/null +++ b/backend/internal/port/outbound/demo_seed.go @@ -0,0 +1,94 @@ +package outbound + +import ( + "context" + "errors" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" +) + +// ErrDemoTrainingBindingMismatch reports that the published families of the +// express training category do not match the binding the seed asked for. +var ErrDemoTrainingBindingMismatch = errors.New("demo training binding does not match the published families") + +// DemoAccountCensus counts the accounts of a stand by whether their address +// belongs to the reserved synthetic demo domain. It holds counts only. +type DemoAccountCensus struct { + Total int64 + Synthetic int64 +} + +// Ordinary is the number of accounts outside the synthetic demo domain. +func (census DemoAccountCensus) Ordinary() int64 { return census.Total - census.Synthetic } + +// DemoTrainingBinding is the express training binding that the demo seed +// stores for the current product policy. The binding pins every published +// family of the training category, which must match ItemCount. +type DemoTrainingBinding struct { + Category string + PolicyVersionID domain.PolicyVersionID + ItemCount int + ReviewedBy domain.AssessmentOperator +} + +// DemoInventory counts the records that the demo seed creates or relies on. +// Two seed runs on the same stand must report the same inventory. It holds +// counts only, never a personal value. +type DemoInventory struct { + SyntheticAccounts int64 + VerifiedSynthetic int64 + Organizations int64 + Memberships int64 + ConsentRecords int64 + CandidateProfiles int64 + Questionnaires int64 + Attempts int64 + AttemptResults int64 + CurrentCategories int64 + EvidenceFacts int64 + PublishedCards int64 + ProductPolicyVersions int64 + PublishedFamilies int64 + CategoryOpenings int64 + CategoryAttestations int64 + TrainingBindings int64 + OrdinaryAccounts int64 + TotalAccounts int64 + SyntheticAccountDomain string +} + +// DemoSeedStore holds the few storage operations of the demo seed that no +// product port covers: an account census, the current category of one +// candidate, the express training binding, and an inventory of counts. Every +// method runs in its own statement or transaction; none reads or returns a +// personal value. +type DemoSeedStore interface { + // CountAccounts counts all accounts and those whose address ends with + // "@" plus syntheticDomain. + CountAccounts(ctx context.Context, syntheticDomain string) (DemoAccountCensus, error) + + // CurrentCategoryAttempt returns the attempt behind the candidate's + // current assessment category of the specialization, and false when the + // candidate holds no such category. + CurrentCategoryAttempt( + ctx context.Context, + candidateID uuid.UUID, + specialization domain.SpecializationCode, + ) (domain.AssessmentAttemptID, bool, error) + + // TrainingBindingExists reports whether the category already has a + // training binding for the policy version. + TrainingBindingExists(ctx context.Context, category string, policyVersionID domain.PolicyVersionID) (bool, error) + + // BindTrainingBank stores the binding of every published family of the + // training category in one transaction. The database checks that the + // category is disjoint from real openings and that the policy is current. + // It returns ErrDemoTrainingBindingMismatch when the published family + // count differs from ItemCount. + BindTrainingBank(ctx context.Context, binding DemoTrainingBinding) error + + // Inventory counts the seed's records on the stand. + Inventory(ctx context.Context, syntheticDomain string, categories []string) (DemoInventory, error) +} diff --git a/backend/internal/usecase/demoseed/attempt.go b/backend/internal/usecase/demoseed/attempt.go new file mode 100644 index 0000000..38d6de3 --- /dev/null +++ b/backend/internal/usecase/demoseed/attempt.go @@ -0,0 +1,202 @@ +package demoseed + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "slices" + "strconv" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/assessment" +) + +// preparedWrongAnswers is the number of frozen items the prepared attempt +// answers wrong, the last ones by ordinal. One mistake keeps the result above +// the demo pass mark of 80% for any item count the demo policy allows (at +// least eight scored items) and shows that the prepared answers are not a +// flawless script of the reference solution. +const preparedWrongAnswers = 1 + +// ensurePreparedAttempt returns the attempt behind the candidate's current +// Backend category. Without one it continues an active attempt or creates a +// new root attempt, answers every frozen item through the ordinary answer +// operation, and finalizes it, so the result, the category, and the evidence +// projection come from the same code and triggers as a candidate's attempt. +func (seeder *Seeder) ensurePreparedAttempt(ctx context.Context, userID uuid.UUID) (domain.AssessmentAttemptID, bool, error) { + attemptID, found, err := seeder.deps.Store.CurrentCategoryAttempt(ctx, userID, fullSpecialization) + if err != nil { + return domain.AssessmentAttemptID{}, false, fmt.Errorf("read current category: %w", err) + } + if found { + return attemptID, false, nil + } + attempt, resumed, err := seeder.activeOrNewAttempt(ctx, userID) + if err != nil { + return domain.AssessmentAttemptID{}, false, err + } + if resumed { + attempt, err = seeder.resumeSession(ctx, userID, attempt) + if err != nil { + return domain.AssessmentAttemptID{}, false, err + } + } + version, err := seeder.answerItems(ctx, userID, attempt) + if err != nil { + return domain.AssessmentAttemptID{}, false, err + } + finalized, err := seeder.deps.Attempts.FinalizeAttempt(ctx, assessment.FinalizeAssessmentAttemptCommand{ + ActorID: userID, AttemptID: attempt.ID(), ExpectedVersion: version, IdempotencyKey: seedKey("finalize"), + }) + if err != nil { + return domain.AssessmentAttemptID{}, false, fmt.Errorf("finalize attempt: %w", err) + } + if finalized.Outcome.StatusCode != http.StatusOK { + return domain.AssessmentAttemptID{}, false, fmt.Errorf("finalize answered %d %s: %w", + finalized.Outcome.StatusCode, finalized.Outcome.ProblemCode, ErrPreparedAttemptFailed) + } + sourceID, found, err := seeder.deps.Store.CurrentCategoryAttempt(ctx, userID, fullSpecialization) + if err != nil { + return domain.AssessmentAttemptID{}, false, fmt.Errorf("read assigned category: %w", err) + } + if !found || sourceID != attempt.ID() { + return domain.AssessmentAttemptID{}, false, ErrPreparedAttemptFailed + } + return attempt.ID(), true, nil +} + +// activeOrNewAttempt returns the active Backend attempt left by an +// interrupted run, or creates the root attempt of the full category. +func (seeder *Seeder) activeOrNewAttempt(ctx context.Context, userID uuid.UUID) (domain.AssessmentAttempt, bool, error) { + var active domain.AssessmentAttempt + found := false + err := seeder.deps.Transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + var err error + active, found, err = unit.AssessmentAttempts().GetActiveForSpecialization(ctx, userID, fullSpecialization) + return err + }) + if err != nil { + return domain.AssessmentAttempt{}, false, fmt.Errorf("read active attempt: %w", err) + } + if found { + return active, true, nil + } + specialization, grade, language := fullSpecialization, fullGrade, fullTaskLanguage + created, err := seeder.deps.Attempts.CreateAttempt(ctx, assessment.CreateAttemptCommand{ + ActorID: userID, IdempotencyKey: seedKey("create"), Kind: domain.AssessmentAttemptKindRoot, + Specialization: &specialization, TargetGrade: &grade, TaskLanguage: &language, + }) + if err != nil { + return domain.AssessmentAttempt{}, false, fmt.Errorf("create attempt: %w", err) + } + if created.Outcome.StatusCode != http.StatusCreated { + return domain.AssessmentAttempt{}, false, fmt.Errorf("create answered %d %s: %w", + created.Outcome.StatusCode, created.Outcome.ProblemCode, ErrPreparedAttemptFailed) + } + attempt, err := seeder.readAttempt(ctx, userID, created.Outcome.Response.ID) + if err != nil { + return domain.AssessmentAttempt{}, false, err + } + return attempt, false, nil +} + +// resumeSession opens a session on an attempt that an interrupted run left, +// because its earlier session may have ended by the idle timeout. +func (seeder *Seeder) resumeSession(ctx context.Context, userID uuid.UUID, attempt domain.AssessmentAttempt) (domain.AssessmentAttempt, error) { + if _, err := seeder.deps.Attempts.StartSession(ctx, assessment.StartAttemptSessionCommand{ + ActorID: userID, AttemptID: attempt.ID(), ExpectedVersion: attempt.Version(), IdempotencyKey: seedKey("session"), + }); err != nil { + return domain.AssessmentAttempt{}, fmt.Errorf("resume attempt session: %w", err) + } + return seeder.readAttempt(ctx, userID, attempt.ID()) +} + +func (seeder *Seeder) readAttempt(ctx context.Context, userID uuid.UUID, attemptID domain.AssessmentAttemptID) (domain.AssessmentAttempt, error) { + var attempt domain.AssessmentAttempt + err := seeder.deps.Transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + var err error + attempt, err = unit.AssessmentAttempts().GetForCandidate(ctx, userID, attemptID) + return err + }) + if err != nil { + return domain.AssessmentAttempt{}, fmt.Errorf("read attempt: %w", err) + } + return attempt, nil +} + +// answerItems answers every unanswered frozen item in order and returns the +// attempt version after the last answer. +func (seeder *Seeder) answerItems(ctx context.Context, userID uuid.UUID, attempt domain.AssessmentAttempt) (int64, error) { + snapshot := attempt.Snapshot() + items := slices.Clone(snapshot.Items) + slices.SortFunc(items, func(left, right domain.AssessmentAttemptItemSnapshot) int { + return int(left.Ordinal - right.Ordinal) + }) + version := snapshot.Version + for index, item := range items { + if !item.AnsweredAt.IsZero() { + continue + } + correct := index < len(items)-preparedWrongAnswers + answer, err := integerAnswer(item.Variant, correct) + if err != nil { + return 0, err + } + result, err := seeder.deps.Attempts.SubmitAnswer(ctx, assessment.SubmitAttemptAnswerCommand{ + ActorID: userID, AttemptID: attempt.ID(), ItemID: item.ID, ExpectedVersion: version, + IdempotencyKey: seedKey("answer"), Answer: answer, + }) + if err != nil { + return 0, fmt.Errorf("answer item %d: %w", item.Ordinal, err) + } + if result.Outcome.StatusCode != http.StatusOK { + return 0, fmt.Errorf("answer item %d answered %d %s: %w", + item.Ordinal, result.Outcome.StatusCode, result.Outcome.ProblemCode, ErrPreparedAttemptFailed) + } + version = result.Outcome.Response.Version + } + return version, nil +} + +// integerAnswer builds the answer body of an integer item: the reference +// answer, or the next integer for a wrong answer. It checks the intended +// correctness against the variant, so a template change cannot silently turn +// the prepared answers into wrong ones. +func integerAnswer(variant domain.AssessmentVariant, correct bool) (json.RawMessage, error) { + if variant.AnswerFormat != domain.AnswerFormatInteger { + return nil, fmt.Errorf("demoseed.integerAnswer - unsupported answer format %q", variant.AnswerFormat) + } + reference, err := strconv.ParseInt(variant.ReferenceAnswer, 10, 64) + if err != nil { + return nil, errors.New("demoseed.integerAnswer - the reference answer is not an integer") + } + if !correct { + reference++ + } + answer, err := json.Marshal(struct { + Format string `json:"format"` + Number int64 `json:"number"` + }{Format: "number", Number: reference}) + if err != nil { + return nil, fmt.Errorf("demoseed.integerAnswer - encode answer: %w", err) + } + _, matches, err := domain.CanonicalAssessmentAnswerForVariant(answer, variant) + if err != nil { + return nil, fmt.Errorf("demoseed.integerAnswer - check answer: %w", err) + } + if matches != correct { + return nil, errors.New("demoseed.integerAnswer - the answer does not have the intended correctness") + } + return answer, nil +} + +// seedKey returns a fresh idempotency key of one seed command. The seed is +// idempotent by the state it reads, not by replaying these keys. +func seedKey(operation string) string { + return "demo-seed:" + operation + ":" + uuid.NewString() +} diff --git a/backend/internal/usecase/demoseed/bank.go b/backend/internal/usecase/demoseed/bank.go new file mode 100644 index 0000000..01b432e --- /dev/null +++ b/backend/internal/usecase/demoseed/bank.go @@ -0,0 +1,144 @@ +package demoseed + +import ( + "fmt" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/usecase/assessment" +) + +const ( + // FullCategory is the bank category of the prepared full attempt and of + // the full test the jury can start. It maps to Backend Junior with Go. + FullCategory = domain.AssessmentCategory("demo-backend-junior") + // TrainingCategory is the separate express training category. It never + // has a real opening, so an express run never feeds a category. + TrainingCategory = "demo-express" + + fullBundleName = "demo-seed-backend-junior" + trainingBundleName = "demo-seed-express" + fullFamilyStem = "demo-seed-backend" + trainingFamilyStem = "demo-seed-express" + // bankAuthor marks the families as synthetic drafts. bankReviewer is the + // fixed audit label of the seed as their reviewer, not a subject review. + // Both are part of the family content, so they stay the same for every + // operator and a repeated import changes nothing. + bankAuthor = "ai:demo-seed-synthetic-bank" + bankReviewer = "operator:demo-seed-bank-reviewer" + // maxBankFamilies bounds what a policy may ask for; the bundle loader + // accepts at most 200 families per bundle. + maxBankFamilies = 200 +) + +// fullSpecialization and friends are the public catalog mapping of the full +// category. +var ( + fullSpecialization = domain.SpecializationBackend + fullGrade = domain.GradeJunior + fullTaskLanguage = domain.TaskLanguageGo +) + +// familyTemplate is one synthetic task family whose answer is an integer. +// The seed answers the integer formats only, so every template has one. +type familyTemplate struct { + specialization string + title string + generator domain.AssessmentSeedGenerator + solution string + principle string + criteria []domain.AssessmentRubricCriterion +} + +const rubricPrinciple = "A submission is first compared with the reference answer of its variant and then judged against the criteria below. This rubric defines no points and no pass mark: how criteria turn into a grade is decided by the versioned grading policy." + +// familyTemplates are the synthetic task families of the demonstration bank, +// the integer-answer families of the checked-in backend demo draft. +func familyTemplates() []familyTemplate { + return []familyTemplate{ + { + specialization: "rate-limiting", + title: "Rejected requests of a sliding-window limiter", + generator: domain.AssessmentSeedGenerator{ + Algorithm: "rate_limit_window.v1", + Parameters: map[string]domain.AssessmentParameterRange{ + "requests": {Min: 12, Max: 30}, "window": {Min: 3, Max: 15}, + "limit": {Min: 2, Max: 6}, "max_gap": {Min: 1, Max: 5}, + }, + StatementTemplate: "A gateway applies a sliding-window limiter. A request at second t is accepted only when fewer than {{.limit}} previously accepted requests arrived in (t - {{.window}}, t]. Rejected requests are not remembered. The gateway receives {{.requests}} requests at these non-decreasing arrival times: {{.timestamps}}. How many requests are rejected?", + }, + solution: "Keep accepted arrival times in order. Before each request at t, remove accepted times at or before t - window. Accept and append t when fewer than limit times remain; otherwise count a rejection without appending it.", + principle: rubricPrinciple, + criteria: []domain.AssessmentRubricCriterion{ + {ID: "correct_answer", Description: "The submitted number equals the reference answer of the variant."}, + {ID: "window_boundary", Description: "A request exactly window seconds old is outside the half-open interval."}, + {ID: "rejected_not_counted", Description: "Rejected requests do not occupy capacity in later windows."}, + }, + }, + { + specialization: "messaging", + title: "Idempotent consumer with a duplicate window", + generator: domain.AssessmentSeedGenerator{ + Algorithm: "dedup_window.v1", + Parameters: map[string]domain.AssessmentParameterRange{ + "events": {Min: 10, Max: 40}, "keys": {Min: 2, Max: 6}, + "ttl": {Min: 3, Max: 20}, "max_gap": {Min: 1, Max: 6}, + }, + StatementTemplate: "A consumer receives {{.events}} messages written as KEY@TIME, where TIME is the arrival second and times never decrease. It processes a message unless the same KEY was processed less than {{.ttl}} seconds earlier; such a message is dropped as a duplicate. A dropped message does not postpone the next processing of its KEY. The stream is: {{.stream}}. How many messages does the consumer process?", + }, + solution: "Keep a map from key to the time of its last processed message. For each message, if the key is present and the time difference is smaller than ttl, drop it; otherwise record the time and count the message as processed.", + principle: rubricPrinciple, + criteria: []domain.AssessmentRubricCriterion{ + {ID: "correct_answer", Description: "The submitted number equals the reference answer of the variant."}, + {ID: "duplicate_boundary", Description: "A message exactly ttl seconds after the last processed one with the same key is processed, not dropped."}, + {ID: "dropped_not_extending", Description: "A dropped duplicate does not move the time stored for its key."}, + }, + }, + { + specialization: "caching", + title: "Hit count of a least-recently-used cache", + generator: domain.AssessmentSeedGenerator{ + Algorithm: "lru_hits.v1", + Parameters: map[string]domain.AssessmentParameterRange{ + "accesses": {Min: 15, Max: 50}, "keys": {Min: 3, Max: 10}, "capacity": {Min: 2, Max: 5}, + }, + StatementTemplate: "An in-memory cache holds at most {{.capacity}} entries and evicts the least recently used entry when it is full and a missing key must be stored. Reading a key that is present is a hit; reading a key that is absent is a miss, after which the key is stored. Both a hit and a miss make the key the most recently used one. The cache starts empty and serves these {{.accesses}} reads, drawn from {{.keys}} possible keys numbered from 1 to {{.keys}}: {{.sequence}}. How many reads are hits?", + }, + solution: "Maintain the cached keys ordered from least to most recently used. On a hit move the key to the recent end; on a miss evict from the old end when the cache is full, then add the key at the recent end. Count the hits.", + principle: rubricPrinciple, + criteria: []domain.AssessmentRubricCriterion{ + {ID: "correct_answer", Description: "The submitted number equals the reference answer of the variant."}, + {ID: "recency_on_hit", Description: "A hit refreshes the recency of the key, so it is evicted later."}, + {ID: "eviction_order", Description: "On a miss in a full cache the least recently used key is evicted before the new key is stored."}, + }, + }, + } +} + +// syntheticBundle builds count reviewed families of the category by cycling +// the templates under keys stem-01, stem-02, and so on. +func syntheticBundle(name string, category string, stem string, count int) (assessment.Bundle, error) { + if count < 1 || count > maxBankFamilies { + return assessment.Bundle{}, fmt.Errorf("demoseed.syntheticBundle - %d families are outside 1 to %d", count, maxBankFamilies) + } + templates := familyTemplates() + bundle := assessment.Bundle{ + Name: name, Category: category, Author: bankAuthor, + Review: assessment.BundleReview{Status: string(domain.AssessmentReviewApproved), Reviewer: bankReviewer}, + Families: make([]assessment.BundleFamily, 0, count), + } + for index := range count { + template := templates[index%len(templates)] + bundle.Families = append(bundle.Families, assessment.BundleFamily{ + Key: fmt.Sprintf("%s-%02d", stem, index+1), Version: 1, + Specialization: template.specialization, + Title: fmt.Sprintf("%s (synthetic demo %02d)", template.title, index+1), + SeedGenerator: template.generator, + AnswerKey: domain.AssessmentAnswerKey{AnswerFormat: domain.AnswerFormatInteger, ReferenceSolution: template.solution}, + Rubric: domain.AssessmentRubric{Principle: template.principle, Criteria: template.criteria}, + }) + } + if _, err := bundle.Drafts(); err != nil { + return assessment.Bundle{}, fmt.Errorf("demoseed.syntheticBundle - validate bundle: %w", err) + } + return bundle, nil +} diff --git a/backend/internal/usecase/demoseed/dataset.go b/backend/internal/usecase/demoseed/dataset.go new file mode 100644 index 0000000..b335570 --- /dev/null +++ b/backend/internal/usecase/demoseed/dataset.go @@ -0,0 +1,161 @@ +package demoseed + +import ( + "fmt" + + "lincodex/backend/internal/domain" +) + +// SyntheticDomain is the reserved address domain of every demo account. The +// .test top-level domain never receives mail, so an account on it can only be +// verified by the seed, and the domain marks the account as synthetic in +// every listing and in the reset check. +const SyntheticDomain = "demo.lincodex.test" + +// preparedCohortSize is the number of identical prepared candidates. The +// anonymous card shows a quasi-identifier combination only from five +// candidates on (domain.GeneralizeAnonymousCandidateCohort), so six keep the +// demo search non-empty after one candidate unpublishes or hides an +// organization during a session. +const preparedCohortSize = 6 + +// accountRole tells what the seed builds for an account. +type accountRole int + +const ( + roleEmployer accountRole = iota + // roleSelfService is the candidate the jury signs in with to run the + // express and to start the full test: profile and questionnaire, no + // attempt, no publication. + roleSelfService + // rolePrepared is a candidate with a prepared full attempt, its synthetic + // demonstration category, and a published card. + rolePrepared +) + +// accountSpec is one synthetic account of the seed. +type accountSpec struct { + local string + role accountRole + ordinal int + fullName string +} + +func (spec accountSpec) email() string { return spec.local + "@" + SyntheticDomain } + +func (spec accountSpec) scenario() domain.Scenario { + if spec.role == roleEmployer { + return domain.ScenarioEmployer + } + return domain.ScenarioCandidate +} + +const ( + alphaOwnerLocal = "employer-alpha" + betaOwnerLocal = "employer-beta" + selfServiceName = "candidate" + preparedStem = "prepared-" +) + +// accounts lists every synthetic account in creation order. +func accounts() []accountSpec { + specs := []accountSpec{ + {local: alphaOwnerLocal, role: roleEmployer}, + {local: betaOwnerLocal, role: roleEmployer}, + {local: selfServiceName, role: roleSelfService, fullName: "Демо-кандидат для самостоятельного прохождения (синтетический профиль)"}, + } + for ordinal := 1; ordinal <= preparedCohortSize; ordinal++ { + specs = append(specs, accountSpec{ + local: fmt.Sprintf("%s%d", preparedStem, ordinal), role: rolePrepared, ordinal: ordinal, + fullName: fmt.Sprintf("Демо-кандидат %d с подготовленной попыткой (синтетический профиль)", ordinal), + }) + } + return specs +} + +// organizationSpec is one synthetic organization: its owner and, optionally, +// a second member with a role that the minimal release denies tenant actions. +type organizationSpec struct { + name string + description string + sphere string + ownerLocal string + memberLocal string + memberRole domain.OrganizationRole +} + +// organizations lists the two synthetic organizations. The owner of Alpha is +// a recruiter of Beta, so one account shows two different permissions: full +// owner access in Alpha and the owner-only denial in Beta. +func organizations() []organizationSpec { + return []organizationSpec{ + { + name: "Демо-компания «Альфа» (синтетические данные)", + description: "Синтетическая организация демонстрационного стенда. Реальной компании за ней нет.", + sphere: "Демонстрационные данные", + ownerLocal: alphaOwnerLocal, + }, + { + name: "Демо-компания «Бета» (синтетические данные)", + description: "Вторая синтетическая организация демонстрационного стенда. Реальной компании за ней нет.", + sphere: "Демонстрационные данные", + ownerLocal: betaOwnerLocal, + memberLocal: alphaOwnerLocal, + memberRole: domain.OrganizationRoleRecruiter, + }, + } +} + +// preparedMarker is the profile text that labels the prepared attempt for +// the candidate and for anyone who reads the profile or its PDF. +const preparedMarker = "Синтетический профиль демонстрационного стенда. Полная попытка теста подготовлена командой demo-seed по обычным правилам теста; человек ее не проходил." + +const selfServiceMarker = "Синтетический профиль демонстрационного стенда для самостоятельного прохождения экспресс-теста и полного теста." + +// profileInput builds the manual profile of a candidate: a name, the +// synthetic address as contact, one stack tag, the declared role, and one +// synthetic work period. No FSP ID is linked; the profile has no place for +// one. +func profileInput(spec accountSpec) domain.CandidateProfileInput { + marker := selfServiceMarker + if spec.role == rolePrepared { + marker = preparedMarker + } + confirmed := domain.ProfileClaimConfirmed + return domain.CandidateProfileInput{ + FullName: &domain.ProfileClaimInput[string]{Value: spec.fullName, Status: confirmed}, + Email: &domain.ProfileClaimInput[string]{Value: spec.email(), Status: confirmed}, + Stack: []domain.ProfileClaimInput[string]{{Value: "go", Status: confirmed}}, + Roles: []domain.ProfileClaimInput[domain.ProfileRole]{{ + Value: domain.ProfileRole{Specialization: fullSpecialization, SelfAssessedGrade: fullGrade}, Status: confirmed, + }}, + Experience: []domain.ProfileClaimInput[domain.ProfileExperience]{{ + Value: domain.ProfileExperience{ + EmployerName: "Синтетическая компания (демо)", Specialization: fullSpecialization, + StartedOn: "2023-01", EndedOn: "2025-12", Summary: marker, + }, + Status: confirmed, + }}, + } +} + +// questionnaireInput declares Backend Junior with Go and remote work, the +// selection of the full category. +func questionnaireInput() domain.CandidateQuestionnaireInput { + return domain.CandidateQuestionnaireInput{ + Specializations: []domain.QuestionnaireSpecialization{{ + Specialization: fullSpecialization, SelfAssessedGrade: fullGrade, + TaskLanguages: []domain.TaskLanguageCode{fullTaskLanguage}, Stack: []string{}, + }}, + WorkFormats: []domain.QuestionnaireWorkFormat{domain.QuestionnaireWorkFormatRemote}, + } +} + +// publishedFields are the card fields of every prepared candidate. They are +// identical across the cohort, so the cards form one cohort of six. +func publishedFields() []domain.CardField { + return []domain.CardField{ + domain.CardFieldCategories, domain.CardFieldStack, domain.CardFieldExperience, + domain.CardFieldSelfAssessment, domain.CardFieldWorkFormats, + } +} diff --git a/backend/internal/usecase/demoseed/reset.go b/backend/internal/usecase/demoseed/reset.go new file mode 100644 index 0000000..bfc45c9 --- /dev/null +++ b/backend/internal/usecase/demoseed/reset.go @@ -0,0 +1,82 @@ +package demoseed + +import ( + "context" + "errors" + "fmt" + + "lincodex/backend/internal/port/outbound" +) + +// ResetVerdict says whether the operator tooling may discard the stand's +// database to rebuild the demo world. +type ResetVerdict string + +const ( + // ResetAllowedEmpty is a stand without any account: nothing to lose. + ResetAllowedEmpty ResetVerdict = "empty" + // ResetAllowedSynthetic is a seeded stand whose every account is a + // synthetic demo account. + ResetAllowedSynthetic ResetVerdict = "synthetic" + // ResetRefusedOrdinary is a stand that holds at least one account outside + // the synthetic domain. Such an account is ordinary data, and the reset + // never deletes it. + ResetRefusedOrdinary ResetVerdict = "ordinary_accounts" +) + +// Allowed reports whether the verdict lets the reset proceed. +func (verdict ResetVerdict) Allowed() bool { + return verdict == ResetAllowedEmpty || verdict == ResetAllowedSynthetic +} + +// ResetCheck is the read-only answer of CheckReset. It holds counts only. +type ResetCheck struct { + Verdict ResetVerdict + Census outbound.DemoAccountCensus +} + +// DecideReset applies the reset rule to an account census: a database may be +// discarded only when it has no account at all or only synthetic demo +// accounts. +func DecideReset(census outbound.DemoAccountCensus) ResetVerdict { + switch { + case census.Total == 0: + return ResetAllowedEmpty + case census.Ordinary() == 0: + return ResetAllowedSynthetic + default: + return ResetRefusedOrdinary + } +} + +// Inspector reads the account census and the inventory of a stand. It +// changes nothing. +type Inspector struct { + store outbound.DemoSeedStore +} + +// NewInspector fails without a store. +func NewInspector(store outbound.DemoSeedStore) (*Inspector, error) { + if store == nil { + return nil, errors.New("demoseed.NewInspector - store must be set") + } + return &Inspector{store: store}, nil +} + +// CheckReset counts the accounts and returns the verdict. +func (inspector *Inspector) CheckReset(ctx context.Context) (ResetCheck, error) { + census, err := inspector.store.CountAccounts(ctx, SyntheticDomain) + if err != nil { + return ResetCheck{}, fmt.Errorf("Inspector.CheckReset - count accounts: %w", err) + } + return ResetCheck{Verdict: DecideReset(census), Census: census}, nil +} + +// Inventory returns the counts of the seed's records. +func (inspector *Inspector) Inventory(ctx context.Context) (outbound.DemoInventory, error) { + inventory, err := inspector.store.Inventory(ctx, SyntheticDomain, []string{string(FullCategory), TrainingCategory}) + if err != nil { + return outbound.DemoInventory{}, fmt.Errorf("Inspector.Inventory - count records: %w", err) + } + return inventory, nil +} diff --git a/backend/internal/usecase/demoseed/seeder.go b/backend/internal/usecase/demoseed/seeder.go new file mode 100644 index 0000000..c3143b7 --- /dev/null +++ b/backend/internal/usecase/demoseed/seeder.go @@ -0,0 +1,686 @@ +// Package demoseed builds the small reproducible demonstration world of an +// isolated demo stand: synthetic accounts of both roles that are confirmed +// without mail, two organizations with different permissions, a candidate +// without an FSP ID, the express training bank apart from the full bank, and +// prepared full attempts that run through the ordinary attempt operations. +// +// The seed is idempotent: a second run finds every record and creates +// nothing. It never changes or removes a record it did not create, and it +// refuses a stand that holds accounts of other people but none of its own. +package demoseed + +import ( + "context" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/assessment" + "lincodex/backend/internal/usecase/candidateprivacy" + "lincodex/backend/internal/usecase/consent" + "lincodex/backend/internal/usecase/policy" + "lincodex/backend/internal/usecase/profile" + "lincodex/backend/internal/usecase/questionnaire" +) + +var ( + // ErrStandNotFresh reports a stand that holds ordinary accounts and no + // account of the seed. The seed never mixes demo records with them. + ErrStandNotFresh = errors.New("the stand holds ordinary accounts and was never seeded") + // ErrForeignPolicy reports a product policy that the seed did not expect: + // neither the initial demo version nor the demo version the seed publishes. + ErrForeignPolicy = errors.New("the product policy is not the initial or the seeded demo policy") + // ErrAccountConflict reports an address of the seed that belongs to an + // account in another state, for example an unconfirmed registration. + ErrAccountConflict = errors.New("a demo address belongs to an account the seed did not create") + // ErrPreparedAttemptFailed reports a prepared attempt that did not end + // with an assigned synthetic demonstration category. + ErrPreparedAttemptFailed = errors.New("the prepared attempt did not assign its demonstration category") +) + +// seedPolicy is the demo product policy version the seed publishes: the +// explicit demo_basic attempt settings, the separate express training mode, +// the review band, and the matching section. +func seedPolicy() domain.ProductPolicy { return domain.DemoProductPolicyV4() } + +// Dependencies are the product services and ports the seed drives. +type Dependencies struct { + Transactor outbound.Transactor + Store outbound.DemoSeedStore + Hasher outbound.PasswordHasher + Consents *consent.Service + Profiles *profile.Service + Questionnaires *questionnaire.Service + Privacy *candidateprivacy.Service + Attempts *assessment.AttemptService + Bank *assessment.Bank + Attestor *assessment.CategoryAttestor + Clock func() time.Time +} + +// Seeder runs the demo seed. +type Seeder struct { + deps Dependencies +} + +// NewSeeder fails when a dependency is missing. +func NewSeeder(deps Dependencies) (*Seeder, error) { + if deps.Transactor == nil || deps.Store == nil || deps.Hasher == nil || deps.Consents == nil || + deps.Profiles == nil || deps.Questionnaires == nil || deps.Privacy == nil || deps.Attempts == nil || + deps.Bank == nil || deps.Attestor == nil || deps.Clock == nil { + return nil, errors.New("demoseed.NewSeeder - every dependency must be set") + } + return &Seeder{deps: deps}, nil +} + +// Input is a validated seed request. Password is the shared password of the +// synthetic accounts; it is set only when an account is created. +type Input struct { + Actor domain.AssessmentOperator + Password domain.Password +} + +// Report lists what one run created and what it found. It holds addresses +// of synthetic accounts and identifiers only. +type Report struct { + PolicyVersion int32 + Created []string + Present []string + Logins []Login + PreparedAttempts []PreparedAttempt +} + +// Login is one synthetic account the operator hands out. +type Login struct { + Email string + Role string +} + +// PreparedAttempt identifies one prepared full attempt. +type PreparedAttempt struct { + Email string + AttemptID domain.AssessmentAttemptID +} + +func (report *Report) record(created bool, item string) { + if created { + report.Created = append(report.Created, item) + return + } + report.Present = append(report.Present, item) +} + +// Seed builds the demo world or finds it complete. +func (seeder *Seeder) Seed(ctx context.Context, input Input) (Report, error) { + const location = "Seeder.Seed" + if _, err := domain.ParseAssessmentOperator(string(input.Actor)); err != nil { + return Report{}, fmt.Errorf("%s - validate actor: %w", location, err) + } + census, err := seeder.deps.Store.CountAccounts(ctx, SyntheticDomain) + if err != nil { + return Report{}, fmt.Errorf("%s - count accounts: %w", location, err) + } + if census.Synthetic == 0 && census.Ordinary() > 0 { + return Report{}, fmt.Errorf("%s - check the stand: %w", location, ErrStandNotFresh) + } + var report Report + productPolicy, err := seeder.ensurePolicy(ctx, input.Actor, &report) + if err != nil { + return Report{}, err + } + report.PolicyVersion = productPolicy.Version() + if err := seeder.ensureFullBank(ctx, input.Actor, productPolicy, &report); err != nil { + return Report{}, err + } + if err := seeder.ensureTrainingBank(ctx, input.Actor, productPolicy, &report); err != nil { + return Report{}, err + } + users, err := seeder.ensureAccounts(ctx, input.Password, &report) + if err != nil { + return Report{}, err + } + for _, spec := range organizations() { + if err := seeder.ensureOrganization(ctx, spec, users, &report); err != nil { + return Report{}, err + } + } + if err := seeder.ensureCandidates(ctx, users, &report); err != nil { + return Report{}, err + } + return report, nil +} + +// ensureAccounts creates or finds every synthetic account, keyed by its +// local part. +func (seeder *Seeder) ensureAccounts(ctx context.Context, password domain.Password, report *Report) (map[string]domain.User, error) { + users := make(map[string]domain.User) + for _, spec := range accounts() { + user, err := seeder.ensureAccount(ctx, spec, password, report) + if err != nil { + return nil, err + } + users[spec.local] = user + report.Logins = append(report.Logins, Login{Email: spec.email(), Role: roleLabel(spec.role)}) + } + return users, nil +} + +// ensureCandidates completes every candidate account. +func (seeder *Seeder) ensureCandidates(ctx context.Context, users map[string]domain.User, report *Report) error { + for _, spec := range accounts() { + if spec.role == roleEmployer { + continue + } + attemptID, err := seeder.ensureCandidate(ctx, spec, users[spec.local], report) + if err != nil { + return err + } + if !attemptID.IsZero() { + report.PreparedAttempts = append(report.PreparedAttempts, PreparedAttempt{Email: spec.email(), AttemptID: attemptID}) + } + } + return nil +} + +func roleLabel(role accountRole) string { + switch role { + case roleEmployer: + return "employer" + case rolePrepared: + return "candidate with a prepared full attempt" + case roleSelfService: + return "candidate for the express and the full test" + } + return "account" +} + +// ensurePolicy publishes the seed policy over the initial demo version or +// finds it already published. It refuses any other latest version, so an +// operator-owned policy is never replaced. +func (seeder *Seeder) ensurePolicy(ctx context.Context, actor domain.AssessmentOperator, report *Report) (domain.PolicyVersion, error) { + const location = "Seeder.ensurePolicy" + initial, err := demoDraft(domain.DemoProductPolicyV1(), domain.DemoPolicySeedAuthor) + if err != nil { + return domain.PolicyVersion{}, fmt.Errorf("%s - build initial draft: %w", location, err) + } + author, err := domain.ParsePolicyAuthor(string(actor)) + if err != nil { + return domain.PolicyVersion{}, fmt.Errorf("%s - validate author: %w", location, err) + } + target, err := demoDraft(seedPolicy(), author) + if err != nil { + return domain.PolicyVersion{}, fmt.Errorf("%s - build seed draft: %w", location, err) + } + var version domain.PolicyVersion + created := false + err = seeder.deps.Transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + latest, err := unit.Policies().GetLatest(ctx, domain.ProductPolicyKey) + if err != nil { + return fmt.Errorf("read latest product policy: %w", err) + } + now, err := unit.AssessmentBank().DatabaseTime(ctx) + if err != nil { + return fmt.Errorf("read database time: %w", err) + } + effective, err := unit.Policies().GetEffective(ctx, domain.ProductPolicyKey, now) + if err != nil { + return fmt.Errorf("read effective product policy: %w", err) + } + if effective.ID() != latest.ID() || latest.Kind() != domain.PolicyKindDemo { + return ErrForeignPolicy + } + if latest.DocumentHash() == target.DocumentHash() { + version = latest + return nil + } + if latest.Version() != 1 || latest.DocumentHash() != initial.DocumentHash() { + return ErrForeignPolicy + } + version, err = policy.NewPublisher(unit.Policies(), func() time.Time { return now }).Publish(ctx, policy.PublishInput{ + Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: author, Policy: seedPolicy(), + }) + if err != nil { + return fmt.Errorf("publish seed policy: %w", err) + } + created = true + return nil + }) + if err != nil { + if errors.Is(err, outbound.ErrPolicyVersionNotFound) { + return domain.PolicyVersion{}, fmt.Errorf("%s - the stand has no product policy yet: %w", location, err) + } + return domain.PolicyVersion{}, fmt.Errorf("%s - transaction: %w", location, err) + } + report.record(created, fmt.Sprintf("product policy version %d", version.Version())) + return version, nil +} + +func demoDraft(product domain.ProductPolicy, author domain.PolicyAuthor) (domain.PolicyVersionDraft, error) { + return domain.NewPolicyVersionDraft(domain.NewPolicyVersionDraftInput{ + Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: author, Policy: product, + }) +} + +// ensureFullBank imports and publishes the families of the full category, +// opens it under the seed policy with its catalog mapping, and attests the +// opening as a source of synthetic demonstration categories. +func (seeder *Seeder) ensureFullBank( + ctx context.Context, + actor domain.AssessmentOperator, + productPolicy domain.PolicyVersion, + report *Report, +) error { + const location = "Seeder.ensureFullBank" + required, err := domain.RequiredPublishedAssessmentFamilies(productPolicy.Policy()) + if err != nil { + return fmt.Errorf("%s - read family requirement: %w", location, err) + } + bundle, err := syntheticBundle(fullBundleName, string(FullCategory), fullFamilyStem, int(required)) + if err != nil { + return fmt.Errorf("%s - build bundle: %w", location, err) + } + if err := seeder.publishBundle(ctx, bundle, actor, report); err != nil { + return fmt.Errorf("%s - %w", location, err) + } + opening, err := seeder.deps.Bank.CategoryAvailability(ctx, FullCategory) + if err != nil || opening.PolicyVersionID != productPolicy.ID() { + metadata, err := domain.NewAssessmentCategoryCatalogMetadata( + fullSpecialization, fullGrade, []domain.TaskLanguageCode{fullTaskLanguage}, + ) + if err != nil { + return fmt.Errorf("%s - build catalog mapping: %w", location, err) + } + if _, err := seeder.deps.Bank.OpenCategory(ctx, assessment.OpenCategoryInput{ + Category: FullCategory, GradingPolicyID: productPolicy.ID(), OpenedBy: actor, CatalogMetadata: &metadata, + }); err != nil { + return fmt.Errorf("%s - open category: %w", location, err) + } + report.record(true, "opening of category "+string(FullCategory)) + } else { + report.record(false, "opening of category "+string(FullCategory)) + } + language := fullTaskLanguage + attestation, err := seeder.deps.Attestor.Attest(ctx, fullSpecialization, fullGrade, &language, string(actor)) + if err != nil { + return fmt.Errorf("%s - attest category: %w", location, err) + } + report.record(attestation.Created, "synthetic demonstration attestation of "+string(FullCategory)) + return nil +} + +// ensureTrainingBank publishes the express families and binds them to the +// seed policy. The training category never gets a real opening. +func (seeder *Seeder) ensureTrainingBank( + ctx context.Context, + actor domain.AssessmentOperator, + productPolicy domain.PolicyVersion, + report *Report, +) error { + const location = "Seeder.ensureTrainingBank" + training := productPolicy.Policy().Assessment.Training + if training == nil { + return fmt.Errorf("%s - the seed policy has no express training mode", location) + } + bundle, err := syntheticBundle(trainingBundleName, TrainingCategory, trainingFamilyStem, int(training.DemoExpressItemCount)) + if err != nil { + return fmt.Errorf("%s - build bundle: %w", location, err) + } + if err := seeder.publishBundle(ctx, bundle, actor, report); err != nil { + return fmt.Errorf("%s - %w", location, err) + } + exists, err := seeder.deps.Store.TrainingBindingExists(ctx, TrainingCategory, productPolicy.ID()) + if err != nil { + return fmt.Errorf("%s - read binding: %w", location, err) + } + if !exists { + if err := seeder.deps.Store.BindTrainingBank(ctx, outbound.DemoTrainingBinding{ + Category: TrainingCategory, PolicyVersionID: productPolicy.ID(), + ItemCount: int(training.DemoExpressItemCount), ReviewedBy: actor, + }); err != nil { + return fmt.Errorf("%s - bind training bank: %w", location, err) + } + } + report.record(!exists, "express training binding of "+TrainingCategory) + return nil +} + +// publishBundle imports the bundle, which leaves stored versions unchanged, +// and publishes every family that has no published version yet. +func (seeder *Seeder) publishBundle(ctx context.Context, bundle assessment.Bundle, actor domain.AssessmentOperator, report *Report) error { + if _, err := seeder.deps.Bank.ImportBundle(ctx, bundle); err != nil { + return fmt.Errorf("import bundle %s: %w", bundle.Name, err) + } + published := 0 + for _, family := range bundle.Families { + key := domain.AssessmentFamilyKey(family.Key) + if _, err := seeder.deps.Bank.ActiveFamily(ctx, key); err == nil { + continue + } else if !errors.Is(err, outbound.ErrAssessmentFamilyNotFound) { + return fmt.Errorf("read family %s: %w", family.Key, err) + } + if _, err := seeder.deps.Bank.PublishFamily(ctx, key, family.Version, actor); err != nil { + return fmt.Errorf("publish family %s: %w", family.Key, err) + } + published++ + } + report.record(published > 0, fmt.Sprintf("%d published families of %s", len(bundle.Families), bundle.Category)) + return nil +} + +// ensureAccount creates a confirmed synthetic account with the C1 grant of a +// registration, or finds it. The address is on the reserved domain, so no +// mail is sent and ordinary registration keeps its email check. +func (seeder *Seeder) ensureAccount(ctx context.Context, spec accountSpec, password domain.Password, report *Report) (domain.User, error) { + const location = "Seeder.ensureAccount" + email, err := domain.NewEmailAddress(spec.email()) + if err != nil { + return domain.User{}, fmt.Errorf("%s - build address: %w", location, err) + } + existing, found, err := seeder.readAccount(ctx, email) + if err != nil { + return domain.User{}, fmt.Errorf("%s - read account: %w", location, err) + } + if found { + if !existing.EmailVerified() || existing.Scenario != spec.scenario() { + return domain.User{}, fmt.Errorf("%s - %s: %w", location, spec.email(), ErrAccountConflict) + } + report.record(false, "account "+spec.email()) + return existing, nil + } + if password.IsZero() { + return domain.User{}, fmt.Errorf("%s - a password is required to create %s", location, spec.email()) + } + passwordHash, err := seeder.deps.Hasher.Hash(ctx, password) + if err != nil { + return domain.User{}, fmt.Errorf("%s - hash password: %w", location, err) + } + now := seeder.now() + user, err := domain.NewUser(domain.Registration{ + Email: email, PasswordHash: passwordHash, Scenario: spec.scenario(), RegisteredAt: now, + }) + if err != nil { + return domain.User{}, fmt.Errorf("%s - build account: %w", location, err) + } + var verified domain.User + err = seeder.deps.Transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := unit.Users().Create(ctx, user); err != nil { + return fmt.Errorf("create account: %w", err) + } + text, err := unit.ConsentTexts().Current(ctx, domain.ConsentPurposePersonalData, now) + if err != nil { + return fmt.Errorf("read C1 text: %w", err) + } + if _, err := seeder.deps.Consents.GrantAtRegistration(ctx, unit, user.ID, user.RegistrationVersion, text.Version()); err != nil { + return fmt.Errorf("grant C1: %w", err) + } + verified, err = unit.Users().MarkEmailVerified(ctx, user.ID, user.RegistrationVersion, now) + if err != nil { + return fmt.Errorf("confirm address: %w", err) + } + return nil + }) + if err != nil { + if errors.Is(err, outbound.ErrEmailTaken) { + return domain.User{}, fmt.Errorf("%s - %s: %w", location, spec.email(), ErrAccountConflict) + } + return domain.User{}, fmt.Errorf("%s - transaction: %w", location, err) + } + report.record(true, "account "+spec.email()) + return verified, nil +} + +func (seeder *Seeder) readAccount(ctx context.Context, email domain.EmailAddress) (domain.User, bool, error) { + var user domain.User + found := false + err := seeder.deps.Transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + stored, err := unit.Users().GetByEmail(ctx, email) + if errors.Is(err, outbound.ErrUserNotFound) { + return nil + } + if err != nil { + return err + } + user, found = stored, true + return nil + }) + return user, found, err +} + +// ensureOrganization finds the organization by name among the organizations +// its owner owns, or creates it with the owner, and adds the second member. +func (seeder *Seeder) ensureOrganization( + ctx context.Context, + spec organizationSpec, + users map[string]domain.User, + report *Report, +) error { + const location = "Seeder.ensureOrganization" + owner := users[spec.ownerLocal] + organizationID, found, err := seeder.findOwnedOrganization(ctx, owner.ID, spec.name) + if err != nil { + return fmt.Errorf("%s - list organizations: %w", location, err) + } + if !found { + organizationID, err = seeder.createOrganization(ctx, spec, owner.ID) + if err != nil { + return fmt.Errorf("%s - %w", location, err) + } + } + report.record(!found, "organization "+spec.name) + if spec.memberLocal == "" { + return nil + } + member := users[spec.memberLocal] + created, err := seeder.ensureMembership(ctx, organizationID, member.ID, spec.memberRole) + if err != nil { + return fmt.Errorf("%s - %w", location, err) + } + report.record(created, fmt.Sprintf("%s membership of %s in %s", spec.memberRole, spec.memberLocal+"@"+SyntheticDomain, spec.name)) + return nil +} + +func (seeder *Seeder) findOwnedOrganization(ctx context.Context, ownerID uuid.UUID, name string) (uuid.UUID, bool, error) { + var organizationID uuid.UUID + found := false + err := seeder.deps.Transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + var after *outbound.OrganizationListPosition + for { + page, err := unit.Organizations().ListForUser(ctx, outbound.OrganizationListQuery{ + UserID: ownerID, After: after, Limit: outbound.MaxOrganizationPageSize, + }) + if err != nil { + return err + } + for _, item := range page.Items { + if item.Organization.Name() == name && item.Membership.Role() == domain.OrganizationRoleOwner { + organizationID, found = item.Organization.ID(), true + return nil + } + } + if !page.HasMore || len(page.Items) == 0 { + return nil + } + position := outbound.OrganizationPositionOf(page.Items[len(page.Items)-1]) + after = &position + } + }) + return organizationID, found, err +} + +func (seeder *Seeder) createOrganization(ctx context.Context, spec organizationSpec, ownerID uuid.UUID) (uuid.UUID, error) { + profileValue, err := domain.NewOrganizationProfile(domain.OrganizationProfileInput{ + Name: spec.name, Description: spec.description, Sphere: spec.sphere, + }) + if err != nil { + return uuid.Nil, fmt.Errorf("build organization profile: %w", err) + } + now := seeder.now() + organization, err := domain.NewOrganization(profileValue, now) + if err != nil { + return uuid.Nil, fmt.Errorf("build organization: %w", err) + } + ownerMembership, err := domain.NewOwnerMembership(organization.ID(), ownerID, now) + if err != nil { + return uuid.Nil, fmt.Errorf("build owner membership: %w", err) + } + err = seeder.deps.Transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + return unit.Organizations().CreateWithOwner(ctx, organization, ownerMembership) + }) + if err != nil { + return uuid.Nil, fmt.Errorf("create organization: %w", err) + } + return organization.ID(), nil +} + +func (seeder *Seeder) ensureMembership(ctx context.Context, organizationID, userID uuid.UUID, role domain.OrganizationRole) (bool, error) { + created := false + err := seeder.deps.Transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + existing, err := unit.Memberships().Get(ctx, organizationID, userID) + if err == nil { + if existing.Role() != role { + return fmt.Errorf("membership has role %s, want %s: %w", existing.Role(), role, ErrAccountConflict) + } + return nil + } + if !errors.Is(err, outbound.ErrMembershipNotFound) { + return fmt.Errorf("read membership: %w", err) + } + membership, err := domain.NewMembership(domain.MembershipInput{ + OrganizationID: organizationID, UserID: userID, Role: role, At: seeder.now(), + }) + if err != nil { + return fmt.Errorf("build membership: %w", err) + } + if err := unit.Memberships().Insert(ctx, membership); err != nil { + return fmt.Errorf("insert membership: %w", err) + } + created = true + return nil + }) + return created, err +} + +// ensureCandidate gives a candidate its consents, manual profile, and +// questionnaire; a prepared candidate also gets the prepared full attempt and +// a published card. It returns the prepared attempt, or a zero ID. +func (seeder *Seeder) ensureCandidate( + ctx context.Context, + spec accountSpec, + user domain.User, + report *Report, +) (domain.AssessmentAttemptID, error) { + const location = "Seeder.ensureCandidate" + purposes := []domain.ConsentPurpose{domain.ConsentPurposeAutoCategorization} + if spec.role == rolePrepared { + purposes = append(purposes, domain.ConsentPurposePublication) + } + for _, purpose := range purposes { + if err := seeder.grantConsent(ctx, user.ID, purpose); err != nil { + return domain.AssessmentAttemptID{}, fmt.Errorf("%s - %s: %w", location, purpose, err) + } + } + created, err := seeder.ensureProfile(ctx, spec, user.ID) + if err != nil { + return domain.AssessmentAttemptID{}, fmt.Errorf("%s - %w", location, err) + } + report.record(created, "profile of "+spec.email()) + created, err = seeder.ensureQuestionnaire(ctx, user.ID) + if err != nil { + return domain.AssessmentAttemptID{}, fmt.Errorf("%s - %w", location, err) + } + report.record(created, "questionnaire of "+spec.email()) + if spec.role != rolePrepared { + return domain.AssessmentAttemptID{}, nil + } + attemptID, created, err := seeder.ensurePreparedAttempt(ctx, user.ID) + if err != nil { + return domain.AssessmentAttemptID{}, fmt.Errorf("%s - %s: %w", location, spec.email(), err) + } + report.record(created, "prepared full attempt of "+spec.email()) + created, err = seeder.ensurePublication(ctx, user.ID) + if err != nil { + return domain.AssessmentAttemptID{}, fmt.Errorf("%s - %w", location, err) + } + report.record(created, "published card of "+spec.email()) + return attemptID, nil +} + +// grantConsent grants the current text of the purpose; a repeat of the same +// version is idempotent in the ledger. +func (seeder *Seeder) grantConsent(ctx context.Context, subjectID uuid.UUID, purpose domain.ConsentPurpose) error { + var version domain.ConsentTextVersion + err := seeder.deps.Transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + text, err := unit.ConsentTexts().Current(ctx, purpose, seeder.now()) + if err != nil { + return err + } + version = text.Version() + return nil + }) + if err != nil { + return fmt.Errorf("read current text: %w", err) + } + if _, err := seeder.deps.Consents.GrantInSettingsInNewTransaction(ctx, consent.SettingsGrantInput{ + SubjectID: subjectID, Purpose: purpose, TextVersion: version, + }); err != nil { + return fmt.Errorf("grant: %w", err) + } + return nil +} + +// ensureProfile saves the manual profile once. A profile that exists is left +// as it is, also when a visitor edited it; a reset restores it. +func (seeder *Seeder) ensureProfile(ctx context.Context, spec accountSpec, userID uuid.UUID) (bool, error) { + current, err := seeder.deps.Profiles.GetMyProfile(ctx, userID) + if err != nil { + return false, fmt.Errorf("read profile: %w", err) + } + if current.Version() > 0 { + return false, nil + } + if _, err := seeder.deps.Profiles.SaveMyProfile(ctx, userID, current.Version(), profileInput(spec)); err != nil { + return false, fmt.Errorf("save profile: %w", err) + } + return true, nil +} + +// ensureQuestionnaire saves the questionnaire once, after the bank is open, +// because the questionnaire accepts only available task languages. +func (seeder *Seeder) ensureQuestionnaire(ctx context.Context, userID uuid.UUID) (bool, error) { + current, err := seeder.deps.Questionnaires.GetMyQuestionnaire(ctx, userID) + if err != nil { + return false, fmt.Errorf("read questionnaire: %w", err) + } + if current.Version() > 0 { + return false, nil + } + if _, err := seeder.deps.Questionnaires.SaveMyQuestionnaire(ctx, userID, current.Version(), questionnaireInput()); err != nil { + return false, fmt.Errorf("save questionnaire: %w", err) + } + return true, nil +} + +// ensurePublication publishes the card once with the cohort fields. +func (seeder *Seeder) ensurePublication(ctx context.Context, userID uuid.UUID) (bool, error) { + settings, err := seeder.deps.Privacy.GetMyPrivacySettings(ctx, userID) + if err != nil { + return false, fmt.Errorf("read privacy settings: %w", err) + } + if settings.Publication.Version() > 0 { + return false, nil + } + if _, err := seeder.deps.Privacy.SetMyPublication( + ctx, userID, settings.Publication.Version(), domain.PublicationPublished, publishedFields(), + ); err != nil { + return false, fmt.Errorf("publish card: %w", err) + } + return true, nil +} + +func (seeder *Seeder) now() time.Time { + return seeder.deps.Clock().UTC().Truncate(time.Microsecond) +} diff --git a/backend/internal/usecase/demoseed/seeder_test.go b/backend/internal/usecase/demoseed/seeder_test.go new file mode 100644 index 0000000..83b3d64 --- /dev/null +++ b/backend/internal/usecase/demoseed/seeder_test.go @@ -0,0 +1,107 @@ +package demoseed + +import ( + "strings" + "testing" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +func TestDecideResetAllowsOnlyEmptyOrSyntheticStands(t *testing.T) { + for _, test := range []struct { + census outbound.DemoAccountCensus + want ResetVerdict + }{ + {outbound.DemoAccountCensus{}, ResetAllowedEmpty}, + {outbound.DemoAccountCensus{Total: 9, Synthetic: 9}, ResetAllowedSynthetic}, + {outbound.DemoAccountCensus{Total: 10, Synthetic: 9}, ResetRefusedOrdinary}, + {outbound.DemoAccountCensus{Total: 1}, ResetRefusedOrdinary}, + } { + if got := DecideReset(test.census); got != test.want || got.Allowed() == (test.want == ResetRefusedOrdinary) { + t.Errorf("DecideReset(%+v) = %s, want %s", test.census, got, test.want) + } + } +} + +func TestSyntheticBundlesAreValidAndStable(t *testing.T) { + required, err := domain.RequiredPublishedAssessmentFamilies(seedPolicy()) + if err != nil { + t.Fatalf("RequiredPublishedAssessmentFamilies() error = %v", err) + } + full, err := syntheticBundle(fullBundleName, string(FullCategory), fullFamilyStem, int(required)) + if err != nil || len(full.Families) != int(required) { + t.Fatalf("full bundle = %d families, %v; want %d", len(full.Families), err, required) + } + again, err := syntheticBundle(fullBundleName, string(FullCategory), fullFamilyStem, int(required)) + if err != nil || again.Families[len(again.Families)-1].Key != full.Families[len(full.Families)-1].Key || + again.Review != full.Review { + t.Fatal("the bundle differs between two builds, so a repeated import would conflict") + } + for _, family := range full.Families { + if family.AnswerKey.AnswerFormat != domain.AnswerFormatInteger || !strings.Contains(family.Title, "synthetic demo") { + t.Errorf("family %s has format %q and title %q", family.Key, family.AnswerKey.AnswerFormat, family.Title) + } + } + training := seedPolicy().Assessment.Training + if training == nil || seedPolicy().Assessment.Attempt == nil || seedPolicy().Assessment.Attempt.RealMode != domain.AssessmentRealModeDemoBasic { + t.Fatal("the seed policy lacks the express mode or the demo_basic attempt settings") + } + if _, err := syntheticBundle(trainingBundleName, TrainingCategory, trainingFamilyStem, int(training.DemoExpressItemCount)); err != nil { + t.Fatalf("training bundle error = %v", err) + } + if _, err := syntheticBundle(fullBundleName, string(FullCategory), fullFamilyStem, 0); err == nil { + t.Fatal("an empty bundle was accepted") + } +} + +func TestIntegerAnswerHasTheIntendedCorrectness(t *testing.T) { + variant := domain.AssessmentVariant{AnswerFormat: domain.AnswerFormatInteger, ReferenceAnswer: "7"} + for _, correct := range []bool{true, false} { + answer, err := integerAnswer(variant, correct) + if err != nil { + t.Fatalf("integerAnswer(%v) error = %v", correct, err) + } + _, matches, err := domain.CanonicalAssessmentAnswerForVariant(answer, variant) + if err != nil || matches != correct { + t.Errorf("integerAnswer(%v) = %s, matches %v, %v", correct, answer, matches, err) + } + } + for _, variant := range []domain.AssessmentVariant{ + {AnswerFormat: domain.AnswerFormatIntegerSequence, ReferenceAnswer: "1 2"}, + {AnswerFormat: domain.AnswerFormatInteger, ReferenceAnswer: "seven"}, + } { + if _, err := integerAnswer(variant, true); err == nil { + t.Errorf("integerAnswer(%+v) answered an unsupported variant", variant) + } + } +} + +func TestDatasetHasTwoRolesOnTheSyntheticDomainAndACohortOfAtLeastFive(t *testing.T) { + prepared, employers, selfService := 0, 0, 0 + seen := map[string]bool{} + for _, spec := range accounts() { + if seen[spec.email()] || !strings.HasSuffix(spec.email(), "@"+SyntheticDomain) { + t.Fatalf("account %s is repeated or outside the synthetic domain", spec.email()) + } + seen[spec.email()] = true + switch spec.role { + case roleEmployer: + employers++ + case rolePrepared: + prepared++ + case roleSelfService: + selfService++ + } + if spec.role != roleEmployer && !strings.Contains(spec.fullName, "синтетический профиль") { + t.Errorf("candidate %s has no synthetic marker in the name", spec.email()) + } + } + if employers != 2 || selfService != 1 || prepared < 5 { + t.Fatalf("dataset has %d employers, %d self-service and %d prepared candidates", employers, selfService, prepared) + } + specs := organizations() + if len(specs) != 2 || specs[0].ownerLocal == specs[1].ownerLocal || specs[1].memberRole.CanManageOrganization() { + t.Fatal("the organizations do not show two owners and a non-managing second role") + } +} diff --git a/deploy/.gitignore b/deploy/.gitignore index a2406ca..e299b99 100644 --- a/deploy/.gitignore +++ b/deploy/.gitignore @@ -1 +1,2 @@ /release/ +/demo/demo.env diff --git a/deploy/Makefile b/deploy/Makefile index 054b204..f835f5a 100644 --- a/deploy/Makefile +++ b/deploy/Makefile @@ -17,6 +17,7 @@ ML_FILE := $(ROOT)/deploy/docker/docker-compose.ml.yml MONITORING_FILE := $(ROOT)/deploy/docker/docker-compose.monitoring.yml E2E_FILE := $(ROOT)/deploy/docker/docker-compose.e2e.yml E2E_MAIL_FILE := $(ROOT)/deploy/docker/docker-compose.e2e-mail.yml +DEMO_FILE := $(ROOT)/deploy/docker/docker-compose.demo.yml RELEASE_FILE := $(ROOT)/deploy/docker/docker-compose.release.yml ML_RELEASE_FILE := $(ROOT)/deploy/docker/docker-compose.ml.release.yml RELEASE_SCRIPT := $(ROOT)/deploy/scripts/release_manifest.py @@ -36,9 +37,23 @@ RELEASE_MANIFEST_ARG = $(if $(strip $(RELEASE_MANIFEST)),--manifest "$(RELEASE_M # Recursive on purpose: git is asked only by the targets that use the tag. The # project-specific name keeps a generic RELEASE_TAG from enabling release mode. LINCODEX_RELEASE_TAG ?= $(shell PYTHONDONTWRITEBYTECODE=1 python3 "$(RELEASE_SCRIPT)" tag) +# Isolated demonstration stand (deploy/scripts/demo.sh). Every demo target +# needs DEMO_MODE=isolated on the command line and acts only on DEMO_PROJECT. +DEMO_MODE ?= +DEMO_PROJECT ?= lincodex-demo +DEMO_HTTP_PORT ?= 8090 +DEMO_PUBLIC_URL ?= http://localhost:$(DEMO_HTTP_PORT) +DEMO_SUBNET ?= 172.29.84.0/24 +DEMO_FRONTEND_IP ?= 172.29.84.10 +DEMO_ACTOR ?= operator:demo-seed +# demo.env is local; the checked-in example is used when it does not exist. +DEMO_ENV ?= $(if $(wildcard $(ROOT)/deploy/demo/demo.env),$(ROOT)/deploy/demo/demo.env,$(ROOT)/deploy/demo/demo.env.example) +DEMO_SCRIPT_ENV = DOCKER="$(DOCKER)" DEMO_MODE="$(DEMO_MODE)" DEMO_PROJECT="$(DEMO_PROJECT)" APP_PROJECT="$(APP_PROJECT)" \ + ENV_FILE="$(ENV_FILE)" DEMO_ENV_FILE="$(DEMO_ENV)" DEMO_HTTP_PORT="$(DEMO_HTTP_PORT)" DEMO_PUBLIC_URL="$(DEMO_PUBLIC_URL)" \ + DEMO_SUBNET="$(DEMO_SUBNET)" DEMO_FRONTEND_IP="$(DEMO_FRONTEND_IP)" DEMO_ACTOR="$(DEMO_ACTOR)" PLAYWRIGHT_VERSION := $(shell sed -n 's/^ *"@playwright\/test": "\([^"]*\)",\{0,1\}$$/\1/p' "$(ROOT)/frontend/package.json") -.PHONY: help config build up down logs monitoring-config monitoring-up monitoring-down monitoring-logs ml-config ml-build ml-up ml-down ml-logs check check-workflows check-release check-perimeter check-e2e-mail perimeter-test smoke test-e2e test-e2e-registration release-build release-smoke release-e2e release-manifest release-manifest-verify release-manifest-check release-up release-down release-clean +.PHONY: help config build up down logs monitoring-config monitoring-up monitoring-down monitoring-logs ml-config ml-build ml-up ml-down ml-logs check check-workflows check-release check-perimeter check-e2e-mail check-demo perimeter-test smoke test-e2e test-e2e-registration release-build release-smoke release-e2e release-manifest release-manifest-verify release-manifest-check release-up release-down release-clean demo-seed demo-reset demo-down help: ## Show deployment commands @awk 'BEGIN {FS = ":.*## "} /^[a-zA-Z0-9_-]+:.*## / {printf "%-24s %s\n", $$1, $$2}' $(MAKEFILE_LIST) @@ -53,6 +68,7 @@ config: ## Render all Compose files with safe example values APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" LINCODEX_RELEASE_TAG=000000000000 IDENTITY_KEY_SECRET="$(CHECK_IDENTITY_KEY_SECRET)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p "$(APP_PROJECT)" -f "$(CORE_FILE)" -f "$(RELEASE_FILE)" config --quiet APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" LINCODEX_RELEASE_TAG=000000000000 IDENTITY_KEY_SECRET="$(CHECK_IDENTITY_KEY_SECRET)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p "$(ML_PROJECT)" -f "$(ML_FILE)" -f "$(ML_RELEASE_FILE)" config --quiet APP_PROJECT=lincodex-e2e-config APP_NETWORK=lincodex-e2e-config_default PLAYWRIGHT_VERSION="$(PLAYWRIGHT_VERSION)" E2E_UID=1000 E2E_GID=1000 E2E_SPEC_DIR="$(ROOT)/frontend/e2e" E2E_ARTIFACTS_DIR="$(ROOT)/frontend/test-results/e2e" IDENTITY_KEY_SECRET="$(CHECK_IDENTITY_KEY_SECRET)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p lincodex-e2e-config -f "$(CORE_FILE)" -f "$(E2E_FILE)" --profile e2e config --quiet + APP_PROJECT=lincodex-demo-config APP_NETWORK=lincodex-demo-config_default DEMO_ACCOUNT_PASSWORD=render-only-demo-account-password IDENTITY_KEY_SECRET="$(CHECK_IDENTITY_KEY_SECRET)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p lincodex-demo-config -f "$(CORE_FILE)" -f "$(DEMO_FILE)" --profile demo-seed config --quiet E2E_COMPANY_FIXTURE_TOKEN=render-only-company-fixture-token-00000000000000000000000000000000 APP_PROJECT=lincodex-e2e-mail-config APP_NETWORK=lincodex-e2e-mail-config_default PLAYWRIGHT_VERSION="$(PLAYWRIGHT_VERSION)" E2E_UID=1000 E2E_GID=1000 E2E_SPEC_DIR="$(ROOT)/frontend/e2e" E2E_ARTIFACTS_DIR="$(ROOT)/frontend/test-results/e2e" IDENTITY_KEY_SECRET="$(CHECK_IDENTITY_KEY_SECRET)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p lincodex-e2e-mail-config -f "$(CORE_FILE)" -f "$(E2E_FILE)" -f "$(E2E_MAIL_FILE)" --profile e2e config --quiet build: ## Build local frontend and backend images @@ -116,7 +132,7 @@ edge-render: ## Render the edge nginx config from deploy/edge/edge.env into depl edge-config: ## Render the edge templates and check the nginx config with nginx -t in a container @DOCKER="$(DOCKER)" EDGE_NGINX_IMAGE="$(EDGE_NGINX_IMAGE)" bash "$(EDGE_DIR)/scripts/check.sh" "$(EDGE_ENV)" -check: config check-workflows check-release check-perimeter check-e2e-mail ## Validate Compose files, CI workflow aggregates, release tooling, and network boundaries without starting services +check: config check-workflows check-release check-perimeter check-e2e-mail check-demo ## Validate Compose files, CI workflow aggregates, release tooling, and network boundaries without starting services check-workflows: ## Check that each workflow aggregate job requires every other job PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s "$(ROOT)/scripts" -p 'test_workflow_aggregate.py' @@ -130,6 +146,9 @@ check-perimeter: ## Check published ports, the app Nginx paths, limits, and the check-e2e-mail: ## Check that the mail fixture stays inside the explicit local E2E network PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s "$(ROOT)/deploy/scripts" -p 'test_e2e_mail.py' +check-demo: ## Check the guards of the demo targets and the demo overlay without starting services + PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s "$(ROOT)/deploy/scripts" -p 'test_demo.py' + perimeter-test: ## Start throwaway Nginx containers and test denied paths, limits, headers, and forwarded headers over HTTP LINCODEX_PERIMETER_LIVE=1 DOCKER="$(DOCKER)" PERIMETER_NGINX_IMAGE="$(EDGE_NGINX_IMAGE)" PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -v -s "$(ROOT)/deploy/scripts" -p 'test_perimeter.py' @@ -170,3 +189,12 @@ release-down: ## Stop the release project selected by the immutable manifest and release-clean: ## Remove local release image references not retained by an immutable manifest @$(RELEASE) clean-images + +demo-seed: ## Start the isolated demo stand when needed and seed its synthetic data (needs DEMO_MODE=isolated) + @$(DEMO_SCRIPT_ENV) bash scripts/demo.sh seed + +demo-reset: ## Discard only the isolated demo project when it holds no ordinary account, then seed it again (needs DEMO_MODE=isolated) + @$(DEMO_SCRIPT_ENV) bash scripts/demo.sh reset + +demo-down: ## Stop the isolated demo stand and keep its volumes (needs DEMO_MODE=isolated) + @$(DEMO_SCRIPT_ENV) bash scripts/demo.sh down diff --git a/deploy/README.en.md b/deploy/README.en.md index 014764c..d5e0b00 100644 --- a/deploy/README.en.md +++ b/deploy/README.en.md @@ -9,6 +9,7 @@ Configuration for running the application with Docker Compose and Nginx. - `nginx/` configures frontend serving and API proxying. - `docker/docker-compose.e2e.yml` is an overlay used only by the browser suite: it removes the frontend host port and adds the Playwright runner. - `docker/docker-compose.release.yml` and `docker/docker-compose.ml.release.yml` are overlays that name the release images `lincodex.invalid/:` and never pull them from a registry. +- `docker/docker-compose.demo.yml` and `demo/` belong to the isolated demo stand with synthetic data: `make -C deploy demo-seed DEMO_MODE=isolated` starts and seeds it, `demo-reset` rebuilds it only when it holds no ordinary account, and `demo-down` stops it; see the [isolated demo stand](../docs/en/DEPLOY.md#isolated-demo-stand). - `scripts/` contains the isolated stack smoke check, the browser E2E runner, and `release_manifest.py`, which builds, describes, and checks release images. - `edge/` holds the public edge proxy: nginx and tunnel templates, certbot renewal hook, systemd drop-ins, and the scripts that render and check them. `make -C deploy edge-config` renders the nginx configuration and runs `nginx -t` in a container; see the [edge proxy runbook](../docs/en/DEPLOY.md#edge-proxy-https-and-tunnel). - `make -C deploy check-perimeter` checks the published ports, denied paths, limits, and the trusted peer of Nginx from the files; `make -C deploy perimeter-test` checks the same over HTTP on throwaway Nginx containers; see [Public perimeter and client address](../docs/en/DEPLOY.md#public-perimeter-and-client-address). diff --git a/deploy/README.md b/deploy/README.md index 4cccccb..74643ac 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -9,6 +9,7 @@ - `nginx/` содержит конфигурацию раздачи frontend и проксирования API. - `docker/docker-compose.e2e.yml` - overlay только для браузерного набора: убирает host-порт frontend и добавляет запуск Playwright. - `docker/docker-compose.release.yml` и `docker/docker-compose.ml.release.yml` - overlay с именами образов выпуска `lincodex.invalid/:` без скачивания из registry. +- `docker/docker-compose.demo.yml` и `demo/` относятся к изолированному демонстрационному стенду с синтетическими данными: `make -C deploy demo-seed DEMO_MODE=isolated` запускает и заполняет его, `demo-reset` пересоздает его, только если в нем нет обычных аккаунтов, а `demo-down` останавливает; см. [изолированный демонстрационный стенд](../docs/ru/DEPLOY.md#изолированный-демонстрационный-стенд). - `scripts/` содержит smoke-проверку изолированного стека, запуск браузерных E2E и `release_manifest.py` для сборки, описания и сверки образов выпуска. - `edge/` содержит публичный edge proxy: шаблоны nginx и туннеля, hook продления certbot, drop-in systemd и скрипты, которые их отрисовывают и проверяют. `make -C deploy edge-config` отрисовывает конфигурацию nginx и выполняет `nginx -t` в контейнере; см. [runbook edge proxy](../docs/ru/DEPLOY.md#edge-proxy-https-и-туннель). - `make -C deploy check-perimeter` проверяет по файлам опубликованные порты, запрещенные пути, лимиты и доверенного пира Nginx; `make -C deploy perimeter-test` проверяет то же по HTTP на одноразовых контейнерах Nginx; см. [Публичный периметр и адрес клиента](../docs/ru/DEPLOY.md#публичный-периметр-и-адрес-клиента). diff --git a/deploy/demo/demo.env.example b/deploy/demo/demo.env.example new file mode 100644 index 0000000..66c4c57 --- /dev/null +++ b/deploy/demo/demo.env.example @@ -0,0 +1,10 @@ +# Settings of the synthetic demo accounts on an isolated demo stand. Copy this +# file to demo.env next to it to use another password; demo.env is local and +# ignored by Git. Without demo.env, make -C deploy demo-seed reads this +# example. The value is a published demo credential of synthetic accounts on +# a stand without real people, not a secret: never reuse it anywhere else. +# +# Shared password of every synthetic account the seed creates (at least 15 +# characters). It applies when an account is created; change it by editing +# demo.env and running make -C deploy demo-reset DEMO_MODE=isolated. +DEMO_ACCOUNT_PASSWORD=synthetic demo stand only 2026 diff --git a/deploy/docker/docker-compose.demo.yml b/deploy/docker/docker-compose.demo.yml new file mode 100644 index 0000000..0c11af7 --- /dev/null +++ b/deploy/docker/docker-compose.demo.yml @@ -0,0 +1,52 @@ +# Overlay of the isolated demonstration stand. Only deploy/scripts/demo.sh +# combines it with docker-compose.yml, under the dedicated demo project +# (DEMO_PROJECT, lincodex-demo by default); never apply it to the working +# stand. The demo stand holds synthetic data only. +services: + backend: + environment: + # A full test on the demo stand assigns an uncalibrated synthetic + # demonstration category, as the prepared attempts do. + ASSESSMENT_DEMO_CATEGORIES_ENABLED: "true" + labels: + org.lincodex.demo-mode: isolated + + demo-seed: + build: + context: ../../backend + dockerfile: Dockerfile.demo-seed + profiles: ["demo-seed"] + environment: + DATABASE_URL: postgres://${POSTGRES_USER:?Set POSTGRES_USER}:${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_DB:?Set POSTGRES_DB}?sslmode=disable + # The command checks the mode itself; demo.sh passes it only after its + # own guard. + DEMO_MODE: ${DEMO_MODE:-} + DEMO_ACCOUNT_PASSWORD: ${DEMO_ACCOUNT_PASSWORD:?Set DEMO_ACCOUNT_PASSWORD in the demo env file} + depends_on: + postgres: + condition: service_healthy + # The command reaches PostgreSQL only; it never joins the storage network. + networks: + - default + restart: "no" + read_only: true + cap_drop: [ALL] + security_opt: ["no-new-privileges:true"] + deploy: + resources: + limits: + cpus: "1.0" + memory: 256M + +# The label is set when a volume is created, so only volumes that this +# overlay created carry it; demo.sh refuses to discard a volume without it. +volumes: + postgres_data: + labels: + org.lincodex.demo-mode: isolated + seaweedfs_data: + labels: + org.lincodex.demo-mode: isolated + kafka_data: + labels: + org.lincodex.demo-mode: isolated diff --git a/deploy/scripts/demo.sh b/deploy/scripts/demo.sh new file mode 100644 index 0000000..b7e1111 --- /dev/null +++ b/deploy/scripts/demo.sh @@ -0,0 +1,148 @@ +#!/usr/bin/env bash +# Operator actions of the isolated demonstration stand. +# +# The stand is a dedicated Compose project (DEMO_PROJECT, lincodex-demo by +# default) of docker-compose.yml with docker-compose.demo.yml. Every action +# requires DEMO_MODE=isolated and addresses only that project; the ordinary +# project (APP_PROJECT) and its volumes are never touched. +# +# Usage: demo.sh seed|reset|down +# seed start the demo project when needed, run the idempotent seed, and +# print the inventory of its records +# reset check that the demo database holds no account outside the +# synthetic domain, discard the demo project with its volumes, +# start it again, and seed +# down stop the demo project and keep its volumes +# +# Environment (deploy/Makefile sets it): +# DEMO_MODE must be "isolated" +# DEMO_PROJECT Compose project of the demo stand; contains "demo" and +# differs from APP_PROJECT +# APP_PROJECT the ordinary project, only compared against +# ENV_FILE root env file with the stand secrets +# DEMO_ENV_FILE demo env file with DEMO_ACCOUNT_PASSWORD +# DEMO_HTTP_PORT host port of the demo frontend +# DEMO_PUBLIC_URL public origin of the demo stand +# DEMO_SUBNET, DEMO_FRONTEND_IP pinned network of the demo project +# DEMO_ACTOR operator: that the seed records +# DOCKER docker CLI +set -euo pipefail + +root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) +compose_file="$root/deploy/docker/docker-compose.yml" +demo_file="$root/deploy/docker/docker-compose.demo.yml" +docker_cli="${DOCKER:-docker}" +demo_label='org.lincodex.demo-mode' +ready_attempts=120 + +fail() { + printf 'demo: %s\n' "$1" >&2 + exit 2 +} + +if [[ "$#" -ne 1 ]]; then + fail 'usage: demo.sh seed|reset|down' +fi +action=$1 +case "$action" in + seed | reset | down) ;; + *) fail 'usage: demo.sh seed|reset|down' ;; +esac + +# The guards run before any Docker command. +if [[ "${DEMO_MODE:-}" != isolated ]]; then + fail "refusing to $action: set DEMO_MODE=isolated; the demo targets act only on an isolated demo stand" +fi +project="${DEMO_PROJECT:-lincodex-demo}" +ordinary_project="${APP_PROJECT:-app}" +if [[ ! "$project" =~ ^[a-z0-9][a-z0-9_-]*$ || "$project" != *demo* ]]; then + fail "refusing to $action: DEMO_PROJECT must be a Compose project name that contains 'demo'" +fi +if [[ "$project" == "$ordinary_project" ]]; then + fail "refusing to $action: DEMO_PROJECT must differ from the ordinary project APP_PROJECT=$ordinary_project" +fi +env_file="${ENV_FILE:-$root/.env}" +demo_env_file="${DEMO_ENV_FILE:-$root/deploy/demo/demo.env.example}" +[[ -f "$env_file" ]] || fail "missing $env_file; copy .env.example to .env and replace the placeholder passwords" +[[ -f "$demo_env_file" ]] || fail "missing demo env file $demo_env_file" +actor="${DEMO_ACTOR:-operator:demo-seed}" +[[ "$actor" =~ ^operator:[a-z0-9][a-z0-9._-]*$ ]] || fail 'DEMO_ACTOR must be operator:' +port="${DEMO_HTTP_PORT:-8090}" +[[ "$port" =~ ^[1-9][0-9]{0,4}$ ]] || fail 'DEMO_HTTP_PORT must be a port number' +public_url="${DEMO_PUBLIC_URL:-http://localhost:$port}" +subnet="${DEMO_SUBNET:-172.29.84.0/24}" +frontend_ip="${DEMO_FRONTEND_IP:-172.29.84.10}" + +# The shell values override the env files, so the root .env cannot point the +# demo project at the ordinary project's names, network, or port. +compose() { + APP_PROJECT="$project" APP_NETWORK="${project}_default" APP_STORAGE_NETWORK="${project}_storage" \ + APP_HTTP_PORT="$port" APP_SUBNET="$subnet" APP_FRONTEND_IP="$frontend_ip" APP_PUBLIC_URL="$public_url" \ + DEMO_MODE=isolated "$docker_cli" compose \ + --env-file "$env_file" --env-file "$demo_env_file" \ + -p "$project" -f "$compose_file" -f "$demo_file" "$@" +} + +volume_exists() { + "$docker_cli" volume inspect "$1" >/dev/null 2>&1 +} + +# A volume carries the demo label only when the demo overlay created it, so a +# volume of an ordinary stand under this name is never adopted or discarded. +check_volumes() { + local volume label + for volume in "${project}_postgres_data" "${project}_seaweedfs_data" "${project}_kafka_data"; do + if volume_exists "$volume"; then + label=$("$docker_cli" volume inspect --format "{{ index .Labels \"$demo_label\" }}" "$volume") + if [[ "$label" != isolated ]]; then + fail "refusing to $action: volume $volume was not created by the demo overlay" + fi + fi + done +} + +start_stand() { + compose up -d --build --wait --wait-timeout 300 + local attempt response + for ((attempt = 1; attempt <= ready_attempts; attempt++)); do + response=$(compose exec -T frontend wget -q -O - http://backend:8080/readyz 2>/dev/null || true) + if [[ "$response" == '{"status":"ready"}' ]]; then + return 0 + fi + sleep 1 + done + fail "the backend of $project did not become ready" +} + +run_command() { + compose --profile demo-seed run --rm --build demo-seed "$@" +} + +# The inventory after the seed lets two runs be compared line by line. +seed() { + start_stand + run_command seed --actor "$actor" + run_command inventory + printf 'demo: the stand %s serves %s; the password is DEMO_ACCOUNT_PASSWORD of %s\n' \ + "$project" "$public_url" "$demo_env_file" +} + +check_volumes +case "$action" in + seed) + seed + ;; + reset) + if volume_exists "${project}_postgres_data"; then + start_stand + if ! run_command check-reset; then + fail "reset refused for $project; nothing was deleted" + fi + fi + compose down --volumes --remove-orphans + seed + ;; + down) + compose down + ;; +esac diff --git a/deploy/scripts/test_demo.py b/deploy/scripts/test_demo.py new file mode 100644 index 0000000..6c1cf9a --- /dev/null +++ b/deploy/scripts/test_demo.py @@ -0,0 +1,215 @@ +"""Guards of the isolated demo targets and the boundary of the demo overlay. + +The script tests run demo.sh against a recording stub of the docker CLI, so +they prove which Docker commands a refusal never reaches. The render tests +need the docker CLI and are skipped without it. +""" + +import json +import os +import shutil +import stat +import subprocess +import tempfile +import textwrap +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +DEPLOY = ROOT / "deploy" +SCRIPT = DEPLOY / "scripts" / "demo.sh" +DOCKER = os.environ.get("DOCKER", "docker") + +# The stub answers like a running demo stand: volumes exist with the label +# given in STUB_LABEL, the backend is ready, and check-reset exits with +# STUB_CHECK_RESET. Every call is appended to STUB_LOG. +STUB = textwrap.dedent( + """\ + #!/usr/bin/env bash + printf '%s\\n' "$*" >> "$STUB_LOG" + args=" $* " + if [[ "$args" == *" volume inspect --format "* ]]; then + printf '%s\\n' "${STUB_LABEL:-}" + exit 0 + fi + if [[ "$args" == *" volume inspect "* ]]; then + exit "${STUB_VOLUME_STATUS:-0}" + fi + if [[ "$args" == *" wget "* ]]; then + printf '%s' '{"status":"ready"}' + exit 0 + fi + if [[ "$args" == *" check-reset "* ]]; then + exit "${STUB_CHECK_RESET:-0}" + fi + exit 0 + """ +) + + +class DemoScriptGuardTest(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory() + self.addCleanup(self.directory.cleanup) + base = Path(self.directory.name) + self.stub = base / "docker" + self.stub.write_text(STUB) + self.stub.chmod(self.stub.stat().st_mode | stat.S_IXUSR) + self.log = base / "calls.log" + self.log.write_text("") + self.env_file = base / "root.env" + self.env_file.write_text("POSTGRES_USER=demo\n") + self.demo_env = base / "demo.env" + self.demo_env.write_text("DEMO_ACCOUNT_PASSWORD=synthetic demo stand only 2026\n") + + def run_script(self, action, **overrides): + environment = { + "PATH": os.environ.get("PATH", ""), + "HOME": os.environ.get("HOME", ""), + "DOCKER": str(self.stub), + "STUB_LOG": str(self.log), + "DEMO_MODE": "isolated", + "DEMO_PROJECT": "lincodex-demo-test", + "APP_PROJECT": "app", + "ENV_FILE": str(self.env_file), + "DEMO_ENV_FILE": str(self.demo_env), + "STUB_LABEL": "isolated", + } + for key, value in overrides.items(): + if value is None: + environment.pop(key, None) + else: + environment[key] = value + return subprocess.run( + ["bash", str(SCRIPT), action], capture_output=True, text=True, env=environment, check=False + ) + + def calls(self): + return [line for line in self.log.read_text().splitlines() if line] + + def test_every_action_refuses_without_the_isolated_mode_before_docker(self): + for action in ("seed", "reset", "down"): + for mode in (None, "", "production", "ISOLATED"): + with self.subTest(action=action, mode=mode): + result = self.run_script(action, DEMO_MODE=mode) + self.assertEqual(result.returncode, 2, result.stderr) + self.assertIn("DEMO_MODE=isolated", result.stderr) + self.assertEqual(self.calls(), []) + + def test_the_project_must_be_a_separate_demo_project(self): + cases = ( + {"DEMO_PROJECT": "app"}, + {"DEMO_PROJECT": "lincodex-demo-test", "APP_PROJECT": "lincodex-demo-test"}, + {"DEMO_PROJECT": "lincodex"}, + {"DEMO_PROJECT": "Demo Stand"}, + {"DEMO_ACTOR": "alice"}, + {"ENV_FILE": str(Path(self.directory.name) / "missing.env")}, + ) + for overrides in cases: + with self.subTest(overrides=overrides): + result = self.run_script("reset", **overrides) + self.assertEqual(result.returncode, 2, result.stderr) + self.assertEqual(self.calls(), []) + + def test_a_volume_without_the_demo_label_is_never_used(self): + for action in ("seed", "reset"): + with self.subTest(action=action): + result = self.run_script(action, STUB_LABEL="") + self.assertEqual(result.returncode, 2, result.stderr) + self.assertIn("was not created by the demo overlay", result.stderr) + self.assertFalse([call for call in self.calls() if call.startswith("compose")]) + + def test_reset_stops_before_down_when_the_check_refuses(self): + result = self.run_script("reset", STUB_CHECK_RESET="2") + self.assertEqual(result.returncode, 2, result.stderr) + self.assertIn("nothing was deleted", result.stderr) + calls = self.calls() + self.assertTrue(any(" check-reset" in call for call in calls)) + self.assertFalse([call for call in calls if " down" in call]) + + def test_reset_discards_only_the_demo_project_and_seeds_again(self): + result = self.run_script("reset") + self.assertEqual(result.returncode, 0, result.stderr) + compose_calls = [call for call in self.calls() if call.startswith("compose")] + down = [call for call in compose_calls if " down --volumes" in call] + self.assertEqual(len(down), 1) + for call in compose_calls: + self.assertIn("-p lincodex-demo-test ", call) + self.assertIn("docker-compose.demo.yml", call) + self.assertLess(compose_calls.index(next(call for call in compose_calls if " check-reset" in call)), compose_calls.index(down[0])) + self.assertIn(" seed --actor operator:demo-seed", compose_calls[-2]) + self.assertTrue(compose_calls[-1].endswith(" inventory")) + + def test_down_keeps_the_volumes(self): + result = self.run_script("down") + self.assertEqual(result.returncode, 0, result.stderr) + compose_calls = [call for call in self.calls() if call.startswith("compose")] + self.assertEqual(len(compose_calls), 1) + self.assertTrue(compose_calls[0].endswith(" down")) + + +def render_demo(project="lincodex-demo-render"): + environment = dict( + os.environ, + APP_PROJECT=project, + APP_NETWORK=f"{project}_default", + APP_STORAGE_NETWORK=f"{project}_storage", + APP_HTTP_PORT="8090", + APP_SUBNET="172.29.84.0/24", + APP_FRONTEND_IP="172.29.84.10", + IDENTITY_KEY_SECRET="render-only-identity-key-secret", + DEMO_ACCOUNT_PASSWORD="render-only-demo-account-password", + DEMO_MODE="isolated", + ) + environment.pop("APP_HTTP_BIND", None) + command = [ + DOCKER, "compose", "--env-file", str(ROOT / ".env.example"), "-p", project, + "-f", str(DEPLOY / "docker" / "docker-compose.yml"), "-f", str(DEPLOY / "docker" / "docker-compose.demo.yml"), + "--profile", "demo-seed", "config", "--format", "json", + ] + result = subprocess.run(command, capture_output=True, text=True, env=environment, check=False) + if result.returncode != 0: + raise AssertionError(f"docker compose config failed: {result.stderr}") + return json.loads(result.stdout) + + +class DemoOverlayTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + if shutil.which(DOCKER) is None: + raise unittest.SkipTest("docker CLI is not available") + cls.rendered = render_demo() + + def test_only_the_frontend_is_published_on_loopback(self): + published = {name: service["ports"] for name, service in self.rendered["services"].items() if service.get("ports")} + self.assertEqual(list(published), ["frontend"]) + for port in published["frontend"]: + self.assertEqual(port["host_ip"], "127.0.0.1") + self.assertEqual(port["published"], "8090") + + def test_the_seed_reaches_only_the_default_network(self): + seed = self.rendered["services"]["demo-seed"] + self.assertEqual(seed["profiles"], ["demo-seed"]) + self.assertEqual(list(seed["networks"]), ["default"]) + self.assertEqual(seed["build"]["dockerfile"], "Dockerfile.demo-seed") + self.assertTrue(seed["read_only"]) + self.assertEqual(seed["environment"]["DEMO_MODE"], "isolated") + + def test_volumes_carry_the_demo_label_and_the_project_name(self): + for name, volume in self.rendered["volumes"].items(): + with self.subTest(volume=name): + self.assertEqual(volume["labels"]["org.lincodex.demo-mode"], "isolated") + self.assertTrue(volume["name"].startswith("lincodex-demo-render_")) + + def test_the_demo_backend_assigns_synthetic_categories(self): + backend = self.rendered["services"]["backend"] + self.assertEqual(backend["environment"]["ASSESSMENT_DEMO_CATEGORIES_ENABLED"], "true") + self.assertEqual(backend["labels"]["org.lincodex.demo-mode"], "isolated") + + def test_release_and_ordinary_images_never_contain_the_seed(self): + for dockerfile in ("Dockerfile", "Dockerfile.e2e"): + self.assertNotIn("demo-seed", (ROOT / "backend" / dockerfile).read_text()) + + +if __name__ == "__main__": + unittest.main() diff --git a/docs/en/DEPLOY.md b/docs/en/DEPLOY.md index 2881786..f0735ad 100644 --- a/docs/en/DEPLOY.md +++ b/docs/en/DEPLOY.md @@ -359,6 +359,36 @@ make -C backend policy-publish ARGS='matching --actor operator:' - The new version takes effect at once for new searches and changes no stored result. It is also a new version of the whole product policy, so a category opening pinned to the earlier version has to be opened again (and attested again on a demonstration stand, see above) before new assessment attempts are created. Publish it before the candidates start attempts, or repeat the opening and the attestation afterwards. - The demo values (the coefficients of the PRD, the limit of 10 entries per group, and the small specialization-to-technology taxonomy) are in [architecture](ARCHITECTURE.md#product-policy-versions); they are not calibrated. The isolated browser fixture publishes the same section itself. +## Isolated demo stand + +The demo stand is a separate Compose project with synthetic data only: the jury and the team sign in with prepared accounts of both roles, without waiting for mail. It is not the working stand, and real people must not register on it. + +```sh +make -C deploy demo-seed DEMO_MODE=isolated +make -C deploy demo-reset DEMO_MODE=isolated +make -C deploy demo-down DEMO_MODE=isolated +``` + +- Every target requires `DEMO_MODE=isolated` and refuses before any Docker command without it. It acts only on the project `DEMO_PROJECT` (default `lincodex-demo`), whose name must contain `demo` and differ from `APP_PROJECT`; the ordinary project and its volumes are never addressed. The project is `docker-compose.yml` with `docker-compose.demo.yml`, built from the current sources. The overlay sets `ASSESSMENT_DEMO_CATEGORIES_ENABLED=true` on the demo backend, so a full test taken there assigns an uncalibrated synthetic category like the prepared ones (see [Demonstration categories on a stand](#demonstration-categories-on-a-stand)). It reads the secrets from the root `.env` (`ENV_FILE`) and overrides the project name, networks, `APP_HTTP_PORT` (`DEMO_HTTP_PORT`, default 8090), `APP_PUBLIC_URL` (`DEMO_PUBLIC_URL`, default `http://localhost:8090`), and the pinned subnet (`DEMO_SUBNET` 172.29.84.0/24, `DEMO_FRONTEND_IP`), so it can run next to the ordinary stand. The bind address stays `APP_HTTP_BIND`. Behind the edge, set `DEMO_PUBLIC_URL` to the public origin. The mail transport is the one in `.env`; the prepared accounts need no mail. +- `demo-seed` starts the project when needed, waits for the backend readiness (migrations and the startup policy are done by then), runs the `demo-seed seed` command in a separate container, and prints the inventory of the seeded records. A second run creates nothing and prints the same inventory. `demo-down` stops the project and keeps its volumes. +- `demo-reset` first runs `demo-seed check-reset` against the demo database. It refuses, and deletes nothing, when the database holds any account outside the reserved domain `@demo.lincodex.test`, for example a visitor's own registration: such an account is ordinary data. Otherwise it removes the demo project with its volumes (`down --volumes` of `DEMO_PROJECT` only), starts it again, and seeds it. The demo overlay labels the PostgreSQL, SeaweedFS, and Kafka volumes with `org.lincodex.demo-mode=isolated` when it creates them; every target refuses a volume of the project without that label, so a volume of an ordinary stand is never adopted or discarded. A stand that the reset refuses can only be cleared by a deliberate manual decision of the operator. +- The password of every synthetic account is `DEMO_ACCOUNT_PASSWORD` from `deploy/demo/demo.env`, or from the checked-in `deploy/demo/demo.env.example` when that file does not exist. The example value is a published demo credential, not a secret; for a stand reachable from outside, copy the example to `demo.env` (ignored by Git) and hand the new password to the jury separately. The password applies when an account is created; change it with a reset. The commands print the logins and never the password. + +What the seed creates (all names carry a synthetic marker; addresses are on `@demo.lincodex.test`, which never receives mail): + +| Login | Role and state | +| --- | --- | +| `employer-alpha@demo.lincodex.test` | Employer. Owner of "Демо-компания «Альфа»" and recruiter in "Демо-компания «Бета»": full owner access in one organization and the owner-only denial of the minimal release in the other | +| `employer-beta@demo.lincodex.test` | Employer. Owner of "Демо-компания «Бета»" | +| `candidate@demo.lincodex.test` | Candidate for the jury's own run: C1 and C3, a manual profile without an FSP ID, the Backend Junior questionnaire with Go, no attempt, no publication. Runs the express and starts the full test | +| `prepared-1@` to `prepared-6@demo.lincodex.test` | Candidates with a prepared full attempt: C1, C2, C3, the same profile and questionnaire, one finished `demo_basic` attempt with its synthetic demonstration category Backend Junior and evidence, and a published card | + +- Accounts are confirmed by the seed itself: it stores the account, the C1 grant of a registration, and the verification time in one transaction, like the e2e fixtures. Ordinary registration is unchanged and still needs the email link; on a stand with `EMAIL_PROVIDER=disabled` a self-registered account cannot sign in. +- Policy and bank: over the unchanged startup version 1 the seed publishes the demo policy `DemoProductPolicyV4` (explicit `demo_basic` settings, the separate express training section, the review band, and the matching section); a stand whose latest policy is anything else is refused. It imports and publishes 25 synthetic families of the category `demo-backend-junior` (author `ai:demo-seed-synthetic-bank`, reviewer label `operator:demo-seed-bank-reviewer`; the families are not subject-reviewed), opens the category for Backend Junior with Go, and attests it as a synthetic demonstration source. Express mode has its own three families in the category `demo-express` and its own training binding; an express run never creates a category, a percentile, or evidence. +- Prepared attempts run through the ordinary attempt operations: create, answer every frozen item (all but the last one correctly), and finalize, so the result, the category, the history, and the evidence projection come from the same code and triggers as a candidate's attempt. They are not three demonstration questions. They are labelled in the profile of each prepared candidate ("Полная попытка теста подготовлена командой demo-seed"), in the seed output (attempt IDs), and as uncalibrated `synthetic_demo` categories. The database has no separate provenance flag on a result yet. The answers are given within seconds, so the manual-review band of these attempts can show the speed signals. +- Six identical prepared cards exist because a card is shown only in a cohort of at least five; the sixth keeps the search non-empty after one prepared candidate hides an organization or unpublishes. The search of Alpha's owner returns the six entries; the recruiter's search in Beta answers 403. The seed creates no need: an employer creates one during the demonstration. +- The seed refuses a stand that holds ordinary accounts but none of its own, never edits a record it did not create, and leaves its own records alone on a repeat (for example a profile a visitor changed); use the reset to restore them. It refuses an address of the reserved domain that belongs to an unconfirmed or other-role account. `demo-seed` needs `DATABASE_URL` and `DEMO_MODE=isolated`, plus `DEMO_ACCOUNT_PASSWORD` for `seed`; it reads no dotenv file and checks all of them before it connects. The actor `operator:` (`DEMO_ACTOR`, default `operator:demo-seed`) is recorded as the author of the policy version, the publisher of the families, the opener of the category, and the attestor; it is an audit label, not authentication. `make -C backend demo-seed ARGS='inventory'` runs the same command from a host that reaches the database; `make -C backend demo-seed-build` builds `backend/bin/demo-seed`. The command is built by `backend/Dockerfile.demo-seed`; the backend and release images do not contain it. + ## Separate ML Compose project ML uses a separate Compose file and project; it does not require or start Redis or SeaweedFS in the current scaffold. Its default host bind is 127.0.0.1:8000. Set ML_BIND_ADDRESS only after choosing a private address and preparing firewall rules. Prometheus does not scrape remote ML while ML_METRICS_TARGET is empty. diff --git a/docs/en/TESTING.md b/docs/en/TESTING.md index 498ad0b..65df9a7 100644 --- a/docs/en/TESTING.md +++ b/docs/en/TESTING.md @@ -479,6 +479,24 @@ Browser test: `frontend/e2e/notifications.spec.ts` runs in `make -C deploy test- What these tests do not show: a real invitation (none produces an event yet), the behavior of the inbox when the mail provider fails (the handler reads no mail state by construction, and the unit test covers an unverified address), delivery latency or load, push or live updates, and the layout and the screen-reader behavior of the page (no automated check). +## Demo seed tests + +`backend/internal/usecase/demoseed/seeder_test.go` checks without a database that a reset is allowed only for a database without accounts or with synthetic accounts only, that the synthetic bundles pass the loader rules and are identical between builds (so a repeated import changes nothing), that the prepared answers have the intended correctness, and that the dataset has two employers on the synthetic domain, one self-service candidate, and a cohort of at least five prepared candidates. `backend/internal/adapter/primary/cli/demoseed/command_test.go` checks the argument parsing, that every subcommand refuses without `DEMO_MODE=isolated` before it reads the database settings, that a short password is refused without echoing it, that the seed output names the logins and the prepared attempts but never the password, that failures become safe messages, and that `check-reset` fails on any account outside the synthetic domain. + +`TestDemoSeedCommand` in `backend/integration_test/demo_seed_test.go` uses `bootstrap(t, postgresService)` and runs the operator command against migrated databases that carry the startup policy: + +- Without the isolated mode, also against an unreachable database, every subcommand refuses, and nothing is written. +- A database with an ordinary account and no seed is refused by both the seed and the reset check; the account and the policy stay as they were. +- The first seed creates nine confirmed synthetic accounts, two organizations, three memberships (the owner of Alpha is a recruiter of Beta), six prepared attempts with results, current synthetic categories, evidence, and published cards, the seed policy version, 28 published families, one opening, one attestation, and one training binding. A second seed by another operator creates nothing and prints the same inventory. +- Every organization, profile name, and prepared profile carries its synthetic or prepared marker, and every category is an uncalibrated `synthetic_demo` category. +- The owner of Alpha sees exactly the six prepared cards through the card listing that the search uses, and not the unpublished self-service candidate. +- A perfect express run of the self-service candidate through the attempt operations draws three items from the training category, ends as `demonstration`, and adds no category and no evidence; the same candidate can then start the full test. +- After an ordinary account registers on the seeded database, the reset check refuses and counts it, a repeated seed still creates nothing, and the account is unchanged. + +`make -C deploy check-demo` (part of `make -C deploy check`) runs `deploy/scripts/demo.sh` against a recording stub of the docker CLI: every action refuses without `DEMO_MODE=isolated`, with a project name that equals `APP_PROJECT` or lacks `demo`, with an invalid actor, or without the env file, before any Docker command; a project volume without the demo label is refused before any Compose command; a refused reset check stops the reset before `down`; a reset addresses only the demo project and seeds again; `down` keeps the volumes. With the docker CLI it also renders the overlay: only the frontend is published, on loopback; the seed container has only the default network, a read-only root, and the explicit profile; every volume carries the demo label; the demo backend enables synthetic categories; and the backend images do not contain the command. + +The tests do not run the Make targets against a real stack. A manual check on a throwaway project: `make -C deploy demo-seed DEMO_MODE=isolated DEMO_PROJECT=lincodex-demo-check DEMO_HTTP_PORT=18090` twice with identical inventories, a sign-in of the prepared accounts with mail disabled, an express run and the start of the full test, then `demo-reset` refused after a visitor registered. Remove the project afterwards with `docker compose -p lincodex-demo-check down --volumes` and the same variables. The tests do not validate the content of the synthetic bank or any grade, and the browser route of the jury is not covered here. Integration tests need Docker. + ## Future software validation Go unit tests should exercise domain/usecase rules with explicit inputs, results, and errors. Integration tests should use a real PostgreSQL at the same major version, apply goose migrations, and exercise sqlc, constraints, transactions, rollback, and concurrent transitions. The HTTP path should use chi, middleware, usecases, and the database; replace external ML with a controlled HTTP fake and email with a test adapter. diff --git a/docs/ru/DEPLOY.md b/docs/ru/DEPLOY.md index 8e596ee..0bdeae5 100644 --- a/docs/ru/DEPLOY.md +++ b/docs/ru/DEPLOY.md @@ -361,6 +361,36 @@ make -C backend policy-publish ARGS='matching --actor operator:' - Новая версия действует для новых поисков сразу и не меняет сохраненных результатов. Это также новая версия всей политики product, поэтому открытие категории, привязанное к прежней версии, нужно открыть заново (и аттестовать заново на демонстрационном стенде, см. выше), прежде чем создавать новые попытки оценки. Публикуйте ее до начала попыток кандидатов либо повторите открытие и аттестацию после. - Демонстрационные значения (коэффициенты PRD, предел 10 записей на группу и небольшая таксономия «специализация - технология») описаны в [архитектуре](ARCHITECTURE.md#версии-продуктовой-политики); они не калиброваны. Изолированный браузерный стенд публикует тот же раздел сам. +## Изолированный демонстрационный стенд + +Демонстрационный стенд - отдельный Compose-проект только с синтетическими данными: жюри и команда входят в подготовленные аккаунты обеих ролей без ожидания письма. Это не рабочий стенд, и реальные люди не должны на нем регистрироваться. + +```sh +make -C deploy demo-seed DEMO_MODE=isolated +make -C deploy demo-reset DEMO_MODE=isolated +make -C deploy demo-down DEMO_MODE=isolated +``` + +- Каждая цель требует `DEMO_MODE=isolated` и без него отказывает до любой команды Docker. Она работает только с проектом `DEMO_PROJECT` (по умолчанию `lincodex-demo`), имя которого должно содержать `demo` и отличаться от `APP_PROJECT`; к обычному проекту и его томам цели не обращаются. Проект собирается из `docker-compose.yml` и `docker-compose.demo.yml` по текущим исходникам. Overlay включает `ASSESSMENT_DEMO_CATEGORIES_ENABLED=true` в демонстрационном backend, поэтому полный тест на нем присваивает неоткалиброванную синтетическую категорию, как и подготовленные попытки (см. [Демонстрационные категории на стенде](#демонстрационные-категории-на-стенде)). Секреты берутся из корневого `.env` (`ENV_FILE`), а имя проекта, сети, `APP_HTTP_PORT` (`DEMO_HTTP_PORT`, по умолчанию 8090), `APP_PUBLIC_URL` (`DEMO_PUBLIC_URL`, по умолчанию `http://localhost:8090`) и закрепленная подсеть (`DEMO_SUBNET` 172.29.84.0/24, `DEMO_FRONTEND_IP`) переопределяются, поэтому стенд может работать рядом с обычным. Адрес привязки остается `APP_HTTP_BIND`. За edge укажите в `DEMO_PUBLIC_URL` публичный origin. Почтовый транспорт берется из `.env`; подготовленным аккаунтам почта не нужна. +- `demo-seed` при необходимости запускает проект, ждет готовности backend (к этому моменту миграции и стартовая политика уже применены), выполняет команду `demo-seed seed` в отдельном контейнере и печатает перечень созданных записей. Повторный запуск ничего не создает и печатает тот же перечень. `demo-down` останавливает проект и сохраняет тома. +- `demo-reset` сначала выполняет `demo-seed check-reset` против демонстрационной базы. Цель отказывает и ничего не удаляет, если в базе есть хотя бы один аккаунт вне зарезервированного домена `@demo.lincodex.test`, например собственная регистрация посетителя: такой аккаунт - обычные данные. Иначе она удаляет демонстрационный проект вместе с томами (`down --volumes` только для `DEMO_PROJECT`), запускает его снова и заполняет. Overlay при создании помечает тома PostgreSQL, SeaweedFS и Kafka меткой `org.lincodex.demo-mode=isolated`; каждая цель отказывает при томе проекта без этой метки, поэтому том обычного стенда никогда не будет использован или удален. Стенд, сброс которого отклонен, очищается только сознательным ручным решением оператора. +- Пароль всех синтетических аккаунтов - `DEMO_ACCOUNT_PASSWORD` из `deploy/demo/demo.env`, а без этого файла - из закоммиченного `deploy/demo/demo.env.example`. Значение из примера - опубликованные демонстрационные учетные данные, а не секрет; для стенда, доступного извне, скопируйте пример в `demo.env` (Git его игнорирует) и передайте новый пароль жюри отдельно. Пароль применяется при создании аккаунта; меняется он через сброс. Команды печатают логины и никогда не печатают пароль. + +Что создает seed (все названия содержат пометку о синтетических данных; адреса на `@demo.lincodex.test`, который никогда не получает почту): + +| Логин | Роль и состояние | +| --- | --- | +| `employer-alpha@demo.lincodex.test` | Работодатель. Владелец «Демо-компания «Альфа»» и рекрутер в «Демо-компания «Бета»»: полный доступ владельца в одной организации и отказ по правилу «только владелец» минимального выпуска в другой | +| `employer-beta@demo.lincodex.test` | Работодатель. Владелец «Демо-компания «Бета»» | +| `candidate@demo.lincodex.test` | Кандидат для самостоятельного прохождения жюри: C1 и C3, ручной профиль без ФСП ID, опрос Backend Junior с Go, без попыток и без публикации. Проходит экспресс-тест и начинает полный тест | +| `prepared-1@` - `prepared-6@demo.lincodex.test` | Кандидаты с подготовленной полной попыткой: C1, C2, C3, такие же профиль и опрос, одна завершенная попытка `demo_basic` с синтетической демонстрационной категорией Backend Junior и доказательством, опубликованная карточка | + +- Аккаунты подтверждает сам seed: в одной транзакции он сохраняет аккаунт, выдачу C1 при регистрации и время подтверждения, как e2e-фикстуры. Обычная регистрация не меняется и по-прежнему требует ссылку из письма; на стенде с `EMAIL_PROVIDER=disabled` самостоятельно зарегистрированный аккаунт войти не может. +- Политика и банк: поверх неизмененной стартовой версии 1 seed публикует демонстрационную политику `DemoProductPolicyV4` (явные настройки `demo_basic`, отдельный раздел учебного экспресс-режима, полоса ручной проверки и раздел подбора); стенд с любой другой последней версией политики отклоняется. Seed импортирует и публикует 25 синтетических семейств категории `demo-backend-junior` (автор `ai:demo-seed-synthetic-bank`, метка проверяющего `operator:demo-seed-bank-reviewer`; предметной проверки семейства не проходили), открывает категорию для Backend Junior с Go и аттестует ее как синтетический демонстрационный источник. У экспресс-режима свои три семейства в категории `demo-express` и своя учебная привязка; экспресс-прохождение никогда не создает категорию, перцентиль или доказательство. +- Подготовленные попытки проходят через обычные операции попытки: создание, ответ на каждое закрепленное задание (все, кроме последнего, верно) и завершение, поэтому результат, категория, история и проекция доказательств получаются тем же кодом и теми же триггерами, что и у попытки кандидата. Это не три демонстрационных вопроса. Они помечены в профиле каждого подготовленного кандидата («Полная попытка теста подготовлена командой demo-seed»), в выводе seed (идентификаторы попыток) и как неоткалиброванные категории `synthetic_demo`. Отдельного признака происхождения у результата в базе пока нет. Ответы даются за секунды, поэтому полоса ручной проверки этих попыток может показать сигналы скорости. +- Подготовленных карточек шесть одинаковых, потому что карточка показывается только в когорте не меньше пяти; шестая сохраняет непустой поиск, если один подготовленный кандидат скроет организацию или снимет публикацию. Поиск владельца «Альфы» возвращает шесть записей; поиск рекрутера в «Бете» отвечает 403. Потребность seed не создает: работодатель создает ее во время демонстрации. +- Seed отклоняет стенд, где есть обычные аккаунты, но нет ни одного его собственного, никогда не меняет записи, которые не создавал, и при повторе не трогает свои записи (например, профиль, измененный посетителем); для восстановления используйте сброс. Seed отклоняет адрес зарезервированного домена, принадлежащий неподтвержденному аккаунту или аккаунту другой роли. Команде `demo-seed` нужны `DATABASE_URL` и `DEMO_MODE=isolated`, а для `seed` еще `DEMO_ACCOUNT_PASSWORD`; dotenv-файл она не читает и проверяет все значения до подключения. Исполнитель `operator:` (`DEMO_ACTOR`, по умолчанию `operator:demo-seed`) записывается как автор версии политики, публикатор семейств, открывший категорию и аттестующий; это метка аудита, а не аутентификация. `make -C backend demo-seed ARGS='inventory'` запускает ту же команду с хоста, у которого есть доступ к базе; `make -C backend demo-seed-build` собирает `backend/bin/demo-seed`. Команду собирает `backend/Dockerfile.demo-seed`; backend- и release-образы ее не содержат. + ## Отдельный ML Compose ML имеет отдельный Compose-файл и проект; Redis и SeaweedFS ему пока не требуются и здесь не запускаются. По умолчанию он слушает на 127.0.0.1:8000. Настройте ML_BIND_ADDRESS только если выбранный приватный адрес и firewall уже подготовлены. Метрики удаленного ML target не собираются, пока ML_METRICS_TARGET пуст. diff --git a/docs/ru/TESTING.md b/docs/ru/TESTING.md index 3d64f86..40ea1c7 100644 --- a/docs/ru/TESTING.md +++ b/docs/ru/TESTING.md @@ -479,6 +479,24 @@ Unit-тесты (`make -C backend test`) проверяют правила жу Чего эти тесты не показывают: настоящее приглашение (пока ни одно не создает событие), поведение inbox при сбое почтового провайдера (по построению обработчик не читает состояние почты, а модульный тест покрывает неподтвержденный адрес), задержку доставки и нагрузку, push и живые обновления, а также вёрстку и работу страницы со скринридером (автоматической проверки нет). +## Тесты демонстрационного seed + +`backend/internal/usecase/demoseed/seeder_test.go` без базы проверяет, что сброс разрешен только для базы без аккаунтов или только с синтетическими аккаунтами, что синтетические наборы проходят правила загрузчика и совпадают между сборками (поэтому повторный импорт ничего не меняет), что подготовленные ответы имеют задуманную правильность и что в наборе данных два работодателя на синтетическом домене, один кандидат для самостоятельного прохождения и когорта не меньше чем из пяти подготовленных кандидатов. `backend/internal/adapter/primary/cli/demoseed/command_test.go` проверяет разбор аргументов, отказ каждой подкоманды без `DEMO_MODE=isolated` до чтения настроек базы, отказ при коротком пароле без вывода его значения, то, что вывод seed называет логины и подготовленные попытки, но никогда не пароль, безопасные сообщения об ошибках и отказ `check-reset` при любом аккаунте вне синтетического домена. + +`TestDemoSeedCommand` в `backend/integration_test/demo_seed_test.go` использует `bootstrap(t, postgresService)` и запускает операторскую команду против баз с миграциями и стартовой политикой: + +- Без изолированного режима, в том числе против недоступной базы, каждая подкоманда отказывает и ничего не записывает. +- База с обычным аккаунтом и без seed отклоняется и seed, и проверкой сброса; аккаунт и политика остаются прежними. +- Первый seed создает девять подтвержденных синтетических аккаунтов, две организации, три членства (владелец «Альфы» - рекрутер «Беты»), шесть подготовленных попыток с результатами, текущими синтетическими категориями, доказательствами и опубликованными карточками, версию политики seed, 28 опубликованных семейств, одно открытие, одну аттестацию и одну учебную привязку. Повторный seed от другого оператора ничего не создает и печатает тот же перечень. +- Каждая организация, имя профиля и подготовленный профиль содержат пометку о синтетических данных или о подготовке, а каждая категория - неоткалиброванная категория `synthetic_demo`. +- Владелец «Альфы» видит ровно шесть подготовленных карточек через тот же список карточек, что использует поиск, и не видит неопубликованного кандидата для самостоятельного прохождения. +- Безошибочное экспресс-прохождение этого кандидата через операции попытки берет три задания из учебной категории, завершается результатом `demonstration` и не добавляет ни категории, ни доказательства; после этого тот же кандидат может начать полный тест. +- После регистрации обычного аккаунта в заполненной базе проверка сброса отказывает и учитывает его, повторный seed по-прежнему ничего не создает, а аккаунт не меняется. + +`make -C deploy check-demo` (часть `make -C deploy check`) запускает `deploy/scripts/demo.sh` с записывающей заглушкой docker CLI: каждое действие отказывает без `DEMO_MODE=isolated`, с именем проекта, равным `APP_PROJECT` или без `demo`, с неверным исполнителем или без env-файла, до любой команды Docker; том проекта без демонстрационной метки отклоняется до любой команды Compose; отказ проверки сброса останавливает сброс до `down`; сброс обращается только к демонстрационному проекту и заново заполняет его; `down` сохраняет тома. При наличии docker CLI тест также рендерит overlay: опубликован только frontend и только на loopback; у контейнера seed только сеть default, корень только для чтения и явный профиль; у каждого тома есть демонстрационная метка; демонстрационный backend включает синтетические категории; backend-образы команду не содержат. + +Тесты не запускают Make-цели против настоящего стека. Ручная проверка на одноразовом проекте: дважды `make -C deploy demo-seed DEMO_MODE=isolated DEMO_PROJECT=lincodex-demo-check DEMO_HTTP_PORT=18090` с одинаковыми перечнями, вход подготовленными аккаунтами при выключенной почте, экспресс-прохождение и начало полного теста, затем отказ `demo-reset` после регистрации посетителя. После проверки удалите проект командой `docker compose -p lincodex-demo-check down --volumes` с теми же переменными. Тесты не проверяют содержание синтетического банка или какой-либо грейд, а браузерный маршрут жюри здесь не покрыт. Интеграционным тестам нужен Docker. + ## Будущая программная валидация Для Go unit tests нужны правила domain/usecase с конкретными входами, результатами и ошибками. Интеграционные тесты используют настоящую PostgreSQL той же major версии, применяют goose migrations и проверяют sqlc, ограничения, транзакции, rollback и конкурентные переходы. Для HTTP путь собирается через chi, middleware, usecase и БД; внешний ML заменяется контролируемым HTTP fake, почта - тестовым адаптером.