package domain import ( "bytes" "crypto/sha256" "crypto/subtle" "encoding/json" "errors" "fmt" "regexp" "strings" "time" "unicode" "github.com/google/uuid" ) const ( maxAssessmentTitleLength = 200 maxAssessmentIdentityLength = 128 maxAssessmentTextLength = 4000 maxAssessmentRubricCriteria = 20 maxAssessmentCriterionIDSize = 64 ) var ( // ErrInvalidAssessmentFamily reports a family version, bundle value, or // opening that is missing, malformed, or inconsistent. ErrInvalidAssessmentFamily = errors.New("invalid assessment family") // ErrAssessmentFamilyIntegrity reports a stored family whose canonical // content no longer matches the stored SHA-256. The row was changed // outside the application. ErrAssessmentFamilyIntegrity = errors.New("assessment family does not match its hash") // ErrAssessmentRefused reports an operation that the bank rules refuse: // publishing a family or opening a category. errors.As with // *AssessmentRefusalError yields the machine-readable reason. ErrAssessmentRefused = errors.New("assessment bank operation refused") assessmentCategoryPattern = regexp.MustCompile(`^[a-z][a-z0-9-]{1,47}$`) assessmentFamilyKeyPattern = regexp.MustCompile(`^[a-z][a-z0-9-]{2,63}$`) assessmentSpecializationPattern = regexp.MustCompile(`^[a-z][a-z0-9-]{1,63}$`) assessmentBundleNamePattern = regexp.MustCompile(`^[a-z][a-z0-9._-]{2,63}$`) assessmentAuthorPattern = regexp.MustCompile(`^(ai|operator):[a-z0-9][a-z0-9._-]*$`) assessmentOperatorPattern = regexp.MustCompile(`^operator:[a-z0-9][a-z0-9._-]*$`) assessmentCriterionIDPattern = regexp.MustCompile(`^[a-z][a-z0-9_]*$`) ) // AssessmentRefusalReason names why the bank refused an operation. type AssessmentRefusalReason string const ( // RefusalReviewerMissing: the family has no reviewer. RefusalReviewerMissing AssessmentRefusalReason = "reviewer_missing" // RefusalReviewNotApproved: the review of the family is not approved. RefusalReviewNotApproved AssessmentRefusalReason = "review_not_approved" // RefusalNotDraft: the family is not a draft any more. RefusalNotDraft AssessmentRefusalReason = "not_draft" // RefusalNotPublished: the family is not published. RefusalNotPublished AssessmentRefusalReason = "not_published" // RefusalCoverageInsufficient: the category has fewer published families // than the grading policy requires. RefusalCoverageInsufficient AssessmentRefusalReason = "coverage_insufficient" // RefusalGradingPolicyMissing: no versioned grading policy was // referenced, or the reference does not resolve to a stored version. RefusalGradingPolicyMissing AssessmentRefusalReason = "grading_policy_missing" // RefusalVersionConflict: a version with the same number but different // content is already stored. RefusalVersionConflict AssessmentRefusalReason = "version_conflict" // RefusalVersionGap: the version is not the next one of its family. RefusalVersionGap AssessmentRefusalReason = "version_gap" // RefusalCategoryChanged: a new version moves the family to another // category. RefusalCategoryChanged AssessmentRefusalReason = "category_changed" // RefusalNewerVersionPublished: a newer version of the family is already // published, so an older one cannot be published. RefusalNewerVersionPublished AssessmentRefusalReason = "newer_version_published" // RefusalGradingPolicyNotCurrent: the referenced grading policy version // is stored but is not the version in force. RefusalGradingPolicyNotCurrent AssessmentRefusalReason = "grading_policy_not_current" ) // AssessmentRefusalError is the error of a refused operation. It carries the // reason for callers and a detail for operators. The detail never quotes // task content. type AssessmentRefusalError struct { Reason AssessmentRefusalReason Detail string } func (refusal *AssessmentRefusalError) Error() string { return fmt.Sprintf("assessment bank refused: %s: %s", refusal.Reason, refusal.Detail) } func (refusal *AssessmentRefusalError) Unwrap() error { return ErrAssessmentRefused } // NewAssessmentRefusalError builds the error of a refused operation. func NewAssessmentRefusal(reason AssessmentRefusalReason, detail string) *AssessmentRefusalError { return &AssessmentRefusalError{Reason: reason, Detail: detail} } func invalidAssessmentFamily(location, reason string) error { return fmt.Errorf("%s - %s: %w", location, reason, ErrInvalidAssessmentFamily) } // AssessmentFamilyID identifies one stored version of a family. type AssessmentFamilyID uuid.UUID // NewAssessmentFamilyID returns a time-ordered UUIDv7. func NewAssessmentFamilyID() (AssessmentFamilyID, error) { id, err := uuid.NewV7() if err != nil { return AssessmentFamilyID{}, fmt.Errorf("domain.NewAssessmentFamilyID - generate ID: %w", err) } return AssessmentFamilyID(id), nil } func (id AssessmentFamilyID) UUID() uuid.UUID { return uuid.UUID(id) } func (id AssessmentFamilyID) String() string { return uuid.UUID(id).String() } func (id AssessmentFamilyID) IsZero() bool { return uuid.UUID(id) == uuid.Nil } // AssessmentCategory is a category of the bank, for example "backend". A // category is available to candidates only after an opening. type AssessmentCategory string func ParseAssessmentCategory(value string) (AssessmentCategory, error) { if !assessmentCategoryPattern.MatchString(value) { return "", invalidAssessmentFamily("domain.ParseAssessmentCategory", "category must be 2 to 48 lowercase letters, digits, or '-', starting with a letter") } return AssessmentCategory(value), nil } // AssessmentFamilyKey is the stable name of a family across its versions. type AssessmentFamilyKey string func ParseAssessmentFamilyKey(value string) (AssessmentFamilyKey, error) { if !assessmentFamilyKeyPattern.MatchString(value) { return "", invalidAssessmentFamily("domain.ParseAssessmentFamilyKey", "family key must be 3 to 64 lowercase letters, digits, or '-', starting with a letter") } return AssessmentFamilyKey(value), nil } // AssessmentSpecialization is the specialization or domain of a family // inside its category. type AssessmentSpecialization string func ParseAssessmentSpecialization(value string) (AssessmentSpecialization, error) { if !assessmentSpecializationPattern.MatchString(value) { return "", invalidAssessmentFamily("domain.ParseAssessmentSpecialization", "specialization must be 2 to 64 lowercase letters, digits, or '-', starting with a letter") } return AssessmentSpecialization(value), nil } // AssessmentBundleName names the bundle a version was imported from. type AssessmentBundleName string func ParseAssessmentBundleName(value string) (AssessmentBundleName, error) { if !assessmentBundleNamePattern.MatchString(value) { return "", invalidAssessmentFamily("domain.ParseAssessmentBundleName", "bundle name must be 3 to 64 lowercase letters, digits, '.', '_', or '-', starting with a letter") } return AssessmentBundleName(value), nil } // AssessmentAuthor identifies who wrote a family: "ai:" for a // generated draft or "operator:" for a person. Never contact data. type AssessmentAuthor string func ParseAssessmentAuthor(value string) (AssessmentAuthor, error) { if len(value) > maxAssessmentIdentityLength || !assessmentAuthorPattern.MatchString(value) { return "", invalidAssessmentFamily("domain.ParseAssessmentAuthor", "author must be ai: or operator: of at most 128 bytes in lowercase letters, digits, '.', '_', or '-'") } return AssessmentAuthor(value), nil } // AssessmentOperator identifies a person who reviews a family or opens a // category: "operator:". An AI draft cannot review itself or open a // category, so no "ai:" identity parses here. type AssessmentOperator string func ParseAssessmentOperator(value string) (AssessmentOperator, error) { if len(value) > maxAssessmentIdentityLength || !assessmentOperatorPattern.MatchString(value) { return "", invalidAssessmentFamily("domain.ParseAssessmentOperator", "operator must be operator: of at most 128 bytes in lowercase letters, digits, '.', '_', or '-'") } return AssessmentOperator(value), nil } // AssessmentReviewStatus is the state of the independent review of one // family version. type AssessmentReviewStatus string const ( // AssessmentReviewPending means no reviewer has judged the version yet. AssessmentReviewPending AssessmentReviewStatus = "pending" // AssessmentReviewApproved means an independent reviewer approved it. AssessmentReviewApproved AssessmentReviewStatus = "approved" // AssessmentReviewRejected means the reviewer did not approve it. AssessmentReviewRejected AssessmentReviewStatus = "rejected" ) func ParseAssessmentReviewStatus(value string) (AssessmentReviewStatus, error) { status := AssessmentReviewStatus(value) switch status { case AssessmentReviewPending, AssessmentReviewApproved, AssessmentReviewRejected: return status, nil default: return "", invalidAssessmentFamily("domain.ParseAssessmentReviewStatus", "review status must be pending, approved, or rejected") } } // AssessmentLifecycle is the publication state of a family version. type AssessmentLifecycle string const ( // AssessmentLifecycleDraft is an imported version that candidates never // see. AssessmentLifecycleDraft AssessmentLifecycle = "draft" // AssessmentLifecyclePublished is a reviewed version that counts for // coverage. AssessmentLifecyclePublished AssessmentLifecycle = "published" // AssessmentLifecycleRetired is a version withdrawn from the bank. AssessmentLifecycleRetired AssessmentLifecycle = "retired" ) func ParseAssessmentLifecycle(value string) (AssessmentLifecycle, error) { lifecycle := AssessmentLifecycle(value) switch lifecycle { case AssessmentLifecycleDraft, AssessmentLifecyclePublished, AssessmentLifecycleRetired: return lifecycle, nil default: return "", invalidAssessmentFamily("domain.ParseAssessmentLifecycle", "lifecycle must be draft, published, or retired") } } // AssessmentAnswerKey is the reference answer description of a family. The // reference answer of a variant itself comes from the family's algorithm. type AssessmentAnswerKey struct { // AnswerFormat is the format of the reference answer: "integer", // "integer_sequence", or "choice". It must match the algorithm of the // generator; a table generator takes "integer" or "choice". AnswerFormat string `json:"answer_format"` // ReferenceSolution describes the reference approach in prose. ReferenceSolution string `json:"reference_solution"` } // AssessmentRubricCriterion is one thing a reviewer or grader looks for. // A criterion has no points: how criteria become a grade is a matter of the // versioned grading policy, not of the family. type AssessmentRubricCriterion struct { ID string `json:"id"` Description string `json:"description"` } // AssessmentRubric is the rubric of a family. Its principle does not depend // on the seed of a variant. type AssessmentRubric struct { Principle string `json:"principle"` Criteria []AssessmentRubricCriterion `json:"criteria"` } func (rubric AssessmentRubric) clone() AssessmentRubric { copied := rubric copied.Criteria = append([]AssessmentRubricCriterion(nil), rubric.Criteria...) return copied } func (rubric AssessmentRubric) validate(location string) error { if err := checkAssessmentText(location, "rubric principle", rubric.Principle); err != nil { return err } if len(rubric.Criteria) == 0 || len(rubric.Criteria) > maxAssessmentRubricCriteria { return invalidAssessmentFamily(location, fmt.Sprintf("rubric must have 1 to %d criteria", maxAssessmentRubricCriteria)) } seen := make(map[string]bool, len(rubric.Criteria)) for _, criterion := range rubric.Criteria { if len(criterion.ID) > maxAssessmentCriterionIDSize || !assessmentCriterionIDPattern.MatchString(criterion.ID) { return invalidAssessmentFamily(location, "rubric criterion ID must be lowercase letters, digits, or '_', starting with a letter") } if seen[criterion.ID] { return invalidAssessmentFamily(location, "rubric criterion IDs must be unique") } seen[criterion.ID] = true if err := checkAssessmentText(location, "rubric criterion description", criterion.Description); err != nil { return err } } return nil } // validate checks the answer key against the answer format that the // generator produces. func (key AssessmentAnswerKey) validate(location, generatorFormat string) error { if key.AnswerFormat != generatorFormat { return invalidAssessmentFamily(location, "answer format does not match the answer format of the generator") } return checkAssessmentText(location, "reference solution", key.ReferenceSolution) } // checkAssessmentText accepts non-empty text without surrounding blanks, and // without control characters other than line breaks and without Unicode // format characters (category Cf) and line and paragraph separators (Zl, Zp). func checkAssessmentText(location, field, value string) error { trimmed := strings.TrimSpace(value) if trimmed == "" || trimmed != value || len(value) > maxAssessmentTextLength { return invalidAssessmentFamily(location, fmt.Sprintf("%s must be 1 to %d bytes without surrounding blanks", field, maxAssessmentTextLength)) } for _, character := range value { if unicode.IsControl(character) && character != '\n' { return invalidAssessmentFamily(location, field+" must not contain control characters") } // Format characters, such as the bidirectional overrides, change how // text is displayed without being visible, and the line and // paragraph separators U+2028 and U+2029 break lines in ways that // plain text does not expect. if unicode.In(character, unicode.Cf, unicode.Zl, unicode.Zp) { return invalidAssessmentFamily(location, field+" must not contain invisible format characters or line and paragraph separators") } } return nil } // AssessmentFamilyCore holds the immutable content of one family version as // the importer supplies it. type AssessmentFamilyCore struct { Key AssessmentFamilyKey Version int32 Category AssessmentCategory Specialization AssessmentSpecialization Title string BundleName AssessmentBundleName Author AssessmentAuthor // Reviewer is empty while the review is pending. Reviewer AssessmentOperator ReviewStatus AssessmentReviewStatus Generator AssessmentSeedGenerator AnswerKey AssessmentAnswerKey Rubric AssessmentRubric } // NewAssessmentFamilyDraftInput is the input of NewAssessmentFamilyDraft. type NewAssessmentFamilyDraftInput = AssessmentFamilyCore func (core AssessmentFamilyCore) clone() AssessmentFamilyCore { copied := core copied.Generator = core.Generator.clone() copied.Rubric = core.Rubric.clone() return copied } // validate checks every field and the rules between them. probe asks the // generator to render probe variants, which an importer does and a read of a // stored row does not. The review rules // mirror the CHECK constraints of assessment_families: a review is pending // exactly while no reviewer is recorded, and the reviewer is never the // author. func (core AssessmentFamilyCore) validate(location string, probe bool) error { if _, err := ParseAssessmentFamilyKey(string(core.Key)); err != nil { return fmt.Errorf("%s - validate key: %w", location, err) } if core.Version <= 0 { return invalidAssessmentFamily(location, "version must be positive") } if _, err := ParseAssessmentCategory(string(core.Category)); err != nil { return fmt.Errorf("%s - validate category: %w", location, err) } if _, err := ParseAssessmentSpecialization(string(core.Specialization)); err != nil { return fmt.Errorf("%s - validate specialization: %w", location, err) } if _, err := ParseAssessmentBundleName(string(core.BundleName)); err != nil { return fmt.Errorf("%s - validate bundle name: %w", location, err) } if _, err := ParseAssessmentAuthor(string(core.Author)); err != nil { return fmt.Errorf("%s - validate author: %w", location, err) } if len(core.Title) > maxAssessmentTitleLength || strings.Contains(core.Title, "\n") || checkAssessmentText(location, "title", core.Title) != nil { return invalidAssessmentFamily(location, "title must be one line of 1 to 200 bytes without surrounding blanks") } if err := core.validateReview(location); err != nil { return err } generatorFormat, err := core.validateGenerator(location, probe) if err != nil { return err } if err := core.AnswerKey.validate(location, generatorFormat); err != nil { return err } return core.Rubric.validate(location) } // validateGenerator validates the generator of either kind and returns the // answer format that it produces. A table generator produces the format its // answer key declares, after the table has been checked against it. func (core AssessmentFamilyCore) validateGenerator(location string, probe bool) (string, error) { if core.Generator.Table != nil { if err := core.Generator.validateTable(location, core.AnswerKey.AnswerFormat, probe); err != nil { return "", err } return core.AnswerKey.AnswerFormat, nil } algorithm, err := core.Generator.validate(location, probe) if err != nil { return "", err } return algorithm.answerFormat, nil } func (core AssessmentFamilyCore) validateReview(location string) error { if _, err := ParseAssessmentReviewStatus(string(core.ReviewStatus)); err != nil { return fmt.Errorf("%s - validate review status: %w", location, err) } if core.ReviewStatus == AssessmentReviewPending { if core.Reviewer != "" { return invalidAssessmentFamily(location, "a pending review has no reviewer") } return nil } if _, err := ParseAssessmentOperator(string(core.Reviewer)); err != nil { return fmt.Errorf("%s - validate reviewer: %w", location, err) } if string(core.Reviewer) == string(core.Author) { return invalidAssessmentFamily(location, "the reviewer must not be the author") } return nil } // The hash schemes of family content. A stored row keeps its own scheme in // the hash_scheme column, and RestoreAssessmentFamily verifies it with that // scheme's function, so a later scheme verifies new rows without invalidating // the old ones. A change of the canonical layout, of a field, or of the // encoding adds a scheme here and to the assessment_families_hash_scheme_known // CHECK; it never edits the function of an existing scheme. // // Scheme 1 hashes the layout of an algorithmic generator. Scheme 2 is the // layout of a table generator, whose canonical content holds the table instead // of an algorithm and its parameters. A new version gets the scheme of its // generator kind, so the content of an algorithmic family keeps the hash it // had before table generators existed, and importing it again is still // recognized as the same version. const ( assessmentHashSchemeAlgorithmic int16 = 1 assessmentHashSchemeTable int16 = 2 ) // hashScheme is the scheme that a new version of this content is stored with. func (core AssessmentFamilyCore) hashScheme() int16 { if core.Generator.Table != nil { return assessmentHashSchemeTable } return assessmentHashSchemeAlgorithmic } // assessmentHashSchemes maps a scheme number to its hash function. It is a // variable only so that a test can register a scheme. var assessmentHashSchemes = map[int16]func(AssessmentFamilyCore) (AssessmentContentHash, error){ assessmentHashSchemeAlgorithmic: contentHashV1, assessmentHashSchemeTable: contentHashV2, } // assessmentCanonicalGeneratorV1 is the generator layout of scheme 1. It is a // type of its own, so that a later field of AssessmentSeedGenerator cannot // change what scheme 1 hashes. type assessmentCanonicalGeneratorV1 struct { Algorithm string `json:"algorithm"` Parameters map[string]AssessmentParameterRange `json:"parameters"` StatementTemplate string `json:"statement_template"` } // assessmentCanonicalGeneratorV2 is the generator layout of scheme 2. type assessmentCanonicalGeneratorV2 struct { StatementTemplate string `json:"statement_template"` Table *AssessmentVariantTable `json:"table"` } // assessmentCanonicalContent is the form that the schemes hash, with the // generator layout of the scheme. The bundle name, the ID, and the lifecycle // are not part of it: they are provenance and state, not content. type assessmentCanonicalContent[Generator any] struct { Key AssessmentFamilyKey `json:"family_key"` Version int32 `json:"version"` Category AssessmentCategory `json:"category"` Specialization AssessmentSpecialization `json:"specialization"` Title string `json:"title"` Author AssessmentAuthor `json:"author"` Reviewer AssessmentOperator `json:"reviewer,omitempty"` ReviewStatus AssessmentReviewStatus `json:"review_status"` Generator Generator `json:"seed_generator"` AnswerKey AssessmentAnswerKey `json:"answer_key"` Rubric AssessmentRubric `json:"rubric"` } // AssessmentContentHash is the SHA-256 of the canonical content. type AssessmentContentHash [sha256.Size]byte // contentHash hashes the content with the named scheme, or returns // ErrInvalidAssessmentFamily for a scheme that this code does not know. func (core AssessmentFamilyCore) contentHash(scheme int16) (AssessmentContentHash, error) { hashContent, ok := assessmentHashSchemes[scheme] if !ok { return AssessmentContentHash{}, invalidAssessmentFamily("AssessmentFamilyCore.contentHash", "hash scheme is unknown") } return hashContent(core) } func contentHashV1(core AssessmentFamilyCore) (AssessmentContentHash, error) { if core.Generator.Table != nil { return AssessmentContentHash{}, invalidAssessmentFamily("domain.contentHashV1", "scheme 1 does not cover a table generator") } return hashCanonicalContent("domain.contentHashV1", core, assessmentCanonicalGeneratorV1{ Algorithm: core.Generator.Algorithm, Parameters: core.Generator.Parameters, StatementTemplate: core.Generator.StatementTemplate, }) } func contentHashV2(core AssessmentFamilyCore) (AssessmentContentHash, error) { if core.Generator.Table == nil || core.Generator.Algorithm != "" || len(core.Generator.Parameters) != 0 { return AssessmentContentHash{}, invalidAssessmentFamily("domain.contentHashV2", "scheme 2 covers only a table generator") } return hashCanonicalContent("domain.contentHashV2", core, assessmentCanonicalGeneratorV2{ StatementTemplate: core.Generator.StatementTemplate, Table: core.Generator.Table, }) } func hashCanonicalContent[Generator any](location string, core AssessmentFamilyCore, generator Generator) (AssessmentContentHash, error) { encoded, err := json.Marshal(assessmentCanonicalContent[Generator]{ Key: core.Key, Version: core.Version, Category: core.Category, Specialization: core.Specialization, Title: core.Title, Author: core.Author, Reviewer: core.Reviewer, ReviewStatus: core.ReviewStatus, Generator: generator, AnswerKey: core.AnswerKey, Rubric: core.Rubric, }) if err != nil { return AssessmentContentHash{}, fmt.Errorf("%s - encode canonical content: %w", location, err) } return sha256.Sum256(encoded), nil } // AssessmentFamilyDraft is a version that is not stored yet. It has an ID, a // validated content, and its hash, but no creation time: the database sets // that. Every stored version starts as a draft, whatever its review says. type AssessmentFamilyDraft struct { id AssessmentFamilyID core AssessmentFamilyCore hash AssessmentContentHash scheme int16 } // NewAssessmentFamilyDraft validates the content, hashes it, and assigns a // UUIDv7. The family can be generated for review before it is published. func NewAssessmentFamilyDraft(input NewAssessmentFamilyDraftInput) (AssessmentFamilyDraft, error) { const location = "domain.NewAssessmentFamilyDraft" core := input.clone() if err := core.validate(location, true); err != nil { return AssessmentFamilyDraft{}, err } scheme := core.hashScheme() hash, err := core.contentHash(scheme) if err != nil { return AssessmentFamilyDraft{}, err } id, err := NewAssessmentFamilyID() if err != nil { return AssessmentFamilyDraft{}, fmt.Errorf("%s - assign ID: %w", location, err) } return AssessmentFamilyDraft{id: id, core: core, hash: hash, scheme: scheme}, nil } func (draft AssessmentFamilyDraft) ID() AssessmentFamilyID { return draft.id } // Core returns a copy of the content. func (draft AssessmentFamilyDraft) Core() AssessmentFamilyCore { return draft.core.clone() } func (draft AssessmentFamilyDraft) ContentHash() AssessmentContentHash { return draft.hash } // HashScheme is the scheme of ContentHash, stored beside it. func (draft AssessmentFamilyDraft) HashScheme() int16 { return draft.scheme } // IsZero reports a draft not built by NewAssessmentFamilyDraft. func (draft AssessmentFamilyDraft) IsZero() bool { return draft.id.IsZero() } // SeedGeneratorJSON returns the canonical document stored in the // seed_generator column. func (draft AssessmentFamilyDraft) SeedGeneratorJSON() ([]byte, error) { return marshalAssessmentDocument("AssessmentFamilyDraft.SeedGeneratorJSON", draft.core.Generator) } // AnswerKeyJSON returns the canonical document stored in the answer_key // column. func (draft AssessmentFamilyDraft) AnswerKeyJSON() ([]byte, error) { return marshalAssessmentDocument("AssessmentFamilyDraft.AnswerKeyJSON", draft.core.AnswerKey) } // RubricJSON returns the canonical document stored in the rubric column. func (draft AssessmentFamilyDraft) RubricJSON() ([]byte, error) { return marshalAssessmentDocument("AssessmentFamilyDraft.RubricJSON", draft.core.Rubric) } func marshalAssessmentDocument(location string, value any) ([]byte, error) { encoded, err := json.Marshal(value) if err != nil { return nil, fmt.Errorf("%s - encode document: %w", location, err) } return encoded, nil } // StoredAssessmentFamily is an assessment_families row as storage reads it. // Reviewer, PublishedBy, and RetiredBy are empty for a NULL column, and a // zero PublishedAt or RetiredAt means NULL. type StoredAssessmentFamily struct { ID AssessmentFamilyID FamilyKey string Version int32 Category string Specialization string Title string BundleName string Author string Reviewer string ReviewStatus string SeedGenerator []byte AnswerKey []byte Rubric []byte ContentHash []byte HashScheme int16 Lifecycle string CreatedAt time.Time PublishedAt time.Time PublishedBy string RetiredAt time.Time RetiredBy string } // AssessmentFamily is one stored, immutable version of a family. Only // RestoreAssessmentFamily builds it; accessors return copies. type AssessmentFamily struct { id AssessmentFamilyID core AssessmentFamilyCore hash AssessmentContentHash scheme int16 lifecycle AssessmentLifecycle createdAt time.Time publishedAt time.Time publishedBy AssessmentOperator retiredAt time.Time retiredBy AssessmentOperator } // RestoreAssessmentFamily rebuilds a stored version. It decodes every // document strictly, validates the content like NewAssessmentFamilyDraft, // and requires the SHA-256 of the canonical content, built with the scheme // that the row names, to equal the stored hash; otherwise it returns // ErrAssessmentFamilyIntegrity, and an unknown scheme returns // ErrInvalidAssessmentFamily. jsonb normalizes // stored text, so the hash is never compared with stored bytes directly. func RestoreAssessmentFamily(stored StoredAssessmentFamily) (AssessmentFamily, error) { const location = "domain.RestoreAssessmentFamily" if stored.ID.IsZero() { return AssessmentFamily{}, invalidAssessmentFamily(location, "ID must not be nil") } lifecycle, err := ParseAssessmentLifecycle(stored.Lifecycle) if err != nil { return AssessmentFamily{}, fmt.Errorf("%s - parse lifecycle: %w", location, err) } if stored.CreatedAt.IsZero() { return AssessmentFamily{}, invalidAssessmentFamily(location, "creation time must be set") } core := AssessmentFamilyCore{ Key: AssessmentFamilyKey(stored.FamilyKey), Version: stored.Version, Category: AssessmentCategory(stored.Category), Specialization: AssessmentSpecialization(stored.Specialization), Title: stored.Title, BundleName: AssessmentBundleName(stored.BundleName), Author: AssessmentAuthor(stored.Author), Reviewer: AssessmentOperator(stored.Reviewer), ReviewStatus: AssessmentReviewStatus(stored.ReviewStatus), } if err := decodeAssessmentDocument(stored.SeedGenerator, &core.Generator); err != nil { return AssessmentFamily{}, fmt.Errorf("%s - decode seed generator: %w", location, err) } if err := decodeAssessmentDocument(stored.AnswerKey, &core.AnswerKey); err != nil { return AssessmentFamily{}, fmt.Errorf("%s - decode answer key: %w", location, err) } if err := decodeAssessmentDocument(stored.Rubric, &core.Rubric); err != nil { return AssessmentFamily{}, fmt.Errorf("%s - decode rubric: %w", location, err) } if err := core.validate(location, false); err != nil { return AssessmentFamily{}, err } hash, err := core.contentHash(stored.HashScheme) if err != nil { return AssessmentFamily{}, fmt.Errorf("%s - hash content: %w", location, err) } if len(stored.ContentHash) != len(hash) || subtle.ConstantTimeCompare(stored.ContentHash, hash[:]) != 1 { return AssessmentFamily{}, fmt.Errorf("%s - verify content hash: %w", location, ErrAssessmentFamilyIntegrity) } if err := checkLifecycleStamps(location, lifecycle, core, stored); err != nil { return AssessmentFamily{}, err } for _, actor := range []string{stored.PublishedBy, stored.RetiredBy} { if actor == "" { continue } if _, err := ParseAssessmentOperator(actor); err != nil { return AssessmentFamily{}, fmt.Errorf("%s - parse publishing operator: %w", location, err) } } return AssessmentFamily{ id: stored.ID, core: core, hash: hash, scheme: stored.HashScheme, lifecycle: lifecycle, createdAt: stored.CreatedAt, publishedAt: stored.PublishedAt, publishedBy: AssessmentOperator(stored.PublishedBy), retiredAt: stored.RetiredAt, retiredBy: AssessmentOperator(stored.RetiredBy), }, nil } func checkLifecycleStamps(location string, lifecycle AssessmentLifecycle, core AssessmentFamilyCore, stored StoredAssessmentFamily) error { published, retired := !stored.PublishedAt.IsZero(), !stored.RetiredAt.IsZero() if published != (stored.PublishedBy != "") || retired != (stored.RetiredBy != "") { return invalidAssessmentFamily(location, "a publication or retirement time comes with the operator who made it, and only with it") } switch { case lifecycle == AssessmentLifecycleDraft && (published || retired): return invalidAssessmentFamily(location, "a draft has no publication or retirement time") case lifecycle == AssessmentLifecyclePublished && (!published || retired): return invalidAssessmentFamily(location, "a published version has a publication time and no retirement time") case lifecycle == AssessmentLifecycleRetired && (!published || !retired): return invalidAssessmentFamily(location, "a retired version has publication and retirement times") case lifecycle != AssessmentLifecycleDraft && core.ReviewStatus != AssessmentReviewApproved: return invalidAssessmentFamily(location, "a published or retired version needs an approved review") } return nil } // decodeAssessmentDocument decodes one JSON document strictly: an unknown // field or trailing data is an error, so a document of a different layout // never decodes into a partly empty value. func decodeAssessmentDocument(document []byte, target any) error { decoder := json.NewDecoder(bytes.NewReader(document)) decoder.DisallowUnknownFields() if err := decoder.Decode(target); err != nil { return fmt.Errorf("%w: %w", ErrInvalidAssessmentFamily, err) } if decoder.More() { return fmt.Errorf("%w: trailing data after the document", ErrInvalidAssessmentFamily) } return nil } func (family AssessmentFamily) ID() AssessmentFamilyID { return family.id } // Core returns a copy of the content. func (family AssessmentFamily) Core() AssessmentFamilyCore { return family.core.clone() } func (family AssessmentFamily) Key() AssessmentFamilyKey { return family.core.Key } func (family AssessmentFamily) Version() int32 { return family.core.Version } func (family AssessmentFamily) Category() AssessmentCategory { return family.core.Category } func (family AssessmentFamily) Author() AssessmentAuthor { return family.core.Author } // Reviewer is empty while the review is pending. func (family AssessmentFamily) Reviewer() AssessmentOperator { return family.core.Reviewer } func (family AssessmentFamily) ReviewStatus() AssessmentReviewStatus { return family.core.ReviewStatus } func (family AssessmentFamily) AnswerKey() AssessmentAnswerKey { return family.core.AnswerKey } // Rubric returns a copy of the rubric. func (family AssessmentFamily) Rubric() AssessmentRubric { return family.core.Rubric.clone() } func (family AssessmentFamily) ContentHash() AssessmentContentHash { return family.hash } // HashScheme is the scheme that ContentHash was verified with. func (family AssessmentFamily) HashScheme() int16 { return family.scheme } func (family AssessmentFamily) Lifecycle() AssessmentLifecycle { return family.lifecycle } func (family AssessmentFamily) CreatedAt() time.Time { return family.createdAt } // PublishedAt returns the publication time, or false for a draft. func (family AssessmentFamily) PublishedAt() (time.Time, bool) { return family.publishedAt, !family.publishedAt.IsZero() } // PublishedBy is the operator who published the version, or empty for a // draft. It is a declared value of the caller, not an authenticated identity, // until operator accounts exist. func (family AssessmentFamily) PublishedBy() AssessmentOperator { return family.publishedBy } // RetiredBy is the operator who retired the version, or empty. func (family AssessmentFamily) RetiredBy() AssessmentOperator { return family.retiredBy } // IsZero reports an AssessmentFamily not built by RestoreAssessmentFamily. func (family AssessmentFamily) IsZero() bool { return family.id.IsZero() } // CheckPublishable reports why the version cannot be published, or nil. A // version is published only while it is a draft and only with an approved // review by a reviewer who is not its author. The database enforces the same // rules. func (family AssessmentFamily) CheckPublishable() error { switch { case family.lifecycle != AssessmentLifecycleDraft: return NewAssessmentRefusal(RefusalNotDraft, "only a draft version can be published") case family.core.Reviewer == "": return NewAssessmentRefusal(RefusalReviewerMissing, "the version has no independent reviewer") case family.core.ReviewStatus != AssessmentReviewApproved: return NewAssessmentRefusal(RefusalReviewNotApproved, "the review of the version is not approved") default: return nil } } // CheckRetirable reports why the version cannot be retired, or nil. func (family AssessmentFamily) CheckRetirable() error { if family.lifecycle != AssessmentLifecyclePublished { return NewAssessmentRefusal(RefusalNotPublished, "only a published version can be retired") } return nil } // RequiredPublishedAssessmentFamilies returns how many distinct published // families a category needs under a grading policy: max_scored_items plus // seed_items of the stop rule. The owner accepted this rule on 2026-10-06. // The reason: a family gives at most one item to an attempt, so a full // adaptive attempt, which can run to the maximum of scored items and also // carries the seed items, cannot run out of families. Both numbers are read // from the policy; the bank defines no threshold of its own, and a policy // without them is refused with RefusalGradingPolicyMissing. The trigger of // assessment_category_openings reads the same two document paths; an // integration test keeps them equal. func RequiredPublishedAssessmentFamilies(policy ProductPolicy) (int32, error) { rule := policy.Assessment.StopRule if rule.MaxScoredItems <= 0 || rule.SeedItems < 0 { return 0, NewAssessmentRefusal(RefusalGradingPolicyMissing, "the grading policy has no maximum of scored items") } return rule.MaxScoredItems + rule.SeedItems, nil } // AssessmentCategoryOpeningDraft is an opening that is not stored yet. type AssessmentCategoryOpeningDraft struct { id uuid.UUID category AssessmentCategory policyVersionID PolicyVersionID openedBy AssessmentOperator requiredFamilies int32 } // NewAssessmentCategoryOpeningDraft checks that a category can open under the // referenced grading policy version and returns the opening to store. It // refuses with RefusalGradingPolicyMissing without a policy version and with // RefusalCoverageInsufficient when the published families do not reach the // policy's requirement. publishedFamilies is the count of distinct families // with a published version. func NewAssessmentCategoryOpeningDraft( category AssessmentCategory, policy PolicyVersion, publishedFamilies int32, openedBy AssessmentOperator, ) (AssessmentCategoryOpeningDraft, error) { const location = "domain.NewAssessmentCategoryOpeningDraft" if _, err := ParseAssessmentCategory(string(category)); err != nil { return AssessmentCategoryOpeningDraft{}, fmt.Errorf("%s - validate category: %w", location, err) } if _, err := ParseAssessmentOperator(string(openedBy)); err != nil { return AssessmentCategoryOpeningDraft{}, fmt.Errorf("%s - validate operator: %w", location, err) } if policy.IsZero() { return AssessmentCategoryOpeningDraft{}, NewAssessmentRefusal(RefusalGradingPolicyMissing, "a category opens only under a versioned grading policy") } required, err := RequiredPublishedAssessmentFamilies(policy.Policy()) if err != nil { return AssessmentCategoryOpeningDraft{}, err } if publishedFamilies < required { return AssessmentCategoryOpeningDraft{}, NewAssessmentRefusal(RefusalCoverageInsufficient, fmt.Sprintf("category has %d published families, grading policy version %d requires %d", publishedFamilies, policy.Version(), required)) } id, err := uuid.NewV7() if err != nil { return AssessmentCategoryOpeningDraft{}, fmt.Errorf("%s - assign ID: %w", location, err) } return AssessmentCategoryOpeningDraft{ id: id, category: category, policyVersionID: policy.ID(), openedBy: openedBy, requiredFamilies: required, }, nil } func (draft AssessmentCategoryOpeningDraft) ID() uuid.UUID { return draft.id } func (draft AssessmentCategoryOpeningDraft) Category() AssessmentCategory { return draft.category } func (draft AssessmentCategoryOpeningDraft) PolicyVersionID() PolicyVersionID { return draft.policyVersionID } func (draft AssessmentCategoryOpeningDraft) OpenedBy() AssessmentOperator { return draft.openedBy } func (draft AssessmentCategoryOpeningDraft) RequiredFamilies() int32 { return draft.requiredFamilies } // IsZero reports a draft not built by NewAssessmentCategoryOpeningDraft. func (draft AssessmentCategoryOpeningDraft) IsZero() bool { return draft.id == uuid.Nil } // AssessmentCategoryOpening is a stored opening: the proof that a category // was available at OpenedAt under one policy version. type AssessmentCategoryOpening struct { ID uuid.UUID Category AssessmentCategory PolicyVersionID PolicyVersionID OpenedBy AssessmentOperator RequiredFamilies int32 PublishedFamilies int32 OpenedAt time.Time }