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 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 | 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 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 112x 112x 112x 112x 112x 112x 112x 112x 112x 112x 112x 112x 112x 112x 112x 1004x 1004x 1004x 1004x 1004x 1004x 1004x 112x 112x 112x 112x 112x 112x 112x 112x 112x 112x 112x 112x 112x 112x 112x 112x 112x 112x 112x 112x 112x 112x 112x 112x 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 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 3x 3x 3x 3x 3x 3x 3x 3x 3x 12x 12x 12x 12x 12x 12x 12x 12x 12x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 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 | /**
* Progress manager for curriculum tracking
* Handles CRUD operations for student curriculum progress and skill mastery
*/
import { and, desc, eq, inArray, lt, ne, or } from 'drizzle-orm'
import { db, schema } from '@/db'
import type { NewPlayerCurriculum, PlayerCurriculum } from '@/db/schema/player-curriculum'
import type { NewPlayerSkillMastery, PlayerSkillMastery } from '@/db/schema/player-skill-mastery'
import { type PracticeLevel, isActive } from '@/db/schema/player-skill-mastery'
import type { PracticeSession } from '@/db/schema/practice-sessions'
import type { SlotResult } from '@/db/schema/session-plans'
import {
isTutorialSatisfied,
type NewSkillTutorialProgress,
type SkillTutorialProgress,
} from '@/db/schema/skill-tutorial-progress'
import { getRecentSessionResults } from '@/lib/curriculum/session-planner'
import { DEFAULT_SECONDS_PER_PROBLEM } from '@/lib/curriculum/config'
import {
classifyAttemptTiming,
countUnresolvedFlagged,
getEffectiveResponseTimeMs,
isFlagResolved,
type AttemptTimingReason,
} from '@/lib/curriculum/timing/effective-time'
import {
assessPace,
computeChildTimingStats,
type PaceAssessment,
type TimedAttempt,
} from '@/lib/curriculum/timing/pace-estimation'
import type {
DeletedSessionSummary,
FlaggedAttempt,
SerializedSlotResult,
TimingReviewData,
} from '@/lib/curriculum/timing/review-types'
// ============================================================================
// CURRICULUM POSITION OPERATIONS
// ============================================================================
/**
* Get a player's curriculum position
* Returns null if the player hasn't started the curriculum
*/
export async function getPlayerCurriculum(playerId: string): Promise<PlayerCurriculum | null> {
const result = await db.query.playerCurriculum.findFirst({
where: eq(schema.playerCurriculum.playerId, playerId),
})
return result ?? null
}
/**
* Create or update a player's curriculum position
*/
export async function upsertPlayerCurriculum(
playerId: string,
data: Partial<Omit<NewPlayerCurriculum, 'playerId'>>
): Promise<PlayerCurriculum> {
const existing = await getPlayerCurriculum(playerId)
if (existing) {
// Update existing record
await db
.update(schema.playerCurriculum)
.set({
...data,
updatedAt: new Date(),
})
.where(eq(schema.playerCurriculum.playerId, playerId))
return (await getPlayerCurriculum(playerId))!
}
// Create new record with defaults
const newRecord: NewPlayerCurriculum = {
playerId,
currentLevel: data.currentLevel ?? 1,
currentPhaseId: data.currentPhaseId ?? 'L1.add.+1.direct',
worksheetPreset: data.worksheetPreset ?? null,
visualizationMode: data.visualizationMode ?? false,
}
await db.insert(schema.playerCurriculum).values(newRecord)
return (await getPlayerCurriculum(playerId))!
}
/**
* Advance a player to the next curriculum phase
*/
export async function advanceToNextPhase(
playerId: string,
nextPhaseId: string,
nextLevel?: number
): Promise<PlayerCurriculum> {
return upsertPlayerCurriculum(playerId, {
currentPhaseId: nextPhaseId,
...(nextLevel !== undefined ? { currentLevel: nextLevel } : {}),
})
}
// ============================================================================
// SKILL MASTERY OPERATIONS
// ============================================================================
/**
* Get a player's mastery for a specific skill
*/
export async function getSkillMastery(
playerId: string,
skillId: string
): Promise<PlayerSkillMastery | null> {
const result = await db.query.playerSkillMastery.findFirst({
where: and(
eq(schema.playerSkillMastery.playerId, playerId),
eq(schema.playerSkillMastery.skillId, skillId)
),
})
return result ?? null
}
/**
* Get all skill mastery records for a player
*/
export async function getAllSkillMastery(playerId: string): Promise<PlayerSkillMastery[]> {
return db.query.playerSkillMastery.findMany({
where: eq(schema.playerSkillMastery.playerId, playerId),
orderBy: desc(schema.playerSkillMastery.lastPracticedAt),
})
}
// ============================================================================
// Linear-readiness vetoes (L3)
// ============================================================================
/**
* Get the set of skill categories the teacher has vetoed for linear (number
* sentence) practice. A category's PRESENCE means "not yet"; its ABSENCE means
* linear-readiness is auto-conferred once derived. Categories are `SkillCategoryKey`
* strings (validated at the API boundary).
*/
export async function getLinearReadinessVetoes(playerId: string): Promise<Set<string>> {
const rows = await db
.select({ category: schema.linearReadinessVeto.category })
.from(schema.linearReadinessVeto)
.where(eq(schema.linearReadinessVeto.playerId, playerId))
return new Set(rows.map((r) => r.category))
}
/**
* Veto a skill category for linear practice. Idempotent — a repeat veto is a no-op
* thanks to the (player, category) unique index.
*/
export async function setLinearReadinessVeto(
playerId: string,
category: string,
reason?: string
): Promise<void> {
await db
.insert(schema.linearReadinessVeto)
.values({ playerId, category, reason: reason ?? null })
.onConflictDoNothing({
target: [schema.linearReadinessVeto.playerId, schema.linearReadinessVeto.category],
})
}
/** Lift a linear-practice veto for a skill category. Idempotent. */
export async function clearLinearReadinessVeto(playerId: string, category: string): Promise<void> {
await db
.delete(schema.linearReadinessVeto)
.where(
and(
eq(schema.linearReadinessVeto.playerId, playerId),
eq(schema.linearReadinessVeto.category, category)
)
)
}
/**
* Get all skills in a player's active practice rotation (practiceLevel != 'none')
*/
export async function getPracticingSkills(playerId: string): Promise<PlayerSkillMastery[]> {
return db.query.playerSkillMastery.findMany({
where: and(
eq(schema.playerSkillMastery.playerId, playerId),
ne(schema.playerSkillMastery.practiceLevel, 'none')
),
orderBy: desc(schema.playerSkillMastery.lastPracticedAt),
})
}
/**
* Set practice levels for a player's skills.
*
* @param playerId - The player to update
* @param skillLevels - Map of skillId → PracticeLevel
* @returns All skill mastery records for the player after update
*/
export async function setSkillPracticeLevels(
playerId: string,
skillLevels: Record<string, PracticeLevel>
): Promise<PlayerSkillMastery[]> {
const now = new Date()
// Get all existing skills for this player
const existingSkills = await getAllSkillMastery(playerId)
const existingSkillIds = new Set(existingSkills.map((s) => s.skillId))
// Update existing skills
for (const skill of existingSkills) {
const newLevel = skillLevels[skill.skillId] ?? 'none'
const isNowPracticing = isActive(newLevel)
// Only update if something changed
if (skill.practiceLevel !== newLevel || skill.isPracticing !== isNowPracticing) {
await db
.update(schema.playerSkillMastery)
.set({
practiceLevel: newLevel,
isPracticing: isNowPracticing,
updatedAt: now,
})
.where(eq(schema.playerSkillMastery.id, skill.id))
}
}
// Create new skills that don't exist yet
for (const [skillId, level] of Object.entries(skillLevels)) {
if (!existingSkillIds.has(skillId) && isActive(level)) {
const newRecord: NewPlayerSkillMastery = {
playerId,
skillId,
isPracticing: true,
practiceLevel: level,
lastPracticedAt: now,
}
await db.insert(schema.playerSkillMastery).values(newRecord)
}
}
return getAllSkillMastery(playerId)
}
/**
* Set which skills are in a player's active practice rotation.
* Backwards-compatible: treats all provided skills as 'visual' level.
*
* @deprecated Use setSkillPracticeLevels instead.
*/
export async function setPracticingSkills(
playerId: string,
practicingSkillIds: string[]
): Promise<PlayerSkillMastery[]> {
// Get all existing skills to know which ones to set to 'none'
const existingSkills = await getAllSkillMastery(playerId)
const levels: Record<string, PracticeLevel> = {}
// Set existing skills not in the list to 'none'
for (const skill of existingSkills) {
levels[skill.skillId] = 'none'
}
// Set all provided skills to 'visual' (preserves legacy behavior)
for (const skillId of practicingSkillIds) {
levels[skillId] = 'visual'
}
return setSkillPracticeLevels(playerId, levels)
}
/**
* @deprecated Use setSkillPracticeLevels instead. Kept for backwards compatibility.
*/
export async function setMasteredSkills(
playerId: string,
masteredSkillIds: string[]
): Promise<PlayerSkillMastery[]> {
return setPracticingSkills(playerId, masteredSkillIds)
}
/**
* Refresh skill recency by inserting a sentinel record
*
* Use this when a teacher wants to mark a skill as "recently practiced"
* (e.g., student did offline workbooks). This inserts a "recency-refresh"
* sentinel record that BKT sees for lastPracticedAt but ignores for pKnown.
*
* The sentinel approach means:
* - Single source of truth: all lastPracticedAt comes from problem history
* - No abstraction gap: BKT naturally handles recency from the same data source
* - Clear semantics: sentinel records are clearly marked with source='recency-refresh'
*
* @param playerId - The player's ID
* @param skillId - The skill to refresh
* @returns The created session plan containing the sentinel, or null if skill not found
*/
export async function refreshSkillRecency(
playerId: string,
skillId: string
): Promise<{ sessionId: string; timestamp: Date } | null> {
const existing = await getSkillMastery(playerId, skillId)
if (!existing) {
return null
}
const now = new Date()
// Create a minimal session plan with status='recency-refresh'
// This contains a single sentinel SlotResult
const sentinelResult: schema.SlotResult = {
slotId: crypto.randomUUID(),
partNumber: 1,
slotIndex: 0,
problem: {
terms: [0],
answer: 0,
skillsRequired: [skillId],
},
studentAnswer: 0,
isCorrect: true, // Doesn't matter - BKT ignores for recency-refresh
responseTimeMs: 0,
skillsExercised: [skillId],
usedOnScreenAbacus: false,
timestamp: now,
hadHelp: false,
incorrectAttempts: 0,
source: 'recency-refresh', // This marks it as a sentinel record
}
const sessionPlan: schema.NewSessionPlan = {
playerId,
targetDurationMinutes: 0,
estimatedProblemCount: 0,
avgTimePerProblemSeconds: 0,
parts: [], // No actual parts - just the sentinel result
summary: {
focusDescription: 'Recency refresh',
totalProblemCount: 0,
estimatedMinutes: 0,
parts: [],
},
status: 'recency-refresh',
results: [sentinelResult],
createdAt: now,
completedAt: now,
}
const [inserted] = await db.insert(schema.sessionPlans).values(sessionPlan).returning()
return {
sessionId: inserted.id,
timestamp: now,
}
}
/**
* Record a skill attempt (correct or incorrect)
* Updates the lastPracticedAt timestamp on the skill mastery record.
*
* NOTE: Attempt/correct statistics are now computed on-the-fly from session results.
* This function only updates metadata fields (lastPracticedAt) and ensures the
* skill record exists.
*/
export async function recordSkillAttempt(
playerId: string,
skillId: string,
_isCorrect: boolean
): Promise<PlayerSkillMastery> {
const existing = await getSkillMastery(playerId, skillId)
const now = new Date()
if (existing) {
// Update lastPracticedAt timestamp
await db
.update(schema.playerSkillMastery)
.set({
lastPracticedAt: now,
updatedAt: now,
})
.where(eq(schema.playerSkillMastery.id, existing.id))
return (await getSkillMastery(playerId, skillId))!
}
// Create new record - if we're recording an attempt, this skill is being practiced
const newRecord: NewPlayerSkillMastery = {
playerId,
skillId,
isPracticing: true,
practiceLevel: 'abacus',
lastPracticedAt: now,
}
await db.insert(schema.playerSkillMastery).values(newRecord)
return (await getSkillMastery(playerId, skillId))!
}
/**
* Record a skill attempt with help tracking
*
* Updates the lastPracticedAt timestamp and tracks whether help was used.
* BKT handles mastery estimation via evidence weighting (helped answers get 0.5x weight).
*
* NOTE: BKT's conjunctive blame attribution identifies weak skills from multi-skill problems.
*/
export async function recordSkillAttemptWithHelp(
playerId: string,
skillId: string,
_isCorrect: boolean,
hadHelp: boolean,
_responseTimeMs?: number
): Promise<PlayerSkillMastery> {
const existing = await getSkillMastery(playerId, skillId)
const now = new Date()
if (existing) {
await db
.update(schema.playerSkillMastery)
.set({
lastPracticedAt: now,
updatedAt: now,
lastHadHelp: hadHelp,
})
.where(eq(schema.playerSkillMastery.id, existing.id))
return (await getSkillMastery(playerId, skillId))!
}
// Create new record with help tracking - skill is being practiced
const newRecord: NewPlayerSkillMastery = {
playerId,
skillId,
isPracticing: true,
practiceLevel: 'abacus',
lastPracticedAt: now,
lastHadHelp: hadHelp,
}
await db.insert(schema.playerSkillMastery).values(newRecord)
return (await getSkillMastery(playerId, skillId))!
}
/**
* Record multiple skill attempts with help tracking (for batch updates after a problem)
* Response time is shared across all skills since they come from the same problem
*/
export async function recordSkillAttemptsWithHelp(
playerId: string,
skillResults: Array<{ skillId: string; isCorrect: boolean }>,
hadHelp: boolean,
responseTimeMs?: number
): Promise<PlayerSkillMastery[]> {
const results: PlayerSkillMastery[] = []
for (const { skillId, isCorrect } of skillResults) {
const result = await recordSkillAttemptWithHelp(
playerId,
skillId,
isCorrect,
hadHelp,
responseTimeMs
)
results.push(result)
}
return results
}
/**
* Record multiple skill attempts at once (for batch updates after a problem)
*/
export async function recordSkillAttempts(
playerId: string,
skillResults: Array<{ skillId: string; isCorrect: boolean }>
): Promise<PlayerSkillMastery[]> {
const results: PlayerSkillMastery[] = []
for (const { skillId, isCorrect } of skillResults) {
const result = await recordSkillAttempt(playerId, skillId, isCorrect)
results.push(result)
}
return results
}
/**
* Calculate what percentage of given skills are being practiced
*/
export async function calculatePracticingPercent(
playerId: string,
skillIds: string[]
): Promise<number> {
if (skillIds.length === 0) return 0
const masteryRecords = await getAllSkillMastery(playerId)
const relevantRecords = masteryRecords.filter((r) => skillIds.includes(r.skillId))
const practicingCount = relevantRecords.filter((r) => isActive(r.practiceLevel)).length
return Math.round((practicingCount / skillIds.length) * 100)
}
/**
* @deprecated Use calculatePracticingPercent instead.
*/
export async function calculateMasteryPercent(
playerId: string,
skillIds: string[]
): Promise<number> {
return calculatePracticingPercent(playerId, skillIds)
}
// ============================================================================
// PRACTICE SESSION OPERATIONS
// ============================================================================
/** Narrow session_plans projection every session transform reads (#141-safe). */
interface RawSessionRow {
id: string
playerId: string
results: SlotResult[]
startedAt: Date | null
createdAt: Date
completedAt: Date | null
}
/**
* Transform a raw session_plans row into the dashboard `PracticeSession` shape.
*
* Single source of truth shared by `getRecentSessions` and
* `getPaginatedSessions` (previously duplicated). `totalTimeMs`/`averageTimeMs`
* stay RAW (distortion preserved and shown alongside); the clean substats
* (`quarantinedTimingCount`/`cleanTotalTimeMs`/`timedProblemCount`) are derived
* via the shared timing helpers with Tier-1 samples excluded.
*/
function toPracticeSession(session: RawSessionRow): PracticeSession {
const results = session.results ?? []
const problemsAttempted = results.length
const problemsCorrect = results.filter((r) => r.isCorrect).length
// RAW totals — semantics deliberately unchanged.
const totalTimeMs = results.reduce((sum, r) => sum + (r.responseTimeMs || 0), 0)
const averageTimeMs = problemsAttempted > 0 ? Math.round(totalTimeMs / problemsAttempted) : null
const skillsUsed = [...new Set(results.flatMap((r) => r.skillsExercised || []))]
// De-poisoned substats: exclude Tier-1, sum effective non-Tier-1 samples.
let quarantinedTimingCount = 0
let cleanTotalTimeMs = 0
let timedProblemCount = 0
for (const result of results) {
if (classifyAttemptTiming(result).tier === 'tier1') {
quarantinedTimingCount++
continue
}
const effective = getEffectiveResponseTimeMs(result)
if (effective != null) {
cleanTotalTimeMs += effective
timedProblemCount++
}
}
// Resolution-aware "needs review" count for the session-list badge: flagged
// AND not yet omitted/adjusted/confirmed. Context-free (no child stats), so it
// surfaces Tier-1 flags — the same read-time signal `quarantinedTimingCount`
// uses — but disappears as each flag is resolved.
const unresolvedTimingCount = countUnresolvedFlagged(results)
return {
id: session.id,
playerId: session.playerId,
phaseId: 'session', // session_plans don't have phaseId
problemsAttempted,
problemsCorrect,
averageTimeMs,
totalTimeMs,
skillsUsed,
visualizationMode: false, // Not tracked in session_plans
startedAt: session.startedAt || session.createdAt,
completedAt: session.completedAt,
quarantinedTimingCount,
unresolvedTimingCount,
cleanTotalTimeMs,
timedProblemCount,
}
}
/** Sessions the pace window pools attempts over (matches getRecentSessions). */
const PACE_WINDOW_SESSIONS = 10
/** One row of the pace window: the projection every pace/review reader shares. */
interface PaceWindowSession {
id: string
results: SlotResult[]
completedAt: Date | null
}
/**
* Fetch the pace window — the N most-recent finished sessions the pace estimate
* and the timing-review list are both computed over. Extracted so both readers
* pool exactly the same sessions (never forked). Narrow projection avoids the
* heavy `parts` column (issue #141).
*/
async function fetchPaceWindowSessions(playerId: string): Promise<PaceWindowSession[]> {
const sessions = await db
.select({
id: schema.sessionPlans.id,
results: schema.sessionPlans.results,
completedAt: schema.sessionPlans.completedAt,
})
.from(schema.sessionPlans)
.where(
and(
eq(schema.sessionPlans.playerId, playerId),
inArray(schema.sessionPlans.status, ['completed', 'abandoned'])
)
)
.orderBy(desc(schema.sessionPlans.completedAt))
.limit(PACE_WINDOW_SESSIONS)
return sessions.map((session) => ({
id: session.id,
results: (session.results as SlotResult[] | null) ?? [],
completedAt: session.completedAt,
}))
}
/** Flatten pace-window sessions into the `TimedAttempt[]` the estimator reads. */
function toTimedAttempts(sessions: readonly PaceWindowSession[]): TimedAttempt[] {
const attempts: TimedAttempt[] = []
for (const session of sessions) {
const completedAt = session.completedAt ? session.completedAt.toISOString() : null
for (const result of session.results) {
attempts.push({
sessionId: session.id,
completedAt,
termCount: result.problem?.terms?.length ?? 0,
sample: result,
})
}
}
return attempts
}
/**
* Assess pace over an already-fetched pace window. Extracted so callers that
* already hold the window (e.g. {@link getTimingReviewData}) don't re-fetch it —
* the single place the pace statistic is derived from a set of sessions.
*/
function assessPaceForSessions(sessions: readonly PaceWindowSession[]): PaceAssessment {
return assessPace(toTimedAttempts(sessions), sessions.length, {
defaultSecondsPerProblem: DEFAULT_SECONDS_PER_PROBLEM,
})
}
/**
* Compute the robust pace assessment for a player — the SINGLE producer of the
* pace statistic (shared contract). Live-computed at read time from a narrow
* projection of the recent session window; no cached aggregate, so #158 repairs
* self-correct on the next call.
*/
export async function getPaceAssessment(playerId: string): Promise<PaceAssessment> {
const sessions = await fetchPaceWindowSessions(playerId)
return assessPaceForSessions(sessions)
}
/** Serialize a stored result for the wire (its only `Date`, `timestamp`, → ISO). */
function serializeResultForReview(result: SlotResult): SerializedSlotResult {
const ts = result.timestamp as unknown
return {
...result,
timestamp: ts instanceof Date ? ts.toISOString() : String(ts),
}
}
/**
* Read-side data for the timing-review page (#158).
*
* The estimate (`assessment`) comes from the same producer as
* {@link getPaceAssessment} (`assessPaceForSessions`, over one shared fetch of
* the window) — this function NEVER computes its own pace number. It only
* enumerates the flagged attempts (using the same shared classifier and
* per-child stats the estimator uses) so a parent sees every unusual timing at
* the player level without needing to know which session to open, plus the
* soft-deleted sessions available to restore.
*/
export async function getTimingReviewData(playerId: string): Promise<TimingReviewData> {
// Fetch the pace window ONCE and derive the assessment from it (rather than
// calling getPaceAssessment, which would fetch the same window a second time).
const [windowSessions, deletedRows] = await Promise.all([
fetchPaceWindowSessions(playerId),
db
.select({
id: schema.sessionPlans.id,
results: schema.sessionPlans.results,
completedAt: schema.sessionPlans.completedAt,
deletedAt: schema.sessionPlans.deletedAt,
})
.from(schema.sessionPlans)
.where(
and(
eq(schema.sessionPlans.playerId, playerId),
eq(schema.sessionPlans.status, 'deleted')
)
)
.orderBy(desc(schema.sessionPlans.deletedAt))
.limit(PACE_WINDOW_SESSIONS),
])
const assessment = assessPaceForSessions(windowSessions)
// Rebuild the child's clean distribution exactly as the estimator does so the
// Tier-2 classification here matches the assessment's counts (Tier-1 needs no
// stats; Tier-2 is judged against the child's own windowed spread).
const cleanEffectiveMs: number[] = []
for (const session of windowSessions) {
for (const result of session.results) {
if (classifyAttemptTiming(result).tier === 'tier1') continue
const effective = getEffectiveResponseTimeMs(result)
if (effective != null) cleanEffectiveMs.push(effective)
}
}
const childStats = computeChildTimingStats(cleanEffectiveMs)
const flagged: FlaggedAttempt[] = []
for (const session of windowSessions) {
const completedAt = session.completedAt ? session.completedAt.toISOString() : null
session.results.forEach((result, resultIndex) => {
const classification = classifyAttemptTiming(result, childStats)
let displayTier: 'tier1' | 'tier2'
let displayReason: AttemptTimingReason | undefined
if (classification.tier === 'ok') {
// Acting on a flag can re-classify the attempt as 'ok' — omitting or
// adjusting it both null-out / replace the effective time — which would
// silently drop the card the instant it's touched, leaving the adult no
// way to undo a mis-click. Keep any acted-on attempt as a resolved card
// by recovering the tier it WOULD flag as without those overrides, so the
// card (and its Ignore↔Count / Reset controls) stays reachable.
// (`timingConfirmed` never forces 'ok', so it isn't handled here.)
const review = result.timingReview
const actedOn =
review != null &&
(review.omitFromTiming === true || review.adjustedResponseTimeMs != null)
if (!actedOn) return
const original = classifyAttemptTiming(
{
...result,
timingReview: { ...review, omitFromTiming: false, adjustedResponseTimeMs: undefined },
},
childStats
)
if (original.tier === 'ok') return
displayTier = original.tier
displayReason = original.reason
} else {
displayTier = classification.tier
displayReason = classification.reason
}
flagged.push({
sessionId: session.id,
completedAt,
resultIndex,
tier: displayTier,
reason: displayReason,
effectiveMs: getEffectiveResponseTimeMs(result),
// Resolution-aware (#158 FIX A/B): a bare review stamp (e.g. mastery-only)
// or an unconfirm doesn't resolve the timing flag — only omit/adjust/
// confirm does. Keeps the review page's "to review" count and each card's
// resolved state honest (and lets an unconfirm reopen the flag).
resolved: isFlagResolved(result),
result: serializeResultForReview(result),
})
})
}
// Worst (slowest) first; Tier-1 (unbounded/legacy) tends to sort to the top.
// Omitted attempts (effectiveMs null) are resolved, so they sink to the bottom.
flagged.sort((a, b) => (b.effectiveMs ?? 0) - (a.effectiveMs ?? 0))
const deletedSessions: DeletedSessionSummary[] = deletedRows.map((row) => {
const results = (row.results as SlotResult[] | null) ?? []
return {
sessionId: row.id,
completedAt: row.completedAt ? row.completedAt.toISOString() : null,
deletedAt: row.deletedAt ? row.deletedAt.toISOString() : null,
problemsAttempted: results.length,
problemsCorrect: results.filter((r) => r.isCorrect).length,
}
})
return { assessment, flagged, deletedSessions }
}
/**
* Get recent practice sessions for a player
*
* NOTE: This queries from session_plans (the active session system) and
* transforms results into PracticeSession format for the dashboard.
* The old practice_sessions table is no longer populated.
*/
export async function getRecentSessions(
playerId: string,
limit: number = 10
): Promise<PracticeSession[]> {
// Query completed/abandoned sessions from session_plans.
//
// IMPORTANT: We explicitly project only the columns the transform below reads.
// A previous version used `db.query.sessionPlans.findMany(...)` which selects
// every column — including `parts` (10–50 KB of problem-generation traces per
// row) — and blew libsql's response size cap on heavy users (issue #141).
// Same pattern used by batchGetRecentSessionResults in session-planner.ts.
const sessions = await db
.select({
id: schema.sessionPlans.id,
playerId: schema.sessionPlans.playerId,
results: schema.sessionPlans.results,
startedAt: schema.sessionPlans.startedAt,
createdAt: schema.sessionPlans.createdAt,
completedAt: schema.sessionPlans.completedAt,
})
.from(schema.sessionPlans)
.where(
and(
eq(schema.sessionPlans.playerId, playerId),
inArray(schema.sessionPlans.status, ['completed', 'abandoned'])
)
)
.orderBy(desc(schema.sessionPlans.completedAt))
.limit(limit)
// Transform session_plans data into PracticeSession format (shared transform).
return sessions.map(toPracticeSession)
}
/**
* Response type for paginated sessions
*/
export interface PaginatedSessionsResponse {
sessions: PracticeSession[]
nextCursor: string | null
hasMore: boolean
}
/**
* Get paginated sessions with cursor-based pagination
* Cursor is the session ID to start after (for "load more" functionality)
*/
export async function getPaginatedSessions(
playerId: string,
limit: number = 20,
cursor?: string
): Promise<PaginatedSessionsResponse> {
console.log(`[getPaginatedSessions] playerId=${playerId}, limit=${limit}, cursor=${cursor}`)
// If we have a cursor, we need to find sessions older than that cursor's completedAt.
// Project only the two columns we read (id, completedAt) to avoid pulling
// the heavy `parts`/`results` blobs just to check the cursor (#141).
let cursorSession: { id: string; completedAt: Date | null } | null = null
if (cursor) {
cursorSession =
(await db.query.sessionPlans.findFirst({
where: eq(schema.sessionPlans.id, cursor),
columns: { id: true, completedAt: true },
})) ?? null
console.log(
`[getPaginatedSessions] cursorSession found: ${!!cursorSession}, completedAt=${cursorSession?.completedAt}`
)
}
// Build the query conditions - include cursor condition in SQL for proper pagination
const conditions = [
eq(schema.sessionPlans.playerId, playerId),
inArray(schema.sessionPlans.status, ['completed', 'abandoned']),
]
// Add cursor condition to SQL query (sessions older than cursor)
if (cursorSession?.completedAt) {
// Sessions with earlier completedAt, OR same completedAt but smaller ID (for tie-breaking)
conditions.push(
or(
lt(schema.sessionPlans.completedAt, cursorSession.completedAt),
and(
eq(schema.sessionPlans.completedAt, cursorSession.completedAt),
lt(schema.sessionPlans.id, cursorSession.id)
)
)!
)
}
// Query one extra to check if there are more.
// Narrow projection — see getRecentSessions above for context (#141).
const sessions = await db
.select({
id: schema.sessionPlans.id,
playerId: schema.sessionPlans.playerId,
results: schema.sessionPlans.results,
startedAt: schema.sessionPlans.startedAt,
createdAt: schema.sessionPlans.createdAt,
completedAt: schema.sessionPlans.completedAt,
})
.from(schema.sessionPlans)
.where(and(...conditions))
.orderBy(desc(schema.sessionPlans.completedAt))
.limit(limit + 1)
console.log(`[getPaginatedSessions] Raw query returned ${sessions.length} sessions`)
// Check if there are more results
const hasMore = sessions.length > limit
const resultSessions = hasMore ? sessions.slice(0, limit) : sessions
console.log(`[getPaginatedSessions] Final: ${resultSessions.length} sessions, hasMore=${hasMore}`)
// Transform to PracticeSession format (shared transform).
const practiceSessionsResult = resultSessions.map(toPracticeSession)
// Next cursor is the last session's ID
const nextCursor =
hasMore && resultSessions.length > 0 ? resultSessions[resultSessions.length - 1].id : null
return {
sessions: practiceSessionsResult,
nextCursor,
hasMore,
}
}
// ============================================================================
// COMPOSITE OPERATIONS
// ============================================================================
/**
* Get full progress summary for a player
*/
export interface PlayerProgressSummary {
curriculum: PlayerCurriculum | null
totalSkills: number
/** Number of skills with isPracticing=true */
practicingSkillCount: number
/** Percentage of skills being practiced */
practicingPercent: number
recentSessions: PracticeSession[]
recentSkills: PlayerSkillMastery[]
/** @deprecated Use practicingSkillCount instead */
masteredSkills: number
/** @deprecated No longer used - was always 0 */
practicingSkills: number
/** @deprecated No longer used */
learningSkills: number
/** @deprecated Use practicingPercent instead */
masteryPercent: number
}
export async function getPlayerProgressSummary(playerId: string): Promise<PlayerProgressSummary> {
const [curriculum, allSkills, recentSessions] = await Promise.all([
getPlayerCurriculum(playerId),
getAllSkillMastery(playerId),
getRecentSessions(playerId, 5),
])
const practicingSkillCount = allSkills.filter((s) => isActive(s.practiceLevel)).length
const totalSkills = allSkills.length
const practicingPercent =
totalSkills > 0 ? Math.round((practicingSkillCount / totalSkills) * 100) : 0
// Get 5 most recently practiced skills
const recentSkills = allSkills.slice(0, 5)
return {
curriculum,
totalSkills,
practicingSkillCount,
practicingPercent,
recentSessions,
recentSkills,
// Backwards compat - deprecated fields
masteredSkills: practicingSkillCount,
practicingSkills: 0,
learningSkills: totalSkills - practicingSkillCount,
masteryPercent: practicingPercent,
}
}
/**
* Initialize a new student in the curriculum
* Creates curriculum position if it doesn't exist
*/
export async function initializeStudent(playerId: string): Promise<PlayerCurriculum> {
return upsertPlayerCurriculum(playerId, {
currentLevel: 1,
currentPhaseId: 'L1.add.+1.direct',
visualizationMode: false,
})
}
// ============================================================================
// SKILL PERFORMANCE ANALYSIS
// ============================================================================
/**
* Skill performance data with calculated averages
*/
export interface SkillPerformance {
skillId: string
/** BKT-based mastery classification (null = insufficient data, computed client-side) */
bktClassification: 'strong' | 'developing' | 'weak' | null
attempts: number
correct: number
avgResponseTimeMs: number | null // null if no timing data
responseTimeCount: number
}
/**
* Analysis of a player's skill strengths and weaknesses
*/
export interface SkillPerformanceAnalysis {
/** All skills with performance data */
skills: SkillPerformance[]
/** Overall average response time (ms) across all skills with timing data */
overallAvgResponseTimeMs: number | null
/** Skills where student is significantly faster than average (excelling) */
fastSkills: SkillPerformance[]
/** Skills where student is significantly slower than average (struggling) */
slowSkills: SkillPerformance[]
}
/**
* Thresholds for performance analysis
*/
const PERFORMANCE_THRESHOLDS = {
/** Speed deviation threshold (percentage faster/slower than average to flag) */
speedDeviationPercent: 0.3, // 30% faster/slower
/** Minimum responses needed for timing analysis */
minResponsesForTiming: 3,
} as const
/**
* Analyze a player's skill performance to identify strengths and weaknesses
* Uses response time data to find skills where the student excels vs struggles
*
* Note: BKT classification is computed client-side from session plan data,
* so we return null here. The client enriches this with BKT data.
*
* Stats (attempts, correct, responseTime) are computed from session results,
* not from the playerSkillMastery table, ensuring single source of truth.
*/
export async function analyzeSkillPerformance(playerId: string): Promise<SkillPerformanceAnalysis> {
const allSkills = await getAllSkillMastery(playerId)
const sessionResults = await getRecentSessionResults(playerId, 100)
// Aggregate stats per skill from session results
const skillStats = new Map<
string,
{ attempts: number; correct: number; responseTimes: number[] }
>()
for (const result of sessionResults) {
for (const skillId of result.skillsExercised) {
if (!skillStats.has(skillId)) {
skillStats.set(skillId, { attempts: 0, correct: 0, responseTimes: [] })
}
const stats = skillStats.get(skillId)!
stats.attempts++
if (result.isCorrect) {
stats.correct++
}
if (result.responseTimeMs > 0) {
stats.responseTimes.push(result.responseTimeMs)
}
}
}
// Calculate performance data for each skill
// Note: bktClassification is computed client-side from session history
const skills: SkillPerformance[] = allSkills.map((s) => {
const stats = skillStats.get(s.skillId)
const attempts = stats?.attempts ?? 0
const correct = stats?.correct ?? 0
const responseTimes = stats?.responseTimes ?? []
return {
skillId: s.skillId,
bktClassification: null, // Computed client-side from session plans
attempts,
correct,
avgResponseTimeMs:
responseTimes.length > 0
? Math.round(responseTimes.reduce((a, b) => a + b, 0) / responseTimes.length)
: null,
responseTimeCount: responseTimes.length,
}
})
// Calculate overall average response time (only from skills with sufficient data)
const skillsWithTiming = skills.filter(
(s) =>
s.avgResponseTimeMs !== null &&
s.responseTimeCount >= PERFORMANCE_THRESHOLDS.minResponsesForTiming
)
const overallAvgResponseTimeMs =
skillsWithTiming.length > 0
? Math.round(
skillsWithTiming.reduce((sum, s) => sum + (s.avgResponseTimeMs ?? 0), 0) /
skillsWithTiming.length
)
: null
// Identify fast skills (significantly faster than average)
const fastSkills =
overallAvgResponseTimeMs !== null
? skillsWithTiming.filter(
(s) =>
s.avgResponseTimeMs !== null &&
s.avgResponseTimeMs <
overallAvgResponseTimeMs * (1 - PERFORMANCE_THRESHOLDS.speedDeviationPercent)
)
: []
// Identify slow skills (significantly slower than average)
const slowSkills =
overallAvgResponseTimeMs !== null
? skillsWithTiming.filter(
(s) =>
s.avgResponseTimeMs !== null &&
s.avgResponseTimeMs >
overallAvgResponseTimeMs * (1 + PERFORMANCE_THRESHOLDS.speedDeviationPercent)
)
: []
return {
skills,
overallAvgResponseTimeMs,
fastSkills,
slowSkills,
}
}
/**
* Get skills ranked by response time (slowest first)
* Useful for identifying skills that need practice
*/
export async function getSkillsByResponseTime(
playerId: string,
order: 'slowest' | 'fastest' = 'slowest'
): Promise<SkillPerformance[]> {
const analysis = await analyzeSkillPerformance(playerId)
// Filter to only skills with timing data
const skillsWithTiming = analysis.skills.filter(
(s) =>
s.avgResponseTimeMs !== null &&
s.responseTimeCount >= PERFORMANCE_THRESHOLDS.minResponsesForTiming
)
// Sort by response time
return skillsWithTiming.sort((a, b) => {
const timeA = a.avgResponseTimeMs ?? 0
const timeB = b.avgResponseTimeMs ?? 0
return order === 'slowest' ? timeB - timeA : timeA - timeB
})
}
// ============================================================================
// SKILL TUTORIAL PROGRESS OPERATIONS
// ============================================================================
/**
* Get a player's tutorial progress for a specific skill
*/
export async function getSkillTutorialProgress(
playerId: string,
skillId: string
): Promise<SkillTutorialProgress | null> {
const result = await db.query.skillTutorialProgress.findFirst({
where: and(
eq(schema.skillTutorialProgress.playerId, playerId),
eq(schema.skillTutorialProgress.skillId, skillId)
),
})
return result ?? null
}
/**
* Get all tutorial progress records for a player
*/
export async function getAllTutorialProgress(playerId: string): Promise<SkillTutorialProgress[]> {
return db.query.skillTutorialProgress.findMany({
where: eq(schema.skillTutorialProgress.playerId, playerId),
})
}
/**
* Check if a skill's tutorial requirement is satisfied for a player.
* Returns true if tutorial completed OR teacher override applied.
*/
export async function isSkillTutorialSatisfied(
playerId: string,
skillId: string
): Promise<boolean> {
const progress = await getSkillTutorialProgress(playerId, skillId)
return isTutorialSatisfied(progress)
}
/**
* Mark a skill's tutorial as completed
*/
export async function markTutorialComplete(
playerId: string,
skillId: string
): Promise<SkillTutorialProgress> {
const existing = await getSkillTutorialProgress(playerId, skillId)
const now = new Date()
if (existing) {
await db
.update(schema.skillTutorialProgress)
.set({
tutorialCompleted: true,
completedAt: now,
updatedAt: now,
})
.where(eq(schema.skillTutorialProgress.id, existing.id))
return (await getSkillTutorialProgress(playerId, skillId))!
}
// Create new record
const newRecord: NewSkillTutorialProgress = {
playerId,
skillId,
tutorialCompleted: true,
completedAt: now,
createdAt: now,
updatedAt: now,
}
await db.insert(schema.skillTutorialProgress).values(newRecord)
return (await getSkillTutorialProgress(playerId, skillId))!
}
/**
* Apply teacher override to bypass tutorial requirement.
* Use case: student learned the technique offline with their teacher.
*/
export async function applyTutorialOverride(
playerId: string,
skillId: string,
reason?: string
): Promise<SkillTutorialProgress> {
const existing = await getSkillTutorialProgress(playerId, skillId)
const now = new Date()
if (existing) {
await db
.update(schema.skillTutorialProgress)
.set({
teacherOverride: true,
overrideAt: now,
overrideReason: reason ?? null,
updatedAt: now,
})
.where(eq(schema.skillTutorialProgress.id, existing.id))
return (await getSkillTutorialProgress(playerId, skillId))!
}
// Create new record
const newRecord: NewSkillTutorialProgress = {
playerId,
skillId,
teacherOverride: true,
overrideAt: now,
overrideReason: reason ?? null,
createdAt: now,
updatedAt: now,
}
await db.insert(schema.skillTutorialProgress).values(newRecord)
return (await getSkillTutorialProgress(playerId, skillId))!
}
/**
* Record that a student skipped the tutorial prompt.
* Used to surface to teachers if student is repeatedly avoiding tutorials.
*/
export async function recordTutorialSkip(
playerId: string,
skillId: string
): Promise<SkillTutorialProgress> {
const existing = await getSkillTutorialProgress(playerId, skillId)
const now = new Date()
if (existing) {
await db
.update(schema.skillTutorialProgress)
.set({
skipCount: existing.skipCount + 1,
lastSkippedAt: now,
updatedAt: now,
})
.where(eq(schema.skillTutorialProgress.id, existing.id))
return (await getSkillTutorialProgress(playerId, skillId))!
}
// Create new record
const newRecord: NewSkillTutorialProgress = {
playerId,
skillId,
skipCount: 1,
lastSkippedAt: now,
createdAt: now,
updatedAt: now,
}
await db.insert(schema.skillTutorialProgress).values(newRecord)
return (await getSkillTutorialProgress(playerId, skillId))!
}
/**
* Get skills that have been skipped multiple times (for teacher dashboard).
* Returns skills where the student has skipped the tutorial 3+ times.
*/
export async function getRepeatedlySkippedTutorials(
playerId: string,
minSkipCount: number = 3
): Promise<SkillTutorialProgress[]> {
const allProgress = await getAllTutorialProgress(playerId)
return allProgress.filter(
(p) => p.skipCount >= minSkipCount && !p.tutorialCompleted && !p.teacherOverride
)
}
// Re-export the helper function
export { isTutorialSatisfied }
// ============================================================================
// SKILL ACTIVATION OPERATIONS
// ============================================================================
/**
* Enable a single skill for practice at the 'abacus' level (default entry after tutorial).
* Creates a new skill mastery record if one doesn't exist, or updates to 'abacus' level.
* Preserves existing 'visual' level if already set higher.
*
* @param playerId - The player's ID
* @param skillId - The skill to enable
* @returns Updated skill mastery record
*/
export async function enableSkillForPractice(
playerId: string,
skillId: string
): Promise<PlayerSkillMastery> {
const existing = await getSkillMastery(playerId, skillId)
const now = new Date()
if (existing) {
// Only upgrade if currently at 'none' level
if (existing.practiceLevel === 'none') {
await db
.update(schema.playerSkillMastery)
.set({
isPracticing: true,
practiceLevel: 'abacus',
updatedAt: now,
})
.where(eq(schema.playerSkillMastery.id, existing.id))
}
return (await getSkillMastery(playerId, skillId))!
}
// Create new record with skill enabled for practice at abacus level
const newRecord: NewPlayerSkillMastery = {
playerId,
skillId,
isPracticing: true,
practiceLevel: 'abacus',
lastPracticedAt: now,
}
await db.insert(schema.playerSkillMastery).values(newRecord)
return (await getSkillMastery(playerId, skillId))!
}
|