feat: add assessment, privacy and support flows

This commit is contained in:
TakuyaYagam1 committed 2026-10-08 08:08:25 +03:00
1 parent ee3738ee73
commit e4f24fa202
339 files changed
+56454 -1126

No files matched your search

@@ -0,0 +1,657 @@
package domain
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"math"
"strconv"
"strings"
"time"
"github.com/google/uuid"
)
// AssessmentBasicScore is the reproducible raw result of a demo_basic run.
type AssessmentBasicScore struct {
Points int32 `json:"points"`
MaxPoints int32 `json:"max_points"`
PassPoints int32 `json:"pass_points"`
}
// AssessmentAttemptDecision is the immutable completion data derived from
// answers and the policy pinned to the attempt.
type AssessmentAttemptDecision struct {
Outcome AssessmentAttemptOutcome
Score *AssessmentBasicScore
Rationale AssessmentAttemptDecisionRationale
}
type numberAssessmentAnswer struct {
Format string `json:"format"`
Number json.RawMessage `json:"number"`
}
type orderAssessmentAnswer struct {
Format string `json:"format"`
ElementIDs []string `json:"element_ids"`
}
// CanonicalAssessmentAnswer validates and canonicalizes a request answer
// before its idempotency fingerprint is created.
func CanonicalAssessmentAnswer(answer json.RawMessage) (json.RawMessage, error) {
const location = "domain.CanonicalAssessmentAnswer"
format, err := assessmentAnswerFormat(answer)
if err != nil {
return nil, fmt.Errorf("%s - answer format is invalid: %w", location, ErrInvalidAssessmentAttempt)
}
switch format {
case "number":
canonical, err := canonicalNumberAssessmentAnswer(answer)
if err != nil {
return nil, fmt.Errorf("%s - number answer is invalid or exceeds its bound: %w", location, err)
}
return canonical, nil
case "order":
canonical, err := canonicalOrderAssessmentAnswer(answer)
if err != nil {
return nil, fmt.Errorf("%s - order answer is invalid or exceeds its bound: %w", location, err)
}
return canonical, nil
default:
return nil, fmt.Errorf("%s - answer format is not supported by the current bank: %w", location, ErrInvalidAssessmentAttempt)
}
}
func assessmentAnswerFormat(answer json.RawMessage) (string, error) {
if len(answer) == 0 || len(answer) > maxAssessmentAttemptAnswerBytes {
return "", ErrInvalidAssessmentAttempt
}
var header struct {
Format string `json:"format"`
}
if err := json.Unmarshal(answer, &header); err != nil || header.Format == "" {
return "", ErrInvalidAssessmentAttempt
}
return header.Format, nil
}
func canonicalNumberAssessmentAnswer(answer []byte) ([]byte, error) {
var submitted numberAssessmentAnswer
if err := decodeStrictAssessmentAnswer(answer, &submitted); err != nil || len(submitted.Number) == 0 {
return nil, ErrInvalidAssessmentAttempt
}
number, err := canonicalAssessmentNumber(submitted.Number)
if err != nil {
return nil, err
}
canonical, err := json.Marshal(struct {
Format string `json:"format"`
Number json.RawMessage `json:"number"`
}{Format: "number", Number: json.RawMessage(number)})
if err != nil || len(canonical) > maxAssessmentAttemptAnswerBytes {
return nil, ErrInvalidAssessmentAttempt
}
return canonical, nil
}
func canonicalOrderAssessmentAnswer(answer []byte) ([]byte, error) {
var submitted orderAssessmentAnswer
if err := decodeStrictAssessmentAnswer(answer, &submitted); err != nil || len(submitted.ElementIDs) < 2 || len(submitted.ElementIDs) > 20 {
return nil, ErrInvalidAssessmentAttempt
}
if err := validateAssessmentOrderElements(submitted.ElementIDs); err != nil {
return nil, err
}
canonical, err := json.Marshal(map[string]any{"format": "order", "element_ids": submitted.ElementIDs})
if err != nil || len(canonical) > maxAssessmentAttemptAnswerBytes {
return nil, ErrInvalidAssessmentAttempt
}
return canonical, nil
}
func validateAssessmentOrderElements(elementIDs []string) error {
seen := make(map[string]struct{}, len(elementIDs))
for _, elementID := range elementIDs {
if !assessmentPublicTaskElementIDPattern.MatchString(elementID) {
return ErrInvalidAssessmentAttempt
}
if _, exists := seen[elementID]; exists {
return ErrInvalidAssessmentAttempt
}
seen[elementID] = struct{}{}
}
return nil
}
// CanonicalAssessmentAnswerForVariant accepts only the answer formats
// currently produced by the reviewed assessment bank. The returned JSON is
// stable for idempotency and preserves exact sequence semantics for orders.
func CanonicalAssessmentAnswerForVariant(answer json.RawMessage, variant AssessmentVariant) (json.RawMessage, bool, error) {
const location = "domain.CanonicalAssessmentAnswerForVariant"
canonical, err := CanonicalAssessmentAnswer(answer)
if err != nil {
return nil, false, fmt.Errorf("%s - canonicalize answer: %w", location, err)
}
switch variant.AnswerFormat {
case AnswerFormatInteger:
correct, err := assessmentIntegerAnswerIsCorrect(canonical, variant.ReferenceAnswer)
if err != nil {
return nil, false, fmt.Errorf("%s - compare frozen integer key: %w", location, err)
}
return canonical, correct, nil
case AnswerFormatIntegerSequence:
correct, err := assessmentOrderAnswerIsCorrect(canonical, variant)
if err != nil {
return nil, false, fmt.Errorf("%s - compare frozen order key: %w", location, err)
}
return canonical, correct, nil
default:
return nil, false, fmt.Errorf("%s - frozen answer format is unsupported: %w", location, ErrInvalidAssessmentAttempt)
}
}
func assessmentIntegerAnswerIsCorrect(canonical []byte, referenceAnswer string) (bool, error) {
var submitted numberAssessmentAnswer
if err := decodeStrictAssessmentAnswer(canonical, &submitted); err != nil || submitted.Format != "number" || len(submitted.Number) == 0 {
return false, ErrInvalidAssessmentAttempt
}
reference, err := strconv.ParseInt(referenceAnswer, 10, 64)
if err != nil {
return false, ErrInvalidAssessmentAttempt
}
return string(submitted.Number) == strconv.FormatInt(reference, 10), nil
}
func assessmentOrderAnswerIsCorrect(canonical []byte, variant AssessmentVariant) (bool, error) {
var submitted orderAssessmentAnswer
if err := decodeStrictAssessmentAnswer(canonical, &submitted); err != nil || submitted.Format != "order" {
return false, ErrInvalidAssessmentAttempt
}
taskCount, ok := variant.Parameters["tasks"]
if !ok || taskCount < 2 || taskCount > 20 || len(submitted.ElementIDs) != int(taskCount) {
return false, ErrInvalidAssessmentAttempt
}
if err := validateAssessmentOrderElements(submitted.ElementIDs); err != nil || !assessmentOrderHasEveryTask(submitted.ElementIDs, taskCount) {
return false, ErrInvalidAssessmentAttempt
}
return assessmentOrderMatchesReference(submitted.ElementIDs, variant.ReferenceAnswer, taskCount)
}
func assessmentOrderHasEveryTask(elementIDs []string, taskCount int32) bool {
seen := make(map[string]struct{}, len(elementIDs))
for _, elementID := range elementIDs {
seen[elementID] = struct{}{}
}
for ordinal := int32(1); ordinal <= taskCount; ordinal++ {
if _, exists := seen["job_"+strconv.FormatInt(int64(ordinal), 10)]; !exists {
return false
}
}
return true
}
func assessmentOrderMatchesReference(elementIDs []string, referenceAnswer string, taskCount int32) (bool, error) {
reference := strings.Fields(referenceAnswer)
if len(reference) != int(taskCount) {
return false, ErrInvalidAssessmentAttempt
}
for index, token := range reference {
ordinal, err := strconv.ParseInt(token, 10, 32)
if err != nil || ordinal < 1 || ordinal > int64(taskCount) {
return false, ErrInvalidAssessmentAttempt
}
if elementIDs[index] != "job_"+strconv.FormatInt(ordinal, 10) {
return false, nil
}
}
return true, nil
}
func decodeStrictAssessmentAnswer(encoded []byte, target any) error {
if len(encoded) == 0 || len(encoded) > maxAssessmentAttemptAnswerBytes || !json.Valid(encoded) {
return ErrInvalidAssessmentAttempt
}
decoder := json.NewDecoder(bytes.NewReader(encoded))
decoder.UseNumber()
decoder.DisallowUnknownFields()
if err := decoder.Decode(target); err != nil {
return errors.Join(ErrInvalidAssessmentAttempt, err)
}
var extra any
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
return ErrInvalidAssessmentAttempt
}
return nil
}
func canonicalAssessmentNumber(encoded json.RawMessage) (string, error) {
if len(encoded) == 0 || len(encoded) > maxAssessmentAttemptAnswerBytes || !json.Valid(encoded) {
return "", ErrInvalidAssessmentAttempt
}
decoder := json.NewDecoder(bytes.NewReader(encoded))
decoder.UseNumber()
var value any
if err := decoder.Decode(&value); err != nil {
return "", ErrInvalidAssessmentAttempt
}
number, ok := value.(json.Number)
if !ok {
return "", ErrInvalidAssessmentAttempt
}
digits, scale, negative, err := assessmentDecimalParts(number.String())
if err != nil {
return "", err
}
return formatAssessmentDecimal(digits, scale, negative)
}
func assessmentDecimalParts(text string) (string, int64, bool, error) {
negative := strings.HasPrefix(text, "-")
if negative {
text = text[1:]
}
mantissa, exponent, err := assessmentDecimalMantissaAndExponent(text)
if err != nil {
return "", 0, false, err
}
integerDigits := mantissa
fractionDigits := ""
if point := strings.IndexByte(mantissa, '.'); point >= 0 {
integerDigits = mantissa[:point]
fractionDigits = mantissa[point+1:]
}
digits := integerDigits + fractionDigits
scale := int64(len(fractionDigits)) - exponent
if scale > maxAssessmentAttemptAnswerBytes || scale < -maxAssessmentAttemptAnswerBytes {
return "", 0, false, ErrInvalidAssessmentAttempt
}
digits = strings.TrimLeft(digits, "0")
for len(digits) > 0 && scale > 0 && digits[len(digits)-1] == '0' {
digits = digits[:len(digits)-1]
scale--
}
return digits, scale, negative, nil
}
func assessmentDecimalMantissaAndExponent(text string) (string, int64, error) {
decimalAt := strings.IndexAny(text, ".eE")
mantissa := text
exponent := int64(0)
if decimalAt >= 0 {
if text[decimalAt] == '.' {
exponentAt := strings.IndexAny(text[decimalAt+1:], "eE")
if exponentAt >= 0 {
exponentAt += decimalAt + 1
parsed, err := parseAssessmentExponent(text[exponentAt+1:])
if err != nil {
return "", 0, err
}
exponent = parsed
mantissa = text[:exponentAt]
}
} else {
mantissa = text[:decimalAt]
parsed, err := parseAssessmentExponent(text[decimalAt+1:])
if err != nil {
return "", 0, err
}
exponent = parsed
}
}
return mantissa, exponent, nil
}
func parseAssessmentExponent(value string) (int64, error) {
exponent, err := strconv.ParseInt(value, 10, 64)
if err != nil || exponent > maxAssessmentAttemptAnswerBytes || exponent < -maxAssessmentAttemptAnswerBytes {
return 0, ErrInvalidAssessmentAttempt
}
return exponent, nil
}
func formatAssessmentDecimal(digits string, scale int64, negative bool) (string, error) {
if digits == "" {
return "0", nil
}
outputLength := len(digits)
switch {
case scale <= 0:
outputLength += int(-scale)
case int64(len(digits)) <= scale:
outputLength += int(scale-int64(len(digits))) + 2
default:
outputLength++
}
if negative {
outputLength++
}
if outputLength > maxAssessmentAttemptAnswerBytes {
return "", ErrInvalidAssessmentAttempt
}
var canonical string
switch {
case scale <= 0:
canonical = digits + strings.Repeat("0", int(-scale))
case int64(len(digits)) <= scale:
canonical = "0." + strings.Repeat("0", int(scale-int64(len(digits)))) + digits
default:
point := len(digits) - int(scale)
canonical = digits[:point] + "." + digits[point:]
}
if negative {
canonical = "-" + canonical
}
return canonical, nil
}
// SubmitAnswer stores one final answer to the current frozen item. Identical
// repeats are no-ops even when their expected version is stale.
func (attempt AssessmentAttempt) SubmitAnswer(
expectedVersion int64,
itemID uuid.UUID,
answer json.RawMessage,
at time.Time,
) (AssessmentAttempt, bool, error) {
const location = "AssessmentAttempt.SubmitAnswer"
if attempt.IsZero() || itemID == uuid.Nil || at.IsZero() {
return AssessmentAttempt{}, false, fmt.Errorf("%s - attempt, item, and time are required: %w", location, ErrInvalidAssessmentAttempt)
}
index := attempt.itemIndex(itemID)
if index < 0 {
return AssessmentAttempt{}, false, fmt.Errorf("%s - item is not part of this attempt: %w", location, ErrInvalidAssessmentAttempt)
}
return attempt.submitAnswerToItem(expectedVersion, index, answer, canonicalAssessmentTime(at))
}
func (attempt AssessmentAttempt) submitAnswerToItem(
expectedVersion int64,
index int,
answer json.RawMessage,
answeredAt time.Time,
) (AssessmentAttempt, bool, error) {
const location = "AssessmentAttempt.submitAnswerToItem"
item := attempt.snapshot.Items[index]
canonical, _, err := CanonicalAssessmentAnswerForVariant(answer, item.Variant)
if err != nil {
return AssessmentAttempt{}, false, fmt.Errorf("%s - validate answer: %w", location, err)
}
replayed, err := assessmentAnswerReplay(item, canonical, expectedVersion, attempt.snapshot.Version)
if err != nil {
return AssessmentAttempt{}, false, fmt.Errorf("%s - check existing answer: %w", location, err)
}
if replayed {
return attempt, false, nil
}
if err := validateNewAssessmentAnswer(attempt.snapshot, index, expectedVersion, answeredAt); err != nil {
return AssessmentAttempt{}, false, fmt.Errorf("%s - validate lifecycle: %w", location, err)
}
return storeAssessmentAttemptAnswer(attempt, index, canonical, answeredAt)
}
func assessmentAnswerReplay(
item AssessmentAttemptItemSnapshot,
canonical []byte,
expectedVersion, currentVersion int64,
) (bool, error) {
if len(item.Answer) == 0 {
return false, nil
}
if bytes.Equal(item.Answer, canonical) {
return true, nil
}
if expectedVersion != currentVersion {
return false, ErrAssessmentAttemptVersionConflict
}
return false, ErrAssessmentAttemptNotActive
}
func validateNewAssessmentAnswer(
snapshot AssessmentAttemptSnapshot,
index int,
expectedVersion int64,
answeredAt time.Time,
) error {
if expectedVersion != snapshot.Version {
return ErrAssessmentAttemptVersionConflict
}
if snapshot.State != AssessmentAttemptStateInProgress ||
!answeredAt.Before(snapshot.ExpiresAt) || !snapshot.ChainDeadline.IsZero() && !answeredAt.Before(snapshot.ChainDeadline) {
return ErrAssessmentAttemptNotActive
}
idleAt := snapshot.LastActivityAt.Add(time.Duration(snapshot.IdleTimeoutSeconds) * time.Second)
if !answeredAt.Before(idleAt) {
return ErrAssessmentAttemptNotActive
}
if answeredAt.Before(snapshot.LastActivityAt) {
return ErrInvalidAssessmentAttempt
}
if index != firstUnansweredAssessmentItemIndex(snapshot.Items) {
return ErrAssessmentAttemptNotActive
}
return nil
}
func storeAssessmentAttemptAnswer(
attempt AssessmentAttempt,
index int,
canonical []byte,
answeredAt time.Time,
) (AssessmentAttempt, bool, error) {
next := attempt.Snapshot()
next.Items[index].Answer = canonical
next.Items[index].AnsweredAt = answeredAt
next.LastActivityAt = answeredAt
next.UpdatedAt = answeredAt
next.Version++
if allAssessmentAttemptItemsAnswered(next.Items) {
next.State = AssessmentAttemptStateReadyToFinalize
}
updated, err := RestoreAssessmentAttempt(next)
return updated, true, err
}
func (attempt AssessmentAttempt) itemIndex(itemID uuid.UUID) int {
for index, item := range attempt.snapshot.Items {
if item.ID == itemID {
return index
}
}
return -1
}
func firstUnansweredAssessmentItemIndex(items []AssessmentAttemptItemSnapshot) int {
for index, item := range items {
if len(item.Answer) == 0 {
return index
}
}
return -1
}
func allAssessmentAttemptItemsAnswered(items []AssessmentAttemptItemSnapshot) bool {
if len(items) == 0 {
return false
}
for _, item := range items {
if len(item.Answer) == 0 {
return false
}
}
return true
}
// ExpireIfDue records the terminal deadline transition for an incomplete
// in-progress attempt. It does not advance time for read operations.
func (attempt AssessmentAttempt) ExpireIfDue(at time.Time) (AssessmentAttempt, bool, error) {
const location = "AssessmentAttempt.ExpireIfDue"
if attempt.IsZero() || at.IsZero() {
return AssessmentAttempt{}, false, fmt.Errorf("%s - attempt and time are required: %w", location, ErrInvalidAssessmentAttempt)
}
if attempt.snapshot.State != AssessmentAttemptStateInProgress {
return attempt, false, nil
}
expiredAt := canonicalAssessmentTime(at)
if expiredAt.Before(attempt.snapshot.LastActivityAt) {
return AssessmentAttempt{}, false, fmt.Errorf("%s - expiry time predates activity: %w", location, ErrInvalidAssessmentAttempt)
}
if expiredAt.Before(attempt.snapshot.ExpiresAt) &&
(attempt.snapshot.ChainDeadline.IsZero() || expiredAt.Before(attempt.snapshot.ChainDeadline)) {
return attempt, false, nil
}
next := attempt.Snapshot()
next.State = AssessmentAttemptStateExpired
next.UpdatedAt = expiredAt
next.EndedAt = expiredAt
next.Version++
updated, err := RestoreAssessmentAttempt(next)
return updated, true, err
}
// FinalizeDemo applies only the explicit demo_basic pass mark or returns a
// separate demonstration outcome for demo_express. Adaptive scoring is not
// inferred from a basic score.
func (attempt AssessmentAttempt) FinalizeDemo(
expectedVersion int64,
policy AssessmentPolicy,
at time.Time,
) (AssessmentAttempt, bool, AssessmentAttemptDecision, error) {
const location = "AssessmentAttempt.FinalizeDemo"
if attempt.IsZero() || at.IsZero() {
return AssessmentAttempt{}, false, AssessmentAttemptDecision{}, fmt.Errorf("%s - attempt and time are required: %w", location, ErrInvalidAssessmentAttempt)
}
if attempt.snapshot.State == AssessmentAttemptStateCompleted {
decision, err := decisionForCompletedAttempt(attempt, policy)
return attempt, false, decision, err
}
if expectedVersion != attempt.snapshot.Version {
return AssessmentAttempt{}, false, AssessmentAttemptDecision{}, fmt.Errorf("%s - expected version is stale: %w", location, ErrAssessmentAttemptVersionConflict)
}
if attempt.snapshot.State != AssessmentAttemptStateReadyToFinalize || !allAssessmentAttemptItemsAnswered(attempt.snapshot.Items) {
return AssessmentAttempt{}, false, AssessmentAttemptDecision{}, fmt.Errorf("%s - required assessment answers are incomplete: %w", location, ErrAssessmentAttemptNotActive)
}
finalizedAt := canonicalAssessmentTime(at)
if finalizedAt.Before(attempt.snapshot.LastActivityAt) {
return AssessmentAttempt{}, false, AssessmentAttemptDecision{}, fmt.Errorf("%s - decision time predates answer activity: %w", location, ErrInvalidAssessmentAttempt)
}
idleAt := attempt.snapshot.LastActivityAt.Add(time.Duration(attempt.snapshot.IdleTimeoutSeconds) * time.Second)
deadlineDue := !finalizedAt.Before(attempt.snapshot.ExpiresAt) ||
!attempt.snapshot.ChainDeadline.IsZero() && !finalizedAt.Before(attempt.snapshot.ChainDeadline)
if !finalizedAt.Before(idleAt) && !deadlineDue {
return AssessmentAttempt{}, false, AssessmentAttemptDecision{}, fmt.Errorf("%s - work session is idle: %w", location, ErrAssessmentAttemptNotActive)
}
decision, err := assessmentAttemptDecision(attempt.snapshot, policy)
if err != nil {
return AssessmentAttempt{}, false, AssessmentAttemptDecision{}, fmt.Errorf("%s - calculate pinned demo decision: %w", location, err)
}
next := attempt.Snapshot()
next.State = AssessmentAttemptStateCompleted
next.Outcome = decision.Outcome
next.EndedAt = finalizedAt
next.UpdatedAt = finalizedAt
next.Version++
updated, err := RestoreAssessmentAttempt(next)
return updated, true, decision, err
}
func decisionForCompletedAttempt(attempt AssessmentAttempt, policy AssessmentPolicy) (AssessmentAttemptDecision, error) {
return assessmentAttemptDecision(attempt.snapshot, policy)
}
func assessmentAttemptDecision(snapshot AssessmentAttemptSnapshot, policy AssessmentPolicy) (AssessmentAttemptDecision, error) {
if snapshot.Kind == AssessmentAttemptKindDemoExpress {
return assessmentTrainingDecision(snapshot, policy)
}
if snapshot.Kind != AssessmentAttemptKindRoot && snapshot.Kind != AssessmentAttemptKindCorrective {
return AssessmentAttemptDecision{}, ErrAssessmentAttemptNotActive
}
return assessmentBasicDecision(snapshot, policy)
}
func assessmentTrainingDecision(snapshot AssessmentAttemptSnapshot, policy AssessmentPolicy) (AssessmentAttemptDecision, error) {
if policy.Training == nil || !allAssessmentAttemptItemsAnswered(snapshot.Items) ||
snapshot.State == AssessmentAttemptStateCompleted && snapshot.Outcome != AssessmentAttemptOutcomeDemonstration ||
snapshot.State != AssessmentAttemptStateCompleted && snapshot.State != AssessmentAttemptStateReadyToFinalize {
return AssessmentAttemptDecision{}, ErrInvalidAssessmentAttempt
}
return AssessmentAttemptDecision{
Outcome: AssessmentAttemptOutcomeDemonstration,
Rationale: AssessmentAttemptDecisionRationale{Rule: assessmentResultRuleTrainingOnly},
}, nil
}
func assessmentBasicDecision(snapshot AssessmentAttemptSnapshot, policy AssessmentPolicy) (AssessmentAttemptDecision, error) {
maxScored, passMark, err := assessmentBasicDecisionInputs(snapshot, policy)
if err != nil {
return AssessmentAttemptDecision{}, err
}
points, err := scoreAssessmentAttemptItems(snapshot.Items, maxScored)
if err != nil {
return AssessmentAttemptDecision{}, err
}
passPoints64 := (int64(maxScored)*int64(passMark) + int64(basisPointsPerUnit) - 1) / int64(basisPointsPerUnit)
if passPoints64 < 1 || passPoints64 > int64(maxScored) || passPoints64 > math.MaxInt32 {
return AssessmentAttemptDecision{}, ErrInvalidAssessmentAttempt
}
passPoints := int32(passPoints64)
outcome, err := assessmentBasicOutcome(snapshot, points, passPoints)
if err != nil {
return AssessmentAttemptDecision{}, err
}
return AssessmentAttemptDecision{
Outcome: outcome,
Score: &AssessmentBasicScore{Points: points, MaxPoints: maxScored, PassPoints: passPoints},
Rationale: AssessmentAttemptDecisionRationale{
Rule: assessmentResultRuleBasicPassMark, PassMarkBasisPoints: int32(passMark),
PassPoints: passPoints, ScoredItems: maxScored,
},
}, nil
}
func assessmentBasicDecisionInputs(snapshot AssessmentAttemptSnapshot, policy AssessmentPolicy) (int32, BasisPoints, error) {
if snapshot.Mode != AssessmentAttemptModeDemoBasic || policy.Attempt == nil || !allAssessmentAttemptItemsAnswered(snapshot.Items) {
return 0, 0, ErrAssessmentAttemptNotActive
}
maxScored := policy.StopRule.MaxScoredItems
seedCount := policy.StopRule.SeedItems
if maxScored < 1 || seedCount < 0 || int64(maxScored)+int64(seedCount) != int64(len(snapshot.Items)) {
return 0, 0, ErrInvalidAssessmentAttempt
}
passMark := policy.Attempt.BasicPassMark
if passMark < 1 || passMark > basisPointsPerUnit {
return 0, 0, ErrInvalidAssessmentAttempt
}
return maxScored, passMark, nil
}
func assessmentBasicOutcome(
snapshot AssessmentAttemptSnapshot,
points int32,
passPoints int32,
) (AssessmentAttemptOutcome, error) {
outcome := AssessmentAttemptOutcomeNotConfirmed
if points >= passPoints {
outcome = AssessmentAttemptOutcomeConfirmed
}
if snapshot.State == AssessmentAttemptStateCompleted && snapshot.Outcome != outcome {
return "", ErrInvalidAssessmentAttempt
}
return outcome, nil
}
func scoreAssessmentAttemptItems(items []AssessmentAttemptItemSnapshot, scoredItems int32) (int32, error) {
var points int32
for index := int32(0); index < scoredItems; index++ {
item := items[index]
_, correct, err := CanonicalAssessmentAnswerForVariant(item.Answer, item.Variant)
if err != nil {
return 0, err
}
if correct {
points++
}
}
return points, nil
}
@@ -0,0 +1,349 @@
package domain
import (
"encoding/json"
"errors"
"fmt"
"strconv"
"strings"
"testing"
"time"
"github.com/google/uuid"
)
func TestAssessmentAnswerCanonicalizesNumericEqualityAndScoresOnlyPinnedItems(t *testing.T) {
policy := testAssessmentAttemptPolicyVersion(t)
assessmentPolicy := policy.Policy().Assessment
assessmentPolicy.StopRule.MaxScoredItems = 1
assessmentPolicy.StopRule.SeedItems = 1
attempt := testAttemptWithPolicy(t, policy, AssessmentAttemptKindRoot, 2)
created := attempt.Snapshot().CreatedAt
items := attempt.Snapshot().Items
wrong := fmt.Sprintf(`{"format":"number","number":%s}`, items[0].Variant.ReferenceAnswer+"1")
updated, changed, err := attempt.SubmitAnswer(attempt.Version(), items[0].ID, json.RawMessage(wrong), created.Add(time.Second))
if err != nil || !changed || updated.State() != AssessmentAttemptStateInProgress || updated.Version() != 2 {
t.Fatalf("SubmitAnswer(first) = (%v, %v, %v), want one in-progress transition", updated, changed, err)
}
reference := items[0].Variant.ReferenceAnswer
canonicalA, correct, err := CanonicalAssessmentAnswerForVariant(json.RawMessage(fmt.Sprintf(`{"format":"number","number":%s}`, reference)), items[0].Variant)
if err != nil || !correct {
t.Fatalf("CanonicalAssessmentAnswerForVariant(reference) = (%s, %v, %v), want correct", canonicalA, correct, err)
}
canonicalB, _, err := CanonicalAssessmentAnswerForVariant(json.RawMessage(fmt.Sprintf(`{"format":"number","number":%s.0}`, reference)), items[0].Variant)
if err != nil || string(canonicalA) != string(canonicalB) {
t.Fatalf("numeric equivalents canonicalized to %s and %s, error %v", canonicalA, canonicalB, err)
}
seed := items[1]
seedAnswer := json.RawMessage(fmt.Sprintf(`{"format":"number","number":%s}`, seed.Variant.ReferenceAnswer))
ready, changed, err := updated.SubmitAnswer(updated.Version(), seed.ID, seedAnswer, created.Add(2*time.Second))
if err != nil || !changed || ready.State() != AssessmentAttemptStateReadyToFinalize || ready.Version() != 3 {
t.Fatalf("SubmitAnswer(seed) = (%v, %v, %v), want ready_to_finalize", ready, changed, err)
}
final, changed, decision, err := ready.FinalizeDemo(ready.Version(), assessmentPolicy, created.Add(3*time.Second))
if err != nil || !changed || final.State() != AssessmentAttemptStateCompleted || decision.Score == nil ||
decision.Score.Points != 0 || decision.Score.MaxPoints != 1 || decision.Score.PassPoints != 1 ||
decision.Outcome != AssessmentAttemptOutcomeNotConfirmed {
t.Fatalf("FinalizeDemo() = (%v, %v, %+v, %v), want wrong scored item and ignored correct seed", final, changed, decision, err)
}
}
func TestAssessmentNumberEqualityPreservesExactDecimalPrecision(t *testing.T) {
canonicalOne, err := CanonicalAssessmentAnswer(json.RawMessage(`{"format":"number","number":1}`))
if err != nil {
t.Fatalf("CanonicalAssessmentAnswer(1) error = %v", err)
}
canonicalDecimal, err := CanonicalAssessmentAnswer(json.RawMessage(`{"format":"number","number":1.0}`))
if err != nil || string(canonicalOne) != string(canonicalDecimal) {
t.Fatalf("canonical 1 and 1.0 = %s and %s, error %v", canonicalOne, canonicalDecimal, err)
}
canonicalPrecise, err := CanonicalAssessmentAnswer(json.RawMessage(`{"format":"number","number":1.0000000000000001}`))
if err != nil || string(canonicalPrecise) == string(canonicalOne) {
t.Fatalf("canonical precise decimal = %s, error %v; want a value distinct from %s", canonicalPrecise, err, canonicalOne)
}
if _, err := CanonicalAssessmentAnswer(json.RawMessage(`{"format":"number","number":1e999999999}`)); !errors.Is(err, ErrInvalidAssessmentAttempt) {
t.Fatalf("CanonicalAssessmentAnswer(oversized exponent) error = %v, want bounded invalid answer", err)
}
for _, input := range []string{
`{"format":"number","number":null}`,
`{"format":"number","number":"1"}`,
`{"format":"number","number":true}`,
} {
if _, err := CanonicalAssessmentAnswer(json.RawMessage(input)); !errors.Is(err, ErrInvalidAssessmentAttempt) {
t.Errorf("CanonicalAssessmentAnswer(%s) error = %v, want invalid attempt", input, err)
}
}
}
func TestAssessmentAttemptResultSnapshotRetainsRationaleAndRejectsCorruption(t *testing.T) {
policy := testAssessmentAttemptPolicyVersion(t)
assessmentPolicy := policy.Policy().Assessment
assessmentPolicy.StopRule.MaxScoredItems = 2
assessmentPolicy.StopRule.SeedItems = 0
attempt := testAttemptWithPolicy(t, policy, AssessmentAttemptKindRoot, 2)
createdAt := attempt.Snapshot().CreatedAt
for index, item := range attempt.Snapshot().Items {
answer := correctAssessmentTestAnswer(t, item.Variant)
updated, changed, err := attempt.SubmitAnswer(attempt.Version(), item.ID, answer, createdAt.Add(time.Duration(index+1)*time.Second))
if err != nil || !changed {
t.Fatalf("SubmitAnswer(item %d) = changed %v, error %v", index, changed, err)
}
attempt = updated
}
finalized, changed, decision, err := attempt.FinalizeDemo(
attempt.Version(), assessmentPolicy, createdAt.Add(3*time.Second),
)
if err != nil || !changed {
t.Fatalf("FinalizeDemo() = changed %v, error %v", changed, err)
}
result, err := NewAssessmentAttemptResultSnapshot(
finalized, decision, "", []string{"uncalibrated_thresholds", "demo_bank"},
)
if err != nil {
t.Fatalf("NewAssessmentAttemptResultSnapshot() error = %v", err)
}
if err := ValidateAssessmentAttemptResultSnapshot(result); err != nil {
t.Fatalf("ValidateAssessmentAttemptResultSnapshot() error = %v", err)
}
if result.BasicScore == nil || result.BasicScore.Points != 2 || result.BasicScore.MaxPoints != 2 ||
result.BasicScore.PassPoints != 2 || result.Rationale.PassMarkBasisPoints != 8000 ||
result.Rationale.ScoredItems != 2 || result.Rationale.PassPoints != 2 ||
result.Pins.ProductPolicyVersionID != policy.ID() || result.DecidedAt != createdAt.Add(3*time.Second) {
t.Fatalf("persisted decision snapshot = %+v, want raw score, rationale and pins", result)
}
corruptions := []func(*AssessmentAttemptResultSnapshot){
func(snapshot *AssessmentAttemptResultSnapshot) { snapshot.Rationale.PassPoints-- },
func(snapshot *AssessmentAttemptResultSnapshot) { snapshot.Rationale.ScoredItems++ },
func(snapshot *AssessmentAttemptResultSnapshot) { snapshot.BasicScore.Points-- },
func(snapshot *AssessmentAttemptResultSnapshot) { snapshot.Pins.BankVersion = "other.bank" },
}
for index, corrupt := range corruptions {
bad := result
bad.Limitations = append([]string{}, result.Limitations...)
bad.BasicScore = clonePointer(result.BasicScore)
corrupt(&bad)
if err := ValidateAssessmentAttemptResultSnapshot(bad); !errors.Is(err, ErrInvalidAssessmentAttempt) {
t.Errorf("corrupted result %d error = %v, want invalid result", index, err)
}
}
}
func TestAssessmentBasicScoreDoesNotDependOnAnswerElapsedTime(t *testing.T) {
policy := testAssessmentAttemptPolicyVersion(t)
assessmentPolicy := policy.Policy().Assessment
assessmentPolicy.StopRule.MaxScoredItems = 2
assessmentPolicy.StopRule.SeedItems = 0
items := testAssessmentAttemptItems(t, 2)
versions := testAssessmentAttemptVersions(t, policy)
specialization, grade := SpecializationBackend, GradeJunior
durations := [][]time.Duration{
{time.Second, 2 * time.Second},
{15 * time.Minute, 30 * time.Minute},
}
decisions := make([]AssessmentAttemptDecision, 0, len(durations))
for runIndex, answerTimes := range durations {
attempt, err := NewAssessmentAttempt(NewAssessmentAttemptInput{
UserID: uuid.New(), Kind: AssessmentAttemptKindRoot, BankCategory: "unit-category",
Specialization: &specialization, TargetGrade: &grade, Versions: versions,
Policy: policy, CreatedAt: testAssessmentAttemptCreatedAt, Items: items,
})
if err != nil {
t.Fatalf("NewAssessmentAttempt(run %d) error = %v", runIndex, err)
}
for index, item := range attempt.Snapshot().Items {
answer := correctAssessmentTestAnswer(t, item.Variant)
if index == 0 {
answer = incorrectAssessmentTestAnswer(t, item.Variant)
}
updated, changed, err := attempt.SubmitAnswer(
attempt.Version(), item.ID, answer, testAssessmentAttemptCreatedAt.Add(answerTimes[index]),
)
if err != nil || !changed {
t.Fatalf("SubmitAnswer(run %d item %d) = changed %v, error %v", runIndex, index, changed, err)
}
attempt = updated
}
finalized, changed, decision, err := attempt.FinalizeDemo(
attempt.Version(), assessmentPolicy, testAssessmentAttemptCreatedAt.Add(answerTimes[len(answerTimes)-1]+time.Second),
)
if err != nil || !changed || finalized.State() != AssessmentAttemptStateCompleted {
t.Fatalf("FinalizeDemo(run %d) = changed %v state %s error %v", runIndex, changed, finalized.State(), err)
}
decisions = append(decisions, decision)
}
fast, slow := decisions[0], decisions[1]
if fast.Outcome != slow.Outcome || fast.Score == nil || slow.Score == nil || *fast.Score != *slow.Score || fast.Rationale != slow.Rationale {
t.Fatalf("same answers at different elapsed times scored differently: fast=%+v slow=%+v", fast, slow)
}
}
func TestExpressResultSnapshotHasNoScoringOrGrade(t *testing.T) {
policy := testTrainingOnlyAssessmentPolicyVersion(t)
attempt := testAttemptWithPolicy(t, policy, AssessmentAttemptKindDemoExpress, 1)
createdAt := attempt.Snapshot().CreatedAt
for index, item := range attempt.Snapshot().Items {
updated, changed, err := attempt.SubmitAnswer(
attempt.Version(), item.ID, correctAssessmentTestAnswer(t, item.Variant),
createdAt.Add(time.Duration(index+1)*time.Second),
)
if err != nil || !changed {
t.Fatalf("SubmitAnswer(express item %d) = changed %v, error %v", index, changed, err)
}
attempt = updated
}
finalized, changed, decision, err := attempt.FinalizeDemo(
attempt.Version(), policy.Policy().Assessment, createdAt.Add(4*time.Second),
)
if err != nil || !changed || decision.Score != nil || decision.Outcome != AssessmentAttemptOutcomeDemonstration {
t.Fatalf("FinalizeDemo(express) = changed %v decision %+v error %v", changed, decision, err)
}
result, err := NewAssessmentAttemptResultSnapshot(
finalized, decision, "This training run is educational only.", []string{"demonstration_only"},
)
if err != nil || result.BasicScore != nil || result.Attempt.TargetGrade != nil ||
result.Attempt.Specialization != nil || result.Outcome != AssessmentAttemptOutcomeDemonstration {
t.Fatalf("express result = %+v, error %v", result, err)
}
}
func correctAssessmentTestAnswer(t *testing.T, variant AssessmentVariant) json.RawMessage {
t.Helper()
switch variant.AnswerFormat {
case AnswerFormatInteger:
return json.RawMessage(fmt.Sprintf(`{"format":"number","number":%s}`, variant.ReferenceAnswer))
case AnswerFormatIntegerSequence:
elements := make([]string, 0, len(strings.Fields(variant.ReferenceAnswer)))
for _, ordinal := range strings.Fields(variant.ReferenceAnswer) {
elements = append(elements, "job_"+ordinal)
}
encoded, err := json.Marshal(orderAssessmentAnswer{Format: "order", ElementIDs: elements})
if err != nil {
t.Fatalf("json.Marshal(order answer) error = %v", err)
}
return encoded
default:
t.Fatalf("unsupported test answer format %q", variant.AnswerFormat)
return nil
}
}
func incorrectAssessmentTestAnswer(t *testing.T, variant AssessmentVariant) json.RawMessage {
t.Helper()
switch variant.AnswerFormat {
case AnswerFormatInteger:
reference, err := strconv.ParseInt(variant.ReferenceAnswer, 10, 64)
if err != nil {
t.Fatalf("parse frozen numeric key %q: %v", variant.ReferenceAnswer, err)
}
return json.RawMessage(fmt.Sprintf(`{"format":"number","number":%d}`, reference+1))
case AnswerFormatIntegerSequence:
var answer orderAssessmentAnswer
if err := json.Unmarshal(correctAssessmentTestAnswer(t, variant), &answer); err != nil || len(answer.ElementIDs) < 2 {
t.Fatalf("decode frozen order key: %v", err)
}
answer.ElementIDs[0], answer.ElementIDs[1] = answer.ElementIDs[1], answer.ElementIDs[0]
encoded, err := json.Marshal(answer)
if err != nil {
t.Fatalf("marshal incorrect order answer: %v", err)
}
return encoded
default:
t.Fatalf("unsupported test answer format %q", variant.AnswerFormat)
return nil
}
}
func TestAssessmentAnswerDuplicateIsCanonicalNoOpEvenWithStaleVersion(t *testing.T) {
policy := testAssessmentAttemptPolicyVersion(t)
attempt := testAttemptWithPolicy(t, policy, AssessmentAttemptKindRoot, 1)
item := attempt.Snapshot().Items[0]
answer := json.RawMessage(fmt.Sprintf(`{"format":"number","number":%s}`, item.Variant.ReferenceAnswer))
updated, changed, err := attempt.SubmitAnswer(attempt.Version(), item.ID, answer, attempt.Snapshot().CreatedAt.Add(time.Second))
if err != nil || !changed {
t.Fatalf("SubmitAnswer() = (%v, %v, %v), want saved answer", updated, changed, err)
}
answerWithDecimal := json.RawMessage(fmt.Sprintf(`{"format":"number","number":%s.0}`, item.Variant.ReferenceAnswer))
replayed, changed, err := updated.SubmitAnswer(attempt.Version(), item.ID, answerWithDecimal, updated.Snapshot().LastActivityAt.Add(time.Second))
if err != nil || changed || replayed.Version() != updated.Version() || replayed.Snapshot().Items[0].AnsweredAt != updated.Snapshot().Items[0].AnsweredAt {
t.Fatalf("SubmitAnswer(duplicate) = (%v, %v, %v), want unchanged canonical replay", replayed, changed, err)
}
}
func TestAssessmentOrderAnswerRequiresExactPermutationAndScoresFrozenSequence(t *testing.T) {
input := testAssessmentInput()
input.Key = "ordered-assessment-family"
input.Generator = AssessmentSeedGenerator{
Algorithm: "dependency_order.v1",
Parameters: map[string]AssessmentParameterRange{
"tasks": {Min: 4, Max: 4}, "links": {Min: 0, Max: 0},
},
StatementTemplate: "Order tasks {{.tasks}} with dependencies {{.dependencies}}.",
}
input.AnswerKey.AnswerFormat = AnswerFormatIntegerSequence
family := restoreAssessment(t, input)
variant, err := family.NewVariant(VariantSeed(22))
if err != nil {
t.Fatalf("NewVariant() error = %v", err)
}
ordered := make([]string, 0, 4)
for _, token := range strings.Fields(variant.ReferenceAnswer) {
ordered = append(ordered, "job_"+token)
}
wrongOrder := append([]string(nil), ordered...)
wrongOrder[0], wrongOrder[1] = wrongOrder[1], wrongOrder[0]
wrongAnswer, err := json.Marshal(orderAssessmentAnswer{Format: "order", ElementIDs: wrongOrder})
if err != nil {
t.Fatalf("json.Marshal(wrong order) error = %v", err)
}
wrong, correct, err := CanonicalAssessmentAnswerForVariant(wrongAnswer, variant)
if err != nil || correct || len(wrong) == 0 {
t.Fatalf("CanonicalAssessmentAnswerForVariant(wrong permutation) = (%s, %v, %v)", wrong, correct, err)
}
if _, _, err := CanonicalAssessmentAnswerForVariant(
json.RawMessage(`{"format":"order","element_ids":["job_1","job_1","job_3","job_4"]}`), variant,
); !errors.Is(err, ErrInvalidAssessmentAttempt) {
t.Fatalf("duplicate order token error = %v, want invalid attempt", err)
}
correctAnswer, err := json.Marshal(orderAssessmentAnswer{Format: "order", ElementIDs: ordered})
if err != nil {
t.Fatalf("json.Marshal(reference order) error = %v", err)
}
_, correct, err = CanonicalAssessmentAnswerForVariant(correctAnswer, variant)
if err != nil || !correct {
t.Fatalf("CanonicalAssessmentAnswerForVariant(reference order) = (correct=%v, err=%v)", correct, err)
}
}
func testAttemptWithPolicy(
t *testing.T,
policy PolicyVersion,
kind AssessmentAttemptKind,
itemCount int,
) AssessmentAttempt {
t.Helper()
items := testAssessmentAttemptItems(t, itemCount)
if kind == AssessmentAttemptKindDemoExpress {
items = testAssessmentAttemptItems(t, int(policy.Policy().Assessment.Training.DemoExpressItemCount))
}
input := NewAssessmentAttemptInput{
UserID: uuid.New(), Kind: kind, BankCategory: "unit-category", Policy: policy,
CreatedAt: testAssessmentAttemptCreatedAt, Items: items,
}
if kind == AssessmentAttemptKindDemoExpress {
input.Versions = testTrainingAssessmentAttemptVersions(policy)
} else {
specialization, grade := SpecializationBackend, GradeJunior
input.Specialization, input.TargetGrade = &specialization, &grade
input.Versions = testAssessmentAttemptVersions(t, policy)
}
attempt, err := NewAssessmentAttempt(input)
if err != nil {
t.Fatalf("NewAssessmentAttempt() error = %v", err)
}
return attempt
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,556 @@
package domain
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"strings"
"testing"
"time"
"github.com/google/uuid"
)
var testAssessmentAttemptCreatedAt = time.Date(2026, time.October, 7, 10, 0, 0, 0, time.UTC)
func testAssessmentAttemptPolicyVersion(t *testing.T) PolicyVersion {
t.Helper()
draft := mustDraft(t, NewPolicyVersionDraftInput{
Key: ProductPolicyKey, Kind: PolicyKindDemo, Author: DemoPolicySeedAuthor, Policy: DemoProductPolicyV2(),
}, 2)
return mustRestore(t, storedFrom(draft))
}
func testTrainingOnlyAssessmentPolicyVersion(t *testing.T) PolicyVersion {
t.Helper()
policy := DemoProductPolicyV2()
policy.Assessment.Attempt = nil
draft := mustDraft(t, NewPolicyVersionDraftInput{
Key: ProductPolicyKey, Kind: PolicyKindDemo, Author: DemoPolicySeedAuthor, Policy: policy,
}, 2)
return mustRestore(t, storedFrom(draft))
}
func testAssessmentAttemptVersions(t *testing.T, policy PolicyVersion) AssessmentAttemptVersions {
t.Helper()
gradingID, err := NewPolicyVersionID()
if err != nil {
t.Fatalf("NewPolicyVersionID() error = %v", err)
}
return AssessmentAttemptVersions{
ProductPolicyVersionID: policy.ID(), ProductPolicyVersion: policy.Version(),
GradingPolicyVersionID: gradingID, OpeningID: uuid.New(), OpeningManifestHash: testManifestHash(1),
BankVersion: "backend-demo.2026-10.1", AlgorithmVersion: "assessment.v1",
}
}
func testTrainingAssessmentAttemptVersions(policy PolicyVersion) AssessmentAttemptVersions {
return AssessmentAttemptVersions{
ProductPolicyVersionID: policy.ID(), ProductPolicyVersion: policy.Version(),
TrainingBindingID: uuid.New(), TrainingManifestHash: testManifestHash(2),
BankVersion: "training-demo.2026-10.1", AlgorithmVersion: "assessment.v1",
}
}
func testManifestHash(value byte) [32]byte {
var digest [32]byte
digest[0] = value
return digest
}
func testAssessmentAttemptItems(t *testing.T, count int) []AssessmentAttemptItemInput {
t.Helper()
items := make([]AssessmentAttemptItemInput, count)
for index := range items {
input := testAssessmentInput()
input.Key = AssessmentFamilyKey(fmt.Sprintf("unit-test-family-%d", index))
family := restoreAssessment(t, input)
variant, err := family.NewVariant(VariantSeed(index + 1))
if err != nil {
t.Fatalf("NewVariant() error = %v", err)
}
items[index] = AssessmentAttemptItemInput{Variant: variant}
}
return items
}
func testRootAssessmentAttempt(t *testing.T, userID uuid.UUID, grade GradeCode) AssessmentAttempt {
t.Helper()
policy := testAssessmentAttemptPolicyVersion(t)
items := testAssessmentAttemptItems(t, 2)
specialization := SpecializationBackend
attempt, err := NewAssessmentAttempt(NewAssessmentAttemptInput{
UserID: userID, Kind: AssessmentAttemptKindRoot, BankCategory: "unit-category",
Specialization: &specialization, TargetGrade: &grade,
Versions: testAssessmentAttemptVersions(t, policy), Policy: policy,
CreatedAt: testAssessmentAttemptCreatedAt, Items: items,
})
if err != nil {
t.Fatalf("NewAssessmentAttempt(root) error = %v", err)
}
return attempt
}
func terminalAssessmentAttempt(t *testing.T, attempt AssessmentAttempt, state AssessmentAttemptState, outcome AssessmentAttemptOutcome, endedAt time.Time) AssessmentAttempt {
t.Helper()
snapshot := attempt.Snapshot()
snapshot.State = state
snapshot.Outcome = outcome
snapshot.EndedAt = endedAt
snapshot.UpdatedAt = endedAt
restored, err := RestoreAssessmentAttempt(snapshot)
if err != nil {
t.Fatalf("RestoreAssessmentAttempt(terminal) error = %v", err)
}
return restored
}
func TestNewAssessmentAttemptPinsPolicyVersionsAndFrozenVariants(t *testing.T) {
userID := uuid.New()
attempt := testRootAssessmentAttempt(t, userID, GradeJunior)
snapshot := attempt.Snapshot()
if attempt.IsZero() || attempt.UserID() != userID || attempt.Kind() != AssessmentAttemptKindRoot ||
attempt.Mode() != AssessmentAttemptModeDemoBasic || attempt.State() != AssessmentAttemptStateInProgress ||
attempt.Version() != 1 || attempt.SessionsUsed() != 1 || attempt.MaxSessions() != 2 ||
attempt.IdleTimeoutSeconds() != 1800 || attempt.RootAttemptID() != attempt.ID() {
t.Fatalf("new root attempt has unexpected identity or session state: %+v", snapshot)
}
wantDeadline := testAssessmentAttemptCreatedAt.Add(72 * time.Hour)
if !attempt.ExpiresAt().Equal(wantDeadline) || !attempt.ChainDeadline().Equal(wantDeadline) {
t.Fatalf("attempt expires %s and chain ends %s, want %s", attempt.ExpiresAt(), attempt.ChainDeadline(), wantDeadline)
}
if len(snapshot.Items) != 2 || snapshot.Items[0].Ordinal != 1 || snapshot.Items[1].Ordinal != 2 ||
snapshot.Items[0].Variant.Statement == "" || snapshot.Items[0].Variant.ReferenceAnswer == "" {
t.Fatalf("frozen item snapshots = %+v, want ordered variants with reference answers", snapshot.Items)
}
if snapshot.Versions.ProductPolicyVersionID == snapshot.Versions.GradingPolicyVersionID {
t.Fatal("test fixture should prove product and opening grading versions are preserved separately")
}
if snapshot.Versions.OpeningID == uuid.Nil || snapshot.Versions.OpeningManifestHash == [32]byte{} {
t.Fatal("real attempt did not pin its reviewed opening and manifest")
}
}
func TestNewAssessmentAttemptRefusesLegacyPolicyWithoutAttemptSettings(t *testing.T) {
legacyDraft := mustDraft(t, NewPolicyVersionDraftInput{
Key: ProductPolicyKey, Kind: PolicyKindDemo, Author: DemoPolicySeedAuthor, Policy: DemoProductPolicyV1(),
}, 1)
legacyPolicy := mustRestore(t, storedFrom(legacyDraft))
specialization, grade := SpecializationBackend, GradeJunior
_, err := NewAssessmentAttempt(NewAssessmentAttemptInput{
UserID: uuid.New(), Kind: AssessmentAttemptKindRoot, BankCategory: "unit-category",
Specialization: &specialization, TargetGrade: &grade,
Versions: testAssessmentAttemptVersions(t, legacyPolicy), Policy: legacyPolicy,
CreatedAt: testAssessmentAttemptCreatedAt, Items: testAssessmentAttemptItems(t, 1),
})
if !errors.Is(err, ErrInvalidAssessmentAttempt) {
t.Fatalf("NewAssessmentAttempt(legacy policy) error = %v, want fail-closed invalid attempt", err)
}
}
func TestCorrectiveAttemptSharesRootDeadlineAndRejectsForeignOrInvalidRoot(t *testing.T) {
userID := uuid.New()
root := terminalAssessmentAttempt(t, testRootAssessmentAttempt(t, userID, GradeSenior),
AssessmentAttemptStateCompleted, AssessmentAttemptOutcomeNotConfirmed, testAssessmentAttemptCreatedAt.Add(time.Hour))
policy := testAssessmentAttemptPolicyVersion(t)
specialization, grade, language := SpecializationBackend, GradeMiddle, TaskLanguageGo
input := NewAssessmentAttemptInput{
UserID: userID, Kind: AssessmentAttemptKindCorrective, BankCategory: "unit-category",
Specialization: &specialization, TargetGrade: &grade, TaskLanguage: &language,
Chain: []AssessmentAttempt{root}, Versions: testAssessmentAttemptVersions(t, policy), Policy: policy,
CreatedAt: testAssessmentAttemptCreatedAt.Add(12 * time.Hour), Items: testAssessmentAttemptItems(t, 1),
}
attempt, err := NewAssessmentAttempt(input)
if err != nil {
t.Fatalf("NewAssessmentAttempt(corrective) error = %v", err)
}
if attempt.RootAttemptID() != root.ID() || !attempt.ChainDeadline().Equal(root.ChainDeadline()) ||
!attempt.ExpiresAt().Equal(root.ChainDeadline()) {
t.Fatalf("corrective attempt does not share the root deadline: %+v", attempt.Snapshot())
}
foreign := terminalAssessmentAttempt(t, testRootAssessmentAttempt(t, uuid.New(), GradeSenior),
AssessmentAttemptStateExpired, "", testAssessmentAttemptCreatedAt.Add(time.Hour))
input.Chain = []AssessmentAttempt{foreign}
if _, err := NewAssessmentAttempt(input); !errors.Is(err, ErrInvalidAssessmentAttempt) {
t.Fatalf("NewAssessmentAttempt(foreign root) error = %v, want ErrInvalidAssessmentAttempt", err)
}
input.Chain = []AssessmentAttempt{root}
input.TargetGrade = ptr(GradeSenior)
if _, err := NewAssessmentAttempt(input); !errors.Is(err, ErrInvalidAssessmentAttempt) {
t.Fatalf("NewAssessmentAttempt(non-lower grade) error = %v, want ErrInvalidAssessmentAttempt", err)
}
}
func TestCorrectiveAttemptRequiresTerminalPredecessorAndStrictlyDescendingGrades(t *testing.T) {
userID := uuid.New()
activeRoot := testRootAssessmentAttempt(t, userID, GradeSenior)
policy := testAssessmentAttemptPolicyVersion(t)
specialization, grade := SpecializationBackend, GradeMiddle
input := NewAssessmentAttemptInput{
UserID: userID, Kind: AssessmentAttemptKindCorrective, BankCategory: "unit-category",
Specialization: &specialization, TargetGrade: &grade,
Chain: []AssessmentAttempt{activeRoot}, Versions: testAssessmentAttemptVersions(t, policy), Policy: policy,
CreatedAt: testAssessmentAttemptCreatedAt.Add(time.Hour), Items: testAssessmentAttemptItems(t, 1),
}
if _, err := NewAssessmentAttempt(input); !errors.Is(err, ErrInvalidAssessmentAttempt) {
t.Fatalf("corrective attempt from active root error = %v, want ErrInvalidAssessmentAttempt", err)
}
root := terminalAssessmentAttempt(t, activeRoot, AssessmentAttemptStateExpired, "", testAssessmentAttemptCreatedAt.Add(time.Hour))
input.Chain = []AssessmentAttempt{root}
input.CreatedAt = testAssessmentAttemptCreatedAt.Add(2 * time.Hour)
input.TargetGrade = ptr(GradeSenior)
if _, err := NewAssessmentAttempt(input); !errors.Is(err, ErrInvalidAssessmentAttempt) {
t.Fatalf("expired root with non-lower grade error = %v, want ErrInvalidAssessmentAttempt", err)
}
input.TargetGrade = ptr(GradeMiddle)
corrective, err := NewAssessmentAttempt(input)
if err != nil {
t.Fatalf("corrective attempt after early root expiry error = %v", err)
}
ended := terminalAssessmentAttempt(t, corrective, AssessmentAttemptStateCompleted,
AssessmentAttemptOutcomeNotDetermined, testAssessmentAttemptCreatedAt.Add(3*time.Hour))
input.Chain = []AssessmentAttempt{root, ended}
input.TargetGrade = ptr(GradeJunior)
input.CreatedAt = testAssessmentAttemptCreatedAt.Add(4 * time.Hour)
if _, err := NewAssessmentAttempt(input); err != nil {
t.Fatalf("lower corrective attempt after eligible predecessor error = %v", err)
}
input.TargetGrade = ptr(GradeMiddle)
if _, err := NewAssessmentAttempt(input); !errors.Is(err, ErrInvalidAssessmentAttempt) {
t.Fatalf("repeated chain grade error = %v, want ErrInvalidAssessmentAttempt", err)
}
input.TargetGrade = ptr(GradeIntern)
if _, err := NewAssessmentAttempt(input); err != nil {
t.Fatalf("strictly lower final grade error = %v", err)
}
confirmedRoot := terminalAssessmentAttempt(t, activeRoot, AssessmentAttemptStateCompleted,
AssessmentAttemptOutcomeConfirmed, testAssessmentAttemptCreatedAt.Add(time.Hour))
input.Chain = []AssessmentAttempt{confirmedRoot}
input.TargetGrade = ptr(GradeMiddle)
if _, err := NewAssessmentAttempt(input); !errors.Is(err, ErrInvalidAssessmentAttempt) {
t.Fatalf("confirmed root correction error = %v, want ErrInvalidAssessmentAttempt", err)
}
input.Chain = []AssessmentAttempt{root, ended}
input.CreatedAt = root.ChainDeadline()
if _, err := NewAssessmentAttempt(input); !errors.Is(err, ErrInvalidAssessmentAttempt) {
t.Fatalf("corrective attempt at chain deadline error = %v, want ErrInvalidAssessmentAttempt", err)
}
}
func TestDemoExpressAttemptHasNoQualificationTrackAndUsesExplicitDuration(t *testing.T) {
policy := testTrainingOnlyAssessmentPolicyVersion(t)
attempt, err := NewAssessmentAttempt(NewAssessmentAttemptInput{
UserID: uuid.New(), Kind: AssessmentAttemptKindDemoExpress, BankCategory: "unit-training-category",
Versions: testTrainingAssessmentAttemptVersions(policy), Policy: policy,
CreatedAt: testAssessmentAttemptCreatedAt, Items: testAssessmentAttemptItems(t, 3),
})
if err != nil {
t.Fatalf("NewAssessmentAttempt(express) error = %v", err)
}
if attempt.Mode() != AssessmentAttemptModeDemoExpress || !attempt.RootAttemptID().IsZero() ||
!attempt.ChainDeadline().IsZero() || !attempt.ExpiresAt().Equal(testAssessmentAttemptCreatedAt.Add(240*time.Second)) {
t.Fatalf("express attempt has qualification fields or wrong duration: %+v", attempt.Snapshot())
}
if attempt.MaxSessions() != 1 || attempt.IdleTimeoutSeconds() != 240 {
t.Fatalf("express session limits = %d sessions / %d seconds, want the explicit training policy values", attempt.MaxSessions(), attempt.IdleTimeoutSeconds())
}
if versions := attempt.Snapshot().Versions; !versions.GradingPolicyVersionID.IsZero() || versions.OpeningID != uuid.Nil ||
versions.TrainingBindingID == uuid.Nil || versions.TrainingManifestHash == [32]byte{} {
t.Fatalf("express attempt must pin only its separate reviewed training source: %+v", versions)
}
specialization := SpecializationBackend
_, err = NewAssessmentAttempt(NewAssessmentAttemptInput{
UserID: uuid.New(), Kind: AssessmentAttemptKindDemoExpress, BankCategory: "unit-training-category", Specialization: &specialization,
Versions: testTrainingAssessmentAttemptVersions(policy), Policy: policy,
CreatedAt: testAssessmentAttemptCreatedAt, Items: testAssessmentAttemptItems(t, 3),
})
if !errors.Is(err, ErrInvalidAssessmentAttempt) {
t.Fatalf("express attempt with category error = %v, want ErrInvalidAssessmentAttempt", err)
}
}
func TestAttemptCreationRequiresRealFrozenItemsAndDistinctFamilies(t *testing.T) {
userID := uuid.New()
policy := testAssessmentAttemptPolicyVersion(t)
specialization, grade := SpecializationBackend, GradeJunior
input := NewAssessmentAttemptInput{
UserID: userID, Kind: AssessmentAttemptKindRoot, BankCategory: "unit-category",
Specialization: &specialization, TargetGrade: &grade,
Versions: testAssessmentAttemptVersions(t, policy), Policy: policy,
CreatedAt: testAssessmentAttemptCreatedAt,
}
if _, err := NewAssessmentAttempt(input); !errors.Is(err, ErrInvalidAssessmentAttempt) {
t.Fatalf("NewAssessmentAttempt(empty bank) error = %v, want ErrInvalidAssessmentAttempt", err)
}
item := testAssessmentAttemptItems(t, 1)[0]
input.Items = []AssessmentAttemptItemInput{item, item}
if _, err := NewAssessmentAttempt(input); !errors.Is(err, ErrInvalidAssessmentAttempt) {
t.Fatalf("NewAssessmentAttempt(repeated family) error = %v, want ErrInvalidAssessmentAttempt", err)
}
}
func TestAttemptSnapshotCopiesAndRedactsFrozenContent(t *testing.T) {
attempt := testRootAssessmentAttempt(t, uuid.New(), GradeJunior)
first := attempt.Snapshot()
statement := first.Items[0].Variant.Statement
answer := first.Items[0].Variant.ReferenceAnswer
first.Items[0].Variant.Statement = "changed"
first.Items[0].Variant.Parameters["capacity"] = 999
if second := attempt.Snapshot(); second.Items[0].Variant.Statement != statement || second.Items[0].Variant.Parameters["capacity"] == 999 {
t.Fatal("mutating a snapshot changed the attempt's frozen variant")
}
if got := fmt.Sprint(attempt); got != redactedAssessmentAttempt {
t.Fatalf("attempt String() = %q, want redacted marker", got)
}
if got := fmt.Sprint(first.Items[0]); got != redactedAssessmentAttempt {
t.Fatalf("item String() = %q, want redacted marker", got)
}
if got := fmt.Sprint(first); got != redactedAssessmentAttempt {
t.Fatalf("snapshot String() = %q, want redacted marker", got)
}
if answer == "" {
t.Fatal("test variant has no reference answer")
}
publicJSON, err := json.Marshal(attempt.PublicSnapshot())
if err != nil {
t.Fatalf("json.Marshal(PublicSnapshot) error = %v", err)
}
for _, privateName := range []string{"reference_answer", "answer", "seed", "family_key", "user_id", "opening_id", "rubric"} {
if strings.Contains(string(publicJSON), `"`+privateName+`"`) {
t.Fatalf("public attempt snapshot contains private field %q: %s", privateName, publicJSON)
}
}
if public := attempt.PublicSnapshot(); public.CurrentItem == nil || public.CurrentItem.Prompt != statement ||
public.CurrentItem.ID != first.Items[0].ID || public.AnsweredItems != 0 {
t.Fatalf("public attempt projection = %+v, want the current prompt without answers", public)
}
}
func TestFrozenVariantStorageBoundCoversWorstCaseJSONEscaping(t *testing.T) {
key, err := ParseAssessmentFamilyKey("max-content-family")
if err != nil {
t.Fatal(err)
}
criteria := make([]AssessmentRubricCriterion, maxAssessmentRubricCriteria)
for index := range criteria {
criteria[index] = AssessmentRubricCriterion{
ID: fmt.Sprintf("criterion_%d", index), Description: strings.Repeat("<", maxAssessmentTextLength),
}
}
variant := AssessmentVariant{
FamilyID: AssessmentFamilyID(uuid.New()), FamilyKey: key, FamilyVersion: 1,
Seed: 1, Parameters: map[string]int32{"value": 1},
Statement: strings.Repeat("<", maxStatementBytes), ReferenceAnswer: strings.Repeat("<", maxAssessmentTextLength),
AnswerFormat: AnswerFormatInteger,
Rubric: AssessmentRubric{Principle: strings.Repeat("<", maxAssessmentTextLength), Criteria: criteria},
}
encoded, err := MarshalAssessmentAttemptVariant(variant)
if err != nil {
t.Fatalf("json.Marshal(maximum valid variant) error = %v", err)
}
if len(encoded) <= 256<<10 || len(encoded) > maxAssessmentAttemptVariantBytes || !validFrozenVariant(variant) {
t.Fatalf("worst-case encoded variant size = %d bytes; want above 256 KiB, within %d bytes, and valid", len(encoded), maxAssessmentAttemptVariantBytes)
}
variant.Statement = string([]byte{0xff})
if validFrozenVariant(variant) {
t.Fatal("invalid UTF-8 statement was accepted")
}
variant.Statement = "valid"
variant.Parameters = map[string]int32{strings.Repeat("x", maxAssessmentAttemptVariantBytes): 1}
if validFrozenVariant(variant) {
t.Fatal("variant exceeding the persisted JSON byte cap was accepted")
}
}
func TestStartOrResumeSessionIsExplicitVersionedAndBounded(t *testing.T) {
attempt := testRootAssessmentAttempt(t, uuid.New(), GradeJunior)
unchanged, changed, err := attempt.StartOrResumeSession(1, testAssessmentAttemptCreatedAt.Add(time.Minute))
if err != nil || changed || unchanged.Version() != 1 || unchanged.SessionsUsed() != 1 {
t.Fatalf("active-session repeat = version %d, sessions %d, changed %t, err %v", unchanged.Version(), unchanged.SessionsUsed(), changed, err)
}
resumedAt := testAssessmentAttemptCreatedAt.Add(30 * time.Minute)
resumed, changed, err := attempt.StartOrResumeSession(1, resumedAt)
if err != nil || !changed || resumed.Version() != 2 || resumed.SessionsUsed() != 2 || !resumed.Snapshot().SessionStartedAt.Equal(resumedAt) {
t.Fatalf("first resume = version %d, sessions %d, changed %t, err %v", resumed.Version(), resumed.SessionsUsed(), changed, err)
}
endedAt := resumedAt.Add(30 * time.Minute)
expired, changed, err := resumed.StartOrResumeSession(2, endedAt)
if err != nil || !changed || expired.State() != AssessmentAttemptStateExpired || expired.Version() != 3 || expired.SessionsUsed() != 2 {
t.Fatalf("session-budget end = state %s, version %d, sessions %d, changed %t, err %v", expired.State(), expired.Version(), expired.SessionsUsed(), changed, err)
}
if _, _, err := attempt.StartOrResumeSession(0, resumedAt); !errors.Is(err, ErrAssessmentAttemptVersionConflict) {
t.Fatalf("stale session version error = %v, want ErrAssessmentAttemptVersionConflict", err)
}
terminal, changed, err := expired.StartOrResumeSession(3, endedAt.Add(time.Hour))
if err != nil || changed || terminal.Version() != expired.Version() ||
!terminal.Snapshot().UpdatedAt.Equal(expired.Snapshot().UpdatedAt) {
t.Fatalf("terminal session command = version %d, changed %t, err %v; want unchanged stored snapshot", terminal.Version(), changed, err)
}
if _, _, err := expired.StartOrResumeSession(2, endedAt.Add(time.Hour)); !errors.Is(err, ErrAssessmentAttemptVersionConflict) {
t.Fatalf("stale terminal session version error = %v, want version conflict", err)
}
completed := terminalAssessmentAttempt(t, attempt, AssessmentAttemptStateCompleted,
AssessmentAttemptOutcomeNotConfirmed, testAssessmentAttemptCreatedAt.Add(time.Hour))
finished, changed, err := completed.StartOrResumeSession(completed.Version(), testAssessmentAttemptCreatedAt.Add(2*time.Hour))
if err != nil || changed || finished.Version() != completed.Version() ||
!finished.Snapshot().EndedAt.Equal(completed.Snapshot().EndedAt) {
t.Fatalf("completed session command = version %d, changed %t, err %v; want unchanged stored snapshot", finished.Version(), changed, err)
}
}
func TestStartOrResumeSessionExpiresAtAttemptDeadlineWithoutExtendingIt(t *testing.T) {
attempt := testRootAssessmentAttempt(t, uuid.New(), GradeJunior)
attemptExpiry := attempt.ExpiresAt()
expired, changed, err := attempt.StartOrResumeSession(1, attemptExpiry)
if err != nil || !changed || expired.State() != AssessmentAttemptStateExpired || expired.Version() != 2 ||
!expired.ExpiresAt().Equal(attemptExpiry) || !expired.Snapshot().EndedAt.Equal(attemptExpiry) {
t.Fatalf("deadline transition = %+v, changed %t, err %v", expired.Snapshot(), changed, err)
}
}
func TestStartOrResumeSessionDoesNotExpirePendingLifecycleStates(t *testing.T) {
for _, state := range []AssessmentAttemptState{
AssessmentAttemptStatePracticePending,
AssessmentAttemptStateAdditionalPracticePending,
AssessmentAttemptStateReadyToFinalize,
} {
t.Run(string(state), func(t *testing.T) {
attempt := testRootAssessmentAttempt(t, uuid.New(), GradeJunior)
snapshot := attempt.Snapshot()
snapshot.State = state
if state == AssessmentAttemptStateReadyToFinalize {
answeredAt := snapshot.CreatedAt.Add(time.Second)
for index := range snapshot.Items {
item := &snapshot.Items[index]
answer := json.RawMessage(fmt.Sprintf(`{"format":"number","number":%s}`, item.Variant.ReferenceAnswer))
canonical, _, err := CanonicalAssessmentAnswerForVariant(answer, item.Variant)
if err != nil {
t.Fatalf("CanonicalAssessmentAnswerForVariant() error = %v", err)
}
item.Answer, item.AnsweredAt = canonical, answeredAt
}
snapshot.LastActivityAt, snapshot.UpdatedAt = answeredAt, answeredAt
}
attempt, err := RestoreAssessmentAttempt(snapshot)
if err != nil {
t.Fatalf("RestoreAssessmentAttempt() error = %v", err)
}
result, changed, err := attempt.StartOrResumeSession(attempt.Version(), attempt.ExpiresAt())
if err != nil || changed || result.State() != state || result.Version() != attempt.Version() ||
result.SessionsUsed() != attempt.SessionsUsed() ||
!result.Snapshot().UpdatedAt.Equal(attempt.Snapshot().UpdatedAt) ||
!result.Snapshot().EndedAt.IsZero() {
t.Fatalf("session transition = state %s, version %d, sessions %d, changed %t, err %v; want unchanged %s",
result.State(), result.Version(), result.SessionsUsed(), changed, err, state)
}
})
}
}
func TestAssessmentAttemptCanonicalizesTimesAndBoundsStoredAnswers(t *testing.T) {
userID := uuid.New()
policy := testAssessmentAttemptPolicyVersion(t)
specialization, grade := SpecializationBackend, GradeJunior
created := time.Date(2026, time.October, 7, 12, 0, 0, 123456789, time.FixedZone("test", 3*60*60))
attempt, err := NewAssessmentAttempt(NewAssessmentAttemptInput{
UserID: userID, Kind: AssessmentAttemptKindRoot, BankCategory: "unit-category",
Specialization: &specialization, TargetGrade: &grade,
Versions: testAssessmentAttemptVersions(t, policy), Policy: policy,
CreatedAt: created, Items: testAssessmentAttemptItems(t, 1),
})
if err != nil {
t.Fatalf("NewAssessmentAttempt() error = %v", err)
}
wantCreated := time.UnixMicro(created.UTC().UnixMicro()).UTC()
if got := attempt.Snapshot().CreatedAt; !got.Equal(wantCreated) || got.Location() != time.UTC || got.Nanosecond()%1000 != 0 {
t.Fatalf("created time = %s (%s), want canonical UTC microseconds %s", got, got.Location(), wantCreated)
}
snapshot := attempt.Snapshot()
snapshot.UpdatedAt = snapshot.CreatedAt.Add(time.Minute)
sourceAnswer, err := json.Marshal(struct {
Format string `json:"format"`
SourceCode string `json:"source_code"`
}{Format: "practice", SourceCode: strings.Repeat("<", 65536)})
if err != nil {
t.Fatalf("json.Marshal(maximum escaped source answer) error = %v", err)
}
snapshot.Items[0].Answer, err = CanonicalAssessmentAttemptAnswer(sourceAnswer)
if err != nil {
t.Fatalf("CanonicalAssessmentAttemptAnswer(maximum escaped source) error = %v", err)
}
if len(snapshot.Items[0].Answer) <= 6*65536 {
t.Fatalf("canonical source answer length = %d, want HTML escaping overhead", len(snapshot.Items[0].Answer))
}
snapshot.Items[0].AnsweredAt = snapshot.CreatedAt.Add(30 * time.Second)
withAnswer, err := RestoreAssessmentAttempt(snapshot)
if err != nil {
t.Fatalf("RestoreAssessmentAttempt(maximum escaped source answer) error = %v", err)
}
controlAnswer, err := json.Marshal(struct {
Format string `json:"format"`
Config string `json:"config"`
}{Format: "configuration", Config: string([]byte{0, '\n', '\t'})})
if err != nil {
t.Fatalf("json.Marshal(schema-valid control characters) error = %v", err)
}
snapshot.Items[0].Answer, err = CanonicalAssessmentAttemptAnswer(controlAnswer)
if err != nil {
t.Fatalf("CanonicalAssessmentAttemptAnswer(schema-valid control characters) error = %v", err)
}
if !bytes.Contains(snapshot.Items[0].Answer, []byte(`\u0000`)) {
t.Fatalf("canonical answer did not preserve escaped NUL: %q", snapshot.Items[0].Answer)
}
snapshot.Items[0].AnsweredAt = snapshot.CreatedAt.Add(45 * time.Second)
if _, err := RestoreAssessmentAttempt(snapshot); err != nil {
t.Fatalf("RestoreAssessmentAttempt(schema-valid escaped control characters) error = %v", err)
}
stored := withAnswer.Snapshot()
stored.Items[0].Answer[0] = '['
if withAnswer.Snapshot().Items[0].Answer[0] != '{' {
t.Fatal("mutating a returned answer snapshot changed the attempt")
}
snapshot.Items[0].AnsweredAt = snapshot.UpdatedAt.Add(time.Microsecond)
if _, err := RestoreAssessmentAttempt(snapshot); !errors.Is(err, ErrInvalidAssessmentAttempt) {
t.Fatalf("answer after attempt update error = %v, want invalid attempt", err)
}
snapshot.Items[0].AnsweredAt = snapshot.ExpiresAt
if _, err := RestoreAssessmentAttempt(snapshot); !errors.Is(err, ErrInvalidAssessmentAttempt) {
t.Fatalf("answer at attempt expiry error = %v, want invalid attempt", err)
}
snapshot.Items[0].AnsweredAt = snapshot.CreatedAt.Add(time.Second)
oversizedAnswer, err := json.Marshal(struct {
Format string `json:"format"`
SourceCode string `json:"source_code"`
}{Format: "practice", SourceCode: strings.Repeat("<", maxAssessmentAttemptAnswerBytes/6+1)})
if err != nil {
t.Fatalf("json.Marshal(oversized answer) error = %v", err)
}
if _, err := CanonicalAssessmentAttemptAnswer(oversizedAnswer); !errors.Is(err, ErrInvalidAssessmentAttempt) {
t.Fatalf("CanonicalAssessmentAttemptAnswer(oversized) error = %v, want invalid attempt", err)
}
snapshot.Items[0].Answer = oversizedAnswer
if _, err := RestoreAssessmentAttempt(snapshot); !errors.Is(err, ErrInvalidAssessmentAttempt) {
t.Fatalf("oversized answer error = %v, want invalid attempt", err)
}
}
func ptr[T any](value T) *T { return &value }
@@ -0,0 +1,222 @@
package domain
import (
"fmt"
"time"
"github.com/google/uuid"
)
const (
assessmentResultSchemaVersion int32 = 1
assessmentResultRuleBasicPassMark = "demo_basic_pass_mark"
assessmentResultRuleTrainingOnly = "demonstration_only"
)
// AssessmentAttemptResultPins retain the private immutable source identities
// behind a candidate-visible result.
type AssessmentAttemptResultPins struct {
ProductPolicyVersionID PolicyVersionID `json:"product_policy_version_id"`
ProductPolicyVersion int32 `json:"product_policy_version"`
GradingPolicyVersionID PolicyVersionID `json:"grading_policy_version_id"`
OpeningID uuid.UUID `json:"opening_id"`
OpeningManifestHash [32]byte `json:"opening_manifest_sha256"`
TrainingBindingID uuid.UUID `json:"training_binding_id"`
TrainingManifestHash [32]byte `json:"training_manifest_sha256"`
BankVersion string `json:"bank_version"`
AlgorithmVersion string `json:"algorithm_version"`
}
// AssessmentAttemptDecisionRationale records the exact basic rule and policy
// threshold used by the server. It contains no answer keys or per-item data.
type AssessmentAttemptDecisionRationale struct {
Rule string `json:"rule"`
PassMarkBasisPoints int32 `json:"pass_mark_basis_points"`
PassPoints int32 `json:"pass_points"`
ScoredItems int32 `json:"scored_items"`
}
// AssessmentAttemptResultSnapshot is the immutable persisted result for one
// completed attempt. It is separate from mutable attempt progress and stores
// only an allowlisted public projection plus private version pins and rationale.
type AssessmentAttemptResultSnapshot struct {
SchemaVersion int32 `json:"schema_version"`
Attempt AssessmentAttemptPublicSnapshot `json:"attempt"`
Pins AssessmentAttemptResultPins `json:"pins"`
Outcome AssessmentAttemptOutcome `json:"outcome"`
NotDeterminedReason string `json:"not_determined_reason,omitempty"`
BasicScore *AssessmentBasicScore `json:"basic_score,omitempty"`
Rationale AssessmentAttemptDecisionRationale `json:"rationale"`
Limitations []string `json:"limitations"`
Summary string `json:"summary,omitempty"`
DecidedAt time.Time `json:"decided_at"`
}
// NewAssessmentAttemptResultSnapshot binds a finalized domain decision to the
// immutable attempt and its pinned product, bank, and grading versions.
func NewAssessmentAttemptResultSnapshot(
attempt AssessmentAttempt,
decision AssessmentAttemptDecision,
summary string,
limitations []string,
) (AssessmentAttemptResultSnapshot, error) {
const location = "domain.NewAssessmentAttemptResultSnapshot"
snapshot := attempt.Snapshot()
if attempt.IsZero() || snapshot.State != AssessmentAttemptStateCompleted || snapshot.EndedAt.IsZero() {
return AssessmentAttemptResultSnapshot{}, fmt.Errorf("%s - completed attempt is required: %w", location, ErrInvalidAssessmentAttempt)
}
result := AssessmentAttemptResultSnapshot{
SchemaVersion: assessmentResultSchemaVersion, Attempt: attempt.PublicSnapshot(),
Pins: assessmentResultPins(snapshot.Versions), Outcome: decision.Outcome,
BasicScore: clonePointer(decision.Score), Rationale: decision.Rationale,
Limitations: append([]string{}, limitations...), Summary: summary,
DecidedAt: canonicalAssessmentTime(snapshot.EndedAt),
}
if err := ValidateAssessmentAttemptResultSnapshot(result); err != nil {
return AssessmentAttemptResultSnapshot{}, fmt.Errorf("%s - validate result: %w", location, err)
}
return result, nil
}
func assessmentResultPins(versions AssessmentAttemptVersions) AssessmentAttemptResultPins {
return AssessmentAttemptResultPins(versions)
}
// RestoreAssessmentAttemptResultSnapshot detaches slices and validates a
// stored result before it crosses the use-case boundary.
func RestoreAssessmentAttemptResultSnapshot(
result AssessmentAttemptResultSnapshot,
) (AssessmentAttemptResultSnapshot, error) {
public, err := RestoreAssessmentAttemptPublicSnapshot(result.Attempt)
if err != nil {
return AssessmentAttemptResultSnapshot{}, fmt.Errorf("domain.RestoreAssessmentAttemptResultSnapshot - restore public attempt: %w", err)
}
result.Attempt = public
result.BasicScore = clonePointer(result.BasicScore)
result.Limitations = append([]string{}, result.Limitations...)
result.DecidedAt = canonicalAssessmentTime(result.DecidedAt)
if err := ValidateAssessmentAttemptResultSnapshot(result); err != nil {
return AssessmentAttemptResultSnapshot{}, err
}
return result, nil
}
// ValidateAssessmentAttemptResultSnapshot checks stored pins, policy rationale,
// and the reproducible basic score without loading a current policy.
func ValidateAssessmentAttemptResultSnapshot(result AssessmentAttemptResultSnapshot) error {
const location = "domain.ValidateAssessmentAttemptResultSnapshot"
public, err := RestoreAssessmentAttemptPublicSnapshot(result.Attempt)
if err != nil {
return fmt.Errorf("%s - public attempt projection is invalid: %w", location, ErrInvalidAssessmentAttempt)
}
if !validAssessmentResultIdentity(result, public) {
return fmt.Errorf("%s - result identity, versions, or timestamp are invalid: %w", location, ErrInvalidAssessmentAttempt)
}
if !validAssessmentResultLimitations(result.Limitations) {
return fmt.Errorf("%s - result limitations are not a bounded set: %w", location, ErrInvalidAssessmentAttempt)
}
if err := validateAssessmentResultKind(result, public.Kind); err != nil {
return fmt.Errorf("%s - result decision is invalid: %w", location, err)
}
return nil
}
func validAssessmentResultIdentity(result AssessmentAttemptResultSnapshot, public AssessmentAttemptPublicSnapshot) bool {
return result.SchemaVersion == assessmentResultSchemaVersion &&
public.State == AssessmentAttemptStateCompleted && public.FinishedAt != nil &&
!result.DecidedAt.IsZero() && public.FinishedAt.Equal(result.DecidedAt) &&
result.Pins.ProductPolicyVersionID != PolicyVersionID(uuid.Nil) &&
result.Pins.ProductPolicyVersion == public.PolicyVersion &&
result.Pins.BankVersion == public.BankVersion && result.Pins.AlgorithmVersion == public.AlgorithmVersion &&
assessmentVersionLabelPattern.MatchString(result.Pins.BankVersion) &&
assessmentVersionLabelPattern.MatchString(result.Pins.AlgorithmVersion)
}
func validAssessmentResultLimitations(limitations []string) bool {
if limitations == nil || len(limitations) > 10 {
return false
}
seen := make(map[string]struct{}, len(limitations))
for _, limitation := range limitations {
if limitation == "" || len(limitation) > 64 {
return false
}
if _, exists := seen[limitation]; exists {
return false
}
seen[limitation] = struct{}{}
}
return true
}
func validateAssessmentResultKind(result AssessmentAttemptResultSnapshot, kind AssessmentAttemptKind) error {
switch kind {
case AssessmentAttemptKindRoot, AssessmentAttemptKindCorrective:
return validateBasicAssessmentResult(result)
case AssessmentAttemptKindDemoExpress:
return validateTrainingAssessmentResult(result)
default:
return fmt.Errorf("domain.validateAssessmentResultKind - result kind is invalid: %w", ErrInvalidAssessmentAttempt)
}
}
func validateBasicAssessmentResult(result AssessmentAttemptResultSnapshot) error {
if !validBasicResultPins(result.Pins) || !validBasicResultContent(result) {
return ErrInvalidAssessmentAttempt
}
return nil
}
func validBasicResultPins(pins AssessmentAttemptResultPins) bool {
return pins.GradingPolicyVersionID != PolicyVersionID(uuid.Nil) && pins.OpeningID != uuid.Nil &&
pins.OpeningManifestHash != [32]byte{} && pins.TrainingBindingID == uuid.Nil && pins.TrainingManifestHash == [32]byte{}
}
func validBasicResultContent(result AssessmentAttemptResultSnapshot) bool {
if result.Attempt.Mode != AssessmentAttemptModeDemoBasic ||
result.Outcome != AssessmentAttemptOutcomeConfirmed && result.Outcome != AssessmentAttemptOutcomeNotConfirmed ||
result.BasicScore == nil || result.NotDeterminedReason != "" || result.Summary != "" ||
result.Rationale.Rule != assessmentResultRuleBasicPassMark ||
result.Rationale.PassMarkBasisPoints < 1 || result.Rationale.PassMarkBasisPoints > int32(basisPointsPerUnit) {
return false
}
return result.Rationale.ScoredItems >= 1 && result.Rationale.ScoredItems <= result.Attempt.MaxItems &&
result.Rationale.ScoredItems == result.BasicScore.MaxPoints &&
result.Rationale.PassPoints == result.BasicScore.PassPoints &&
validStoredBasicDecision(result.Outcome, *result.BasicScore, result.Rationale)
}
func validateTrainingAssessmentResult(result AssessmentAttemptResultSnapshot) error {
if result.Attempt.Mode != AssessmentAttemptModeDemoExpress || !validTrainingResultPins(result.Pins) ||
result.Outcome != AssessmentAttemptOutcomeDemonstration || result.BasicScore != nil ||
result.NotDeterminedReason != "" || result.Summary == "" ||
result.Rationale != (AssessmentAttemptDecisionRationale{Rule: assessmentResultRuleTrainingOnly}) {
return ErrInvalidAssessmentAttempt
}
return nil
}
func validTrainingResultPins(pins AssessmentAttemptResultPins) bool {
return pins.GradingPolicyVersionID == PolicyVersionID(uuid.Nil) && pins.OpeningID == uuid.Nil &&
pins.OpeningManifestHash == [32]byte{} && pins.TrainingBindingID != uuid.Nil && pins.TrainingManifestHash != [32]byte{}
}
func validStoredBasicDecision(
outcome AssessmentAttemptOutcome,
score AssessmentBasicScore,
rationale AssessmentAttemptDecisionRationale,
) bool {
if score.MaxPoints < 1 || score.Points < 0 || score.Points > score.MaxPoints ||
score.PassPoints < 1 || score.PassPoints > score.MaxPoints {
return false
}
passPoints := (int64(rationale.ScoredItems)*int64(rationale.PassMarkBasisPoints) + int64(basisPointsPerUnit) - 1) / int64(basisPointsPerUnit)
if passPoints != int64(score.PassPoints) || int64(rationale.PassPoints) != passPoints {
return false
}
wantOutcome := AssessmentAttemptOutcomeNotConfirmed
if score.Points >= score.PassPoints {
wantOutcome = AssessmentAttemptOutcomeConfirmed
}
return outcome == wantOutcome
}
@@ -0,0 +1,248 @@
package domain
import (
"errors"
"fmt"
"math"
"slices"
"time"
"github.com/google/uuid"
)
var ErrInvalidAssessmentSignal = errors.New("invalid assessment signal")
const (
maxAssessmentSignalEvents = 50
maxAssessmentSignalDurationMS = int32(259200000)
maxAssessmentSignalSizeBytes = int32(math.MaxInt32)
maxAssessmentSignalReceiptSize = int32(50)
)
type AssessmentSignalKind string
const (
AssessmentSignalFocusLoss AssessmentSignalKind = "focus_loss"
AssessmentSignalCopy AssessmentSignalKind = "copy"
AssessmentSignalPaste AssessmentSignalKind = "paste"
AssessmentSignalCut AssessmentSignalKind = "cut"
AssessmentSignalFullscreenExit AssessmentSignalKind = "fullscreen_exit"
)
func (kind AssessmentSignalKind) IsKnown() bool {
switch kind {
case AssessmentSignalFocusLoss, AssessmentSignalCopy, AssessmentSignalPaste,
AssessmentSignalCut, AssessmentSignalFullscreenExit:
return true
default:
return false
}
}
type AssessmentSignalEventInput struct {
Kind AssessmentSignalKind
ItemInstanceID uuid.UUID
OccurredAt time.Time
DurationMS *int32
SizeBytes *int32
}
type AssessmentSignalEvent struct {
kind AssessmentSignalKind
itemInstanceID uuid.UUID
occurredAt time.Time
durationMS int32
hasDuration bool
sizeBytes int32
hasSize bool
}
func NewAssessmentSignalEvent(input AssessmentSignalEventInput) (AssessmentSignalEvent, error) {
const location = "domain.NewAssessmentSignalEvent"
if input.ItemInstanceID == uuid.Nil || !input.Kind.IsKnown() {
return AssessmentSignalEvent{}, fmt.Errorf("%s - event kind and item instance are required: %w", location, ErrInvalidAssessmentSignal)
}
occurredAt, err := canonicalAssessmentSignalTime(input.OccurredAt)
if err != nil {
return AssessmentSignalEvent{}, fmt.Errorf("%s - client timestamp is invalid: %w", location, err)
}
return newAssessmentSignalEvent(input, occurredAt)
}
func newAssessmentSignalEvent(input AssessmentSignalEventInput, occurredAt time.Time) (AssessmentSignalEvent, error) {
switch input.Kind {
case AssessmentSignalFocusLoss:
return assessmentFocusLossEvent(input, occurredAt)
case AssessmentSignalCopy, AssessmentSignalPaste, AssessmentSignalCut:
return assessmentClipboardEvent(input, occurredAt)
case AssessmentSignalFullscreenExit:
return assessmentFullscreenExitEvent(input, occurredAt)
default:
return AssessmentSignalEvent{}, fmt.Errorf("domain.NewAssessmentSignalEvent - event kind is unknown: %w", ErrInvalidAssessmentSignal)
}
}
func assessmentFocusLossEvent(input AssessmentSignalEventInput, occurredAt time.Time) (AssessmentSignalEvent, error) {
if input.DurationMS == nil || *input.DurationMS < 1 || *input.DurationMS > maxAssessmentSignalDurationMS || input.SizeBytes != nil {
return AssessmentSignalEvent{}, fmt.Errorf("domain.NewAssessmentSignalEvent - focus loss requires a bounded duration only: %w", ErrInvalidAssessmentSignal)
}
return AssessmentSignalEvent{
kind: input.Kind, itemInstanceID: input.ItemInstanceID, occurredAt: occurredAt,
durationMS: *input.DurationMS, hasDuration: true,
}, nil
}
func assessmentClipboardEvent(input AssessmentSignalEventInput, occurredAt time.Time) (AssessmentSignalEvent, error) {
if input.SizeBytes == nil || *input.SizeBytes < 0 || *input.SizeBytes > maxAssessmentSignalSizeBytes || input.DurationMS != nil {
return AssessmentSignalEvent{}, fmt.Errorf("domain.NewAssessmentSignalEvent - clipboard signal requires a byte count only: %w", ErrInvalidAssessmentSignal)
}
return AssessmentSignalEvent{
kind: input.Kind, itemInstanceID: input.ItemInstanceID, occurredAt: occurredAt,
sizeBytes: *input.SizeBytes, hasSize: true,
}, nil
}
func assessmentFullscreenExitEvent(input AssessmentSignalEventInput, occurredAt time.Time) (AssessmentSignalEvent, error) {
if input.DurationMS != nil || input.SizeBytes != nil {
return AssessmentSignalEvent{}, fmt.Errorf("domain.NewAssessmentSignalEvent - fullscreen exit has no measurements: %w", ErrInvalidAssessmentSignal)
}
return AssessmentSignalEvent{kind: input.Kind, itemInstanceID: input.ItemInstanceID, occurredAt: occurredAt}, nil
}
func (event AssessmentSignalEvent) Kind() AssessmentSignalKind { return event.kind }
func (event AssessmentSignalEvent) ItemInstanceID() uuid.UUID { return event.itemInstanceID }
func (event AssessmentSignalEvent) OccurredAt() time.Time { return event.occurredAt }
func (event AssessmentSignalEvent) DurationMS() (int32, bool) {
return event.durationMS, event.hasDuration
}
func (event AssessmentSignalEvent) SizeBytes() (int32, bool) { return event.sizeBytes, event.hasSize }
type AssessmentSignalBatch struct {
id uuid.UUID
attemptID AssessmentAttemptID
receivedAt time.Time
events []AssessmentSignalEvent
}
func NewAssessmentSignalBatch(
id uuid.UUID,
attemptID AssessmentAttemptID,
receivedAt time.Time,
events []AssessmentSignalEvent,
) (AssessmentSignalBatch, error) {
const location = "domain.NewAssessmentSignalBatch"
if id == uuid.Nil || attemptID.IsZero() || len(events) == 0 || len(events) > maxAssessmentSignalEvents {
return AssessmentSignalBatch{}, fmt.Errorf("%s - batch identifiers and 1 to %d events are required: %w", location, maxAssessmentSignalEvents, ErrInvalidAssessmentSignal)
}
canonical, err := canonicalAssessmentSignalTime(receivedAt)
if err != nil {
return AssessmentSignalBatch{}, fmt.Errorf("%s - server receipt time is invalid: %w", location, err)
}
if err := validateAssessmentSignalBatchEvents(events); err != nil {
return AssessmentSignalBatch{}, fmt.Errorf("%s - an event is invalid: %w", location, err)
}
return AssessmentSignalBatch{id: id, attemptID: attemptID, receivedAt: canonical, events: slices.Clone(events)}, nil
}
func validateAssessmentSignalBatchEvents(events []AssessmentSignalEvent) error {
for _, event := range events {
if err := validateAssessmentSignalBatchEvent(event); err != nil {
return err
}
}
return nil
}
func validateAssessmentSignalBatchEvent(event AssessmentSignalEvent) error {
if event.itemInstanceID == uuid.Nil || !event.kind.IsKnown() || event.occurredAt.IsZero() {
return ErrInvalidAssessmentSignal
}
switch event.kind {
case AssessmentSignalFocusLoss:
return validateAssessmentSignalFocusLoss(event)
case AssessmentSignalCopy, AssessmentSignalPaste, AssessmentSignalCut:
return validateAssessmentSignalClipboard(event)
case AssessmentSignalFullscreenExit:
return validateAssessmentSignalFullscreenExit(event)
default:
return ErrInvalidAssessmentSignal
}
}
func validateAssessmentSignalFocusLoss(event AssessmentSignalEvent) error {
if !event.hasDuration || event.durationMS < 1 || event.durationMS > maxAssessmentSignalDurationMS || event.hasSize {
return ErrInvalidAssessmentSignal
}
return nil
}
func validateAssessmentSignalClipboard(event AssessmentSignalEvent) error {
if !event.hasSize || event.sizeBytes < 0 || event.hasDuration {
return ErrInvalidAssessmentSignal
}
return nil
}
func validateAssessmentSignalFullscreenExit(event AssessmentSignalEvent) error {
if event.hasDuration || event.hasSize {
return ErrInvalidAssessmentSignal
}
return nil
}
func (batch AssessmentSignalBatch) ID() uuid.UUID { return batch.id }
func (batch AssessmentSignalBatch) AttemptID() AssessmentAttemptID { return batch.attemptID }
func (batch AssessmentSignalBatch) ReceivedAt() time.Time { return batch.receivedAt }
func (batch AssessmentSignalBatch) Events() []AssessmentSignalEvent {
return slices.Clone(batch.events)
}
type AssessmentSignalReceiptStatus string
const (
AssessmentSignalReceiptAccepted AssessmentSignalReceiptStatus = "accepted"
AssessmentSignalReceiptSaturated AssessmentSignalReceiptStatus = "saturated"
)
type AssessmentSignalReceipt struct {
status AssessmentSignalReceiptStatus
acceptedEvents int32
receivedAt time.Time
}
func NewAssessmentSignalReceipt(
status AssessmentSignalReceiptStatus,
acceptedEvents int32,
receivedAt time.Time,
) (AssessmentSignalReceipt, error) {
const location = "domain.NewAssessmentSignalReceipt"
canonical, err := canonicalAssessmentSignalTime(receivedAt)
if err != nil {
return AssessmentSignalReceipt{}, fmt.Errorf("%s - receipt time is invalid: %w", location, err)
}
switch status {
case AssessmentSignalReceiptAccepted:
if acceptedEvents < 1 || acceptedEvents > maxAssessmentSignalReceiptSize {
return AssessmentSignalReceipt{}, fmt.Errorf("%s - accepted event count is outside the batch bound: %w", location, ErrInvalidAssessmentSignal)
}
case AssessmentSignalReceiptSaturated:
if acceptedEvents != 0 {
return AssessmentSignalReceipt{}, fmt.Errorf("%s - a saturated receipt accepts no events: %w", location, ErrInvalidAssessmentSignal)
}
default:
return AssessmentSignalReceipt{}, fmt.Errorf("%s - receipt status is unknown: %w", location, ErrInvalidAssessmentSignal)
}
return AssessmentSignalReceipt{status: status, acceptedEvents: acceptedEvents, receivedAt: canonical}, nil
}
func (receipt AssessmentSignalReceipt) Status() AssessmentSignalReceiptStatus { return receipt.status }
func (receipt AssessmentSignalReceipt) AcceptedEvents() int32 { return receipt.acceptedEvents }
func (receipt AssessmentSignalReceipt) ReceivedAt() time.Time { return receipt.receivedAt }
func canonicalAssessmentSignalTime(value time.Time) (time.Time, error) {
canonical := value.UTC().Truncate(time.Microsecond)
if value.IsZero() || canonical.Year() < 1 || canonical.Year() > 9999 {
return time.Time{}, ErrInvalidAssessmentSignal
}
return canonical, nil
}
@@ -0,0 +1,113 @@
package domain_test
import (
"errors"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
)
func TestAssessmentSignalEventValidatesAllowlistedMeasurements(t *testing.T) {
itemID := uuid.New()
clientTime := time.Date(2026, time.October, 7, 12, 30, 0, 123456789, time.FixedZone("test", 3*60*60))
duration := int32(2500)
size := int32(4096)
tests := []struct {
name string
input domain.AssessmentSignalEventInput
kind domain.AssessmentSignalKind
}{
{name: "focus loss", input: domain.AssessmentSignalEventInput{Kind: domain.AssessmentSignalFocusLoss, ItemInstanceID: itemID, OccurredAt: clientTime, DurationMS: &duration}, kind: domain.AssessmentSignalFocusLoss},
{name: "copy", input: domain.AssessmentSignalEventInput{Kind: domain.AssessmentSignalCopy, ItemInstanceID: itemID, OccurredAt: clientTime, SizeBytes: &size}, kind: domain.AssessmentSignalCopy},
{name: "paste", input: domain.AssessmentSignalEventInput{Kind: domain.AssessmentSignalPaste, ItemInstanceID: itemID, OccurredAt: clientTime, SizeBytes: &size}, kind: domain.AssessmentSignalPaste},
{name: "cut", input: domain.AssessmentSignalEventInput{Kind: domain.AssessmentSignalCut, ItemInstanceID: itemID, OccurredAt: clientTime, SizeBytes: &size}, kind: domain.AssessmentSignalCut},
{name: "fullscreen exit", input: domain.AssessmentSignalEventInput{Kind: domain.AssessmentSignalFullscreenExit, ItemInstanceID: itemID, OccurredAt: clientTime}, kind: domain.AssessmentSignalFullscreenExit},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
event, err := domain.NewAssessmentSignalEvent(test.input)
if err != nil {
t.Fatalf("NewAssessmentSignalEvent() error = %v", err)
}
if event.Kind() != test.kind || event.ItemInstanceID() != itemID {
t.Fatalf("event identity = %s/%s", event.Kind(), event.ItemInstanceID())
}
if got := event.OccurredAt(); !got.Equal(time.Date(2026, time.October, 7, 9, 30, 0, 123456000, time.UTC)) || got.Location() != time.UTC {
t.Fatalf("canonical event time = %s, want UTC microsecond timestamp", got)
}
})
}
}
func TestAssessmentSignalEventRejectsMismatchedOrUnboundedMeasurements(t *testing.T) {
itemID := uuid.New()
validTime := time.Date(2026, time.October, 7, 12, 0, 0, 0, time.UTC)
zero := int32(0)
tooLong := int32(259200001)
size := int32(1)
unknown := domain.AssessmentSignalKind("answer_text")
tests := []struct {
name string
input domain.AssessmentSignalEventInput
}{
{name: "unknown kind", input: domain.AssessmentSignalEventInput{Kind: unknown, ItemInstanceID: itemID, OccurredAt: validTime}},
{name: "missing item", input: domain.AssessmentSignalEventInput{Kind: domain.AssessmentSignalFullscreenExit, OccurredAt: validTime}},
{name: "missing timestamp", input: domain.AssessmentSignalEventInput{Kind: domain.AssessmentSignalFullscreenExit, ItemInstanceID: itemID}},
{name: "zero focus duration", input: domain.AssessmentSignalEventInput{Kind: domain.AssessmentSignalFocusLoss, ItemInstanceID: itemID, OccurredAt: validTime, DurationMS: &zero}},
{name: "oversized focus duration", input: domain.AssessmentSignalEventInput{Kind: domain.AssessmentSignalFocusLoss, ItemInstanceID: itemID, OccurredAt: validTime, DurationMS: &tooLong}},
{name: "clipboard without size", input: domain.AssessmentSignalEventInput{Kind: domain.AssessmentSignalPaste, ItemInstanceID: itemID, OccurredAt: validTime}},
{name: "negative clipboard size", input: domain.AssessmentSignalEventInput{Kind: domain.AssessmentSignalCopy, ItemInstanceID: itemID, OccurredAt: validTime, SizeBytes: func() *int32 { value := int32(-1); return &value }()}},
{name: "focus with clipboard size", input: domain.AssessmentSignalEventInput{Kind: domain.AssessmentSignalFocusLoss, ItemInstanceID: itemID, OccurredAt: validTime, DurationMS: &size, SizeBytes: &size}},
{name: "fullscreen with measurement", input: domain.AssessmentSignalEventInput{Kind: domain.AssessmentSignalFullscreenExit, ItemInstanceID: itemID, OccurredAt: validTime, SizeBytes: &size}},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if _, err := domain.NewAssessmentSignalEvent(test.input); !errors.Is(err, domain.ErrInvalidAssessmentSignal) {
t.Fatalf("NewAssessmentSignalEvent() error = %v, want ErrInvalidAssessmentSignal", err)
}
})
}
}
func TestAssessmentSignalBatchAndReceiptEnforceBounds(t *testing.T) {
attemptID := domain.AssessmentAttemptID(uuid.New())
itemID := uuid.New()
at := time.Date(2026, time.October, 7, 12, 0, 0, 0, time.UTC)
input := domain.AssessmentSignalEventInput{Kind: domain.AssessmentSignalFullscreenExit, ItemInstanceID: itemID, OccurredAt: at}
event, err := domain.NewAssessmentSignalEvent(input)
if err != nil {
t.Fatalf("NewAssessmentSignalEvent() error = %v", err)
}
if _, err := domain.NewAssessmentSignalBatch(uuid.New(), attemptID, at, nil); !errors.Is(err, domain.ErrInvalidAssessmentSignal) {
t.Fatalf("empty NewAssessmentSignalBatch() error = %v", err)
}
tooMany := make([]domain.AssessmentSignalEvent, 51)
for index := range tooMany {
tooMany[index] = event
}
if _, err := domain.NewAssessmentSignalBatch(uuid.New(), attemptID, at, tooMany); !errors.Is(err, domain.ErrInvalidAssessmentSignal) {
t.Fatalf("oversized NewAssessmentSignalBatch() error = %v", err)
}
batch, err := domain.NewAssessmentSignalBatch(uuid.New(), attemptID, at, []domain.AssessmentSignalEvent{event})
if err != nil || len(batch.Events()) != 1 {
t.Fatalf("valid NewAssessmentSignalBatch() = %d events, error %v", len(batch.Events()), err)
}
for _, test := range []struct {
status domain.AssessmentSignalReceiptStatus
count int32
want bool
}{
{status: domain.AssessmentSignalReceiptAccepted, count: 1, want: true},
{status: domain.AssessmentSignalReceiptAccepted, count: 0},
{status: domain.AssessmentSignalReceiptSaturated, count: 0, want: true},
{status: domain.AssessmentSignalReceiptSaturated, count: 1},
} {
_, err := domain.NewAssessmentSignalReceipt(test.status, test.count, at)
if (err == nil) != test.want {
t.Errorf("NewAssessmentSignalReceipt(%s, %d) error = %v, want valid %v", test.status, test.count, err, test.want)
}
}
}
@@ -0,0 +1,156 @@
package domain
import (
"errors"
"fmt"
"slices"
"time"
"github.com/google/uuid"
)
var ErrInvalidCandidateCardAccess = errors.New("invalid candidate card access")
// CandidateCardAccessKind describes an employer read protected by the current
// publication and grant policy.
type CandidateCardAccessKind string
const (
CandidateCardAccessCardViewed CandidateCardAccessKind = "card_viewed"
CandidateCardAccessContactRead CandidateCardAccessKind = "contact_read"
)
// CandidateCardAccessInput contains identifiers and field codes only. It
// never stores the content that was read or a search query.
type CandidateCardAccessInput struct {
CandidateID uuid.UUID
OrganizationID uuid.UUID
ActorID uuid.UUID
Kind CandidateCardAccessKind
ProjectionFields []CardField
ContactFields []ContactField
OccurredAt time.Time
}
// CandidateCardAccess is one immutable audit record for a permitted read.
type CandidateCardAccess struct {
id uuid.UUID
candidateID uuid.UUID
organizationID uuid.UUID
actorID uuid.UUID
kind CandidateCardAccessKind
fieldCodes []string
occurredAt time.Time
}
// NewCandidateCardAccess builds an immutable event for one permitted read.
func NewCandidateCardAccess(input CandidateCardAccessInput) (CandidateCardAccess, error) {
const location = "domain.NewCandidateCardAccess"
if input.CandidateID == uuid.Nil || input.OrganizationID == uuid.Nil || input.ActorID == uuid.Nil || input.OccurredAt.IsZero() {
return CandidateCardAccess{}, fmt.Errorf("%s - identities and time are required: %w", location, ErrInvalidCandidateCardAccess)
}
input.OccurredAt = input.OccurredAt.UTC().Truncate(time.Microsecond)
if err := validateCandidateCardAccessFields(input, true); err != nil {
return CandidateCardAccess{}, fmt.Errorf("%s - validate field codes: %w", location, err)
}
id, err := uuid.NewV7()
if err != nil {
return CandidateCardAccess{}, fmt.Errorf("%s - generate identifier: %w", location, err)
}
return CandidateCardAccess{
id: id, candidateID: input.CandidateID, organizationID: input.OrganizationID,
actorID: input.ActorID, kind: input.Kind, fieldCodes: candidateCardAccessFieldCodes(input),
occurredAt: input.OccurredAt,
}, nil
}
// RestoreCandidateCardAccess validates an immutable audit record loaded from
// storage.
func RestoreCandidateCardAccess(id uuid.UUID, input CandidateCardAccessInput) (CandidateCardAccess, error) {
const location = "domain.RestoreCandidateCardAccess"
if id == uuid.Nil {
return CandidateCardAccess{}, fmt.Errorf("%s - identifier is required: %w", location, ErrInvalidCandidateCardAccess)
}
if err := validateCandidateCardAccessFields(input, false); err != nil {
return CandidateCardAccess{}, fmt.Errorf("%s - validate field codes: %w", location, err)
}
if input.CandidateID == uuid.Nil || input.OrganizationID == uuid.Nil || input.OccurredAt.IsZero() {
return CandidateCardAccess{}, fmt.Errorf("%s - identities and time are required: %w", location, ErrInvalidCandidateCardAccess)
}
return CandidateCardAccess{
id: id, candidateID: input.CandidateID, organizationID: input.OrganizationID,
actorID: input.ActorID, kind: input.Kind, fieldCodes: candidateCardAccessFieldCodes(input),
occurredAt: input.OccurredAt.UTC().Truncate(time.Microsecond),
}, nil
}
func validateCandidateCardAccessFields(input CandidateCardAccessInput, requireActor bool) error {
if requireActor && input.ActorID == uuid.Nil {
return ErrInvalidCandidateCardAccess
}
switch input.Kind {
case CandidateCardAccessCardViewed:
if len(input.ContactFields) != 0 || len(input.ProjectionFields) > 6 {
return ErrInvalidCandidateCardAccess
}
seen := make(map[CardField]struct{}, len(input.ProjectionFields))
for _, field := range input.ProjectionFields {
if !candidateCardProjectionField(field) {
return ErrInvalidCandidateCardAccess
}
if _, exists := seen[field]; exists {
return ErrInvalidCandidateCardAccess
}
seen[field] = struct{}{}
}
case CandidateCardAccessContactRead:
if len(input.ProjectionFields) != 0 || len(input.ContactFields) == 0 {
return ErrInvalidCandidateCardAccess
}
if _, err := NewContactFieldSet(input.ContactFields...); err != nil {
return ErrInvalidCandidateCardAccess
}
default:
return ErrInvalidCandidateCardAccess
}
return nil
}
func candidateCardProjectionField(field CardField) bool {
switch field {
case CardFieldCategories, CardFieldStack, CardFieldExperience, CardFieldSelfAssessment,
CardFieldWorkFormats, CardFieldSalaryCompatibility:
return true
case CardFieldSoftSkills, CardFieldLocation, CardFieldRelocation:
return false
default:
return false
}
}
func candidateCardAccessFieldCodes(input CandidateCardAccessInput) []string {
codes := make([]string, 0, len(input.ProjectionFields)+len(input.ContactFields))
if input.Kind == CandidateCardAccessCardViewed {
for _, field := range input.ProjectionFields {
codes = append(codes, string(field))
}
} else {
for _, field := range input.ContactFields {
codes = append(codes, string(field))
}
}
slices.Sort(codes)
return codes
}
func (access CandidateCardAccess) ID() uuid.UUID { return access.id }
func (access CandidateCardAccess) CandidateID() uuid.UUID { return access.candidateID }
func (access CandidateCardAccess) OrganizationID() uuid.UUID { return access.organizationID }
func (access CandidateCardAccess) ActorID() uuid.UUID { return access.actorID }
func (access CandidateCardAccess) Kind() CandidateCardAccessKind { return access.kind }
func (access CandidateCardAccess) FieldCodes() []string { return slices.Clone(access.fieldCodes) }
func (access CandidateCardAccess) OccurredAt() time.Time { return access.occurredAt }
func (access CandidateCardAccess) IsZero() bool {
return access.id == uuid.Nil || access.candidateID == uuid.Nil || access.organizationID == uuid.Nil
}
@@ -0,0 +1,109 @@
package domain
import (
"errors"
"slices"
"testing"
"time"
"github.com/google/uuid"
)
func TestCandidateCardAccessStoresOnlyCanonicalAllowedFieldCodes(t *testing.T) {
t.Parallel()
now := time.Date(2026, 10, 7, 12, 0, 0, 123456789, time.FixedZone("test", 3*60*60))
access, err := NewCandidateCardAccess(CandidateCardAccessInput{
CandidateID: uuid.New(), OrganizationID: uuid.New(), ActorID: uuid.New(),
Kind: CandidateCardAccessCardViewed,
ProjectionFields: []CardField{CardFieldWorkFormats, CardFieldCategories, CardFieldStack},
OccurredAt: now,
})
if err != nil {
t.Fatalf("NewCandidateCardAccess() error = %v", err)
}
if access.IsZero() || access.Kind() != CandidateCardAccessCardViewed ||
!access.OccurredAt().Equal(now.UTC().Truncate(time.Microsecond)) {
t.Fatalf("restored access = %#v", access)
}
if got := access.FieldCodes(); !slices.Equal(got, []string{"categories", "stack", "work_formats"}) {
t.Fatalf("FieldCodes() = %v", got)
}
}
func TestCandidateCardAccessRejectsPrivateOrMismatchedFields(t *testing.T) {
t.Parallel()
base := CandidateCardAccessInput{
CandidateID: uuid.New(), OrganizationID: uuid.New(), ActorID: uuid.New(),
Kind: CandidateCardAccessCardViewed, ProjectionFields: []CardField{CardFieldStack},
OccurredAt: time.Now(),
}
cases := map[string]func(*CandidateCardAccessInput){
"free-text location": func(input *CandidateCardAccessInput) { input.ProjectionFields = []CardField{CardFieldLocation} },
"duplicate field": func(input *CandidateCardAccessInput) {
input.ProjectionFields = []CardField{CardFieldStack, CardFieldStack}
},
"mixed contact field": func(input *CandidateCardAccessInput) {
input.ContactFields = []ContactField{ContactFieldEmail}
},
"empty contact read": func(input *CandidateCardAccessInput) {
input.Kind = CandidateCardAccessContactRead
input.ProjectionFields = nil
input.ContactFields = nil
},
"unknown kind": func(input *CandidateCardAccessInput) { input.Kind = "workflow_accepted" },
}
for name, mutate := range cases {
t.Run(name, func(t *testing.T) {
t.Parallel()
input := base
mutate(&input)
if _, err := NewCandidateCardAccess(input); !errors.Is(err, ErrInvalidCandidateCardAccess) {
t.Fatalf("NewCandidateCardAccess() error = %v, want ErrInvalidCandidateCardAccess", err)
}
})
}
}
func TestCandidateCardAccessAllowsPseudonymOnlyReadAndActorlessRestore(t *testing.T) {
t.Parallel()
input := CandidateCardAccessInput{
CandidateID: uuid.New(), OrganizationID: uuid.New(), ActorID: uuid.New(),
Kind: CandidateCardAccessCardViewed, OccurredAt: time.Now(),
}
access, err := NewCandidateCardAccess(input)
if err != nil {
t.Fatalf("NewCandidateCardAccess(pseudonym only) error = %v", err)
}
if got := access.FieldCodes(); len(got) != 0 {
t.Fatalf("pseudonym-only field codes = %v, want empty", got)
}
input.ActorID = uuid.Nil
restored, err := RestoreCandidateCardAccess(access.ID(), input)
if err != nil {
t.Fatalf("RestoreCandidateCardAccess(actor anonymized) error = %v", err)
}
if restored.ActorID() != uuid.Nil || restored.ID() != access.ID() {
t.Fatalf("restored actor/id = %s/%s, want nil/%s", restored.ActorID(), restored.ID(), access.ID())
}
}
func TestCandidateCardAccessContactReadUsesClosedContactFieldSet(t *testing.T) {
t.Parallel()
access, err := NewCandidateCardAccess(CandidateCardAccessInput{
CandidateID: uuid.New(), OrganizationID: uuid.New(), ActorID: uuid.New(),
Kind: CandidateCardAccessContactRead,
ContactFields: []ContactField{ContactFieldPhone, ContactFieldEmail},
OccurredAt: time.Now(),
})
if err != nil {
t.Fatalf("NewCandidateCardAccess() error = %v", err)
}
if got := access.FieldCodes(); !slices.Equal(got, []string{"email", "phone"}) {
t.Fatalf("FieldCodes() = %v", got)
}
}
+717
View File
@@ -0,0 +1,717 @@
package domain
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"log/slog"
"slices"
"strings"
"time"
"github.com/google/uuid"
"golang.org/x/text/unicode/norm"
)
var ErrInvalidAnonymousCandidateView = errors.New("invalid anonymous candidate view")
const (
minimumAnonymousCandidateCohort = 5
maximumCandidateViewGeneralization = 5
maximumCandidateViewSpecializations = 9
maximumCandidateViewWorkFormats = 3
candidateViewPseudonymPrefix = "cv1_"
minimumCandidateViewPseudonymKeyLen = 32
)
const candidateViewPseudonymPurpose = "lincodex/anonymous-candidate-view/v1\x00"
const candidatePreviewPseudonymPurpose = "lincodex/anonymous-candidate-preview/v1\x00"
// CandidateViewPseudonymKey is a dedicated secret for organization-scoped
// candidate aliases. It must not be reused for another HMAC purpose.
type CandidateViewPseudonymKey struct {
secret []byte
}
func NewCandidateViewPseudonymKey(secret []byte) (CandidateViewPseudonymKey, error) {
if len(secret) < minimumCandidateViewPseudonymKeyLen {
return CandidateViewPseudonymKey{}, ErrInvalidAnonymousCandidateView
}
return CandidateViewPseudonymKey{secret: slices.Clone(secret)}, nil
}
func (CandidateViewPseudonymKey) String() string { return "[candidate view pseudonym key]" }
func (CandidateViewPseudonymKey) GoString() string { return "[candidate view pseudonym key]" }
func (CandidateViewPseudonymKey) LogValue() slog.Value {
return slog.StringValue("[candidate view pseudonym key]")
}
// ForOrganization derives a stable pseudonym for one candidate in one
// organization. Fixed-width UUID bytes and a purpose label make the HMAC
// input unambiguous and separate it from other keyed identifiers.
func (key CandidateViewPseudonymKey) ForOrganization(organizationID, candidateID uuid.UUID) (string, error) {
if len(key.secret) < minimumCandidateViewPseudonymKeyLen || organizationID == uuid.Nil || candidateID == uuid.Nil {
return "", ErrInvalidAnonymousCandidateView
}
mac := hmac.New(sha256.New, key.secret)
_, _ = mac.Write([]byte(candidateViewPseudonymPurpose))
_, _ = mac.Write(organizationID[:])
_, _ = mac.Write(candidateID[:])
return candidateViewPseudonymPrefix + base64.RawURLEncoding.EncodeToString(mac.Sum(nil)), nil
}
// ForCandidatePreview derives a private preview alias. Its HMAC purpose is
// separate from organization aliases so a preview never reveals a linkable
// organization identity.
func (key CandidateViewPseudonymKey) ForCandidatePreview(candidateID uuid.UUID) (string, error) {
if len(key.secret) < minimumCandidateViewPseudonymKeyLen || candidateID == uuid.Nil {
return "", ErrInvalidAnonymousCandidateView
}
mac := hmac.New(sha256.New, key.secret)
_, _ = mac.Write([]byte(candidatePreviewPseudonymPurpose))
_, _ = mac.Write(candidateID[:])
return candidateViewPseudonymPrefix + base64.RawURLEncoding.EncodeToString(mac.Sum(nil)), nil
}
// CandidateViewSkillCode is a closed technology taxonomy. Raw profile tags
// are never copied to an organization-facing view.
type CandidateViewSkillCode string
const (
CandidateViewSkillGo CandidateViewSkillCode = "go"
CandidateViewSkillPostgreSQL CandidateViewSkillCode = "postgresql"
CandidateViewSkillKafka CandidateViewSkillCode = "kafka"
CandidateViewSkillDocker CandidateViewSkillCode = "docker"
)
var candidateViewSkillCodes = []CandidateViewSkillCode{
CandidateViewSkillDocker,
CandidateViewSkillGo,
CandidateViewSkillKafka,
CandidateViewSkillPostgreSQL,
}
func (code CandidateViewSkillCode) IsKnown() bool {
return slices.Contains(candidateViewSkillCodes, code)
}
// CandidateViewSkillCodes returns the closed skill taxonomy in canonical
// order.
func CandidateViewSkillCodes() []CandidateViewSkillCode {
return slices.Clone(candidateViewSkillCodes)
}
// CanonicalCandidateViewSkill maps a confirmed profile tag only when its
// normalized value exactly matches a supported taxonomy entry.
func CanonicalCandidateViewSkill(raw string) (CandidateViewSkillCode, bool) {
normalized := strings.ToLower(strings.TrimSpace(norm.NFKC.String(raw)))
switch normalized {
case string(CandidateViewSkillGo):
return CandidateViewSkillGo, true
case string(CandidateViewSkillPostgreSQL):
return CandidateViewSkillPostgreSQL, true
case string(CandidateViewSkillKafka):
return CandidateViewSkillKafka, true
case string(CandidateViewSkillDocker):
return CandidateViewSkillDocker, true
default:
return "", false
}
}
// CandidateExperienceBand is the only work-tenure precision available in an
// anonymous candidate view. The first four values are the normal buckets;
// the last two are emitted only when a rare combination must be generalized.
type CandidateExperienceBand string
const (
CandidateExperienceBandZeroToOne CandidateExperienceBand = "0_1"
CandidateExperienceBandOneToThree CandidateExperienceBand = "1_3"
CandidateExperienceBandThreeToSix CandidateExperienceBand = "3_6"
CandidateExperienceBandSixPlus CandidateExperienceBand = "6_plus"
CandidateExperienceBandZeroToThree CandidateExperienceBand = "0_3"
CandidateExperienceBandThreePlus CandidateExperienceBand = "3_plus"
)
func (band CandidateExperienceBand) IsKnown() bool {
switch band {
case CandidateExperienceBandZeroToOne, CandidateExperienceBandOneToThree,
CandidateExperienceBandThreeToSix, CandidateExperienceBandSixPlus,
CandidateExperienceBandZeroToThree, CandidateExperienceBandThreePlus:
return true
default:
return false
}
}
// CandidateViewConfirmationStatus says whether the current authoritative
// result source confirms a specialization. It carries no attempt history.
type CandidateViewConfirmationStatus string
const (
CandidateViewConfirmationConfirmed CandidateViewConfirmationStatus = "confirmed"
CandidateViewConfirmationUnconfirmed CandidateViewConfirmationStatus = "unconfirmed"
)
// CandidateViewConfirmationStrength is a coarse, non-numeric description of
// an authoritative confirmation. It is absent when no category is confirmed.
type CandidateViewConfirmationStrength string
const (
CandidateViewStrengthStandard CandidateViewConfirmationStrength = "standard"
CandidateViewStrengthStrong CandidateViewConfirmationStrength = "strong"
)
func (strength CandidateViewConfirmationStrength) IsKnown() bool {
return strength == CandidateViewStrengthStandard || strength == CandidateViewStrengthStrong
}
// CandidateViewConfirmedCategoryInput is accepted only from an authoritative
// assessment-result source. It intentionally has no field for attempts,
// failures, scores, or the candidate's self-assessment.
type CandidateViewConfirmedCategoryInput struct {
Specialization SpecializationCode
Grade GradeCode
Strength CandidateViewConfirmationStrength
}
type candidateViewStackClaim struct {
value string
status ProfileClaimStatus
}
type candidateViewRoleClaim struct {
value ProfileRole
status ProfileClaimStatus
}
type candidateViewExperienceClaim struct {
startedOn string
endedOn string
status ProfileClaimStatus
}
// CandidateViewProfile is the private, minimal input needed for projection.
// It carries no name, contact, employer, resume quote, summary, salary, or
// free-text location or soft skill.
type CandidateViewProfile struct {
stack []candidateViewStackClaim
roles []candidateViewRoleClaim
experience []candidateViewExperienceClaim
}
func (CandidateViewProfile) String() string { return "[candidate view profile]" }
func (CandidateViewProfile) GoString() string { return "[candidate view profile]" }
func (CandidateViewProfile) LogValue() slog.Value {
return slog.StringValue("[candidate view profile]")
}
// CandidateViewProfileFromContent removes private profile values that are
// not needed to build the anonymous organization-facing view.
func CandidateViewProfileFromContent(content CandidateProfileContent) CandidateViewProfile {
profile := CandidateViewProfile{}
for _, claim := range content.Stack() {
profile.stack = append(profile.stack, candidateViewStackClaim{value: claim.Value(), status: claim.Status()})
}
for _, claim := range content.Roles() {
profile.roles = append(profile.roles, candidateViewRoleClaim{value: claim.Value(), status: claim.Status()})
}
for _, claim := range content.Experience() {
value := claim.Value()
profile.experience = append(profile.experience, candidateViewExperienceClaim{
startedOn: value.StartedOn, endedOn: value.EndedOn, status: claim.Status(),
})
}
return profile
}
// CandidateViewCategory is the category and coarse strength shown only when
// categories were explicitly included in the publication.
type CandidateViewCategory struct {
Specialization SpecializationCode `json:"specialization"`
Grade GradeCode `json:"grade"`
Strength CandidateViewConfirmationStrength `json:"strength"`
}
// CandidateViewSelfAssessment is a candidate-declared specialization and
// grade, separate from the confirmed categories collection.
type CandidateViewSelfAssessment struct {
Specialization SpecializationCode `json:"specialization"`
ConfirmationStatus CandidateViewConfirmationStatus `json:"confirmation_status"`
DeclaredGrade *GradeCode `json:"declared_grade,omitempty"`
}
// CandidateViewSalaryCompatibility is a typed comparison result. The numeric
// salary bounds and the candidate's minimum are never part of a view.
type CandidateViewSalaryCompatibility string
const (
CandidateViewSalaryCompatible CandidateViewSalaryCompatibility = "compatible"
CandidateViewSalaryNotCompatible CandidateViewSalaryCompatibility = "not_compatible"
)
func (compatibility CandidateViewSalaryCompatibility) IsKnown() bool {
return compatibility == CandidateViewSalaryCompatible || compatibility == CandidateViewSalaryNotCompatible
}
// AnonymousCandidateViewDTO is the complete closed organization-facing data
// transfer object. It contains no account ID, raw profile fields, or history.
type AnonymousCandidateViewDTO struct {
Pseudonym string `json:"pseudonym"`
Skills []CandidateViewSkillCode `json:"skills"`
Categories []CandidateViewCategory `json:"categories"`
SelfAssessment []CandidateViewSelfAssessment `json:"self_assessment"`
ExperienceBand *CandidateExperienceBand `json:"experience_band"`
WorkFormats []QuestionnaireWorkFormat `json:"work_formats"`
SalaryCompatibility *CandidateViewSalaryCompatibility `json:"salary_compatibility"`
}
func (AnonymousCandidateViewDTO) String() string { return "[anonymous candidate view]" }
func (AnonymousCandidateViewDTO) GoString() string { return "[anonymous candidate view]" }
func (AnonymousCandidateViewDTO) LogValue() slog.Value {
return slog.StringValue("[anonymous candidate view]")
}
// CandidateViewInput combines explicitly published profile data with typed
// results from authoritative sources. Profile content stays private and is
// projected through a closed allowlist.
type CandidateViewInput struct {
Pseudonym string
PublishedFields CardFieldSet
Profile CandidateViewProfile
AsOf time.Time
ConfirmedCategories []CandidateViewConfirmedCategoryInput
WorkFormats []QuestionnaireWorkFormat
SalaryCompatibility *CandidateViewSalaryCompatibility
}
func (CandidateViewInput) String() string { return "[candidate view input]" }
func (CandidateViewInput) GoString() string { return "[candidate view input]" }
func (CandidateViewInput) LogValue() slog.Value {
return slog.StringValue("[candidate view input]")
}
// AnonymousCandidateView is a validated, organization-scoped anonymous
// projection. The internal generalization level is never exposed.
type AnonymousCandidateView struct {
dto AnonymousCandidateViewDTO
generalizationLevel int
}
// NewAnonymousCandidateView builds a strictly allowlisted projection from
// currently published fields and typed, authoritative inputs.
func NewAnonymousCandidateView(input CandidateViewInput) (AnonymousCandidateView, error) {
const location = "domain.NewAnonymousCandidateView"
if !validCandidateViewPseudonym(input.Pseudonym) {
return AnonymousCandidateView{}, fmt.Errorf("%s - pseudonym is invalid: %w", location, ErrInvalidAnonymousCandidateView)
}
if err := validateCandidateViewConfirmations(input.ConfirmedCategories); err != nil {
return AnonymousCandidateView{}, fmt.Errorf("%s - confirmations are invalid: %w", location, err)
}
view := AnonymousCandidateView{dto: AnonymousCandidateViewDTO{Pseudonym: input.Pseudonym}}
if input.PublishedFields.Contains(CardFieldStack) {
view.dto.Skills = candidateViewSkills(input.Profile)
}
if input.PublishedFields.Contains(CardFieldExperience) {
band, err := candidateViewExperienceBand(input.Profile.experience, input.AsOf)
if err != nil {
return AnonymousCandidateView{}, fmt.Errorf("%s - project experience: %w", location, err)
}
view.dto.ExperienceBand = band
}
if input.PublishedFields.Contains(CardFieldCategories) {
view.dto.Categories = candidateViewCategories(input.ConfirmedCategories)
}
if input.PublishedFields.Contains(CardFieldSelfAssessment) {
view.dto.SelfAssessment = candidateViewSelfAssessments(input.Profile.roles, input.ConfirmedCategories)
}
if input.PublishedFields.Contains(CardFieldWorkFormats) {
formats, err := canonicalCandidateViewWorkFormats(input.WorkFormats)
if err != nil {
return AnonymousCandidateView{}, fmt.Errorf("%s - work formats are invalid: %w", location, err)
}
view.dto.WorkFormats = formats
}
if input.PublishedFields.Contains(CardFieldSalaryCompatibility) && input.SalaryCompatibility != nil {
if !input.SalaryCompatibility.IsKnown() {
return AnonymousCandidateView{}, fmt.Errorf("%s - salary compatibility is invalid: %w", location, ErrInvalidAnonymousCandidateView)
}
value := *input.SalaryCompatibility
view.dto.SalaryCompatibility = &value
}
return view, nil
}
// DTO returns a detached copy of the allowlisted organization-facing value.
func (view AnonymousCandidateView) DTO() AnonymousCandidateViewDTO {
return cloneAnonymousCandidateViewDTO(view.dto)
}
func cloneAnonymousCandidateViewDTO(dto AnonymousCandidateViewDTO) AnonymousCandidateViewDTO {
dto.Skills = slices.Clone(dto.Skills)
dto.Categories = slices.Clone(dto.Categories)
dto.SelfAssessment = slices.Clone(dto.SelfAssessment)
for index := range dto.SelfAssessment {
dto.SelfAssessment[index].DeclaredGrade = clonePointer(dto.SelfAssessment[index].DeclaredGrade)
}
dto.ExperienceBand = clonePointer(dto.ExperienceBand)
dto.WorkFormats = slices.Clone(dto.WorkFormats)
dto.SalaryCompatibility = clonePointer(dto.SalaryCompatibility)
return dto
}
func validCandidateViewPseudonym(pseudonym string) bool {
if !strings.HasPrefix(pseudonym, candidateViewPseudonymPrefix) {
return false
}
encoded := strings.TrimPrefix(pseudonym, candidateViewPseudonymPrefix)
decoded, err := base64.RawURLEncoding.DecodeString(encoded)
return err == nil && len(decoded) == sha256.Size && base64.RawURLEncoding.EncodeToString(decoded) == encoded
}
// IsCandidateViewPseudonym reports whether value is a canonical opaque view
// alias. It does not establish that the alias is visible to any organization.
func IsCandidateViewPseudonym(value string) bool {
return validCandidateViewPseudonym(value)
}
func validateCandidateViewConfirmations(confirmations []CandidateViewConfirmedCategoryInput) error {
seen := make(map[SpecializationCode]struct{}, len(confirmations))
for _, confirmation := range confirmations {
if !confirmation.Specialization.IsKnown() || !confirmation.Grade.IsKnown() || !confirmation.Strength.IsKnown() {
return ErrInvalidAnonymousCandidateView
}
if _, duplicate := seen[confirmation.Specialization]; duplicate {
return ErrInvalidAnonymousCandidateView
}
seen[confirmation.Specialization] = struct{}{}
}
if len(confirmations) > maximumCandidateViewSpecializations {
return ErrInvalidAnonymousCandidateView
}
return nil
}
func candidateViewSkills(profile CandidateViewProfile) []CandidateViewSkillCode {
seen := make(map[CandidateViewSkillCode]struct{})
for _, claim := range profile.stack {
if claim.status != ProfileClaimConfirmed {
continue
}
code, ok := CanonicalCandidateViewSkill(claim.value)
if ok {
seen[code] = struct{}{}
}
}
if len(seen) == 0 {
return nil
}
result := make([]CandidateViewSkillCode, 0, len(seen))
for code := range seen {
result = append(result, code)
}
slices.Sort(result)
return result
}
func candidateViewExperienceBand(claims []candidateViewExperienceClaim, asOf time.Time) (*CandidateExperienceBand, error) {
periods := make([]candidateViewMonthRange, 0, len(claims))
for _, claim := range claims {
if claim.status != ProfileClaimConfirmed {
continue
}
period, err := candidateViewExperiencePeriod(claim, asOf)
if err != nil {
return nil, err
}
periods = append(periods, period)
}
if len(periods) == 0 {
return nil, nil
}
slices.SortFunc(periods, func(left, right candidateViewMonthRange) int {
if left.start < right.start {
return -1
}
if left.start > right.start {
return 1
}
if left.end < right.end {
return -1
}
if left.end > right.end {
return 1
}
return 0
})
months := candidateViewUnionMonthCount(periods)
if months < 0 {
return nil, ErrInvalidAnonymousCandidateView
}
band := candidateViewBandForMonths(months)
return &band, nil
}
func candidateViewExperiencePeriod(experience candidateViewExperienceClaim, asOf time.Time) (candidateViewMonthRange, error) {
start, valid := candidateViewMonthIndex(experience.startedOn)
if !valid {
return candidateViewMonthRange{}, ErrInvalidAnonymousCandidateView
}
var end int64
switch {
case experience.endedOn != "":
end, valid = candidateViewMonthIndex(experience.endedOn)
case !asOf.IsZero():
end, valid = candidateViewMonthIndex(asOf.UTC().Format("2006-01"))
default:
return candidateViewMonthRange{}, ErrInvalidAnonymousCandidateView
}
if !valid || end < start {
return candidateViewMonthRange{}, ErrInvalidAnonymousCandidateView
}
return candidateViewMonthRange{start: start, end: end}, nil
}
type candidateViewMonthRange struct {
start int64
end int64
}
func candidateViewMonthIndex(value string) (int64, bool) {
if len(value) != 7 || value[4] != '-' {
return 0, false
}
var year, month int64
if _, err := fmt.Sscanf(value, "%4d-%2d", &year, &month); err != nil || year < 1 || month < 1 || month > 12 {
return 0, false
}
return year*12 + month - 1, true
}
func candidateViewUnionMonthCount(periods []candidateViewMonthRange) int64 {
start, end := periods[0].start, periods[0].end
var months int64
for _, period := range periods[1:] {
if period.start <= end+1 {
if period.end > end {
end = period.end
}
continue
}
months += end - start + 1
start, end = period.start, period.end
}
return months + end - start + 1
}
func candidateViewBandForMonths(months int64) CandidateExperienceBand {
switch {
case months < 12:
return CandidateExperienceBandZeroToOne
case months < 36:
return CandidateExperienceBandOneToThree
case months < 72:
return CandidateExperienceBandThreeToSix
default:
return CandidateExperienceBandSixPlus
}
}
func candidateViewCategories(confirmations []CandidateViewConfirmedCategoryInput) []CandidateViewCategory {
if len(confirmations) == 0 {
return nil
}
result := make([]CandidateViewCategory, 0, len(confirmations))
for _, confirmation := range confirmations {
result = append(result, CandidateViewCategory(confirmation))
}
slices.SortFunc(result, func(left, right CandidateViewCategory) int {
return strings.Compare(string(left.Specialization), string(right.Specialization))
})
return result
}
func candidateViewSelfAssessments(
roles []candidateViewRoleClaim,
confirmations []CandidateViewConfirmedCategoryInput,
) []CandidateViewSelfAssessment {
confirmationBySpecialization := make(map[SpecializationCode]struct{}, len(confirmations))
for _, confirmation := range confirmations {
confirmationBySpecialization[confirmation.Specialization] = struct{}{}
}
result := make([]CandidateViewSelfAssessment, 0, len(roles))
seen := make(map[SpecializationCode]struct{}, len(roles))
for _, claim := range roles {
if claim.status != ProfileClaimConfirmed {
continue
}
role := claim.value
if _, duplicate := seen[role.Specialization]; duplicate {
return nil
}
seen[role.Specialization] = struct{}{}
status := CandidateViewConfirmationUnconfirmed
if _, confirmed := confirmationBySpecialization[role.Specialization]; confirmed {
status = CandidateViewConfirmationConfirmed
}
item := CandidateViewSelfAssessment{Specialization: role.Specialization, ConfirmationStatus: status}
if role.SelfAssessedGrade != "" {
grade := role.SelfAssessedGrade
item.DeclaredGrade = &grade
}
result = append(result, item)
}
if len(result) == 0 {
return nil
}
slices.SortFunc(result, func(left, right CandidateViewSelfAssessment) int {
return strings.Compare(string(left.Specialization), string(right.Specialization))
})
return result
}
func canonicalCandidateViewWorkFormats(formats []QuestionnaireWorkFormat) ([]QuestionnaireWorkFormat, error) {
if len(formats) > maximumCandidateViewWorkFormats {
return nil, ErrInvalidAnonymousCandidateView
}
if len(formats) == 0 {
return nil, nil
}
result := slices.Clone(formats)
for _, format := range result {
if !format.IsKnown() {
return nil, ErrInvalidAnonymousCandidateView
}
}
slices.Sort(result)
if len(slices.Compact(slices.Clone(result))) != len(result) {
return nil, ErrInvalidAnonymousCandidateView
}
return result, nil
}
// GeneralizeAnonymousCandidateCohort suppresses or generalizes the complete
// visible quasi-identifier combination until every displayed combination has
// at least five distinct pseudonyms. The caller must pass only candidates
// whose C2, publication, and organization visibility checks succeeded.
func GeneralizeAnonymousCandidateCohort(views []AnonymousCandidateView) ([]AnonymousCandidateView, error) {
result := make([]AnonymousCandidateView, len(views))
seenPseudonyms := make(map[string]struct{}, len(views))
for index, view := range views {
if !validCandidateViewPseudonym(view.dto.Pseudonym) {
return nil, ErrInvalidAnonymousCandidateView
}
if _, duplicate := seenPseudonyms[view.dto.Pseudonym]; duplicate {
return nil, ErrInvalidAnonymousCandidateView
}
seenPseudonyms[view.dto.Pseudonym] = struct{}{}
result[index] = AnonymousCandidateView{
dto: cloneAnonymousCandidateViewDTO(view.dto), generalizationLevel: view.generalizationLevel,
}
}
for pass := 0; pass <= maximumCandidateViewGeneralization; pass++ {
groups := candidateViewCohortGroups(result)
changed := false
for _, indexes := range groups {
if len(indexes) >= minimumAnonymousCandidateCohort {
continue
}
for _, index := range indexes {
if result[index].generalizationLevel >= maximumCandidateViewGeneralization {
continue
}
result[index].generalizationLevel++
applyCandidateViewGeneralization(&result[index])
changed = true
}
}
if !changed {
break
}
}
return suppressSmallCandidateViewGroups(result), nil
}
func suppressSmallCandidateViewGroups(views []AnonymousCandidateView) []AnonymousCandidateView {
groups := candidateViewCohortGroups(views)
keep := make([]bool, len(views))
for _, indexes := range groups {
if len(indexes) < minimumAnonymousCandidateCohort {
continue
}
for _, index := range indexes {
keep[index] = true
}
}
result := make([]AnonymousCandidateView, 0, len(views))
for index, view := range views {
if keep[index] {
result = append(result, view)
}
}
return result
}
func candidateViewCohortGroups(views []AnonymousCandidateView) map[string][]int {
groups := make(map[string][]int)
for index, view := range views {
encoded, _ := json.Marshal(candidateViewCohortFeatures(view.dto))
groups[string(encoded)] = append(groups[string(encoded)], index)
}
return groups
}
type anonymousCandidateViewFeatures struct {
Skills []CandidateViewSkillCode `json:"skills"`
Categories []CandidateViewCategory `json:"categories"`
SelfAssessment []CandidateViewSelfAssessment `json:"self_assessment"`
ExperienceBand *CandidateExperienceBand `json:"experience_band"`
WorkFormats []QuestionnaireWorkFormat `json:"work_formats"`
SalaryCompatibility *CandidateViewSalaryCompatibility `json:"salary_compatibility"`
}
func candidateViewCohortFeatures(dto AnonymousCandidateViewDTO) anonymousCandidateViewFeatures {
return anonymousCandidateViewFeatures{
Skills: dto.Skills, Categories: dto.Categories, SelfAssessment: dto.SelfAssessment,
ExperienceBand: dto.ExperienceBand, WorkFormats: dto.WorkFormats,
SalaryCompatibility: dto.SalaryCompatibility,
}
}
func applyCandidateViewGeneralization(view *AnonymousCandidateView) {
switch view.generalizationLevel {
case 1:
view.dto.Skills = nil
case 2:
view.dto.WorkFormats = nil
case 3:
view.dto.SalaryCompatibility = nil
view.dto.ExperienceBand = generalizedCandidateExperienceBand(view.dto.ExperienceBand)
case 4:
view.dto.Categories = nil
view.dto.SelfAssessment = nil
case 5:
view.dto.ExperienceBand = nil
}
}
func generalizedCandidateExperienceBand(band *CandidateExperienceBand) *CandidateExperienceBand {
if band == nil {
return nil
}
var generalized CandidateExperienceBand
switch *band {
case CandidateExperienceBandZeroToOne, CandidateExperienceBandOneToThree:
generalized = CandidateExperienceBandZeroToThree
case CandidateExperienceBandThreeToSix, CandidateExperienceBandSixPlus:
generalized = CandidateExperienceBandThreePlus
case CandidateExperienceBandZeroToThree, CandidateExperienceBandThreePlus:
generalized = *band
default:
return clonePointer(band)
}
return &generalized
}
@@ -0,0 +1,88 @@
package domain
import (
"errors"
"fmt"
"log/slog"
"slices"
"time"
"github.com/google/uuid"
)
var ErrInvalidCandidateViewSource = errors.New("invalid candidate view source")
// CandidateViewSource is a private read-model source for one currently
// published candidate. Its identifier and source values must never be logged
// or serialized as an organization-facing response.
type CandidateViewSource struct {
candidateID uuid.UUID
publishedFields CardFieldSet
profile CandidateViewProfile
confirmedCategories []CandidateViewConfirmedCategoryInput
workFormats []QuestionnaireWorkFormat
salaryCompatibility *CandidateViewSalaryCompatibility
}
func NewCandidateViewSource(
candidateID uuid.UUID,
publishedFields CardFieldSet,
profile CandidateViewProfile,
confirmedCategories []CandidateViewConfirmedCategoryInput,
workFormats []QuestionnaireWorkFormat,
salaryCompatibility *CandidateViewSalaryCompatibility,
) (CandidateViewSource, error) {
if candidateID == uuid.Nil || publishedFields.IsEmpty() {
return CandidateViewSource{}, ErrInvalidCandidateViewSource
}
if len(workFormats) > maximumCandidateViewWorkFormats || len(confirmedCategories) > maximumCandidateViewSpecializations {
return CandidateViewSource{}, ErrInvalidCandidateViewSource
}
return CandidateViewSource{
candidateID: candidateID, publishedFields: publishedFields,
profile: cloneCandidateViewProfile(profile),
confirmedCategories: slices.Clone(confirmedCategories), workFormats: slices.Clone(workFormats),
salaryCompatibility: clonePointer(salaryCompatibility),
}, nil
}
func (CandidateViewSource) String() string { return "[private candidate view source]" }
func (CandidateViewSource) GoString() string { return "[private candidate view source]" }
func (CandidateViewSource) LogValue() slog.Value {
return slog.StringValue("[private candidate view source]")
}
// CandidateID is an internal join key for deriving the organization-scoped
// pseudonym. It is not part of the anonymous DTO.
func (source CandidateViewSource) CandidateID() uuid.UUID { return source.candidateID }
// PublishedFields returns the selected allowlist for the private projection.
func (source CandidateViewSource) PublishedFields() CardFieldSet { return source.publishedFields }
// Input returns detached, typed projection data without the candidate ID.
func (source CandidateViewSource) Input(pseudonym string, asOf time.Time) CandidateViewInput {
return CandidateViewInput{
Pseudonym: pseudonym, PublishedFields: source.publishedFields,
Profile: cloneCandidateViewProfile(source.profile), AsOf: asOf,
ConfirmedCategories: slices.Clone(source.confirmedCategories),
WorkFormats: slices.Clone(source.workFormats),
SalaryCompatibility: clonePointer(source.salaryCompatibility),
}
}
func cloneCandidateViewProfile(profile CandidateViewProfile) CandidateViewProfile {
return CandidateViewProfile{
stack: slices.Clone(profile.stack), roles: slices.Clone(profile.roles),
experience: slices.Clone(profile.experience),
}
}
func ValidateCandidateViewSource(source CandidateViewSource) error {
if source.candidateID == uuid.Nil || source.publishedFields.IsEmpty() {
return fmt.Errorf("candidate view source identity or publication is invalid: %w", ErrInvalidCandidateViewSource)
}
if source.salaryCompatibility != nil && !source.salaryCompatibility.IsKnown() {
return fmt.Errorf("candidate view source compatibility is invalid: %w", ErrInvalidCandidateViewSource)
}
return nil
}
@@ -0,0 +1,419 @@
package domain
import (
"bytes"
"encoding/json"
"errors"
"strings"
"testing"
"time"
"github.com/google/uuid"
)
func TestCandidateViewPseudonymIsStableAndOrganizationScoped(t *testing.T) {
t.Parallel()
key, err := NewCandidateViewPseudonymKey(bytes.Repeat([]byte("k"), minimumCandidateViewPseudonymKeyLen))
if err != nil {
t.Fatalf("NewCandidateViewPseudonymKey() error = %v", err)
}
organizationA := uuid.New()
organizationB := uuid.New()
candidate := uuid.New()
first, err := key.ForOrganization(organizationA, candidate)
if err != nil {
t.Fatalf("ForOrganization() error = %v", err)
}
repeated, err := key.ForOrganization(organizationA, candidate)
if err != nil {
t.Fatalf("ForOrganization() repeat error = %v", err)
}
otherOrganization, err := key.ForOrganization(organizationB, candidate)
if err != nil {
t.Fatalf("ForOrganization() other organization error = %v", err)
}
otherCandidate, err := key.ForOrganization(organizationA, uuid.New())
if err != nil {
t.Fatalf("ForOrganization() other candidate error = %v", err)
}
if first != repeated {
t.Fatal("pseudonym changed for the same organization and candidate")
}
if first == otherOrganization || first == otherCandidate {
t.Fatal("pseudonym did not vary by organization and candidate")
}
if !validCandidateViewPseudonym(first) || strings.Contains(first, candidate.String()) {
t.Fatalf("pseudonym is not an opaque full-length alias: %q", first)
}
if strings.Contains(key.String(), string(bytes.Repeat([]byte("k"), minimumCandidateViewPseudonymKeyLen))) {
t.Fatal("key formatting exposed its secret")
}
}
func TestCandidateViewPseudonymRejectsWeakKeyAndEmptyIdentity(t *testing.T) {
t.Parallel()
if _, err := NewCandidateViewPseudonymKey(make([]byte, minimumCandidateViewPseudonymKeyLen-1)); !errors.Is(err, ErrInvalidAnonymousCandidateView) {
t.Fatalf("short key error = %v, want ErrInvalidAnonymousCandidateView", err)
}
key, err := NewCandidateViewPseudonymKey(bytes.Repeat([]byte("k"), minimumCandidateViewPseudonymKeyLen))
if err != nil {
t.Fatalf("NewCandidateViewPseudonymKey() error = %v", err)
}
if _, err := key.ForOrganization(uuid.Nil, uuid.New()); !errors.Is(err, ErrInvalidAnonymousCandidateView) {
t.Fatalf("empty organization error = %v, want ErrInvalidAnonymousCandidateView", err)
}
if _, err := key.ForOrganization(uuid.New(), uuid.Nil); !errors.Is(err, ErrInvalidAnonymousCandidateView) {
t.Fatalf("empty candidate error = %v, want ErrInvalidAnonymousCandidateView", err)
}
if _, err := key.ForCandidatePreview(uuid.Nil); !errors.Is(err, ErrInvalidAnonymousCandidateView) {
t.Fatalf("empty preview candidate error = %v, want ErrInvalidAnonymousCandidateView", err)
}
}
func TestCandidatePreviewPseudonymUsesSeparateContext(t *testing.T) {
t.Parallel()
key, err := NewCandidateViewPseudonymKey(bytes.Repeat([]byte("k"), minimumCandidateViewPseudonymKeyLen))
if err != nil {
t.Fatalf("NewCandidateViewPseudonymKey() error = %v", err)
}
candidateID := uuid.New()
preview, err := key.ForCandidatePreview(candidateID)
if err != nil {
t.Fatalf("ForCandidatePreview() error = %v", err)
}
organization, err := key.ForOrganization(uuid.New(), candidateID)
if err != nil {
t.Fatalf("ForOrganization() error = %v", err)
}
previewAgain, err := key.ForCandidatePreview(candidateID)
if err != nil {
t.Fatalf("ForCandidatePreview() repeat error = %v", err)
}
if preview == organization || previewAgain != preview || !validCandidateViewPseudonym(preview) {
t.Fatal("preview pseudonym must be stable, valid, and separate from employer aliases")
}
}
func TestAnonymousCandidateViewUsesPublishedAllowlist(t *testing.T) {
t.Parallel()
profileID := uuid.New()
profile, err := EmptyCandidateProfile(profileID)
if err != nil {
t.Fatalf("EmptyCandidateProfile() error = %v", err)
}
input := CandidateProfileInput{
FullName: confirmed("NameMarker"), Email: confirmed("person-marker@example.test"),
Phone: confirmed("+79000000000"), Telegram: confirmed("@external_marker"),
Stack: confirmedItems("Go", "postgresql", "UniqueStackMarker"),
Roles: confirmedItems(
ProfileRole{Specialization: SpecializationBackend, SelfAssessedGrade: GradeJunior},
ProfileRole{Specialization: SpecializationNetworkEngineer, SelfAssessedGrade: GradeSenior},
),
Experience: confirmedItems(
ProfileExperience{EmployerName: "EmployerMarker", Specialization: SpecializationBackend, StartedOn: "2022-01", EndedOn: "2023-12", Summary: "SummaryMarker"},
ProfileExperience{EmployerName: "OtherEmployerMarker", Specialization: SpecializationBackend, StartedOn: "2023-01", EndedOn: "2024-12", Summary: "OtherSummaryMarker"},
),
ParallelPeriodAcknowledgements: []ProfileParallelPeriodAcknowledgement{{
FirstIndex: 0, SecondIndex: 1,
FirstPeriod: ProfileExperiencePeriod{StartedOn: "2022-01", EndedOn: "2023-12"},
SecondPeriod: ProfileExperiencePeriod{StartedOn: "2023-01", EndedOn: "2024-12"},
}},
SoftSkills: confirmedItems("SoftSkillMarker"), Location: confirmed("LocationMarker"),
Relocation: confirmed(true), SalaryMinimum: confirmed(ProfileSalaryMinimum{Amount: 180_000, TaxBasis: ProfileTaxNet}),
}
content, err := ResolveCandidateProfileContent(profile.Content(), input, time.Date(2026, 10, 6, 0, 0, 0, 0, time.UTC))
if err != nil {
t.Fatalf("ResolveCandidateProfileContent() error = %v", err)
}
fields, err := NewCardFieldSet([]CardField{
CardFieldStack, CardFieldExperience, CardFieldCategories, CardFieldSelfAssessment,
CardFieldWorkFormats, CardFieldSalaryCompatibility,
})
if err != nil {
t.Fatalf("NewCardFieldSet() error = %v", err)
}
pseudonym := candidateViewTestPseudonym(t, uuid.New(), profileID)
view, err := NewAnonymousCandidateView(CandidateViewInput{
Pseudonym: pseudonym, PublishedFields: fields, Profile: CandidateViewProfileFromContent(content),
AsOf: time.Date(2026, 10, 6, 0, 0, 0, 0, time.UTC),
ConfirmedCategories: []CandidateViewConfirmedCategoryInput{{
Specialization: SpecializationBackend, Grade: GradeMiddle, Strength: CandidateViewStrengthStrong,
}},
WorkFormats: []QuestionnaireWorkFormat{QuestionnaireWorkFormatRemote, QuestionnaireWorkFormatHybrid},
})
if err != nil {
t.Fatalf("NewAnonymousCandidateView() error = %v", err)
}
dto := view.DTO()
if len(dto.Skills) != 2 || !containsCandidateViewSkill(dto.Skills, CandidateViewSkillGo) || !containsCandidateViewSkill(dto.Skills, CandidateViewSkillPostgreSQL) {
t.Fatalf("skills = %#v, want only canonical Go and PostgreSQL", dto.Skills)
}
if dto.ExperienceBand == nil || *dto.ExperienceBand != CandidateExperienceBandThreeToSix {
t.Fatalf("experience band = %v, want 3_6", dto.ExperienceBand)
}
if len(dto.Categories) != 1 || dto.Categories[0].Specialization != SpecializationBackend || dto.Categories[0].Grade != GradeMiddle || dto.Categories[0].Strength != CandidateViewStrengthStrong {
t.Fatalf("categories = %#v, want only the authoritative backend result", dto.Categories)
}
if len(dto.SelfAssessment) != 2 {
t.Fatalf("self assessment = %#v, want two separately published declared specializations", dto.SelfAssessment)
}
if dto.SelfAssessment[0].Specialization != SpecializationBackend || dto.SelfAssessment[0].ConfirmationStatus != CandidateViewConfirmationConfirmed ||
dto.SelfAssessment[0].DeclaredGrade == nil || *dto.SelfAssessment[0].DeclaredGrade != GradeJunior {
t.Fatalf("backend self assessment = %#v, want separately declared grade", dto.SelfAssessment[0])
}
if dto.SelfAssessment[1].Specialization != SpecializationNetworkEngineer || dto.SelfAssessment[1].ConfirmationStatus != CandidateViewConfirmationUnconfirmed ||
dto.SelfAssessment[1].DeclaredGrade == nil || *dto.SelfAssessment[1].DeclaredGrade != GradeSenior {
t.Fatalf("network self assessment = %#v, want declared-only grade", dto.SelfAssessment[1])
}
if len(dto.WorkFormats) != 2 || dto.SalaryCompatibility != nil {
t.Fatalf("work formats and compatibility = %#v, %#v", dto.WorkFormats, dto.SalaryCompatibility)
}
encoded, err := json.Marshal(dto)
if err != nil {
t.Fatalf("Marshal() error = %v", err)
}
for _, marker := range []string{
"NameMarker", "person-marker@example.test", "+79000000000", "external_marker",
"EmployerMarker", "OtherEmployerMarker", "SummaryMarker", "OtherSummaryMarker",
"SoftSkillMarker", "LocationMarker", "UniqueStackMarker", "180000",
} {
if strings.Contains(string(encoded), marker) {
t.Errorf("anonymous DTO contains forbidden marker %q: %s", marker, encoded)
}
}
if strings.Contains(string(encoded), `"declared_grade":null`) || strings.Contains(string(encoded), `"strength":null`) {
t.Fatalf("missing values must be omitted rather than encoded as zero values: %s", encoded)
}
if strings.Contains(string(encoded), `"specialization":"network_engineer","grade":"senior"`) {
t.Fatalf("declared grade was mixed into confirmed categories: %s", encoded)
}
}
func TestAnonymousCandidateViewSalaryCompatibilityRequiresExplicitField(t *testing.T) {
t.Parallel()
profile, err := EmptyCandidateProfile(uuid.New())
if err != nil {
t.Fatalf("EmptyCandidateProfile() error = %v", err)
}
compatibility := CandidateViewSalaryNotCompatible
fields, err := NewCardFieldSet([]CardField{CardFieldSalaryCompatibility})
if err != nil {
t.Fatalf("NewCardFieldSet() error = %v", err)
}
view, err := NewAnonymousCandidateView(CandidateViewInput{
Pseudonym: candidateViewTestPseudonym(t, uuid.New(), profile.UserID()),
PublishedFields: fields, Profile: CandidateViewProfileFromContent(profile.Content()), SalaryCompatibility: &compatibility,
})
if err != nil {
t.Fatalf("NewAnonymousCandidateView() error = %v", err)
}
if view.DTO().SalaryCompatibility == nil || *view.DTO().SalaryCompatibility != CandidateViewSalaryNotCompatible {
t.Fatalf("compatibility = %v, want explicitly supplied non-compatible result", view.DTO().SalaryCompatibility)
}
fields, err = NewCardFieldSet(nil)
if err != nil {
t.Fatalf("NewCardFieldSet(empty) error = %v", err)
}
view, err = NewAnonymousCandidateView(CandidateViewInput{
Pseudonym: candidateViewTestPseudonym(t, uuid.New(), profile.UserID()),
PublishedFields: fields, Profile: CandidateViewProfileFromContent(profile.Content()), SalaryCompatibility: &compatibility,
})
if err != nil {
t.Fatalf("NewAnonymousCandidateView() without opt-in error = %v", err)
}
if view.DTO().SalaryCompatibility != nil {
t.Fatalf("compatibility = %v without the publication opt-in, want nil", view.DTO().SalaryCompatibility)
}
}
func TestAnonymousCandidateViewKeepsCategoriesSeparateFromSelfAssessment(t *testing.T) {
t.Parallel()
profile, err := EmptyCandidateProfile(uuid.New())
if err != nil {
t.Fatalf("EmptyCandidateProfile() error = %v", err)
}
content, err := ResolveCandidateProfileContent(profile.Content(), CandidateProfileInput{
Roles: confirmedItems(ProfileRole{Specialization: SpecializationBackend, SelfAssessedGrade: GradeJunior}),
}, candidateTestTime)
if err != nil {
t.Fatalf("ResolveCandidateProfileContent() error = %v", err)
}
category := CandidateViewConfirmedCategoryInput{
Specialization: SpecializationBackend, Grade: GradeMiddle, Strength: CandidateViewStrengthStandard,
}
newView := func(field CardField) AnonymousCandidateViewDTO {
t.Helper()
fields, err := NewCardFieldSet([]CardField{field})
if err != nil {
t.Fatalf("NewCardFieldSet() error = %v", err)
}
view, err := NewAnonymousCandidateView(CandidateViewInput{
Pseudonym: candidateViewTestPseudonym(t, uuid.New(), profile.UserID()),
PublishedFields: fields, Profile: CandidateViewProfileFromContent(content),
ConfirmedCategories: []CandidateViewConfirmedCategoryInput{category},
})
if err != nil {
t.Fatalf("NewAnonymousCandidateView() error = %v", err)
}
return view.DTO()
}
categoryOnly := newView(CardFieldCategories)
if len(categoryOnly.Categories) != 1 || categoryOnly.SelfAssessment != nil {
t.Fatalf("categories-only opt-in returned categories=%#v self_assessment=%#v", categoryOnly.Categories, categoryOnly.SelfAssessment)
}
selfAssessmentOnly := newView(CardFieldSelfAssessment)
if selfAssessmentOnly.Categories != nil || len(selfAssessmentOnly.SelfAssessment) != 1 {
t.Fatalf("self-assessment-only opt-in returned categories=%#v self_assessment=%#v", selfAssessmentOnly.Categories, selfAssessmentOnly.SelfAssessment)
}
}
func TestCandidateViewExperienceBandsHaveExactBoundaries(t *testing.T) {
t.Parallel()
for _, test := range []struct {
name string
from string
to string
want CandidateExperienceBand
}{
{name: "eleven months", from: "2024-01", to: "2024-11", want: CandidateExperienceBandZeroToOne},
{name: "one year", from: "2024-01", to: "2024-12", want: CandidateExperienceBandOneToThree},
{name: "three years", from: "2022-01", to: "2024-12", want: CandidateExperienceBandThreeToSix},
{name: "six years", from: "2020-01", to: "2025-12", want: CandidateExperienceBandSixPlus},
} {
t.Run(test.name, func(t *testing.T) {
t.Parallel()
profile, err := EmptyCandidateProfile(uuid.New())
if err != nil {
t.Fatalf("EmptyCandidateProfile() error = %v", err)
}
content, err := ResolveCandidateProfileContent(profile.Content(), CandidateProfileInput{Experience: confirmedItems(ProfileExperience{
Specialization: SpecializationBackend, StartedOn: test.from, EndedOn: test.to,
})}, candidateTestTime)
if err != nil {
t.Fatalf("ResolveCandidateProfileContent() error = %v", err)
}
band, err := candidateViewExperienceBand(CandidateViewProfileFromContent(content).experience, time.Time{})
if err != nil {
t.Fatalf("candidateViewExperienceBand() error = %v", err)
}
if band == nil || *band != test.want {
t.Fatalf("band = %v, want %s", band, test.want)
}
})
}
}
func TestGeneralizeAnonymousCandidateCohortSuppressesRareCombinations(t *testing.T) {
t.Parallel()
organizationID := uuid.New()
key, err := NewCandidateViewPseudonymKey(bytes.Repeat([]byte("p"), minimumCandidateViewPseudonymKeyLen))
if err != nil {
t.Fatalf("NewCandidateViewPseudonymKey() error = %v", err)
}
newView := func(skill CandidateViewSkillCode, candidateID uuid.UUID) AnonymousCandidateView {
t.Helper()
profile, err := EmptyCandidateProfile(candidateID)
if err != nil {
t.Fatalf("EmptyCandidateProfile() error = %v", err)
}
fields, err := NewCardFieldSet([]CardField{CardFieldStack})
if err != nil {
t.Fatalf("NewCardFieldSet() error = %v", err)
}
input := CandidateProfileInput{Stack: confirmedItems(string(skill))}
content, err := ResolveCandidateProfileContent(profile.Content(), input, candidateTestTime)
if err != nil {
t.Fatalf("ResolveCandidateProfileContent() error = %v", err)
}
pseudonym, err := key.ForOrganization(organizationID, candidateID)
if err != nil {
t.Fatalf("ForOrganization() error = %v", err)
}
view, err := NewAnonymousCandidateView(CandidateViewInput{
Pseudonym: pseudonym, PublishedFields: fields, Profile: CandidateViewProfileFromContent(content),
})
if err != nil {
t.Fatalf("NewAnonymousCandidateView() error = %v", err)
}
return view
}
views := make([]AnonymousCandidateView, 0, 10)
for range 4 {
views = append(views, newView(CandidateViewSkillGo, uuid.New()))
}
views = append(views, newView(CandidateViewSkillKafka, uuid.New()))
for range 5 {
views = append(views, newView(CandidateViewSkillDocker, uuid.New()))
}
generalized, err := GeneralizeAnonymousCandidateCohort(views)
if err != nil {
t.Fatalf("GeneralizeAnonymousCandidateCohort() error = %v", err)
}
if len(generalized) != 10 {
t.Fatalf("generalized views = %d, want all ten after the rare combinations merge safely", len(generalized))
}
var generalizedRare, retainedCommon int
for _, view := range generalized {
switch {
case len(view.DTO().Skills) == 0:
generalizedRare++
case len(view.DTO().Skills) == 1 && view.DTO().Skills[0] == CandidateViewSkillDocker:
retainedCommon++
default:
t.Fatalf("view retained an unexpected skill combination: %#v", view.DTO().Skills)
}
}
if generalizedRare != 5 || retainedCommon != 5 {
t.Fatalf("generalized rare/common counts = %d/%d, want 5/5", generalizedRare, retainedCommon)
}
for _, cohortSize := range []int{1, 4} {
small := make([]AnonymousCandidateView, 0, cohortSize)
for range cohortSize {
small = append(small, newView(CandidateViewSkillGo, uuid.New()))
}
result, err := GeneralizeAnonymousCandidateCohort(small)
if err != nil {
t.Fatalf("GeneralizeAnonymousCandidateCohort(size=%d) error = %v", cohortSize, err)
}
if len(result) != 0 {
t.Fatalf("cohort size %d returned %d profiles after maximum generalization, want suppression", cohortSize, len(result))
}
}
}
func candidateViewTestPseudonym(t *testing.T, organizationID, candidateID uuid.UUID) string {
t.Helper()
key, err := NewCandidateViewPseudonymKey(bytes.Repeat([]byte("v"), minimumCandidateViewPseudonymKeyLen))
if err != nil {
t.Fatalf("NewCandidateViewPseudonymKey() error = %v", err)
}
pseudonym, err := key.ForOrganization(organizationID, candidateID)
if err != nil {
t.Fatalf("ForOrganization() error = %v", err)
}
return pseudonym
}
func containsCandidateViewSkill(skills []CandidateViewSkillCode, wanted CandidateViewSkillCode) bool {
for _, skill := range skills {
if skill == wanted {
return true
}
}
return false
}
+118 -24
View File
@@ -1,6 +1,7 @@
package domain
import (
"encoding/json"
"errors"
"fmt"
"log/slog"
@@ -25,16 +26,19 @@ var (
)
const (
maxNeedTitleRunes = 200
maxNeedSourceTextRunes = 10000
maxNeedNameRunes = 100
maxNeedTaskRunes = 300
maxNeedQuoteRunes = 300
maxNeedSkillItems = 30
maxNeedTaskItems = 20
maxNeedWorkFormats = 3
MaxNeedSnapshotBytes = 262144
redactedNeed = "[redacted need]"
maxNeedTitleRunes = 200
maxNeedSourceTextRunes = 10000
maxNeedNameRunes = 100
maxNeedTaskRunes = 300
maxNeedQuoteRunes = 300
maxNeedSkillItems = 30
maxNeedTaskItems = 20
maxNeedWorkFormats = 3
MaxNeedRejectedSuggestions = 64
MaxNeedSnapshotBytes = 262144
MaxNeedJSONBTextHeadroom = 8192
MaxNeedSnapshotStorageBytes = MaxNeedSnapshotBytes + MaxNeedJSONBTextHeadroom
redactedNeed = "[redacted need]"
)
// NeedValueStatus is the confirmation state of one need field.
@@ -157,16 +161,39 @@ func EmptyNeedRequirements() NeedRequirements {
// NeedSnapshot is the complete immutable business state of one need version.
// Derived readiness and recommendations are computed separately.
type NeedSnapshot struct {
ID uuid.UUID `json:"id"`
OrganizationID uuid.UUID `json:"organization_id"`
VacancyID *uuid.UUID `json:"vacancy_id"`
Title string `json:"title"`
SourceText *string `json:"source_text"`
Version int64 `json:"version"`
RequirementsVersion int64 `json:"requirements_version"`
Requirements NeedRequirements `json:"requirements"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
ID uuid.UUID `json:"id"`
OrganizationID uuid.UUID `json:"organization_id"`
VacancyID *uuid.UUID `json:"vacancy_id"`
Title string `json:"title"`
SourceText *string `json:"source_text"`
Version int64 `json:"version"`
RequirementsVersion int64 `json:"requirements_version"`
Requirements NeedRequirements `json:"requirements"`
RejectedSuggestions []NeedRejectedSuggestion `json:"rejected_suggestions"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// NeedRejectedSuggestionField groups extracted values for suppression after
// an owner explicitly deletes them.
type NeedRejectedSuggestionField string
const (
NeedRejectedSpecialization NeedRejectedSuggestionField = "specialization"
NeedRejectedGrade NeedRejectedSuggestionField = "grade"
NeedRejectedSkills NeedRejectedSuggestionField = "skills"
NeedRejectedTasks NeedRejectedSuggestionField = "tasks"
NeedRejectedDomain NeedRejectedSuggestionField = "domain"
NeedRejectedWorkFormats NeedRejectedSuggestionField = "work_formats"
NeedRejectedLocation NeedRejectedSuggestionField = "location"
NeedRejectedSalary NeedRejectedSuggestionField = "salary"
)
// NeedRejectedSuggestion records an extracted proposal that an owner removed.
// It is private need state and is never included in the public Need response.
type NeedRejectedSuggestion struct {
Field NeedRejectedSuggestionField `json:"field"`
Value string `json:"value"`
}
// Need is one immutable version of an organization's hiring need. Snapshot
@@ -190,6 +217,9 @@ func RestoreNeed(snapshot NeedSnapshot) (Need, error) {
const location = "domain.RestoreNeed"
snapshot.CreatedAt = canonicalNeedTime(snapshot.CreatedAt)
snapshot.UpdatedAt = canonicalNeedTime(snapshot.UpdatedAt)
if snapshot.RejectedSuggestions == nil {
snapshot.RejectedSuggestions = []NeedRejectedSuggestion{}
}
if err := validateNeedSnapshot(location, snapshot); err != nil {
return Need{}, err
}
@@ -453,6 +483,19 @@ func confirmedNeedTasks(tasks []NeedTask) []string {
}
func validateNeedSnapshot(location string, snapshot NeedSnapshot) error {
if err := validateNeedSnapshotMetadata(location, snapshot); err != nil {
return err
}
if err := validateNeedRejectedSuggestions(location, snapshot.RejectedSuggestions); err != nil {
return err
}
if err := validateNeedRequirements(location, snapshot.Version, snapshot.Requirements); err != nil {
return err
}
return validateNeedSnapshotSize(location, snapshot)
}
func validateNeedSnapshotMetadata(location string, snapshot NeedSnapshot) error {
switch {
case snapshot.ID == uuid.Nil || snapshot.OrganizationID == uuid.Nil:
return invalidNeed(location, "need and organization IDs must be set")
@@ -462,10 +505,60 @@ func validateNeedSnapshot(location string, snapshot NeedSnapshot) error {
return invalidNeedField(location, "/title", "must be 1 to 200 characters without surrounding whitespace or line breaks")
case snapshot.SourceText != nil && !validNeedLength(*snapshot.SourceText, maxNeedSourceTextRunes):
return invalidNeedField(location, "/source_text", "must be 1 to 10000 characters")
case snapshot.CreatedAt.IsZero() || snapshot.UpdatedAt.IsZero() || snapshot.UpdatedAt.Before(snapshot.CreatedAt):
return invalidNeed(location, "timestamps must be set and ordered")
case !validNeedTimestamp(snapshot.CreatedAt) || !validNeedTimestamp(snapshot.UpdatedAt) || snapshot.UpdatedAt.Before(snapshot.CreatedAt):
return invalidNeed(location, "timestamps must be set, representable, and ordered")
}
return nil
}
func validateNeedSnapshotSize(location string, snapshot NeedSnapshot) error {
encoded, err := json.Marshal(snapshot)
if err != nil {
return invalidNeed(location, "snapshot cannot be encoded")
}
if len(encoded) > MaxNeedSnapshotBytes {
return invalidNeedField(location, "/rejected_suggestions", "combined need snapshot exceeds its storage bound")
}
return nil
}
func validNeedTimestamp(value time.Time) bool {
return !value.IsZero() && value.Year() >= 1 && value.Year() <= 9999
}
func validateNeedRejectedSuggestions(location string, suggestions []NeedRejectedSuggestion) error {
if suggestions == nil || len(suggestions) > MaxNeedRejectedSuggestions {
return invalidNeedField(location, "/rejected_suggestions", "must be present and within its storage bound")
}
seen := make(map[string]struct{}, len(suggestions))
for index, suggestion := range suggestions {
pointer := "/rejected_suggestions/" + strconv.Itoa(index)
if !knownNeedRejectedSuggestionField(suggestion.Field) || !validNeedLength(suggestion.Value, maxNeedTaskRunes) ||
strings.TrimSpace(suggestion.Value) != suggestion.Value || strings.ToLower(suggestion.Value) != suggestion.Value {
return invalidNeedField(location, pointer, "must have a normalized field and value")
}
for _, char := range suggestion.Value {
if isNeedLineBreak(char) {
return invalidNeedField(location, pointer+"/value", "must not contain line breaks")
}
}
key := string(suggestion.Field) + "\x00" + suggestion.Value
if _, exists := seen[key]; exists {
return invalidNeedField(location, pointer, "duplicates a rejected suggestion")
}
seen[key] = struct{}{}
}
return nil
}
func knownNeedRejectedSuggestionField(field NeedRejectedSuggestionField) bool {
switch field {
case NeedRejectedSpecialization, NeedRejectedGrade, NeedRejectedSkills, NeedRejectedTasks,
NeedRejectedDomain, NeedRejectedWorkFormats, NeedRejectedLocation, NeedRejectedSalary:
return true
default:
return false
}
return validateNeedRequirements(location, snapshot.Version, snapshot.Requirements)
}
func validateNeedRequirements(location string, version int64, requirements NeedRequirements) error {
@@ -718,7 +811,7 @@ func validNeedText(value string, maxRunes int) bool {
}
func validNeedLength(value string, maxRunes int) bool {
if !utf8.ValidString(value) {
if !utf8.ValidString(value) || strings.ContainsRune(value, '\x00') {
return false
}
length := utf8.RuneCountInString(value)
@@ -743,6 +836,7 @@ func cloneNeedSnapshot(snapshot NeedSnapshot) NeedSnapshot {
cloned.VacancyID = cloneNeedPointer(snapshot.VacancyID)
cloned.SourceText = cloneNeedPointer(snapshot.SourceText)
cloned.Requirements = cloneNeedRequirements(snapshot.Requirements)
cloned.RejectedSuggestions = slices.Clone(snapshot.RejectedSuggestions)
return cloned
}
+266
View File
@@ -0,0 +1,266 @@
package domain
import (
"fmt"
"math"
"slices"
"time"
)
const (
MaxNeedCreationResultBytes = 524288
MaxNeedCreationResultStorageBytes = MaxNeedCreationResultBytes + MaxNeedJSONBTextHeadroom
)
// NeedRecommendationStatus is the public state of category calculation.
type NeedRecommendationStatus string
const (
NeedRecommendationsComputed NeedRecommendationStatus = "computed"
NeedRecommendationsPending NeedRecommendationStatus = "pending"
NeedRecommendationsNotAvailable NeedRecommendationStatus = "not_available"
)
type NeedMoneyStatus string
const (
NeedMoneyComputed NeedMoneyStatus = "computed"
NeedMoneyInsufficientData NeedMoneyStatus = "insufficient_data"
NeedMoneyNoSalary NeedMoneyStatus = "no_salary"
NeedMoneyWithheld NeedMoneyStatus = "withheld"
)
type NeedSupplyBand string
const (
NeedSupplyFewerThanFive NeedSupplyBand = "fewer_than_5"
NeedSupplyFromFiveTo29 NeedSupplyBand = "from_5_to_29"
NeedSupply30OrMore NeedSupplyBand = "30_or_more"
)
// NeedSkillOverlap is the public category skill coverage component.
type NeedSkillOverlap struct {
Share float64 `json:"share"`
CoveredSkills []string `json:"covered_skills"`
UncoveredSkills []string `json:"uncovered_skills"`
}
// NeedMoneyFit is the privacy-preserving public salary component.
type NeedMoneyFit struct {
Status NeedMoneyStatus `json:"status"`
Share *float64 `json:"share"`
}
// NeedCategoryRecommendation is one category and the public components used
// to rank it. It contains no candidate-level salary information.
type NeedCategoryRecommendation struct {
Specialization SpecializationCode `json:"specialization"`
Grade GradeCode `json:"grade"`
Score *float64 `json:"score"`
SkillOverlap NeedSkillOverlap `json:"skill_overlap"`
Money NeedMoneyFit `json:"money"`
Supply NeedSupplyBand `json:"supply"`
}
// NeedCategoryRecommendations is the server's versioned public calculation
// state for the confirmed requirements.
type NeedCategoryRecommendations struct {
Status NeedRecommendationStatus `json:"status"`
RequirementsVersion int64 `json:"requirements_version"`
PolicyVersion *int32 `json:"policy_version"`
AlgorithmVersion *string `json:"algorithm_version"`
ComputedAt *time.Time `json:"computed_at"`
Categories []NeedCategoryRecommendation `json:"categories"`
}
// NeedResponseSnapshot is an immutable public result captured when an
// idempotent create succeeds. Replay uses this snapshot instead of reading a
// later need version or recomputing readiness or recommendations.
type NeedResponseSnapshot struct {
Need NeedSnapshot `json:"need"`
Readiness NeedReadinessReport `json:"readiness"`
Recommendations NeedCategoryRecommendations `json:"recommendations"`
}
// NeedResponseSnapshot returns the current public result without exposing
// private rejected suggestion state to the response mapper.
func (need Need) ResponseSnapshot() NeedResponseSnapshot {
return NeedResponseSnapshot{
Need: need.Snapshot(), Readiness: need.Readiness(), Recommendations: need.Recommendations(),
}
}
// Recommendations returns the honest current MVP state. It never fabricates
// a computed category result while the calculator is unavailable.
func (need Need) Recommendations() NeedCategoryRecommendations {
status := NeedRecommendationsNotAvailable
if hasConfirmedNeedSkill(need.snapshot.Requirements.RequiredSkills) || hasConfirmedNeedSkill(need.snapshot.Requirements.DesiredSkills) {
status = NeedRecommendationsPending
}
return NeedCategoryRecommendations{
Status: status, RequirementsVersion: need.RequirementsVersion(),
Categories: []NeedCategoryRecommendation{},
}
}
// RestoreNeedResponseSnapshot validates and defensively copies an immutable
// create result read from storage.
func RestoreNeedResponseSnapshot(snapshot NeedResponseSnapshot) (NeedResponseSnapshot, error) {
const location = "domain.RestoreNeedResponseSnapshot"
need, err := RestoreNeed(snapshot.Need)
if err != nil {
return NeedResponseSnapshot{}, fmt.Errorf("%s - restore need: %w", location, err)
}
if err := validateNeedReadiness(location, snapshot.Readiness); err != nil {
return NeedResponseSnapshot{}, err
}
if err := validateNeedRecommendations(location, need, snapshot.Recommendations); err != nil {
return NeedResponseSnapshot{}, err
}
snapshot.Need = need.Snapshot()
snapshot.Readiness = cloneNeedReadiness(snapshot.Readiness)
snapshot.Recommendations = cloneNeedRecommendations(snapshot.Recommendations)
return snapshot, nil
}
func validateNeedReadiness(location string, readiness NeedReadinessReport) error {
if readiness.MissingFields == nil || len(readiness.MissingFields) > 9 {
return invalidNeed(location, "stored readiness fields are outside their bound")
}
if readiness.Status != NeedReadinessComplete && readiness.Status != NeedReadinessIncomplete {
return invalidNeed(location, "stored readiness status is unknown")
}
seen := make(map[NeedMissingFieldName]struct{}, len(readiness.MissingFields))
for _, missing := range readiness.MissingFields {
if !knownNeedMissingField(missing.Field) || (missing.Reason != NeedMissingUnknown && missing.Reason != NeedMissingUnconfirmed) || !validNeedText(missing.Question, 300) {
return invalidNeed(location, "stored readiness field is invalid")
}
if _, exists := seen[missing.Field]; exists {
return invalidNeed(location, "stored readiness field is duplicated")
}
seen[missing.Field] = struct{}{}
}
if (readiness.Status == NeedReadinessComplete) != (len(readiness.MissingFields) == 0) {
return invalidNeed(location, "stored readiness status does not match its fields")
}
return nil
}
func knownNeedMissingField(field NeedMissingFieldName) bool {
switch field {
case NeedMissingSpecialization, NeedMissingGrade, NeedMissingRequiredSkills, NeedMissingWorkFormats, NeedMissingLocation, NeedMissingSalary:
return true
default:
return false
}
}
func validateNeedRecommendations(location string, need Need, recommendations NeedCategoryRecommendations) error {
if recommendations.RequirementsVersion != need.RequirementsVersion() || recommendations.Categories == nil || len(recommendations.Categories) > 10 {
return invalidNeed(location, "stored recommendation snapshot is outside its bound")
}
hasConfirmedSkill := hasConfirmedNeedSkill(need.snapshot.Requirements.RequiredSkills) || hasConfirmedNeedSkill(need.snapshot.Requirements.DesiredSkills)
switch recommendations.Status {
case NeedRecommendationsPending, NeedRecommendationsNotAvailable:
return validateUncalculatedRecommendations(location, recommendations, hasConfirmedSkill)
case NeedRecommendationsComputed:
return validateComputedRecommendations(location, recommendations, hasConfirmedSkill)
default:
return invalidNeed(location, "stored recommendation status is unknown")
}
}
func validateUncalculatedRecommendations(location string, recommendations NeedCategoryRecommendations, hasConfirmedSkill bool) error {
shouldBePending := recommendations.Status == NeedRecommendationsPending
if recommendations.PolicyVersion != nil || recommendations.AlgorithmVersion != nil || recommendations.ComputedAt != nil || len(recommendations.Categories) != 0 ||
shouldBePending != hasConfirmedSkill {
return invalidNeed(location, "uncalculated recommendations must not contain calculation data")
}
return nil
}
func validateComputedRecommendations(location string, recommendations NeedCategoryRecommendations, hasConfirmedSkill bool) error {
if !hasConfirmedSkill || recommendations.PolicyVersion == nil || *recommendations.PolicyVersion < 1 || recommendations.AlgorithmVersion == nil ||
!validNeedVersionLabel(*recommendations.AlgorithmVersion) || recommendations.ComputedAt == nil || !validNeedTimestamp(*recommendations.ComputedAt) {
return invalidNeed(location, "computed recommendations require a valid policy, algorithm, and timestamp")
}
return validateNeedRecommendationCategories(location, recommendations.Categories)
}
func validateNeedRecommendationCategories(location string, categories []NeedCategoryRecommendation) error {
seen := make(map[string]struct{}, len(categories))
for _, category := range categories {
if !category.Specialization.IsKnown() || !category.Grade.IsKnown() || !validOptionalNeedScore(category.Score) || !validOptionalNeedScore(&category.SkillOverlap.Share) ||
category.SkillOverlap.CoveredSkills == nil || category.SkillOverlap.UncoveredSkills == nil || len(category.SkillOverlap.CoveredSkills) > 60 || len(category.SkillOverlap.UncoveredSkills) > 60 ||
!validNeedMoneyFit(category.Money) || !validNeedSupplyBand(category.Supply) {
return invalidNeed(location, "stored recommendation category is invalid")
}
key := string(category.Specialization) + "\x00" + string(category.Grade)
if _, exists := seen[key]; exists {
return invalidNeed(location, "stored recommendation category is duplicated")
}
seen[key] = struct{}{}
for _, skill := range append(slices.Clone(category.SkillOverlap.CoveredSkills), category.SkillOverlap.UncoveredSkills...) {
if !validNeedText(skill, maxNeedNameRunes) {
return invalidNeed(location, "stored recommendation skill is invalid")
}
}
}
return nil
}
func validOptionalNeedScore(value *float64) bool {
return value == nil || !math.IsNaN(*value) && !math.IsInf(*value, 0) && *value >= 0 && *value <= 1
}
func validNeedMoneyFit(value NeedMoneyFit) bool {
switch value.Status {
case NeedMoneyComputed:
if value.Share == nil || !validOptionalNeedScore(value.Share) {
return false
}
case NeedMoneyInsufficientData, NeedMoneyNoSalary, NeedMoneyWithheld:
if value.Share != nil {
return false
}
default:
return false
}
return true
}
func validNeedSupplyBand(value NeedSupplyBand) bool {
return value == NeedSupplyFewerThanFive || value == NeedSupplyFromFiveTo29 || value == NeedSupply30OrMore
}
func cloneNeedReadiness(readiness NeedReadinessReport) NeedReadinessReport {
readiness.MissingFields = slices.Clone(readiness.MissingFields)
return readiness
}
func cloneNeedRecommendations(recommendations NeedCategoryRecommendations) NeedCategoryRecommendations {
cloned := recommendations
if recommendations.PolicyVersion != nil {
value := *recommendations.PolicyVersion
cloned.PolicyVersion = &value
}
if recommendations.AlgorithmVersion != nil {
value := *recommendations.AlgorithmVersion
cloned.AlgorithmVersion = &value
}
if recommendations.ComputedAt != nil {
value := canonicalNeedTime(*recommendations.ComputedAt)
cloned.ComputedAt = &value
}
cloned.Categories = slices.Clone(recommendations.Categories)
for index := range cloned.Categories {
cloned.Categories[index].Score = cloneNeedPointer(recommendations.Categories[index].Score)
cloned.Categories[index].SkillOverlap.CoveredSkills = slices.Clone(recommendations.Categories[index].SkillOverlap.CoveredSkills)
cloned.Categories[index].SkillOverlap.UncoveredSkills = slices.Clone(recommendations.Categories[index].SkillOverlap.UncoveredSkills)
cloned.Categories[index].Money.Share = cloneNeedPointer(recommendations.Categories[index].Money.Share)
}
return cloned
}
func (snapshot NeedResponseSnapshot) String() string { return redactedNeed }
func (snapshot NeedResponseSnapshot) GoString() string { return redactedNeed }
@@ -0,0 +1,75 @@
package domain
import (
"testing"
"time"
)
func TestNeedResponseSnapshotPreservesReadinessAndRecommendations(t *testing.T) {
snapshot := validNeedSnapshot()
need, err := NewNeed(snapshot)
if err != nil {
t.Fatalf("NewNeed() error = %v", err)
}
response := need.ResponseSnapshot()
if response.Recommendations.Status != NeedRecommendationsNotAvailable || response.Recommendations.Categories == nil {
t.Fatalf("recommendations = %+v, want honest not_available state", response.Recommendations)
}
restored, err := RestoreNeedResponseSnapshot(response)
if err != nil {
t.Fatalf("RestoreNeedResponseSnapshot() error = %v", err)
}
if restored.Readiness.Status != response.Readiness.Status || restored.Recommendations.Status != response.Recommendations.Status || restored.Need.ID != need.ID() {
t.Fatalf("restored response snapshot = %+v, want original public result", restored)
}
response.Readiness.MissingFields[0].Question = "changed"
if restored.Readiness.MissingFields[0].Question == "changed" {
t.Fatal("restored readiness shares the caller's slice")
}
}
func TestNeedResponseSnapshotRequiresStatusConsistentWithConfirmedSkills(t *testing.T) {
snapshot := validNeedSnapshot()
skill := NeedSkill{Name: "Go", Status: NeedItemConfirmed, Source: *manualNeedSource()}
snapshot.Requirements.RequiredSkills = []NeedSkill{skill}
need, err := NewNeed(snapshot)
if err != nil {
t.Fatalf("NewNeed() error = %v", err)
}
response := need.ResponseSnapshot()
if response.Recommendations.Status != NeedRecommendationsPending {
t.Fatalf("recommendations = %+v, want pending while calculation is unavailable", response.Recommendations)
}
response.Recommendations.Status = NeedRecommendationsNotAvailable
if _, err := RestoreNeedResponseSnapshot(response); err == nil {
t.Fatal("RestoreNeedResponseSnapshot() accepted not_available despite a confirmed skill")
}
response = need.ResponseSnapshot()
response.Recommendations.Status = NeedRecommendationsComputed
response.Recommendations.PolicyVersion = needPointer(int32(1))
response.Recommendations.AlgorithmVersion = needPointer("category.1")
computedAt := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
response.Recommendations.ComputedAt = &computedAt
response.Recommendations.Categories = []NeedCategoryRecommendation{{
Specialization: SpecializationBackend, Grade: GradeJunior,
Score: needPointer(0.5), SkillOverlap: NeedSkillOverlap{Share: 1, CoveredSkills: []string{"Go"}, UncoveredSkills: []string{}},
Money: NeedMoneyFit{Status: NeedMoneyNoSalary}, Supply: NeedSupplyFromFiveTo29,
}}
restored, err := RestoreNeedResponseSnapshot(response)
if err != nil || restored.Recommendations.Status != NeedRecommendationsComputed {
t.Fatalf("restore computed creation snapshot = %+v, error %v", restored.Recommendations, err)
}
}
func TestNeedResponseSnapshotRejectsMalformedCalculationMetadata(t *testing.T) {
need, err := NewNeed(validNeedSnapshot())
if err != nil {
t.Fatalf("NewNeed() error = %v", err)
}
response := need.ResponseSnapshot()
response.Recommendations.Status = NeedRecommendationsPending
response.Recommendations.PolicyVersion = needPointer(int32(1))
if _, err := RestoreNeedResponseSnapshot(response); err == nil {
t.Fatal("RestoreNeedResponseSnapshot() accepted calculation metadata on pending recommendations")
}
}
+122
View File
@@ -1,6 +1,7 @@
package domain
import (
"encoding/json"
"errors"
"fmt"
"reflect"
@@ -53,6 +54,15 @@ func TestNewNeedCanonicalizesTimestampsToStoragePrecision(t *testing.T) {
}
}
func TestNeedRejectsTimestampsOutsideContractDateTimeRange(t *testing.T) {
snapshot := validNeedSnapshot()
snapshot.CreatedAt = time.Date(10000, 1, 1, 0, 0, 0, 0, time.UTC)
snapshot.UpdatedAt = snapshot.CreatedAt
if _, err := NewNeed(snapshot); !errors.Is(err, ErrInvalidNeed) {
t.Fatalf("NewNeed(year 10000) error = %v, want ErrInvalidNeed", err)
}
}
func TestNeedReadinessRequiresLocationOnlyForConfirmedOfficeOrHybrid(t *testing.T) {
snapshot := validNeedSnapshot()
formats := []NeedWorkFormat{NeedWorkFormatRemote}
@@ -197,6 +207,104 @@ func TestNeedSnapshotIsDefensiveAndRedacted(t *testing.T) {
}
}
func TestNeedRejectedSuggestionsArePrivateDefensiveAndBounded(t *testing.T) {
snapshot := validNeedSnapshot()
snapshot.RejectedSuggestions = []NeedRejectedSuggestion{{Field: NeedRejectedSkills, Value: "postgresql"}}
need, err := NewNeed(snapshot)
if err != nil {
t.Fatalf("NewNeed() error = %v", err)
}
copied := need.Snapshot()
copied.RejectedSuggestions[0].Value = "changed"
if got := need.Snapshot().RejectedSuggestions[0].Value; got != "postgresql" {
t.Fatalf("suppressed value changed through snapshot copy: %q", got)
}
if printed := fmt.Sprintf("%+v", need); strings.Contains(printed, "postgresql") {
t.Fatalf("need formatting exposed a suppressed suggestion: %q", printed)
}
tests := []struct {
name string
suggestions []NeedRejectedSuggestion
}{
{name: "unknown field", suggestions: []NeedRejectedSuggestion{{Field: "role", Value: "owner"}}},
{name: "empty value", suggestions: []NeedRejectedSuggestion{{Field: NeedRejectedSkills}}},
{name: "not normalized", suggestions: []NeedRejectedSuggestion{{Field: NeedRejectedSkills, Value: "PostgreSQL"}}},
{name: "duplicate", suggestions: []NeedRejectedSuggestion{
{Field: NeedRejectedSkills, Value: "postgresql"}, {Field: NeedRejectedSkills, Value: "postgresql"},
}},
{name: "too many", suggestions: tooManyNeedRejectedSuggestions()},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
invalid := validNeedSnapshot()
invalid.RejectedSuggestions = test.suggestions
if _, err := NewNeed(invalid); !errors.Is(err, ErrInvalidNeed) {
t.Fatalf("NewNeed() error = %v, want ErrInvalidNeed", err)
}
})
}
}
func TestNeedRejectsSnapshotThatExceedsSerializedStorageBound(t *testing.T) {
snapshot := validNeedSnapshot()
controlText := strings.Repeat("\x01", maxNeedSourceTextRunes)
snapshot.SourceText = &controlText
snapshot.RejectedSuggestions = make([]NeedRejectedSuggestion, MaxNeedRejectedSuggestions)
for index := range snapshot.RejectedSuggestions {
value := strings.Repeat("\x01", maxNeedTaskRunes-3) + fmt.Sprintf("%03d", index)
snapshot.RejectedSuggestions[index] = NeedRejectedSuggestion{Field: NeedRejectedTasks, Value: value}
}
for index := 0; index < maxNeedSkillItems; index++ {
quote := strings.Repeat("\x01", maxNeedQuoteRunes)
snapshot.Requirements.RequiredSkills = append(snapshot.Requirements.RequiredSkills, NeedSkill{
Name: fmt.Sprintf("skill-%02d", index), Status: NeedItemExtracted,
Source: NeedValueSource{Origin: NeedValueExtractedFromText, Quote: &quote,
ExtractedInVersion: needPointer(int64(1)), ExtractionVersion: needPointer("rules.1")},
})
}
for index := 0; index < maxNeedSkillItems; index++ {
quote := strings.Repeat("\x01", maxNeedQuoteRunes)
snapshot.Requirements.DesiredSkills = append(snapshot.Requirements.DesiredSkills, NeedSkill{
Name: fmt.Sprintf("other-%02d", index), Status: NeedItemExtracted,
Source: NeedValueSource{Origin: NeedValueExtractedFromText, Quote: &quote,
ExtractedInVersion: needPointer(int64(1)), ExtractionVersion: needPointer("rules.1")},
})
}
_, err := NewNeed(snapshot)
if !errors.Is(err, ErrInvalidNeed) || !strings.Contains(fmt.Sprint(err), "/rejected_suggestions") {
t.Fatalf("NewNeed(oversized snapshot) error = %v, want bounded snapshot validation error", err)
}
}
func TestRestoreNeedAcceptsLegacySnapshotWithoutRejectedSuggestions(t *testing.T) {
encoded, err := json.Marshal(validNeedSnapshot())
if err != nil {
t.Fatalf("marshal snapshot: %v", err)
}
var fields map[string]json.RawMessage
if err := json.Unmarshal(encoded, &fields); err != nil {
t.Fatalf("decode snapshot fields: %v", err)
}
delete(fields, "rejected_suggestions")
legacy, err := json.Marshal(fields)
if err != nil {
t.Fatalf("marshal legacy snapshot: %v", err)
}
var snapshot NeedSnapshot
if err := json.Unmarshal(legacy, &snapshot); err != nil {
t.Fatalf("decode legacy snapshot: %v", err)
}
need, err := RestoreNeed(snapshot)
if err != nil {
t.Fatalf("RestoreNeed(legacy) error = %v", err)
}
if got := need.Snapshot().RejectedSuggestions; got == nil || len(got) != 0 {
t.Fatalf("legacy rejected suggestions = %#v, want an empty list", got)
}
}
func TestNeedRestoresContractProvenanceAndRejectsInvalidValues(t *testing.T) {
tests := []struct {
name string
@@ -236,18 +344,24 @@ func TestNeedRestoresContractProvenanceAndRejectsInvalidValues(t *testing.T) {
func TestNeedRejectsInvalidUTF8InContractText(t *testing.T) {
invalid := string([]byte{0xff})
nul := "role\x00name"
tests := []struct {
name string
change func(*NeedSnapshot)
}{
{name: "title", change: func(snapshot *NeedSnapshot) { snapshot.Title = invalid }},
{name: "source text", change: func(snapshot *NeedSnapshot) { snapshot.SourceText = &invalid }},
{name: "title with NUL", change: func(snapshot *NeedSnapshot) { snapshot.Title = nul }},
{name: "source text with NUL", change: func(snapshot *NeedSnapshot) { snapshot.SourceText = &nul }},
{name: "provenance quote", change: func(snapshot *NeedSnapshot) {
snapshot.Requirements.Specialization = NeedValue[SpecializationCode]{
Status: NeedValueExtracted, Value: needPointer(SpecializationBackend), Source: textNeedSource(1),
}
snapshot.Requirements.Specialization.Source.Quote = &invalid
}},
{name: "skill name with NUL", change: func(snapshot *NeedSnapshot) {
snapshot.Requirements.RequiredSkills = []NeedSkill{{Name: nul, Status: NeedItemConfirmed, Source: *manualNeedSource()}}
}},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
@@ -360,6 +474,14 @@ func confirmedNeedValue[T any](value T, source *NeedValueSource) NeedValue[T] {
func needPointer[T any](value T) *T { return &value }
func tooManyNeedRejectedSuggestions() []NeedRejectedSuggestion {
suggestions := make([]NeedRejectedSuggestion, MaxNeedRejectedSuggestions+1)
for index := range suggestions {
suggestions[index] = NeedRejectedSuggestion{Field: NeedRejectedTasks, Value: fmt.Sprintf("task-%d", index)}
}
return suggestions
}
func containsNeedField(fields []NeedMissingField, field NeedMissingFieldName) bool {
for _, candidate := range fields {
if candidate.Field == field {
+129 -5
View File
@@ -62,6 +62,12 @@ const (
maxSameGradeRetryInterval = CalendarDays(365)
maxAssessmentAttemptsPerWindow = 20
maxAssessmentAttemptWindow = CalendarDays(730)
maxAssessmentLifetime = Hours(30 * 24)
maxAssessmentIdleTimeoutSeconds = 24 * 60 * 60
maxAssessmentSessions = 10
minAssessmentExpressSeconds = 180
maxAssessmentExpressSeconds = 300
maxAssessmentExpressItems = 20
maxPromotionInterval = CalendarDays(730)
maxScoredItems = 200
maxSeedItems = 20
@@ -84,6 +90,9 @@ type ProductPolicy struct {
Assessment AssessmentPolicy
Identity IdentityPolicy
SearchStatus SearchStatusPolicy
// Support is absent only in immutable policy documents that predate the
// support section. New demo policies should set it explicitly.
Support *SupportPolicy
}
// Validate checks every section. A zero value is never valid, so a section
@@ -100,6 +109,11 @@ func (policy ProductPolicy) Validate() error {
return err
}
}
if policy.Support != nil {
if err := policy.Support.Validate(); err != nil {
return fmt.Errorf("ProductPolicy.Validate - support section: %w: %w", ErrInvalidPolicy, err)
}
}
return nil
}
@@ -108,6 +122,18 @@ func (policy ProductPolicy) Validate() error {
func (policy ProductPolicy) clone() ProductPolicy {
copied := policy
copied.Invitations.ResponseDeadlineOptions = slices.Clone(policy.Invitations.ResponseDeadlineOptions)
if attempt := policy.Assessment.Attempt; attempt != nil {
attemptCopy := *attempt
copied.Assessment.Attempt = &attemptCopy
}
if training := policy.Assessment.Training; training != nil {
trainingCopy := *training
copied.Assessment.Training = &trainingCopy
}
if support := policy.Support; support != nil {
supportCopy := *support
copied.Support = &supportCopy
}
return copied
}
@@ -276,10 +302,9 @@ type AssessmentPolicy struct {
// SameGradeRetryAfter is the pause before another attempt at the same
// grade.
SameGradeRetryAfter CalendarDays
// MaxAttemptsPerWindow limits attempts in any AttemptWindow. Whether the
// limit counts per grade, per specialty, or across all assessments of a
// candidate is an open question for attempt accounting;
// the policy stores only the number.
// MaxAttemptsPerWindow limits a candidate's root attempts across all
// specializations in any AttemptWindow. Corrective and training attempts
// do not reserve another root slot.
MaxAttemptsPerWindow int32
AttemptWindow CalendarDays
// PromotionMinInterval is the minimum time between grade promotions.
@@ -292,6 +317,92 @@ type AssessmentPolicy struct {
// scored attempt.
PracticeRequired bool
StopRule AssessmentStopRule
// Attempt is nil in legacy policy documents that predate the attempt
// contract. Attempt creation must fail closed when it is nil; readers keep
// those policy versions available for records created under them.
Attempt *AssessmentAttemptPolicy
// Training is an explicit non-qualification policy section. It is nil in
// immutable legacy policies and never inherits real assessment settings.
Training *AssessmentTrainingPolicy
}
// AssessmentAttemptPolicy holds the versioned execution limits for a newly
// started attempt. It is optional only for immutable legacy policy versions;
// callers cannot infer missing values from defaults.
type AssessmentAttemptPolicy struct {
Lifetime Hours
ChainDeadline Hours
MaxSessions int32
IdleTimeoutSeconds int32
RealMode AssessmentRealMode
BasicPassMark BasisPoints
}
// AssessmentTrainingPolicy holds settings for a separate training run. Its
// bank source is pinned independently from real category openings.
type AssessmentTrainingPolicy struct {
DemoExpressDurationSeconds int32
DemoExpressItemCount int32
MaxSessions int32
IdleTimeoutSeconds int32
}
// AssessmentRealMode is a server-selected mode for a real assessment.
type AssessmentRealMode string
const (
AssessmentRealModeDemoBasic AssessmentRealMode = "demo_basic"
AssessmentRealModeAdaptive AssessmentRealMode = "adaptive"
)
func (policy AssessmentAttemptPolicy) validate(calibration AssessmentCalibration) error {
const location = "AssessmentAttemptPolicy.Validate"
if err := firstError(
checkRange(location, "assessment.attempt.lifetime_hours", policy.Lifetime, 1, maxAssessmentLifetime),
checkRange(location, "assessment.attempt.chain_deadline_hours", policy.ChainDeadline, 1, maxAssessmentLifetime),
checkRange(location, "assessment.attempt.max_sessions", policy.MaxSessions, 1, maxAssessmentSessions),
checkRange(location, "assessment.attempt.idle_timeout_seconds", policy.IdleTimeoutSeconds, 60, maxAssessmentIdleTimeoutSeconds),
); err != nil {
return err
}
if policy.ChainDeadline > policy.Lifetime {
return invalidPolicy(location, "assessment.attempt.chain_deadline_hours must not exceed lifetime_hours")
}
if int64(policy.IdleTimeoutSeconds) > int64(policy.Lifetime)*60*60 {
return invalidPolicy(location, "assessment.attempt.idle_timeout_seconds must not exceed lifetime_hours")
}
switch policy.RealMode {
case AssessmentRealModeDemoBasic:
if err := checkRange(location, "assessment.attempt.basic_pass_mark_bp", policy.BasicPassMark, 1, basisPointsPerUnit); err != nil {
return err
}
case AssessmentRealModeAdaptive:
if policy.BasicPassMark != 0 {
return invalidPolicy(location, "assessment.attempt.basic_pass_mark_bp must be zero in adaptive mode")
}
if calibration != AssessmentCalibrationCalibrated {
return invalidPolicy(location, "adaptive assessment mode requires a calibrated assessment policy")
}
default:
return invalidPolicy(location, "assessment.attempt.real_mode must be demo_basic or adaptive")
}
return nil
}
func (policy AssessmentTrainingPolicy) validate() error {
const location = "AssessmentTrainingPolicy.Validate"
if err := firstError(
checkRange(location, "assessment.training.demo_express_duration_seconds", policy.DemoExpressDurationSeconds, minAssessmentExpressSeconds, maxAssessmentExpressSeconds),
checkRange(location, "assessment.training.demo_express_item_count", policy.DemoExpressItemCount, 1, maxAssessmentExpressItems),
checkRange(location, "assessment.training.max_sessions", policy.MaxSessions, 1, maxAssessmentSessions),
checkRange(location, "assessment.training.idle_timeout_seconds", policy.IdleTimeoutSeconds, 60, maxAssessmentIdleTimeoutSeconds),
); err != nil {
return err
}
if policy.IdleTimeoutSeconds > policy.DemoExpressDurationSeconds {
return invalidPolicy(location, "assessment.training.idle_timeout_seconds must not exceed demo_express_duration_seconds")
}
return nil
}
// AssessmentStopRule ends an adaptive attempt. After MinScoredItems the
@@ -328,7 +439,20 @@ func (policy AssessmentPolicy) Validate() error {
if policy.HighStrengthThreshold < policy.ConfirmationThreshold {
return invalidPolicy(location, "assessment.high_strength_threshold_bp must not be below the confirmation threshold")
}
return policy.StopRule.validate(location, policy.ConfirmationThreshold)
if err := policy.StopRule.validate(location, policy.ConfirmationThreshold); err != nil {
return err
}
if policy.Attempt != nil {
if err := policy.Attempt.validate(policy.Calibration); err != nil {
return err
}
}
if policy.Training != nil {
if err := policy.Training.validate(); err != nil {
return err
}
}
return nil
}
func (rule AssessmentStopRule) validate(location string, confirmation BasisPoints) error {
@@ -0,0 +1,67 @@
package domain
import (
"bytes"
"testing"
)
func TestLegacyPolicyDocumentRestoresWithoutAttemptSettings(t *testing.T) {
policy, err := decodeProductPolicy([]byte(demoProductPolicyV1Document))
if err != nil {
t.Fatalf("decodeProductPolicy(V1) error = %v", err)
}
if policy.Assessment.Attempt != nil {
t.Fatal("legacy V1 policy acquired implicit attempt settings")
}
encoded, _, err := encodeProductPolicy(policy)
if err != nil {
t.Fatalf("encodeProductPolicy(V1) error = %v", err)
}
if !bytes.Equal(encoded, []byte(demoProductPolicyV1Document)) {
t.Fatalf("legacy V1 canonical document changed:\n%s\nwant:\n%s", encoded, demoProductPolicyV1Document)
}
}
func TestDemoProductPolicyV2PinsAttemptSettings(t *testing.T) {
policy := DemoProductPolicyV2()
if err := policy.Validate(); err != nil {
t.Fatalf("DemoProductPolicyV2().Validate() error = %v", err)
}
got := policy.Assessment.Attempt
if got == nil {
t.Fatal("DemoProductPolicyV2() has no attempt settings")
}
if got.Lifetime != 72 || got.ChainDeadline != 72 || got.MaxSessions != 2 ||
got.IdleTimeoutSeconds != 1800 || got.RealMode != AssessmentRealModeDemoBasic ||
got.BasicPassMark != 8000 {
t.Fatalf("DemoProductPolicyV2().Assessment.Attempt = %+v, want explicitly configured values", got)
}
if training := policy.Assessment.Training; training == nil || training.DemoExpressDurationSeconds != 240 || training.DemoExpressItemCount != 3 {
t.Fatalf("DemoProductPolicyV2().Assessment.Training = %+v, want explicit duration and item count", training)
}
draft, err := NewPolicyVersionDraft(NewPolicyVersionDraftInput{
Key: ProductPolicyKey, Kind: PolicyKindDemo, Author: DemoPolicySeedAuthor, Policy: policy,
})
if err != nil {
t.Fatalf("NewPolicyVersionDraft(V2) error = %v", err)
}
decoded, err := decodeProductPolicy(draft.Document())
if err != nil {
t.Fatalf("decodeProductPolicy(V2) error = %v", err)
}
if decoded.Assessment.Attempt == nil || *decoded.Assessment.Attempt != *got ||
decoded.Assessment.Training == nil || *decoded.Assessment.Training != *policy.Assessment.Training {
t.Fatalf("decoded attempt policy = %+v, want %+v", decoded.Assessment.Attempt, got)
}
returnedPolicy := draft.Policy()
returnedPolicy.Assessment.Attempt.IdleTimeoutSeconds++
if draft.Policy().Assessment.Attempt.IdleTimeoutSeconds != got.IdleTimeoutSeconds {
t.Fatal("changing returned attempt settings changed the policy draft")
}
returnedPolicy.Assessment.Training.DemoExpressDurationSeconds++
if draft.Policy().Assessment.Training.DemoExpressDurationSeconds != policy.Assessment.Training.DemoExpressDurationSeconds {
t.Fatal("changing returned training settings changed the policy draft")
}
}
+26
View File
@@ -60,3 +60,29 @@ func DemoProductPolicyV1() ProductPolicy {
},
}
}
// DemoProductPolicyV2 returns an explicit demo policy with assessment attempt
// execution values. The idle timeout, mode, and basic pass mark are initial
// product choices, not facts established by the assessment PRD or calibration.
// Publishing this value is an explicit operation; startup seeding continues
// to publish V1 only and never replaces an immutable stored version.
func DemoProductPolicyV2() ProductPolicy {
policy := DemoProductPolicyV1()
policy.Assessment.Attempt = &AssessmentAttemptPolicy{
Lifetime: 72,
ChainDeadline: 72,
MaxSessions: 2,
IdleTimeoutSeconds: 1800,
RealMode: AssessmentRealModeDemoBasic,
BasicPassMark: 8000,
}
policy.Assessment.Training = &AssessmentTrainingPolicy{
DemoExpressDurationSeconds: 240,
DemoExpressItemCount: 3,
MaxSessions: 1,
IdleTimeoutSeconds: 240,
}
support := DemoSupportPolicy()
policy.Support = &support
return policy
}
+201 -22
View File
@@ -10,10 +10,11 @@ import (
)
const (
// productPolicySchemaVersion is the layout of the stored document. A new
// layout adds a decoder for its version; stored versions are never
// rewritten.
productPolicySchemaVersion = 1
// productPolicySchemaVersionV1 is the original immutable policy layout.
productPolicySchemaVersionV1 = 1
// productPolicySchemaVersionV2 adds optional policy extensions. Stored
// versions are never rewritten when a newer layout is introduced.
productPolicySchemaVersionV2 = 2
// maxPolicyDocumentBytes bounds a document before decoding. The current
// layout encodes to well under 2 KiB.
maxPolicyDocumentBytes = 64 << 10
@@ -22,9 +23,11 @@ const (
// PolicyDocumentHash is the SHA-256 of the canonical policy document.
type PolicyDocumentHash [sha256.Size]byte
// The document types mirror ProductPolicy field by field. Every field is a
// pointer, so the decoder can tell a missing field from a zero value: a
// missing field is an error, never a default. Field names carry their unit.
// The document types mirror ProductPolicy field by field. Required fields are
// pointers, so the decoder can tell a missing field from a zero value: a
// missing field is an error, never a default. Optional attempt, training, and
// support sections are absent only in immutable legacy policy documents.
// Field names carry their unit.
type productPolicyDocument struct {
SchemaVersion *int32 `json:"schema_version"`
Invitations *invitationPolicyDocument `json:"invitations"`
@@ -32,6 +35,18 @@ type productPolicyDocument struct {
Assessment *assessmentPolicyDocument `json:"assessment"`
Identity *identityPolicyDocument `json:"identity"`
SearchStatus *searchStatusDocument `json:"search_status"`
Support *supportPolicyDocument `json:"support,omitempty"`
}
// productPolicyV1Document deliberately excludes extension keys. Its strict
// decoder keeps old documents unambiguous even when a newer field is null.
type productPolicyV1Document struct {
SchemaVersion *int32 `json:"schema_version"`
Invitations *invitationPolicyDocument `json:"invitations"`
OrganizationQuotas *organizationQuotaDocument `json:"organization_quotas"`
Assessment *assessmentPolicyV1Document `json:"assessment"`
Identity *identityPolicyDocument `json:"identity"`
SearchStatus *searchStatusDocument `json:"search_status"`
}
type invitationPolicyDocument struct {
@@ -62,6 +77,20 @@ type organizationTierQuotaDocument struct {
}
type assessmentPolicyDocument struct {
Calibration *AssessmentCalibration `json:"calibration"`
SameGradeRetryAfterDays *CalendarDays `json:"same_grade_retry_after_days"`
MaxAttemptsPerWindow *int32 `json:"max_attempts_per_window"`
AttemptWindowDays *CalendarDays `json:"attempt_window_days"`
PromotionMinIntervalDays *CalendarDays `json:"promotion_min_interval_days"`
ConfirmationThresholdBP *BasisPoints `json:"confirmation_threshold_bp"`
HighStrengthThresholdBP *BasisPoints `json:"high_strength_threshold_bp"`
PracticeRequired *bool `json:"practice_required"`
StopRule *assessmentStopDocument `json:"stop_rule"`
Attempt *assessmentAttemptDocument `json:"attempt,omitempty"`
Training *assessmentTrainingDocument `json:"training,omitempty"`
}
type assessmentPolicyV1Document struct {
Calibration *AssessmentCalibration `json:"calibration"`
SameGradeRetryAfterDays *CalendarDays `json:"same_grade_retry_after_days"`
MaxAttemptsPerWindow *int32 `json:"max_attempts_per_window"`
@@ -73,6 +102,22 @@ type assessmentPolicyDocument struct {
StopRule *assessmentStopDocument `json:"stop_rule"`
}
type assessmentAttemptDocument struct {
LifetimeHours *Hours `json:"lifetime_hours"`
ChainDeadlineHours *Hours `json:"chain_deadline_hours"`
MaxSessions *int32 `json:"max_sessions"`
IdleTimeoutSeconds *int32 `json:"idle_timeout_seconds"`
RealMode *AssessmentRealMode `json:"real_mode"`
BasicPassMarkBP *BasisPoints `json:"basic_pass_mark_bp"`
}
type assessmentTrainingDocument struct {
DemoExpressDurationSeconds *int32 `json:"demo_express_duration_seconds"`
DemoExpressItemCount *int32 `json:"demo_express_item_count"`
MaxSessions *int32 `json:"max_sessions"`
IdleTimeoutSeconds *int32 `json:"idle_timeout_seconds"`
}
type assessmentStopDocument struct {
MinScoredItems *int32 `json:"min_scored_items"`
MaxScoredItems *int32 `json:"max_scored_items"`
@@ -101,8 +146,20 @@ func encodeProductPolicy(policy ProductPolicy) ([]byte, PolicyDocumentHash, erro
quotas := policy.OrganizationQuotas
assessment := policy.Assessment
identity := policy.Identity
var support *supportPolicyDocument
if policy.Support != nil {
var err error
support, err = encodeSupportPolicy(*policy.Support)
if err != nil {
return nil, PolicyDocumentHash{}, err
}
}
schemaVersion := int32(productPolicySchemaVersionV1)
if policy.Assessment.Attempt != nil || policy.Assessment.Training != nil || policy.Support != nil {
schemaVersion = productPolicySchemaVersionV2
}
document := productPolicyDocument{
SchemaVersion: pointer(int32(productPolicySchemaVersion)),
SchemaVersion: pointer(schemaVersion),
Invitations: &invitationPolicyDocument{
ResponseDeadlineOptionsDays: pointer(invitations.ResponseDeadlineOptions),
DefaultResponseDeadlineDays: pointer(invitations.DefaultResponseDeadline),
@@ -137,6 +194,8 @@ func encodeProductPolicy(policy ProductPolicy) ([]byte, PolicyDocumentHash, erro
LowerProbabilityBP: pointer(assessment.StopRule.LowerProbability),
MaxStandardErrorBP: pointer(assessment.StopRule.MaxStandardError),
},
Attempt: encodeAssessmentAttemptPolicy(assessment.Attempt),
Training: encodeAssessmentTrainingPolicy(assessment.Training),
},
Identity: &identityPolicyDocument{
VerificationTokenLifetimeHours: pointer(identity.VerificationTokenLifetime),
@@ -147,6 +206,7 @@ func encodeProductPolicy(policy ProductPolicy) ([]byte, PolicyDocumentHash, erro
SearchStatus: &searchStatusDocument{
SearchingConfirmationIntervalDays: pointer(policy.SearchStatus.SearchingConfirmationInterval),
},
Support: support,
}
encoded, err := json.Marshal(document)
if err != nil {
@@ -155,6 +215,32 @@ func encodeProductPolicy(policy ProductPolicy) ([]byte, PolicyDocumentHash, erro
return encoded, sha256.Sum256(encoded), nil
}
func encodeAssessmentAttemptPolicy(policy *AssessmentAttemptPolicy) *assessmentAttemptDocument {
if policy == nil {
return nil
}
return &assessmentAttemptDocument{
LifetimeHours: pointer(policy.Lifetime),
ChainDeadlineHours: pointer(policy.ChainDeadline),
MaxSessions: pointer(policy.MaxSessions),
IdleTimeoutSeconds: pointer(policy.IdleTimeoutSeconds),
RealMode: pointer(policy.RealMode),
BasicPassMarkBP: pointer(policy.BasicPassMark),
}
}
func encodeAssessmentTrainingPolicy(policy *AssessmentTrainingPolicy) *assessmentTrainingDocument {
if policy == nil {
return nil
}
return &assessmentTrainingDocument{
DemoExpressDurationSeconds: pointer(policy.DemoExpressDurationSeconds),
DemoExpressItemCount: pointer(policy.DemoExpressItemCount),
MaxSessions: pointer(policy.MaxSessions),
IdleTimeoutSeconds: pointer(policy.IdleTimeoutSeconds),
}
}
func encodeTierQuota(quota OrganizationTierQuota) *organizationTierQuotaDocument {
return &organizationTierQuotaDocument{
Active: pointer(quota.Active),
@@ -163,30 +249,98 @@ func encodeTierQuota(quota OrganizationTierQuota) *organizationTierQuotaDocument
}
}
// decodeProductPolicy reads a document strictly: it rejects unknown fields,
// missing fields, null values, values of the wrong type or out of the int32
// range, an unknown schema version, and trailing data. It checks structure
// only; ProductPolicy.Validate checks the values. encoding/json matches field
// names without regard to letter case and keeps the last of duplicate keys;
// the document hash, computed over the canonical re-encoding, is what pins
// the content.
// decodeProductPolicy reads a versioned document strictly. It rejects unknown
// fields, missing fields, null required values, values of the wrong type or
// out of the int32 range, unknown schema versions, and trailing data. It
// checks structure only; ProductPolicy.Validate checks the values.
func decodeProductPolicy(document []byte) (ProductPolicy, error) {
const location = "domain.decodeProductPolicy"
if len(document) > maxPolicyDocumentBytes {
return ProductPolicy{}, invalidPolicy(location, fmt.Sprintf("document must have at most %d bytes", maxPolicyDocumentBytes))
}
decoder := json.NewDecoder(bytes.NewReader(document))
decoder.DisallowUnknownFields()
version, err := decodeProductPolicySchemaVersion(document)
if err != nil {
return ProductPolicy{}, err
}
var parsed productPolicyDocument
if err := decoder.Decode(&parsed); err != nil {
return ProductPolicy{}, fmt.Errorf("%s - decode document: %w: %w", location, ErrInvalidPolicy, err)
switch version {
case productPolicySchemaVersionV1:
var legacy productPolicyV1Document
if err := decodeStrictPolicyDocument(document, &legacy); err != nil {
return ProductPolicy{}, err
}
parsed = productPolicyDocument{
SchemaVersion: legacy.SchemaVersion,
Invitations: legacy.Invitations,
OrganizationQuotas: legacy.OrganizationQuotas,
Identity: legacy.Identity,
SearchStatus: legacy.SearchStatus,
}
if legacy.Assessment != nil {
assessment := legacy.Assessment
parsed.Assessment = &assessmentPolicyDocument{
Calibration: assessment.Calibration,
SameGradeRetryAfterDays: assessment.SameGradeRetryAfterDays,
MaxAttemptsPerWindow: assessment.MaxAttemptsPerWindow,
AttemptWindowDays: assessment.AttemptWindowDays,
PromotionMinIntervalDays: assessment.PromotionMinIntervalDays,
ConfirmationThresholdBP: assessment.ConfirmationThresholdBP,
HighStrengthThresholdBP: assessment.HighStrengthThresholdBP,
PracticeRequired: assessment.PracticeRequired,
StopRule: assessment.StopRule,
}
}
case productPolicySchemaVersionV2:
if err := decodeStrictPolicyDocument(document, &parsed); err != nil {
return ProductPolicy{}, err
}
assessment := parsed.Assessment
hasAssessmentExtension := assessment != nil && (assessment.Attempt != nil || assessment.Training != nil)
if !hasAssessmentExtension && parsed.Support == nil {
return ProductPolicy{}, invalidPolicy(location, "schema_version 2 requires at least one policy extension")
}
default:
return ProductPolicy{}, invalidPolicy(location, fmt.Sprintf("schema_version must be %d or %d", productPolicySchemaVersionV1, productPolicySchemaVersionV2))
}
return decodeProductPolicyFields(parsed, version)
}
func decodeProductPolicySchemaVersion(document []byte) (int32, error) {
const location = "domain.decodeProductPolicy"
var envelope struct {
SchemaVersion *int32 `json:"schema_version"`
}
decoder := json.NewDecoder(bytes.NewReader(document))
if err := decoder.Decode(&envelope); err != nil {
return 0, fmt.Errorf("%s - decode document: %w: %w", location, ErrInvalidPolicy, err)
}
if _, err := decoder.Token(); !errors.Is(err, io.EOF) {
return ProductPolicy{}, invalidPolicy(location, "document must contain one JSON object")
return 0, invalidPolicy(location, "document must contain one JSON object")
}
if envelope.SchemaVersion == nil {
return 0, invalidPolicy(location, "schema_version is required and must be an integer")
}
return *envelope.SchemaVersion, nil
}
func decodeStrictPolicyDocument[T any](document []byte, parsed *T) error {
const location = "domain.decodeProductPolicy"
decoder := json.NewDecoder(bytes.NewReader(document))
decoder.DisallowUnknownFields()
if err := decoder.Decode(parsed); err != nil {
return fmt.Errorf("%s - decode document: %w: %w", location, ErrInvalidPolicy, err)
}
if _, err := decoder.Token(); !errors.Is(err, io.EOF) {
return invalidPolicy(location, "document must contain one JSON object")
}
return nil
}
func decodeProductPolicyFields(parsed productPolicyDocument, schemaVersion int32) (ProductPolicy, error) {
const location = "domain.decodeProductPolicy"
reader := documentReader{}
if version := require(&reader, "schema_version", parsed.SchemaVersion); reader.missing == "" && version != productPolicySchemaVersion {
return ProductPolicy{}, invalidPolicy(location, fmt.Sprintf("schema_version must be %d", productPolicySchemaVersion))
if version := require(&reader, "schema_version", parsed.SchemaVersion); reader.missing == "" && version != schemaVersion {
return ProductPolicy{}, invalidPolicy(location, fmt.Sprintf("schema_version must be %d", schemaVersion))
}
invitations := require(&reader, "invitations", parsed.Invitations)
quotas := require(&reader, "organization_quotas", parsed.OrganizationQuotas)
@@ -195,6 +349,28 @@ func decodeProductPolicy(document []byte) (ProductPolicy, error) {
stopRule := require(&reader, "assessment.stop_rule", assessment.StopRule)
identity := require(&reader, "identity", parsed.Identity)
searchStatus := require(&reader, "search_status", parsed.SearchStatus)
var attemptPolicy *AssessmentAttemptPolicy
if assessment.Attempt != nil {
attempt := assessment.Attempt
attemptPolicy = &AssessmentAttemptPolicy{
Lifetime: require(&reader, "assessment.attempt.lifetime_hours", attempt.LifetimeHours),
ChainDeadline: require(&reader, "assessment.attempt.chain_deadline_hours", attempt.ChainDeadlineHours),
MaxSessions: require(&reader, "assessment.attempt.max_sessions", attempt.MaxSessions),
IdleTimeoutSeconds: require(&reader, "assessment.attempt.idle_timeout_seconds", attempt.IdleTimeoutSeconds),
RealMode: require(&reader, "assessment.attempt.real_mode", attempt.RealMode),
BasicPassMark: require(&reader, "assessment.attempt.basic_pass_mark_bp", attempt.BasicPassMarkBP),
}
}
var trainingPolicy *AssessmentTrainingPolicy
if assessment.Training != nil {
training := assessment.Training
trainingPolicy = &AssessmentTrainingPolicy{
DemoExpressDurationSeconds: require(&reader, "assessment.training.demo_express_duration_seconds", training.DemoExpressDurationSeconds),
DemoExpressItemCount: require(&reader, "assessment.training.demo_express_item_count", training.DemoExpressItemCount),
MaxSessions: require(&reader, "assessment.training.max_sessions", training.MaxSessions),
IdleTimeoutSeconds: require(&reader, "assessment.training.idle_timeout_seconds", training.IdleTimeoutSeconds),
}
}
policy := ProductPolicy{
Invitations: InvitationPolicy{
ResponseDeadlineOptions: require(&reader, "invitations.response_deadline_options_days", invitations.ResponseDeadlineOptionsDays),
@@ -228,6 +404,8 @@ func decodeProductPolicy(document []byte) (ProductPolicy, error) {
LowerProbability: require(&reader, "assessment.stop_rule.lower_probability_bp", stopRule.LowerProbabilityBP),
MaxStandardError: require(&reader, "assessment.stop_rule.max_standard_error_bp", stopRule.MaxStandardErrorBP),
},
Attempt: attemptPolicy,
Training: trainingPolicy,
},
Identity: IdentityPolicy{
VerificationTokenLifetime: require(&reader, "identity.verification_token_lifetime_hours", identity.VerificationTokenLifetimeHours),
@@ -238,6 +416,7 @@ func decodeProductPolicy(document []byte) (ProductPolicy, error) {
SearchStatus: SearchStatusPolicy{
SearchingConfirmationInterval: require(&reader, "search_status.searching_confirmation_interval_days", searchStatus.SearchingConfirmationIntervalDays),
},
Support: decodeOptionalSupportPolicy(&reader, parsed.Support),
}
if reader.missing != "" {
return ProductPolicy{}, invalidPolicy(location, reader.missing+" is required")
@@ -0,0 +1,140 @@
package domain
import (
"encoding/json"
"errors"
"testing"
)
func TestPolicySchemaVersionsPreserveLegacyAndRequireExtensions(t *testing.T) {
t.Run("schema 1 rejects every extension key even when null", func(t *testing.T) {
for _, test := range []struct {
name string
edit func(map[string]any)
}{
{name: "attempt", edit: func(document map[string]any) { policySection(t, document, "assessment")["attempt"] = nil }},
{name: "training", edit: func(document map[string]any) { policySection(t, document, "assessment")["training"] = nil }},
{name: "support", edit: func(document map[string]any) { document["support"] = nil }},
} {
t.Run(test.name, func(t *testing.T) {
encoded := editPolicySchemaDocument(t, []byte(demoProductPolicyV1Document), test.edit)
if _, err := decodeProductPolicy(encoded); !errors.Is(err, ErrInvalidPolicy) {
t.Fatalf("decodeProductPolicy(schema 1 with null %s) error = %v, want ErrInvalidPolicy", test.name, err)
}
})
}
})
t.Run("schema 2 requires at least one extension", func(t *testing.T) {
encoded := editPolicySchemaDocument(t, []byte(demoProductPolicyV1Document), func(document map[string]any) {
document["schema_version"] = 2
})
if _, err := decodeProductPolicy(encoded); !errors.Is(err, ErrInvalidPolicy) {
t.Fatalf("decodeProductPolicy(schema 2 without extensions) error = %v, want ErrInvalidPolicy", err)
}
})
t.Run("unknown schema version is rejected", func(t *testing.T) {
encoded := editPolicySchemaDocument(t, []byte(demoProductPolicyV1Document), func(document map[string]any) {
document["schema_version"] = 3
})
if _, err := decodeProductPolicy(encoded); !errors.Is(err, ErrInvalidPolicy) {
t.Fatalf("decodeProductPolicy(schema 3) error = %v, want ErrInvalidPolicy", err)
}
})
}
func TestPolicySchemaV2RoundTripsEachExtensionIndependently(t *testing.T) {
base := DemoProductPolicyV1()
configured := DemoProductPolicyV2()
tests := []struct {
name string
change func(*ProductPolicy)
check func(*testing.T, ProductPolicy)
}{
{
name: "attempt",
change: func(policy *ProductPolicy) {
attempt := *configured.Assessment.Attempt
policy.Assessment.Attempt = &attempt
},
check: func(t *testing.T, policy ProductPolicy) {
t.Helper()
if policy.Assessment.Attempt == nil || policy.Assessment.Training != nil || policy.Support != nil {
t.Fatalf("decoded extensions = attempt:%v training:%v support:%v", policy.Assessment.Attempt != nil, policy.Assessment.Training != nil, policy.Support != nil)
}
},
},
{
name: "training",
change: func(policy *ProductPolicy) {
training := *configured.Assessment.Training
policy.Assessment.Training = &training
},
check: func(t *testing.T, policy ProductPolicy) {
t.Helper()
if policy.Assessment.Attempt != nil || policy.Assessment.Training == nil || policy.Support != nil {
t.Fatalf("decoded extensions = attempt:%v training:%v support:%v", policy.Assessment.Attempt != nil, policy.Assessment.Training != nil, policy.Support != nil)
}
},
},
{
name: "support",
change: func(policy *ProductPolicy) {
support := *configured.Support
policy.Support = &support
},
check: func(t *testing.T, policy ProductPolicy) {
t.Helper()
if policy.Assessment.Attempt != nil || policy.Assessment.Training != nil || policy.Support == nil {
t.Fatalf("decoded extensions = attempt:%v training:%v support:%v", policy.Assessment.Attempt != nil, policy.Assessment.Training != nil, policy.Support != nil)
}
},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
policy := base.clone()
test.change(&policy)
encoded, _, err := encodeProductPolicy(policy)
if err != nil {
t.Fatalf("encodeProductPolicy() error = %v", err)
}
var envelope struct {
SchemaVersion int32 `json:"schema_version"`
}
if err := json.Unmarshal(encoded, &envelope); err != nil || envelope.SchemaVersion != productPolicySchemaVersionV2 {
t.Fatalf("encoded schema version = %d (error %v), want 2", envelope.SchemaVersion, err)
}
decoded, err := decodeProductPolicy(encoded)
if err != nil {
t.Fatalf("decodeProductPolicy() error = %v", err)
}
test.check(t, decoded)
})
}
}
func editPolicySchemaDocument(t *testing.T, source []byte, edit func(map[string]any)) []byte {
t.Helper()
var document map[string]any
if err := json.Unmarshal(source, &document); err != nil {
t.Fatalf("unmarshal policy document: %v", err)
}
edit(document)
encoded, err := json.Marshal(document)
if err != nil {
t.Fatalf("marshal policy document: %v", err)
}
return encoded
}
func policySection(t *testing.T, document map[string]any, name string) map[string]any {
t.Helper()
section, ok := document[name].(map[string]any)
if !ok {
t.Fatalf("policy document %q section is missing or invalid", name)
}
return section
}
+87
View File
@@ -0,0 +1,87 @@
package domain
import (
"fmt"
"time"
)
// supportPolicyDocument is the strict stored representation of the support
// section. Pointer fields make omission distinct from a configured zero.
type supportPolicyDocument struct {
SupportResponseDays *BusinessDays `json:"support_response_business_days"`
ComplaintResponseDays *BusinessDays `json:"complaint_response_business_days"`
ManualAssessmentResponseDays *BusinessDays `json:"manual_assessment_response_business_days"`
AppealResponseDays *BusinessDays `json:"appeal_response_business_days"`
MaxRequestsPerWindow *int32 `json:"max_requests_per_window"`
RequestWindowSeconds *int32 `json:"request_window_seconds"`
MaxAppealsPerTarget *int32 `json:"max_appeals_per_target"`
PauseWhenWaitingForUser *bool `json:"pause_when_waiting_for_user"`
BusinessCalendarVersion *int32 `json:"business_calendar_version"`
}
func encodeSupportPolicy(policy SupportPolicy) (*supportPolicyDocument, error) {
requestWindowSeconds := int64(policy.requestWindow / time.Second)
if requestWindowSeconds < 1 || policy.requestWindow%time.Second != 0 || requestWindowSeconds > 1<<31-1 {
return nil, fmt.Errorf("encodeSupportPolicy - request window must fit whole int32 seconds: %w", ErrInvalidSupportPolicy)
}
return &supportPolicyDocument{
SupportResponseDays: pointer(policy.supportResponseDays),
ComplaintResponseDays: pointer(policy.complaintResponseDays),
ManualAssessmentResponseDays: pointer(policy.manualAssessmentResponseDays),
AppealResponseDays: pointer(policy.appealResponseDays),
MaxRequestsPerWindow: pointer(policy.maxRequestsPerWindow),
RequestWindowSeconds: pointer(int32(requestWindowSeconds)),
MaxAppealsPerTarget: pointer(policy.maxAppealsPerTarget),
PauseWhenWaitingForUser: pointer(policy.pauseWhenWaitingForUser),
BusinessCalendarVersion: pointer(policy.businessCalendarVersion),
}, nil
}
// decodeSupportPolicy reads every required support field. Unknown fields are
// rejected by the enclosing product-policy decoder, which uses
// DisallowUnknownFields.
func decodeSupportPolicy(reader *documentReader, document *supportPolicyDocument) SupportPolicy {
return SupportPolicy{
supportResponseDays: require(reader, "support.support_response_business_days", document.SupportResponseDays),
complaintResponseDays: require(reader, "support.complaint_response_business_days", document.ComplaintResponseDays),
manualAssessmentResponseDays: require(reader, "support.manual_assessment_response_business_days", document.ManualAssessmentResponseDays),
appealResponseDays: require(reader, "support.appeal_response_business_days", document.AppealResponseDays),
maxRequestsPerWindow: require(reader, "support.max_requests_per_window", document.MaxRequestsPerWindow),
requestWindow: time.Duration(require(reader, "support.request_window_seconds", document.RequestWindowSeconds)) * time.Second,
maxAppealsPerTarget: require(reader, "support.max_appeals_per_target", document.MaxAppealsPerTarget),
pauseWhenWaitingForUser: require(reader, "support.pause_when_waiting_for_user", document.PauseWhenWaitingForUser),
businessCalendarVersion: require(reader, "support.business_calendar_version", document.BusinessCalendarVersion),
}
}
// decodeOptionalSupportPolicy preserves immutable legacy documents that were
// published before the support section existed. It never fills an omitted
// section with demo values.
func decodeOptionalSupportPolicy(reader *documentReader, document *supportPolicyDocument) *SupportPolicy {
if document == nil {
return nil
}
policy := decodeSupportPolicy(reader, document)
return &policy
}
// Validate rejects an absent or unsupported support-policy section. Product
// policies may leave the optional section nil only for immutable legacy
// documents; policy creation uses an explicit SupportPolicy value.
func (policy SupportPolicy) Validate() error {
if policy.IsZero() {
return ErrInvalidSupportPolicy
}
_, err := NewSupportPolicy(SupportPolicyInput{
SupportResponseDays: policy.supportResponseDays,
ComplaintResponseDays: policy.complaintResponseDays,
ManualAssessmentResponseDays: policy.manualAssessmentResponseDays,
AppealResponseDays: policy.appealResponseDays,
MaxRequestsPerWindow: policy.maxRequestsPerWindow,
RequestWindow: policy.requestWindow,
MaxAppealsPerTarget: policy.maxAppealsPerTarget,
PauseWhenWaitingForUser: policy.pauseWhenWaitingForUser,
BusinessCalendarVersion: policy.businessCalendarVersion,
})
return err
}
+36
View File
@@ -202,6 +202,37 @@ func TestProductPolicyValidateRejectsEachSection(t *testing.T) {
"upper stop below confirmation": func(policy *ProductPolicy) { policy.Assessment.StopRule.UpperProbability = 7000 },
"zero standard error": func(policy *ProductPolicy) { policy.Assessment.StopRule.MaxStandardError = 0 },
"standard error above one": func(policy *ProductPolicy) { policy.Assessment.StopRule.MaxStandardError = 10001 },
"zero attempt lifetime": func(policy *ProductPolicy) {
policy.Assessment.Attempt.Lifetime = 0
},
"chain exceeds attempt lifetime": func(policy *ProductPolicy) {
policy.Assessment.Attempt.Lifetime = 24
policy.Assessment.Attempt.ChainDeadline = 25
},
"idle timeout above lifetime": func(policy *ProductPolicy) {
policy.Assessment.Attempt.Lifetime = 1
policy.Assessment.Attempt.IdleTimeoutSeconds = 3601
},
"unknown real attempt mode": func(policy *ProductPolicy) {
policy.Assessment.Attempt.RealMode = "client_selected"
},
"basic mode missing pass mark": func(policy *ProductPolicy) {
policy.Assessment.Attempt.BasicPassMark = 0
},
"adaptive mode with basic mark": func(policy *ProductPolicy) {
policy.Assessment.Attempt.RealMode = AssessmentRealModeAdaptive
},
"adaptive mode without calibration": func(policy *ProductPolicy) {
policy.Assessment.Calibration = AssessmentCalibrationUncalibratedInitial
policy.Assessment.Attempt.RealMode = AssessmentRealModeAdaptive
policy.Assessment.Attempt.BasicPassMark = 0
},
"invalid express duration": func(policy *ProductPolicy) {
policy.Assessment.Training.DemoExpressDurationSeconds = 179
},
"invalid express item count": func(policy *ProductPolicy) {
policy.Assessment.Training.DemoExpressItemCount = 0
},
"zero token lifetime": func(policy *ProductPolicy) { policy.Identity.VerificationTokenLifetime = 0 },
"zero unverified account lifetime": func(policy *ProductPolicy) { policy.Identity.UnverifiedAccountLifetime = 0 },
"zero idle timeout": func(policy *ProductPolicy) { policy.Identity.SessionIdleTimeout = 0 },
@@ -220,6 +251,11 @@ func TestProductPolicyValidateRejectsEachSection(t *testing.T) {
for name, mutate := range tests {
t.Run(name, func(t *testing.T) {
policy := testPolicy()
preset := DemoProductPolicyV2().Assessment
attempt := *preset.Attempt
training := *preset.Training
policy.Assessment.Attempt = &attempt
policy.Assessment.Training = &training
mutate(&policy)
if err := policy.Validate(); !errors.Is(err, ErrInvalidPolicy) {
t.Fatalf("Validate() error = %v, want ErrInvalidPolicy", err)
@@ -0,0 +1,90 @@
package domain
import (
"bytes"
"errors"
"strings"
"testing"
)
func TestDemoProductPolicyV2PinsTrainingSessionLimits(t *testing.T) {
policy := DemoProductPolicyV2()
if err := policy.Validate(); err != nil {
t.Fatalf("DemoProductPolicyV2().Validate() error = %v", err)
}
training := policy.Assessment.Training
if training == nil || training.DemoExpressDurationSeconds != 240 || training.DemoExpressItemCount != 3 ||
training.MaxSessions != 1 || training.IdleTimeoutSeconds != 240 {
t.Fatalf("DemoProductPolicyV2().Assessment.Training = %+v, want explicit demo limits", training)
}
encoded, _, err := encodeProductPolicy(policy)
if err != nil {
t.Fatalf("encodeProductPolicy() error = %v", err)
}
decoded, err := decodeProductPolicy(encoded)
if err != nil {
t.Fatalf("decodeProductPolicy() error = %v", err)
}
if decoded.Assessment.Training == nil || *decoded.Assessment.Training != *training {
t.Fatalf("decoded training policy = %+v, want %+v", decoded.Assessment.Training, training)
}
}
func TestTrainingPolicyRequiresAllDocumentFieldsAndRejectsUnknownFields(t *testing.T) {
encoded, _, err := encodeProductPolicy(DemoProductPolicyV2())
if err != nil {
t.Fatalf("encodeProductPolicy() error = %v", err)
}
missing := bytes.Replace(encoded, []byte(`,"max_sessions":1`), nil, 1)
if bytes.Equal(missing, encoded) {
t.Fatal("encoded training section did not contain max_sessions")
}
if _, err := decodeProductPolicy(missing); !errors.Is(err, ErrInvalidPolicy) {
t.Fatalf("decodeProductPolicy(missing max_sessions) error = %v, want ErrInvalidPolicy", err)
}
unknown := bytes.Replace(encoded, []byte(`"max_sessions":1`), []byte(`"max_sessions":1,"unknown":true`), 1)
if bytes.Equal(unknown, encoded) {
t.Fatal("encoded training section did not contain max_sessions")
}
if _, err := decodeProductPolicy(unknown); !errors.Is(err, ErrInvalidPolicy) {
t.Fatalf("decodeProductPolicy(unknown training field) error = %v, want ErrInvalidPolicy", err)
}
}
func TestAssessmentTrainingPolicyRejectsInvalidSessionLimits(t *testing.T) {
tests := []struct {
name string
change func(*AssessmentTrainingPolicy)
}{
{name: "zero sessions", change: func(policy *AssessmentTrainingPolicy) { policy.MaxSessions = 0 }},
{name: "too many sessions", change: func(policy *AssessmentTrainingPolicy) { policy.MaxSessions = 11 }},
{name: "idle timeout below minimum", change: func(policy *AssessmentTrainingPolicy) { policy.IdleTimeoutSeconds = 59 }},
{name: "idle timeout above duration", change: func(policy *AssessmentTrainingPolicy) { policy.IdleTimeoutSeconds = 241 }},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
policy := DemoProductPolicyV2()
test.change(policy.Assessment.Training)
if err := policy.Validate(); !errors.Is(err, ErrInvalidPolicy) {
t.Fatalf("ProductPolicy.Validate() error = %v, want ErrInvalidPolicy", err)
}
})
}
}
func TestTrainingPolicyDocumentUsesSnakeCaseSessionFields(t *testing.T) {
encoded, _, err := encodeProductPolicy(DemoProductPolicyV2())
if err != nil {
t.Fatalf("encodeProductPolicy() error = %v", err)
}
text := string(encoded)
for _, field := range []string{`"max_sessions":1`, `"idle_timeout_seconds":240`} {
if !strings.Contains(text, field) {
t.Errorf("encoded policy %q does not contain %s", text, field)
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,542 @@
package domain
import (
"bytes"
"errors"
"fmt"
"log/slog"
"strings"
"testing"
"time"
"github.com/google/uuid"
)
var testSupportCaseCreatedAt = time.Date(2026, time.October, 7, 10, 0, 0, 0, time.UTC)
func newTestSupportCase(t *testing.T, caseType SupportCaseType) SupportCase {
t.Helper()
policy := DemoSupportPolicy()
target, err := policy.ResponseTarget(caseType, 3, testSupportCaseCreatedAt)
if err != nil {
t.Fatalf("ResponseTarget() error = %v", err)
}
input := NewSupportCaseInput{
Number: "SC-2026-000123", OwnerID: uuid.New(), Type: caseType,
Description: "Please review this request.", ResponseTarget: target, CreatedAt: testSupportCaseCreatedAt,
}
switch caseType {
case SupportCaseTypeSupport:
// A support case has no required type-specific fields.
case SupportCaseTypeComplaint:
reason := SupportComplaintOrganizationConduct
input.ComplaintReason = &reason
input.Object = &SupportCaseReference{Type: SupportCaseObjectOrganization, ID: uuid.New()}
case SupportCaseTypeGradeAppeal:
input.Object = &SupportCaseReference{Type: SupportCaseObjectAssessmentAttempt, ID: uuid.New()}
case SupportCaseTypeAnticheatAppeal:
input.Object = &SupportCaseReference{Type: SupportCaseObjectAssessmentAttempt, ID: uuid.New()}
case SupportCaseTypeManualAssessment:
target := SupportCaseAssessmentTarget{Specialization: SpecializationBackend, Grade: GradeJunior}
input.AssessmentTarget = &target
}
supportCase, err := NewSupportCase(input)
if err != nil {
t.Fatalf("NewSupportCase(%s) error = %v", caseType, err)
}
return supportCase
}
func TestNewSupportCaseSetsOwnerAndTypeSpecificInitialHistory(t *testing.T) {
tests := []struct {
caseType SupportCaseType
status SupportCaseStatus
events int
}{
{caseType: SupportCaseTypeSupport, status: SupportCaseStatusSubmitted, events: 1},
{caseType: SupportCaseTypeComplaint, status: SupportCaseStatusSubmitted, events: 1},
{caseType: SupportCaseTypeGradeAppeal, status: SupportCaseStatusWaitingExpert, events: 2},
{caseType: SupportCaseTypeAnticheatAppeal, status: SupportCaseStatusWaitingExpert, events: 2},
{caseType: SupportCaseTypeManualAssessment, status: SupportCaseStatusWaitingExpert, events: 2},
}
for _, test := range tests {
t.Run(string(test.caseType), func(t *testing.T) {
supportCase := newTestSupportCase(t, test.caseType)
snapshot := supportCase.Snapshot()
if supportCase.IsZero() || supportCase.OwnerID() == uuid.Nil || supportCase.Type() != test.caseType ||
supportCase.Status() != test.status || snapshot.Number != "SC-2026-000123" ||
len(snapshot.History) != test.events || !snapshot.CreatedAt.Equal(snapshot.UpdatedAt) {
t.Fatalf("new case snapshot = %+v", snapshot)
}
created := snapshot.History[0]
if created.Sequence != 1 || created.Kind != SupportCaseEventCreated || created.Actor != SupportCaseActorUser ||
created.Status == nil || *created.Status != SupportCaseStatusSubmitted || created.Message != nil {
t.Fatalf("first history event = %+v, want author-created submitted event", created)
}
if test.events == 2 {
routed := snapshot.History[1]
if routed.Sequence != 2 || routed.Kind != SupportCaseEventStatusChanged || routed.Actor != SupportCaseActorSystem ||
routed.Status == nil || *routed.Status != SupportCaseStatusWaitingExpert || routed.Message != nil {
t.Fatalf("expert routing event = %+v", routed)
}
}
})
}
}
func TestRestoreSupportCaseSummaryValidatesAndClonesProjection(t *testing.T) {
for _, caseType := range []SupportCaseType{
SupportCaseTypeSupport, SupportCaseTypeComplaint, SupportCaseTypeGradeAppeal,
SupportCaseTypeAnticheatAppeal, SupportCaseTypeManualAssessment,
} {
t.Run(string(caseType), func(t *testing.T) {
original := newTestSupportCase(t, caseType).Summary()
restored, err := RestoreSupportCaseSummary(original)
if err != nil {
t.Fatalf("RestoreSupportCaseSummary() error = %v", err)
}
if restored.ID != original.ID || restored.Type != caseType || restored.CreatedAt != original.CreatedAt {
t.Fatalf("restored summary = %+v, want %+v", restored, original)
}
if original.Object != nil {
original.Object.ID = uuid.New()
if restored.Object.ID == original.Object.ID {
t.Fatal("restored object reference aliases the input")
}
}
})
}
}
func TestRestoreSupportCaseSummaryRejectsInconsistentStorageProjection(t *testing.T) {
valid := newTestSupportCase(t, SupportCaseTypeSupport).Summary()
tests := []struct {
name string
change func(*SupportCaseSummary)
}{
{name: "bad number year", change: func(summary *SupportCaseSummary) { summary.Number = "SC-2025-000123" }},
{name: "unknown status", change: func(summary *SupportCaseSummary) { summary.Status = "unknown" }},
{name: "unsupported target version", change: func(summary *SupportCaseSummary) { summary.ResponseTarget.CalendarVersion = 0 }},
{name: "unresolved decision", change: func(summary *SupportCaseSummary) {
outcome := SupportCaseDecisionAnswered
summary.DecisionOutcome = &outcome
}},
{name: "missing complaint object", change: func(summary *SupportCaseSummary) {
summary.Type = SupportCaseTypeComplaint
}},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
summary := cloneSupportCaseSummary(valid)
test.change(&summary)
if _, err := RestoreSupportCaseSummary(summary); !errors.Is(err, ErrInvalidSupportCase) {
t.Fatalf("RestoreSupportCaseSummary() error = %v, want ErrInvalidSupportCase", err)
}
})
}
}
func TestValidateSupportCaseRequestReportsFieldsBeforeObjectResolution(t *testing.T) {
tests := []struct {
name string
input NewSupportCaseInput
pointer string
}{
{
name: "unicode whitespace description",
input: NewSupportCaseInput{Type: SupportCaseTypeSupport, Description: "\u0085"},
pointer: "/description",
},
{
name: "invitation complaint reason with organization reference",
input: NewSupportCaseInput{
Type: SupportCaseTypeComplaint, Description: "Please review this offer.",
Object: &SupportCaseReference{Type: SupportCaseObjectOrganization, ID: uuid.New()},
ComplaintReason: supportCaseComplaintReasonPointer(SupportComplaintSalaryTermsViolation),
},
pointer: "/object/type",
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
err := ValidateSupportCaseRequest(test.input)
fieldError, ok := errors.AsType[*SupportCaseFieldError](err)
if !ok || fieldError.Pointer != test.pointer || !errors.Is(err, ErrInvalidSupportCase) {
t.Fatalf("ValidateSupportCaseRequest() error = %v, want invalid field %s", err, test.pointer)
}
})
}
}
func TestValidateSupportCaseRequestAllowsManualAssessmentWithoutAttemptOrRubric(t *testing.T) {
input := NewSupportCaseInput{
Type: SupportCaseTypeManualAssessment, Description: "Please assess my Go skills.",
AssessmentTarget: &SupportCaseAssessmentTarget{Specialization: SpecializationBackend, Grade: GradeJunior},
}
if err := ValidateSupportCaseRequest(input); err != nil {
t.Fatalf("ValidateSupportCaseRequest(manual assessment) error = %v", err)
}
}
func TestManualAssessmentNeedsNoAttemptOrConsentField(t *testing.T) {
supportCase := newTestSupportCase(t, SupportCaseTypeManualAssessment)
if supportCase.Object() != nil || supportCase.RubricVersion() != nil ||
supportCase.Status() != SupportCaseStatusWaitingExpert || len(supportCase.History()) != 2 {
t.Fatalf("manual assessment should be accepted without a prior attempt, rubric, or consent: %+v", supportCase.Snapshot())
}
}
func TestManualAssessmentRubricPinsAreValidatedAndCloned(t *testing.T) {
snapshot := newTestSupportCase(t, SupportCaseTypeManualAssessment).Snapshot()
version := int32(7)
openingID := uuid.New()
policyID := PolicyVersionID(uuid.New())
expectedOpeningID := openingID
expectedPolicyID := policyID
snapshot.RubricVersion = &version
snapshot.RubricOpeningID = &openingID
snapshot.RubricPolicyID = &policyID
manualCase, err := RestoreSupportCase(snapshot)
if err != nil {
t.Fatalf("RestoreSupportCase(valid rubric pin) error = %v", err)
}
version = 8
openingID = uuid.New()
policyID = PolicyVersionID(uuid.New())
stored := manualCase.Snapshot()
if stored.RubricVersion == nil || *stored.RubricVersion != 7 || stored.RubricOpeningID == nil ||
*stored.RubricOpeningID == openingID || stored.RubricPolicyID == nil || *stored.RubricPolicyID == policyID {
t.Fatalf("stored rubric pin aliases caller input: %+v", stored)
}
*stored.RubricVersion = 9
*stored.RubricOpeningID = uuid.New()
*stored.RubricPolicyID = PolicyVersionID(uuid.New())
again := manualCase.Snapshot()
if again.RubricVersion == nil || *again.RubricVersion != 7 || again.RubricOpeningID == nil ||
*again.RubricOpeningID != expectedOpeningID || again.RubricPolicyID == nil ||
*again.RubricPolicyID != expectedPolicyID {
t.Fatalf("snapshot mutation changed stored rubric pin: %+v", again)
}
}
func TestManualAssessmentRubricPinsMustBeCompleteAndTypeSpecific(t *testing.T) {
base := newTestSupportCase(t, SupportCaseTypeManualAssessment).Snapshot()
openingID := uuid.New()
policyID := PolicyVersionID(uuid.New())
version := int32(2)
tests := []struct {
name string
change func(*SupportCaseSnapshot)
}{
{name: "version only", change: func(snapshot *SupportCaseSnapshot) { snapshot.RubricVersion = &version }},
{name: "opening only", change: func(snapshot *SupportCaseSnapshot) { snapshot.RubricOpeningID = &openingID }},
{name: "policy only", change: func(snapshot *SupportCaseSnapshot) { snapshot.RubricPolicyID = &policyID }},
{name: "pins on non-manual case", change: func(snapshot *SupportCaseSnapshot) {
snapshot.Type = SupportCaseTypeSupport
snapshot.AssessmentTarget = nil
snapshot.RubricVersion = &version
snapshot.RubricOpeningID = &openingID
snapshot.RubricPolicyID = &policyID
}},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
snapshot := cloneSupportCaseSnapshot(base)
test.change(&snapshot)
if _, err := RestoreSupportCase(snapshot); !errors.Is(err, ErrInvalidSupportCase) {
t.Fatalf("RestoreSupportCase() error = %v, want ErrInvalidSupportCase", err)
}
})
}
}
func TestNewSupportCaseValidatesDescriptionAndTypeSpecificFields(t *testing.T) {
valid := newTestSupportCase(t, SupportCaseTypeSupport).Snapshot()
tests := []struct {
name string
change func(*SupportCaseSnapshot)
}{
{name: "blank description", change: func(snapshot *SupportCaseSnapshot) { snapshot.Description = "\u0085\uFEFF" }},
{name: "unknown type", change: func(snapshot *SupportCaseSnapshot) { snapshot.Type = "unknown" }},
{name: "foreign-shaped reference", change: func(snapshot *SupportCaseSnapshot) {
snapshot.Object = &SupportCaseReference{Type: "unknown", ID: uuid.New()}
}},
{name: "nil object identifier", change: func(snapshot *SupportCaseSnapshot) {
snapshot.Object = &SupportCaseReference{Type: SupportCaseObjectOrganization}
}},
{name: "bad number year", change: func(snapshot *SupportCaseSnapshot) { snapshot.Number = "SC-2025-000123" }},
{name: "zero response target version", change: func(snapshot *SupportCaseSnapshot) { snapshot.ResponseTarget.PolicyVersion = 0 }},
{name: "history status mismatch", change: func(snapshot *SupportCaseSnapshot) {
snapshot.History[0].Status = supportCaseStatusPointer(SupportCaseStatusClosed)
}},
{name: "created event repeated", change: func(snapshot *SupportCaseSnapshot) {
created := cloneSupportCaseEventSnapshot(snapshot.History[0])
created.Sequence = 2
created.OccurredAt = snapshot.CreatedAt.Add(time.Minute)
snapshot.History = append(snapshot.History, created)
snapshot.UpdatedAt = created.OccurredAt
}},
{name: "unanswered target has calendar version", change: func(snapshot *SupportCaseSnapshot) {
snapshot.ResponseTarget.CalendarVersion = 0
}},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
snapshot := cloneSupportCaseSnapshot(valid)
test.change(&snapshot)
if _, err := RestoreSupportCase(snapshot); !errors.Is(err, ErrInvalidSupportCase) {
t.Fatalf("RestoreSupportCase() error = %v, want ErrInvalidSupportCase", err)
}
})
}
}
func TestComplaintReasonsThatRequireInvitationRejectOtherObjectTypes(t *testing.T) {
for _, reason := range []SupportCaseComplaintReason{SupportComplaintOfferContent, SupportComplaintSalaryTermsViolation} {
t.Run(string(reason), func(t *testing.T) {
supportCase := newTestSupportCase(t, SupportCaseTypeComplaint)
snapshot := supportCase.Snapshot()
snapshot.ComplaintReason = &reason
if _, err := RestoreSupportCase(snapshot); !errors.Is(err, ErrInvalidSupportCase) {
t.Fatalf("RestoreSupportCase() error = %v, want ErrInvalidSupportCase", err)
}
})
}
}
func TestSupportCaseSnapshotsClonePointersAndHistory(t *testing.T) {
objectID := uuid.New()
assessmentTarget := SupportCaseAssessmentTarget{Specialization: SpecializationBackend, Grade: GradeJunior}
policy := DemoSupportPolicy()
responseTarget, err := policy.ResponseTarget(SupportCaseTypeSupport, 3, testSupportCaseCreatedAt)
if err != nil {
t.Fatal(err)
}
input := NewSupportCaseInput{
Number: "SC-2026-000124", OwnerID: uuid.New(), Type: SupportCaseTypeSupport,
Description: "A private description", Object: &SupportCaseReference{Type: SupportCaseObjectOrganization, ID: objectID},
AssessmentTarget: &assessmentTarget, ResponseTarget: responseTarget, CreatedAt: testSupportCaseCreatedAt,
}
supportCase, err := NewSupportCase(input)
if err != nil {
t.Fatalf("NewSupportCase() error = %v", err)
}
input.Object.ID = uuid.New()
input.AssessmentTarget.Grade = GradeSenior
snapshot := supportCase.Snapshot()
snapshot.Object.ID = uuid.New()
snapshot.AssessmentTarget.Grade = GradeSenior
*snapshot.History[0].Status = SupportCaseStatusClosed
if supportCase.Object().ID != objectID || supportCase.AssessmentTarget().Grade != GradeJunior ||
supportCase.History()[0].Snapshot().Status == nil || *supportCase.History()[0].Snapshot().Status != SupportCaseStatusSubmitted {
t.Fatalf("caller mutated the stored support case through an input or snapshot alias: %+v", supportCase.Snapshot())
}
}
func TestSupportCaseFormattingAndLoggingRedactUserAndObjectContent(t *testing.T) {
supportCase := newTestSupportCase(t, SupportCaseTypeSupport)
snapshot := supportCase.Snapshot()
snapshot.Description = "private-description-marker"
snapshot.Object = &SupportCaseReference{Type: SupportCaseObjectOrganization, ID: uuid.New()}
message := "private-public-message-marker"
snapshot.History = append(snapshot.History, SupportCaseEventSnapshot{
Sequence: 2, Kind: SupportCaseEventReply, Actor: SupportCaseActorSupport,
OccurredAt: testSupportCaseCreatedAt.Add(time.Minute), Message: &message,
})
answeredAt := testSupportCaseCreatedAt.Add(time.Minute)
snapshot.ResponseTarget.AnsweredAt = &answeredAt
snapshot.Status = SupportCaseStatusSubmitted
snapshot.UpdatedAt = testSupportCaseCreatedAt.Add(time.Minute)
if _, err := RestoreSupportCase(snapshot); err != nil {
t.Fatalf("RestoreSupportCase() error = %v", err)
}
values := []any{supportCase, snapshot, snapshot.History[1], *snapshot.Object}
for _, value := range values {
formatted := fmt.Sprintf("%+v %#v", value, value)
if strings.Contains(formatted, "private-description-marker") || strings.Contains(formatted, "private-public-message-marker") {
t.Fatalf("formatted %T leaked private content: %s", value, formatted)
}
}
var buffer bytes.Buffer
logger := slog.New(slog.NewJSONHandler(&buffer, nil))
logger.Info("case", slog.Any("case", snapshot), slog.Any("event", snapshot.History[1]), slog.Any("object", *snapshot.Object))
if strings.Contains(buffer.String(), "private-description-marker") || strings.Contains(buffer.String(), "private-public-message-marker") ||
strings.Contains(buffer.String(), snapshot.Object.ID.String()) {
t.Fatalf("structured log leaked private content or object ID: %s", buffer.String())
}
}
func TestSupportCaseRequiresMatchingFirstResponseAndTerminalClosureEvent(t *testing.T) {
supportCase := newTestSupportCase(t, SupportCaseTypeSupport)
snapshot := supportCase.Snapshot()
firstReplyAt := testSupportCaseCreatedAt.Add(time.Minute)
replyMessage := "We are reviewing this request."
snapshot.History = append(snapshot.History, SupportCaseEventSnapshot{
Sequence: 2, Kind: SupportCaseEventReply, Actor: SupportCaseActorSupport,
OccurredAt: firstReplyAt, Message: &replyMessage,
})
snapshot.ResponseTarget.AnsweredAt = &firstReplyAt
snapshot.UpdatedAt = firstReplyAt
if _, err := RestoreSupportCase(snapshot); err != nil {
t.Fatalf("RestoreSupportCase(first reply) error = %v", err)
}
wrongAnswerAt := firstReplyAt.Add(time.Second)
snapshot.ResponseTarget.AnsweredAt = &wrongAnswerAt
if _, err := RestoreSupportCase(snapshot); !errors.Is(err, ErrInvalidSupportCase) {
t.Fatalf("RestoreSupportCase(wrong answered time) error = %v, want ErrInvalidSupportCase", err)
}
futureAnswerAt := firstReplyAt.Add(time.Hour)
snapshot.ResponseTarget.AnsweredAt = &futureAnswerAt
snapshot.History[1].OccurredAt = futureAnswerAt
if err := validateSupportCaseResponseTargetAnswer("test", snapshot); !errors.Is(err, ErrInvalidSupportCase) {
t.Fatalf("future answer time error = %v, want ErrInvalidSupportCase", err)
}
closed := supportCase.Snapshot()
closed.Status = SupportCaseStatusClosed
closedAt := firstReplyAt.Add(time.Minute)
closed.UpdatedAt = closedAt
closed.History = append(closed.History, SupportCaseEventSnapshot{
Sequence: 2, Kind: SupportCaseEventStatusChanged, Actor: SupportCaseActorSupport,
OccurredAt: closedAt, Status: supportCaseStatusPointer(SupportCaseStatusClosed),
})
closed.ResponseTarget.AnsweredAt = &closedAt
if _, err := RestoreSupportCase(closed); !errors.Is(err, ErrInvalidSupportCase) {
t.Fatalf("RestoreSupportCase(closed without reason) error = %v, want ErrInvalidSupportCase", err)
}
closureReason := "This case was closed as a duplicate."
closed.History[1].Message = &closureReason
if _, err := RestoreSupportCase(closed); err != nil {
t.Fatalf("RestoreSupportCase(closed with reason) error = %v", err)
}
}
func TestSupportCaseReservesOneHistoryEventForTerminalState(t *testing.T) {
supportCase := newTestSupportCase(t, SupportCaseTypeSupport)
snapshot := supportCase.Snapshot()
firstReplyAt := testSupportCaseCreatedAt.Add(time.Minute)
message := "A public reply."
snapshot.ResponseTarget.AnsweredAt = &firstReplyAt
snapshot.History = append(snapshot.History, SupportCaseEventSnapshot{
Sequence: 2, Kind: SupportCaseEventReply, Actor: SupportCaseActorSupport,
OccurredAt: firstReplyAt, Message: &message,
})
for sequence := int32(3); sequence <= 199; sequence++ {
occurredAt := firstReplyAt.Add(time.Duration(sequence-2) * time.Minute)
snapshot.History = append(snapshot.History, SupportCaseEventSnapshot{
Sequence: sequence, Kind: SupportCaseEventReply, Actor: SupportCaseActorSupport,
OccurredAt: occurredAt, Message: &message,
})
}
snapshot.UpdatedAt = snapshot.History[len(snapshot.History)-1].OccurredAt
if _, err := RestoreSupportCase(snapshot); err != nil {
t.Fatalf("RestoreSupportCase(199 nonterminal events) error = %v", err)
}
snapshot.History = append(snapshot.History, SupportCaseEventSnapshot{
Sequence: 200, Kind: SupportCaseEventReply, Actor: SupportCaseActorSupport,
OccurredAt: snapshot.UpdatedAt.Add(time.Minute), Message: &message,
})
snapshot.UpdatedAt = snapshot.History[len(snapshot.History)-1].OccurredAt
if _, err := RestoreSupportCase(snapshot); !errors.Is(err, ErrInvalidSupportCase) {
t.Fatalf("RestoreSupportCase(200 nonterminal events) error = %v, want ErrInvalidSupportCase", err)
}
}
func TestSupportCaseCanonicalizesPersistedTimesToUTCMicroseconds(t *testing.T) {
createdAt := time.Date(2026, time.October, 7, 13, 0, 0, 1234567, time.FixedZone("local", 3*60*60))
policy := DemoSupportPolicy()
target, err := policy.ResponseTarget(SupportCaseTypeSupport, 3, createdAt)
if err != nil {
t.Fatalf("ResponseTarget() error = %v", err)
}
supportCase, err := NewSupportCase(NewSupportCaseInput{
Number: "SC-2026-000125", OwnerID: uuid.New(), Type: SupportCaseTypeSupport,
Description: "Canonical timestamps", ResponseTarget: target, CreatedAt: createdAt,
})
if err != nil {
t.Fatalf("NewSupportCase() error = %v", err)
}
wantCreatedAt := time.Date(2026, time.October, 7, 10, 0, 0, 1234000, time.UTC)
snapshot := supportCase.Snapshot()
if snapshot.CreatedAt != wantCreatedAt || snapshot.UpdatedAt != wantCreatedAt ||
snapshot.History[0].OccurredAt != wantCreatedAt || snapshot.ResponseTarget.DueAt.Nanosecond()%1000 != 0 ||
snapshot.ResponseTarget.DueAt.Location() != time.UTC {
t.Fatalf("persisted times are not canonical UTC microseconds: %+v", snapshot)
}
decision, err := NewSupportCaseDecision(SupportCaseDecisionSnapshot{
Outcome: SupportCaseDecisionAnswered, Reason: "Resolved", DecidedAt: createdAt,
})
if err != nil {
t.Fatalf("NewSupportCaseDecision() error = %v", err)
}
if decision.DecidedAt() != wantCreatedAt {
t.Fatalf("decision time = %s, want canonical %s", decision.DecidedAt(), wantCreatedAt)
}
}
func TestSupportCaseCreateOutcomePreservesOriginalCreationSnapshot(t *testing.T) {
supportCase := newTestSupportCase(t, SupportCaseTypeSupport)
outcome, err := NewSupportCaseCreatedOutcome(supportCase)
if err != nil {
t.Fatalf("NewSupportCaseCreatedOutcome() error = %v", err)
}
snapshot := outcome.Snapshot()
snapshot.Case.Description = "mutated-replay"
replayed, ok := outcome.Case()
if !ok || replayed.Description() != "Please review this request." || outcome.Kind() != SupportCaseCreateOutcomeCreated {
t.Fatalf("outcome did not preserve the original create snapshot: %+v", outcome.Snapshot())
}
if late, ok := outcome.CreationTargetWasLate(); !ok || late {
t.Fatalf("creation target lateness = %t, %t; want the original not-late response", late, ok)
}
progressedSnapshot := supportCase.Snapshot()
progressedSnapshot.Status = SupportCaseStatusInReview
progressedAt := testSupportCaseCreatedAt.Add(time.Minute)
progressedSnapshot.UpdatedAt = progressedAt
progressedSnapshot.History = append(progressedSnapshot.History, SupportCaseEventSnapshot{
Sequence: 2, Kind: SupportCaseEventStatusChanged, Actor: SupportCaseActorSupport,
OccurredAt: progressedAt, Status: supportCaseStatusPointer(SupportCaseStatusInReview),
})
progressed, err := RestoreSupportCase(progressedSnapshot)
if err != nil {
t.Fatalf("RestoreSupportCase(progressed) error = %v", err)
}
if _, err := NewSupportCaseCreatedOutcome(progressed); !errors.Is(err, ErrInvalidSupportCase) {
t.Fatalf("NewSupportCaseCreatedOutcome(progressed) error = %v, want ErrInvalidSupportCase", err)
}
for _, failure := range []SupportCaseCreateOutcome{NewSupportCaseNotFoundOutcome(), NewSupportCaseStateConflictOutcome()} {
if failure.IsZero() || failure.Snapshot().Case != nil {
t.Fatalf("failure outcome carries a case or is zero: %+v", failure.Snapshot())
}
}
if _, err := RestoreSupportCaseCreateOutcome(SupportCaseCreateOutcomeSnapshot{Kind: SupportCaseCreateOutcomeCreated}); !errors.Is(err, ErrInvalidSupportCase) {
t.Fatalf("created outcome without a snapshot error = %v, want ErrInvalidSupportCase", err)
}
if _, err := RestoreSupportCaseCreateOutcome(SupportCaseCreateOutcomeSnapshot{
Kind: SupportCaseCreateOutcomeNotFound, Case: func() *SupportCaseSnapshot { value := supportCase.Snapshot(); return &value }(),
}); !errors.Is(err, ErrInvalidSupportCase) {
t.Fatalf("failure outcome with a case error = %v, want ErrInvalidSupportCase", err)
}
}
func TestSupportCaseNumberRequiresExpectedFormatAndUTCYear(t *testing.T) {
if _, err := ParseSupportCaseNumber("SC-2026-123"); !errors.Is(err, ErrInvalidSupportCase) {
t.Fatalf("short number error = %v, want ErrInvalidSupportCase", err)
}
parsed, err := ParseSupportCaseNumber("SC-2026-000123")
if err != nil || !parsed.validFor(testSupportCaseCreatedAt) {
t.Fatalf("ParseSupportCaseNumber() = %q, %v; want a valid 2026 number", parsed, err)
}
if parsed.validFor(time.Date(2027, time.January, 1, 0, 0, 0, 0, time.UTC)) {
t.Fatal("number year must match case creation year")
}
}
func supportCaseComplaintReasonPointer(reason SupportCaseComplaintReason) *SupportCaseComplaintReason {
return &reason
}
+213
View File
@@ -0,0 +1,213 @@
package domain
import (
"errors"
"fmt"
"time"
)
var ErrInvalidSupportPolicy = errors.New("invalid support policy")
const (
// MaxSupportRequestWindow bounds the rolling-window quota that an
// implementation must support and retain request events for.
MaxSupportRequestWindow = 24 * time.Hour
maxSupportResponseBusinessDays = BusinessDays(60)
maxSupportRequestsPerWindow = int32(1000)
supportBusinessCalendarV1 = int32(1)
supportAppealsPerTargetV1 = int32(1)
)
// SupportPolicyInput describes the operational targets and request budget for
// support cases. Targets are operational goals, never legal deadlines.
type SupportPolicyInput struct {
SupportResponseDays BusinessDays
ComplaintResponseDays BusinessDays
ManualAssessmentResponseDays BusinessDays
AppealResponseDays BusinessDays
MaxRequestsPerWindow int32
RequestWindow time.Duration
MaxAppealsPerTarget int32
PauseWhenWaitingForUser bool
BusinessCalendarVersion int32
}
// SupportPolicy is an immutable set of support-case operating rules. Its
// calendar is versioned weekdays-only UTC and does not include public
// holidays. Waiting for the user does not pause the target. Manual assessment
// does not depend on C3 consent.
type SupportPolicy struct {
supportResponseDays BusinessDays
complaintResponseDays BusinessDays
manualAssessmentResponseDays BusinessDays
appealResponseDays BusinessDays
maxRequestsPerWindow int32
requestWindow time.Duration
maxAppealsPerTarget int32
pauseWhenWaitingForUser bool
businessCalendarVersion int32
}
// NewSupportPolicy validates and freezes explicit support settings. The
// caller still has to pin the containing product policy version when it
// creates a response target.
func NewSupportPolicy(input SupportPolicyInput) (SupportPolicy, error) {
const location = "domain.NewSupportPolicy"
for _, value := range []struct {
name string
days BusinessDays
}{
{name: "support response days", days: input.SupportResponseDays},
{name: "complaint response days", days: input.ComplaintResponseDays},
{name: "manual assessment response days", days: input.ManualAssessmentResponseDays},
{name: "appeal response days", days: input.AppealResponseDays},
} {
if value.days < 1 || value.days > maxSupportResponseBusinessDays {
return SupportPolicy{}, fmt.Errorf("%s - %s must be 1 to %d business days: %w",
location, value.name, maxSupportResponseBusinessDays, ErrInvalidSupportPolicy)
}
}
if input.MaxRequestsPerWindow < 1 || input.MaxRequestsPerWindow > maxSupportRequestsPerWindow {
return SupportPolicy{}, fmt.Errorf("%s - request limit must be 1 to %d: %w",
location, maxSupportRequestsPerWindow, ErrInvalidSupportPolicy)
}
if input.RequestWindow <= 0 || input.RequestWindow > MaxSupportRequestWindow || input.RequestWindow%time.Second != 0 {
return SupportPolicy{}, fmt.Errorf("%s - request window must be whole seconds, positive, and no longer than 24 hours: %w",
location, ErrInvalidSupportPolicy)
}
if input.MaxAppealsPerTarget != supportAppealsPerTargetV1 {
return SupportPolicy{}, fmt.Errorf("%s - MVP allows exactly one appeal per target and type: %w",
location, ErrInvalidSupportPolicy)
}
if input.PauseWhenWaitingForUser {
return SupportPolicy{}, fmt.Errorf("%s - waiting for the user cannot pause an MVP response target: %w",
location, ErrInvalidSupportPolicy)
}
if input.BusinessCalendarVersion != supportBusinessCalendarV1 {
return SupportPolicy{}, fmt.Errorf("%s - unsupported business calendar version: %w",
location, ErrInvalidSupportPolicy)
}
return SupportPolicy{
supportResponseDays: input.SupportResponseDays,
complaintResponseDays: input.ComplaintResponseDays,
manualAssessmentResponseDays: input.ManualAssessmentResponseDays,
appealResponseDays: input.AppealResponseDays,
maxRequestsPerWindow: input.MaxRequestsPerWindow,
requestWindow: input.RequestWindow,
maxAppealsPerTarget: input.MaxAppealsPerTarget,
pauseWhenWaitingForUser: input.PauseWhenWaitingForUser,
businessCalendarVersion: input.BusinessCalendarVersion,
}, nil
}
// DemoSupportPolicy returns explicit demo defaults. These values are not a
// calibrated service commitment and do not describe a legal deadline.
func DemoSupportPolicy() SupportPolicy {
return SupportPolicy{
supportResponseDays: 5,
complaintResponseDays: 5,
manualAssessmentResponseDays: 5,
appealResponseDays: 10,
maxRequestsPerWindow: 10,
requestWindow: time.Hour,
maxAppealsPerTarget: supportAppealsPerTargetV1,
businessCalendarVersion: supportBusinessCalendarV1,
}
}
func (policy SupportPolicy) IsZero() bool {
return policy.supportResponseDays == 0 || policy.complaintResponseDays == 0 ||
policy.manualAssessmentResponseDays == 0 || policy.appealResponseDays == 0 ||
policy.maxRequestsPerWindow == 0 || policy.requestWindow == 0 ||
policy.maxAppealsPerTarget == 0 || policy.businessCalendarVersion == 0
}
func (policy SupportPolicy) SupportResponseDays() BusinessDays {
return policy.supportResponseDays
}
func (policy SupportPolicy) ComplaintResponseDays() BusinessDays {
return policy.complaintResponseDays
}
func (policy SupportPolicy) ManualAssessmentResponseDays() BusinessDays {
return policy.manualAssessmentResponseDays
}
func (policy SupportPolicy) AppealResponseDays() BusinessDays {
return policy.appealResponseDays
}
func (policy SupportPolicy) MaxRequestsPerWindow() int32 { return policy.maxRequestsPerWindow }
func (policy SupportPolicy) RequestWindow() time.Duration { return policy.requestWindow }
// MaxAppealsPerTarget fixes the MVP rule: an appeal type may be opened once
// for one target, regardless of the status of the first case.
func (policy SupportPolicy) MaxAppealsPerTarget() int32 { return policy.maxAppealsPerTarget }
// PausesWhenWaitingForUser reports the fixed MVP rule that response targets
// continue to run while a case waits for the author.
func (policy SupportPolicy) PausesWhenWaitingForUser() bool { return policy.pauseWhenWaitingForUser }
func (policy SupportPolicy) BusinessCalendarVersion() int32 {
return policy.businessCalendarVersion
}
// ResponseTarget fixes the business-day target and its policy version at case
// creation. Its UTC calendar excludes Saturdays and Sundays only.
func (policy SupportPolicy) ResponseTarget(
caseType SupportCaseType,
policyVersion int32,
createdAt time.Time,
) (SupportResponseTarget, error) {
const location = "SupportPolicy.ResponseTarget"
if policy.IsZero() {
return SupportResponseTarget{}, fmt.Errorf("%s - policy must be set: %w", location, ErrInvalidSupportPolicy)
}
if policyVersion < 1 || createdAt.IsZero() {
return SupportResponseTarget{}, fmt.Errorf("%s - version and creation time must be set: %w", location, ErrInvalidSupportPolicy)
}
days, err := policy.responseDays(caseType)
if err != nil {
return SupportResponseTarget{}, fmt.Errorf("%s - resolve response target: %w", location, err)
}
dueAt := addWeekdaysUTC(createdAt, days)
target, err := NewSupportResponseTarget(SupportResponseTargetSnapshot{
BusinessDays: days,
DueAt: dueAt,
PolicyVersion: policyVersion,
CalendarVersion: policy.BusinessCalendarVersion(),
})
if err != nil {
return SupportResponseTarget{}, fmt.Errorf("%s - build response target: %w", location, err)
}
return target, nil
}
func (policy SupportPolicy) responseDays(caseType SupportCaseType) (BusinessDays, error) {
switch caseType {
case SupportCaseTypeSupport:
return policy.supportResponseDays, nil
case SupportCaseTypeComplaint:
return policy.complaintResponseDays, nil
case SupportCaseTypeManualAssessment:
return policy.manualAssessmentResponseDays, nil
case SupportCaseTypeGradeAppeal, SupportCaseTypeAnticheatAppeal:
return policy.appealResponseDays, nil
default:
return 0, fmt.Errorf("unknown case type: %w", ErrInvalidSupportPolicy)
}
}
func addWeekdaysUTC(start time.Time, days BusinessDays) time.Time {
dueAt := start.UTC()
remaining := int(days)
for remaining > 0 {
dueAt = dueAt.AddDate(0, 0, 1)
if dueAt.Weekday() != time.Saturday && dueAt.Weekday() != time.Sunday {
remaining--
}
}
return dueAt
}
@@ -0,0 +1,188 @@
package domain
import (
"bytes"
"encoding/json"
"errors"
"reflect"
"strings"
"testing"
"time"
)
func TestDemoSupportPolicyUsesExplicitDemoTargetsAndRequestLimit(t *testing.T) {
policy := DemoSupportPolicy()
if policy.SupportResponseDays() != 5 || policy.ComplaintResponseDays() != 5 ||
policy.ManualAssessmentResponseDays() != 5 || policy.AppealResponseDays() != 10 ||
policy.MaxRequestsPerWindow() != 10 || policy.RequestWindow() != time.Hour ||
policy.MaxAppealsPerTarget() != 1 || policy.PausesWhenWaitingForUser() || policy.BusinessCalendarVersion() != 1 {
t.Fatalf("DemoSupportPolicy() = %+v, want the documented demo defaults", policy)
}
}
func TestNewSupportPolicyRejectsOutOfRangeInputs(t *testing.T) {
valid := SupportPolicyInput{
SupportResponseDays: 5, ComplaintResponseDays: 5, ManualAssessmentResponseDays: 5,
AppealResponseDays: 10, MaxRequestsPerWindow: 10, RequestWindow: time.Hour,
MaxAppealsPerTarget: 1, BusinessCalendarVersion: 1,
}
tests := []struct {
name string
change func(*SupportPolicyInput)
}{
{name: "zero target", change: func(input *SupportPolicyInput) { input.SupportResponseDays = 0 }},
{name: "target above bound", change: func(input *SupportPolicyInput) { input.AppealResponseDays = 61 }},
{name: "zero request limit", change: func(input *SupportPolicyInput) { input.MaxRequestsPerWindow = 0 }},
{name: "request limit above bound", change: func(input *SupportPolicyInput) { input.MaxRequestsPerWindow = 1001 }},
{name: "zero window", change: func(input *SupportPolicyInput) { input.RequestWindow = 0 }},
{name: "window above bound", change: func(input *SupportPolicyInput) { input.RequestWindow = 24*time.Hour + time.Nanosecond }},
{name: "fractional-second window", change: func(input *SupportPolicyInput) { input.RequestWindow = time.Second + time.Nanosecond }},
{name: "appeals per target above bound", change: func(input *SupportPolicyInput) { input.MaxAppealsPerTarget = 2 }},
{name: "paused while waiting", change: func(input *SupportPolicyInput) { input.PauseWhenWaitingForUser = true }},
{name: "unsupported calendar", change: func(input *SupportPolicyInput) { input.BusinessCalendarVersion = 2 }},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
input := valid
test.change(&input)
if _, err := NewSupportPolicy(input); !errors.Is(err, ErrInvalidSupportPolicy) {
t.Fatalf("NewSupportPolicy() error = %v, want ErrInvalidSupportPolicy", err)
}
})
}
}
func TestSupportPolicyDocumentRoundTripAndLegacyOmission(t *testing.T) {
reader := documentReader{}
if decoded := decodeOptionalSupportPolicy(&reader, nil); decoded != nil || reader.missing != "" {
t.Fatalf("omitted support section decoded as %v with missing field %q, want no policy and no error", decoded, reader.missing)
}
policy := DemoSupportPolicy()
encodedDocument, err := encodeSupportPolicy(policy)
if err != nil {
t.Fatalf("encodeSupportPolicy() error = %v", err)
}
encoded, err := json.Marshal(encodedDocument)
if err != nil {
t.Fatalf("Marshal(support policy) error = %v", err)
}
decoder := json.NewDecoder(bytes.NewReader(encoded))
decoder.DisallowUnknownFields()
var parsedDocument supportPolicyDocument
if err := decoder.Decode(&parsedDocument); err != nil {
t.Fatalf("Decode(support policy document) error = %v", err)
}
reader = documentReader{}
decoded := decodeOptionalSupportPolicy(&reader, &parsedDocument)
if reader.missing != "" || decoded == nil || !reflect.DeepEqual(*decoded, policy) {
t.Fatalf("decoded policy = %+v, missing = %q, want %+v", decoded, reader.missing, policy)
}
if err := decoded.Validate(); err != nil {
t.Fatalf("decoded.Validate() error = %v", err)
}
if !strings.Contains(string(encoded), `"pause_when_waiting_for_user":false`) ||
!strings.Contains(string(encoded), `"business_calendar_version":1`) {
t.Fatalf("document omitted explicit false or calendar version: %s", encoded)
}
}
func TestSupportPolicyDocumentRequiresEveryFieldAndRejectsUnknownFields(t *testing.T) {
encodedDocument, err := encodeSupportPolicy(DemoSupportPolicy())
if err != nil {
t.Fatalf("encodeSupportPolicy() error = %v", err)
}
encoded, err := json.Marshal(encodedDocument)
if err != nil {
t.Fatalf("Marshal(support policy) error = %v", err)
}
var parsedDocument supportPolicyDocument
decoder := json.NewDecoder(bytes.NewReader(append(encoded[:len(encoded)-1], []byte(`,"unexpected":true}`)...)))
decoder.DisallowUnknownFields()
if err := decoder.Decode(&parsedDocument); err == nil {
t.Fatal("support policy document accepted an unknown field")
}
var complete supportPolicyDocument
if err := json.Unmarshal(encoded, &complete); err != nil {
t.Fatalf("Unmarshal(support policy) error = %v", err)
}
complete.RequestWindowSeconds = nil
reader := documentReader{}
decoded := decodeSupportPolicy(&reader, &complete)
if reader.missing != "support.request_window_seconds" || !decoded.IsZero() {
t.Fatalf("missing field = %q and decoded = %+v, want exact missing-field path and zero policy", reader.missing, decoded)
}
}
func TestSupportPolicyValidationDoesNotFillOmittedValues(t *testing.T) {
if err := (SupportPolicy{}).Validate(); !errors.Is(err, ErrInvalidSupportPolicy) {
t.Fatalf("zero SupportPolicy.Validate() error = %v, want ErrInvalidSupportPolicy", err)
}
policy := DemoProductPolicyV1()
if policy.Support != nil {
t.Fatal("legacy DemoProductPolicyV1 unexpectedly contains support defaults")
}
if err := policy.Validate(); err != nil {
t.Fatalf("legacy policy without optional support section must remain valid: %v", err)
}
v2 := DemoProductPolicyV2()
if v2.Support == nil || v2.Support.SupportResponseDays() != 5 || v2.Support.AppealResponseDays() != 10 {
t.Fatalf("DemoProductPolicyV2 support section = %+v, want explicit support demo values", v2.Support)
}
v2.Support = &SupportPolicy{}
if err := v2.Validate(); !errors.Is(err, ErrInvalidPolicy) || !errors.Is(err, ErrInvalidSupportPolicy) {
t.Fatalf("ProductPolicy.Validate() error = %v, want both policy and support policy errors", err)
}
}
func TestSupportPolicyResponseTargetUsesVersionedWeekdaysInUTC(t *testing.T) {
policy := DemoSupportPolicy()
createdAt := time.Date(2026, time.October, 9, 15, 30, 0, 0, time.FixedZone("local", 3*60*60)) // Friday in UTC.
tests := []struct {
caseType SupportCaseType
wantDays BusinessDays
}{
{caseType: SupportCaseTypeSupport, wantDays: 5},
{caseType: SupportCaseTypeComplaint, wantDays: 5},
{caseType: SupportCaseTypeManualAssessment, wantDays: 5},
{caseType: SupportCaseTypeGradeAppeal, wantDays: 10},
{caseType: SupportCaseTypeAnticheatAppeal, wantDays: 10},
}
for _, test := range tests {
t.Run(string(test.caseType), func(t *testing.T) {
target, err := policy.ResponseTarget(test.caseType, 7, createdAt)
if err != nil {
t.Fatalf("ResponseTarget() error = %v", err)
}
wantDueAt := time.Date(2026, time.October, 16, 12, 30, 0, 0, time.UTC)
if test.wantDays == 10 {
wantDueAt = time.Date(2026, time.October, 23, 12, 30, 0, 0, time.UTC)
}
if target.BusinessDays() != test.wantDays || target.DueAt() != wantDueAt || target.PolicyVersion() != 7 ||
target.BusinessCalendarVersion() != 1 || target.Snapshot().CalendarVersion != 1 ||
target.Kind() != SupportResponseTargetOperationalGoal {
t.Fatalf("target = %+v, want %d business days through %s at policy 7", target, test.wantDays, wantDueAt)
}
})
}
if DemoSupportPolicy().PausesWhenWaitingForUser() {
t.Fatal("waiting for the user must not pause an MVP response target")
}
}
func TestSupportPolicyRejectsUnsetPolicyUnknownCaseAndInvalidVersion(t *testing.T) {
createdAt := time.Date(2026, time.October, 7, 10, 0, 0, 0, time.UTC)
if _, err := (SupportPolicy{}).ResponseTarget(SupportCaseTypeSupport, 1, createdAt); !errors.Is(err, ErrInvalidSupportPolicy) {
t.Fatalf("zero policy error = %v, want ErrInvalidSupportPolicy", err)
}
policy := DemoSupportPolicy()
if _, err := policy.ResponseTarget("unknown", 1, createdAt); !errors.Is(err, ErrInvalidSupportPolicy) {
t.Fatalf("unknown case type error = %v, want ErrInvalidSupportPolicy", err)
}
if _, err := policy.ResponseTarget(SupportCaseTypeSupport, 0, createdAt); !errors.Is(err, ErrInvalidSupportPolicy) {
t.Fatalf("zero policy version error = %v, want ErrInvalidSupportPolicy", err)
}
if _, err := policy.ResponseTarget(SupportCaseTypeSupport, 1, time.Time{}); !errors.Is(err, ErrInvalidSupportPolicy) {
t.Fatalf("zero creation time error = %v, want ErrInvalidSupportPolicy", err)
}
}
+10 -6
View File
@@ -80,12 +80,15 @@ const MaxHiddenOrganizations = 1000
type CardField string
const (
CardFieldCategories CardField = "categories"
CardFieldStack CardField = "stack"
CardFieldExperience CardField = "experience"
CardFieldSoftSkills CardField = "soft_skills"
CardFieldLocation CardField = "location"
CardFieldRelocation CardField = "relocation"
CardFieldCategories CardField = "categories"
CardFieldStack CardField = "stack"
CardFieldExperience CardField = "experience"
CardFieldSoftSkills CardField = "soft_skills"
CardFieldLocation CardField = "location"
CardFieldRelocation CardField = "relocation"
CardFieldSelfAssessment CardField = "self_assessment"
CardFieldWorkFormats CardField = "work_formats"
CardFieldSalaryCompatibility CardField = "salary_compatibility"
)
const (
@@ -99,6 +102,7 @@ const (
var cardFields = []CardField{
CardFieldCategories, CardFieldStack, CardFieldExperience,
CardFieldSoftSkills, CardFieldLocation, CardFieldRelocation,
CardFieldSelfAssessment, CardFieldWorkFormats, CardFieldSalaryCompatibility,
}
// CardFields returns every card field the contract defines.