diff --git a/.env.example b/.env.example index 4d410d5..e2593c7 100644 --- a/.env.example +++ b/.env.example @@ -97,6 +97,11 @@ IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT=10 IDENTITY_SESSION_IDLE_TIMEOUT=24h IDENTITY_SESSION_ABSOLUTE_LIFETIME=168h +# Off by default. Allow demo_basic category assignment only for a reviewed +# synthetic opening with an exactly pinned manifest and product policy. +# demo_express never assigns a category. Leave false outside a synthetic stand. +ASSESSMENT_DEMO_CATEGORIES_ENABLED=false + # Reverse proxies the backend trusts to report the client address in # X-Forwarded-For. Leave it unset: the default is the frontend container's # APP_FRONTEND_IP as a single address. A wider list lets other containers (or a diff --git a/api/core/components/schemas.yml b/api/core/components/schemas.yml index 3c92c99..382e7e0 100644 --- a/api/core/components/schemas.yml +++ b/api/core/components/schemas.yml @@ -1214,6 +1214,74 @@ AssessmentResult: root: '#/AssessmentQualifiedResult' corrective: '#/AssessmentCorrectiveResult' demo_express: '#/AssessmentExpressResult' +AssessmentRealResult: + description: A completed root or corrective result. Training-only demo_express results are excluded from qualification history. + oneOf: + - $ref: '#/AssessmentQualifiedResult' + - $ref: '#/AssessmentCorrectiveResult' + discriminator: + propertyName: kind + mapping: + root: '#/AssessmentQualifiedResult' + corrective: '#/AssessmentCorrectiveResult' +AssessmentCategoryDecisionView: + type: object + description: Category decision captured when this result was stored. It is absent from legacy v1 results because their current grade cannot be inferred later. It never exposes review identifiers, private answers, or the candidate's current category after this decision. + additionalProperties: false + required: + - status + - previous_confirmed_grade + - current_confirmed_grade + - method + - source + - calibration_status + properties: + status: + type: string + enum: + - not_eligible + - not_confirmed + - assigned + - unchanged + previous_confirmed_grade: + oneOf: + - $ref: '#/GradeCode' + - type: 'null' + current_confirmed_grade: + oneOf: + - $ref: '#/GradeCode' + - type: 'null' + method: + oneOf: + - type: string + enum: + - demo_basic_pass_mark + - type: 'null' + source: + oneOf: + - type: string + enum: + - synthetic_demo + - type: 'null' + calibration_status: + oneOf: + - $ref: '#/CalibrationStatus' + - type: 'null' +AssessmentResultHistoryPage: + type: object + description: Owner-only immutable root and corrective results ordered by decided_at and attempt_id descending. Legacy v1 results omit category_decision. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 50 + items: + $ref: '#/AssessmentRealResult' + page: + $ref: '#/PageInfo' AssessmentFinalizeConflictProblem: type: object description: A finalize state conflict. `pending_item_ids` is present only when the attempt still has required questions without answers; it is omitted for other state conflicts and idempotency conflicts. @@ -1346,6 +1414,8 @@ AssessmentRealResultCommon: oneOf: - $ref: '#/GradeCode' - type: 'null' + category_decision: + $ref: '#/AssessmentCategoryDecisionView' strength: description: Strength of an adaptive confirmation, otherwise null. oneOf: diff --git a/api/core/components/schemas/assessment_schemas.yml b/api/core/components/schemas/assessment_schemas.yml index f599cbd..1371cfe 100644 --- a/api/core/components/schemas/assessment_schemas.yml +++ b/api/core/components/schemas/assessment_schemas.yml @@ -1330,6 +1330,82 @@ schemas: root: "#/schemas/AssessmentQualifiedResult" corrective: "#/schemas/AssessmentCorrectiveResult" demo_express: "#/schemas/AssessmentExpressResult" + AssessmentRealResult: + description: >- + A completed root or corrective result. Training-only demo_express + results are excluded from qualification history. + oneOf: + - $ref: "#/schemas/AssessmentQualifiedResult" + - $ref: "#/schemas/AssessmentCorrectiveResult" + discriminator: + propertyName: kind + mapping: + root: "#/schemas/AssessmentQualifiedResult" + corrective: "#/schemas/AssessmentCorrectiveResult" + AssessmentCategoryDecisionView: + type: object + description: >- + Category decision captured when this result was stored. It is absent + from legacy v1 results because their current grade cannot be inferred + later. It never exposes review identifiers, private answers, or the + candidate's current category after this decision. + additionalProperties: false + required: + - status + - previous_confirmed_grade + - current_confirmed_grade + - method + - source + - calibration_status + properties: + status: + type: string + enum: + - not_eligible + - not_confirmed + - assigned + - unchanged + previous_confirmed_grade: + oneOf: + - $ref: "./catalog_schemas.yml#/schemas/GradeCode" + - type: "null" + current_confirmed_grade: + oneOf: + - $ref: "./catalog_schemas.yml#/schemas/GradeCode" + - type: "null" + method: + oneOf: + - type: string + enum: + - demo_basic_pass_mark + - type: "null" + source: + oneOf: + - type: string + enum: + - synthetic_demo + - type: "null" + calibration_status: + oneOf: + - $ref: "#/schemas/CalibrationStatus" + - type: "null" + AssessmentResultHistoryPage: + type: object + description: >- + Owner-only immutable root and corrective results ordered by decided_at + and attempt_id descending. Legacy v1 results omit category_decision. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 50 + items: + $ref: "#/schemas/AssessmentRealResult" + page: + $ref: "./common_schemas.yml#/schemas/PageInfo" AssessmentFinalizeConflictProblem: type: object description: >- @@ -1484,6 +1560,8 @@ schemas: oneOf: - $ref: "./catalog_schemas.yml#/schemas/GradeCode" - type: "null" + category_decision: + $ref: "#/schemas/AssessmentCategoryDecisionView" strength: description: Strength of an adaptive confirmation, otherwise null. oneOf: diff --git a/api/core/openapi.bundle.yml b/api/core/openapi.bundle.yml index a1b87b6..5facd98 100644 --- a/api/core/openapi.bundle.yml +++ b/api/core/openapi.bundle.yml @@ -669,6 +669,48 @@ paths: $ref: '#/components/responses/Forbidden' default: $ref: '#/components/responses/Problem' + /api/v1/me/assessment-results: + get: + operationId: ListMyAssessmentResults + summary: List immutable real assessment results of the current candidate. + description: |- + Requires a candidate session. Returns only completed root and corrective results owned by this candidate, newest first by decided_at and attempt_id. demo_express training results never appear. The cursor is opaque and bound to this candidate and listing; a malformed or foreign cursor returns 400 validation_failed. + + A v2 result includes the category decision captured when that attempt ended, including the confirmed grade then in force. Legacy v1 results omit category_decision because a later category must not be projected backward. Later policy, bank, review, or category changes do not alter either result. Employers cannot read this history; their separate projection contains only the current permitted category and no answers. + security: + - sessionCookie: [] + tags: + - assessment + parameters: + - name: limit + in: query + required: false + description: Maximum number of results per page. + schema: + type: integer + format: int32 + minimum: 1 + maximum: 50 + default: 20 + - $ref: '#/components/parameters/PageCursor' + responses: + '200': + description: One owner-scoped page of immutable results. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/AssessmentResultHistoryPage' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + default: + $ref: '#/components/responses/Problem' /api/v1/me/assessment-attempts: post: operationId: CreateMyAssessmentAttempt @@ -5640,6 +5682,74 @@ components: root: '#/components/schemas/AssessmentQualifiedResult' corrective: '#/components/schemas/AssessmentCorrectiveResult' demo_express: '#/components/schemas/AssessmentExpressResult' + AssessmentRealResult: + description: A completed root or corrective result. Training-only demo_express results are excluded from qualification history. + oneOf: + - $ref: '#/components/schemas/AssessmentQualifiedResult' + - $ref: '#/components/schemas/AssessmentCorrectiveResult' + discriminator: + propertyName: kind + mapping: + root: '#/components/schemas/AssessmentQualifiedResult' + corrective: '#/components/schemas/AssessmentCorrectiveResult' + AssessmentCategoryDecisionView: + type: object + description: Category decision captured when this result was stored. It is absent from legacy v1 results because their current grade cannot be inferred later. It never exposes review identifiers, private answers, or the candidate's current category after this decision. + additionalProperties: false + required: + - status + - previous_confirmed_grade + - current_confirmed_grade + - method + - source + - calibration_status + properties: + status: + type: string + enum: + - not_eligible + - not_confirmed + - assigned + - unchanged + previous_confirmed_grade: + oneOf: + - $ref: '#/components/schemas/GradeCode' + - type: 'null' + current_confirmed_grade: + oneOf: + - $ref: '#/components/schemas/GradeCode' + - type: 'null' + method: + oneOf: + - type: string + enum: + - demo_basic_pass_mark + - type: 'null' + source: + oneOf: + - type: string + enum: + - synthetic_demo + - type: 'null' + calibration_status: + oneOf: + - $ref: '#/components/schemas/CalibrationStatus' + - type: 'null' + AssessmentResultHistoryPage: + type: object + description: Owner-only immutable root and corrective results ordered by decided_at and attempt_id descending. Legacy v1 results omit category_decision. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 50 + items: + $ref: '#/components/schemas/AssessmentRealResult' + page: + $ref: '#/components/schemas/PageInfo' AssessmentGradeAvailabilityStatus: type: string description: |- @@ -9229,6 +9339,171 @@ components: enum: - demo_basic - adaptive + AssessmentRealResultCommon: + type: object + description: Immutable result of a real assessment, visible only to its candidate. It records the method, versions, decision, uncertainty, and limitations. A corrective result also carries root_attempt_id and chain_deadline from the same chain. Later policy, bank, or algorithm versions never change it. It never contains answers, per-item correctness, keys, seeds, hidden checks, or anti-cheat signals. Fields the method does not compute are null, never zero. + additionalProperties: false + required: + - attempt_id + - specialization + - target_grade + - task_language + - kind + - mode + - versions + - outcome + - not_determined_reason + - confirmed_grade + - previous_confirmed_grade + - strength + - calibration_status + - limitations + - uncertainty + - basic_score + - practices + - gaps + - durations + - next_steps + - decided_at + properties: + attempt_id: + type: string + format: uuid + specialization: + $ref: '#/components/schemas/SpecializationCode' + target_grade: + $ref: '#/components/schemas/GradeCode' + root_attempt_id: + description: Root attempt of a corrective check, or null when this is not a corrective result. The corrective attempt keeps this link. + oneOf: + - type: string + format: uuid + - type: 'null' + readOnly: true + chain_deadline: + description: Immutable deadline shared by a corrective chain, or null when this result is not from a corrective check. + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + readOnly: true + task_language: + oneOf: + - $ref: '#/components/schemas/TaskLanguage' + - type: 'null' + kind: + type: string + enum: + - root + - corrective + mode: + type: string + enum: + - demo_basic + - adaptive + versions: + $ref: '#/components/schemas/AssessmentVersions' + outcome: + $ref: '#/components/schemas/AssessmentOutcome' + not_determined_reason: + description: The reason when `outcome` is `not_determined`, otherwise null. + oneOf: + - $ref: '#/components/schemas/AssessmentNotDeterminedReason' + - type: 'null' + confirmed_grade: + description: Grade that this attempt confirmed, the target grade, or null when it confirmed none. Together with the specialization it forms the category. + oneOf: + - $ref: '#/components/schemas/GradeCode' + - type: 'null' + previous_confirmed_grade: + description: Confirmed grade of the specialization before this attempt, or null. When the attempt confirmed nothing, this grade stays in force. + oneOf: + - $ref: '#/components/schemas/GradeCode' + - type: 'null' + category_decision: + $ref: '#/components/schemas/AssessmentCategoryDecisionView' + strength: + description: Strength of an adaptive confirmation, otherwise null. + oneOf: + - $ref: '#/components/schemas/AssessmentStrength' + - type: 'null' + calibration_status: + $ref: '#/components/schemas/CalibrationStatus' + limitations: + type: array + maxItems: 10 + uniqueItems: true + items: + $ref: '#/components/schemas/AssessmentLimitation' + uncertainty: + description: Ability estimate and uncertainty of an adaptive attempt with a decision; null for demo_basic, which computes none, and for an attempt without a decision. + oneOf: + - $ref: '#/components/schemas/AssessmentUncertainty' + - type: 'null' + basic_score: + description: Raw score of a demo_basic attempt with a decision, otherwise null. + oneOf: + - $ref: '#/components/schemas/BasicScore' + - type: 'null' + practices: + type: array + maxItems: 5 + description: Verdicts of the practices that have one, main first. + items: + $ref: '#/components/schemas/AssessmentPracticeResult' + gaps: + type: array + maxItems: 20 + description: Domains with weak evidence; empty when none were found or the method finds none. + items: + $ref: '#/components/schemas/AssessmentGap' + durations: + $ref: '#/components/schemas/AssessmentDurations' + next_steps: + type: array + maxItems: 5 + items: + $ref: '#/components/schemas/AssessmentNextStep' + decided_at: + $ref: '#/components/schemas/Timestamp' + AssessmentQualifiedResult: + description: Result of a real assessment that is not a corrective attempt. The correction-chain fields are explicitly null. + allOf: + - $ref: '#/components/schemas/AssessmentRealResultCommon' + - type: object + properties: + kind: + type: string + enum: + - root + root_attempt_id: + type: 'null' + chain_deadline: + type: 'null' + required: + - kind + - root_attempt_id + - chain_deadline + AssessmentCorrectiveResult: + description: Result of a corrective real assessment. Both chain fields are present and identify the same immutable correction chain. + allOf: + - $ref: '#/components/schemas/AssessmentRealResultCommon' + - type: object + properties: + kind: + type: string + enum: + - corrective + root_attempt_id: + type: string + format: uuid + readOnly: true + chain_deadline: + $ref: '#/components/schemas/Timestamp' + readOnly: true + required: + - kind + - root_attempt_id + - chain_deadline AssessmentQualifiedAttemptCreate: type: object description: Start a real assessment for a specialization and target grade, with the task language. The candidate comes from the session. The server chooses demo_basic or adaptive and fixes the policy, bank, and algorithm versions. Unknown fields such as `mode`, `seed`, or `score` are rejected. @@ -9539,169 +9814,6 @@ components: type: string format: uuid description: Frozen item IDs still unanswered when finalize is rejected for an incomplete attempt. Omitted when the conflict is unrelated to unanswered items. - AssessmentRealResultCommon: - type: object - description: Immutable result of a real assessment, visible only to its candidate. It records the method, versions, decision, uncertainty, and limitations. A corrective result also carries root_attempt_id and chain_deadline from the same chain. Later policy, bank, or algorithm versions never change it. It never contains answers, per-item correctness, keys, seeds, hidden checks, or anti-cheat signals. Fields the method does not compute are null, never zero. - additionalProperties: false - required: - - attempt_id - - specialization - - target_grade - - task_language - - kind - - mode - - versions - - outcome - - not_determined_reason - - confirmed_grade - - previous_confirmed_grade - - strength - - calibration_status - - limitations - - uncertainty - - basic_score - - practices - - gaps - - durations - - next_steps - - decided_at - properties: - attempt_id: - type: string - format: uuid - specialization: - $ref: '#/components/schemas/SpecializationCode' - target_grade: - $ref: '#/components/schemas/GradeCode' - root_attempt_id: - description: Root attempt of a corrective check, or null when this is not a corrective result. The corrective attempt keeps this link. - oneOf: - - type: string - format: uuid - - type: 'null' - readOnly: true - chain_deadline: - description: Immutable deadline shared by a corrective chain, or null when this result is not from a corrective check. - oneOf: - - $ref: '#/components/schemas/Timestamp' - - type: 'null' - readOnly: true - task_language: - oneOf: - - $ref: '#/components/schemas/TaskLanguage' - - type: 'null' - kind: - type: string - enum: - - root - - corrective - mode: - type: string - enum: - - demo_basic - - adaptive - versions: - $ref: '#/components/schemas/AssessmentVersions' - outcome: - $ref: '#/components/schemas/AssessmentOutcome' - not_determined_reason: - description: The reason when `outcome` is `not_determined`, otherwise null. - oneOf: - - $ref: '#/components/schemas/AssessmentNotDeterminedReason' - - type: 'null' - confirmed_grade: - description: Grade that this attempt confirmed, the target grade, or null when it confirmed none. Together with the specialization it forms the category. - oneOf: - - $ref: '#/components/schemas/GradeCode' - - type: 'null' - previous_confirmed_grade: - description: Confirmed grade of the specialization before this attempt, or null. When the attempt confirmed nothing, this grade stays in force. - oneOf: - - $ref: '#/components/schemas/GradeCode' - - type: 'null' - strength: - description: Strength of an adaptive confirmation, otherwise null. - oneOf: - - $ref: '#/components/schemas/AssessmentStrength' - - type: 'null' - calibration_status: - $ref: '#/components/schemas/CalibrationStatus' - limitations: - type: array - maxItems: 10 - uniqueItems: true - items: - $ref: '#/components/schemas/AssessmentLimitation' - uncertainty: - description: Ability estimate and uncertainty of an adaptive attempt with a decision; null for demo_basic, which computes none, and for an attempt without a decision. - oneOf: - - $ref: '#/components/schemas/AssessmentUncertainty' - - type: 'null' - basic_score: - description: Raw score of a demo_basic attempt with a decision, otherwise null. - oneOf: - - $ref: '#/components/schemas/BasicScore' - - type: 'null' - practices: - type: array - maxItems: 5 - description: Verdicts of the practices that have one, main first. - items: - $ref: '#/components/schemas/AssessmentPracticeResult' - gaps: - type: array - maxItems: 20 - description: Domains with weak evidence; empty when none were found or the method finds none. - items: - $ref: '#/components/schemas/AssessmentGap' - durations: - $ref: '#/components/schemas/AssessmentDurations' - next_steps: - type: array - maxItems: 5 - items: - $ref: '#/components/schemas/AssessmentNextStep' - decided_at: - $ref: '#/components/schemas/Timestamp' - AssessmentQualifiedResult: - description: Result of a real assessment that is not a corrective attempt. The correction-chain fields are explicitly null. - allOf: - - $ref: '#/components/schemas/AssessmentRealResultCommon' - - type: object - properties: - kind: - type: string - enum: - - root - root_attempt_id: - type: 'null' - chain_deadline: - type: 'null' - required: - - kind - - root_attempt_id - - chain_deadline - AssessmentCorrectiveResult: - description: Result of a corrective real assessment. Both chain fields are present and identify the same immutable correction chain. - allOf: - - $ref: '#/components/schemas/AssessmentRealResultCommon' - - type: object - properties: - kind: - type: string - enum: - - corrective - root_attempt_id: - type: string - format: uuid - readOnly: true - chain_deadline: - $ref: '#/components/schemas/Timestamp' - readOnly: true - required: - - kind - - root_attempt_id - - chain_deadline AssessmentExpressResult: type: object description: Immutable educational result of a demo_express run. It includes a short summary but cannot report a category, percentile, uncertainty, grade, strength, or qualification evidence. The result belongs only to the training mode and does not consume a real-assessment quota. diff --git a/api/core/openapi.yml b/api/core/openapi.yml index 80df6b5..fb2186f 100644 --- a/api/core/openapi.yml +++ b/api/core/openapi.yml @@ -103,6 +103,8 @@ paths: $ref: ./routes/candidate_profile.yml /api/v1/me/assessment-availability: $ref: ./routes/candidate_assessment_availability.yml + /api/v1/me/assessment-results: + $ref: ./routes/candidate_assessment_results.yml /api/v1/me/assessment-attempts: $ref: ./routes/candidate_assessment_attempts.yml /api/v1/me/assessment-attempts/{attempt_id}: @@ -487,6 +489,12 @@ components: $ref: ./components/schemas.yml#/AssessmentNextStep AssessmentResult: $ref: ./components/schemas.yml#/AssessmentResult + AssessmentRealResult: + $ref: ./components/schemas.yml#/AssessmentRealResult + AssessmentCategoryDecisionView: + $ref: ./components/schemas.yml#/AssessmentCategoryDecisionView + AssessmentResultHistoryPage: + $ref: ./components/schemas.yml#/AssessmentResultHistoryPage AssessmentGradeAvailabilityStatus: $ref: ./components/schemas.yml#/AssessmentGradeAvailabilityStatus AssessmentGradeAvailability: diff --git a/api/core/routes/candidate_assessment_results.yml b/api/core/routes/candidate_assessment_results.yml new file mode 100644 index 0000000..9325906 --- /dev/null +++ b/api/core/routes/candidate_assessment_results.yml @@ -0,0 +1,41 @@ +get: + operationId: ListMyAssessmentResults + summary: List immutable real assessment results of the current candidate. + description: |- + Requires a candidate session. Returns only completed root and corrective results owned by this candidate, newest first by decided_at and attempt_id. demo_express training results never appear. The cursor is opaque and bound to this candidate and listing; a malformed or foreign cursor returns 400 validation_failed. + + A v2 result includes the category decision captured when that attempt ended, including the confirmed grade then in force. Legacy v1 results omit category_decision because a later category must not be projected backward. Later policy, bank, review, or category changes do not alter either result. Employers cannot read this history; their separate projection contains only the current permitted category and no answers. + security: + - sessionCookie: [] + tags: + - assessment + parameters: + - name: limit + in: query + required: false + description: Maximum number of results per page. + schema: + type: integer + format: int32 + minimum: 1 + maximum: 50 + default: 20 + - $ref: ../components/parameters.yml#/PageCursor + responses: + "200": + description: One owner-scoped page of immutable results. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/AssessmentResultHistoryPage + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/Forbidden + default: + $ref: ../components/responses.yml#/Problem diff --git a/backend/config/assessment.go b/backend/config/assessment.go new file mode 100644 index 0000000..561e650 --- /dev/null +++ b/backend/config/assessment.go @@ -0,0 +1,12 @@ +package config + +// loadAssessment reads narrowly scoped assessment feature gates. All gates +// default off so configuration cannot silently grant synthetic provenance. +func (config *Config) loadAssessment(lookup LookupEnv) error { + enabled, err := boolOrDefault(lookup, "ASSESSMENT_DEMO_CATEGORIES_ENABLED", false) + if err != nil { + return err + } + config.AssessmentDemoCategoriesEnabled = enabled + return nil +} diff --git a/backend/config/assessment_test.go b/backend/config/assessment_test.go new file mode 100644 index 0000000..f2bd81a --- /dev/null +++ b/backend/config/assessment_test.go @@ -0,0 +1,37 @@ +package config + +import ( + "strings" + "testing" +) + +func TestLoadFromEnvAssessmentDemoCategoriesDefaultsOff(t *testing.T) { + settings, err := LoadFromEnv(testEnvironment(nil)) + if err != nil { + t.Fatalf("LoadFromEnv() error = %v", err) + } + if settings.AssessmentDemoCategoriesEnabled { + t.Fatal("AssessmentDemoCategoriesEnabled = true, want default false") + } +} + +func TestLoadFromEnvAssessmentDemoCategoriesReadsExplicitValue(t *testing.T) { + settings, err := LoadFromEnv(testEnvironment(map[string]string{ + "ASSESSMENT_DEMO_CATEGORIES_ENABLED": " TRUE ", + })) + if err != nil { + t.Fatalf("LoadFromEnv() error = %v", err) + } + if !settings.AssessmentDemoCategoriesEnabled { + t.Fatal("AssessmentDemoCategoriesEnabled = false, want explicit true") + } +} + +func TestLoadFromEnvAssessmentDemoCategoriesRejectsAmbiguousValue(t *testing.T) { + _, err := LoadFromEnv(testEnvironment(map[string]string{ + "ASSESSMENT_DEMO_CATEGORIES_ENABLED": "yes", + })) + if err == nil || !strings.HasPrefix(err.Error(), "config.boolOrDefault - ASSESSMENT_DEMO_CATEGORIES_ENABLED") { + t.Fatalf("LoadFromEnv() error = %v, want a strict boolean setting error", err) + } +} diff --git a/backend/config/config.go b/backend/config/config.go index a3a50d3..350abd2 100644 --- a/backend/config/config.go +++ b/backend/config/config.go @@ -143,6 +143,9 @@ type Config struct { // IdentitySessionAbsoluteLifetime is the maximum lifetime of a session, // even when it remains active. IdentitySessionAbsoluteLifetime time.Duration + // AssessmentDemoCategoriesEnabled explicitly enables synthetic demo category + // assignment. Reviewed source provenance is required separately. + AssessmentDemoCategoriesEnabled bool // TrustedProxyCIDRs are the reverse proxies in front of the API. The // client address is taken from X-Forwarded-For only through them (see @@ -197,10 +200,7 @@ func LoadFromEnv(lookup LookupEnv) (Config, error) { if err := config.loadPasswordHash(lookup); err != nil { return Config{}, err } - if err := config.loadIdentity(lookup); err != nil { - return Config{}, err - } - if err := config.loadTrustedProxies(lookup); err != nil { + if err := config.loadIdentityAndProxySettings(lookup); err != nil { return Config{}, err } @@ -231,6 +231,16 @@ func LoadFromEnv(lookup LookupEnv) (Config, error) { return config, nil } +func (config *Config) loadIdentityAndProxySettings(lookup LookupEnv) error { + if err := config.loadIdentity(lookup); err != nil { + return err + } + if err := config.loadAssessment(lookup); err != nil { + return err + } + return config.loadTrustedProxies(lookup) +} + func (config Config) Validate() error { if err := config.ValidateSeaweedFS(); err != nil { return err diff --git a/backend/db/migrations/00031_assessment_category_results.sql b/backend/db/migrations/00031_assessment_category_results.sql new file mode 100644 index 0000000..42f8c75 --- /dev/null +++ b/backend/db/migrations/00031_assessment_category_results.sql @@ -0,0 +1,383 @@ +-- +goose Up +-- Synthetic category decisions extend immutable result rows without changing +-- the existing result_snapshot document. Version 1 rows remain readable as-is. + +ALTER TABLE assessment_attempt_results + DROP CONSTRAINT assessment_attempt_results_schema, + ADD COLUMN category_decision jsonb, + ADD COLUMN current_confirmed_grade text, + ADD CONSTRAINT assessment_attempt_results_schema CHECK (schema_version IN (1, 2)), + ADD CONSTRAINT assessment_attempt_results_category_extension CHECK ( + (schema_version = 1 AND category_decision IS NULL AND current_confirmed_grade IS NULL) + OR ( + schema_version = 2 + AND kind IN ('root', 'corrective') AND mode = 'demo_basic' + AND jsonb_typeof(category_decision) = 'object' + AND category_decision->>'attempt_id' = attempt_id::text + AND category_decision->>'specialization' IS NOT NULL + AND category_decision->>'attempted_grade' IS NOT NULL + AND category_decision->>'product_policy_version_id' = product_policy_version_id::text + AND (category_decision->>'product_policy_version')::integer = product_policy_version + AND category_decision->>'grading_policy_version_id' = grading_policy_version_id::text + AND category_decision->>'opening_id' = opening_id::text + AND category_decision->>'opening_manifest_sha256' = encode(opening_manifest_sha256, 'hex') + AND (category_decision->>'decided_at')::timestamptz = decided_at + AND category_decision->>'status' IN ('not_eligible', 'not_confirmed', 'assigned', 'unchanged') + AND NULLIF(category_decision->>'current_grade', '') IS NOT DISTINCT FROM current_confirmed_grade + AND (current_confirmed_grade IS NULL OR current_confirmed_grade IN ('intern', 'junior', 'middle', 'senior')) + ) + ); + +CREATE UNIQUE INDEX assessment_attempt_results_attempt_owner_key +ON assessment_attempt_results (attempt_id, user_id); + +CREATE INDEX assessment_attempt_results_history_idx +ON assessment_attempt_results (user_id, decided_at DESC, attempt_id DESC) +WHERE kind IN ('root', 'corrective'); + +CREATE TABLE assessment_synthetic_category_reviews ( + id uuid NOT NULL, + opening_id uuid NOT NULL REFERENCES assessment_category_openings (id), + category text NOT NULL, + source text NOT NULL, + opening_manifest_sha256 bytea NOT NULL, + product_policy_version_id uuid NOT NULL REFERENCES policy_versions (id), + product_policy_version integer NOT NULL, + reviewed_by text NOT NULL, + reviewed_at timestamptz NOT NULL, + CONSTRAINT assessment_synthetic_category_reviews_pkey PRIMARY KEY (id), + CONSTRAINT assessment_synthetic_category_reviews_exact_source_key UNIQUE ( + opening_id, product_policy_version_id, opening_manifest_sha256, source + ), + CONSTRAINT assessment_synthetic_category_reviews_source CHECK (source = 'synthetic_demo'), + CONSTRAINT assessment_synthetic_category_reviews_hash CHECK (octet_length(opening_manifest_sha256) = 32), + CONSTRAINT assessment_synthetic_category_reviews_policy_version CHECK (product_policy_version > 0), + CONSTRAINT assessment_synthetic_category_reviews_reviewer CHECK ( + char_length(reviewed_by) <= 128 + AND reviewed_by ~ '^operator:[a-z0-9][a-z0-9._-]*$' + ) +); + +-- A review attestation is accepted only for the exact immutable opening and +-- reviewed catalog manifest. The policy is pinned by ID and version; domain +-- validation additionally requires the complete explicit demo V2 policy. +-- +goose StatementBegin +CREATE FUNCTION assessment_synthetic_category_review_guard() RETURNS trigger +LANGUAGE plpgsql AS $$ +DECLARE + opening_category text; + opening_policy_id uuid; + manifest_hash bytea; + policy_version integer; +BEGIN + SELECT opening.category, opening.policy_version_id, binding.published_manifest_sha256 + INTO opening_category, opening_policy_id, manifest_hash + FROM assessment_category_openings AS opening + JOIN assessment_category_catalog_bindings AS binding ON binding.opening_id = opening.id + WHERE opening.id = NEW.opening_id; + + IF NOT FOUND OR opening_category <> NEW.category OR + manifest_hash IS DISTINCT FROM NEW.opening_manifest_sha256 THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_synthetic_category_review_source', + MESSAGE = 'synthetic category review does not match its immutable opening and manifest'; + END IF; + IF NOT EXISTS ( + SELECT 1 FROM policy_versions AS policy + WHERE policy.id = opening_policy_id AND policy.policy_key = 'product' + ) THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_synthetic_category_review_opening_policy', + MESSAGE = 'synthetic category review opening has no product grading policy'; + END IF; + + SELECT policy.version INTO policy_version + FROM policy_versions AS policy + WHERE policy.id = NEW.product_policy_version_id + AND policy.policy_key = 'product' + AND policy.kind = 'demo' + AND policy.version = NEW.product_policy_version + AND policy.document #>> '{assessment,attempt,real_mode}' = 'demo_basic' + AND policy.document #>> '{assessment,attempt,basic_pass_mark_bp}' = '8000'; + IF NOT FOUND OR policy_version <> NEW.product_policy_version THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_synthetic_category_review_policy', + MESSAGE = 'synthetic category review policy is not an explicit demo basic policy'; + END IF; + + NEW.reviewed_at := clock_timestamp(); + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_synthetic_category_review_guard +BEFORE INSERT ON assessment_synthetic_category_reviews +FOR EACH ROW EXECUTE FUNCTION assessment_synthetic_category_review_guard(); + +-- Review attestations are provenance records and cannot be rewritten or +-- removed independently of account cleanup. +-- +goose StatementBegin +CREATE FUNCTION assessment_synthetic_category_review_refuse_change() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' AND pg_trigger_depth() > 1 THEN + RETURN OLD; + END IF; + RAISE EXCEPTION USING + ERRCODE = '23000', CONSTRAINT = 'assessment_synthetic_category_review_immutable', + MESSAGE = 'synthetic category reviews are immutable'; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_synthetic_category_review_refuse_mutation +BEFORE UPDATE OR DELETE ON assessment_synthetic_category_reviews +FOR EACH ROW EXECUTE FUNCTION assessment_synthetic_category_review_refuse_change(); + +CREATE TABLE candidate_assessment_categories ( + candidate_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE, + specialization text NOT NULL, + grade text NOT NULL, + source_attempt_id uuid NOT NULL, + source_review_id uuid NOT NULL REFERENCES assessment_synthetic_category_reviews (id), + product_policy_version_id uuid NOT NULL REFERENCES policy_versions (id), + product_policy_version integer NOT NULL, + grading_policy_version_id uuid NOT NULL REFERENCES policy_versions (id), + opening_id uuid NOT NULL REFERENCES assessment_category_openings (id), + opening_manifest_sha256 bytea NOT NULL, + source text NOT NULL, + calibration_status text NOT NULL, + assigned_at timestamptz NOT NULL, + CONSTRAINT candidate_assessment_categories_pkey PRIMARY KEY (candidate_id, specialization), + CONSTRAINT candidate_assessment_categories_source_attempt_key UNIQUE (source_attempt_id), + CONSTRAINT candidate_assessment_categories_attempt_owner_fk FOREIGN KEY (source_attempt_id, candidate_id) + REFERENCES assessment_attempt_results (attempt_id, user_id) ON DELETE CASCADE, + CONSTRAINT candidate_assessment_categories_specialization CHECK ( + specialization IN ('backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', + 'data_analyst', 'ds_ml', 'information_security', 'qa') + ), + CONSTRAINT candidate_assessment_categories_grade CHECK (grade IN ('intern', 'junior', 'middle', 'senior')), + CONSTRAINT candidate_assessment_categories_source CHECK (source = 'synthetic_demo'), + CONSTRAINT candidate_assessment_categories_calibration CHECK (calibration_status = 'uncalibrated'), + CONSTRAINT candidate_assessment_categories_hash CHECK (octet_length(opening_manifest_sha256) = 32), + CONSTRAINT candidate_assessment_categories_policy_version CHECK (product_policy_version > 0) +); + +-- Current grade rows are derived only from an assigned immutable v2 result. +-- Upgrades are monotonic; a lower passing result remains visible in its own +-- result record and cannot lower the current category. +-- +goose StatementBegin +CREATE FUNCTION candidate_assessment_category_guard() RETURNS trigger +LANGUAGE plpgsql AS $$ +DECLARE + decision jsonb; + result_grade text; + result_user_id uuid; + result_at timestamptz; + review assessment_synthetic_category_reviews%ROWTYPE; + prior_rank integer; + next_rank integer; +BEGIN + SELECT result.category_decision, result.user_id, result.decided_at + INTO decision, result_user_id, result_at + FROM assessment_attempt_results AS result + WHERE result.attempt_id = NEW.source_attempt_id AND result.user_id = NEW.candidate_id + AND result.schema_version = 2; + + result_grade := decision->>'current_grade'; + IF NOT FOUND OR decision->>'status' <> 'assigned' OR result_user_id <> NEW.candidate_id OR + result_grade <> NEW.grade OR decision->>'specialization' <> NEW.specialization OR + decision->>'source' <> NEW.source OR decision->>'calibration_status' <> NEW.calibration_status OR + decision->>'review_id' <> NEW.source_review_id::text OR + decision->>'product_policy_version_id' <> NEW.product_policy_version_id::text OR + (decision->>'product_policy_version')::integer <> NEW.product_policy_version OR + decision->>'grading_policy_version_id' <> NEW.grading_policy_version_id::text OR + decision->>'opening_id' <> NEW.opening_id::text OR + decision->>'opening_manifest_sha256' <> encode(NEW.opening_manifest_sha256, 'hex') OR + NEW.assigned_at <> result_at THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'candidate_assessment_categories_result_match', + MESSAGE = 'current category does not match an assigned immutable result'; + END IF; + + SELECT * INTO review + FROM assessment_synthetic_category_reviews AS source + WHERE source.id = NEW.source_review_id + AND source.opening_id = NEW.opening_id + AND source.category = (SELECT attempt.bank_category FROM assessment_attempts AS attempt WHERE attempt.id = NEW.source_attempt_id) + AND source.source = NEW.source + AND source.opening_manifest_sha256 = NEW.opening_manifest_sha256 + AND source.product_policy_version_id = NEW.product_policy_version_id + AND source.product_policy_version = NEW.product_policy_version + AND source.reviewed_at <= result_at; + IF NOT FOUND THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'candidate_assessment_categories_review_match', + MESSAGE = 'current category is missing its exact reviewed synthetic source'; + END IF; + + next_rank := CASE NEW.grade WHEN 'intern' THEN 0 WHEN 'junior' THEN 1 WHEN 'middle' THEN 2 WHEN 'senior' THEN 3 ELSE -1 END; + IF TG_OP = 'UPDATE' THEN + prior_rank := CASE OLD.grade WHEN 'intern' THEN 0 WHEN 'junior' THEN 1 WHEN 'middle' THEN 2 WHEN 'senior' THEN 3 ELSE -1 END; + IF OLD.candidate_id <> NEW.candidate_id OR OLD.specialization <> NEW.specialization OR next_rank <= prior_rank THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'candidate_assessment_categories_monotonic', + MESSAGE = 'current category updates must be a strict upgrade in the same scope'; + END IF; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER candidate_assessment_category_guard +BEFORE INSERT OR UPDATE ON candidate_assessment_categories +FOR EACH ROW EXECUTE FUNCTION candidate_assessment_category_guard(); + +-- Do not permit manual removal of current category state. Account deletion may +-- cascade through the candidate owner row. +-- +goose StatementBegin +CREATE FUNCTION candidate_assessment_category_refuse_delete() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF pg_trigger_depth() > 1 THEN + RETURN OLD; + END IF; + RAISE EXCEPTION USING + ERRCODE = '23000', CONSTRAINT = 'candidate_assessment_categories_delete', + MESSAGE = 'current category can only change through a qualified result'; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER candidate_assessment_category_refuse_delete +BEFORE DELETE ON candidate_assessment_categories +FOR EACH ROW EXECUTE FUNCTION candidate_assessment_category_refuse_delete(); + +-- The extension guard ties a typed v2 decision to the row's immutable attempt +-- and exact reviewed source. Legacy v1 rows must keep both new columns NULL. +-- +goose StatementBegin +CREATE FUNCTION assessment_attempt_result_category_guard() RETURNS trigger +LANGUAGE plpgsql AS $$ +DECLARE + review assessment_synthetic_category_reviews%ROWTYPE; + attempt assessment_attempts%ROWTYPE; +BEGIN + IF NEW.schema_version = 1 THEN + RETURN NEW; + END IF; + + SELECT * INTO attempt + FROM assessment_attempts + WHERE id = NEW.attempt_id AND user_id = NEW.user_id; + IF NOT FOUND OR NEW.category_decision->>'bank_category' IS DISTINCT FROM attempt.bank_category OR + NEW.category_decision->>'specialization' IS DISTINCT FROM attempt.specialization OR + NEW.category_decision->>'attempted_grade' IS DISTINCT FROM attempt.target_grade OR + NEW.category_decision->>'grading_policy_version_id' IS DISTINCT FROM attempt.grading_policy_version_id::text OR + NEW.category_decision->>'opening_id' IS DISTINCT FROM attempt.opening_id::text OR + NEW.category_decision->>'opening_manifest_sha256' IS DISTINCT FROM encode(attempt.opening_manifest_sha256, 'hex') THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_result_category_decision', + MESSAGE = 'category decision does not match its attempt'; + END IF; + + IF NEW.category_decision->>'status' = 'not_eligible' THEN + IF NEW.category_decision ? 'review_id' OR NEW.category_decision->>'source' IS NOT NULL OR + NEW.category_decision->>'method' IS NOT NULL OR NEW.category_decision->>'calibration_status' IS NOT NULL OR + NEW.category_decision->>'current_grade' IS DISTINCT FROM NEW.category_decision->>'previous_grade' THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_result_category_decision', + MESSAGE = 'ineligible category decision contains review or assignment data'; + END IF; + ELSIF NEW.category_decision->>'status' IN ('not_confirmed', 'assigned', 'unchanged') THEN + IF NOT (NEW.category_decision ? 'review_id') OR + NEW.category_decision->>'source' <> 'synthetic_demo' OR + NEW.category_decision->>'calibration_status' <> 'uncalibrated' OR + NEW.category_decision->>'method' <> 'demo_basic_pass_mark' THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_result_category_decision', + MESSAGE = 'reviewed category decision lacks its synthetic provenance'; + END IF; + ELSE + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_result_category_decision', + MESSAGE = 'category decision status is unsupported'; + END IF; + + IF NEW.category_decision ? 'review_id' THEN + SELECT * INTO review + FROM assessment_synthetic_category_reviews AS source + WHERE source.id = (NEW.category_decision->>'review_id')::uuid + AND source.opening_id = NEW.opening_id + AND source.category = NEW.category_decision->>'bank_category' + AND source.source = NEW.category_decision->>'source' + AND source.opening_manifest_sha256 = NEW.opening_manifest_sha256 + AND source.product_policy_version_id = NEW.product_policy_version_id + AND source.product_policy_version = NEW.product_policy_version + AND (SELECT policy_version_id FROM assessment_category_openings WHERE id = source.opening_id) = NEW.grading_policy_version_id + AND source.reviewed_at <= NEW.decided_at; + IF NOT FOUND THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_result_category_review', + MESSAGE = 'category decision does not match its exact reviewed source'; + END IF; + ELSIF NEW.category_decision->>'status' <> 'not_eligible' THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_result_category_review_required', + MESSAGE = 'reviewed category decisions require an immutable source attestation'; + END IF; + + IF NEW.category_decision->>'status' = 'assigned' AND + (NEW.outcome <> 'confirmed' OR NEW.category_decision->>'source' <> 'synthetic_demo' OR + NEW.category_decision->>'calibration_status' <> 'uncalibrated' OR + NEW.category_decision->>'method' <> 'demo_basic_pass_mark' OR + NEW.current_confirmed_grade IS DISTINCT FROM NEW.category_decision->>'attempted_grade') THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_result_category_assignment', + MESSAGE = 'category assignment is not a passing reviewed demo decision'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_attempt_result_category_guard +BEFORE INSERT ON assessment_attempt_results +FOR EACH ROW EXECUTE FUNCTION assessment_attempt_result_category_guard(); + +-- +goose Down +-- Preserve category evidence and v2 result snapshots rather than silently +-- discarding their meanings when this migration is rolled back. +-- +goose StatementBegin +DO $$ +BEGIN + IF EXISTS (SELECT 1 FROM assessment_attempt_results WHERE schema_version = 2) + OR EXISTS (SELECT 1 FROM assessment_synthetic_category_reviews) + OR EXISTS (SELECT 1 FROM candidate_assessment_categories) THEN + RAISE EXCEPTION 'assessment category data uses migration 00031 and must be retained'; + END IF; +END; +$$; +-- +goose StatementEnd + +DROP TRIGGER candidate_assessment_category_refuse_delete ON candidate_assessment_categories; +DROP FUNCTION candidate_assessment_category_refuse_delete(); +DROP TRIGGER candidate_assessment_category_guard ON candidate_assessment_categories; +DROP FUNCTION candidate_assessment_category_guard(); +DROP TABLE candidate_assessment_categories; +DROP TRIGGER assessment_synthetic_category_review_refuse_mutation ON assessment_synthetic_category_reviews; +DROP FUNCTION assessment_synthetic_category_review_refuse_change(); +DROP TRIGGER assessment_synthetic_category_review_guard ON assessment_synthetic_category_reviews; +DROP FUNCTION assessment_synthetic_category_review_guard(); +DROP TABLE assessment_synthetic_category_reviews; +DROP TRIGGER assessment_attempt_result_category_guard ON assessment_attempt_results; +DROP FUNCTION assessment_attempt_result_category_guard(); +DROP INDEX assessment_attempt_results_history_idx; +DROP INDEX assessment_attempt_results_attempt_owner_key; +ALTER TABLE assessment_attempt_results + DROP CONSTRAINT assessment_attempt_results_category_extension, + DROP COLUMN category_decision, + DROP COLUMN current_confirmed_grade, + DROP CONSTRAINT assessment_attempt_results_schema, + ADD CONSTRAINT assessment_attempt_results_schema CHECK (schema_version = 1); diff --git a/backend/db/migrations/00032_create_notification_inbox.sql b/backend/db/migrations/00032_create_notification_inbox.sql new file mode 100644 index 0000000..2ebfcd5 --- /dev/null +++ b/backend/db/migrations/00032_create_notification_inbox.sql @@ -0,0 +1,115 @@ +-- Inbox rows reference current product records instead of copying their +-- content. Recipient deletion removes the private inbox; organization context +-- remains retained while a source event refers to it. +-- +goose Up +CREATE TABLE notification_inbox_events ( + recipient_user_id uuid NOT NULL, + event_id uuid NOT NULL, + organization_id uuid NOT NULL, + event_type text NOT NULL, + schema_version integer NOT NULL, + source_type text NOT NULL, + source_id uuid NOT NULL, + occurred_at timestamptz NOT NULL, + read_at timestamptz, + CONSTRAINT notification_inbox_events_pkey PRIMARY KEY ( + recipient_user_id, event_id + ), + CONSTRAINT notification_inbox_events_recipient_fkey FOREIGN KEY ( + recipient_user_id + ) REFERENCES users (id) ON DELETE CASCADE, + CONSTRAINT notification_inbox_events_organization_fkey FOREIGN KEY ( + organization_id + ) REFERENCES organizations (id) ON DELETE RESTRICT, + CONSTRAINT notification_inbox_events_type_known CHECK ( + event_type = 'invitation.delivered' + AND schema_version = 1 + AND source_type = 'invitation' + ) +); + +-- Supports a recipient's chronological inbox and exact organization filters. +CREATE INDEX notification_inbox_events_recipient_occurred_idx +ON notification_inbox_events (recipient_user_id, occurred_at DESC, event_id DESC); + +CREATE INDEX notification_inbox_events_recipient_organization_occurred_idx +ON notification_inbox_events ( + recipient_user_id, organization_id, occurred_at DESC, event_id DESC +); + +-- The event reference is immutable. Only the first read timestamp may be +-- added; repeated mark-read calls may keep that timestamp unchanged. +-- +goose StatementBegin +CREATE FUNCTION notification_inbox_events_refuse_update() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.recipient_user_id IS NOT DISTINCT FROM OLD.recipient_user_id + AND NEW.event_id IS NOT DISTINCT FROM OLD.event_id + AND NEW.organization_id IS NOT DISTINCT FROM OLD.organization_id + AND NEW.event_type IS NOT DISTINCT FROM OLD.event_type + AND NEW.schema_version IS NOT DISTINCT FROM OLD.schema_version + AND NEW.source_type IS NOT DISTINCT FROM OLD.source_type + AND NEW.source_id IS NOT DISTINCT FROM OLD.source_id + AND NEW.occurred_at IS NOT DISTINCT FROM OLD.occurred_at + AND ( + NEW.read_at IS NOT DISTINCT FROM OLD.read_at + OR (OLD.read_at IS NULL AND NEW.read_at IS NOT NULL) + ) THEN + RETURN NEW; + END IF; + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'notification_inbox_events_immutable', + TABLE = 'notification_inbox_events', + MESSAGE = 'notification inbox event metadata is immutable'; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER notification_inbox_events_refuse_update +BEFORE UPDATE ON notification_inbox_events +FOR EACH ROW EXECUTE FUNCTION notification_inbox_events_refuse_update(); + +-- Prevent clearing a recipient's event marker while allowing account +-- deletion to cascade through private inbox rows. +-- +goose StatementBegin +CREATE FUNCTION notification_inbox_events_refuse_delete() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF pg_trigger_depth() > 1 THEN + RETURN OLD; + END IF; + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'notification_inbox_events_retained', + TABLE = 'notification_inbox_events', + MESSAGE = 'notification inbox events cannot be deleted directly'; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER notification_inbox_events_refuse_delete +BEFORE DELETE ON notification_inbox_events +FOR EACH ROW EXECUTE FUNCTION notification_inbox_events_refuse_delete(); + +-- A rollback must not silently remove recipient-visible history. +-- +goose Down +-- +goose StatementBegin +DO $$ +BEGIN + IF EXISTS (SELECT 1 FROM notification_inbox_events) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'notification_inbox_events_retained', + TABLE = 'notification_inbox_events', + MESSAGE = 'notification inbox records must be resolved before rollback'; + END IF; +END; +$$; +-- +goose StatementEnd + +DROP TRIGGER notification_inbox_events_refuse_update ON notification_inbox_events; +DROP FUNCTION notification_inbox_events_refuse_update(); +DROP TRIGGER notification_inbox_events_refuse_delete ON notification_inbox_events; +DROP FUNCTION notification_inbox_events_refuse_delete(); +DROP TABLE notification_inbox_events; diff --git a/backend/db/queries/assessment_results.sql b/backend/db/queries/assessment_results.sql new file mode 100644 index 0000000..f28217e --- /dev/null +++ b/backend/db/queries/assessment_results.sql @@ -0,0 +1,111 @@ +-- Stores the category decision and current grade captured at real-attempt +-- finalization. The base result document remains its original v1 shape. +-- name: InsertAssessmentAttemptResultV2 :exec +INSERT INTO assessment_attempt_results ( + attempt_id, user_id, result_snapshot, schema_version, category_decision, + current_confirmed_grade, kind, mode, outcome, product_policy_version_id, + product_policy_version, grading_policy_version_id, opening_id, + opening_manifest_sha256, training_binding_id, training_manifest_sha256, + bank_version, algorithm_version, rationale_rule, pass_mark_basis_points, + scored_items, raw_score, pass_points, decided_at +) VALUES ( + sqlc.arg(attempt_id), sqlc.arg(user_id), sqlc.arg(result_snapshot), 2, + sqlc.arg(category_decision)::jsonb, sqlc.narg(current_confirmed_grade), + sqlc.arg(kind), sqlc.arg(mode), sqlc.arg(outcome), sqlc.arg(product_policy_version_id), + sqlc.arg(product_policy_version), sqlc.arg(grading_policy_version_id), sqlc.arg(opening_id), + sqlc.arg(opening_manifest_sha256), NULL, NULL, sqlc.arg(bank_version), + sqlc.arg(algorithm_version), sqlc.arg(rationale_rule), sqlc.arg(pass_mark_basis_points), + sqlc.arg(scored_items), sqlc.arg(raw_score), sqlc.arg(pass_points), sqlc.arg(decided_at) +); + +-- Returns both immutable result versions. NULL category fields identify a +-- legacy v1 record and must not be reconstructed from current state. +-- name: GetAssessmentAttemptResultHistoryEntry :one +SELECT schema_version, result_snapshot::text, category_decision::text, current_confirmed_grade +FROM assessment_attempt_results +WHERE user_id = sqlc.arg(user_id) AND attempt_id = sqlc.arg(attempt_id); + +-- The caller validates and signs an opaque owner-bound cursor. This query +-- applies the keyset to the same stable order and fetches one extra row. +-- name: ListCandidateAssessmentResults :many +SELECT attempt_id, user_id, schema_version, result_snapshot::text, + category_decision::text, current_confirmed_grade, decided_at +FROM assessment_attempt_results +WHERE user_id = sqlc.arg(user_id) + AND kind IN ('root', 'corrective') + AND (sqlc.narg(cursor_decided_at)::timestamptz IS NULL OR + (decided_at, attempt_id) < + (sqlc.narg(cursor_decided_at)::timestamptz, sqlc.narg(cursor_attempt_id)::uuid)) +ORDER BY decided_at DESC, attempt_id DESC +LIMIT sqlc.arg(limit_count)::integer + 1; + +-- Acquired after C3, candidate/specialization scope, and attempt row locks. +-- This independent lock serializes current category upgrades for one scope. +-- name: LockCandidateAssessmentCategory :exec +SELECT pg_advisory_xact_lock(hashtextextended( + 'lincodex.assessment.category:candidate:' || sqlc.arg(candidate_id)::text || ':' || sqlc.arg(specialization)::text, + 0 +)); + +-- name: GetCandidateAssessmentCategory :one +SELECT candidate_id, specialization, grade, source_attempt_id, source_review_id, + product_policy_version_id, product_policy_version, grading_policy_version_id, + opening_id, opening_manifest_sha256, source, calibration_status, assigned_at +FROM candidate_assessment_categories +WHERE candidate_id = sqlc.arg(candidate_id) AND specialization = sqlc.arg(specialization); + +-- name: GetSyntheticCategoryReview :one +SELECT review.id, review.opening_id, review.category, review.source, + review.opening_manifest_sha256, review.product_policy_version_id, + review.product_policy_version, review.reviewed_by, review.reviewed_at +FROM assessment_synthetic_category_reviews AS review +JOIN assessment_category_openings AS opening ON opening.id = review.opening_id +WHERE review.opening_id = sqlc.arg(opening_id) + AND review.category = sqlc.arg(category) + AND review.source = 'synthetic_demo' + AND review.opening_manifest_sha256 = sqlc.arg(opening_manifest_sha256) + AND review.product_policy_version_id = sqlc.arg(product_policy_version_id) + AND review.product_policy_version = sqlc.arg(product_policy_version) + AND opening.policy_version_id = sqlc.arg(grading_policy_version_id); + +-- The application accepts only a validated immutable review snapshot. The +-- trigger independently checks the source opening, manifest and policy. +-- name: InsertSyntheticCategoryReview :exec +INSERT INTO assessment_synthetic_category_reviews ( + id, opening_id, category, source, opening_manifest_sha256, + product_policy_version_id, product_policy_version, reviewed_by, reviewed_at +) VALUES ( + sqlc.arg(id), sqlc.arg(opening_id), sqlc.arg(category), sqlc.arg(source), + sqlc.arg(opening_manifest_sha256), sqlc.arg(product_policy_version_id), + sqlc.arg(product_policy_version), sqlc.arg(reviewed_by), sqlc.arg(reviewed_at) +); + +-- Only strict grade upgrades replace the current row. The trigger enforces +-- the same monotonic rule as a final guard against adapter mistakes. +-- name: SaveCandidateAssessmentCategory :execrows +INSERT INTO candidate_assessment_categories ( + candidate_id, specialization, grade, source_attempt_id, source_review_id, + product_policy_version_id, product_policy_version, grading_policy_version_id, + opening_id, opening_manifest_sha256, source, calibration_status, assigned_at +) VALUES ( + sqlc.arg(candidate_id), sqlc.arg(specialization), sqlc.arg(grade), sqlc.arg(source_attempt_id), + sqlc.arg(source_review_id), sqlc.arg(product_policy_version_id), sqlc.arg(product_policy_version), + sqlc.arg(grading_policy_version_id), sqlc.arg(opening_id), sqlc.arg(opening_manifest_sha256), + sqlc.arg(source), sqlc.arg(calibration_status), sqlc.arg(assigned_at) +) +ON CONFLICT (candidate_id, specialization) DO UPDATE SET + grade = EXCLUDED.grade, + source_attempt_id = EXCLUDED.source_attempt_id, + source_review_id = EXCLUDED.source_review_id, + product_policy_version_id = EXCLUDED.product_policy_version_id, + product_policy_version = EXCLUDED.product_policy_version, + grading_policy_version_id = EXCLUDED.grading_policy_version_id, + opening_id = EXCLUDED.opening_id, + opening_manifest_sha256 = EXCLUDED.opening_manifest_sha256, + source = EXCLUDED.source, + calibration_status = EXCLUDED.calibration_status, + assigned_at = EXCLUDED.assigned_at +WHERE CASE candidate_assessment_categories.grade + WHEN 'intern' THEN 0 WHEN 'junior' THEN 1 WHEN 'middle' THEN 2 WHEN 'senior' THEN 3 ELSE -1 END + < CASE EXCLUDED.grade + WHEN 'intern' THEN 0 WHEN 'junior' THEN 1 WHEN 'middle' THEN 2 WHEN 'senior' THEN 3 ELSE -1 END; diff --git a/backend/db/queries/notification_inbox.sql b/backend/db/queries/notification_inbox.sql new file mode 100644 index 0000000..669f2e4 --- /dev/null +++ b/backend/db/queries/notification_inbox.sql @@ -0,0 +1,89 @@ +-- Store one recipient's reference to a delivered invitation event. The +-- unique key absorbs at-least-once redelivery without copying event content. +-- name: InsertNotificationInboxEvent :execrows +INSERT INTO notification_inbox_events ( + recipient_user_id, + event_id, + organization_id, + event_type, + schema_version, + source_type, + source_id, + occurred_at +) VALUES ( + sqlc.arg(recipient_user_id), + sqlc.arg(event_id), + sqlc.arg(organization_id), + sqlc.arg(event_type), + sqlc.arg(schema_version), + sqlc.arg(source_type), + sqlc.arg(source_id), + sqlc.arg(occurred_at) +) +ON CONFLICT (recipient_user_id, event_id) DO NOTHING; + +-- Read the existing row after a duplicate insert so the repository can reject +-- an event ID whose immutable metadata changed on redelivery. +-- name: GetNotificationInboxEvent :one +SELECT + recipient_user_id, + event_id, + organization_id, + event_type, + schema_version, + source_type, + source_id, + occurred_at, + read_at +FROM notification_inbox_events +WHERE recipient_user_id = sqlc.arg(recipient_user_id) + AND event_id = sqlc.arg(event_id); + +-- List only the authenticated recipient's rows, optionally narrowed to one +-- organization context. The caller resolves current source visibility before +-- returning content. +-- name: ListNotificationInboxEvents :many +SELECT + recipient_user_id, + event_id, + organization_id, + event_type, + schema_version, + source_type, + source_id, + occurred_at, + read_at +FROM notification_inbox_events +WHERE recipient_user_id = sqlc.arg(recipient_user_id) + AND ( + sqlc.narg(organization_id)::uuid IS NULL + OR organization_id = sqlc.narg(organization_id)::uuid + ) + AND ( + sqlc.narg(after_occurred_at)::timestamptz IS NULL + OR (occurred_at, event_id) < ( + sqlc.narg(after_occurred_at)::timestamptz, + sqlc.narg(after_event_id)::uuid + ) + ) +ORDER BY occurred_at DESC, event_id DESC +LIMIT sqlc.arg(page_limit); + +-- Persist the first read time under exact recipient and organization scope. +-- Repeated calls preserve the original read timestamp. +-- name: MarkNotificationInboxEventRead :one +UPDATE notification_inbox_events +SET read_at = COALESCE(read_at, sqlc.arg(read_at)::timestamptz) +WHERE recipient_user_id = sqlc.arg(recipient_user_id) + AND organization_id = sqlc.arg(organization_id) + AND event_id = sqlc.arg(event_id) +RETURNING + recipient_user_id, + event_id, + organization_id, + event_type, + schema_version, + source_type, + source_id, + occurred_at, + read_at; diff --git a/backend/internal/adapter/secondary/postgres/notification_inbox.go b/backend/internal/adapter/secondary/postgres/notification_inbox.go new file mode 100644 index 0000000..c5763dd --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/notification_inbox.go @@ -0,0 +1,243 @@ +package postgres + +import ( + "context" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgtype" + "github.com/jackc/pgx/v5/pgxpool" + + "lincodex/backend/internal/adapter/secondary/postgres/sqlc" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +var _ outbound.NotificationInboxRepository = notificationInboxRepository{} + +// NewNotificationInboxRepository creates a direct store for inbox operations. +// Transaction-bound callers can construct the same repository around the +// queries of their current UnitOfWork. +func NewNotificationInboxRepository(pool *pgxpool.Pool) outbound.NotificationInboxRepository { + return notificationInboxRepository{queries: sqlc.New(pool)} +} + +type notificationInboxRepository struct { + queries *sqlc.Queries +} + +func (repository notificationInboxRepository) Store( + ctx context.Context, + entry domain.NotificationInboxEntry, +) (bool, error) { + const location = "notificationInboxRepository.Store" + if err := validateInboxEntryForStore(entry); err != nil { + return false, fmt.Errorf("%s - validate event: %w", location, err) + } + _, isRead := entry.ReadAt() + if isRead { + return false, fmt.Errorf("%s - a delivered event must be unread: %w", location, domain.ErrInvalidNotificationInboxEntry) + } + rows, err := repository.queries.InsertNotificationInboxEvent(ctx, sqlc.InsertNotificationInboxEventParams{ + RecipientUserID: pgUUID(entry.RecipientUserID()), + EventID: pgUUID(entry.EventID()), + OrganizationID: pgUUID(entry.OrganizationID()), + EventType: string(entry.EventType()), + SchemaVersion: entry.SchemaVersion(), + SourceType: string(entry.SourceType()), + SourceID: pgUUID(entry.SourceID()), + OccurredAt: pgTime(entry.OccurredAt()), + }) + if err != nil { + return false, fmt.Errorf("%s - insert recipient event: %w", location, sanitizedDatabaseError(err)) + } + if rows == 1 { + return true, nil + } + stored, err := repository.queries.GetNotificationInboxEvent(ctx, sqlc.GetNotificationInboxEventParams{ + RecipientUserID: pgUUID(entry.RecipientUserID()), EventID: pgUUID(entry.EventID()), + }) + if errors.Is(err, pgx.ErrNoRows) { + return false, fmt.Errorf("%s - duplicate event disappeared before comparison: %w", location, outbound.ErrNotificationInboxEntryNotFound) + } + if err != nil { + return false, fmt.Errorf("%s - read duplicate event: %w", location, sanitizedDatabaseError(err)) + } + existing, err := notificationInboxEntryFromRow(stored) + if err != nil { + return false, fmt.Errorf("%s - restore duplicate event: %w", location, err) + } + if !sameNotificationInboxEvent(existing, entry) { + return false, fmt.Errorf("%s - event ID has different immutable metadata: %w", location, outbound.ErrNotificationInboxEventConflict) + } + return false, nil +} + +func (repository notificationInboxRepository) List( + ctx context.Context, + query outbound.NotificationInboxListQuery, +) (outbound.NotificationInboxPage, error) { + const location = "notificationInboxRepository.List" + if err := validateNotificationInboxListQuery(query); err != nil { + return outbound.NotificationInboxPage{}, fmt.Errorf("%s - validate page: %w", location, err) + } + params := sqlc.ListNotificationInboxEventsParams{ + RecipientUserID: pgUUID(query.RecipientUserID), + OrganizationID: notificationInboxOptionalUUID(query.OrganizationID), + AfterOccurredAt: pgOptionalTime(notificationInboxPositionTime(query.After)), + AfterEventID: notificationInboxPositionID(query.After), + PageLimit: query.Limit + 1, + } + rows, err := repository.queries.ListNotificationInboxEvents(ctx, params) + if err != nil { + return outbound.NotificationInboxPage{}, fmt.Errorf("%s - list recipient events: %w", location, sanitizedDatabaseError(err)) + } + page := outbound.NotificationInboxPage{HasMore: len(rows) > int(query.Limit)} + if page.HasMore { + rows = rows[:query.Limit] + } + page.Items = make([]domain.NotificationInboxEntry, 0, len(rows)) + for _, row := range rows { + entry, err := notificationInboxEntryFromRow(row) + if err != nil { + return outbound.NotificationInboxPage{}, fmt.Errorf("%s - restore event row: %w", location, err) + } + if entry.RecipientUserID() != query.RecipientUserID || (query.OrganizationID != nil && entry.OrganizationID() != *query.OrganizationID) { + return outbound.NotificationInboxPage{}, fmt.Errorf("%s - database returned an event outside the recipient scope", location) + } + page.Items = append(page.Items, entry) + } + return page, nil +} + +func (repository notificationInboxRepository) MarkRead( + ctx context.Context, + recipientUserID uuid.UUID, + organizationID uuid.UUID, + eventID uuid.UUID, + at time.Time, +) (domain.NotificationInboxEntry, error) { + const location = "notificationInboxRepository.MarkRead" + if recipientUserID == uuid.Nil || organizationID == uuid.Nil || eventID == uuid.Nil || at.IsZero() { + return domain.NotificationInboxEntry{}, fmt.Errorf("%s - recipient, organization, event, and read time are required: %w", location, domain.ErrInvalidNotificationInboxEntry) + } + row, err := repository.queries.MarkNotificationInboxEventRead(ctx, sqlc.MarkNotificationInboxEventReadParams{ + RecipientUserID: pgUUID(recipientUserID), OrganizationID: pgUUID(organizationID), + EventID: pgUUID(eventID), ReadAt: pgTime(at), + }) + if errors.Is(err, pgx.ErrNoRows) { + return domain.NotificationInboxEntry{}, fmt.Errorf("%s - read event: %w", location, outbound.ErrNotificationInboxEntryNotFound) + } + if err != nil { + return domain.NotificationInboxEntry{}, fmt.Errorf("%s - persist read time: %w", location, sanitizedDatabaseError(err)) + } + entry, err := notificationInboxEntryFromRow(row) + if err != nil { + return domain.NotificationInboxEntry{}, fmt.Errorf("%s - restore read event: %w", location, err) + } + return entry, nil +} + +func validateInboxEntryForStore(entry domain.NotificationInboxEntry) error { + _, err := domain.RestoreNotificationInboxEntry(domain.NotificationInboxEntryInput{ + EventID: entry.EventID(), RecipientUserID: entry.RecipientUserID(), OrganizationID: entry.OrganizationID(), + EventType: entry.EventType(), SchemaVersion: entry.SchemaVersion(), + SourceType: entry.SourceType(), SourceID: entry.SourceID(), OccurredAt: entry.OccurredAt(), + }) + return err +} + +func validateNotificationInboxListQuery(query outbound.NotificationInboxListQuery) error { + if query.RecipientUserID == uuid.Nil || query.Limit < 1 || query.Limit > outbound.MaxNotificationInboxPageSize { + return domain.ErrInvalidNotificationInboxEntry + } + if query.OrganizationID != nil && *query.OrganizationID == uuid.Nil { + return domain.ErrInvalidNotificationInboxEntry + } + if query.After != nil && (query.After.EventID == uuid.Nil || query.After.OccurredAt.IsZero()) { + return domain.ErrInvalidNotificationInboxEntry + } + return nil +} + +func notificationInboxPositionTime(position *outbound.NotificationInboxPosition) *time.Time { + if position == nil { + return nil + } + return &position.OccurredAt +} + +func notificationInboxPositionID(position *outbound.NotificationInboxPosition) pgtype.UUID { + if position == nil { + return pgtype.UUID{} + } + return pgUUID(position.EventID) +} + +func notificationInboxOptionalUUID(value *uuid.UUID) pgtype.UUID { + if value == nil { + return pgtype.UUID{} + } + return pgUUID(*value) +} + +func notificationInboxEntryFromRow(row sqlc.GetNotificationInboxEventRow) (domain.NotificationInboxEntry, error) { + return restoreNotificationInboxEntryRow( + row.RecipientUserID, row.EventID, row.OrganizationID, row.EventType, + row.SchemaVersion, row.SourceType, row.SourceID, row.OccurredAt, row.ReadAt, + ) +} + +func notificationInboxEntryFromListRow(row sqlc.ListNotificationInboxEventsRow) (domain.NotificationInboxEntry, error) { + return restoreNotificationInboxEntryRow( + row.RecipientUserID, row.EventID, row.OrganizationID, row.EventType, + row.SchemaVersion, row.SourceType, row.SourceID, row.OccurredAt, row.ReadAt, + ) +} + +func notificationInboxEntryFromReadRow(row sqlc.MarkNotificationInboxEventReadRow) (domain.NotificationInboxEntry, error) { + return restoreNotificationInboxEntryRow( + row.RecipientUserID, row.EventID, row.OrganizationID, row.EventType, + row.SchemaVersion, row.SourceType, row.SourceID, row.OccurredAt, row.ReadAt, + ) +} + +func restoreNotificationInboxEntryRow( + recipientUserID, eventID, organizationID pgtype.UUID, + eventType string, + schemaVersion int32, + sourceType string, + sourceID pgtype.UUID, + occurredAt pgtype.Timestamptz, + readAt pgtype.Timestamptz, +) (domain.NotificationInboxEntry, error) { + if !recipientUserID.Valid || !eventID.Valid || !organizationID.Valid || !sourceID.Valid || !occurredAt.Valid || + recipientUserID.Bytes == uuid.Nil || eventID.Bytes == uuid.Nil || organizationID.Bytes == uuid.Nil || sourceID.Bytes == uuid.Nil { + return domain.NotificationInboxEntry{}, errors.New("postgres.restoreNotificationInboxEntryRow - stored identity or time is invalid") + } + var readAtValue *time.Time + if readAt.Valid { + value := readAt.Time + readAtValue = &value + } + entry, err := domain.RestoreNotificationInboxEntry(domain.NotificationInboxEntryInput{ + EventID: eventID.Bytes, RecipientUserID: recipientUserID.Bytes, + OrganizationID: organizationID.Bytes, EventType: domain.NotificationInboxEventType(eventType), + SchemaVersion: schemaVersion, SourceType: domain.NotificationInboxSourceType(sourceType), + SourceID: sourceID.Bytes, OccurredAt: occurredAt.Time, ReadAt: readAtValue, + }) + if err != nil { + return domain.NotificationInboxEntry{}, fmt.Errorf("postgres.restoreNotificationInboxEntryRow - restore metadata: %w", err) + } + return entry, nil +} + +func sameNotificationInboxEvent(left, right domain.NotificationInboxEntry) bool { + return left.EventID() == right.EventID() && left.RecipientUserID() == right.RecipientUserID() && + left.OrganizationID() == right.OrganizationID() && left.EventType() == right.EventType() && + left.SchemaVersion() == right.SchemaVersion() && left.SourceType() == right.SourceType() && + left.SourceID() == right.SourceID() && left.OccurredAt().Equal(right.OccurredAt()) +} diff --git a/backend/internal/bootstrap/assessment.go b/backend/internal/bootstrap/assessment.go index 8c2d56d..7d31566 100644 --- a/backend/internal/bootstrap/assessment.go +++ b/backend/internal/bootstrap/assessment.go @@ -33,7 +33,15 @@ func newAssessmentHandler( return nil, nil, fmt.Errorf("bootstrap.newAssessmentHandler - create pool: %w", err) } transactor := postgres.NewTransactor(pool) - service, err := assessment.NewAttemptService(transactor, transactor, keyring, time.Now) + service, err := assessment.NewAttemptServiceWithCategorySettings( + transactor, + transactor, + keyring, + time.Now, + assessment.AssessmentCategoryDecisionSettings{ + SyntheticDemoAssignmentsEnabled: settings.AssessmentDemoCategoriesEnabled, + }, + ) if err != nil { pool.Close() return nil, nil, fmt.Errorf("bootstrap.newAssessmentHandler - create service: %w", err) diff --git a/backend/internal/domain/assessment_category.go b/backend/internal/domain/assessment_category.go new file mode 100644 index 0000000..ce2acda --- /dev/null +++ b/backend/internal/domain/assessment_category.go @@ -0,0 +1,675 @@ +package domain + +import ( + "errors" + "fmt" + "time" + + "github.com/google/uuid" +) + +var ErrInvalidAssessmentCategory = errors.New("invalid assessment category") + +type AssessmentCategoryDecisionStatus string + +const ( + AssessmentCategoryDecisionNotEligible AssessmentCategoryDecisionStatus = "not_eligible" + AssessmentCategoryDecisionNotConfirmed AssessmentCategoryDecisionStatus = "not_confirmed" + AssessmentCategoryDecisionAssigned AssessmentCategoryDecisionStatus = "assigned" + AssessmentCategoryDecisionUnchanged AssessmentCategoryDecisionStatus = "unchanged" + AssessmentCategoryDecisionTrainingOnly AssessmentCategoryDecisionStatus = "training_only" +) + +const ( + AssessmentAttemptResultHistorySchemaV1 int32 = 1 + AssessmentAttemptResultHistorySchemaV2 int32 = 2 +) + +type AssessmentCategoryDecisionMethod string + +const AssessmentCategoryDecisionDemoBasicPassMark AssessmentCategoryDecisionMethod = "demo_basic_pass_mark" + +type AssessmentCategoryCalibrationStatus string + +const AssessmentCategoryCalibrationUncalibrated AssessmentCategoryCalibrationStatus = "uncalibrated" + +type AssessmentCategorySource string + +const AssessmentCategorySourceSyntheticDemo AssessmentCategorySource = "synthetic_demo" + +// AssessmentSyntheticCategoryReviewSnapshot pins the reviewed synthetic bank +// opening to the exact product policy under which demo categories may be assigned. +type AssessmentSyntheticCategoryReviewSnapshot struct { + ID uuid.UUID + OpeningID uuid.UUID + Category AssessmentCategory + Source AssessmentCategorySource + OpeningManifestHash [32]byte + ProductPolicyVersionID PolicyVersionID + ProductPolicyVersion int32 + ReviewedBy AssessmentOperator + ReviewedAt time.Time +} + +// AssessmentSyntheticCategoryReview is an immutable review attestation used +// only when the separate synthetic-category config gate is enabled. +type AssessmentSyntheticCategoryReview struct { + snapshot AssessmentSyntheticCategoryReviewSnapshot +} + +func NewAssessmentSyntheticCategoryReview( + snapshot AssessmentSyntheticCategoryReviewSnapshot, +) (AssessmentSyntheticCategoryReview, error) { + const location = "domain.NewAssessmentSyntheticCategoryReview" + review, err := RestoreAssessmentSyntheticCategoryReview(snapshot) + if err != nil { + return AssessmentSyntheticCategoryReview{}, fmt.Errorf("%s - validate review: %w", location, err) + } + return review, nil +} + +func RestoreAssessmentSyntheticCategoryReview( + snapshot AssessmentSyntheticCategoryReviewSnapshot, +) (AssessmentSyntheticCategoryReview, error) { + const location = "domain.RestoreAssessmentSyntheticCategoryReview" + operator, operatorErr := ParseAssessmentOperator(string(snapshot.ReviewedBy)) + category, categoryErr := ParseAssessmentCategory(string(snapshot.Category)) + if snapshot.ID == uuid.Nil || snapshot.OpeningID == uuid.Nil || snapshot.OpeningManifestHash == [32]byte{} || + snapshot.ProductPolicyVersionID.IsZero() || snapshot.ProductPolicyVersion <= 0 || snapshot.ReviewedAt.IsZero() || + snapshot.Source != AssessmentCategorySourceSyntheticDemo || + operatorErr != nil || operator != snapshot.ReviewedBy || categoryErr != nil || category != snapshot.Category { + return AssessmentSyntheticCategoryReview{}, fmt.Errorf("%s - review identity or pins are invalid: %w", location, ErrInvalidAssessmentCategory) + } + snapshot.ReviewedAt = canonicalAssessmentTime(snapshot.ReviewedAt) + return AssessmentSyntheticCategoryReview{snapshot: snapshot}, nil +} + +func (review AssessmentSyntheticCategoryReview) IsZero() bool { return review.snapshot.ID == uuid.Nil } + +func (review AssessmentSyntheticCategoryReview) Snapshot() AssessmentSyntheticCategoryReviewSnapshot { + return review.snapshot +} + +// CandidateAssessmentCategorySnapshot is the private current-state and audit +// record. It contains candidate and source identifiers and must not be returned +// directly to an employer-facing API. +type CandidateAssessmentCategorySnapshot struct { + CandidateID uuid.UUID + Specialization SpecializationCode + Grade GradeCode + SourceAttemptID AssessmentAttemptID + SourceReviewID uuid.UUID + ProductPolicyVersionID PolicyVersionID + ProductPolicyVersion int32 + OpeningID uuid.UUID + OpeningManifestHash [32]byte + Source AssessmentCategorySource + CalibrationStatus AssessmentCategoryCalibrationStatus + AssignedAt time.Time +} + +// CandidateAssessmentCategory is the current confirmed category for one +// candidate specialization. +type CandidateAssessmentCategory struct { + snapshot CandidateAssessmentCategorySnapshot +} + +func RestoreCandidateAssessmentCategory( + snapshot CandidateAssessmentCategorySnapshot, +) (CandidateAssessmentCategory, error) { + const location = "domain.RestoreCandidateAssessmentCategory" + if snapshot.CandidateID == uuid.Nil || !snapshot.Specialization.IsKnown() || !snapshot.Grade.IsKnown() || + snapshot.SourceAttemptID.IsZero() || snapshot.SourceReviewID == uuid.Nil || + snapshot.ProductPolicyVersionID.IsZero() || snapshot.ProductPolicyVersion <= 0 || + snapshot.OpeningID == uuid.Nil || snapshot.OpeningManifestHash == [32]byte{} || + snapshot.Source != AssessmentCategorySourceSyntheticDemo || + snapshot.CalibrationStatus != AssessmentCategoryCalibrationUncalibrated || snapshot.AssignedAt.IsZero() { + return CandidateAssessmentCategory{}, fmt.Errorf("%s - current category or source is invalid: %w", location, ErrInvalidAssessmentCategory) + } + snapshot.AssignedAt = canonicalAssessmentTime(snapshot.AssignedAt) + return CandidateAssessmentCategory{snapshot: snapshot}, nil +} + +func (category CandidateAssessmentCategory) IsZero() bool { + return category.snapshot.CandidateID == uuid.Nil +} + +func (category CandidateAssessmentCategory) Snapshot() CandidateAssessmentCategorySnapshot { + return category.snapshot +} + +// AssessmentCategoryDecisionSnapshot is the allowlisted category extension +// for one immutable result. It contains no private answer or item data. +type AssessmentCategoryDecisionSnapshot struct { + AttemptID AssessmentAttemptID + BankCategory AssessmentCategory + Specialization *SpecializationCode + AttemptedGrade *GradeCode + PreviousGrade *GradeCode + CurrentGrade *GradeCode + Status AssessmentCategoryDecisionStatus + Method AssessmentCategoryDecisionMethod + ProductPolicyVersionID PolicyVersionID + ProductPolicyVersion int32 + GradingPolicyVersionID PolicyVersionID + OpeningID uuid.UUID + OpeningManifestHash [32]byte + ReviewID uuid.UUID + Source AssessmentCategorySource + CalibrationStatus AssessmentCategoryCalibrationStatus + DecidedAt time.Time +} + +// AssessmentCategoryDecision is the immutable category outcome associated +// with a completed result. Current category changes only for a higher passing +// grade from a reviewed synthetic source. +type AssessmentCategoryDecision struct { + snapshot AssessmentCategoryDecisionSnapshot + current *CandidateAssessmentCategory +} + +type AssessmentCategoryDecisionInput struct { + Attempt AssessmentAttempt + Result AssessmentAttemptResultSnapshot + Policy PolicyVersion + Review *AssessmentSyntheticCategoryReview + Current *CandidateAssessmentCategory + SyntheticDemoCategoryAssignmentEnabled bool +} + +func DecideAssessmentCategory( + input AssessmentCategoryDecisionInput, +) (AssessmentCategoryDecision, error) { + const location = "domain.DecideAssessmentCategory" + result, err := RestoreAssessmentAttemptResultSnapshot(input.Result) + if err != nil || !assessmentResultMatchesAttempt(input.Attempt, result) { + return AssessmentCategoryDecision{}, fmt.Errorf("%s - result and attempt do not match: %w", location, ErrInvalidAssessmentCategory) + } + attempt := input.Attempt.Snapshot() + if input.Current != nil && input.Current.snapshot.CandidateID != attempt.UserID { + return AssessmentCategoryDecision{}, fmt.Errorf("%s - current category belongs to another candidate: %w", location, ErrInvalidAssessmentCategory) + } + if attempt.Kind == AssessmentAttemptKindDemoExpress { + return restoreDecision(newTrainingOnlyCategoryDecision(attempt, result), input.Current) + } + if attempt.Kind != AssessmentAttemptKindRoot && attempt.Kind != AssessmentAttemptKindCorrective { + return AssessmentCategoryDecision{}, fmt.Errorf("%s - attempt kind cannot produce a category: %w", location, ErrInvalidAssessmentCategory) + } + if attempt.Specialization == nil || attempt.TargetGrade == nil || !input.PolicyMatchesResult(result) { + return AssessmentCategoryDecision{}, fmt.Errorf("%s - track or pinned policy is invalid: %w", location, ErrInvalidAssessmentCategory) + } + if input.Current != nil && !currentCategoryMatchesAttempt(input.Current, attempt) { + return AssessmentCategoryDecision{}, fmt.Errorf("%s - current category is outside the attempt scope: %w", location, ErrInvalidAssessmentCategory) + } + return decideReviewedSyntheticCategory(input, attempt, result) +} + +func decideReviewedSyntheticCategory( + input AssessmentCategoryDecisionInput, + attempt AssessmentAttemptSnapshot, + result AssessmentAttemptResultSnapshot, +) (AssessmentCategoryDecision, error) { + decision := newRealCategoryDecision(attempt, result, input.Current) + if !input.SyntheticDemoCategoryAssignmentEnabled || !eligibleSyntheticCategoryPolicy(input.Policy, result) || + !reviewMatchesCategoryAttempt(input.Review, attempt, result) { + return restoreDecision(decision, input.Current) + } + decision.Status = AssessmentCategoryDecisionNotConfirmed + decision.Method = AssessmentCategoryDecisionDemoBasicPassMark + decision.ReviewID = input.Review.snapshot.ID + decision.Source = AssessmentCategorySourceSyntheticDemo + decision.CalibrationStatus = AssessmentCategoryCalibrationUncalibrated + if result.Outcome != AssessmentAttemptOutcomeConfirmed { + return restoreDecision(decision, input.Current) + } + if input.Current != nil && gradeRank(*attempt.TargetGrade) <= gradeRank(input.Current.snapshot.Grade) { + decision.Status = AssessmentCategoryDecisionUnchanged + return restoreDecision(decision, input.Current) + } + return assignSyntheticCategory(decision, attempt, result, input) +} + +func assignSyntheticCategory( + decision AssessmentCategoryDecisionSnapshot, + attempt AssessmentAttemptSnapshot, + result AssessmentAttemptResultSnapshot, + input AssessmentCategoryDecisionInput, +) (AssessmentCategoryDecision, error) { + decision.Status = AssessmentCategoryDecisionAssigned + decision.CurrentGrade = clonePointer(attempt.TargetGrade) + current, err := RestoreCandidateAssessmentCategory(CandidateAssessmentCategorySnapshot{ + CandidateID: attempt.UserID, Specialization: *attempt.Specialization, Grade: *attempt.TargetGrade, + SourceAttemptID: attempt.ID, SourceReviewID: input.Review.snapshot.ID, + ProductPolicyVersionID: result.Pins.ProductPolicyVersionID, ProductPolicyVersion: result.Pins.ProductPolicyVersion, + OpeningID: result.Pins.OpeningID, OpeningManifestHash: result.Pins.OpeningManifestHash, + Source: AssessmentCategorySourceSyntheticDemo, CalibrationStatus: AssessmentCategoryCalibrationUncalibrated, + AssignedAt: result.DecidedAt, + }) + if err != nil { + return AssessmentCategoryDecision{}, fmt.Errorf("domain.assignSyntheticCategory - build current category: %w", err) + } + return restoreDecision(decision, ¤t) +} + +func (input AssessmentCategoryDecisionInput) PolicyMatchesResult(result AssessmentAttemptResultSnapshot) bool { + return !input.Policy.IsZero() && input.Policy.Key() == ProductPolicyKey && + input.Policy.ID() == result.Pins.ProductPolicyVersionID && + input.Policy.Version() == result.Pins.ProductPolicyVersion +} + +func newTrainingOnlyCategoryDecision( + attempt AssessmentAttemptSnapshot, + result AssessmentAttemptResultSnapshot, +) AssessmentCategoryDecisionSnapshot { + return AssessmentCategoryDecisionSnapshot{ + AttemptID: attempt.ID, Status: AssessmentCategoryDecisionTrainingOnly, + ProductPolicyVersionID: result.Pins.ProductPolicyVersionID, + ProductPolicyVersion: result.Pins.ProductPolicyVersion, DecidedAt: result.DecidedAt, + } +} + +func newRealCategoryDecision( + attempt AssessmentAttemptSnapshot, + result AssessmentAttemptResultSnapshot, + current *CandidateAssessmentCategory, +) AssessmentCategoryDecisionSnapshot { + decision := AssessmentCategoryDecisionSnapshot{ + AttemptID: attempt.ID, BankCategory: attempt.BankCategory, + Specialization: clonePointer(attempt.Specialization), AttemptedGrade: clonePointer(attempt.TargetGrade), + Status: AssessmentCategoryDecisionNotEligible, + ProductPolicyVersionID: result.Pins.ProductPolicyVersionID, + ProductPolicyVersion: result.Pins.ProductPolicyVersion, + GradingPolicyVersionID: result.Pins.GradingPolicyVersionID, + OpeningID: result.Pins.OpeningID, OpeningManifestHash: result.Pins.OpeningManifestHash, + DecidedAt: result.DecidedAt, + } + if current != nil { + previous := current.snapshot.Grade + decision.PreviousGrade = &previous + decision.CurrentGrade = &previous + } + return decision +} + +func eligibleSyntheticCategoryPolicy(policy PolicyVersion, result AssessmentAttemptResultSnapshot) bool { + product := policy.Policy() + return policy.Kind() == PolicyKindDemo && policy.Key() == ProductPolicyKey && + sameAssessmentPolicy(product.Assessment, DemoProductPolicyV2().Assessment) && + result.Attempt.Mode == AssessmentAttemptModeDemoBasic && result.Rationale.Rule == assessmentResultRuleBasicPassMark && + int32(product.Assessment.Attempt.BasicPassMark) == result.Rationale.PassMarkBasisPoints && + (result.Outcome == AssessmentAttemptOutcomeConfirmed || result.Outcome == AssessmentAttemptOutcomeNotConfirmed) +} + +func sameAssessmentPolicy(left, right AssessmentPolicy) bool { + return sameAssessmentPolicyRules(left, right) && + sameOptionalAssessmentAttemptPolicy(left.Attempt, right.Attempt) && + sameOptionalAssessmentTrainingPolicy(left.Training, right.Training) +} + +func sameAssessmentPolicyRules(left, right AssessmentPolicy) bool { + return left.Calibration == right.Calibration && left.SameGradeRetryAfter == right.SameGradeRetryAfter && + left.MaxAttemptsPerWindow == right.MaxAttemptsPerWindow && left.AttemptWindow == right.AttemptWindow && + left.PromotionMinInterval == right.PromotionMinInterval && left.ConfirmationThreshold == right.ConfirmationThreshold && + left.HighStrengthThreshold == right.HighStrengthThreshold && left.PracticeRequired == right.PracticeRequired && + left.StopRule == right.StopRule +} + +func sameOptionalAssessmentAttemptPolicy(left, right *AssessmentAttemptPolicy) bool { + if left == nil || right == nil { + return left == right + } + return *left == *right +} + +func sameOptionalAssessmentTrainingPolicy(left, right *AssessmentTrainingPolicy) bool { + if left == nil || right == nil { + return left == right + } + return *left == *right +} + +func reviewMatchesCategoryAttempt( + review *AssessmentSyntheticCategoryReview, + attempt AssessmentAttemptSnapshot, + result AssessmentAttemptResultSnapshot, +) bool { + if review == nil || review.IsZero() { + return false + } + snapshot := review.snapshot + return !snapshot.ReviewedAt.After(result.DecidedAt) && + snapshot.OpeningID == result.Pins.OpeningID && snapshot.Category == attempt.BankCategory && + snapshot.OpeningManifestHash == result.Pins.OpeningManifestHash && + snapshot.ProductPolicyVersionID == result.Pins.ProductPolicyVersionID && + snapshot.ProductPolicyVersion == result.Pins.ProductPolicyVersion +} + +func assessmentResultMatchesAttempt(attempt AssessmentAttempt, result AssessmentAttemptResultSnapshot) bool { + if !assessmentAttemptCompletedMatchesResult(attempt, result) || !assessmentAttemptPublicMatchesResult(attempt, result) { + return false + } + return assessmentAttemptVersionsMatchResult(attempt.Snapshot().Versions, result.Pins) +} + +func assessmentAttemptCompletedMatchesResult(attempt AssessmentAttempt, result AssessmentAttemptResultSnapshot) bool { + return !attempt.IsZero() && attempt.State() == AssessmentAttemptStateCompleted && + result.Attempt.ID == attempt.ID() && result.Attempt.Kind == attempt.Kind() && + result.Attempt.Mode == attempt.Mode() && result.Outcome == attempt.snapshot.Outcome && + result.DecidedAt.Equal(attempt.snapshot.EndedAt) +} + +func assessmentAttemptPublicMatchesResult(attempt AssessmentAttempt, result AssessmentAttemptResultSnapshot) bool { + public := attempt.PublicSnapshot() + return public.PolicyVersion == result.Attempt.PolicyVersion && public.BankVersion == result.Attempt.BankVersion && + public.AlgorithmVersion == result.Attempt.AlgorithmVersion && + sameSpecialization(public.Specialization, result.Attempt.Specialization) && + sameGrade(public.TargetGrade, result.Attempt.TargetGrade) +} + +func assessmentAttemptVersionsMatchResult(versions AssessmentAttemptVersions, pins AssessmentAttemptResultPins) bool { + return versions.ProductPolicyVersionID == pins.ProductPolicyVersionID && versions.ProductPolicyVersion == pins.ProductPolicyVersion && + versions.GradingPolicyVersionID == pins.GradingPolicyVersionID && versions.OpeningID == pins.OpeningID && + versions.OpeningManifestHash == pins.OpeningManifestHash && versions.TrainingBindingID == pins.TrainingBindingID && + versions.TrainingManifestHash == pins.TrainingManifestHash && versions.BankVersion == pins.BankVersion && + versions.AlgorithmVersion == pins.AlgorithmVersion +} + +func currentCategoryMatchesAttempt(current *CandidateAssessmentCategory, attempt AssessmentAttemptSnapshot) bool { + return current != nil && !current.IsZero() && attempt.Specialization != nil && + current.snapshot.CandidateID == attempt.UserID && current.snapshot.Specialization == *attempt.Specialization +} + +func restoreDecision( + snapshot AssessmentCategoryDecisionSnapshot, + current *CandidateAssessmentCategory, +) (AssessmentCategoryDecision, error) { + const location = "domain.restoreDecision" + if err := validateAssessmentCategoryDecision(snapshot); err != nil { + return AssessmentCategoryDecision{}, fmt.Errorf("%s - decision is invalid: %w", location, err) + } + cloned := snapshot + cloned.Specialization = clonePointer(snapshot.Specialization) + cloned.AttemptedGrade = clonePointer(snapshot.AttemptedGrade) + cloned.PreviousGrade = clonePointer(snapshot.PreviousGrade) + cloned.CurrentGrade = clonePointer(snapshot.CurrentGrade) + return AssessmentCategoryDecision{snapshot: cloned, current: current}, nil +} + +// RestoreAssessmentCategoryDecision validates a stored immutable decision. +func RestoreAssessmentCategoryDecision(snapshot AssessmentCategoryDecisionSnapshot) (AssessmentCategoryDecision, error) { + return restoreDecision(snapshot, nil) +} + +func validateAssessmentCategoryDecision(snapshot AssessmentCategoryDecisionSnapshot) error { + if snapshot.AttemptID.IsZero() || snapshot.DecidedAt.IsZero() { + return ErrInvalidAssessmentCategory + } + if snapshot.Status == AssessmentCategoryDecisionTrainingOnly { + return validateTrainingOnlyCategoryDecision(snapshot) + } + category, categoryErr := ParseAssessmentCategory(string(snapshot.BankCategory)) + if categoryErr != nil || category != snapshot.BankCategory { + return ErrInvalidAssessmentCategory + } + if !validRealCategoryDecisionTrack(snapshot) || !validRealCategoryDecisionPins(snapshot) || !validRealCategoryDecisionGrades(snapshot) { + return ErrInvalidAssessmentCategory + } + return validateCategoryDecisionStatus(snapshot) +} + +func validateTrainingOnlyCategoryDecision(snapshot AssessmentCategoryDecisionSnapshot) error { + if snapshot.Specialization != nil || snapshot.AttemptedGrade != nil || snapshot.PreviousGrade != nil || snapshot.CurrentGrade != nil || + snapshot.Method != "" || snapshot.ReviewID != uuid.Nil || snapshot.Source != "" || snapshot.CalibrationStatus != "" { + return ErrInvalidAssessmentCategory + } + return nil +} + +func validRealCategoryDecisionPins(snapshot AssessmentCategoryDecisionSnapshot) bool { + return !snapshot.ProductPolicyVersionID.IsZero() && snapshot.ProductPolicyVersion > 0 && + !snapshot.GradingPolicyVersionID.IsZero() && snapshot.OpeningID != uuid.Nil && snapshot.OpeningManifestHash != [32]byte{} +} + +func validRealCategoryDecisionGrades(snapshot AssessmentCategoryDecisionSnapshot) bool { + return (snapshot.PreviousGrade == nil || snapshot.PreviousGrade.IsKnown()) && + (snapshot.CurrentGrade == nil || snapshot.CurrentGrade.IsKnown()) +} + +func validateCategoryDecisionStatus(snapshot AssessmentCategoryDecisionSnapshot) error { + switch snapshot.Status { + case AssessmentCategoryDecisionNotEligible: + return validateNotEligibleCategoryDecision(snapshot) + case AssessmentCategoryDecisionNotConfirmed: + return validateNotConfirmedCategoryDecision(snapshot) + case AssessmentCategoryDecisionAssigned: + return validateAssignedCategoryDecision(snapshot) + case AssessmentCategoryDecisionUnchanged: + return validateUnchangedCategoryDecision(snapshot) + case AssessmentCategoryDecisionTrainingOnly: + return ErrInvalidAssessmentCategory + default: + return ErrInvalidAssessmentCategory + } +} + +func validateNotEligibleCategoryDecision(snapshot AssessmentCategoryDecisionSnapshot) error { + if snapshot.ReviewID != uuid.Nil || snapshot.Method != "" || snapshot.Source != "" || + snapshot.CalibrationStatus != "" || !sameGrade(snapshot.CurrentGrade, snapshot.PreviousGrade) { + return ErrInvalidAssessmentCategory + } + return nil +} + +func validateNotConfirmedCategoryDecision(snapshot AssessmentCategoryDecisionSnapshot) error { + if !hasSyntheticReviewDecisionPins(snapshot) || !sameGrade(snapshot.CurrentGrade, snapshot.PreviousGrade) { + return ErrInvalidAssessmentCategory + } + return nil +} + +func validateAssignedCategoryDecision(snapshot AssessmentCategoryDecisionSnapshot) error { + if !hasSyntheticReviewDecisionPins(snapshot) || snapshot.CurrentGrade == nil || + *snapshot.CurrentGrade != *snapshot.AttemptedGrade || snapshot.PreviousGrade != nil && + gradeRank(*snapshot.CurrentGrade) <= gradeRank(*snapshot.PreviousGrade) { + return ErrInvalidAssessmentCategory + } + return nil +} + +func validateUnchangedCategoryDecision(snapshot AssessmentCategoryDecisionSnapshot) error { + if !hasSyntheticReviewDecisionPins(snapshot) || snapshot.PreviousGrade == nil || snapshot.CurrentGrade == nil || + *snapshot.CurrentGrade != *snapshot.PreviousGrade || + gradeRank(*snapshot.AttemptedGrade) > gradeRank(*snapshot.PreviousGrade) { + return ErrInvalidAssessmentCategory + } + return nil +} + +func hasSyntheticReviewDecisionPins(snapshot AssessmentCategoryDecisionSnapshot) bool { + return snapshot.ReviewID != uuid.Nil && snapshot.Method == AssessmentCategoryDecisionDemoBasicPassMark && + snapshot.Source == AssessmentCategorySourceSyntheticDemo && + snapshot.CalibrationStatus == AssessmentCategoryCalibrationUncalibrated +} + +func validRealCategoryDecisionTrack(snapshot AssessmentCategoryDecisionSnapshot) bool { + return snapshot.Specialization != nil && snapshot.Specialization.IsKnown() && + snapshot.AttemptedGrade != nil && snapshot.AttemptedGrade.IsKnown() +} + +func sameGrade(left, right *GradeCode) bool { + if left == nil || right == nil { + return left == nil && right == nil + } + return *left == *right +} + +func sameSpecialization(left, right *SpecializationCode) bool { + if left == nil || right == nil { + return left == nil && right == nil + } + return *left == *right +} + +func gradeRank(grade GradeCode) int { + switch grade { + case GradeIntern: + return 0 + case GradeJunior: + return 1 + case GradeMiddle: + return 2 + case GradeSenior: + return 3 + default: + return -1 + } +} + +func (decision AssessmentCategoryDecision) Snapshot() AssessmentCategoryDecisionSnapshot { + snapshot := decision.snapshot + snapshot.Specialization = clonePointer(decision.snapshot.Specialization) + snapshot.AttemptedGrade = clonePointer(decision.snapshot.AttemptedGrade) + snapshot.PreviousGrade = clonePointer(decision.snapshot.PreviousGrade) + snapshot.CurrentGrade = clonePointer(decision.snapshot.CurrentGrade) + return snapshot +} + +func (decision AssessmentCategoryDecision) ShouldUpdateCurrent() bool { + return decision.snapshot.Status == AssessmentCategoryDecisionAssigned && decision.current != nil +} + +func (decision AssessmentCategoryDecision) CurrentCategory() (CandidateAssessmentCategory, bool) { + if decision.current != nil { + return *decision.current, true + } + return CandidateAssessmentCategory{}, false +} + +// AssessmentAttemptResultHistoryEntry is a read-side projection of the +// immutable result store. V1 entries have no category decision and therefore +// carry no inferred current grade. V2 entries capture the category decision +// and current grade as they existed when that result was finalized. +type AssessmentAttemptResultHistoryEntry struct { + SchemaVersion int32 + Result AssessmentAttemptResultSnapshot + CategoryDecision *AssessmentCategoryDecisionSnapshot + CurrentConfirmedGrade *GradeCode +} + +func NewLegacyAssessmentAttemptResultHistoryEntry( + result AssessmentAttemptResultSnapshot, +) (AssessmentAttemptResultHistoryEntry, error) { + const location = "domain.NewLegacyAssessmentAttemptResultHistoryEntry" + validated, err := RestoreAssessmentAttemptResultSnapshot(result) + if err != nil { + return AssessmentAttemptResultHistoryEntry{}, fmt.Errorf("%s - validate legacy result: %w", location, err) + } + return AssessmentAttemptResultHistoryEntry{ + SchemaVersion: AssessmentAttemptResultHistorySchemaV1, + Result: validated, + }, nil +} + +func NewCategoryAssessmentAttemptResultHistoryEntry( + result AssessmentAttemptResultSnapshot, + decision AssessmentCategoryDecisionSnapshot, +) (AssessmentAttemptResultHistoryEntry, error) { + const location = "domain.NewCategoryAssessmentAttemptResultHistoryEntry" + validated, err := RestoreAssessmentAttemptResultSnapshot(result) + if err != nil { + return AssessmentAttemptResultHistoryEntry{}, fmt.Errorf("%s - validate result: %w", location, err) + } + if validated.Attempt.Kind == AssessmentAttemptKindDemoExpress { + return AssessmentAttemptResultHistoryEntry{}, fmt.Errorf("%s - training result cannot carry category data: %w", location, ErrInvalidAssessmentCategory) + } + categoryDecision, err := RestoreAssessmentCategoryDecision(decision) + if err != nil { + return AssessmentAttemptResultHistoryEntry{}, fmt.Errorf("%s - validate category decision: %w", location, err) + } + if !categoryDecisionMatchesResult(categoryDecision.snapshot, validated) { + return AssessmentAttemptResultHistoryEntry{}, fmt.Errorf("%s - decision does not match result: %w", location, ErrInvalidAssessmentCategory) + } + entry := AssessmentAttemptResultHistoryEntry{ + SchemaVersion: AssessmentAttemptResultHistorySchemaV2, + Result: validated, + CategoryDecision: pointer(categoryDecision.Snapshot()), + CurrentConfirmedGrade: clonePointer(categoryDecision.snapshot.CurrentGrade), + } + return RestoreAssessmentAttemptResultHistoryEntry(entry) +} + +func RestoreAssessmentAttemptResultHistoryEntry( + entry AssessmentAttemptResultHistoryEntry, +) (AssessmentAttemptResultHistoryEntry, error) { + const location = "domain.RestoreAssessmentAttemptResultHistoryEntry" + result, err := RestoreAssessmentAttemptResultSnapshot(entry.Result) + if err != nil { + return AssessmentAttemptResultHistoryEntry{}, fmt.Errorf("%s - restore result: %w", location, err) + } + entry.Result = result + switch entry.SchemaVersion { + case AssessmentAttemptResultHistorySchemaV1: + if entry.CategoryDecision != nil || entry.CurrentConfirmedGrade != nil { + return AssessmentAttemptResultHistoryEntry{}, fmt.Errorf("%s - legacy result must not contain category data: %w", location, ErrInvalidAssessmentCategory) + } + return entry, nil + case AssessmentAttemptResultHistorySchemaV2: + if entry.CategoryDecision == nil || entry.CurrentConfirmedGrade != nil && !entry.CurrentConfirmedGrade.IsKnown() { + return AssessmentAttemptResultHistoryEntry{}, fmt.Errorf("%s - category result is incomplete: %w", location, ErrInvalidAssessmentCategory) + } + decision, err := RestoreAssessmentCategoryDecision(*entry.CategoryDecision) + if err != nil { + return AssessmentAttemptResultHistoryEntry{}, fmt.Errorf("%s - restore category decision: %w", location, err) + } + snapshot := decision.Snapshot() + if !categoryDecisionMatchesResult(snapshot, result) || !sameGrade(entry.CurrentConfirmedGrade, snapshot.CurrentGrade) { + return AssessmentAttemptResultHistoryEntry{}, fmt.Errorf("%s - category result pins or current grade do not match: %w", location, ErrInvalidAssessmentCategory) + } + entry.CategoryDecision = pointer(snapshot) + entry.CurrentConfirmedGrade = clonePointer(entry.CurrentConfirmedGrade) + return entry, nil + default: + return AssessmentAttemptResultHistoryEntry{}, fmt.Errorf("%s - unsupported result history version: %w", location, ErrInvalidAssessmentCategory) + } +} + +func categoryDecisionMatchesResult( + decision AssessmentCategoryDecisionSnapshot, + result AssessmentAttemptResultSnapshot, +) bool { + return validCategoryResultDecisionStatus(decision.Status) && + decision.AttemptID == result.Attempt.ID && decision.DecidedAt.Equal(result.DecidedAt) && + categoryDecisionPinsMatchResult(decision, result) && categoryDecisionTrackMatchesResult(decision, result) +} + +func validCategoryResultDecisionStatus(status AssessmentCategoryDecisionStatus) bool { + switch status { + case AssessmentCategoryDecisionNotEligible, AssessmentCategoryDecisionNotConfirmed, + AssessmentCategoryDecisionAssigned, AssessmentCategoryDecisionUnchanged: + return true + case AssessmentCategoryDecisionTrainingOnly: + return false + default: + return false + } +} + +func categoryDecisionPinsMatchResult( + decision AssessmentCategoryDecisionSnapshot, + result AssessmentAttemptResultSnapshot, +) bool { + return decision.ProductPolicyVersionID == result.Pins.ProductPolicyVersionID && + decision.ProductPolicyVersion == result.Pins.ProductPolicyVersion && + decision.GradingPolicyVersionID == result.Pins.GradingPolicyVersionID && + decision.OpeningID == result.Pins.OpeningID && decision.OpeningManifestHash == result.Pins.OpeningManifestHash +} + +func categoryDecisionTrackMatchesResult( + decision AssessmentCategoryDecisionSnapshot, + result AssessmentAttemptResultSnapshot, +) bool { + return decision.Specialization != nil && sameSpecialization(decision.Specialization, result.Attempt.Specialization) && + sameGrade(decision.AttemptedGrade, result.Attempt.TargetGrade) && + (result.Attempt.Kind == AssessmentAttemptKindRoot || result.Attempt.Kind == AssessmentAttemptKindCorrective) && + result.Attempt.Mode == AssessmentAttemptModeDemoBasic +} diff --git a/backend/internal/domain/assessment_category_test.go b/backend/internal/domain/assessment_category_test.go new file mode 100644 index 0000000..5350c7d --- /dev/null +++ b/backend/internal/domain/assessment_category_test.go @@ -0,0 +1,495 @@ +package domain + +import ( + "errors" + "testing" + "time" + + "github.com/google/uuid" +) + +func TestDecideAssessmentCategoryUsesReviewedPinnedThreshold(t *testing.T) { + policy := testCategoryPolicyVersion(t) + previous := testCurrentAssessmentCategory(t, uuid.New(), GradeIntern, policy) + userID := previous.snapshot.CandidateID + + failedAttempt := newCategoryTestAttempt(t, policy, GradeJunior, userID) + failedAttempt, failedResult := finishCategoryTestAttempt(t, failedAttempt, policy, 18) + failedReview := categoryReviewForAttempt(t, failedAttempt, policy) + failed, err := DecideAssessmentCategory(AssessmentCategoryDecisionInput{ + Attempt: failedAttempt, Result: failedResult, Policy: policy, Review: &failedReview, Current: &previous, + SyntheticDemoCategoryAssignmentEnabled: true, + }) + if err != nil { + t.Fatalf("DecideAssessmentCategory(k-1) error = %v", err) + } + if snapshot := failed.Snapshot(); snapshot.Status != AssessmentCategoryDecisionNotConfirmed || + snapshot.PreviousGrade == nil || *snapshot.PreviousGrade != GradeIntern || + snapshot.CurrentGrade == nil || *snapshot.CurrentGrade != GradeIntern || failed.ShouldUpdateCurrent() { + t.Fatalf("k-1 decision = %+v, want failed attempt preserving the current intern grade", snapshot) + } + if current, ok := failed.CurrentCategory(); !ok || current.Snapshot().Grade != GradeIntern { + t.Fatalf("current category after k-1 = (%+v, %v), want the previous grade", current.Snapshot(), ok) + } + + passingAttempt := newCategoryTestAttempt(t, policy, GradeJunior, userID) + passingAttempt, passingResult := finishCategoryTestAttempt(t, passingAttempt, policy, 19) + passingReview := categoryReviewForAttempt(t, passingAttempt, policy) + passing, err := DecideAssessmentCategory(AssessmentCategoryDecisionInput{ + Attempt: passingAttempt, Result: passingResult, Policy: policy, Review: &passingReview, Current: &previous, + SyntheticDemoCategoryAssignmentEnabled: true, + }) + if err != nil { + t.Fatalf("DecideAssessmentCategory(k) error = %v", err) + } + snapshot := passing.Snapshot() + if snapshot.Status != AssessmentCategoryDecisionAssigned || snapshot.Method != AssessmentCategoryDecisionDemoBasicPassMark || + snapshot.PreviousGrade == nil || *snapshot.PreviousGrade != GradeIntern || + snapshot.CurrentGrade == nil || *snapshot.CurrentGrade != GradeJunior || + snapshot.CalibrationStatus != AssessmentCategoryCalibrationUncalibrated || + snapshot.Source != AssessmentCategorySourceSyntheticDemo || !passing.ShouldUpdateCurrent() { + t.Fatalf("k decision = %+v, want explicit uncalibrated synthetic assignment", snapshot) + } + current, ok := passing.CurrentCategory() + if !ok || current.Snapshot().Grade != GradeJunior || current.Snapshot().SourceReviewID != passingReview.Snapshot().ID { + t.Fatalf("assigned current category = (%+v, %v), want the reviewed junior grade", current.Snapshot(), ok) + } +} + +func TestDecideAssessmentCategoryRejectsReviewAfterResult(t *testing.T) { + policy := testCategoryPolicyVersion(t) + attempt := newCategoryTestAttempt(t, policy, GradeJunior, uuid.New()) + attempt, result := finishCategoryTestAttempt(t, attempt, policy, 19) + review := categoryReviewForAttempt(t, attempt, policy) + reviewSnapshot := review.Snapshot() + reviewSnapshot.ReviewedAt = result.DecidedAt + boundaryReview, err := RestoreAssessmentSyntheticCategoryReview(reviewSnapshot) + if err != nil { + t.Fatalf("RestoreAssessmentSyntheticCategoryReview(at decision time) error = %v", err) + } + boundary, err := DecideAssessmentCategory(AssessmentCategoryDecisionInput{ + Attempt: attempt, Result: result, Policy: policy, Review: &boundaryReview, + SyntheticDemoCategoryAssignmentEnabled: true, + }) + if err != nil || boundary.Snapshot().Status != AssessmentCategoryDecisionAssigned { + t.Fatalf("DecideAssessmentCategory(review at decision time) = (%+v, %v), want assignment", boundary.Snapshot(), err) + } + + reviewSnapshot.ReviewedAt = result.DecidedAt.Add(time.Microsecond) + futureReview, err := RestoreAssessmentSyntheticCategoryReview(reviewSnapshot) + if err != nil { + t.Fatalf("RestoreAssessmentSyntheticCategoryReview(after decision time) error = %v", err) + } + future, err := DecideAssessmentCategory(AssessmentCategoryDecisionInput{ + Attempt: attempt, Result: result, Policy: policy, Review: &futureReview, + SyntheticDemoCategoryAssignmentEnabled: true, + }) + if err != nil || future.Snapshot().Status != AssessmentCategoryDecisionNotEligible || future.ShouldUpdateCurrent() { + t.Fatalf("DecideAssessmentCategory(review after decision time) = (%+v, %v), want no assignment", future.Snapshot(), err) + } +} + +func TestDecideAssessmentCategoryFailsClosedWithoutMatchingReview(t *testing.T) { + policy := testCategoryPolicyVersion(t) + attempt := newCategoryTestAttempt(t, policy, GradeJunior, uuid.New()) + attempt, result := finishCategoryTestAttempt(t, attempt, policy, 19) + + decision, err := DecideAssessmentCategory(AssessmentCategoryDecisionInput{ + Attempt: attempt, Result: result, Policy: policy, SyntheticDemoCategoryAssignmentEnabled: true, + }) + if err != nil { + t.Fatalf("DecideAssessmentCategory(no review) error = %v", err) + } + if snapshot := decision.Snapshot(); snapshot.Status != AssessmentCategoryDecisionNotEligible || + snapshot.CurrentGrade != nil || snapshot.ReviewID != uuid.Nil || decision.ShouldUpdateCurrent() { + t.Fatalf("unreviewed decision = %+v, want no category evidence", snapshot) + } + + review := categoryReviewForAttempt(t, attempt, policy) + reviewSnapshot := review.Snapshot() + reviewSnapshot.ProductPolicyVersion++ + wrongPolicyReview, err := RestoreAssessmentSyntheticCategoryReview(reviewSnapshot) + if err != nil { + t.Fatalf("RestoreAssessmentSyntheticCategoryReview(wrong policy) error = %v", err) + } + decision, err = DecideAssessmentCategory(AssessmentCategoryDecisionInput{ + Attempt: attempt, Result: result, Policy: policy, Review: &wrongPolicyReview, + SyntheticDemoCategoryAssignmentEnabled: true, + }) + if err != nil || decision.Snapshot().Status != AssessmentCategoryDecisionNotEligible || decision.ShouldUpdateCurrent() { + t.Fatalf("DecideAssessmentCategory(mismatched review) = (%+v, %v), want no assignment", decision.Snapshot(), err) + } + + otherPolicy := testCategoryPolicyVersion(t) + if _, err := DecideAssessmentCategory(AssessmentCategoryDecisionInput{ + Attempt: attempt, Result: result, Policy: otherPolicy, Review: &review, + SyntheticDemoCategoryAssignmentEnabled: true, + }); !errors.Is(err, ErrInvalidAssessmentCategory) { + t.Fatalf("DecideAssessmentCategory(unpinned policy) error = %v, want invalid category", err) + } +} + +func TestDecideAssessmentCategoryNeverLowersCurrentGrade(t *testing.T) { + policy := testCategoryPolicyVersion(t) + userID := uuid.New() + current := testCurrentAssessmentCategory(t, userID, GradeMiddle, policy) + attempt := newCategoryTestAttempt(t, policy, GradeJunior, userID) + attempt, result := finishCategoryTestAttempt(t, attempt, policy, 19) + review := categoryReviewForAttempt(t, attempt, policy) + decision, err := DecideAssessmentCategory(AssessmentCategoryDecisionInput{ + Attempt: attempt, Result: result, Policy: policy, Review: &review, Current: ¤t, + SyntheticDemoCategoryAssignmentEnabled: true, + }) + if err != nil { + t.Fatalf("DecideAssessmentCategory(lower passing grade) error = %v", err) + } + if snapshot := decision.Snapshot(); snapshot.Status != AssessmentCategoryDecisionUnchanged || + snapshot.PreviousGrade == nil || *snapshot.PreviousGrade != GradeMiddle || + snapshot.CurrentGrade == nil || *snapshot.CurrentGrade != GradeMiddle || decision.ShouldUpdateCurrent() { + t.Fatalf("lower-grade decision = %+v, want the existing middle grade unchanged", snapshot) + } + unchanged, ok := decision.CurrentCategory() + if !ok || unchanged.Snapshot().Grade != GradeMiddle || unchanged.Snapshot().SourceAttemptID != current.Snapshot().SourceAttemptID { + t.Fatalf("current category changed after a lower pass: %+v", unchanged.Snapshot()) + } +} + +func TestDecideAssessmentCategoryAllowsCorrectiveDemoBasic(t *testing.T) { + policy := testCategoryPolicyVersion(t) + userID := uuid.New() + root := newCategoryTestAttempt(t, policy, GradeSenior, userID) + root, _ = finishCategoryTestAttempt(t, root, policy, 18) + corrective := newCategoryTestAttemptAt( + t, policy, AssessmentAttemptKindCorrective, GradeMiddle, userID, []AssessmentAttempt{root}, + root.Snapshot().UpdatedAt.Add(time.Second), + ) + corrective, result := finishCategoryTestAttempt(t, corrective, policy, 19) + review := categoryReviewForAttempt(t, corrective, policy) + decision, err := DecideAssessmentCategory(AssessmentCategoryDecisionInput{ + Attempt: corrective, Result: result, Policy: policy, Review: &review, + SyntheticDemoCategoryAssignmentEnabled: true, + }) + if err != nil { + t.Fatalf("DecideAssessmentCategory(corrective) error = %v", err) + } + if snapshot := decision.Snapshot(); snapshot.Status != AssessmentCategoryDecisionAssigned || + snapshot.CurrentGrade == nil || *snapshot.CurrentGrade != GradeMiddle { + t.Fatalf("corrective decision = %+v, want a middle-grade assignment", snapshot) + } +} + +func TestDecideAssessmentCategoryExpressNeverCreatesEvidence(t *testing.T) { + policy := testCategoryPolicyVersion(t) + userID := uuid.New() + current := testCurrentAssessmentCategory(t, userID, GradeJunior, policy) + attempt, err := NewAssessmentAttempt(NewAssessmentAttemptInput{ + UserID: userID, Kind: AssessmentAttemptKindDemoExpress, BankCategory: "unit-training", + Versions: testTrainingAssessmentAttemptVersions(policy), Policy: policy, + CreatedAt: testAssessmentAttemptCreatedAt, Items: testAssessmentAttemptItems(t, 3), + }) + if err != nil { + t.Fatalf("NewAssessmentAttempt(express) error = %v", err) + } + attempt, result := finishCategoryTestAttempt(t, attempt, policy, 3) + decision, err := DecideAssessmentCategory(AssessmentCategoryDecisionInput{ + Attempt: attempt, Result: result, Policy: policy, Current: ¤t, + SyntheticDemoCategoryAssignmentEnabled: true, + }) + if err != nil { + t.Fatalf("DecideAssessmentCategory(express) error = %v", err) + } + if snapshot := decision.Snapshot(); snapshot.Status != AssessmentCategoryDecisionTrainingOnly || + snapshot.Specialization != nil || snapshot.AttemptedGrade != nil || snapshot.ReviewID != uuid.Nil || + decision.ShouldUpdateCurrent() { + t.Fatalf("express decision = %+v, want no category fields or update", snapshot) + } + unchanged, ok := decision.CurrentCategory() + if !ok || unchanged.Snapshot().Grade != GradeJunior || unchanged.Snapshot().SourceAttemptID != current.Snapshot().SourceAttemptID { + t.Fatalf("express changed current category: %+v", unchanged.Snapshot()) + } +} + +func TestDecideAssessmentCategoryIsDefaultOffEvenWithReviewedSource(t *testing.T) { + policy := testCategoryPolicyVersion(t) + attempt := newCategoryTestAttempt(t, policy, GradeJunior, uuid.New()) + attempt, result := finishCategoryTestAttempt(t, attempt, policy, 19) + review := categoryReviewForAttempt(t, attempt, policy) + + decision, err := DecideAssessmentCategory(AssessmentCategoryDecisionInput{ + Attempt: attempt, Result: result, Policy: policy, Review: &review, + }) + if err != nil { + t.Fatalf("DecideAssessmentCategory(default gate) error = %v", err) + } + if snapshot := decision.Snapshot(); snapshot.Status != AssessmentCategoryDecisionNotEligible || + snapshot.ReviewID != uuid.Nil || snapshot.CurrentGrade != nil || decision.ShouldUpdateCurrent() { + t.Fatalf("default-off decision = %+v, want no assignment without an explicit feature gate", snapshot) + } +} + +func TestSyntheticCategoryPolicyRequiresTheCompleteAcceptedAssessmentPolicy(t *testing.T) { + accepted := DemoProductPolicyV2().Assessment + if !sameAssessmentPolicy(accepted, DemoProductPolicyV2().Assessment) { + t.Fatal("sameAssessmentPolicy(accepted) = false, want exact accepted policy") + } + changed := DemoProductPolicyV2().Assessment + changed.StopRule.SeedItems++ + if sameAssessmentPolicy(changed, accepted) { + t.Fatal("sameAssessmentPolicy(changed stop rule) = true, want false") + } + changed = DemoProductPolicyV2().Assessment + changed.Attempt.IdleTimeoutSeconds++ + if sameAssessmentPolicy(changed, accepted) { + t.Fatal("sameAssessmentPolicy(changed session settings) = true, want false") + } + changed = DemoProductPolicyV2().Assessment + changed.Training = nil + if sameAssessmentPolicy(changed, accepted) { + t.Fatal("sameAssessmentPolicy(missing training settings) = true, want false") + } +} + +func TestAssessmentAttemptResultHistoryKeepsV1CategoryUnknown(t *testing.T) { + policy := testCategoryPolicyVersion(t) + userID := uuid.New() + current := testCurrentAssessmentCategory(t, userID, GradeMiddle, policy) + attempt := newCategoryTestAttempt(t, policy, GradeSenior, userID) + attempt, result := finishCategoryTestAttempt(t, attempt, policy, 19) + review := categoryReviewForAttempt(t, attempt, policy) + decision, err := DecideAssessmentCategory(AssessmentCategoryDecisionInput{ + Attempt: attempt, Result: result, Policy: policy, Review: &review, Current: ¤t, + SyntheticDemoCategoryAssignmentEnabled: true, + }) + if err != nil { + t.Fatalf("DecideAssessmentCategory() error = %v", err) + } + + legacy, err := NewLegacyAssessmentAttemptResultHistoryEntry(result) + if err != nil { + t.Fatalf("NewLegacyAssessmentAttemptResultHistoryEntry() error = %v", err) + } + if legacy.SchemaVersion != AssessmentAttemptResultHistorySchemaV1 || legacy.CategoryDecision != nil || legacy.CurrentConfirmedGrade != nil { + t.Fatalf("legacy history entry = %+v, want v1 with category grade unknown", legacy) + } + + v2, err := NewCategoryAssessmentAttemptResultHistoryEntry(result, decision.Snapshot()) + if err != nil { + t.Fatalf("NewCategoryAssessmentAttemptResultHistoryEntry() error = %v", err) + } + if v2.SchemaVersion != AssessmentAttemptResultHistorySchemaV2 || v2.CurrentConfirmedGrade == nil || + *v2.CurrentConfirmedGrade != GradeSenior || v2.CategoryDecision == nil || + v2.CategoryDecision.PreviousGrade == nil || *v2.CategoryDecision.PreviousGrade != GradeMiddle || + v2.CategoryDecision.CurrentGrade == nil || *v2.CategoryDecision.CurrentGrade != GradeSenior { + t.Fatalf("v2 history entry = %+v, want previous middle and captured current senior", v2) + } +} + +func TestAssessmentAttemptResultHistoryRejectsInventedLegacyGradeAndMismatchedV2(t *testing.T) { + policy := testCategoryPolicyVersion(t) + attempt := newCategoryTestAttempt(t, policy, GradeJunior, uuid.New()) + attempt, result := finishCategoryTestAttempt(t, attempt, policy, 3) + review := categoryReviewForAttempt(t, attempt, policy) + decision, err := DecideAssessmentCategory(AssessmentCategoryDecisionInput{ + Attempt: attempt, Result: result, Policy: policy, Review: &review, + SyntheticDemoCategoryAssignmentEnabled: true, + }) + if err != nil { + t.Fatalf("DecideAssessmentCategory() error = %v", err) + } + + legacy, err := NewLegacyAssessmentAttemptResultHistoryEntry(result) + if err != nil { + t.Fatalf("NewLegacyAssessmentAttemptResultHistoryEntry() error = %v", err) + } + legacy.CurrentConfirmedGrade = pointer(GradeIntern) + if _, err := RestoreAssessmentAttemptResultHistoryEntry(legacy); !errors.Is(err, ErrInvalidAssessmentCategory) { + t.Fatalf("RestoreAssessmentAttemptResultHistoryEntry(v1 with inferred grade) error = %v, want invalid category", err) + } + + v2, err := NewCategoryAssessmentAttemptResultHistoryEntry(result, decision.Snapshot()) + if err != nil { + t.Fatalf("NewCategoryAssessmentAttemptResultHistoryEntry() error = %v", err) + } + v2.CategoryDecision.OpeningManifestHash = testManifestHash(200) + if _, err := RestoreAssessmentAttemptResultHistoryEntry(v2); !errors.Is(err, ErrInvalidAssessmentCategory) { + t.Fatalf("RestoreAssessmentAttemptResultHistoryEntry(mismatched pins) error = %v, want invalid category", err) + } +} + +func TestAssessmentCategorySnapshotsRejectUnknownOrIncompleteProvenance(t *testing.T) { + policy := testCategoryPolicyVersion(t) + current := testCurrentAssessmentCategory(t, uuid.New(), GradeJunior, policy) + corrupt := current.Snapshot() + corrupt.SourceReviewID = uuid.Nil + if _, err := RestoreCandidateAssessmentCategory(corrupt); !errors.Is(err, ErrInvalidAssessmentCategory) { + t.Fatalf("RestoreCandidateAssessmentCategory(missing review) error = %v, want invalid category", err) + } + + operator, err := ParseAssessmentOperator("operator:assessment-reviewer") + if err != nil { + t.Fatalf("ParseAssessmentOperator() error = %v", err) + } + if _, err := RestoreAssessmentSyntheticCategoryReview(AssessmentSyntheticCategoryReviewSnapshot{ + ID: uuid.New(), OpeningID: uuid.New(), Category: "backend", Source: AssessmentCategorySourceSyntheticDemo, + OpeningManifestHash: testManifestHash(1), + ProductPolicyVersionID: policy.ID(), ProductPolicyVersion: policy.Version(), ReviewedBy: operator, + }); !errors.Is(err, ErrInvalidAssessmentCategory) { + t.Fatalf("RestoreAssessmentSyntheticCategoryReview(missing time) error = %v, want invalid category", err) + } + if _, err := RestoreAssessmentSyntheticCategoryReview(AssessmentSyntheticCategoryReviewSnapshot{ + ID: uuid.New(), OpeningID: uuid.New(), Category: "backend", OpeningManifestHash: testManifestHash(1), + ProductPolicyVersionID: policy.ID(), ProductPolicyVersion: policy.Version(), ReviewedBy: operator, + ReviewedAt: testAssessmentAttemptCreatedAt, + }); !errors.Is(err, ErrInvalidAssessmentCategory) { + t.Fatalf("RestoreAssessmentSyntheticCategoryReview(missing source) error = %v, want invalid category", err) + } + if _, err := RestoreAssessmentSyntheticCategoryReview(AssessmentSyntheticCategoryReviewSnapshot{ + ID: uuid.New(), OpeningID: uuid.New(), Category: "backend", Source: AssessmentCategorySource("operator_import"), + OpeningManifestHash: testManifestHash(1), ProductPolicyVersionID: policy.ID(), ProductPolicyVersion: policy.Version(), + ReviewedBy: operator, ReviewedAt: testAssessmentAttemptCreatedAt, + }); !errors.Is(err, ErrInvalidAssessmentCategory) { + t.Fatalf("RestoreAssessmentSyntheticCategoryReview(wrong source) error = %v, want invalid category", err) + } +} + +func testCategoryPolicyVersion(t *testing.T) PolicyVersion { + t.Helper() + policy := DemoProductPolicyV2() + draft, err := NewPolicyVersionDraft(NewPolicyVersionDraftInput{ + Key: ProductPolicyKey, Kind: PolicyKindDemo, Author: DemoPolicySeedAuthor, + EffectiveAt: testPolicyEffectiveAt, Policy: policy, + }) + if err != nil { + t.Fatalf("NewPolicyVersionDraft(category policy) error = %v", err) + } + numbered, err := draft.WithVersion(2) + if err != nil { + t.Fatalf("PolicyVersionDraft.WithVersion(category policy) error = %v", err) + } + return mustRestore(t, storedFrom(numbered)) +} + +func newCategoryTestAttempt( + t *testing.T, + policy PolicyVersion, + grade GradeCode, + userID uuid.UUID, +) AssessmentAttempt { + t.Helper() + return newCategoryTestAttemptAt(t, policy, AssessmentAttemptKindRoot, grade, userID, nil, testAssessmentAttemptCreatedAt) +} + +func newCategoryTestAttemptAt( + t *testing.T, + policy PolicyVersion, + kind AssessmentAttemptKind, + grade GradeCode, + userID uuid.UUID, + chain []AssessmentAttempt, + createdAt time.Time, +) AssessmentAttempt { + t.Helper() + specialization := SpecializationBackend + attempt, err := NewAssessmentAttempt(NewAssessmentAttemptInput{ + UserID: userID, Kind: kind, BankCategory: "unit-category", Specialization: &specialization, + TargetGrade: &grade, Chain: chain, Versions: testAssessmentAttemptVersions(t, policy), + Policy: policy, CreatedAt: createdAt, Items: testAssessmentAttemptItems(t, int(policy.Policy().Assessment.StopRule.MaxScoredItems+policy.Policy().Assessment.StopRule.SeedItems)), + }) + if err != nil { + t.Fatalf("NewAssessmentAttempt(category test) error = %v", err) + } + return attempt +} + +func finishCategoryTestAttempt( + t *testing.T, + attempt AssessmentAttempt, + policy PolicyVersion, + correctCount int, +) (AssessmentAttempt, AssessmentAttemptResultSnapshot) { + t.Helper() + items := attempt.Snapshot().Items + if correctCount < 0 || correctCount > len(items) { + t.Fatalf("correct count %d outside %d attempt items", correctCount, len(items)) + } + startedAt := attempt.Snapshot().CreatedAt + for index, item := range items { + answer := incorrectAssessmentTestAnswer(t, item.Variant) + if index < correctCount { + answer = correctAssessmentTestAnswer(t, item.Variant) + } + updated, changed, err := attempt.SubmitAnswer(attempt.Version(), item.ID, answer, startedAt.Add(time.Duration(index+1)*time.Second)) + if err != nil || !changed { + t.Fatalf("SubmitAnswer(category item %d) = changed %v, error %v", index, changed, err) + } + attempt = updated + } + finalized, changed, answerDecision, err := attempt.FinalizeDemo( + attempt.Version(), policy.Policy().Assessment, startedAt.Add(time.Duration(len(items)+1)*time.Second), + ) + if err != nil || !changed { + t.Fatalf("FinalizeDemo(category attempt) = changed %v, error %v", changed, err) + } + summary := "" + limitations := []string{"uncalibrated_thresholds"} + if finalized.Kind() == AssessmentAttemptKindDemoExpress { + summary = "This training run is educational only." + limitations = []string{"demonstration_only"} + } + result, err := NewAssessmentAttemptResultSnapshot(finalized, answerDecision, summary, limitations) + if err != nil { + t.Fatalf("NewAssessmentAttemptResultSnapshot(category attempt) error = %v", err) + } + return finalized, result +} + +func categoryReviewForAttempt( + t *testing.T, + attempt AssessmentAttempt, + policy PolicyVersion, +) AssessmentSyntheticCategoryReview { + t.Helper() + reviewer, err := ParseAssessmentOperator("operator:assessment-reviewer") + if err != nil { + t.Fatalf("ParseAssessmentOperator() error = %v", err) + } + snapshot := attempt.Snapshot() + review, err := NewAssessmentSyntheticCategoryReview(AssessmentSyntheticCategoryReviewSnapshot{ + ID: uuid.New(), OpeningID: snapshot.Versions.OpeningID, Category: snapshot.BankCategory, + Source: AssessmentCategorySourceSyntheticDemo, + OpeningManifestHash: snapshot.Versions.OpeningManifestHash, + ProductPolicyVersionID: policy.ID(), ProductPolicyVersion: policy.Version(), + ReviewedBy: reviewer, ReviewedAt: testAssessmentAttemptCreatedAt, + }) + if err != nil { + t.Fatalf("NewAssessmentSyntheticCategoryReview() error = %v", err) + } + return review +} + +func testCurrentAssessmentCategory( + t *testing.T, + userID uuid.UUID, + grade GradeCode, + policy PolicyVersion, +) CandidateAssessmentCategory { + t.Helper() + return restoredTestCategory(t, CandidateAssessmentCategorySnapshot{ + CandidateID: userID, Specialization: SpecializationBackend, Grade: grade, + SourceAttemptID: AssessmentAttemptID(uuid.New()), SourceReviewID: uuid.New(), + ProductPolicyVersionID: policy.ID(), ProductPolicyVersion: policy.Version(), + OpeningID: uuid.New(), OpeningManifestHash: testManifestHash(9), + Source: AssessmentCategorySourceSyntheticDemo, + CalibrationStatus: AssessmentCategoryCalibrationUncalibrated, + AssignedAt: testAssessmentAttemptCreatedAt, + }) +} + +func restoredTestCategory(t *testing.T, snapshot CandidateAssessmentCategorySnapshot) CandidateAssessmentCategory { + t.Helper() + category, err := RestoreCandidateAssessmentCategory(snapshot) + if err != nil { + t.Fatalf("RestoreCandidateAssessmentCategory() error = %v", err) + } + return category +} diff --git a/backend/internal/domain/notification_inbox.go b/backend/internal/domain/notification_inbox.go new file mode 100644 index 0000000..eeb15d1 --- /dev/null +++ b/backend/internal/domain/notification_inbox.go @@ -0,0 +1,149 @@ +package domain + +import ( + "errors" + "fmt" + "time" + + "github.com/google/uuid" +) + +var ErrInvalidNotificationInboxEntry = errors.New("invalid notification inbox entry") + +// NotificationInboxEventType is an allowlisted source event that can appear +// in the internal inbox. +type NotificationInboxEventType string + +const NotificationInboxInvitationDelivered NotificationInboxEventType = "invitation.delivered" + +// NotificationInboxSourceType identifies the current source-of-truth record +// used to resolve an inbox item's content. +type NotificationInboxSourceType string + +const NotificationInboxSourceInvitation NotificationInboxSourceType = "invitation" + +// NotificationInboxEntryInput contains identifiers and event metadata only. +// It deliberately has no content snapshot: presentation is resolved from the +// current source and its visibility rules when the item is read. +type NotificationInboxEntryInput struct { + EventID uuid.UUID + RecipientUserID uuid.UUID + OrganizationID uuid.UUID + EventType NotificationInboxEventType + SchemaVersion int32 + SourceType NotificationInboxSourceType + SourceID uuid.UUID + OccurredAt time.Time + ReadAt *time.Time +} + +// NotificationInboxEntry is an immutable delivered event plus its +// recipient-specific read state. EventID is the idempotency identity for one +// recipient; the same source event can be delivered to different recipients. +type NotificationInboxEntry struct { + eventID uuid.UUID + recipientUserID uuid.UUID + organizationID uuid.UUID + eventType NotificationInboxEventType + schemaVersion int32 + sourceType NotificationInboxSourceType + sourceID uuid.UUID + occurredAt time.Time + readAt *time.Time +} + +// NewNotificationInboxEntry validates an event record before it is stored. +func NewNotificationInboxEntry(input NotificationInboxEntryInput) (NotificationInboxEntry, error) { + const location = "domain.NewNotificationInboxEntry" + if input.ReadAt != nil { + return NotificationInboxEntry{}, fmt.Errorf("%s - new entries cannot start as read: %w", location, ErrInvalidNotificationInboxEntry) + } + return restoreNotificationInboxEntry(input) +} + +// RestoreNotificationInboxEntry validates inbox metadata loaded from storage. +func RestoreNotificationInboxEntry(input NotificationInboxEntryInput) (NotificationInboxEntry, error) { + const location = "domain.RestoreNotificationInboxEntry" + return restoreNotificationInboxEntryWithLocation(input, location) +} + +func restoreNotificationInboxEntry(input NotificationInboxEntryInput) (NotificationInboxEntry, error) { + return restoreNotificationInboxEntryWithLocation(input, "domain.NewNotificationInboxEntry") +} + +func restoreNotificationInboxEntryWithLocation( + input NotificationInboxEntryInput, + location string, +) (NotificationInboxEntry, error) { + if input.EventID == uuid.Nil || input.RecipientUserID == uuid.Nil || input.OrganizationID == uuid.Nil || input.SourceID == uuid.Nil { + return NotificationInboxEntry{}, fmt.Errorf("%s - event, recipient, organization, and source IDs are required: %w", location, ErrInvalidNotificationInboxEntry) + } + if input.EventType != NotificationInboxInvitationDelivered || input.SchemaVersion != 1 || input.SourceType != NotificationInboxSourceInvitation { + return NotificationInboxEntry{}, fmt.Errorf("%s - event type, schema version, and source type are unsupported: %w", location, ErrInvalidNotificationInboxEntry) + } + if input.OccurredAt.IsZero() { + return NotificationInboxEntry{}, fmt.Errorf("%s - occurrence time is required: %w", location, ErrInvalidNotificationInboxEntry) + } + occurredAt := canonicalNotificationInboxTime(input.OccurredAt) + var readAt *time.Time + if input.ReadAt != nil { + if input.ReadAt.IsZero() { + return NotificationInboxEntry{}, fmt.Errorf("%s - read time cannot be zero: %w", location, ErrInvalidNotificationInboxEntry) + } + canonical := canonicalNotificationInboxTime(*input.ReadAt) + readAt = &canonical + } + return NotificationInboxEntry{ + eventID: input.EventID, + recipientUserID: input.RecipientUserID, + organizationID: input.OrganizationID, + eventType: input.EventType, + schemaVersion: input.SchemaVersion, + sourceType: input.SourceType, + sourceID: input.SourceID, + occurredAt: occurredAt, + readAt: readAt, + }, nil +} + +// MarkRead returns the same entry with its first read timestamp. A retry does +// not replace the original timestamp. +func (entry NotificationInboxEntry) MarkRead(at time.Time) (NotificationInboxEntry, error) { + const location = "NotificationInboxEntry.MarkRead" + if entry.IsZero() || at.IsZero() { + return NotificationInboxEntry{}, fmt.Errorf("%s - entry and read time are required: %w", location, ErrInvalidNotificationInboxEntry) + } + if entry.readAt != nil { + return entry, nil + } + readAt := canonicalNotificationInboxTime(at) + entry.readAt = &readAt + return entry, nil +} + +func canonicalNotificationInboxTime(value time.Time) time.Time { + return value.UTC().Truncate(time.Microsecond) +} + +func (entry NotificationInboxEntry) EventID() uuid.UUID { return entry.eventID } +func (entry NotificationInboxEntry) RecipientUserID() uuid.UUID { return entry.recipientUserID } +func (entry NotificationInboxEntry) OrganizationID() uuid.UUID { return entry.organizationID } +func (entry NotificationInboxEntry) EventType() NotificationInboxEventType { + return entry.eventType +} +func (entry NotificationInboxEntry) SchemaVersion() int32 { return entry.schemaVersion } +func (entry NotificationInboxEntry) SourceType() NotificationInboxSourceType { + return entry.sourceType +} +func (entry NotificationInboxEntry) SourceID() uuid.UUID { return entry.sourceID } +func (entry NotificationInboxEntry) OccurredAt() time.Time { return entry.occurredAt } +func (entry NotificationInboxEntry) ReadAt() (time.Time, bool) { + if entry.readAt == nil { + return time.Time{}, false + } + return *entry.readAt, true +} + +func (entry NotificationInboxEntry) IsZero() bool { + return entry.eventID == uuid.Nil || entry.recipientUserID == uuid.Nil || entry.organizationID == uuid.Nil || entry.sourceID == uuid.Nil +} diff --git a/backend/internal/domain/notification_inbox_test.go b/backend/internal/domain/notification_inbox_test.go new file mode 100644 index 0000000..cf84bf2 --- /dev/null +++ b/backend/internal/domain/notification_inbox_test.go @@ -0,0 +1,120 @@ +package domain + +import ( + "errors" + "testing" + "time" + + "github.com/google/uuid" +) + +func TestNewNotificationInboxEntry(t *testing.T) { + t.Parallel() + + occurredAt := time.Date(2026, time.October, 8, 12, 30, 0, 123456789, time.FixedZone("test", 3*60*60)) + input := NotificationInboxEntryInput{ + EventID: uuid.New(), RecipientUserID: uuid.New(), OrganizationID: uuid.New(), + EventType: NotificationInboxInvitationDelivered, SchemaVersion: 1, + SourceType: NotificationInboxSourceInvitation, SourceID: uuid.New(), OccurredAt: occurredAt, + } + entry, err := NewNotificationInboxEntry(input) + if err != nil { + t.Fatalf("NewNotificationInboxEntry() error = %v", err) + } + if entry.EventID() != input.EventID || entry.RecipientUserID() != input.RecipientUserID || entry.OrganizationID() != input.OrganizationID { + t.Fatal("entry identities do not match input") + } + if entry.SourceID() != input.SourceID || entry.SourceType() != input.SourceType || entry.EventType() != input.EventType || entry.SchemaVersion() != input.SchemaVersion { + t.Fatal("entry source metadata does not match input") + } + wantOccurredAt := occurredAt.UTC().Truncate(time.Microsecond) + if !entry.OccurredAt().Equal(wantOccurredAt) { + t.Fatalf("OccurredAt() = %s, want %s", entry.OccurredAt(), wantOccurredAt) + } + if _, isRead := entry.ReadAt(); isRead { + t.Fatal("new entry is already read") + } +} + +func TestRestoreNotificationInboxEntryRejectsInvalidMetadata(t *testing.T) { + t.Parallel() + + base := NotificationInboxEntryInput{ + EventID: uuid.New(), RecipientUserID: uuid.New(), OrganizationID: uuid.New(), + EventType: NotificationInboxInvitationDelivered, SchemaVersion: 1, + SourceType: NotificationInboxSourceInvitation, SourceID: uuid.New(), + OccurredAt: time.Date(2026, time.October, 8, 12, 30, 0, 0, time.UTC), + } + zeroTime := time.Time{} + tests := []struct { + name string + mutate func(*NotificationInboxEntryInput) + }{ + {name: "missing event ID", mutate: func(input *NotificationInboxEntryInput) { input.EventID = uuid.Nil }}, + {name: "missing recipient ID", mutate: func(input *NotificationInboxEntryInput) { input.RecipientUserID = uuid.Nil }}, + {name: "missing organization ID", mutate: func(input *NotificationInboxEntryInput) { input.OrganizationID = uuid.Nil }}, + {name: "missing source ID", mutate: func(input *NotificationInboxEntryInput) { input.SourceID = uuid.Nil }}, + {name: "unknown event type", mutate: func(input *NotificationInboxEntryInput) { input.EventType = "notification.mail_requested" }}, + {name: "unsupported schema version", mutate: func(input *NotificationInboxEntryInput) { input.SchemaVersion = 2 }}, + {name: "unknown source type", mutate: func(input *NotificationInboxEntryInput) { input.SourceType = "mail_request" }}, + {name: "missing occurrence time", mutate: func(input *NotificationInboxEntryInput) { input.OccurredAt = time.Time{} }}, + {name: "zero read time", mutate: func(input *NotificationInboxEntryInput) { input.ReadAt = &zeroTime }}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + input := base + test.mutate(&input) + if _, err := RestoreNotificationInboxEntry(input); !errors.Is(err, ErrInvalidNotificationInboxEntry) { + t.Fatalf("RestoreNotificationInboxEntry() error = %v, want ErrInvalidNotificationInboxEntry", err) + } + }) + } +} + +func TestNewNotificationInboxEntryRejectsReadState(t *testing.T) { + t.Parallel() + + readAt := time.Date(2026, time.October, 8, 13, 0, 0, 0, time.UTC) + input := NotificationInboxEntryInput{ + EventID: uuid.New(), RecipientUserID: uuid.New(), OrganizationID: uuid.New(), + EventType: NotificationInboxInvitationDelivered, SchemaVersion: 1, + SourceType: NotificationInboxSourceInvitation, SourceID: uuid.New(), + OccurredAt: time.Date(2026, time.October, 8, 12, 30, 0, 0, time.UTC), ReadAt: &readAt, + } + if _, err := NewNotificationInboxEntry(input); !errors.Is(err, ErrInvalidNotificationInboxEntry) { + t.Fatalf("NewNotificationInboxEntry() error = %v, want ErrInvalidNotificationInboxEntry", err) + } +} + +func TestNotificationInboxEntryMarkReadPreservesFirstTimestamp(t *testing.T) { + t.Parallel() + + entry, err := NewNotificationInboxEntry(NotificationInboxEntryInput{ + EventID: uuid.New(), RecipientUserID: uuid.New(), OrganizationID: uuid.New(), + EventType: NotificationInboxInvitationDelivered, SchemaVersion: 1, + SourceType: NotificationInboxSourceInvitation, SourceID: uuid.New(), + OccurredAt: time.Date(2026, time.October, 8, 12, 30, 0, 0, time.UTC), + }) + if err != nil { + t.Fatalf("NewNotificationInboxEntry() error = %v", err) + } + first := time.Date(2026, time.October, 8, 13, 0, 0, 987654321, time.FixedZone("test", -4*60*60)) + marked, err := entry.MarkRead(first) + if err != nil { + t.Fatalf("MarkRead(first) error = %v", err) + } + second := first.Add(time.Hour) + retried, err := marked.MarkRead(second) + if err != nil { + t.Fatalf("MarkRead(retry) error = %v", err) + } + want := first.UTC().Truncate(time.Microsecond) + got, isRead := retried.ReadAt() + if !isRead || !got.Equal(want) { + t.Fatalf("ReadAt() = %s, %t, want %s, true", got, isRead, want) + } + if retried.EventID() != entry.EventID() || retried.SourceID() != entry.SourceID() { + t.Fatal("MarkRead changed immutable source identity") + } +} diff --git a/backend/internal/port/outbound/assessment_attempt.go b/backend/internal/port/outbound/assessment_attempt.go index 7fe0fb6..f326ff4 100644 --- a/backend/internal/port/outbound/assessment_attempt.go +++ b/backend/internal/port/outbound/assessment_attempt.go @@ -26,6 +26,9 @@ var ( // ErrAssessmentAttemptResultNotFound reports a completed attempt with no // persisted immutable decision snapshot. ErrAssessmentAttemptResultNotFound = errors.New("assessment attempt result not found") + // ErrAssessmentCategoryConflict reports a current category that could not + // be advanced under its owner and specialization lock. + ErrAssessmentCategoryConflict = errors.New("assessment category changed concurrently") ) // AssessmentAttemptIdempotencyScope is the server HMAC of the operation, @@ -108,6 +111,26 @@ type AssessmentRootQuotaSnapshot struct { AvailableAt *time.Time } +// AssessmentAttemptResultCursor is the keyset boundary for owner history. +// It is internal to the repository; the usecase wraps it in an owner-bound +// authenticated token before accepting it from HTTP. +type AssessmentAttemptResultCursor struct { + DecidedAt time.Time + AttemptID domain.AssessmentAttemptID +} + +// AssessmentAttemptResultRecord contains one immutable result and the owner +// returned by the scoped query. The usecase rechecks ownership and eligibility. +type AssessmentAttemptResultRecord struct { + UserID uuid.UUID + Entry domain.AssessmentAttemptResultHistoryEntry +} + +type AssessmentAttemptResultPage struct { + Records []AssessmentAttemptResultRecord + HasMore bool +} + // AssessmentAttemptRepositories exposes the repository bound to a UnitOfWork // transaction. type AssessmentAttemptRepositories interface { @@ -223,6 +246,52 @@ type AssessmentAttemptRepository interface { // GetResult returns the immutable owner-scoped result snapshot. GetResult(ctx context.Context, userID uuid.UUID, attemptID domain.AssessmentAttemptID) (domain.AssessmentAttemptResultSnapshot, error) + // SaveResultHistoryEntry stores a typed v1 or v2 immutable result. V1 keeps + // the original result document; v2 carries category decision columns. + SaveResultHistoryEntry(ctx context.Context, userID uuid.UUID, entry domain.AssessmentAttemptResultHistoryEntry) error + + // GetResultHistoryEntry returns the exact stored v1/v2 record without + // reconstructing category information from current state. + GetResultHistoryEntry(ctx context.Context, userID uuid.UUID, attemptID domain.AssessmentAttemptID) (domain.AssessmentAttemptResultHistoryEntry, error) + + // ListCandidateAssessmentResults returns an owner-scoped keyset page and at + // most limit entries. HasMore indicates that the repository found one more. + ListCandidateAssessmentResults( + ctx context.Context, + userID uuid.UUID, + cursor *AssessmentAttemptResultCursor, + limit int32, + ) (AssessmentAttemptResultPage, error) + + // LockCandidateCategory serializes one candidate/specialization upgrade. + // Call only after consent, candidate/specialization, and attempt locks. + LockCandidateCategory(ctx context.Context, candidateID uuid.UUID, specialization domain.SpecializationCode) error + + GetCandidateCategory( + ctx context.Context, + candidateID uuid.UUID, + specialization domain.SpecializationCode, + ) (domain.CandidateAssessmentCategory, bool, error) + + // GetSyntheticCategoryReview requires the complete immutable opening and + // product-policy pins; gradingPolicyID must match the opening's policy. + GetSyntheticCategoryReview( + ctx context.Context, + openingID uuid.UUID, + category domain.AssessmentCategory, + openingManifestHash [32]byte, + productPolicyID domain.PolicyVersionID, + productPolicyVersion int32, + gradingPolicyID domain.PolicyVersionID, + ) (domain.AssessmentSyntheticCategoryReview, bool, error) + + // CreateSyntheticCategoryReview stores an operator-attributed immutable + // attestation after the domain has validated its explicit synthetic source. + CreateSyntheticCategoryReview(ctx context.Context, review domain.AssessmentSyntheticCategoryReview) error + + // SaveCandidateAssessmentCategory writes only an assigned category upgrade. + SaveCandidateAssessmentCategory(ctx context.Context, category domain.CandidateAssessmentCategory) error + // SaveSessionOutcome records the original 200 public projection for the // already-reserved idempotency scope. It shares the transaction and expiry // of the generic idempotency record. diff --git a/backend/internal/port/outbound/notification_inbox.go b/backend/internal/port/outbound/notification_inbox.go new file mode 100644 index 0000000..443c442 --- /dev/null +++ b/backend/internal/port/outbound/notification_inbox.go @@ -0,0 +1,70 @@ +package outbound + +import ( + "context" + "errors" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" +) + +var ( + // ErrNotificationInboxEntryNotFound covers a missing event and an event + // owned by a different recipient or organization context. + ErrNotificationInboxEntryNotFound = errors.New("notification inbox entry not found") + // ErrNotificationInboxEventConflict reports an event ID reused with + // different immutable recipient or source metadata. + ErrNotificationInboxEventConflict = errors.New("notification inbox event metadata conflicts") +) + +const MaxNotificationInboxPageSize = 100 + +// NotificationInboxRepository stores recipient-scoped event references and +// read state. Implementations can bind these methods to a transaction; the +// standalone PostgreSQL store uses one SQL statement per operation. +type NotificationInboxRepository interface { + // Store inserts one recipient-specific event. It returns false for an + // identical event already stored under the same recipient and event ID. + Store(ctx context.Context, entry domain.NotificationInboxEntry) (created bool, err error) + + // List returns one newest-first page for the exact recipient. A nil + // OrganizationID means all organization contexts of that recipient. + List(ctx context.Context, query NotificationInboxListQuery) (NotificationInboxPage, error) + + // MarkRead records the first read time in exact recipient and organization + // context. Missing and unauthorized identities share one not-found result. + MarkRead( + ctx context.Context, + recipientUserID uuid.UUID, + organizationID uuid.UUID, + eventID uuid.UUID, + at time.Time, + ) (domain.NotificationInboxEntry, error) +} + +// NotificationInboxListQuery selects a bounded recipient-owned page. +type NotificationInboxListQuery struct { + RecipientUserID uuid.UUID + OrganizationID *uuid.UUID + After *NotificationInboxPosition + Limit int32 +} + +// NotificationInboxPosition continues a newest-first inbox page. +type NotificationInboxPosition struct { + OccurredAt time.Time + EventID uuid.UUID +} + +// NotificationInboxPage is a bounded page plus whether another row exists. +type NotificationInboxPage struct { + Items []domain.NotificationInboxEntry + HasMore bool +} + +// NotificationInboxPositionOf returns the continuation key for an entry. +func NotificationInboxPositionOf(entry domain.NotificationInboxEntry) NotificationInboxPosition { + return NotificationInboxPosition{OccurredAt: entry.OccurredAt(), EventID: entry.EventID()} +} diff --git a/backend/internal/usecase/assessment/attempt.go b/backend/internal/usecase/assessment/attempt.go index c9d5c82..a2dfe2c 100644 --- a/backend/internal/usecase/assessment/attempt.go +++ b/backend/internal/usecase/assessment/attempt.go @@ -59,10 +59,11 @@ func (fieldError *AttemptFieldError) Unwrap() error { return ErrInvalidAttemptRe // AttemptService creates, reads, and resumes candidate-owned attempts. type AttemptService struct { - transactor outbound.Transactor - snapshotExecutor outbound.ReadOnlySnapshotTransactor - keyring Keyring - clock func() time.Time + transactor outbound.Transactor + snapshotExecutor outbound.ReadOnlySnapshotTransactor + keyring Keyring + clock func() time.Time + categoryDecisions AssessmentCategoryDecisionService } // NewAttemptService fails at startup when a required dependency is missing. @@ -77,9 +78,27 @@ func NewAttemptService( } return &AttemptService{ transactor: transactor, snapshotExecutor: snapshotExecutor, keyring: keyring, clock: clock, + categoryDecisions: NewAssessmentCategoryDecisionService(AssessmentCategoryDecisionSettings{}), }, nil } +// NewAttemptServiceWithCategorySettings keeps assignment fail-closed unless +// the caller explicitly enables the synthetic-demo gate. +func NewAttemptServiceWithCategorySettings( + transactor outbound.Transactor, + snapshotExecutor outbound.ReadOnlySnapshotTransactor, + keyring Keyring, + clock func() time.Time, + settings AssessmentCategoryDecisionSettings, +) (*AttemptService, error) { + service, err := NewAttemptService(transactor, snapshotExecutor, keyring, clock) + if err != nil { + return nil, err + } + service.categoryDecisions = NewAssessmentCategoryDecisionService(settings) + return service, nil +} + // CreateAttemptCommand is one of the three disjoint public request shapes. // All values are private candidate data and must not be logged. type CreateAttemptCommand struct { diff --git a/backend/internal/usecase/assessment/category.go b/backend/internal/usecase/assessment/category.go new file mode 100644 index 0000000..76e02db --- /dev/null +++ b/backend/internal/usecase/assessment/category.go @@ -0,0 +1,176 @@ +package assessment + +import ( + "context" + "errors" + "fmt" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" +) + +var ( + ErrAssessmentCategoryRepositoryRequired = errors.New("assessment category repository is required") + ErrAssessmentCategoryHistoryInvalid = errors.New("assessment result history is invalid") +) + +// AssessmentCategoryDecisionSettings are explicit runtime gates. The zero +// value denies synthetic demo category assignment. +type AssessmentCategoryDecisionSettings struct { + SyntheticDemoAssignmentsEnabled bool +} + +// AssessmentCategoryReviewPins identify one exact reviewed source. The +// repository must not substitute a current opening or a different manifest. +// AssessmentCategoryDecisionRepository is bound to the finalization +// transaction. Its category lock is acquired after the caller has obtained +// C3, candidate/specialization scope, and the attempt row lock, in that order. +// The caller persists the returned result and any current-category update in +// this same transaction; no separate category-history table is needed. +type AssessmentCategoryDecisionRepository interface { + LockCandidateCategory(ctx context.Context, candidateID uuid.UUID, specialization domain.SpecializationCode) error + GetCandidateCategory( + ctx context.Context, + candidateID uuid.UUID, + specialization domain.SpecializationCode, + ) (domain.CandidateAssessmentCategory, bool, error) + GetSyntheticCategoryReview( + ctx context.Context, + openingID uuid.UUID, + category domain.AssessmentCategory, + openingManifestHash [32]byte, + productPolicyID domain.PolicyVersionID, + productPolicyVersion int32, + gradingPolicyID domain.PolicyVersionID, + ) (domain.AssessmentSyntheticCategoryReview, bool, error) +} + +// AssessmentCategoryDecisionPlan contains the immutable v2 result projection +// and the current-state write, if the confirmed grade advances. The caller +// must save both atomically with the completed attempt transition. +type AssessmentCategoryDecisionPlan struct { + Result domain.AssessmentAttemptResultHistoryEntry + Decision domain.AssessmentCategoryDecisionSnapshot + CurrentCategory *domain.CandidateAssessmentCategory + ReplaceCurrent bool +} + +// AssessmentCategoryDecisionService applies the explicit synthetic-category +// gate and the reviewed, pinned domain decision. It performs reads and locking +// only; the enclosing finalization transaction persists the plan atomically. +type AssessmentCategoryDecisionService struct { + settings AssessmentCategoryDecisionSettings +} + +func NewAssessmentCategoryDecisionService( + settings AssessmentCategoryDecisionSettings, +) AssessmentCategoryDecisionService { + return AssessmentCategoryDecisionService{settings: settings} +} + +// PrepareFinalizedResult reads the exact current category and optional +// synthetic review after the caller's C3, candidate/specialization, and +// attempt locks. V1 remains the stored shape for express training results; +// real root/corrective results get a v2 category projection even when the +// feature gate is off, so the contemporaneous current grade is explicit. +func (service AssessmentCategoryDecisionService) PrepareFinalizedResult( + ctx context.Context, + repository AssessmentCategoryDecisionRepository, + attempt domain.AssessmentAttempt, + result domain.AssessmentAttemptResultSnapshot, + policy domain.PolicyVersion, +) (AssessmentCategoryDecisionPlan, error) { + const location = "AssessmentCategoryDecisionService.PrepareFinalizedResult" + if repository == nil { + return AssessmentCategoryDecisionPlan{}, fmt.Errorf("%s - require repository: %w", location, ErrAssessmentCategoryRepositoryRequired) + } + input := domain.AssessmentCategoryDecisionInput{ + Attempt: attempt, Result: result, Policy: policy, + SyntheticDemoCategoryAssignmentEnabled: service.settings.SyntheticDemoAssignmentsEnabled, + } + preflight, err := domain.DecideAssessmentCategory(input) + if err != nil { + return AssessmentCategoryDecisionPlan{}, fmt.Errorf("%s - validate finalized result: %w", location, err) + } + if attempt.Kind() == domain.AssessmentAttemptKindDemoExpress { + return prepareTrainingCategoryResult(location, result, preflight) + } + return service.prepareRealFinalizedResult(ctx, location, repository, attempt, result, input) +} + +func prepareTrainingCategoryResult( + location string, + result domain.AssessmentAttemptResultSnapshot, + decision domain.AssessmentCategoryDecision, +) (AssessmentCategoryDecisionPlan, error) { + legacy, err := domain.NewLegacyAssessmentAttemptResultHistoryEntry(result) + if err != nil { + return AssessmentCategoryDecisionPlan{}, fmt.Errorf("%s - build training result view: %w", location, err) + } + return AssessmentCategoryDecisionPlan{Result: legacy, Decision: decision.Snapshot()}, nil +} + +func (service AssessmentCategoryDecisionService) prepareRealFinalizedResult( + ctx context.Context, + location string, + repository AssessmentCategoryDecisionRepository, + attempt domain.AssessmentAttempt, + result domain.AssessmentAttemptResultSnapshot, + input domain.AssessmentCategoryDecisionInput, +) (AssessmentCategoryDecisionPlan, error) { + track := attempt.Snapshot() + if track.Specialization == nil { + return AssessmentCategoryDecisionPlan{}, fmt.Errorf("%s - finalized real attempt has no specialization: %w", location, domain.ErrInvalidAssessmentCategory) + } + if err := repository.LockCandidateCategory(ctx, track.UserID, *track.Specialization); err != nil { + return AssessmentCategoryDecisionPlan{}, fmt.Errorf("%s - lock candidate category: %w", location, err) + } + current, found, err := repository.GetCandidateCategory(ctx, track.UserID, *track.Specialization) + if err != nil { + return AssessmentCategoryDecisionPlan{}, fmt.Errorf("%s - read candidate category: %w", location, err) + } + var currentPointer *domain.CandidateAssessmentCategory + if found { + if current.IsZero() { + return AssessmentCategoryDecisionPlan{}, fmt.Errorf("%s - repository returned an empty current category: %w", location, domain.ErrInvalidAssessmentCategory) + } + currentPointer = ¤t + } + + if service.settings.SyntheticDemoAssignmentsEnabled { + review, reviewFound, err := repository.GetSyntheticCategoryReview( + ctx, + result.Pins.OpeningID, + track.BankCategory, + result.Pins.OpeningManifestHash, + result.Pins.ProductPolicyVersionID, + result.Pins.ProductPolicyVersion, + result.Pins.GradingPolicyVersionID, + ) + if err != nil { + return AssessmentCategoryDecisionPlan{}, fmt.Errorf("%s - read pinned synthetic review: %w", location, err) + } + if reviewFound { + input.Review = &review + } + } + input.Current = currentPointer + decision, err := domain.DecideAssessmentCategory(input) + if err != nil { + return AssessmentCategoryDecisionPlan{}, fmt.Errorf("%s - decide category: %w", location, err) + } + decisionSnapshot := decision.Snapshot() + entry, err := domain.NewCategoryAssessmentAttemptResultHistoryEntry(result, decisionSnapshot) + if err != nil { + return AssessmentCategoryDecisionPlan{}, fmt.Errorf("%s - build immutable result v2 projection: %w", location, err) + } + currentValue, hasCurrent := decision.CurrentCategory() + plan := AssessmentCategoryDecisionPlan{ + Result: entry, Decision: decisionSnapshot, ReplaceCurrent: decision.ShouldUpdateCurrent(), + } + if hasCurrent { + plan.CurrentCategory = ¤tValue + } + return plan, nil +} diff --git a/backend/internal/usecase/assessment/category_history.go b/backend/internal/usecase/assessment/category_history.go new file mode 100644 index 0000000..73d34df --- /dev/null +++ b/backend/internal/usecase/assessment/category_history.go @@ -0,0 +1,245 @@ +package assessment + +import ( + "crypto/hmac" + "context" + "encoding/base64" + "encoding/binary" + "errors" + "fmt" + "strings" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +const ( + AssessmentResultHistoryDefaultLimit int32 = 20 + AssessmentResultHistoryMaxLimit int32 = 50 + assessmentResultHistoryMaxCursorBytes = 512 +) + +var ErrInvalidAssessmentResultHistoryRequest = errors.New("invalid assessment result history request") + +// AssessmentResultHistoryRecord is one owner-scoped row returned by the +// existing immutable attempt-result store. CandidateID is private and never +// part of the public response. +type AssessmentResultHistoryRecord struct { + CandidateID uuid.UUID + Entry domain.AssessmentAttemptResultHistoryEntry +} + +// AssessmentResultHistoryRepository reads the existing v1/v2 result records. +// Implementations must owner-scope the query and apply the supplied keyset. +type AssessmentResultHistoryRepository interface { + ListCandidateAssessmentResults( + ctx context.Context, + candidateID uuid.UUID, + cursor *outbound.AssessmentAttemptResultCursor, + limit int32, + ) (outbound.AssessmentAttemptResultPage, error) +} + +type AssessmentResultHistoryPage struct { + Entries []domain.AssessmentAttemptResultHistoryEntry + NextCursor string +} + +type AssessmentResultHistoryService struct { + repository AssessmentResultHistoryRepository + keyring Keyring +} + +func NewAssessmentResultHistoryService(repository AssessmentResultHistoryRepository, keyring Keyring) AssessmentResultHistoryService { + return AssessmentResultHistoryService{repository: repository, keyring: keyring} +} + +// ListMine returns completed root and corrective results in descending +// decided_at, attempt_id order. It does not look up current category state: +// legacy v1 records remain category-unknown and v2 uses only its captured +// current-grade value. +func (service AssessmentResultHistoryService) ListMine( + ctx context.Context, + candidateID uuid.UUID, + cursor string, + limit int32, +) (AssessmentResultHistoryPage, error) { + const location = "AssessmentResultHistoryService.ListMine" + if invalidAssessmentResultHistoryRequest(service.repository, service.keyring, candidateID, cursor, limit) { + return AssessmentResultHistoryPage{}, fmt.Errorf("%s - validate request: %w", location, ErrInvalidAssessmentResultHistoryRequest) + } + if limit == 0 { + limit = AssessmentResultHistoryDefaultLimit + } + keyset, err := decodeAssessmentResultHistoryCursor(service.keyring, candidateID, cursor) + if err != nil { + return AssessmentResultHistoryPage{}, fmt.Errorf("%s - decode owner cursor: %w", location, ErrInvalidAssessmentResultHistoryRequest) + } + page, err := service.repository.ListCandidateAssessmentResults(ctx, candidateID, keyset, limit) + if err != nil { + return AssessmentResultHistoryPage{}, fmt.Errorf("%s - read immutable results: %w", location, err) + } + entries, err := restoreAssessmentResultHistoryPage(candidateID, limit, page) + if err != nil { + return AssessmentResultHistoryPage{}, fmt.Errorf("%s - validate repository page: %w", location, err) + } + var nextCursor string + if page.HasMore { + last := entries[len(entries)-1] + nextCursor, err = encodeAssessmentResultHistoryCursor(service.keyring, candidateID, outbound.AssessmentAttemptResultCursor{ + DecidedAt: last.Result.DecidedAt, AttemptID: last.Result.Attempt.ID, + }) + if err != nil { + return AssessmentResultHistoryPage{}, fmt.Errorf("%s - sign owner cursor: %w", location, err) + } + } + return AssessmentResultHistoryPage{Entries: entries, NextCursor: nextCursor}, nil +} + +func invalidAssessmentResultHistoryRequest( + repository AssessmentResultHistoryRepository, + keyring Keyring, + candidateID uuid.UUID, + cursor string, + limit int32, +) bool { + return repository == nil || keyring == nil || candidateID == uuid.Nil || limit < 0 || limit > AssessmentResultHistoryMaxLimit || + len(cursor) > assessmentResultHistoryMaxCursorBytes +} + +const assessmentResultHistoryCursorOperation = "assessment.result-history.cursor.v1" + +const assessmentResultHistoryCursorPayloadSize = 8 + 4 + 16 + +func encodeAssessmentResultHistoryCursor( + keyring Keyring, + candidateID uuid.UUID, + cursor outbound.AssessmentAttemptResultCursor, +) (string, error) { + if keyring == nil || candidateID == uuid.Nil || cursor.AttemptID.IsZero() || cursor.DecidedAt.IsZero() || + cursor.DecidedAt.Nanosecond()%1000 != 0 { + return "", ErrInvalidAssessmentResultHistoryRequest + } + payload := make([]byte, assessmentResultHistoryCursorPayloadSize) + binary.BigEndian.PutUint64(payload[:8], uint64(cursor.DecidedAt.Unix())) + binary.BigEndian.PutUint32(payload[8:12], uint32(cursor.DecidedAt.Nanosecond())) + attemptID := cursor.AttemptID.UUID() + copy(payload[12:], attemptID[:]) + encodedPayload := base64.RawURLEncoding.EncodeToString(payload) + mac := keyring.IdempotencyScope(assessmentResultHistoryCursorOperation, encodedPayload, candidateID.String()) + return encodedPayload + "." + base64.RawURLEncoding.EncodeToString(mac[:]), nil +} + +func decodeAssessmentResultHistoryCursor( + keyring Keyring, + candidateID uuid.UUID, + token string, +) (*outbound.AssessmentAttemptResultCursor, error) { + if token == "" { + return nil, nil + } + if keyring == nil || candidateID == uuid.Nil || len(token) > assessmentResultHistoryMaxCursorBytes { + return nil, ErrInvalidAssessmentResultHistoryRequest + } + encodedPayload, encodedMAC, found := strings.Cut(token, ".") + if !found || encodedPayload == "" || encodedMAC == "" || strings.Contains(encodedMAC, ".") { + return nil, ErrInvalidAssessmentResultHistoryRequest + } + payload, err := base64.RawURLEncoding.DecodeString(encodedPayload) + if err != nil || len(payload) != assessmentResultHistoryCursorPayloadSize || + base64.RawURLEncoding.EncodeToString(payload) != encodedPayload { + return nil, ErrInvalidAssessmentResultHistoryRequest + } + suppliedMAC, err := base64.RawURLEncoding.DecodeString(encodedMAC) + if err != nil || len(suppliedMAC) != outbound.IdempotencyDigestSize || + base64.RawURLEncoding.EncodeToString(suppliedMAC) != encodedMAC { + return nil, ErrInvalidAssessmentResultHistoryRequest + } + expectedMAC := keyring.IdempotencyScope(assessmentResultHistoryCursorOperation, encodedPayload, candidateID.String()) + if !hmac.Equal(suppliedMAC, expectedMAC[:]) { + return nil, ErrInvalidAssessmentResultHistoryRequest + } + seconds := int64(binary.BigEndian.Uint64(payload[:8])) + nanos := binary.BigEndian.Uint32(payload[8:12]) + if nanos >= uint32(time.Second) || nanos%1000 != 0 { + return nil, ErrInvalidAssessmentResultHistoryRequest + } + var attemptUUID uuid.UUID + copy(attemptUUID[:], payload[12:]) + attemptID := domain.AssessmentAttemptID(attemptUUID) + if attemptID.IsZero() { + return nil, ErrInvalidAssessmentResultHistoryRequest + } + decidedAt := time.Unix(seconds, int64(nanos)).UTC() + if decidedAt.Unix() != seconds || uint32(decidedAt.Nanosecond()) != nanos { + return nil, ErrInvalidAssessmentResultHistoryRequest + } + return &outbound.AssessmentAttemptResultCursor{DecidedAt: decidedAt, AttemptID: attemptID}, nil +} + +func restoreAssessmentResultHistoryPage( + candidateID uuid.UUID, + limit int32, + page outbound.AssessmentAttemptResultPage, +) ([]domain.AssessmentAttemptResultHistoryEntry, error) { + const location = "restoreAssessmentResultHistoryPage" + if len(page.Records) > int(limit) || page.HasMore && len(page.Records) == 0 { + return nil, fmt.Errorf("%s - repository page exceeds bounds: %w", location, ErrAssessmentCategoryHistoryInvalid) + } + entries := make([]domain.AssessmentAttemptResultHistoryEntry, 0, len(page.Records)) + seen := make(map[domain.AssessmentAttemptID]struct{}, len(page.Records)) + var previous *domain.AssessmentAttemptResultHistoryEntry + for _, record := range page.Records { + entry, err := restoreAssessmentResultHistoryRecord(candidateID, AssessmentResultHistoryRecord{ + CandidateID: record.UserID, Entry: record.Entry, + }) + if err != nil { + return nil, fmt.Errorf("%s - restore immutable result: %w", location, err) + } + attemptID := entry.Result.Attempt.ID + if _, exists := seen[attemptID]; exists || previous != nil && !historyEntryFollows(*previous, entry) { + return nil, fmt.Errorf("%s - repository ordering or uniqueness is invalid: %w", location, ErrAssessmentCategoryHistoryInvalid) + } + seen[attemptID] = struct{}{} + entries = append(entries, entry) + previous = &entries[len(entries)-1] + } + return entries, nil +} + +func restoreAssessmentResultHistoryRecord( + candidateID uuid.UUID, + record AssessmentResultHistoryRecord, +) (domain.AssessmentAttemptResultHistoryEntry, error) { + if record.CandidateID != candidateID { + return domain.AssessmentAttemptResultHistoryEntry{}, fmt.Errorf("repository returned a foreign owner row: %w", ErrAssessmentCategoryHistoryInvalid) + } + entry, err := domain.RestoreAssessmentAttemptResultHistoryEntry(record.Entry) + if err != nil { + return domain.AssessmentAttemptResultHistoryEntry{}, fmt.Errorf("restore immutable result: %w", ErrAssessmentCategoryHistoryInvalid) + } + if !historyEntryIsEligible(entry) { + return domain.AssessmentAttemptResultHistoryEntry{}, fmt.Errorf("repository returned an ineligible result kind: %w", ErrAssessmentCategoryHistoryInvalid) + } + return entry, nil +} + +func historyEntryIsEligible(entry domain.AssessmentAttemptResultHistoryEntry) bool { + return entry.Result.Attempt.State == domain.AssessmentAttemptStateCompleted && + (entry.Result.Attempt.Kind == domain.AssessmentAttemptKindRoot || + entry.Result.Attempt.Kind == domain.AssessmentAttemptKindCorrective) +} + +func historyEntryFollows(previous, current domain.AssessmentAttemptResultHistoryEntry) bool { + previousAt, currentAt := previous.Result.DecidedAt, current.Result.DecidedAt + if currentAt.Before(previousAt) { + return true + } + if !currentAt.Equal(previousAt) { + return false + } + return current.Result.Attempt.ID.String() < previous.Result.Attempt.ID.String() +} diff --git a/backend/internal/usecase/assessment/category_history_test.go b/backend/internal/usecase/assessment/category_history_test.go new file mode 100644 index 0000000..cb298da --- /dev/null +++ b/backend/internal/usecase/assessment/category_history_test.go @@ -0,0 +1,168 @@ +package assessment + +import ( + "context" + "errors" + "strings" + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" +) + +func TestAssessmentResultHistoryReadsOwnerScopedV1WithoutInventingGrade(t *testing.T) { + ownerID := uuid.New() + policy := categoryServiceTestPolicy(t) + _, result := completedCategoryServiceAttempt(t, policy, ownerID, categoryServiceTestTime) + entry, err := domain.NewLegacyAssessmentAttemptResultHistoryEntry(result) + if err != nil { + t.Fatalf("NewLegacyAssessmentAttemptResultHistoryEntry() error = %v", err) + } + repository := &assessmentResultHistoryRepositoryFake{page: AssessmentResultHistoryRepositoryPage{ + Records: []AssessmentResultHistoryRecord{{CandidateID: ownerID, Entry: entry}}, NextCursor: "next-page-token", + }} + service := NewAssessmentResultHistoryService(repository) + + page, err := service.ListMine(t.Context(), ownerID, "", 0) + if err != nil { + t.Fatalf("ListMine(default limit) error = %v", err) + } + if repository.ownerID != ownerID || repository.cursor != "" || repository.limit != AssessmentResultHistoryDefaultLimit { + t.Fatalf("repository request = owner %s cursor %q limit %d", repository.ownerID, repository.cursor, repository.limit) + } + if len(page.Entries) != 1 || page.NextCursor != "next-page-token" || + page.Entries[0].SchemaVersion != domain.AssessmentAttemptResultHistorySchemaV1 || + page.Entries[0].CategoryDecision != nil || page.Entries[0].CurrentConfirmedGrade != nil { + t.Fatalf("history page = %+v, want one legacy result with unknown category", page) + } +} + +func TestAssessmentResultHistoryRejectsForeignOwnerAndExpressRows(t *testing.T) { + ownerID := uuid.New() + policy := categoryServiceTestPolicy(t) + attempt, result := completedCategoryServiceAttempt(t, policy, ownerID, categoryServiceTestTime) + entry, err := domain.NewLegacyAssessmentAttemptResultHistoryEntry(result) + if err != nil { + t.Fatalf("NewLegacyAssessmentAttemptResultHistoryEntry() error = %v", err) + } + service := NewAssessmentResultHistoryService(&assessmentResultHistoryRepositoryFake{ + page: AssessmentResultHistoryRepositoryPage{Records: []AssessmentResultHistoryRecord{{CandidateID: uuid.New(), Entry: entry}}}, + }) + if _, err := service.ListMine(t.Context(), ownerID, "", 10); !errors.Is(err, ErrAssessmentCategoryHistoryInvalid) { + t.Fatalf("ListMine(foreign owner) error = %v, want invalid history", err) + } + + express, expressResult := completedExpressCategoryServiceAttempt(t, policy, ownerID, categoryServiceTestTime) + expressEntry, err := domain.NewLegacyAssessmentAttemptResultHistoryEntry(expressResult) + if err != nil { + t.Fatalf("NewLegacyAssessmentAttemptResultHistoryEntry(express) error = %v", err) + } + service = NewAssessmentResultHistoryService(&assessmentResultHistoryRepositoryFake{ + page: AssessmentResultHistoryRepositoryPage{Records: []AssessmentResultHistoryRecord{{CandidateID: ownerID, Entry: expressEntry}}}, + }) + if _, err := service.ListMine(t.Context(), ownerID, "", 10); !errors.Is(err, ErrAssessmentCategoryHistoryInvalid) { + t.Fatalf("ListMine(express row) error = %v, want invalid history", err) + } + if express.Kind() != domain.AssessmentAttemptKindDemoExpress || attempt.Kind() != domain.AssessmentAttemptKindRoot { + t.Fatal("fixture attempt kinds changed unexpectedly") + } +} + +func TestAssessmentResultHistoryRejectsInvalidBoundsAndDuplicateResults(t *testing.T) { + ownerID := uuid.New() + policy := categoryServiceTestPolicy(t) + _, result := completedCategoryServiceAttempt(t, policy, ownerID, categoryServiceTestTime) + entry, err := domain.NewLegacyAssessmentAttemptResultHistoryEntry(result) + if err != nil { + t.Fatalf("NewLegacyAssessmentAttemptResultHistoryEntry() error = %v", err) + } + repository := &assessmentResultHistoryRepositoryFake{page: AssessmentResultHistoryRepositoryPage{ + Records: []AssessmentResultHistoryRecord{{CandidateID: ownerID, Entry: entry}}, + }} + service := NewAssessmentResultHistoryService(repository) + if _, err := service.ListMine(t.Context(), ownerID, strings.Repeat("x", assessmentResultHistoryMaxCursorBytes+1), 1); !errors.Is(err, ErrInvalidAssessmentResultHistoryRequest) { + t.Fatalf("ListMine(oversized cursor) error = %v, want invalid request", err) + } + if _, err := service.ListMine(t.Context(), ownerID, "", AssessmentResultHistoryMaxLimit+1); !errors.Is(err, ErrInvalidAssessmentResultHistoryRequest) { + t.Fatalf("ListMine(oversized limit) error = %v, want invalid request", err) + } + repository.page.NextCursor = strings.Repeat("x", assessmentResultHistoryMaxCursorBytes+1) + if _, err := service.ListMine(t.Context(), ownerID, "", 1); !errors.Is(err, ErrAssessmentCategoryHistoryInvalid) { + t.Fatalf("ListMine(oversized next cursor) error = %v, want invalid history", err) + } + repository.page.NextCursor = "" + + repository.page.Records = append(repository.page.Records, + AssessmentResultHistoryRecord{CandidateID: ownerID, Entry: entry}) + if _, err := service.ListMine(t.Context(), ownerID, "", 2); !errors.Is(err, ErrAssessmentCategoryHistoryInvalid) { + t.Fatalf("ListMine(duplicate result) error = %v, want invalid history", err) + } +} + +func TestAssessmentResultHistoryOrdersTiedDecisionsByAttemptIDDescending(t *testing.T) { + ownerID := uuid.New() + policy := categoryServiceTestPolicy(t) + _, result := completedCategoryServiceAttempt(t, policy, ownerID, categoryServiceTestTime) + decidedAt := time.Date(2026, time.September, 1, 11, 0, 0, 0, time.UTC) + + entryForID := func(id string) domain.AssessmentAttemptResultHistoryEntry { + t.Helper() + resultCopy := result + resultCopy.Attempt.ID = domain.AssessmentAttemptID(uuid.MustParse(id)) + resultCopy.DecidedAt = decidedAt + resultCopy.Attempt.FinishedAt = &decidedAt + entry, err := domain.NewLegacyAssessmentAttemptResultHistoryEntry(resultCopy) + if err != nil { + t.Fatalf("NewLegacyAssessmentAttemptResultHistoryEntry(%s) error = %v", id, err) + } + return entry + } + + higherID := entryForID("ffffffff-ffff-4fff-bfff-ffffffffffff") + lowerID := entryForID("00000000-0000-4000-8000-000000000001") + service := NewAssessmentResultHistoryService(&assessmentResultHistoryRepositoryFake{ + page: AssessmentResultHistoryRepositoryPage{Records: []AssessmentResultHistoryRecord{ + {CandidateID: ownerID, Entry: higherID}, + {CandidateID: ownerID, Entry: lowerID}, + }}, + }) + page, err := service.ListMine(t.Context(), ownerID, "", 2) + if err != nil { + t.Fatalf("ListMine(descending tie order) error = %v", err) + } + if len(page.Entries) != 2 || page.Entries[0].Result.Attempt.ID.String() <= page.Entries[1].Result.Attempt.ID.String() { + t.Fatalf("tied attempt IDs = %v, want descending order", []string{ + page.Entries[0].Result.Attempt.ID.String(), page.Entries[1].Result.Attempt.ID.String(), + }) + } + + service = NewAssessmentResultHistoryService(&assessmentResultHistoryRepositoryFake{ + page: AssessmentResultHistoryRepositoryPage{Records: []AssessmentResultHistoryRecord{ + {CandidateID: ownerID, Entry: lowerID}, + {CandidateID: ownerID, Entry: higherID}, + }}, + }) + if _, err := service.ListMine(t.Context(), ownerID, "", 2); !errors.Is(err, ErrAssessmentCategoryHistoryInvalid) { + t.Fatalf("ListMine(ascending tie order) error = %v, want invalid history", err) + } +} + +type assessmentResultHistoryRepositoryFake struct { + page AssessmentResultHistoryRepositoryPage + ownerID uuid.UUID + cursor string + limit int32 + readErr error +} + +func (repository *assessmentResultHistoryRepositoryFake) ListCandidateAssessmentResults( + _ context.Context, + ownerID uuid.UUID, + cursor string, + limit int32, +) (AssessmentResultHistoryRepositoryPage, error) { + repository.ownerID, repository.cursor, repository.limit = ownerID, cursor, limit + return repository.page, repository.readErr +} diff --git a/backend/internal/usecase/assessment/category_test.go b/backend/internal/usecase/assessment/category_test.go new file mode 100644 index 0000000..2782891 --- /dev/null +++ b/backend/internal/usecase/assessment/category_test.go @@ -0,0 +1,377 @@ +package assessment + +import ( + "context" + "encoding/json" + "fmt" + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" +) + +func TestAssessmentCategoryDecisionServiceRequiresDefaultOffGate(t *testing.T) { + userID := uuid.New() + policy := categoryServiceTestPolicy(t) + attempt, result := completedCategoryServiceAttempt(t, policy, userID, categoryServiceTestTime) + current := categoryServiceCurrent(t, attempt, policy, domain.GradeIntern) + review := categoryServiceReview(t, attempt, result, policy) + repository := &categoryDecisionRepositoryFake{current: ¤t, review: &review} + service := NewAssessmentCategoryDecisionService(AssessmentCategoryDecisionSettings{}) + + plan, err := service.PrepareFinalizedResult(t.Context(), repository, attempt, result, policy) + if err != nil { + t.Fatalf("PrepareFinalizedResult(default gate) error = %v", err) + } + if plan.Decision.Status != domain.AssessmentCategoryDecisionNotEligible || plan.ReplaceCurrent || + plan.CurrentCategory == nil || plan.CurrentCategory.Snapshot().Grade != domain.GradeIntern || + plan.Result.SchemaVersion != domain.AssessmentAttemptResultHistorySchemaV2 || + plan.Result.CurrentConfirmedGrade == nil || *plan.Result.CurrentConfirmedGrade != domain.GradeIntern { + t.Fatalf("default-off plan = %+v, want existing category captured without assignment", plan) + } + if len(repository.calls) != 2 || repository.calls[0] != "lock" || repository.calls[1] != "current" { + t.Fatalf("repository calls = %v, want category lock and current read only", repository.calls) + } +} + +func TestAssessmentCategoryDecisionServiceAssignsOnlyTheExactReviewedPolicySource(t *testing.T) { + userID := uuid.New() + policy := categoryServiceTestPolicy(t) + attempt, result := completedCategoryServiceAttempt(t, policy, userID, categoryServiceTestTime) + review := categoryServiceReview(t, attempt, result, policy) + repository := &categoryDecisionRepositoryFake{review: &review} + service := NewAssessmentCategoryDecisionService(AssessmentCategoryDecisionSettings{ + SyntheticDemoAssignmentsEnabled: true, + }) + + plan, err := service.PrepareFinalizedResult(t.Context(), repository, attempt, result, policy) + if err != nil { + t.Fatalf("PrepareFinalizedResult(reviewed source) error = %v", err) + } + if plan.Decision.Status != domain.AssessmentCategoryDecisionAssigned || !plan.ReplaceCurrent || + plan.CurrentCategory == nil || plan.CurrentCategory.Snapshot().Grade != domain.GradeJunior || + plan.Result.SchemaVersion != domain.AssessmentAttemptResultHistorySchemaV2 || + plan.Result.CurrentConfirmedGrade == nil || *plan.Result.CurrentConfirmedGrade != domain.GradeJunior { + t.Fatalf("reviewed plan = %+v, want pinned junior category assignment", plan) + } + if repository.reviewPins.Category != attempt.Snapshot().BankCategory || + repository.reviewPins.OpeningID != result.Pins.OpeningID || + repository.reviewPins.OpeningManifestHash != result.Pins.OpeningManifestHash || + repository.reviewPins.ProductPolicyVersionID != result.Pins.ProductPolicyVersionID || + repository.reviewPins.ProductPolicyVersion != result.Pins.ProductPolicyVersion { + t.Fatalf("review query pins = %+v, want exact finalized source pins", repository.reviewPins) + } +} + +func TestAssessmentCategoryDecisionServiceKeepsExpressTrainingOutOfCategoryStorage(t *testing.T) { + userID := uuid.New() + policy := categoryServiceTestPolicy(t) + attempt, result := completedExpressCategoryServiceAttempt(t, policy, userID, categoryServiceTestTime) + repository := &categoryDecisionRepositoryFake{} + service := NewAssessmentCategoryDecisionService(AssessmentCategoryDecisionSettings{ + SyntheticDemoAssignmentsEnabled: true, + }) + + plan, err := service.PrepareFinalizedResult(t.Context(), repository, attempt, result, policy) + if err != nil { + t.Fatalf("PrepareFinalizedResult(express) error = %v", err) + } + if plan.Decision.Status != domain.AssessmentCategoryDecisionTrainingOnly || plan.ReplaceCurrent || + plan.Result.SchemaVersion != domain.AssessmentAttemptResultHistorySchemaV1 || + plan.Result.CategoryDecision != nil || plan.Result.CurrentConfirmedGrade != nil || len(repository.calls) != 0 { + t.Fatalf("express plan = %+v with calls %v, want training-only v1 and no category reads", plan, repository.calls) + } +} + +type categoryDecisionRepositoryFake struct { + calls []string + current *domain.CandidateAssessmentCategory + review *domain.AssessmentSyntheticCategoryReview + reviewPins AssessmentCategoryReviewPins +} + +func (repository *categoryDecisionRepositoryFake) LockCandidateCategory( + context.Context, + uuid.UUID, + domain.SpecializationCode, +) error { + repository.calls = append(repository.calls, "lock") + return nil +} + +func (repository *categoryDecisionRepositoryFake) GetCandidateCategory( + context.Context, + uuid.UUID, + domain.SpecializationCode, +) (domain.CandidateAssessmentCategory, bool, error) { + repository.calls = append(repository.calls, "current") + if repository.current == nil { + return domain.CandidateAssessmentCategory{}, false, nil + } + return *repository.current, true, nil +} + +func (repository *categoryDecisionRepositoryFake) GetSyntheticCategoryReview( + _ context.Context, + pins AssessmentCategoryReviewPins, +) (domain.AssessmentSyntheticCategoryReview, bool, error) { + repository.calls = append(repository.calls, "review") + repository.reviewPins = pins + if repository.review == nil { + return domain.AssessmentSyntheticCategoryReview{}, false, nil + } + snapshot := repository.review.Snapshot() + if snapshot.Category != pins.Category || snapshot.OpeningID != pins.OpeningID || + snapshot.OpeningManifestHash != pins.OpeningManifestHash || + snapshot.ProductPolicyVersionID != pins.ProductPolicyVersionID || + snapshot.ProductPolicyVersion != pins.ProductPolicyVersion { + return domain.AssessmentSyntheticCategoryReview{}, false, nil + } + return *repository.review, true, nil +} + +var categoryServiceTestTime = time.Date(2026, time.September, 1, 10, 0, 0, 0, time.UTC) + +const categoryServiceCorrectAnswers = 19 + +func categoryServiceTestPolicy(t *testing.T) domain.PolicyVersion { + t.Helper() + draft, err := domain.NewPolicyVersionDraft(domain.NewPolicyVersionDraftInput{ + Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: domain.DemoPolicySeedAuthor, + EffectiveAt: categoryServiceTestTime, Policy: domain.DemoProductPolicyV2(), + }) + if err != nil { + t.Fatalf("NewPolicyVersionDraft() error = %v", err) + } + numbered, err := draft.WithVersion(2) + if err != nil { + t.Fatalf("PolicyVersionDraft.WithVersion() error = %v", err) + } + hash := numbered.DocumentHash() + policy, err := domain.RestorePolicyVersion(domain.StoredPolicyVersion{ + ID: numbered.ID(), Key: string(numbered.Key()), Version: numbered.Version(), Kind: string(numbered.Kind()), + Author: string(numbered.Author()), EffectiveAt: categoryServiceTestTime, CreatedAt: categoryServiceTestTime, + Document: numbered.Document(), DocumentHash: hash[:], + }) + if err != nil { + t.Fatalf("RestorePolicyVersion() error = %v", err) + } + return policy +} + +func completedCategoryServiceAttempt( + t *testing.T, + policy domain.PolicyVersion, + userID uuid.UUID, + createdAt time.Time, +) (domain.AssessmentAttempt, domain.AssessmentAttemptResultSnapshot) { + t.Helper() + items := categoryServiceAttemptItems(t, int(policy.Policy().Assessment.StopRule.MaxScoredItems+policy.Policy().Assessment.StopRule.SeedItems)) + specialization, grade := domain.SpecializationBackend, domain.GradeJunior + attempt, err := domain.NewAssessmentAttempt(domain.NewAssessmentAttemptInput{ + UserID: userID, Kind: domain.AssessmentAttemptKindRoot, BankCategory: "backend", + Specialization: &specialization, TargetGrade: &grade, Versions: categoryServiceAttemptVersions(t, policy), + Policy: policy, CreatedAt: createdAt, Items: items, + }) + if err != nil { + t.Fatalf("NewAssessmentAttempt() error = %v", err) + } + attempt = submitCategoryServiceAnswers(t, attempt, categoryServiceCorrectAnswers, createdAt) + completed, changed, decision, err := attempt.FinalizeDemo( + attempt.Version(), policy.Policy().Assessment, createdAt.Add(time.Duration(len(items)+2)*time.Second), + ) + if err != nil || !changed { + t.Fatalf("FinalizeDemo() = changed %v, error %v", changed, err) + } + result, err := domain.NewAssessmentAttemptResultSnapshot(completed, decision, "", []string{"uncalibrated_thresholds"}) + if err != nil { + t.Fatalf("NewAssessmentAttemptResultSnapshot() error = %v", err) + } + return completed, result +} + +func completedExpressCategoryServiceAttempt( + t *testing.T, + policy domain.PolicyVersion, + userID uuid.UUID, + createdAt time.Time, +) (domain.AssessmentAttempt, domain.AssessmentAttemptResultSnapshot) { + t.Helper() + items := categoryServiceAttemptItems(t, int(policy.Policy().Assessment.Training.DemoExpressItemCount)) + attempt, err := domain.NewAssessmentAttempt(domain.NewAssessmentAttemptInput{ + UserID: userID, Kind: domain.AssessmentAttemptKindDemoExpress, BankCategory: "training-demo", + Versions: domain.AssessmentAttemptVersions{ + ProductPolicyVersionID: policy.ID(), ProductPolicyVersion: policy.Version(), + TrainingBindingID: uuid.New(), TrainingManifestHash: categoryServiceManifestHash(2), + BankVersion: "training-demo.v1", AlgorithmVersion: "assessment.v1", + }, + Policy: policy, CreatedAt: createdAt, Items: items, + }) + if err != nil { + t.Fatalf("NewAssessmentAttempt(express) error = %v", err) + } + attempt = submitCategoryServiceAnswers(t, attempt, len(items), createdAt) + completed, changed, decision, err := attempt.FinalizeDemo( + attempt.Version(), policy.Policy().Assessment, createdAt.Add(time.Duration(len(items)+2)*time.Second), + ) + if err != nil || !changed { + t.Fatalf("FinalizeDemo(express) = changed %v, error %v", changed, err) + } + result, err := domain.NewAssessmentAttemptResultSnapshot( + completed, decision, "Training only.", []string{"demonstration_only"}, + ) + if err != nil { + t.Fatalf("NewAssessmentAttemptResultSnapshot(express) error = %v", err) + } + return completed, result +} + +func submitCategoryServiceAnswers( + t *testing.T, + attempt domain.AssessmentAttempt, + correctCount int, + createdAt time.Time, +) domain.AssessmentAttempt { + t.Helper() + for index, item := range attempt.Snapshot().Items { + reference := item.Variant.ReferenceAnswer + if index >= correctCount { + reference += "1" + } + answer := json.RawMessage(fmt.Sprintf(`{"format":"number","number":%s}`, reference)) + 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 + } + return attempt +} + +func categoryServiceAttemptItems(t *testing.T, count int) []domain.AssessmentAttemptItemInput { + t.Helper() + items := make([]domain.AssessmentAttemptItemInput, count) + for index := range items { + family := categoryServiceFamily(t, index) + variant, err := family.NewVariant(domain.VariantSeed(index + 1)) + if err != nil { + t.Fatalf("AssessmentFamily.NewVariant(%d) error = %v", index, err) + } + items[index] = domain.AssessmentAttemptItemInput{Variant: variant} + } + return items +} + +func categoryServiceFamily(t *testing.T, index int) domain.AssessmentFamily { + t.Helper() + draft, err := domain.NewAssessmentFamilyDraft(domain.NewAssessmentFamilyDraftInput{ + Key: domain.AssessmentFamilyKey(fmt.Sprintf("category-service-family-%02d", index)), + Version: 1, Category: "backend", Specialization: "backend", Title: fmt.Sprintf("Category fixture %02d", index), + BundleName: "category-service-fixture", Author: "ai:category-service-test", ReviewStatus: domain.AssessmentReviewPending, + Generator: domain.AssessmentSeedGenerator{ + Algorithm: "lru_hits.v1", Parameters: map[string]domain.AssessmentParameterRange{ + "accesses": {Min: 10, Max: 30}, "keys": {Min: 3, Max: 8}, "capacity": {Min: 2, Max: 4}, + }, + StatementTemplate: "Capacity {{.capacity}}, reads {{.sequence}}.", + }, + AnswerKey: domain.AssessmentAnswerKey{AnswerFormat: domain.AnswerFormatInteger, ReferenceSolution: "Simulate the cache."}, + Rubric: domain.AssessmentRubric{ + Principle: "Compare with the reference answer.", + Criteria: []domain.AssessmentRubricCriterion{{ID: "correct_answer", Description: "Matches the reference answer."}}, + }, + }) + if err != nil { + t.Fatalf("NewAssessmentFamilyDraft() error = %v", err) + } + core, hash := draft.Core(), draft.ContentHash() + generator, err := draft.SeedGeneratorJSON() + if err != nil { + t.Fatalf("SeedGeneratorJSON() error = %v", err) + } + answerKey, err := draft.AnswerKeyJSON() + if err != nil { + t.Fatalf("AnswerKeyJSON() error = %v", err) + } + rubric, err := draft.RubricJSON() + if err != nil { + t.Fatalf("RubricJSON() error = %v", err) + } + family, err := domain.RestoreAssessmentFamily(domain.StoredAssessmentFamily{ + ID: draft.ID(), FamilyKey: string(core.Key), Version: core.Version, Category: string(core.Category), + Specialization: string(core.Specialization), Title: core.Title, BundleName: string(core.BundleName), + Author: string(core.Author), Reviewer: string(core.Reviewer), ReviewStatus: string(core.ReviewStatus), + SeedGenerator: generator, AnswerKey: answerKey, Rubric: rubric, ContentHash: hash[:], + HashScheme: draft.HashScheme(), Lifecycle: string(domain.AssessmentLifecycleDraft), CreatedAt: categoryServiceTestTime, + }) + if err != nil { + t.Fatalf("RestoreAssessmentFamily() error = %v", err) + } + return family +} + +func categoryServiceAttemptVersions(t *testing.T, policy domain.PolicyVersion) domain.AssessmentAttemptVersions { + t.Helper() + gradingID, err := domain.NewPolicyVersionID() + if err != nil { + t.Fatalf("NewPolicyVersionID() error = %v", err) + } + return domain.AssessmentAttemptVersions{ + ProductPolicyVersionID: policy.ID(), ProductPolicyVersion: policy.Version(), + GradingPolicyVersionID: gradingID, OpeningID: uuid.New(), OpeningManifestHash: categoryServiceManifestHash(1), + BankVersion: "backend-demo.v1", AlgorithmVersion: "assessment.v1", + } +} + +func categoryServiceManifestHash(value byte) [32]byte { + var digest [32]byte + digest[0] = value + return digest +} + +func categoryServiceReview( + t *testing.T, + attempt domain.AssessmentAttempt, + result domain.AssessmentAttemptResultSnapshot, + policy domain.PolicyVersion, +) domain.AssessmentSyntheticCategoryReview { + t.Helper() + reviewer, err := domain.ParseAssessmentOperator("operator:category-reviewer") + if err != nil { + t.Fatalf("ParseAssessmentOperator() error = %v", err) + } + pins := result.Pins + review, err := domain.NewAssessmentSyntheticCategoryReview(domain.AssessmentSyntheticCategoryReviewSnapshot{ + ID: uuid.New(), OpeningID: pins.OpeningID, Category: attempt.Snapshot().BankCategory, + Source: domain.AssessmentCategorySourceSyntheticDemo, + OpeningManifestHash: pins.OpeningManifestHash, ProductPolicyVersionID: policy.ID(), + ProductPolicyVersion: policy.Version(), ReviewedBy: reviewer, ReviewedAt: result.DecidedAt, + }) + if err != nil { + t.Fatalf("NewAssessmentSyntheticCategoryReview() error = %v", err) + } + return review +} + +func categoryServiceCurrent( + t *testing.T, + attempt domain.AssessmentAttempt, + policy domain.PolicyVersion, + grade domain.GradeCode, +) domain.CandidateAssessmentCategory { + t.Helper() + snapshot := attempt.Snapshot() + category, err := domain.RestoreCandidateAssessmentCategory(domain.CandidateAssessmentCategorySnapshot{ + CandidateID: snapshot.UserID, Specialization: *snapshot.Specialization, Grade: grade, + SourceAttemptID: domain.AssessmentAttemptID(uuid.New()), SourceReviewID: uuid.New(), + ProductPolicyVersionID: policy.ID(), ProductPolicyVersion: policy.Version(), + OpeningID: snapshot.Versions.OpeningID, OpeningManifestHash: snapshot.Versions.OpeningManifestHash, + Source: domain.AssessmentCategorySourceSyntheticDemo, + CalibrationStatus: domain.AssessmentCategoryCalibrationUncalibrated, AssignedAt: categoryServiceTestTime, + }) + if err != nil { + t.Fatalf("RestoreCandidateAssessmentCategory() error = %v", err) + } + return category +} diff --git a/backend/internal/usecase/assessment/finalize.go b/backend/internal/usecase/assessment/finalize.go index ce0af80..4d8fea0 100644 --- a/backend/internal/usecase/assessment/finalize.go +++ b/backend/internal/usecase/assessment/finalize.go @@ -32,6 +32,7 @@ type canonicalAttemptFinalizeBody struct { type AssessmentAttemptResult struct { Attempt domain.AssessmentAttemptPublicSnapshot Outcome domain.AssessmentAttemptOutcome + CategoryDecision *domain.AssessmentCategoryDecisionSnapshot NotDeterminedReason string BasicScore *domain.AssessmentBasicScore Limitations []string @@ -148,6 +149,20 @@ func lockAttemptForFinalize( if err := lockSessionConsent(ctx, unit, command.ActorID, kind); err != nil { return domain.AssessmentAttempt{}, fmt.Errorf("%s - authorize finalization: %w", location, err) } + selected, err := repository.GetForCandidate(ctx, command.ActorID, command.AttemptID) + if err != nil { + if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) { + return domain.AssessmentAttempt{}, outbound.ErrAssessmentAttemptNotFound + } + return domain.AssessmentAttempt{}, fmt.Errorf("%s - read candidate scope before attempt lock: %w", location, err) + } + selectedSnapshot := selected.Snapshot() + if selected.Kind() != kind { + return domain.AssessmentAttempt{}, fmt.Errorf("%s - immutable attempt kind changed before lock: %w", location, domain.ErrInvalidAssessmentAttempt) + } + if err := repository.LockScope(ctx, command.ActorID, selectedSnapshot.Specialization); err != nil { + return domain.AssessmentAttempt{}, fmt.Errorf("%s - lock candidate and specialization scope: %w", location, err) + } current, err := repository.GetForCandidateForUpdate(ctx, command.ActorID, command.AttemptID) if err != nil { if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) { @@ -155,8 +170,9 @@ func lockAttemptForFinalize( } return domain.AssessmentAttempt{}, fmt.Errorf("%s - lock owner-scoped attempt: %w", location, err) } - if current.Kind() != kind { - return domain.AssessmentAttempt{}, fmt.Errorf("%s - immutable attempt kind changed: %w", location, domain.ErrInvalidAssessmentAttempt) + if current.Kind() != kind || current.Snapshot().Specialization == nil && selectedSnapshot.Specialization != nil || + current.Snapshot().Specialization != nil && (selectedSnapshot.Specialization == nil || *current.Snapshot().Specialization != *selectedSnapshot.Specialization) { + return domain.AssessmentAttempt{}, fmt.Errorf("%s - immutable attempt scope changed: %w", location, domain.ErrInvalidAssessmentAttempt) } return current, nil } @@ -228,10 +244,10 @@ func (service *AttemptService) finalizeActiveAttempt( } return fmt.Errorf("%s - calculate pinned decision: %w", location, finalizeErr) } - return persistFinalizedAttempt(ctx, repository, scope, command, current, updated, changed, decision, result) + return service.persistFinalizedAttempt(ctx, repository, scope, command, current, updated, changed, decision, policy, result) } -func persistFinalizedAttempt( +func (service *AttemptService) persistFinalizedAttempt( ctx context.Context, repository outbound.AssessmentAttemptRepository, scope outbound.AssessmentAttemptIdempotencyScope, @@ -239,6 +255,7 @@ func persistFinalizedAttempt( current, updated domain.AssessmentAttempt, changed bool, decision domain.AssessmentAttemptDecision, + policy domain.PolicyVersion, result *outbound.AssessmentAttemptCommandResult, ) error { const location = "AttemptService.persistFinalizedAttempt" @@ -251,8 +268,22 @@ func persistFinalizedAttempt( if err != nil { return fmt.Errorf("%s - build immutable result snapshot: %w", location, err) } - if err := repository.SaveResult(ctx, command.ActorID, storedResult); err != nil { - return fmt.Errorf("%s - persist immutable result snapshot: %w", location, err) + categoryPlan, err := service.categoryDecisions.PrepareFinalizedResult( + ctx, repository, updated, storedResult, policy, + ) + if err != nil { + return fmt.Errorf("%s - prepare immutable category result: %w", location, err) + } + if err := repository.SaveResultHistoryEntry(ctx, command.ActorID, categoryPlan.Result); err != nil { + return fmt.Errorf("%s - persist immutable result history entry: %w", location, err) + } + if categoryPlan.ReplaceCurrent { + if categoryPlan.CurrentCategory == nil { + return fmt.Errorf("%s - category plan lacks assigned current value: %w", location, domain.ErrInvalidAssessmentCategory) + } + if err := repository.SaveCandidateAssessmentCategory(ctx, *categoryPlan.CurrentCategory); err != nil { + return fmt.Errorf("%s - persist current category: %w", location, err) + } } } outcome := outbound.AssessmentAttemptCommandOutcome{StatusCode: 200, Response: updated.PublicSnapshot()} @@ -343,14 +374,20 @@ func readCompletedAttemptResult( attempt domain.AssessmentAttempt, ) (AssessmentAttemptResult, error) { const location = "AttemptService.readCompletedAttemptResult" - stored, err := unit.AssessmentAttempts().GetResult(ctx, userID, attemptID) + stored, err := unit.AssessmentAttempts().GetResultHistoryEntry(ctx, userID, attemptID) if err != nil { return AssessmentAttemptResult{}, fmt.Errorf("%s - read immutable result: %w", location, err) } - if !assessmentResultMatchesAttempt(stored, attempt) { + if !assessmentResultMatchesAttempt(stored.Result, attempt) { return AssessmentAttemptResult{}, fmt.Errorf("%s - immutable result does not match its attempt: %w", location, domain.ErrInvalidAssessmentAttempt) } - return assessmentAttemptResultFromSnapshot(stored), nil + entry, err := domain.RestoreAssessmentAttemptResultHistoryEntry(stored) + if err != nil { + return AssessmentAttemptResult{}, fmt.Errorf("%s - restore stored category result: %w", location, err) + } + result := assessmentAttemptResultFromSnapshot(entry.Result) + result.CategoryDecision = entry.CategoryDecision + return result, nil } func terminalAttemptResult(attempt domain.AssessmentAttempt) (AssessmentAttemptResult, error) { diff --git a/backend/internal/usecase/notification/inbox.go b/backend/internal/usecase/notification/inbox.go new file mode 100644 index 0000000..fb872ad --- /dev/null +++ b/backend/internal/usecase/notification/inbox.go @@ -0,0 +1,231 @@ +package notification + +import ( + "context" + "errors" + "fmt" + "net/url" + "strings" + "time" + "unicode/utf8" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +var ( + ErrInboxUnavailable = errors.New("notification inbox is unavailable") + // ErrInboxContentUnavailable means the referenced source is missing or its + // current visibility no longer permits the original presentation. + ErrInboxContentUnavailable = errors.New("notification content is unavailable") +) + +const ( + maxInboxTitleRunes = 120 + maxInboxSummaryRunes = 500 +) + +// InboxContent is resolved from the current source at read time. It is never +// written to notification_inbox_events. +type InboxContent struct { + title string + summary string + linkPath string +} + +// NewInboxContent validates a small same-origin presentation returned by a +// source resolver after its current visibility checks. +func NewInboxContent(title, summary, linkPath string) (InboxContent, error) { + const location = "notification.NewInboxContent" + if !validInboxText(title, maxInboxTitleRunes, false) || !validInboxText(summary, maxInboxSummaryRunes, true) { + return InboxContent{}, fmt.Errorf("%s - title and summary are invalid: %w", location, ErrInboxUnavailable) + } + if linkPath != "" && !validInboxLinkPath(linkPath) { + return InboxContent{}, fmt.Errorf("%s - link path must be relative and same-origin: %w", location, ErrInboxUnavailable) + } + return InboxContent{title: title, summary: summary, linkPath: linkPath}, nil +} + +func (content InboxContent) Title() string { return content.title } +func (content InboxContent) Summary() string { return content.summary } +func (content InboxContent) LinkPath() string { return content.linkPath } + +func validInboxText(value string, maxRunes int, allowNewlines bool) bool { + if !utf8.ValidString(value) || value == "" || strings.TrimSpace(value) != value || utf8.RuneCountInString(value) > maxRunes { + return false + } + for _, character := range value { + if character == 0 || (character < 0x20 && !(allowNewlines && (character == '\n' || character == '\t'))) || character == 0x7f { + return false + } + } + return true +} + +func validInboxLinkPath(value string) bool { + if !strings.HasPrefix(value, "/") || strings.HasPrefix(value, "//") || strings.ContainsAny(value, "\\?#%") { + return false + } + parsed, err := url.ParseRequestURI(value) + if err != nil || parsed.IsAbs() || parsed.Host != "" || parsed.Path != value { + return false + } + for _, segment := range strings.Split(value, "/") { + if segment == "." || segment == ".." { + return false + } + } + return true +} + +// InboxContentResolver reads the current source under its current visibility +// rules. It must return ErrInboxContentUnavailable when that source is gone or +// no longer safe to present. +type InboxContentResolver interface { + Resolve(ctx context.Context, entry domain.NotificationInboxEntry) (InboxContent, error) +} + +// InboxItem pairs immutable event metadata with content resolved for this +// read. Content is nil when a safe generic fallback is required. +type InboxItem struct { + Entry domain.NotificationInboxEntry + Content *InboxContent + ContentUnavailable bool +} + +// InboxListRequest is built from the authenticated recipient and optional +// organization context. The organization ID filters items but grants no +// authorization by itself. +type InboxListRequest struct { + RecipientUserID uuid.UUID + OrganizationID *uuid.UUID + After *outbound.NotificationInboxPosition + Limit int32 +} + +type InboxPage struct { + Items []InboxItem + HasMore bool +} + +// InboxService coordinates recipient-scoped storage and read-time content +// resolution. A caller for employer-scoped notices must authorize current +// membership before constructing the request; invitation recipients need not +// belong to the sender's organization. +type InboxService struct { + repository outbound.NotificationInboxRepository + resolver InboxContentResolver + clock func() time.Time +} + +func NewInboxService( + repository outbound.NotificationInboxRepository, + resolver InboxContentResolver, + clock func() time.Time, +) (*InboxService, error) { + if repository == nil || resolver == nil || clock == nil { + return nil, fmt.Errorf("notification.NewInboxService - repository, resolver, and clock are required: %w", ErrInboxUnavailable) + } + return &InboxService{repository: repository, resolver: resolver, clock: clock}, nil +} + +// StoreInvitationDelivered stores the recipient-specific reference to an +// invitation-delivered event. A transaction-bound repository lets a future +// event handler commit this row with the invitation state and consumer marker. +func (service *InboxService) StoreInvitationDelivered( + ctx context.Context, + input domain.NotificationInboxEntryInput, +) (bool, error) { + const location = "InboxService.StoreInvitationDelivered" + entry, err := domain.NewNotificationInboxEntry(input) + if err != nil { + return false, err + } + created, err := service.repository.Store(ctx, entry) + if err != nil { + return false, fmt.Errorf("%s - store event: %w", location, err) + } + return created, nil +} + +// List resolves each stored reference against its current source. A source +// that is missing or no longer visible is returned without source content. +func (service *InboxService) List(ctx context.Context, request InboxListRequest) (InboxPage, error) { + const location = "InboxService.List" + if err := validateInboxListRequest(request); err != nil { + return InboxPage{}, err + } + stored, err := service.repository.List(ctx, outbound.NotificationInboxListQuery{ + RecipientUserID: request.RecipientUserID, + OrganizationID: request.OrganizationID, + After: request.After, + Limit: request.Limit, + }) + if err != nil { + return InboxPage{}, fmt.Errorf("%s - list recipient events: %w", location, err) + } + page := InboxPage{Items: make([]InboxItem, 0, len(stored.Items)), HasMore: stored.HasMore} + for _, entry := range stored.Items { + if !inboxEntryMatchesRequest(entry, request) { + return InboxPage{}, fmt.Errorf("%s - repository returned an event outside the recipient scope: %w", location, ErrInboxUnavailable) + } + item := InboxItem{Entry: entry} + content, resolveErr := service.resolver.Resolve(ctx, entry) + if errors.Is(resolveErr, ErrInboxContentUnavailable) { + item.ContentUnavailable = true + } else if resolveErr != nil { + return InboxPage{}, fmt.Errorf("%s - resolve current event content: %w", location, resolveErr) + } else { + item.Content = &content + } + page.Items = append(page.Items, item) + } + return page, nil +} + +// MarkRead persists the first read timestamp for one recipient and exact +// organization context. The source is not read and no private content is +// returned by this command. +func (service *InboxService) MarkRead( + ctx context.Context, + recipientUserID uuid.UUID, + organizationID uuid.UUID, + eventID uuid.UUID, +) (domain.NotificationInboxEntry, error) { + const location = "InboxService.MarkRead" + if recipientUserID == uuid.Nil || organizationID == uuid.Nil || eventID == uuid.Nil { + return domain.NotificationInboxEntry{}, fmt.Errorf("%s - recipient, organization, and event IDs are required: %w", location, ErrInboxUnavailable) + } + at := service.clock() + if at.IsZero() { + return domain.NotificationInboxEntry{}, fmt.Errorf("%s - clock returned zero: %w", location, ErrInboxUnavailable) + } + entry, err := service.repository.MarkRead(ctx, recipientUserID, organizationID, eventID, at) + if err != nil { + return domain.NotificationInboxEntry{}, fmt.Errorf("%s - mark event read: %w", location, err) + } + return entry, nil +} + +func validateInboxListRequest(request InboxListRequest) error { + const location = "notification.validateInboxListRequest" + if request.RecipientUserID == uuid.Nil || request.Limit < 1 || request.Limit > outbound.MaxNotificationInboxPageSize { + return fmt.Errorf("%s - recipient and a bounded page size are required: %w", location, ErrInboxUnavailable) + } + if request.OrganizationID != nil && *request.OrganizationID == uuid.Nil { + return fmt.Errorf("%s - organization context cannot be zero: %w", location, ErrInboxUnavailable) + } + if request.After != nil && (request.After.EventID == uuid.Nil || request.After.OccurredAt.IsZero()) { + return fmt.Errorf("%s - page position is invalid: %w", location, ErrInboxUnavailable) + } + return nil +} + +func inboxEntryMatchesRequest(entry domain.NotificationInboxEntry, request InboxListRequest) bool { + if entry.IsZero() || entry.RecipientUserID() != request.RecipientUserID { + return false + } + return request.OrganizationID == nil || entry.OrganizationID() == *request.OrganizationID +} diff --git a/backend/internal/usecase/notification/inbox_test.go b/backend/internal/usecase/notification/inbox_test.go new file mode 100644 index 0000000..ce5f809 --- /dev/null +++ b/backend/internal/usecase/notification/inbox_test.go @@ -0,0 +1,245 @@ +package notification + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +func TestInboxServiceStoreInvitationDeliveredDeduplicatesRecipientEvent(t *testing.T) { + t.Parallel() + + repository := &memoryInboxRepository{} + service := newInboxTestService(t, repository, &memoryInboxResolver{}, time.Now) + input := inboxTestEntryInput() + created, err := service.StoreInvitationDelivered(context.Background(), input) + if err != nil || !created { + t.Fatalf("StoreInvitationDelivered(first) = %t, %v, want true, nil", created, err) + } + created, err = service.StoreInvitationDelivered(context.Background(), input) + if err != nil || created { + t.Fatalf("StoreInvitationDelivered(retry) = %t, %v, want false, nil", created, err) + } + if len(repository.entries) != 1 { + t.Fatalf("stored entries = %d, want one", len(repository.entries)) + } + + changed := input + changed.SourceID = uuid.New() + if _, err := service.StoreInvitationDelivered(context.Background(), changed); !errors.Is(err, outbound.ErrNotificationInboxEventConflict) { + t.Fatalf("StoreInvitationDelivered(changed replay) error = %v, want ErrNotificationInboxEventConflict", err) + } +} + +func TestInboxServiceListRechecksContentAndFallsBackSafely(t *testing.T) { + t.Parallel() + + first := mustInboxTestEntry(t, inboxTestEntryInput()) + secondInput := inboxTestEntryInput() + secondInput.RecipientUserID = first.RecipientUserID() + secondInput.OrganizationID = first.OrganizationID() + secondInput.EventID = uuid.New() + second := mustInboxTestEntry(t, secondInput) + wrongOrganizationInput := inboxTestEntryInput() + wrongOrganizationInput.RecipientUserID = first.RecipientUserID() + wrongOrganizationInput.EventID = uuid.New() + wrongOrganizationInput.OrganizationID = uuid.New() + wrongOrganization := mustInboxTestEntry(t, wrongOrganizationInput) + repository := &memoryInboxRepository{entries: []domain.NotificationInboxEntry{first, second, wrongOrganization}} + resolver := &memoryInboxResolver{unavailable: map[uuid.UUID]bool{second.EventID(): true}} + service := newInboxTestService(t, repository, resolver, time.Now) + orgID := first.OrganizationID() + page, err := service.List(context.Background(), InboxListRequest{ + RecipientUserID: first.RecipientUserID(), OrganizationID: &orgID, Limit: 10, + }) + if err != nil { + t.Fatalf("List() error = %v", err) + } + if len(page.Items) != 2 { + t.Fatalf("List() returned %d items, want 2", len(page.Items)) + } + if page.Items[0].Content == nil || page.Items[0].ContentUnavailable { + t.Fatalf("visible item = %+v, want current content", page.Items[0]) + } + if page.Items[1].Content != nil || !page.Items[1].ContentUnavailable { + t.Fatalf("hidden item = %+v, want safe fallback without source content", page.Items[1]) + } + if resolver.calls != 2 { + t.Fatalf("resolver calls = %d, want one current visibility check per returned item", resolver.calls) + } +} + +func TestInboxServiceListRejectsRepositoryRowsOutsideRecipientScope(t *testing.T) { + t.Parallel() + + entry := mustInboxTestEntry(t, inboxTestEntryInput()) + repository := &memoryInboxRepository{entries: []domain.NotificationInboxEntry{entry}, ignoreListScope: true} + service := newInboxTestService(t, repository, &memoryInboxResolver{}, time.Now) + _, err := service.List(context.Background(), InboxListRequest{ + RecipientUserID: uuid.New(), OrganizationID: uuidPointer(entry.OrganizationID()), Limit: 10, + }) + if !errors.Is(err, ErrInboxUnavailable) { + t.Fatalf("List(out-of-scope repository row) error = %v, want ErrInboxUnavailable", err) + } +} + +func TestInboxServiceMarkReadPersistsAndKeepsFirstTime(t *testing.T) { + t.Parallel() + + entry := mustInboxTestEntry(t, inboxTestEntryInput()) + firstRead := time.Date(2026, time.October, 8, 13, 0, 0, 1000, time.UTC) + secondRead := firstRead.Add(time.Hour) + clockCalls := 0 + clock := func() time.Time { + clockCalls++ + if clockCalls == 1 { + return firstRead + } + return secondRead + } + repository := &memoryInboxRepository{entries: []domain.NotificationInboxEntry{entry}} + service := newInboxTestService(t, repository, &memoryInboxResolver{}, clock) + for range 2 { + read, err := service.MarkRead(context.Background(), entry.RecipientUserID(), entry.OrganizationID(), entry.EventID()) + if err != nil { + t.Fatalf("MarkRead() error = %v", err) + } + got, isRead := read.ReadAt() + if !isRead || !got.Equal(firstRead.UTC().Truncate(time.Microsecond)) { + t.Fatalf("ReadAt() = %s, %t, want the first read time", got, isRead) + } + } +} + +func TestNewInboxContentRejectsExternalOrAmbiguousLinks(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + path string + }{ + {name: "external URL", path: "https://example.test/invitation"}, + {name: "protocol-relative URL", path: "//example.test/invitation"}, + {name: "query string", path: "/candidate/invitations?token=secret"}, + {name: "fragment", path: "/candidate/invitations#current"}, + {name: "backslash", path: `/candidate\\invitations`}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + if _, err := NewInboxContent("Приглашение", "Проверьте новое приглашение.", test.path); !errors.Is(err, ErrInboxUnavailable) { + t.Fatalf("NewInboxContent() error = %v, want ErrInboxUnavailable", err) + } + }) + } +} + +func newInboxTestService( + t *testing.T, + repository outbound.NotificationInboxRepository, + resolver InboxContentResolver, + clock func() time.Time, +) *InboxService { + t.Helper() + service, err := NewInboxService(repository, resolver, clock) + if err != nil { + t.Fatalf("NewInboxService() error = %v", err) + } + return service +} + +func inboxTestEntryInput() domain.NotificationInboxEntryInput { + return domain.NotificationInboxEntryInput{ + EventID: uuid.New(), RecipientUserID: uuid.New(), OrganizationID: uuid.New(), + EventType: domain.NotificationInboxInvitationDelivered, SchemaVersion: 1, + SourceType: domain.NotificationInboxSourceInvitation, SourceID: uuid.New(), + OccurredAt: time.Date(2026, time.October, 8, 12, 0, 0, 0, time.UTC), + } +} + +func mustInboxTestEntry(t *testing.T, input domain.NotificationInboxEntryInput) domain.NotificationInboxEntry { + t.Helper() + entry, err := domain.NewNotificationInboxEntry(input) + if err != nil { + t.Fatalf("NewNotificationInboxEntry() error = %v", err) + } + return entry +} + +func uuidPointer(value uuid.UUID) *uuid.UUID { return &value } + +type memoryInboxRepository struct { + entries []domain.NotificationInboxEntry + ignoreListScope bool +} + +func (repository *memoryInboxRepository) Store(_ context.Context, entry domain.NotificationInboxEntry) (bool, error) { + for _, existing := range repository.entries { + if existing.RecipientUserID() != entry.RecipientUserID() || existing.EventID() != entry.EventID() { + continue + } + if !sameInboxEvent(existing, entry) { + return false, outbound.ErrNotificationInboxEventConflict + } + return false, nil + } + repository.entries = append(repository.entries, entry) + return true, nil +} + +func (repository *memoryInboxRepository) List(_ context.Context, query outbound.NotificationInboxListQuery) (outbound.NotificationInboxPage, error) { + page := outbound.NotificationInboxPage{} + for _, entry := range repository.entries { + if !repository.ignoreListScope && (entry.RecipientUserID() != query.RecipientUserID || (query.OrganizationID != nil && entry.OrganizationID() != *query.OrganizationID)) { + continue + } + page.Items = append(page.Items, entry) + } + return page, nil +} + +func (repository *memoryInboxRepository) MarkRead( + _ context.Context, + recipientUserID uuid.UUID, + organizationID uuid.UUID, + eventID uuid.UUID, + at time.Time, +) (domain.NotificationInboxEntry, error) { + for index, entry := range repository.entries { + if entry.RecipientUserID() != recipientUserID || entry.OrganizationID() != organizationID || entry.EventID() != eventID { + continue + } + read, err := entry.MarkRead(at) + if err != nil { + return domain.NotificationInboxEntry{}, err + } + repository.entries[index] = read + return read, nil + } + return domain.NotificationInboxEntry{}, outbound.ErrNotificationInboxEntryNotFound +} + +func sameInboxEvent(left, right domain.NotificationInboxEntry) bool { + return left.OrganizationID() == right.OrganizationID() && left.EventType() == right.EventType() && + left.SchemaVersion() == right.SchemaVersion() && left.SourceType() == right.SourceType() && + left.SourceID() == right.SourceID() && left.OccurredAt().Equal(right.OccurredAt()) +} + +type memoryInboxResolver struct { + unavailable map[uuid.UUID]bool + calls int +} + +func (resolver *memoryInboxResolver) Resolve(_ context.Context, entry domain.NotificationInboxEntry) (InboxContent, error) { + resolver.calls++ + if resolver.unavailable[entry.EventID()] { + return InboxContent{}, ErrInboxContentUnavailable + } + return NewInboxContent("Приглашение", "Проверьте новое приглашение.", "/candidate/invitations") +} diff --git a/deploy/docker/docker-compose.yml b/deploy/docker/docker-compose.yml index 9630da1..bb4d4de 100644 --- a/deploy/docker/docker-compose.yml +++ b/deploy/docker/docker-compose.yml @@ -238,6 +238,7 @@ services: IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT: ${IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT:-10} IDENTITY_SESSION_IDLE_TIMEOUT: ${IDENTITY_SESSION_IDLE_TIMEOUT:-24h} IDENTITY_SESSION_ABSOLUTE_LIFETIME: ${IDENTITY_SESSION_ABSOLUTE_LIFETIME:-168h} + ASSESSMENT_DEMO_CATEGORIES_ENABLED: ${ASSESSMENT_DEMO_CATEGORIES_ENABLED:-false} # Proxies whose X-Forwarded-For is believed: only the frontend container, # which has a fixed address on the pinned app network below. Other # containers of that network (Prometheus, exporters, Alloy) are not diff --git a/scripts/test_assessment_contract.py b/scripts/test_assessment_contract.py index 04fb536..04b5909 100644 --- a/scripts/test_assessment_contract.py +++ b/scripts/test_assessment_contract.py @@ -444,6 +444,34 @@ class AssessmentContractTest(unittest.TestCase): f"organization operation {path} must not reach assessment signal schemas", ) + def test_result_history_excludes_training_and_keeps_legacy_grade_unknown(self) -> None: + operation = self.paths["/api/v1/me/assessment-results"]["get"] + self.assertEqual(operation["operationId"], "ListMyAssessmentResults") + self.assertEqual(operation["security"], [{"sessionCookie": []}]) + self.assertEqual({"200", "400", "401", "403"} - set(operation["responses"]), set()) + limit = next(parameter for parameter in operation["parameters"] if parameter.get("name") == "limit") + self.assertEqual(limit["schema"]["maximum"], 50) + self.assertTrue(any(parameter.get("$ref", "").endswith("/PageCursor") for parameter in operation["parameters"])) + + page = resolve_schema(self.schemas["AssessmentResultHistoryPage"], self.schemas) + self.assertEqual(set(page["required"]), {"items", "page"}) + self.assertEqual(page["properties"]["items"]["maxItems"], 50) + real_results = resolve_schema(page["properties"]["items"]["items"], self.schemas) + self.assertEqual(set(real_results["discriminator"]["mapping"]), {"root", "corrective"}) + self.assertEqual(len(real_results["oneOf"]), 2) + + common = resolve_schema(self.schemas["AssessmentRealResultCommon"], self.schemas) + self.assertIn("category_decision", common["properties"]) + self.assertNotIn("category_decision", common["required"]) + express = resolve_schema(self.schemas["AssessmentExpressResult"], self.schemas) + self.assertNotIn("category_decision", express["properties"]) + decision = resolve_schema(self.schemas["AssessmentCategoryDecisionView"], self.schemas) + self.assertEqual( + set(decision["properties"]), + {"status", "previous_confirmed_grade", "current_confirmed_grade", "method", "source", "calibration_status"}, + ) + self.assertFalse(decision.get("additionalProperties", True)) + if __name__ == "__main__": unittest.main()