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 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 | 3x 3x 3x 3x 13x 13x 83x 83x 83x 83x 83x 83x 83x 321x 519x 408x 220x 220x 220x 130x 130x 130x 130x 125x 125x 3x 3x 33x 33x 32x 32x 32x 382x 369x 260x 352x 92x 92x 5x 145x 92x 92x 238x 25x 14x 2662x 239x 239x 239x 239x 1852x 1852x 1476x 376x 306x 70x 70x 239x 127x 289x 211x 101x 1248x 33x 35x 94x 10x 94x 94x 1x 1x 9x 9x 9x 124x 124x 124x 124x 124x 120x 120x 4x 4x 124x 5x 124x 94x 124x 124x 3x 3x 91x 124x 124x 124x 4x 79x 79x 5x 5x 5x 79x 79x 3x 79x 79x 79x 79x 62x 62x 62x 78x 78x 78x 73x 73x 79x 79x 38x 38x 38x 20x 79x 58x 79x 40x 20x 20x 20x 79x 79x 115x 115x 115x 115x 115x 79x 2x 1x 1x 1x 1x 1x 79x 1x 79x 79x 79x 115x 79x 79x 79x 79x 79x 79x 79x 115x 73x 115x 115x 73x 73x 115x 115x 73x 115x 115x 115x 43x 115x 43x 43x 43x 119x 149x 141x 141x 102x 22x 22x 1x 1x 101x 141x 141x 141x 140x 140x 39x 30x 101x 85x 25x 140x 140x 124x 124x 123x 123x 123x 1x 1x 1x 140x 140x 25x 25x 115x 115x 115x 140x 140x 140x 140x 140x 141x 141x 141x 141x 141x 141x 140x 140x 140x 140x 141x 141x 141x 141x 141x 141x 141x 119x 119x 141x 141x 141x 119x 13x 13x 119x 13x 13x 119x 119x 119x 119x 119x 119x 119x 119x 119x 119x 119x 119x 119x 140x 216x 2135x 427x 119x 119x 259x 119x 119x 119x 119x 119x 119x 119x 119x 119x 92x 92x 114x 114x 114x 114x 114x 114x 92x 114x 25x 25x 25x 92x 92x 92x 82x 119x 92x 92x 1x 1x 91x 92x 92x 92x 92x 92x 90x 90x 89x 89x 88x 88x 88x 110x 88x 92x 92x 92x 92x 114x 92x 92x 82x 82x 82x 82x 82x 1x 1x 1x 81x 1x 1x 1x 80x 80x 92x 80x 92x 92x 92x 4x 4x 4x 88x 4x 4x 4x 84x 2x 2x 2x 82x 92x 10x 10x 10x 80x 80x 80x 102x 80x 102x 119x 119x 119x 119x 32x 32x 32x 119x 119x 119x 80x 236x 32x 43x 32x 31x 31x 31x 31x 31x 31x 4x 31x 31x 27x 27x 1x 26x 4x 4x 4x 4x 3x 1x 2x | import { randomUUID } from "node:crypto";
import type { TutorContentResult, TutorDialogTurn } from "@shared/tutor";
import {
inspectLearningQuestion,
isSemanticallyRepeatedQuestion,
TUTOR_PROMPT_REVISION,
TutorService,
type TutorFollowUpSource,
} from "../tutor-service";
import {
TutorProviderError,
type LLMProvider,
type LLMProviderRequest,
type ProviderQuestionResult,
type ProviderStructuredResult,
type StructuredLLMProvider,
type StructuredLLMProviderRequest,
} from "../llm-provider";
import { CurriculumTutorAdapter } from "../curriculum-tutor-adapter";
import type { TutorPlanningContentContext } from "../tutor-planning";
import type { TutorProgressionState } from "../curriculum/progression-state";
import type { TutorQualityExpectation } from "./anchor-corpus";
import { canonicalDigest, canonicalJson, sha256 } from "./canonical";
import { TUTOR_TEMPERATURE } from "../kiconnect-provider";
import {
buildJudgeInput,
callJudge,
parseJudgeResult,
JudgeProviderCallError,
type TutorQualityJudgePrompt,
type TutorQualitySemanticEvaluation,
} from "./judge";
import { createTutorQualityRunManifest, writeRunArtifacts } from "./report";
import { findRevealedLiteral } from "./reveal-check";
import { computeTutorQualityVerdict, type TutorQualityVerdict, type TutorQualityVerdictSample } from "./quality-verdict";
export type TutorQualityExecutionStatus = "completed" | "invalid" | "technical-failure" | "not-run";
export const MAX_TUTOR_QUALITY_SAMPLES = 20;
export const MAX_TUTOR_QUALITY_CALLS = 500;
const EMPTY_STAGE_A_PROVIDER_CALLS: TutorQualityStageAProviderCallCounts = {
total: 0,
modelListCalls: 0,
generationCalls: 0,
};
const EMPTY_PROVIDER_CALLS: TutorQualityProviderCallCounts = {
...EMPTY_STAGE_A_PROVIDER_CALLS,
judgeCalls: 0,
};
export type TutorQualityTurn =
| {
readonly kind: "initial";
readonly difficulty?: number;
}
| {
readonly kind: "dialog";
readonly question: string;
readonly answer: string;
readonly continuationOf?: number;
readonly difficulty?: number;
readonly history?: readonly TutorDialogTurn[];
};
export interface TutorQualityEvaluationScenario {
readonly id: string;
readonly corpusId: string;
readonly corpusVersion: number;
readonly sketchRef: string;
readonly sketch: string;
readonly sketchDigest?: string;
readonly corpusFileDigest?: string;
readonly judge?: {
readonly facts: readonly string[];
readonly criteria: readonly { readonly id: string; readonly text: string }[];
};
readonly courseContent?: TutorPlanningContentContext;
readonly turns: readonly TutorQualityTurn[];
readonly expected?: TutorQualityExpectation;
}
export interface TutorQualityGitState {
readonly sha: string;
readonly trackedClean: boolean;
readonly relevantUntrackedClean: boolean;
}
export interface TutorQualityEvaluationOptions {
readonly scenarios: readonly TutorQualityEvaluationScenario[];
readonly provider: LLMProvider;
readonly providerId: string;
readonly endpointOrigin?: string;
readonly credential?: string;
readonly requestedModel: string;
readonly judgeModel?: string;
readonly judgeCredential?: string;
readonly samples: number;
readonly maxCalls: number;
readonly timeoutMs?: number;
readonly outputDir?: string;
readonly git: TutorQualityGitState;
readonly now?: () => Date;
readonly runSuffix?: () => string;
readonly artifactWriter?: (
report: TutorQualityEvaluationReport,
transcripts: readonly TutorQualityTranscript[],
) => Promise<void>;
}
export type TutorQualityCheckOutcome = "pass" | "fail" | "not-applicable";
export interface TutorQualityDeterministicCheck {
readonly name: string;
/** R-ATT-2: a check that cannot be interpreted is `not-applicable`, neither a pass nor a fail. */
readonly outcome: TutorQualityCheckOutcome;
/** True only for `pass`. Kept for the transcript-v1 contract (§11.4); count by `outcome`. */
readonly passed: boolean;
readonly details?: string;
/** Why the check is not applicable. */
readonly reason?: string;
}
export interface TutorQualityInvariantViolation {
readonly code: string;
readonly source: "raw-provider" | "final-tutor" | "state" | "scenario";
readonly turnIndex?: number;
readonly details?: string;
}
export interface TutorQualityTechnicalError {
readonly kind: string;
readonly name: string;
}
export interface TutorQualityProviderRequestArtifact {
readonly model: string;
readonly systemPrompt: string;
readonly systemPromptDigest: string;
readonly userPrompt: string;
readonly userPromptDigest: string;
}
export interface TutorQualityTranscriptTurn {
readonly index: number;
readonly input: TutorQualityTurn;
readonly startedAt: string;
readonly durationMs: number;
readonly providerCalls: TutorQualityStageAProviderCallCounts;
readonly providerRequest?: TutorQualityProviderRequestArtifact;
readonly rawProviderResult?: Record<string, unknown>;
readonly finalTutorResult?: Record<string, unknown>;
/** Where the final follow-up question came from (R-FUP-1); recorded by TutorService at the decision site. */
readonly followUpSource?: TutorFollowUpSource;
readonly returnedModel?: string;
readonly deterministicChecks: readonly TutorQualityDeterministicCheck[];
readonly technicalError?: TutorQualityTechnicalError;
}
export interface TutorQualityTranscript {
readonly schemaVersion: "tutor-quality-transcript-v1";
readonly runId: string;
readonly evaluationIdentity: string;
readonly metadata: TutorQualityMetadata;
readonly scenario: {
readonly id: string;
readonly corpusId: string;
readonly corpusVersion: number;
readonly sketchRef: string;
readonly sketch: string;
readonly syntheticTurns: readonly TutorQualityTurn[];
};
readonly stateBefore?: TutorProgressionState;
readonly stateAfter?: TutorProgressionState;
readonly turns: readonly TutorQualityTranscriptTurn[];
readonly deterministicChecks: readonly TutorQualityDeterministicCheck[];
readonly executionStatus: TutorQualityExecutionStatus;
readonly invalidReason?: string;
readonly technicalError?: TutorQualityTechnicalError;
readonly invariantViolations: readonly TutorQualityInvariantViolation[];
}
export interface TutorQualityMetadata {
readonly providerId: string;
readonly endpointOrigin?: string;
readonly requestedModel: string;
readonly returnedModels: readonly string[];
readonly promptRevision: {
readonly id: string;
readonly templateDigest: string;
};
readonly courseContentRevision: string;
readonly corpusId: string;
readonly corpusVersion: number;
readonly gitSha: string;
readonly gitState: "clean";
readonly sampleIndex: number;
readonly sampleCount: number;
readonly sampleStartedAt: string;
readonly sampleDurationMs: number;
readonly providerCalls: TutorQualityStageAProviderCallCounts;
readonly timeoutMs?: number;
readonly temperature?: number;
readonly maxCalls: number;
}
export interface TutorQualityStageAProviderCallCounts {
readonly total: number;
readonly modelListCalls: number;
readonly generationCalls: number;
}
export interface TutorQualityProviderCallCounts extends TutorQualityStageAProviderCallCounts {
readonly judgeCalls: number;
}
export interface TutorQualityScenarioAggregate {
readonly samplesRequested: number;
readonly samplesObserved: number;
readonly completed: number;
readonly invalid: number;
readonly technicalFailures: number;
readonly notRun: number;
readonly invariantViolationSamples: number;
readonly budgetExhausted: number;
readonly providerCalls: TutorQualityProviderCallCounts;
readonly technicalErrorKinds: Readonly<Record<string, number>>;
readonly rates: TutorQualityRates;
}
export interface TutorQualityRates {
readonly completedOfObserved: number | null;
readonly invalidOfObserved: number | null;
readonly technicalFailureOfObserved: number | null;
readonly notRunOfObserved: number | null;
readonly invariantViolationOfObserved: number | null;
}
export interface TutorQualityEvaluationReport {
readonly schemaVersion: "tutor-quality-report-v1";
readonly runId: string;
readonly evaluationIdentity: string;
readonly runStatus: TutorQualityExecutionStatus;
readonly reason?: string;
readonly providerId: string;
readonly requestedModel: string;
readonly credentialPresent: boolean;
readonly samplesRequested: number;
readonly samplesObserved: number;
readonly completed: number;
readonly invalid: number;
readonly technicalFailures: number;
readonly notRun: number;
readonly invariantViolationSamples: number;
readonly budgetExhausted: number;
readonly providerCalls: TutorQualityProviderCallCounts;
readonly technicalErrorKinds: Readonly<Record<string, number>>;
readonly byScenario: Readonly<Record<string, TutorQualityScenarioAggregate>>;
readonly rates: TutorQualityRates;
readonly monetaryCost: "unavailable";
readonly totalDurationMs: number;
readonly semanticEvaluations?: readonly TutorQualitySemanticEvaluationRecord[];
/** Run-level quality statement (Evaluation SSOT §12). */
readonly qualityVerdict: TutorQualityVerdict;
}
type TutorQualityReportWithoutVerdict = Omit<TutorQualityEvaluationReport, "qualityVerdict">;
export interface TutorQualitySemanticEvaluationRecord {
readonly scenarioId: string;
readonly sampleIndex: number;
readonly learningPhase?: string;
readonly evaluation: TutorQualitySemanticEvaluation;
}
export interface TutorQualityEvaluationResult {
readonly report: TutorQualityEvaluationReport;
readonly transcripts: readonly TutorQualityTranscript[];
readonly semanticEvaluations: readonly TutorQualitySemanticEvaluationRecord[];
}
interface ProviderCapture {
readonly request: LLMProviderRequest;
readonly response?: ProviderQuestionResult;
readonly error?: unknown;
}
class EvaluationBudgetExceeded extends Error {
constructor() {
super("call-budget-exhausted");
this.name = "EvaluationBudgetExceeded";
}
}
export class CountingProvider implements LLMProvider, StructuredLLMProvider {
private totalCalls = 0;
private modelListCalls = 0;
private generationCalls = 0;
private judgeCalls = 0;
private readonly generations: ProviderCapture[] = [];
constructor(
private readonly provider: LLMProvider,
private readonly maxCalls: number,
) {}
get counts(): TutorQualityProviderCallCounts {
return {
total: this.totalCalls,
modelListCalls: this.modelListCalls,
generationCalls: this.generationCalls,
judgeCalls: this.judgeCalls,
};
}
get stageACounts(): TutorQualityStageAProviderCallCounts {
return {
total: this.modelListCalls + this.generationCalls,
modelListCalls: this.modelListCalls,
generationCalls: this.generationCalls,
};
}
get generationCaptures(): readonly ProviderCapture[] {
return this.generations;
}
async listModels(credential: string): Promise<readonly string[]> {
this.reserveCall();
this.modelListCalls += 1;
return this.provider.listModels(credential);
}
async generateLearningQuestion(request: LLMProviderRequest, credential: string): Promise<ProviderQuestionResult> {
this.reserveCall();
this.generationCalls += 1;
try {
const response = await this.provider.generateLearningQuestion(request, credential);
this.generations.push({ request, response });
return response;
} catch (error) {
this.generations.push({ request, error });
throw error;
}
}
async generateStructuredResponse(
request: StructuredLLMProviderRequest,
credential: string,
): Promise<ProviderStructuredResult> {
const provider = this.provider as LLMProvider & Partial<StructuredLLMProvider>;
if (!provider.generateStructuredResponse) throw new TutorProviderError("provider-unavailable");
this.reserveCall();
this.judgeCalls += 1;
return provider.generateStructuredResponse(request, credential);
}
private reserveCall(): void {
if (this.totalCalls >= this.maxCalls) throw new EvaluationBudgetExceeded();
this.totalCalls += 1;
}
}
function clone<T>(value: T): T {
return structuredClone(value);
}
function courseRevision(scenario: TutorQualityEvaluationScenario): string {
return scenario.courseContent?.revision ?? "free-tutor";
}
function makeEvaluationIdentity(options: TutorQualityEvaluationOptions): string {
const first = options.scenarios[0];
return canonicalDigest({
unosimGitSha: options.git.sha,
courseContentRevisions: [...new Set(options.scenarios.map(courseRevision))].sort((left, right) => left.localeCompare(right)),
corpusId: first?.corpusId,
corpusVersion: first?.corpusVersion,
providerId: options.providerId,
requestedModel: options.requestedModel,
promptRevision: {
id: TUTOR_PROMPT_REVISION.id,
templateDigest: TUTOR_PROMPT_REVISION.templateDigest,
},
parameters: {
timeoutMs: options.timeoutMs,
temperature: TUTOR_TEMPERATURE,
sampleCount: options.samples,
maxCalls: options.maxCalls,
difficulties: options.scenarios.flatMap((scenario) => scenario.turns.map((turn) => turn.difficulty ?? 30)),
},
});
}
function makeRunId(options: TutorQualityEvaluationOptions): string {
const now = (options.now ?? (() => new Date()))().toISOString().replaceAll(/[^0-9TZ]/g, "");
return `tq2a-${now}-${(options.runSuffix ?? randomUUID)()}`;
}
function metadata(
options: TutorQualityEvaluationOptions,
scenario: TutorQualityEvaluationScenario,
sampleIndex: number,
returnedModels: readonly string[] = [],
sampleStartedAt = new Date(0).toISOString(),
sampleDurationMs = 0,
providerCalls: TutorQualityStageAProviderCallCounts = EMPTY_STAGE_A_PROVIDER_CALLS,
): TutorQualityMetadata {
return {
providerId: options.providerId,
...(options.endpointOrigin ? { endpointOrigin: options.endpointOrigin } : {}),
requestedModel: options.requestedModel,
returnedModels,
promptRevision: {
id: TUTOR_PROMPT_REVISION.id,
templateDigest: TUTOR_PROMPT_REVISION.templateDigest,
},
courseContentRevision: courseRevision(scenario),
corpusId: scenario.corpusId,
corpusVersion: scenario.corpusVersion,
gitSha: options.git.sha,
gitState: "clean",
sampleIndex,
sampleCount: options.samples,
sampleStartedAt,
sampleDurationMs,
providerCalls,
...(options.timeoutMs === undefined ? {} : { timeoutMs: options.timeoutMs }),
temperature: TUTOR_TEMPERATURE,
maxCalls: options.maxCalls,
};
}
function technicalError(error: unknown): TutorQualityTechnicalError {
if (error instanceof EvaluationBudgetExceeded) return { kind: "call-budget-exhausted", name: error.name };
Eif (error instanceof TutorProviderError) return { kind: error.kind, name: error.name };
return { kind: "provider-error", name: "ProviderError" };
}
function redact(value: string, credential: string | undefined): string {
return credential && credential.length > 0 ? value.split(credential).join("[REDACTED]") : value;
}
function safeResult(value: unknown, credential?: string): Record<string, unknown> | undefined {
Iif (value === null || typeof value !== "object" || Array.isArray(value)) return undefined;
const allowed = new Set([
"responseStyle", "feedback", "question", "topic", "difficulty", "answerRating", "mermaid",
"topicId", "conceptId", "questionId", "indicatorId", "questionKind", "strategyId", "strategySource",
"contentRevision", "learningPhase", "activeTopicId", "masteredTopicIds", "progressionBlockedReason",
"extensionTargetTopicId",
]);
const result: Record<string, unknown> = {};
for (const [key, item] of Object.entries(value as Record<string, unknown>)) {
Iif (!allowed.has(key)) continue;
if (typeof item === "string") {
result[key] = redact(item, credential);
} else if (typeof item === "number" || typeof item === "boolean" || item === undefined) {
result[key] = item;
} else Eif (Array.isArray(item) && item.every((entry) => typeof entry === "string")) {
result[key] = item.map((entry) => redact(entry, credential));
}
}
return result;
}
function requestArtifact(request: LLMProviderRequest, credential?: string): TutorQualityProviderRequestArtifact {
return {
model: request.model,
systemPrompt: redact(request.systemPrompt, credential),
systemPromptDigest: sha256(request.systemPrompt),
userPrompt: redact(request.userPrompt, credential),
userPromptDigest: sha256(request.userPrompt),
};
}
function safeTurn(turn: TutorQualityTurn, credential?: string): TutorQualityTurn {
if (turn.kind === "initial") return turn;
return {
...turn,
question: redact(turn.question, credential),
answer: redact(turn.answer, credential),
...(turn.history === undefined ? {} : {
history: turn.history.map((entry) => ({
...entry,
question: redact(entry.question, credential),
answer: redact(entry.answer, credential),
...(entry.feedback === undefined ? {} : { feedback: redact(entry.feedback, credential) }),
})),
}),
};
}
function historyFromSource(history: readonly TutorDialogTurn[] | undefined): readonly TutorDialogTurn[] {
return history ?? [];
}
function addCheck(
checks: TutorQualityDeterministicCheck[],
name: string,
passed: boolean,
details?: string,
): void {
checks.push({ name, outcome: passed ? "pass" : "fail", passed, ...(details ? { details } : {}) });
}
function addNotApplicableCheck(
checks: TutorQualityDeterministicCheck[],
name: string,
reason: string,
details?: string,
): void {
checks.push({ name, outcome: "not-applicable", passed: false, reason, ...(details ? { details } : {}) });
}
function addViolation(
violations: TutorQualityInvariantViolation[],
code: string,
source: TutorQualityInvariantViolation["source"],
turnIndex: number | undefined,
details?: string,
): void {
violations.push({ code, source, ...(turnIndex === undefined ? {} : { turnIndex }), ...(details ? { details } : {}) });
}
function declaredLeakCheck(
rawResult: unknown,
literals: readonly string[] | undefined,
turnIndex: number,
checks: TutorQualityDeterministicCheck[],
violations: TutorQualityInvariantViolation[],
): void {
if (literals === undefined) return;
const raw = typeof rawResult === "object" && rawResult !== null && !Array.isArray(rawResult)
? rawResult as { feedback?: unknown; question?: unknown }
: {};
const texts = [raw.feedback, raw.question].filter((text): text is string => typeof text === "string");
if (texts.length === 0) {
addNotApplicableCheck(checks, "raw-provider-no-declared-leak", "raw-provider-no-readable-text");
return;
}
// A miss only means that no declared literal occurred (R-REV-3).
const revealed = findRevealedLiteral(texts, literals);
addCheck(checks, "raw-provider-no-declared-leak", revealed === undefined, revealed);
if (revealed !== undefined) addViolation(violations, "solution-revealed", "raw-provider", turnIndex, revealed);
}
function deterministicRawChecks(
rawResult: unknown,
turn: TutorQualityTurn,
turnIndex: number,
checks: TutorQualityDeterministicCheck[],
violations: TutorQualityInvariantViolation[],
expected?: TutorQualityExpectation,
): void {
const inspection = inspectLearningQuestion(rawResult, turn.difficulty);
const issueCodes = new Set(inspection.violations.map(({ code }) => code));
const schemaValid = !issueCodes.has("schema-invalid");
addCheck(checks, "raw-provider-schema-valid", schemaValid);
// The question and solution guards inspect only schema-valid output.
if (schemaValid) {
addCheck(checks, "raw-provider-one-primary-question", !issueCodes.has("multiple-primary-questions"));
addCheck(checks, "raw-provider-no-complete-solution", !issueCodes.has("complete-solution"));
} else {
addNotApplicableCheck(checks, "raw-provider-one-primary-question", "raw-provider-schema-invalid");
addNotApplicableCheck(checks, "raw-provider-no-complete-solution", "raw-provider-schema-invalid");
}
for (const issue of inspection.violations) {
addViolation(violations, issue.code, "raw-provider", turnIndex);
}
if (turn.kind !== "dialog") return;
declaredLeakCheck(rawResult, expected?.mustNotReveal, turnIndex, checks, violations);
const question = typeof rawResult === "object" && rawResult !== null && !Array.isArray(rawResult)
? (rawResult as { question?: unknown }).question
: undefined;
// A schema-valid result always has a question; without readable text there is nothing to compare.
if (typeof question !== "string") {
addNotApplicableCheck(checks, "raw-provider-question-not-repeated", "raw-provider-schema-invalid");
return;
}
const previous = [turn.question, ...(turn.history ?? []).map(({ question: historyQuestion }) => historyQuestion)];
const repeated = isSemanticallyRepeatedQuestion(question, previous);
addCheck(checks, "raw-provider-question-not-repeated", !repeated);
if (repeated) {
addViolation(violations, "question-repeat", "raw-provider", turnIndex, question === turn.question ? "exact" : "stage1-heuristic");
}
}
interface ExpectedCheckContext {
readonly scenario: TutorQualityEvaluationScenario;
readonly result: TutorContentResult;
readonly turn: TutorQualityTurn;
readonly stateBefore: TutorProgressionState | undefined;
readonly stateAfter: TutorProgressionState | undefined;
readonly checks: TutorQualityDeterministicCheck[];
readonly violations: TutorQualityInvariantViolation[];
readonly turnIndex: number;
}
function expectedTopicCheck(context: ExpectedCheckContext): void {
const expectedTopic = context.scenario.expected?.topicId;
if (expectedTopic === undefined) return;
const passed = context.result.topicId === expectedTopic;
addCheck(context.checks, "expected-topic", passed, expectedTopic);
Iif (!passed) addViolation(context.violations, "topic-mismatch", "final-tutor", context.turnIndex, expectedTopic);
}
function expectedTopicAbsentCheck(context: ExpectedCheckContext): void {
const forbiddenTopic = context.scenario.expected?.topicIdAbsent;
if (forbiddenTopic === undefined) return;
const passed = context.result.topicId !== forbiddenTopic && context.result.activeTopicId !== forbiddenTopic;
addCheck(context.checks, "expected-topic-absent", passed, forbiddenTopic);
Iif (!passed) addViolation(context.violations, "forbidden-topic-activation", "final-tutor", context.turnIndex, forbiddenTopic);
}
function expectedPhaseCheck(context: ExpectedCheckContext): void {
const expectedPhase = context.scenario.expected?.learningPhase;
if (expectedPhase === undefined) return;
const passed = context.result.learningPhase === expectedPhase;
addCheck(context.checks, "expected-learning-phase", passed, expectedPhase);
Iif (!passed) addViolation(context.violations, "phase-mismatch", "final-tutor", context.turnIndex, expectedPhase);
}
function ratingOutOfBand(context: ExpectedCheckContext): boolean {
const band = context.scenario.expected?.answerRating;
const isFinalTurn = context.turnIndex === context.scenario.turns.length - 1;
if (band === undefined || !isFinalTurn) return false;
const rating = context.result.answerRating;
return rating === undefined || rating < band[0] || rating > band[1];
}
function expectedAnswerRatingCheck(context: ExpectedCheckContext): void {
const band = context.scenario.expected?.answerRating;
if (band === undefined || context.turnIndex !== context.scenario.turns.length - 1) return;
const passed = !ratingOutOfBand(context);
addCheck(context.checks, "expected-answer-rating", passed, `${band[0]}-${band[1]}`);
if (!passed) {
addViolation(context.violations, "answer-rating-out-of-band", "final-tutor", context.turnIndex, `${context.result.answerRating ?? "none"} not in ${band[0]}-${band[1]}`);
}
}
function expectedPhaseAfterCheck(context: ExpectedCheckContext): void {
if (context.turnIndex !== context.scenario.turns.length - 1) return;
const expectedPhaseAfter = context.scenario.expected?.phaseAfter;
if (expectedPhaseAfter === undefined) return;
if (ratingOutOfBand(context)) {
addNotApplicableCheck(context.checks, "expected-phase-after", "rating-out-of-band", expectedPhaseAfter);
return;
}
const passed = context.stateAfter?.phase === expectedPhaseAfter;
addCheck(context.checks, "expected-phase-after", passed, expectedPhaseAfter);
if (!passed) addViolation(context.violations, "phase-after-mismatch", "state", context.turnIndex, expectedPhaseAfter);
}
function unexpectedBlockedStateCheck(context: ExpectedCheckContext): void {
const actualReason = context.result.progressionBlockedReason ?? context.stateAfter?.progressionBlockedReason;
const expectedReason = context.scenario.expected?.progressionBlockedReason;
const passed = actualReason === expectedReason;
addCheck(context.checks, "expected-progression-blocked-reason", passed, expectedReason ?? "none");
Iif (!passed) {
addViolation(
context.violations,
"progression-blocked-reason-mismatch",
"state",
context.turnIndex,
actualReason ?? "none",
);
}
}
function expectedStateCheck(context: ExpectedCheckContext): void {
if (!context.scenario.expected?.stateUnchanged) return;
if (!context.stateBefore || !context.stateAfter) {
addNotApplicableCheck(context.checks, "expected-state-unchanged", "no-progression-state");
return;
}
const passed = canonicalJson(context.stateBefore) === canonicalJson(context.stateAfter);
addCheck(context.checks, "expected-state-unchanged", passed);
Iif (!passed) addViolation(context.violations, "state-changed-unexpectedly", "state", context.turnIndex);
}
function expectedQuestionCheck(context: ExpectedCheckContext): void {
if (context.scenario.expected?.questionNotRepeat !== "exact-or-heuristic" || context.turn.kind !== "dialog") return;
const previousQuestions = [context.turn.question, ...(context.turn.history ?? []).map(({ question }) => question)];
const passed = !isSemanticallyRepeatedQuestion(context.result.question, previousQuestions);
addCheck(context.checks, "final-question-not-repeated", passed);
Iif (!passed) addViolation(context.violations, "question-repeat", "final-tutor", context.turnIndex, "stage1-heuristic");
}
function expectedChecks(context: ExpectedCheckContext): void {
if (!context.scenario.expected) return;
expectedTopicCheck(context);
expectedTopicAbsentCheck(context);
expectedPhaseCheck(context);
expectedAnswerRatingCheck(context);
expectedPhaseAfterCheck(context);
expectedStateCheck(context);
expectedQuestionCheck(context);
}
function applicationMetadataChecks(
result: TutorContentResult,
courseContent: TutorPlanningContentContext | undefined,
stateAfter: TutorProgressionState | undefined,
checks: TutorQualityDeterministicCheck[],
violations: TutorQualityInvariantViolation[],
turnIndex: number,
): void {
if (!courseContent) return;
const revisionPassed = result.contentRevision === undefined || result.contentRevision === courseContent.revision;
addCheck(checks, "content-revision-consistent", revisionPassed);
Iif (!revisionPassed) addViolation(violations, "content-revision-mismatch", "final-tutor", turnIndex);
Iif (!stateAfter) return;
const phasePassed = result.learningPhase === undefined
|| stateAfter.phase === undefined
|| result.learningPhase === stateAfter.phase
|| (result.learningPhase === "LEARN" && stateAfter.phase === "DEEPEN")
|| (result.learningPhase === "DEEPEN" && stateAfter.phase === "EXPAND");
addCheck(checks, "phase-state-consistent", phasePassed);
Iif (!phasePassed) addViolation(violations, "state-phase-mismatch", "state", turnIndex);
const topicPassed = result.activeTopicId === undefined || result.activeTopicId === stateAfter.activeTopicId;
addCheck(checks, "active-topic-state-consistent", topicPassed);
Iif (!topicPassed) addViolation(violations, "state-topic-mismatch", "state", turnIndex);
}
function questionIdReuseCheck(
result: TutorContentResult,
turn: TutorQualityTurn,
courseContent: TutorPlanningContentContext | undefined,
checks: TutorQualityDeterministicCheck[],
violations: TutorQualityInvariantViolation[],
turnIndex: number,
): void {
if (!courseContent?.tutor || turn.kind !== "dialog" || !result.questionId) return;
const usedIds = new Set((turn.history ?? []).map(({ questionId }) => questionId).filter((id): id is string => id !== undefined));
Iif (result.questionId === undefined) return;
const passed = !usedIds.has(result.questionId);
addCheck(checks, "question-id-not-reused", passed);
Iif (!passed) addViolation(violations, "question-id-reused", "final-tutor", turnIndex, result.questionId);
}
function sampleTemplate(
options: TutorQualityEvaluationOptions,
scenario: TutorQualityEvaluationScenario,
runId: string,
evaluationIdentity: string,
sampleIndex: number,
): TutorQualityTranscript {
return {
schemaVersion: "tutor-quality-transcript-v1",
runId,
evaluationIdentity,
metadata: metadata(options, scenario, sampleIndex),
scenario: {
id: scenario.id,
corpusId: scenario.corpusId,
corpusVersion: scenario.corpusVersion,
sketchRef: scenario.sketchRef,
sketch: redact(scenario.sketch, options.credential),
syntheticTurns: scenario.turns.map((turn) => safeTurn(turn, options.credential)),
},
...(scenario.courseContent?.progressionState ? { stateBefore: clone(scenario.courseContent.progressionState) } : {}),
turns: [],
deterministicChecks: [],
executionStatus: "completed",
invariantViolations: [],
};
}
interface SampleTurnContext {
readonly options: TutorQualityEvaluationOptions;
readonly provider: CountingProvider;
readonly service: TutorService;
readonly scenario: TutorQualityEvaluationScenario;
readonly content: TutorPlanningContentContext | undefined;
readonly stateBefore: TutorProgressionState | undefined;
readonly finalQuestions: Map<number, string>;
readonly violations: TutorQualityInvariantViolation[];
readonly turn: TutorQualityTurn;
readonly turnIndex: number;
}
interface InvokedTutorTurn {
readonly finalResult?: TutorContentResult;
readonly followUpSource?: TutorFollowUpSource;
readonly error?: TutorQualityTechnicalError;
readonly invalidReason?: string;
}
interface ProcessedCapture {
readonly returnedModel?: string;
readonly invalidReason?: string;
}
interface SampleTurnOutcome {
readonly transcriptTurn?: TutorQualityTranscriptTurn;
readonly returnedModel?: string;
readonly executionStatus?: Extract<TutorQualityExecutionStatus, "invalid" | "technical-failure">;
readonly invalidReason?: string;
readonly terminalError?: TutorQualityTechnicalError;
readonly stop: boolean;
}
function invalidTurnContext(context: SampleTurnContext): string | undefined {
const { turn, turnIndex, finalQuestions, violations } = context;
if (turn.kind === "initial") return undefined;
if (turn.continuationOf !== undefined) {
const precedingQuestion = finalQuestions.get(turn.continuationOf);
if (precedingQuestion === undefined || precedingQuestion !== turn.question) {
addViolation(violations, "preceding-question-mismatch", "scenario", turnIndex);
return "preceding-question-mismatch";
}
}
return undefined;
}
async function invokeTutorTurn(context: SampleTurnContext): Promise<InvokedTutorTurn> {
const { options, service, scenario, content, turn } = context;
const invalidReason = invalidTurnContext(context);
if (invalidReason) return { invalidReason };
try {
if (turn.kind === "initial") {
const response = await service.generateQuestion(scenario.sketch, options.credential, options.requestedModel, turn.difficulty ?? 30, content);
return { finalResult: response.result, followUpSource: response.followUpSource };
}
const response = await service.generateDialogResponse(
scenario.sketch,
historyFromSource(turn.history),
turn.question,
turn.answer,
options.credential,
options.requestedModel,
turn.difficulty ?? 30,
content,
);
return { finalResult: response.result, followUpSource: response.followUpSource };
} catch (error_) {
return { error: technicalError(error_) };
}
}
function latestCapture(provider: CountingProvider, beforeGenerationCount: number): ProviderCapture | undefined {
return provider.generationCaptures.length > beforeGenerationCount
? provider.generationCaptures.at(-1)
: undefined;
}
function processCapture(
capture: ProviderCapture | undefined,
context: SampleTurnContext,
checks: TutorQualityDeterministicCheck[],
): ProcessedCapture {
if (!capture?.response) return {};
const returnedModel = capture.response.model;
if (typeof returnedModel === "string" && returnedModel.trim().length > 0) {
addCheck(checks, "returned-model-present", true);
deterministicRawChecks(capture.response.result, context.turn, context.turnIndex, checks, context.violations, context.scenario.expected);
return { returnedModel };
}
addCheck(checks, "returned-model-present", false, "missing");
deterministicRawChecks(capture.response.result, context.turn, context.turnIndex, checks, context.violations, context.scenario.expected);
return { invalidReason: "returned-model-missing" };
}
function processFinalResult(
context: SampleTurnContext,
invocation: InvokedTutorTurn,
checks: TutorQualityDeterministicCheck[],
): void {
const { finalResult, error } = invocation;
if (!finalResult) {
Eif (error) addCheck(checks, "final-tutor-response-present", false, error.kind);
return;
}
context.finalQuestions.set(context.turnIndex, finalResult.question);
addCheck(checks, "final-tutor-response-present", true);
expectedChecks({
scenario: context.scenario,
result: finalResult,
turn: context.turn,
stateBefore: context.stateBefore,
stateAfter: context.content?.progressionState,
checks,
violations: context.violations,
turnIndex: context.turnIndex,
});
unexpectedBlockedStateCheck({
scenario: context.scenario,
result: finalResult,
turn: context.turn,
stateBefore: context.stateBefore,
stateAfter: context.content?.progressionState,
checks,
violations: context.violations,
turnIndex: context.turnIndex,
});
applicationMetadataChecks(finalResult, context.content, context.content?.progressionState, checks, context.violations, context.turnIndex);
questionIdReuseCheck(finalResult, context.turn, context.content, checks, context.violations, context.turnIndex);
}
function buildTranscriptTurn(
context: SampleTurnContext,
startedAt: Date,
callsBefore: TutorQualityStageAProviderCallCounts,
finishedAt: Date,
capture: ProviderCapture | undefined,
invocation: InvokedTutorTurn,
checks: readonly TutorQualityDeterministicCheck[],
): TutorQualityTranscriptTurn {
const { options, provider, turn, turnIndex } = context;
return {
index: turnIndex,
input: safeTurn(turn, options.credential),
startedAt: startedAt.toISOString(),
durationMs: Math.max(0, finishedAt.getTime() - startedAt.getTime()),
providerCalls: subtractStageACounts(provider.stageACounts, callsBefore),
...(capture?.request ? { providerRequest: requestArtifact(capture.request, options.credential) } : {}),
...(capture?.response ? {
rawProviderResult: safeResult(capture.response.result, options.credential),
...(typeof capture.response.model === "string" ? { returnedModel: redact(capture.response.model, options.credential) } : {}),
} : {}),
...(invocation.finalResult ? { finalTutorResult: safeResult(invocation.finalResult, options.credential) } : {}),
...(invocation.finalResult && invocation.followUpSource ? { followUpSource: invocation.followUpSource } : {}),
deterministicChecks: checks,
...(invocation.error ? { technicalError: invocation.error } : {}),
};
}
async function executeSampleTurn(context: SampleTurnContext): Promise<SampleTurnOutcome> {
const startedAt = (context.options.now ?? (() => new Date()))();
const callsBefore = context.provider.stageACounts;
const checks: TutorQualityDeterministicCheck[] = [];
const beforeGenerationCount = context.provider.generationCaptures.length;
const invocation = await invokeTutorTurn(context);
if (invocation.invalidReason) return { invalidReason: invocation.invalidReason, executionStatus: "invalid", stop: true };
const capture = latestCapture(context.provider, beforeGenerationCount);
const captureResult = processCapture(capture, context, checks);
processFinalResult(context, invocation, checks);
const finishedAt = (context.options.now ?? (() => new Date()))();
return {
transcriptTurn: buildTranscriptTurn(context, startedAt, callsBefore, finishedAt, capture, invocation, checks),
returnedModel: captureResult.returnedModel,
...(invocation.error ? { executionStatus: "technical-failure" as const, terminalError: invocation.error } : {}),
...(captureResult.invalidReason ? { executionStatus: "invalid" as const, invalidReason: captureResult.invalidReason } : {}),
stop: invocation.error !== undefined,
};
}
interface SampleExecutionState {
readonly violations: TutorQualityInvariantViolation[];
readonly turns: TutorQualityTranscriptTurn[];
readonly returnedModels: string[];
readonly finalQuestions: Map<number, string>;
executionStatus: TutorQualityExecutionStatus;
invalidReason: string | undefined;
terminalError: TutorQualityTechnicalError | undefined;
}
function applySampleTurnOutcome(state: SampleExecutionState, outcome: SampleTurnOutcome): void {
if (outcome.executionStatus === "technical-failure") state.executionStatus = "technical-failure";
if (outcome.executionStatus === "invalid") state.executionStatus = "invalid";
if (outcome.invalidReason) state.invalidReason = state.invalidReason ?? outcome.invalidReason;
if (outcome.terminalError) state.terminalError = outcome.terminalError;
if (outcome.returnedModel) state.returnedModels.push(outcome.returnedModel);
if (outcome.transcriptTurn) state.turns.push(outcome.transcriptTurn);
}
interface SampleTurnsContext {
readonly options: TutorQualityEvaluationOptions;
readonly provider: CountingProvider;
readonly service: TutorService;
readonly scenario: TutorQualityEvaluationScenario;
readonly content: TutorPlanningContentContext | undefined;
readonly stateBefore: TutorProgressionState | undefined;
readonly execution: SampleExecutionState;
}
async function executeSampleTurns(context: SampleTurnsContext): Promise<void> {
const { options, provider, service, scenario, content, stateBefore, execution } = context;
for (const [turnIndex, turn] of scenario.turns.entries()) {
const outcome = await executeSampleTurn({
options,
provider,
service,
scenario,
content,
stateBefore,
finalQuestions: execution.finalQuestions,
violations: execution.violations,
turn,
turnIndex,
});
applySampleTurnOutcome(execution, outcome);
if (outcome.stop) break;
}
}
function recordFailureStateCheck(
terminalError: TutorQualityTechnicalError | undefined,
stateBefore: TutorProgressionState | undefined,
stateAfter: TutorProgressionState | undefined,
turns: TutorQualityTranscriptTurn[],
violations: TutorQualityInvariantViolation[],
): void {
if (!terminalError || !stateBefore || !stateAfter) return;
const unchanged = canonicalJson(stateBefore) === canonicalJson(stateAfter);
const stateChecks = turns.at(-1)?.deterministicChecks;
if (stateChecks) {
addCheck(stateChecks as TutorQualityDeterministicCheck[], "state-unchanged-after-failure", unchanged);
}
if (!unchanged) addViolation(violations, "state-mutated-after-failure", "state", undefined);
}
async function runSample(
options: TutorQualityEvaluationOptions,
provider: CountingProvider,
scenario: TutorQualityEvaluationScenario,
runId: string,
evaluationIdentity: string,
sampleIndex: number,
): Promise<TutorQualityTranscript> {
const sampleStartedAt = (options.now ?? (() => new Date()))();
const callsBeforeSample = provider.stageACounts;
const content = scenario.courseContent ? clone(scenario.courseContent) : undefined;
const stateBefore = content?.progressionState ? clone(content.progressionState) : undefined;
const service = new TutorService(provider, content ? new CurriculumTutorAdapter() : undefined);
const execution: SampleExecutionState = {
violations: [],
turns: [],
returnedModels: [],
finalQuestions: new Map<number, string>(),
executionStatus: "completed",
invalidReason: undefined,
terminalError: undefined,
};
await executeSampleTurns({ options, provider, service, scenario, content, stateBefore, execution });
const stateAfter = content?.progressionState ? clone(content.progressionState) : undefined;
recordFailureStateCheck(execution.terminalError, stateBefore, stateAfter, execution.turns, execution.violations);
const sample = sampleTemplate(options, scenario, runId, evaluationIdentity, sampleIndex);
const sampleFinishedAt = (options.now ?? (() => new Date()))();
const sampleCalls = subtractStageACounts(provider.stageACounts, callsBeforeSample);
return {
...sample,
metadata: metadata(
options,
scenario,
sampleIndex,
execution.returnedModels,
sampleStartedAt.toISOString(),
Math.max(0, sampleFinishedAt.getTime() - sampleStartedAt.getTime()),
sampleCalls,
),
...(stateBefore ? { stateBefore } : {}),
...(stateAfter ? { stateAfter } : {}),
turns: execution.turns,
deterministicChecks: execution.turns.flatMap(({ deterministicChecks }) => deterministicChecks),
executionStatus: execution.executionStatus,
...(execution.invalidReason ? { invalidReason: execution.invalidReason } : {}),
...(execution.terminalError ? { technicalError: execution.terminalError } : {}),
invariantViolations: execution.violations,
};
}
function emptyAggregate(samples: number): TutorQualityScenarioAggregate {
return {
samplesRequested: samples,
samplesObserved: 0,
completed: 0,
invalid: 0,
technicalFailures: 0,
notRun: 0,
invariantViolationSamples: 0,
budgetExhausted: 0,
providerCalls: { ...EMPTY_PROVIDER_CALLS },
technicalErrorKinds: {},
rates: ratesFor(0, 0, 0, 0, 0, 0),
};
}
function ratio(numerator: number, denominator: number): number | null {
return denominator === 0 ? null : numerator / denominator;
}
function ratesFor(
completed: number,
invalid: number,
technicalFailures: number,
notRun: number,
invariantViolations: number,
observed: number,
): TutorQualityRates {
return {
completedOfObserved: ratio(completed, observed),
invalidOfObserved: ratio(invalid, observed),
technicalFailureOfObserved: ratio(technicalFailures, observed),
notRunOfObserved: ratio(notRun, observed),
invariantViolationOfObserved: ratio(invariantViolations, observed),
};
}
function addCounts(left: TutorQualityProviderCallCounts, right: TutorQualityProviderCallCounts): TutorQualityProviderCallCounts {
return {
total: left.total + right.total,
modelListCalls: left.modelListCalls + right.modelListCalls,
generationCalls: left.generationCalls + right.generationCalls,
judgeCalls: left.judgeCalls + right.judgeCalls,
};
}
function subtractCounts(
current: TutorQualityProviderCallCounts,
previous: TutorQualityProviderCallCounts,
): TutorQualityProviderCallCounts {
return {
total: current.total - previous.total,
modelListCalls: current.modelListCalls - previous.modelListCalls,
generationCalls: current.generationCalls - previous.generationCalls,
judgeCalls: current.judgeCalls - previous.judgeCalls,
};
}
function subtractStageACounts(
current: TutorQualityStageAProviderCallCounts,
previous: TutorQualityStageAProviderCallCounts,
): TutorQualityStageAProviderCallCounts {
return {
total: current.total - previous.total,
modelListCalls: current.modelListCalls - previous.modelListCalls,
generationCalls: current.generationCalls - previous.generationCalls,
};
}
function addTranscriptToAggregate(
aggregate: TutorQualityScenarioAggregate,
transcript: TutorQualityTranscript,
calls: TutorQualityProviderCallCounts,
): TutorQualityScenarioAggregate {
const samplesObserved = aggregate.samplesObserved + 1;
const completed = aggregate.completed + Number(transcript.executionStatus === "completed");
const invalid = aggregate.invalid + Number(transcript.executionStatus === "invalid");
const technicalFailures = aggregate.technicalFailures + Number(transcript.executionStatus === "technical-failure");
const notRun = aggregate.notRun + Number(transcript.executionStatus === "not-run");
const invariantViolationSamples = aggregate.invariantViolationSamples + Number(transcript.invariantViolations.length > 0);
const budgetExhausted = aggregate.budgetExhausted + Number(transcript.technicalError?.kind === "call-budget-exhausted");
const technicalErrorKinds = transcript.technicalError
? { ...aggregate.technicalErrorKinds, [transcript.technicalError.kind]: (aggregate.technicalErrorKinds[transcript.technicalError.kind] ?? 0) + 1 }
: aggregate.technicalErrorKinds;
return {
...aggregate,
samplesObserved,
completed,
invalid,
technicalFailures,
notRun,
invariantViolationSamples,
budgetExhausted,
providerCalls: addCounts(aggregate.providerCalls, calls),
technicalErrorKinds,
rates: ratesFor(completed, invalid, technicalFailures, notRun, invariantViolationSamples, samplesObserved),
};
}
interface BaseReportContext {
readonly options: TutorQualityEvaluationOptions;
readonly runId: string;
readonly evaluationIdentity: string;
readonly runStatus: TutorQualityExecutionStatus;
readonly reason?: string;
readonly calls: TutorQualityProviderCallCounts;
readonly byScenario: Readonly<Record<string, TutorQualityScenarioAggregate>>;
readonly samplesObserved?: number;
readonly startedAt: Date;
}
function baseReport(context: BaseReportContext): TutorQualityReportWithoutVerdict {
const { options, runId, evaluationIdentity, runStatus, reason, calls, byScenario, samplesObserved = 0, startedAt } = context;
const aggregates = Object.values(byScenario);
const completed = aggregates.reduce((sum, item) => sum + item.completed, 0);
const invalid = aggregates.reduce((sum, item) => sum + item.invalid, 0);
const technicalFailures = aggregates.reduce((sum, item) => sum + item.technicalFailures, 0);
const notRun = aggregates.reduce((sum, item) => sum + item.notRun, 0);
const invariantViolationSamples = aggregates.reduce((sum, item) => sum + item.invariantViolationSamples, 0);
const budgetExhausted = aggregates.reduce((sum, item) => sum + item.budgetExhausted, 0);
const sampleTechnicalErrorKinds = Object.fromEntries(
aggregates.flatMap((item) => Object.entries(item.technicalErrorKinds)).reduce((entries, [kind, count]) => {
const current = entries.get(kind) ?? 0;
entries.set(kind, current + count);
return entries;
}, new Map<string, number>()),
);
const preflightTechnicalFailure = runStatus === "technical-failure" ? 1 : 0;
const technicalErrorKinds = reason && preflightTechnicalFailure > 0
? { ...sampleTechnicalErrorKinds, [reason]: (sampleTechnicalErrorKinds[reason] ?? 0) + 1 }
: sampleTechnicalErrorKinds;
return {
schemaVersion: "tutor-quality-report-v1",
runId,
evaluationIdentity,
runStatus,
...(reason ? { reason } : {}),
providerId: options.providerId,
requestedModel: options.requestedModel,
credentialPresent: Boolean(options.credential),
samplesRequested: options.scenarios.length * options.samples,
samplesObserved,
completed,
invalid,
technicalFailures: technicalFailures + preflightTechnicalFailure,
notRun,
invariantViolationSamples,
budgetExhausted,
providerCalls: calls,
technicalErrorKinds,
byScenario,
rates: ratesFor(completed, invalid, technicalFailures + preflightTechnicalFailure, notRun, invariantViolationSamples, samplesObserved),
monetaryCost: "unavailable",
totalDurationMs: Math.max(0, (options.now ?? (() => new Date()))().getTime() - startedAt.getTime()),
};
}
function verdictSample(transcript: TutorQualityTranscript): TutorQualityVerdictSample {
return {
scenarioId: transcript.scenario.id,
sampleIndex: transcript.metadata.sampleIndex,
executionStatus: transcript.executionStatus,
...(transcript.invalidReason ? { invalidReason: transcript.invalidReason } : {}),
...(transcript.technicalError ? { technicalErrorKind: transcript.technicalError.kind } : {}),
violations: transcript.invariantViolations,
};
}
function withQualityVerdict(
options: TutorQualityEvaluationOptions,
report: TutorQualityReportWithoutVerdict,
transcripts: readonly TutorQualityTranscript[],
): TutorQualityEvaluationReport {
return {
...report,
qualityVerdict: computeTutorQualityVerdict({
runStatus: report.runStatus,
...(report.reason ? { runReason: report.reason } : {}),
samplesPerCase: options.samples,
judgeConfigured: Boolean(options.judgeModel),
samples: transcripts.map(verdictSample),
semanticEvaluations: report.semanticEvaluations ?? [],
}),
};
}
async function writeArtifacts(
options: TutorQualityEvaluationOptions,
report: TutorQualityEvaluationReport,
transcripts: readonly TutorQualityTranscript[],
): Promise<void> {
if (options.artifactWriter) {
await options.artifactWriter(report, transcripts);
return;
}
const manifest = createTutorQualityRunManifest(options, transcripts, report.semanticEvaluations ?? []);
await writeRunArtifacts(options.outputDir, report, manifest, transcripts);
}
function invalidBasicPreflightReason(options: TutorQualityEvaluationOptions): string | undefined {
Iif (!options.requestedModel || options.requestedModel === "auto") return "fixed-model-required";
Iif (options.judgeModel === "auto" || (options.judgeModel !== undefined && !options.judgeModel)) return "fixed-judge-model-required";
Iif (!options.git.sha) return "git-sha-missing";
if (!options.git.trackedClean || !options.git.relevantUntrackedClean) return "dirty-relevant-worktree";
Iif (!Number.isInteger(options.samples) || options.samples < 1) return "invalid-sample-count";
if (options.samples > MAX_TUTOR_QUALITY_SAMPLES) return "sample-count-exceeds-limit";
Iif (!Number.isInteger(options.maxCalls) || options.maxCalls < 0) return "invalid-call-budget";
if (options.maxCalls > MAX_TUTOR_QUALITY_CALLS) return "call-budget-exceeds-limit";
return undefined;
}
function invalidCorpusPreflightReason(options: TutorQualityEvaluationOptions): string | undefined {
Iif (options.scenarios.length === 0) return "empty-corpus";
const first = options.scenarios[0];
Iif (options.scenarios.some((scenario) => scenario.corpusId !== first?.corpusId || scenario.corpusVersion !== first?.corpusVersion)) {
return "mixed-corpus-versions";
}
return undefined;
}
function invalidPreflightReason(options: TutorQualityEvaluationOptions): string | undefined {
return invalidBasicPreflightReason(options) ?? invalidCorpusPreflightReason(options);
}
export async function runTutorQualityEvaluation(options: TutorQualityEvaluationOptions): Promise<TutorQualityEvaluationResult> {
const startedAt = (options.now ?? (() => new Date()))();
const runId = makeRunId(options);
const evaluationIdentity = makeEvaluationIdentity(options);
const emptyByScenario = Object.fromEntries(options.scenarios.map((scenario) => [scenario.id, emptyAggregate(options.samples)]));
const earlyResult = await createEarlyResult(options, runId, evaluationIdentity, emptyByScenario, startedAt);
if (earlyResult) return earlyResult;
Iif (!options.credential) throw new Error("Tutor credential preflight did not reject missing credentials");
const provider = new CountingProvider(options.provider, options.maxCalls);
let availableModels: readonly string[];
try {
availableModels = await provider.listModels(options.credential);
} catch (error) {
const report = withQualityVerdict(options, baseReport({ startedAt, options, runId, evaluationIdentity, runStatus: "technical-failure", reason: technicalError(error).kind, calls: provider.counts, byScenario: emptyByScenario }), []);
await writeArtifacts(options, report, []);
return { report, transcripts: [], semanticEvaluations: [] };
}
if (!availableModels.includes(options.requestedModel)) {
const report = withQualityVerdict(options, baseReport({ startedAt, options, runId, evaluationIdentity, runStatus: "invalid", reason: "model-unavailable", calls: provider.counts, byScenario: emptyByScenario }), []);
await writeArtifacts(options, report, []);
return { report, transcripts: [], semanticEvaluations: [] };
}
if (options.judgeModel && !availableModels.includes(options.judgeModel)) {
const report = withQualityVerdict(options, baseReport({ startedAt, options, runId, evaluationIdentity, runStatus: "invalid", reason: "judge-model-unavailable", calls: provider.counts, byScenario: emptyByScenario }), []);
await writeArtifacts(options, report, []);
return { report, transcripts: [], semanticEvaluations: [] };
}
const { transcripts, semanticEvaluations, byScenario } = await evaluateSamples(options, provider, runId, evaluationIdentity);
const report = withQualityVerdict(options, {
...baseReport({ startedAt, options, runId, evaluationIdentity, runStatus: "completed", calls: provider.counts, byScenario, samplesObserved: transcripts.length }),
...(semanticEvaluations.length ? { semanticEvaluations } : {}),
}, transcripts);
await writeArtifacts(options, report, transcripts);
return { report, transcripts, semanticEvaluations };
}
async function createEarlyResult(
options: TutorQualityEvaluationOptions,
runId: string,
evaluationIdentity: string,
byScenario: Record<string, TutorQualityScenarioAggregate>,
startedAt: Date,
): Promise<TutorQualityEvaluationResult | undefined> {
let status: TutorQualityEvaluationReport["runStatus"] | undefined;
let reason: string | undefined;
let calls: TutorQualityProviderCallCounts = EMPTY_PROVIDER_CALLS;
const invalidReason = invalidPreflightReason(options);
if (invalidReason) {
status = "invalid";
reason = invalidReason;
calls = EMPTY_PROVIDER_CALLS;
} else if (!options.credential) {
status = "not-run";
reason = "missing-credential";
calls = EMPTY_PROVIDER_CALLS;
} else if (options.judgeModel && !options.judgeCredential) {
// R-PYR-2: without the Judge credential the run would spend Tutor calls and end inconclusive.
status = "not-run";
reason = "missing-judge-credential";
calls = EMPTY_PROVIDER_CALLS;
} else Iif (options.maxCalls === 0) {
status = "not-run";
reason = "call-budget-zero";
calls = EMPTY_PROVIDER_CALLS;
}
if (!status || !reason) return undefined;
const report = withQualityVerdict(options, baseReport({ startedAt, options, runId, evaluationIdentity, runStatus: status, reason, calls, byScenario }), []);
await writeArtifacts(options, report, []);
return { report, transcripts: [], semanticEvaluations: [] };
}
async function evaluateSamples(
options: TutorQualityEvaluationOptions,
provider: CountingProvider,
runId: string,
evaluationIdentity: string,
): Promise<{
readonly transcripts: TutorQualityTranscript[];
readonly semanticEvaluations: TutorQualitySemanticEvaluationRecord[];
readonly byScenario: Record<string, TutorQualityScenarioAggregate>;
}> {
const transcripts: TutorQualityTranscript[] = [];
const semanticEvaluations: TutorQualitySemanticEvaluationRecord[] = [];
const byScenario: Record<string, TutorQualityScenarioAggregate> = Object.fromEntries(
options.scenarios.map((scenario) => [scenario.id, emptyAggregate(options.samples)]),
);
for (const scenario of options.scenarios) {
for (let sampleIndex = 0; sampleIndex < options.samples; sampleIndex += 1) {
const callsBeforeSample = provider.counts;
const transcript = await runSample(options, provider, scenario, runId, evaluationIdentity, sampleIndex);
transcripts.push(transcript);
if (scenario.judge && options.judgeModel) {
const evaluation = redactSemanticEvaluation(
await evaluateSemanticSample(provider, options, scenario, transcript),
[options.credential, options.judgeCredential],
);
const phase = transcript.turns.at(-1)?.finalTutorResult?.learningPhase;
semanticEvaluations.push({
scenarioId: scenario.id,
sampleIndex,
...(typeof phase === "string" ? { learningPhase: phase } : {}),
evaluation,
});
}
const aggregate = byScenario[scenario.id];
Iif (!aggregate) throw new Error(`Missing scenario aggregate for ${scenario.id}`);
byScenario[scenario.id] = addTranscriptToAggregate(aggregate, transcript, subtractCounts(provider.counts, callsBeforeSample));
}
}
return { transcripts, semanticEvaluations, byScenario };
}
function redactSemanticEvaluation(
evaluation: TutorQualitySemanticEvaluation,
credentials: readonly (string | undefined)[],
): TutorQualitySemanticEvaluation {
const redactValue = (value: string): string => credentials.reduce<string>((safe, credential) => redact(safe, credential), value);
return {
...evaluation,
...(evaluation.reason ? { reason: redactValue(evaluation.reason) } : {}),
...(evaluation.model ? { model: redactValue(evaluation.model) } : {}),
...(evaluation.criteria ? {
criteria: evaluation.criteria.map((criterion) => ({
...criterion,
reason: redactValue(criterion.reason),
...(criterion.quote ? { quote: redactValue(criterion.quote) } : {}),
})),
} : {}),
...(evaluation.criticalIssues ? {
criticalIssues: evaluation.criticalIssues.map((issue) => ({
...issue,
reason: redactValue(issue.reason),
quote: redactValue(issue.quote),
})),
} : {}),
};
}
async function evaluateSemanticSample(
provider: CountingProvider,
options: TutorQualityEvaluationOptions,
scenario: TutorQualityEvaluationScenario,
transcript: TutorQualityTranscript,
): Promise<TutorQualitySemanticEvaluation> {
if (transcript.executionStatus !== "completed") return { status: "not-evaluated", reason: "tutor-turn-not-completed" };
Iif (!options.judgeCredential) return { status: "judge-error", reason: "missing-credential" };
const input = buildJudgeInput(scenario, transcript);
Iif (!input) return { status: "not-evaluated", reason: "judge-evidence-unavailable" };
const startedAt = Date.now();
try {
return await evaluateJudgeResponse(provider, options, input, startedAt);
} catch (error) {
return classifyJudgeError(error, startedAt);
}
}
function judgePromptMetadata(prompt: TutorQualityJudgePrompt, durationMs: number) {
return {
durationMs,
promptRevision: prompt.revision,
promptDigest: prompt.digest,
systemPromptDigest: prompt.systemDigest,
userPromptDigest: prompt.userDigest,
};
}
async function evaluateJudgeResponse(
provider: CountingProvider,
options: TutorQualityEvaluationOptions,
input: NonNullable<ReturnType<typeof buildJudgeInput>>,
startedAt: number,
): Promise<TutorQualitySemanticEvaluation> {
const { result, prompt } = await callJudge(provider, options.judgeModel!, options.judgeCredential!, input);
const metadata = judgePromptMetadata(prompt, Date.now() - startedAt);
if (typeof result.model !== "string" || result.model.trim().length === 0) {
return {
status: "judge-invalid",
reason: "returned-model-missing",
model: result.model,
...metadata,
};
}
return { ...parseJudgeResult(result.result, input), model: result.model, ...metadata };
}
function classifyJudgeError(error: unknown, startedAt: number): TutorQualitySemanticEvaluation {
const providerError = error instanceof JudgeProviderCallError ? error.providerError : error;
const prompt = error instanceof JudgeProviderCallError ? error.prompt : undefined;
const metadata = prompt ? judgePromptMetadata(prompt, Date.now() - startedAt) : {};
if (providerError instanceof EvaluationBudgetExceeded) return { status: "budget-exhausted", reason: "call-budget-exhausted" };
if (providerError instanceof TutorProviderError && providerError.kind === "invalid-response") {
return { status: "judge-invalid", reason: "provider-invalid-response", ...metadata };
}
Eif (providerError instanceof TutorProviderError) return { status: "judge-error", reason: providerError.kind, ...metadata };
return { status: "judge-error", reason: "provider-error", ...metadata };
}
export { EvaluationBudgetExceeded };
|