feat(assessment): assign the demonstration category and keep result history

This commit is contained in:
shira committed 2026-10-09 00:35:13 +03:00
1 parent b3c6dc870b
commit 8277133712
61 files changed
+4338 -268

No files matched your search

@@ -0,0 +1,151 @@
// Package categoryattest implements the local operator command that attests the
// current opening of an assessment category as a source of synthetic
// demonstration categories. It is meant for isolated synthetic stands: a
// category is assigned only when the runtime gate
// ASSESSMENT_DEMO_CATEGORIES_ENABLED is also on.
package categoryattest
import (
"context"
"errors"
"flag"
"fmt"
"io"
"strings"
"lincodex/backend/config"
"lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/assessment"
)
// syntheticOnlyWarning is printed before any work, also when the command fails.
const syntheticOnlyWarning = "warning: synthetic demonstration categories are enabled by this attestation; never on a production stand\n"
const usage = "usage: assessment-category-attest attest --specialization <code> --grade <code> [--task-language <code>] --actor operator:<handle>"
// Command is a parsed, validated attestation request.
type Command struct {
Specialization domain.SpecializationCode
Grade domain.GradeCode
TaskLanguage *domain.TaskLanguageCode
Actor string
}
// Attestor stores an attestation.
type Attestor interface {
Attest(
ctx context.Context,
specialization domain.SpecializationCode,
grade domain.GradeCode,
language *domain.TaskLanguageCode,
actor string,
) (assessment.CategoryAttestation, error)
}
// Parse validates every argument before Run reads configuration or connects
// to PostgreSQL.
func Parse(args []string) (Command, error) {
if len(args) == 0 || args[0] != "attest" {
return Command{}, errors.New(usage)
}
flags := flag.NewFlagSet("assessment-category-attest attest", flag.ContinueOnError)
flags.SetOutput(io.Discard)
specialization := flags.String("specialization", "", "specialization code")
grade := flags.String("grade", "", "grade code")
language := flags.String("task-language", "", "task language code")
actor := flags.String("actor", "", "operator handle")
if err := flags.Parse(args[1:]); err != nil || flags.NArg() != 0 {
return Command{}, errors.New(usage)
}
command := Command{
Specialization: domain.SpecializationCode(strings.TrimSpace(*specialization)),
Grade: domain.GradeCode(strings.TrimSpace(*grade)),
Actor: strings.TrimSpace(*actor),
}
if !command.Specialization.IsKnown() {
return Command{}, errors.New("specialization must be a known specialization code")
}
if !command.Grade.IsKnown() {
return Command{}, errors.New("grade must be intern, junior, middle, or senior")
}
if trimmed := strings.TrimSpace(*language); trimmed != "" {
taskLanguage := domain.TaskLanguageCode(trimmed)
if !taskLanguage.IsKnown() {
return Command{}, errors.New("task language must be a known task language code")
}
command.TaskLanguage = &taskLanguage
}
if _, err := domain.ParseAssessmentOperator(command.Actor); err != nil {
return Command{}, errors.New("actor must be operator:<handle>")
}
return command, nil
}
// Run parses the command, loads only DATABASE_URL from the supplied
// environment, and executes the attestation. It does not load dotenv files.
func Run(ctx context.Context, args []string, lookup config.LookupEnv, output io.Writer) error {
command, err := Parse(args)
if err != nil {
return err
}
if lookup == nil || output == nil {
return errors.New("category attestation command dependencies are required")
}
databaseURL := config.DatabaseURLFromEnv(lookup)
if databaseURL == "" {
return errors.New("DATABASE_URL is not set")
}
pool, err := postgres.NewPool(ctx, databaseURL)
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")
}
attestor, err := assessment.NewCategoryAttestor(postgres.NewTransactor(pool))
if err != nil {
return errors.New("category attestation is unavailable")
}
return Execute(ctx, command, attestor, output)
}
// Execute stores the attestation and prints identifiers and versions only; it
// prints no candidate, answer, or contact data.
func Execute(ctx context.Context, command Command, attestor Attestor, output io.Writer) error {
if attestor == nil || output == nil {
return errors.New("category attestation command dependencies are required")
}
if _, err := io.WriteString(output, syntheticOnlyWarning); err != nil {
return errors.New("could not write the result")
}
attestation, err := attestor.Attest(ctx, command.Specialization, command.Grade, command.TaskLanguage, command.Actor)
if err != nil {
return safeOperationError(err)
}
status := "already attested"
if attestation.Created {
status = "attested"
}
if _, err := fmt.Fprintf(output,
"%s: category %s, opening %s, review %s, policy_version %d, by %s\n"+
"note: synthetic demonstration only; categories are assigned only while ASSESSMENT_DEMO_CATEGORIES_ENABLED is true on this stand\n",
status, attestation.Category, attestation.OpeningID, attestation.ReviewID, attestation.ProductPolicyVersion, attestation.ReviewedBy,
); err != nil {
return errors.New("could not write the result")
}
return nil
}
func safeOperationError(err error) error {
switch {
case errors.Is(err, outbound.ErrAssessmentSelectionUnavailable), errors.Is(err, outbound.ErrAssessmentSelectionAmbiguous):
return errors.New("no single current reviewed category matches the request")
case errors.Is(err, domain.ErrInvalidAssessmentCategory):
return errors.New("the request is invalid or the current policy is not the explicit demo_basic demonstration policy")
default:
return errors.New("category attestation failed")
}
}
@@ -0,0 +1,120 @@
package categoryattest
import (
"bytes"
"context"
"errors"
"strings"
"testing"
"github.com/google/uuid"
"lincodex/backend/config"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/assessment"
)
type attestorFake struct {
attestation assessment.CategoryAttestation
err error
calls int
command Command
}
func (attestor *attestorFake) Attest(
_ context.Context,
specialization domain.SpecializationCode,
grade domain.GradeCode,
language *domain.TaskLanguageCode,
actor string,
) (assessment.CategoryAttestation, error) {
attestor.calls++
attestor.command = Command{Specialization: specialization, Grade: grade, TaskLanguage: language, Actor: actor}
return attestor.attestation, attestor.err
}
func TestParseRequiresATrackAndAnOperatorHandle(t *testing.T) {
command, err := Parse([]string{"attest", "--specialization", "backend", "--grade", "intern", "--task-language", "go", "--actor", "operator:night"})
if err != nil || command.Specialization != domain.SpecializationBackend || command.Grade != domain.GradeIntern ||
command.TaskLanguage == nil || *command.TaskLanguage != domain.TaskLanguageGo || command.Actor != "operator:night" {
t.Fatalf("Parse(valid) = %+v, %v", command, err)
}
if command, err := Parse([]string{"attest", "--specialization", "backend", "--grade", "junior", "--actor", "operator:night"}); err != nil || command.TaskLanguage != nil {
t.Fatalf("Parse(without language) = %+v, %v", command, err)
}
for _, args := range [][]string{
nil,
{"list"},
{"attest"},
{"attest", "--specialization", "backend", "--grade", "junior"},
{"attest", "--specialization", "backend", "--grade", "junior", "--actor", "alice"},
{"attest", "--specialization", "chef", "--grade", "junior", "--actor", "operator:night"},
{"attest", "--specialization", "backend", "--grade", "lead", "--actor", "operator:night"},
{"attest", "--specialization", "backend", "--grade", "junior", "--task-language", "cobol", "--actor", "operator:night"},
{"attest", "--specialization", "backend", "--grade", "junior", "--actor", "operator:night", "extra"},
} {
if _, err := Parse(args); err == nil {
t.Errorf("Parse(%v) accepted invalid arguments", args)
}
}
}
func TestRunValidatesArgumentsBeforeReadingTheEnvironment(t *testing.T) {
lookup := func(string) (string, bool) {
t.Fatal("environment read before arguments were validated")
return "", false
}
if err := Run(context.Background(), []string{"attest"}, lookup, &bytes.Buffer{}); err == nil {
t.Fatal("Run(invalid arguments) succeeded")
}
var noDatabase config.LookupEnv = func(string) (string, bool) { return "", false }
err := Run(context.Background(), []string{"attest", "--specialization", "backend", "--grade", "intern", "--actor", "operator:night"}, noDatabase, &bytes.Buffer{})
if err == nil || !strings.Contains(err.Error(), "DATABASE_URL") {
t.Fatalf("Run(no database) error = %v, want a DATABASE_URL message", err)
}
}
func TestExecutePrintsIdentifiersAndTheSyntheticOnlyNote(t *testing.T) {
attestor := &attestorFake{attestation: assessment.CategoryAttestation{
ReviewID: uuid.New(), OpeningID: uuid.New(), Category: "backend-intern", ProductPolicyVersion: 2,
ReviewedBy: "operator:night", Created: true,
}}
var output bytes.Buffer
command := Command{Specialization: domain.SpecializationBackend, Grade: domain.GradeIntern, Actor: "operator:night"}
if err := Execute(context.Background(), command, attestor, &output); err != nil {
t.Fatalf("Execute() error = %v", err)
}
if !strings.HasPrefix(output.String(), "warning: synthetic demonstration categories are enabled by this attestation; never on a production stand") {
t.Errorf("output does not start with the synthetic-only warning:\n%s", output.String())
}
for _, want := range []string{"attested: category backend-intern", attestor.attestation.ReviewID.String(), "policy_version 2", "by operator:night", "synthetic demonstration only", "ASSESSMENT_DEMO_CATEGORIES_ENABLED"} {
if !strings.Contains(output.String(), want) {
t.Errorf("output lacks %q:\n%s", want, output.String())
}
}
attestor.attestation.Created = false
output.Reset()
if err := Execute(context.Background(), command, attestor, &output); err != nil || !strings.Contains(output.String(), "\nalready attested") {
t.Fatalf("Execute(repeat) = %v, %q, want an already attested line", err, output.String())
}
if attestor.calls != 2 || attestor.command.Actor != "operator:night" || attestor.command.Grade != domain.GradeIntern {
t.Fatalf("attestor calls/command = %d/%+v, want the parsed request", attestor.calls, attestor.command)
}
}
func TestExecuteMapsFailuresToSafeMessages(t *testing.T) {
for _, test := range []struct {
err error
want string
}{
{outbound.ErrAssessmentSelectionUnavailable, "no single current reviewed category"},
{domain.ErrInvalidAssessmentCategory, "demo_basic"},
{errors.New("pq: password authentication failed for user lincodex at 10.0.0.5"), "attestation failed"},
} {
err := Execute(context.Background(), Command{}, &attestorFake{err: test.err}, &bytes.Buffer{})
if err == nil || !strings.Contains(err.Error(), test.want) || strings.Contains(err.Error(), "10.0.0.5") {
t.Errorf("Execute(%v) error = %v, want a safe %q message", test.err, err, test.want)
}
}
}