package domain import ( "errors" "fmt" "slices" "strings" "time" "github.com/google/uuid" ) // ErrInvalidEvidence reports a skill evidence value that breaks a rule of the // evidence model. var ErrInvalidEvidence = errors.New("invalid skill evidence") // EvidenceKind separates what a person stated from what a system observed. A // claim never becomes a measurement by repetition. type EvidenceKind string const ( EvidenceKindClaim EvidenceKind = "claim" EvidenceKindMeasurement EvidenceKind = "measurement" ) // EvidenceSourceType names where a fact comes from. type EvidenceSourceType string // EvidenceSourceAssessmentResult is a real (root or corrective) assessment // result that confirmed a grade. An express training run is never a source. const EvidenceSourceAssessmentResult EvidenceSourceType = "assessment_result" // EvidenceAttribution says whose contribution a fact is. type EvidenceAttribution string const ( EvidenceAttributionPersonal EvidenceAttribution = "personal" EvidenceAttributionTeamRole EvidenceAttribution = "team_role" EvidenceAttributionTeamUnattributed EvidenceAttribution = "team_unattributed" ) // EvidenceTrust is the strength of a confirmation: 0 stated, 1 an observable // online result without a reliable confirmation of the identity or the // authorship, 2 tied to a confirmed identity or an independent party, 3 an // in-person check. type EvidenceTrust uint8 const ( EvidenceTrustStated EvidenceTrust = 0 // EvidenceTrustOnlineUnconfirmed is the level of an online assessment: it // is unproctored and nothing confirms who answered. The database function // that projects a result writes this value, and a test keeps the two equal. EvidenceTrustOnlineUnconfirmed EvidenceTrust = 1 EvidenceTrustIdentityTied EvidenceTrust = 2 EvidenceTrustInPerson EvidenceTrust = 3 ) // EvidenceVisibility says whether a fact may take part in what an // organization reads. It never publishes a fact by itself. type EvidenceVisibility string const ( EvidenceVisibilityVisible EvidenceVisibility = "visible" EvidenceVisibilityHidden EvidenceVisibility = "hidden" ) // EvidenceSkillCode is a skill tag from a closed set: the specialization codes // of the catalog and the technology codes of the anonymous card. type EvidenceSkillCode string // EvidenceSkillOfSpecialization tags a fact with the specialization of a // category. func EvidenceSkillOfSpecialization(code SpecializationCode) EvidenceSkillCode { return EvidenceSkillCode(code) } // IsKnown reports whether code belongs to the closed skill set. func (code EvidenceSkillCode) IsKnown() bool { return SpecializationCode(code).IsKnown() || CandidateViewSkillCode(code).IsKnown() } // EvidenceSkillCodes returns the closed skill set in its stored order. func EvidenceSkillCodes() []EvidenceSkillCode { codes := make([]EvidenceSkillCode, 0, len(specializationCodes)+len(candidateViewSkillCodes)) for _, code := range specializationCodes { codes = append(codes, EvidenceSkillCode(code)) } for _, code := range candidateViewSkillCodes { codes = append(codes, EvidenceSkillCode(code)) } return codes } // EvidenceResult is what a fact says: the grade that was passed, the basis of // the measurement, and its calibration. It carries no score, answer, item, // failure, or anti-cheat data. type EvidenceResult struct { Grade GradeCode Basis AssessmentCategorySource CalibrationStatus AssessmentCategoryCalibrationStatus } // EvidenceFactSnapshot is the stored shape of one fact of a candidate. type EvidenceFactSnapshot struct { ID uuid.UUID CandidateID uuid.UUID Kind EvidenceKind SourceType EvidenceSourceType // EventID is the source event and ResultID its immutable result. For an // assessment both are the attempt. EventID uuid.UUID ResultID uuid.UUID Skills []EvidenceSkillCode Result EvidenceResult Attribution EvidenceAttribution Trust EvidenceTrust OccurredAt time.Time Visibility EvidenceVisibility } // EvidenceFact is one independent fact: one source event. The skills of the // event are tags of the fact, so adding a tag never adds a fact. type EvidenceFact struct { snapshot EvidenceFactSnapshot } // RestoreEvidenceFact validates a stored fact against the rules of the model: // the trust level fits the kind, an assessment fact is a personal measurement // below the in-person level, and the skills are known, distinct, and ordered. func RestoreEvidenceFact(snapshot EvidenceFactSnapshot) (EvidenceFact, error) { const location = "domain.RestoreEvidenceFact" if snapshot.ID == uuid.Nil || snapshot.CandidateID == uuid.Nil || snapshot.EventID == uuid.Nil || snapshot.ResultID == uuid.Nil || snapshot.OccurredAt.IsZero() { return EvidenceFact{}, fmt.Errorf("%s - identities and time are required: %w", location, ErrInvalidEvidence) } if !snapshot.Kind.valid() || !snapshot.Attribution.valid() || !snapshot.Visibility.valid() || !validEvidenceTrustForKind(snapshot.Kind, snapshot.Trust) { return EvidenceFact{}, fmt.Errorf("%s - kind, trust, attribution, or visibility is invalid: %w", location, ErrInvalidEvidence) } if !isOnlineAssessmentEvidence(snapshot) { return EvidenceFact{}, fmt.Errorf("%s - an assessment fact is a personal online measurement of its own attempt: %w", location, ErrInvalidEvidence) } if err := validateEvidenceResult(snapshot.Result); err != nil { return EvidenceFact{}, fmt.Errorf("%s - result: %w", location, err) } skills, err := canonicalEvidenceSkills(snapshot.Skills) if err != nil { return EvidenceFact{}, fmt.Errorf("%s - skills: %w", location, err) } snapshot.Skills = skills snapshot.OccurredAt = snapshot.OccurredAt.UTC().Truncate(time.Microsecond) return EvidenceFact{snapshot: snapshot}, nil } // isOnlineAssessmentEvidence reports whether a fact has the shape of the only // source that exists: a personal measurement of an assessment attempt that is // below the in-person level. func isOnlineAssessmentEvidence(snapshot EvidenceFactSnapshot) bool { return snapshot.SourceType == EvidenceSourceAssessmentResult && snapshot.Kind == EvidenceKindMeasurement && snapshot.Attribution == EvidenceAttributionPersonal && snapshot.EventID == snapshot.ResultID && snapshot.Trust <= EvidenceTrustIdentityTied } // Snapshot returns a copy of the stored shape. func (fact EvidenceFact) Snapshot() EvidenceFactSnapshot { snapshot := fact.snapshot snapshot.Skills = slices.Clone(snapshot.Skills) return snapshot } // IsZero reports whether the fact is the zero value. func (fact EvidenceFact) IsZero() bool { return fact.snapshot.ID == uuid.Nil } // Bounds of the year that an organization reads, so a stored value outside a // sane range is refused instead of shown. const ( minEvidenceObservedYear = 2000 maxEvidenceObservedYear = 9999 ) // EvidenceOrganizationFactInput is the allowlisted shape of the one fact that // supports a category of the card: the skill, the grade that was passed, the // trust level, the year of the event, and the basis and calibration of the // method, which are the same for every candidate. It has no identifier, no // exact time, and no source detail. type EvidenceOrganizationFactInput struct { Skill EvidenceSkillCode Grade GradeCode Trust EvidenceTrust Basis AssessmentCategorySource CalibrationStatus AssessmentCategoryCalibrationStatus ObservedYear int32 } // EvidenceOrganizationFact is one fact in the organization projection. type EvidenceOrganizationFact struct { input EvidenceOrganizationFactInput } // NewEvidenceOrganizationFact validates the allowlisted organization shape. The // fact is always a measurement, so its trust is at least 1. func NewEvidenceOrganizationFact(input EvidenceOrganizationFactInput) (EvidenceOrganizationFact, error) { const location = "domain.NewEvidenceOrganizationFact" if !input.Skill.IsKnown() || !input.Grade.IsKnown() || !validEvidenceTrustForKind(EvidenceKindMeasurement, input.Trust) { return EvidenceOrganizationFact{}, fmt.Errorf("%s - skill, grade, or trust is invalid: %w", location, ErrInvalidEvidence) } if err := validateEvidenceResult(EvidenceResult{Grade: input.Grade, Basis: input.Basis, CalibrationStatus: input.CalibrationStatus}); err != nil { return EvidenceOrganizationFact{}, fmt.Errorf("%s - result: %w", location, err) } if input.ObservedYear < minEvidenceObservedYear || input.ObservedYear > maxEvidenceObservedYear { return EvidenceOrganizationFact{}, fmt.Errorf("%s - observed year is out of range: %w", location, ErrInvalidEvidence) } return EvidenceOrganizationFact{input: input}, nil } // Input returns the allowlisted shape. func (fact EvidenceOrganizationFact) Input() EvidenceOrganizationFactInput { return fact.input } func (kind EvidenceKind) valid() bool { return kind == EvidenceKindClaim || kind == EvidenceKindMeasurement } func (attribution EvidenceAttribution) valid() bool { switch attribution { case EvidenceAttributionPersonal, EvidenceAttributionTeamRole, EvidenceAttributionTeamUnattributed: return true default: return false } } func (visibility EvidenceVisibility) valid() bool { return visibility == EvidenceVisibilityVisible || visibility == EvidenceVisibilityHidden } // validEvidenceTrustForKind keeps a claim at level 0 and a measurement at // levels 1 to 3. func validEvidenceTrustForKind(kind EvidenceKind, trust EvidenceTrust) bool { switch kind { case EvidenceKindClaim: return trust == EvidenceTrustStated case EvidenceKindMeasurement: return trust >= EvidenceTrustOnlineUnconfirmed && trust <= EvidenceTrustInPerson default: return false } } func validateEvidenceResult(result EvidenceResult) error { if !result.Grade.IsKnown() || result.Basis != AssessmentCategorySourceSyntheticDemo || result.CalibrationStatus != AssessmentCategoryCalibrationUncalibrated { return fmt.Errorf("grade, basis, or calibration is not known: %w", ErrInvalidEvidence) } return nil } // canonicalEvidenceSkills returns the skills sorted, after checking that there // is at least one, that each is known, and that none repeats. func canonicalEvidenceSkills(skills []EvidenceSkillCode) ([]EvidenceSkillCode, error) { if len(skills) == 0 || len(skills) > len(EvidenceSkillCodes()) { return nil, fmt.Errorf("a fact needs between one and every known skill: %w", ErrInvalidEvidence) } ordered := slices.Clone(skills) slices.SortFunc(ordered, func(left, right EvidenceSkillCode) int { return strings.Compare(string(left), string(right)) }) for index, code := range ordered { if !code.IsKnown() { return nil, fmt.Errorf("skill %q is not known: %w", string(code), ErrInvalidEvidence) } if index > 0 && ordered[index-1] == code { return nil, fmt.Errorf("skill %q repeats: %w", string(code), ErrInvalidEvidence) } } return ordered, nil }