All files / scripts tutor-quality-real-provider-eval.ts

85.8% Statements 133/155
75.17% Branches 109/145
88% Functions 22/25
93.02% Lines 120/129

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                                                                                                1x   1x 1x 1x     40x 40x 211x 211x 211x 211x 211x 211x         58x 58x 58x 57x 55x       36x 35x         40x 40x   40x 40x   40x 40x 40x 40x 211x   40x 40x   30x 30x   28x 28x   40x 40x         32x 32x   30x 30x   5x 5x   4x 4x 4x   2x     34x 33x 33x 33x 32x 32x 32x 31x                         1x         2x 2x 2x 2x         2x 2x                                     810x 450x 450x               30x 30x 570x                   30x 30x 30x 30x 30x 30x 570x 570x 570x         30x 30x 30x 570x 570x                                     1x 1x       3x 3x 3x 2x               1x 1x 1x 1x 1x       1x             29x 29x 29x 29x 28x 282x 28x 513x 29x 29x 29x 29x 29x                                   13x   2x     7x     4x               8x 8x 8x 8x 7x             7x   1x 1x       1x     1x      
import { execFileSync } from "node:child_process";
import { access, readFile } from "node:fs/promises";
import { accessSync, constants as fsConstants } from "node:fs";
import path from "node:path";
import { pathToFileURL } from "node:url";
import { parse as parseYaml } from "yaml";
import { sha256 } from "../server/services/tutor/evaluation/canonical";
import { createAnchorCourseContent, ANCHOR_COURSE_CONTENT_FIXTURE_IDS, type AnchorCourseContentFixtureId } from "../server/services/tutor/evaluation/anchor-course-content";
import { config } from "../server/config";
import {
  parseTutorQualityCorpus,
  type TutorQualityHistoryEntrySource,
  type TutorQualityTurnSource,
} from "../server/services/tutor/evaluation/anchor-corpus";
import {
  MAX_TUTOR_QUALITY_CALLS,
  MAX_TUTOR_QUALITY_SAMPLES,
  runTutorQualityEvaluation,
  type TutorQualityEvaluationReport,
  type TutorQualityEvaluationScenario,
  type TutorQualityGitState,
  type TutorQualityTurn,
} from "../server/services/tutor/evaluation/real-provider-evaluation";
import { KiconnectProvider } from "../server/services/tutor/kiconnect-provider";
import type { LLMProvider } from "../server/services/tutor/llm-provider";
 
export interface TutorQualityCliOptions {
  readonly model: string;
  readonly samples: number;
  readonly maxCalls: number;
  readonly outputDir: string;
  readonly corpusPath: string;
  readonly credentialEnv: string;
  readonly judgeModel?: string;
  readonly judgeCredentialEnv: string;
  readonly cases: readonly string[];
}
 
export interface TutorQualityCliDependencies {
  readonly cwd?: string;
  readonly environment?: NodeJS.ProcessEnv;
  readonly provider?: LLMProvider;
  readonly git?: TutorQualityGitState;
  readonly log?: (line: string) => void;
  readonly error?: (line: string) => void;
}
 
/** Evaluation SSOT R-VER-8. */
export const TUTOR_QUALITY_EXIT_CODES = { success: 0, cliError: 1, qualityFail: 2, inconclusive: 3 } as const;
 
const DEFAULT_CORPUS_PATH = "evals/tutor-quality/anchor-corpus.yaml";
const DEFAULT_CREDENTIAL_ENV = "UNOSIM_TUTOR_EVAL_CREDENTIAL";
const DEFAULT_JUDGE_CREDENTIAL_ENV = "UNOSIM_TUTOR_JUDGE_CREDENTIAL";
 
function argumentPairs(argv: readonly string[]): readonly (readonly [string, string])[] {
  Iif (argv.length % 2 !== 0) throw new Error("Tutor Quality evaluation options require values");
  return Array.from({ length: argv.length / 2 }, (_, pairIndex) => {
    const index = pairIndex * 2;
    const flag = argv[index];
    const value = argv[index + 1];
    Iif (!flag?.startsWith("--")) throw new Error(`Unknown Tutor Quality evaluation option: ${flag ?? ""}`);
    Iif (!value || value.startsWith("--")) throw new Error(`${flag} requires a value`);
    return [flag, value] as const;
  });
}
 
function parsePositiveInteger(value: string, flag: string, allowZero = false, maximum?: number): number {
  Iif (!/^\d+$/.test(value)) throw new Error(`${flag} must be an integer`);
  const parsed = Number(value);
  if (!Number.isSafeInteger(parsed) || (allowZero ? parsed < 0 : parsed < 1)) throw new Error(`${flag} is out of range`);
  if (maximum !== undefined && parsed > maximum) throw new Error(`${flag} exceeds maximum ${maximum}`);
  return parsed;
}
 
function parseCredentialEnvironmentName(value: string): string {
  if (!/^[A-Z][A-Z0-9_]{1,63}$/.test(value)) throw new Error("--credential-env must be an environment-variable name");
  return value;
}
 
export function parseTutorQualityCliArgs(argv: readonly string[]): TutorQualityCliOptions {
  let model: string | undefined;
  let samples = 1;
  let maxCalls = 20;
  let outputDir: string | undefined;
  let corpusPath = DEFAULT_CORPUS_PATH;
  let credentialEnv = DEFAULT_CREDENTIAL_ENV;
  let judgeModel: string | undefined;
  let judgeCredentialEnv = DEFAULT_JUDGE_CREDENTIAL_ENV;
  let judgeCredentialEnvWasSet = false;
  const cases: string[] = [];
  for (const [flag, value] of argumentPairs(argv)) {
    switch (flag) {
      case "--model":
        model = value;
        break;
      case "--samples":
        samples = parsePositiveInteger(value, flag, false, MAX_TUTOR_QUALITY_SAMPLES);
        break;
      case "--max-calls":
        maxCalls = parsePositiveInteger(value, flag, true, MAX_TUTOR_QUALITY_CALLS);
        break;
      case "--output-dir":
        outputDir = value;
        break;
      case "--corpus":
        corpusPath = value;
        break;
      case "--credential-env":
        credentialEnv = parseCredentialEnvironmentName(value);
        break;
      case "--case":
        cases.push(value);
        break;
      case "--judge-model":
        judgeModel = value;
        break;
      case "--judge-credential-env":
        judgeCredentialEnv = parseCredentialEnvironmentName(value);
        judgeCredentialEnvWasSet = true;
        break;
      default:
        throw new Error(`Unknown Tutor Quality evaluation option: ${flag}`);
    }
  }
  if (!model || model === "auto") throw new Error("--model requires a fixed model id; auto is not allowed");
  Iif (!outputDir) throw new Error("--output-dir is required");
  Iif (!/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/.test(model)) throw new Error("--model is invalid");
  if (judgeModel === "auto") throw new Error("--judge-model requires a fixed model id; auto is not allowed");
  Iif (judgeModel !== undefined && !/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/.test(judgeModel)) throw new Error("--judge-model is invalid");
  Iif (judgeCredentialEnvWasSet && !judgeModel) throw new Error("--judge-credential-env requires --judge-model");
  if (judgeModel && judgeCredentialEnv === credentialEnv) throw new Error("Tutor and Judge must use separate credential environment-variable names");
  return {
    model,
    samples,
    maxCalls,
    outputDir,
    corpusPath,
    credentialEnv,
    ...(judgeModel ? { judgeModel } : {}),
    judgeCredentialEnv,
    cases,
  };
}
 
const GIT_EXECUTABLE_CANDIDATES = process.platform === "win32"
  ? [String.raw`C:\Program Files\Git\cmd\git.exe`, String.raw`C:\Program Files\Git\bin\git.exe`]
  : ["/usr/bin/git", "/opt/homebrew/bin/git", "/usr/local/bin/git"];
 
function resolveGitExecutable(): string {
  const executable = GIT_EXECUTABLE_CANDIDATES.find((candidate) => {
    try {
      accessSync(candidate, fsConstants.X_OK);
      return true;
    } catch {
      return false;
    }
  });
  Iif (!executable) throw new Error("git executable not found in fixed system locations");
  return executable;
}
 
function historyEntry(entry: TutorQualityHistoryEntrySource): import("../shared/tutor").TutorDialogTurn {
  const common = {
    question: entry.question,
    answer: entry.answer ?? "synthetic scripted history",
    ...(entry.questionId === undefined ? {} : { questionId: entry.questionId }),
  };
  // The corpus parser rejects ratings on philosophical turns, matching the shared dialog schema.
  if (entry.responseStyle === "philosophical") return { ...common, responseStyle: "philosophical" };
  return {
    ...common,
    responseStyle: "normal",
    ...(entry.answerRating === undefined ? {} : { answerRating: entry.answerRating }),
  };
}
 
function materializeTurn(turn: TutorQualityTurnSource): TutorQualityTurn {
  if (turn.kind === "initial") return turn;
  const { history, ...dialogTurn } = turn;
  return {
    ...dialogTurn,
    ...(history === undefined ? {} : { history: history.map(historyEntry) }),
  };
}
 
function declaredSketchReferences(source: unknown): string[] {
  // Collect references from the unvalidated YAML only; parseTutorQualityCorpus reports malformed input.
  Iif (typeof source !== "object" || source === null || !("scenarios" in source) || !Array.isArray(source.scenarios)) return [];
  return source.scenarios.flatMap((scenario: unknown) => (
    typeof scenario === "object" && scenario !== null && "sketch" in scenario && typeof scenario.sketch === "string"
      ? [scenario.sketch]
      : []
  ));
}
 
export async function loadTutorQualityEvaluationScenarios(
  cwd: string,
  corpusPath: string,
): Promise<readonly TutorQualityEvaluationScenario[]> {
  const manifestPath = path.resolve(cwd, corpusPath);
  const sourceText = await readFile(manifestPath, "utf8");
  const corpusFileDigest = sha256(sourceText);
  const source: unknown = parseYaml(sourceText);
  const sketchRefs = new Set<string>();
  for (const sketch of declaredSketchReferences(source)) {
    try {
      await access(path.resolve(cwd, sketch));
      sketchRefs.add(sketch);
    } catch {
      // Keep the reference absent so the corpus validator reports the contract error.
    }
  }
  const courseContentFixtures = new Set<string>(ANCHOR_COURSE_CONTENT_FIXTURE_IDS);
  const corpus = parseTutorQualityCorpus(source, { sketches: sketchRefs, courseContentFixtures });
  return Promise.all(corpus.scenarios.map(async (scenario) => {
    const sketch = await readFile(path.resolve(cwd, scenario.sketch), "utf8");
    return {
      id: scenario.id,
      corpusId: corpus.corpusId,
      corpusVersion: corpus.corpusVersion,
      corpusFileDigest,
      sketchRef: scenario.sketch,
      sketch,
      sketchDigest: sha256(sketch),
      ...(scenario.courseContent === "free"
        ? {}
        : { courseContent: createAnchorCourseContent(scenario.courseContent as AnchorCourseContentFixtureId) }),
      turns: scenario.turns.map(materializeTurn),
      ...(scenario.judge === undefined ? {} : { judge: scenario.judge }),
      ...(scenario.expected === undefined ? {} : { expected: scenario.expected }),
    };
  }));
}
 
function statusLines(cwd: string): readonly string[] {
  const output = execFileSync(resolveGitExecutable(), ["status", "--porcelain=v1", "-uall"], { cwd, encoding: "utf8" });
  return output.split("\n").map((line) => line.trimEnd()).filter(Boolean);
}
 
export function isTutorQualityRelevantUntrackedPath(relativePath: string, outputDir: string): boolean {
  const normalized = relativePath.replaceAll("\\", "/");
  const normalizedOutput = outputDir.replaceAll("\\", "/").replace(/\/$/, "");
  if (normalizedOutput && (normalized === normalizedOutput || normalized.startsWith(`${normalizedOutput}/`))) return false;
  return normalized.startsWith("evals/tutor-quality/")
    || normalized.startsWith("server/")
    || normalized.startsWith("shared/")
    || normalized.startsWith("scripts/")
    || ["package.json", "package-lock.json", ".nvmrc"].includes(normalized);
}
 
export function readTutorQualityGitState(cwd: string, outputDir: string): TutorQualityGitState {
  const sha = execFileSync(resolveGitExecutable(), ["rev-parse", "HEAD"], { cwd, encoding: "utf8" }).trim();
  const lines = statusLines(cwd);
  const trackedClean = lines.every((line) => line.startsWith("??"));
  const outputRelative = path.relative(cwd, path.resolve(cwd, outputDir));
  const relevantUntrackedClean = lines.every((line) => {
    if (!line.startsWith("??")) return true;
    return !isTutorQualityRelevantUntrackedPath(line.slice(3).trim(), outputRelative);
  });
  return { sha, trackedClean, relevantUntrackedClean };
}
 
export async function runTutorQualityCli(
  argv: readonly string[],
  dependencies: TutorQualityCliDependencies = {},
) {
  const options = parseTutorQualityCliArgs(argv);
  const cwd = dependencies.cwd ?? process.cwd();
  const environment = dependencies.environment ?? process.env;
  const loadedScenarios = await loadTutorQualityEvaluationScenarios(cwd, options.corpusPath);
  const requestedCases = new Set(options.cases);
  const unknownCases = [...requestedCases].filter((id) => !loadedScenarios.some((scenario) => scenario.id === id));
  Iif (unknownCases.length) throw new Error(`Unknown Tutor Quality case: ${unknownCases.join(", ")}`);
  const scenarios = requestedCases.size ? loadedScenarios.filter(({ id }) => requestedCases.has(id)) : loadedScenarios;
  const git = dependencies.git ?? readTutorQualityGitState(cwd, options.outputDir);
  const provider = dependencies.provider ?? new KiconnectProvider();
  const credential = environment[options.credentialEnv];
  const judgeCredential = options.judgeModel ? environment[options.judgeCredentialEnv] : undefined;
  return runTutorQualityEvaluation({
    scenarios,
    provider,
    providerId: "kiconnect",
    endpointOrigin: environment.UNOSIM_LLM_BASE_URL ? new URL(environment.UNOSIM_LLM_BASE_URL).origin : undefined,
    ...(credential ? { credential } : {}),
    requestedModel: options.model,
    ...(options.judgeModel ? { judgeModel: options.judgeModel } : {}),
    ...(judgeCredential ? { judgeCredential } : {}),
    samples: options.samples,
    maxCalls: options.maxCalls,
    timeoutMs: config.tutor.timeoutMs,
    outputDir: path.resolve(cwd, options.outputDir),
    git,
  });
}
 
export function tutorQualityExitCode(report: Pick<TutorQualityEvaluationReport, "runStatus" | "qualityVerdict">): number {
  switch (report.qualityVerdict.verdict) {
    case "fail":
      return TUTOR_QUALITY_EXIT_CODES.qualityFail;
    case "inconclusive":
      // R-PYR-2: a run skipped for a missing credential or a zero budget must not fail CI.
      return report.runStatus === "not-run" ? TUTOR_QUALITY_EXIT_CODES.success : TUTOR_QUALITY_EXIT_CODES.inconclusive;
    case "pass":
    case "warn":
      return TUTOR_QUALITY_EXIT_CODES.success;
  }
}
 
export async function runTutorQualityCliMain(
  argv: readonly string[],
  dependencies: TutorQualityCliDependencies = {},
): Promise<number> {
  const log = dependencies.log ?? console.log;
  const error = dependencies.error ?? console.error;
  try {
    const { report } = await runTutorQualityCli(argv, dependencies);
    log(JSON.stringify({
      runId: report.runId,
      runStatus: report.runStatus,
      reason: report.reason,
      qualityVerdict: report.qualityVerdict.verdict,
      providerCalls: report.providerCalls,
    }));
    return tutorQualityExitCode(report);
  } catch (error_: unknown) {
    error(error_ instanceof Error ? error_.message : "Tutor Quality evaluation failed");
    return TUTOR_QUALITY_EXIT_CODES.cliError;
  }
}
 
const invokedDirectly = process.argv[1] !== undefined
  && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href;
 
Iif (invokedDirectly) {
  process.exitCode = await runTutorQualityCliMain(process.argv.slice(2));
}