All files / web/src/lib/curriculum session-mode.ts

52.04% Statements 178/342
100% Branches 6/6
80% Functions 4/5
52.04% Lines 178/342

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 3432x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x                                                                                                                                                                                                                                                                                                                                         2x 2x 2x 2x 2x 2x 2x 2x 2x 7x 7x 2x 2x 2x 2x 2x 7x 7x 2x 2x 2x 2x 2x 8x 8x 2x 2x 2x 2x 2x 6x 3x 3x 3x 3x  
/**
 * Session Mode - Unified session state computation
 *
 * This module provides a single source of truth for determining what mode
 * a student's practice session should be in:
 *
 * - remediation: Student has weak skills that need strengthening
 * - progression: Student is ready to learn a new skill
 * - maintenance: All skills are strong, mixed practice
 *
 * The session mode drives:
 * - Dashboard banners
 * - StartPracticeModal CTA
 * - Session planner problem generation
 */
 
import { computeBktFromHistory, DEFAULT_BKT_OPTIONS } from '@/lib/curriculum/bkt'
import { BKT_THRESHOLDS } from '@/lib/curriculum/config/bkt-integration'
import { WEAK_SKILL_THRESHOLDS } from '@/lib/curriculum/config'
import { ALL_PHASES, type CurriculumPhase } from '@/lib/curriculum/definitions'
import {
  getPracticingSkills,
  getSkillTutorialProgress,
  isSkillTutorialSatisfied,
} from '@/lib/curriculum/progress-manager'
import { getRecentSessionResults } from '@/lib/curriculum/session-planner'
import {
  assessAllSkillsReadiness,
  readinessMapToRecord,
  type SkillReadinessResult,
} from '@/lib/curriculum/skill-readiness'
import { getActiveDeferral } from '@/lib/curriculum/progression-deferrals'
import { skillHasMathSentence } from '@/constants/skillCategories'
import { SKILL_TUTORIAL_CONFIGS, getSkillDisplayName } from './skill-tutorial-config'
 
// ============================================================================
// Types
// ============================================================================
 
/**
 * Information about a skill for display purposes
 */
export interface SkillInfo {
  skillId: string
  displayName: string
  /** P(known) from BKT, 0-1 */
  pKnown: number
  /** Whether displayName is a concise math rule (e.g., "+4 = +5 - 1") suitable for the practice banner */
  hasMathSentence: boolean
}
 
/**
 * Information about a blocked promotion (when remediation is needed)
 */
export interface BlockedPromotion {
  /** The skill the student would learn if not blocked */
  nextSkill: SkillInfo
  /** Human-readable reason for the block */
  reason: string
  /** The curriculum phase of the blocked skill */
  phase: CurriculumPhase
  /** Whether the tutorial is already satisfied */
  tutorialReady: boolean
}
 
/**
 * Remediation mode - student has weak skills that need work
 */
export interface RemediationMode {
  type: 'remediation'
  /** Skills that need strengthening (sorted by pKnown ascending) */
  weakSkills: SkillInfo[]
  /** Description for the session header */
  focusDescription: string
  /** What promotion is being blocked, if any */
  blockedPromotion?: BlockedPromotion
}
 
/**
 * Progression mode - student is ready to learn a new skill
 */
export interface ProgressionMode {
  type: 'progression'
  /** The skill to learn next */
  nextSkill: SkillInfo
  /** The curriculum phase */
  phase: CurriculumPhase
  /** Whether a tutorial is required before practicing */
  tutorialRequired: boolean
  /** Number of times the student has skipped this tutorial */
  skipCount: number
  /** Description for the session header */
  focusDescription: string
  /**
   * Whether the student can skip the tutorial and still practice.
   * False when this is their first skill (no other skills to practice).
   * When false, the tutorial is mandatory - skipping would result in no skills.
   */
  canSkipTutorial: boolean
}
 
/**
 * Maintenance mode - all skills are strong, mixed practice
 */
export interface MaintenanceMode {
  type: 'maintenance'
  /** Description for the session header */
  focusDescription: string
  /** Number of skills being maintained */
  skillCount: number
  /** Present when progression is available but not all dimensions are met or deferred */
  deferredProgression?: {
    nextSkill: SkillInfo
    readiness: Record<string, SkillReadinessResult>
    phase: CurriculumPhase
  }
}
 
/**
 * The unified session mode
 */
export type SessionMode = RemediationMode | ProgressionMode | MaintenanceMode
 
// ============================================================================
// Session Mode Computation
// ============================================================================
 
/**
 * Compute the session mode for a student.
 *
 * This is the single source of truth for what type of session should be run.
 * The result drives dashboard display, modal CTA, and problem generation.
 *
 * Logic:
 * 1. Compute BKT to identify weak and strong skills
 * 2. If weak skills exist → remediation mode
 * 3. Else, find next skill in curriculum:
 *    - If found → progression mode
 *    - If not found → maintenance mode
 *
 * @param playerId - The player to compute mode for
 * @returns The session mode
 */
export async function getSessionMode(playerId: string): Promise<SessionMode> {
  // 1. Get BKT results for all practiced skills
  const history = await getRecentSessionResults(playerId, 100)
  const bktResults = computeBktFromHistory(history, {
    ...DEFAULT_BKT_OPTIONS,
    confidenceThreshold: BKT_THRESHOLDS.confidence,
  })

  // 2. Identify weak skills (confident that P(known) is low)
  const { confidenceThreshold, pKnownThreshold } = WEAK_SKILL_THRESHOLDS
  const weakSkills: SkillInfo[] = bktResults.skills
    .filter((s) => s.confidence >= confidenceThreshold && s.pKnown < pKnownThreshold)
    .sort((a, b) => a.pKnown - b.pKnown) // Weakest first
    .map((s) => ({
      skillId: s.skillId,
      displayName: getSkillDisplayName(s.skillId),
      pKnown: s.pKnown,
      hasMathSentence: skillHasMathSentence(s.skillId),
    }))

  // 3. Find strong skills for maintenance mode counting
  const strongSkillIds = new Set(
    bktResults.skills.filter((s) => s.masteryClassification === 'strong').map((s) => s.skillId)
  )

  // 4. Get currently practicing skills
  const practicing = await getPracticingSkills(playerId)
  const practicingIds = new Set(practicing.map((s) => s.skillId))

  // 5. Find the next skill in curriculum (if any)
  let nextSkillInfo: {
    skillId: string
    phase: CurriculumPhase
    tutorialReady: boolean
    skipCount: number
  } | null = null

  for (const phase of ALL_PHASES) {
    const skillId = phase.primarySkillId

    // Skip if no tutorial config (not a learnable skill)
    if (!SKILL_TUTORIAL_CONFIGS[skillId]) {
      continue
    }

    // Strong? Skip - they know it
    if (strongSkillIds.has(skillId)) {
      continue
    }

    // Currently practicing? They're working on it
    if (practicingIds.has(skillId)) {
      break // Stop looking, they're actively working on something
    }

    // Found first non-strong, unpracticed skill!
    const tutorialProgress = await getSkillTutorialProgress(playerId, skillId)
    const tutorialReady = await isSkillTutorialSatisfied(playerId, skillId)

    nextSkillInfo = {
      skillId,
      phase,
      tutorialReady,
      skipCount: tutorialProgress?.skipCount ?? 0,
    }
    break
  }

  // 6. Determine mode based on weak skills and next skill
  if (weakSkills.length > 0) {
    // REMEDIATION MODE
    const weakSkillNames = weakSkills.slice(0, 3).map((s) => s.displayName)
    const moreCount = weakSkills.length - 3
    const skillList =
      moreCount > 0
        ? `${weakSkillNames.join(', ')} +${moreCount} more`
        : weakSkillNames.join(weakSkills.length === 2 ? ' and ' : ', ')

    const focusDescription = `Strengthening: ${skillList}`

    // Check if there's a promotion being blocked
    let blockedPromotion: BlockedPromotion | undefined
    if (nextSkillInfo) {
      const nextSkillDisplay = getSkillDisplayName(nextSkillInfo.skillId)
      blockedPromotion = {
        nextSkill: {
          skillId: nextSkillInfo.skillId,
          displayName: nextSkillDisplay,
          pKnown: 0, // Not yet practiced
          hasMathSentence: skillHasMathSentence(nextSkillInfo.skillId),
        },
        reason: `Strengthen ${weakSkillNames.slice(0, 2).join(' and ')} first`,
        phase: nextSkillInfo.phase,
        tutorialReady: nextSkillInfo.tutorialReady,
      }
    }

    return {
      type: 'remediation',
      weakSkills,
      focusDescription,
      blockedPromotion,
    }
  }

  if (nextSkillInfo) {
    const nextSkillDisplay = getSkillDisplayName(nextSkillInfo.skillId)
    const nextSkill: SkillInfo = {
      skillId: nextSkillInfo.skillId,
      displayName: nextSkillDisplay,
      pKnown: 0, // Not yet practiced
      hasMathSentence: skillHasMathSentence(nextSkillInfo.skillId),
    }

    // Gate: only offer progression if ALL practicing skills are solid (all 4 dimensions met)
    // First skill ever (practicingIds.size === 0): skip readiness gate — tutorial is mandatory
    const readiness = assessAllSkillsReadiness(history, bktResults.skills, practicingIds)
    const allSolid =
      practicingIds.size === 0 ||
      [...practicingIds].every((id) => readiness.get(id)?.isSolid ?? false)

    if (allSolid) {
      // Check for active deferral
      const deferral = await getActiveDeferral(playerId, nextSkillInfo.skillId)

      if (!deferral) {
        // PROGRESSION MODE
        // Student can skip tutorial only if they have other skills to practice.
        // If this is their first skill (no practicing skills yet), skipping would
        // result in NoSkillsEnabledClientError - so we must prevent skip.
        const canSkipTutorial = practicingIds.size > 0

        return {
          type: 'progression',
          nextSkill,
          phase: nextSkillInfo.phase,
          tutorialRequired: !nextSkillInfo.tutorialReady,
          skipCount: nextSkillInfo.skipCount,
          focusDescription: `Learning: ${nextSkillDisplay}`,
          canSkipTutorial,
        }
      }
    }

    // MAINTENANCE MODE with deferred progression info
    return {
      type: 'maintenance',
      focusDescription: 'Mixed practice',
      skillCount: practicingIds.size,
      deferredProgression: {
        nextSkill,
        readiness: readinessMapToRecord(readiness),
        phase: nextSkillInfo.phase,
      },
    }
  }

  // MAINTENANCE MODE
  return {
    type: 'maintenance',
    focusDescription: 'Mixed practice',
    skillCount: practicingIds.size,
  }
}
 
// ============================================================================
// Helper Functions
// ============================================================================
 
/**
 * Check if session mode indicates remediation is needed
 */
export function isRemediationMode(mode: SessionMode): mode is RemediationMode {
  return mode.type === 'remediation'
}
 
/**
 * Check if session mode indicates progression is available
 */
export function isProgressionMode(mode: SessionMode): mode is ProgressionMode {
  return mode.type === 'progression'
}
 
/**
 * Check if session mode indicates maintenance
 */
export function isMaintenanceMode(mode: SessionMode): mode is MaintenanceMode {
  return mode.type === 'maintenance'
}
 
/**
 * Get the weak skill IDs from a session mode (for session planner)
 */
export function getWeakSkillIds(mode: SessionMode): string[] {
  if (mode.type === 'remediation') {
    return mode.weakSkills.map((s) => s.skillId)
  }
  return []
}