All files / src/services/api/routers EvaluationRouter.tsx

90.38% Statements 188/208
79.05% Branches 151/191
100% Functions 49/49
89.72% Lines 166/185

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                                                                                                                                                                                                                                                              70x 27x                     2241x                   2241x     2241x       2241x 4x 4x       2241x 6x     6x                       2241x     8x 8x     2241x       3x 3x                         2241x 3x 3x             3x                 2241x           3x       3x     2241x 3x 3x         2241x 6x     6x       2241x       4x       4x     2241x       3x     3x         2241x     6x     6x               2241x     47x       47x       2241x 23x     23x       2241x     4x 4x     2241x       5x 5x           2241x       4x       4x     2241x 3x 3x         2241x 26x     26x       2241x       7x       7x     2241x       4x     4x                 2241x 22x     22x         2241x                 24x       24x           2241x       25x       25x               25x       2241x     27x     27x 2x 2x         25x         2241x       4x     4x                       2241x 7x 7x             7x                         2241x                                 5x 5x 5x                                   2241x                 4x       4x     2241x 6x     6x       2241x       3x       3x       2241x       3x       3x             2241x                 3x       3x     2241x     6x             6x 6x     2241x 3x       3x                   2241x           6x                   6x       2241x         5x           5x 3x     2241x         3x       3x             2241x       4x     4x 1x                   2241x       7x     7x 4x       2241x 5x     5x 1x                       2241x                                   12x       12x 1x         2241x     12x       12x 3x             2241x 13x       13x 7x 7x                     6x             2241x       6x       6x 1x       2241x             6x       6x 5x     2241x         3x       3x         2241x       4x       4x 4x            
import {
  BatchReportRow,
  BatchReportTotals,
  EvaluateAgentStarted,
  FleetAssurance,
  PlatformBenchmark,
  BestConfigurations,
  CaseExample,
  CaseExpectation,
  Comparison,
  CriterionItem,
  ExpectedBehaviour,
  DatasetVersionDetail,
  DatasetVersionList,
  PresetCatalogue,
  PresetResult,
  ImportCasesResult,
  EvaluationScorer,
  EvaluationTarget,
  Experiment,
  ExperimentBatch,
  ExperimentRun,
  ExperimentCreate,
  ExperimentUpdate,
  ExperimentVariant,
  OptimisationState,
  RegressionMetric,
  RegressionReport,
  ScorerCatalogue,
  TestCase,
  TestCaseCreate,
  TestCaseUpdate,
  TestSuite,
  TestSuiteCopy,
  TestSuiteCreate,
  TestSuiteUpdate,
  VariantCreate,
  VariantUpdate,
} from "@/objects/Evaluation";
import { Dictionary } from "@/types/ext";
import { AxiosRequestConfig } from "axios";
import { ScopedHistoryRouter } from "../HistoricalApiRouter";
import { isPlainObject } from "@/types/null";
 
/** What POST /experiments/{id}/run answers with once a batch is queued. */
export interface RunExperimentResponse {
  batch_id: string;
  status: string;
  /** How many variants and cases the queued matrix covers. */
  variants: number;
  cases: number;
  /** How many times each case is asked; `total` counts every answer. */
  repeats?: number;
  total: number;
}
 
/** What POST /experiments/{id}/optimise answers with. */
export interface OptimiseResponse {
  optimisation_id: string;
  status: string;
  rounds: number;
  candidates_per_round: number;
}
 
/** One metric a regression comparison tracks, from the catalogue endpoint. */
export interface RegressionMetricSpec {
  key: string;
  label: string;
  description: string;
  direction: "higher_is_better" | "lower_is_better";
  gating: boolean;
  tolerance: number;
  relative_tolerance: boolean;
}
 
/**
 * Whether a variant may be promoted onto an agent.
 *
 * `unmeasured` never blocks: the gate refuses on evidence of a regression, not
 * on the absence of evidence.
 */
export interface PromotionGate {
  status: "clear" | "blocked" | "unmeasured";
  reasons: string[];
  metrics: RegressionMetric[];
  batch: {
    id: string;
    label: string | null;
    finished_at: string | null;
    scorer: EvaluationScorer | null;
  } | null;
  candidate: PromotionGateSide | null;
  control: PromotionGateSide | null;
}
 
/** One side of a gate comparison — the candidate, or the control it is
 *  measured against. */
export interface PromotionGateSide {
  variant_id: string;
  variant_name: string;
  mean_score?: number | null;
  pass_rate?: number | null;
  rank?: number;
  total?: number;
  errors?: number;
}
 
/** What promoting a variant onto an agent answers with. */
export interface PromoteResponse {
  agent_id: string;
  agent_name: string;
  previous_system_prompt: string | null;
  system_prompt: string;
  /** The agent revision this promotion created — the link into its history. */
  agent_version: number | null;
  gate: PromotionGate;
  /** True when the promotion went ahead past a closed gate. */
  forced: boolean;
}
 
/**
 * A created row, or null when the body is not one.
 *
 * Every create in this router answers with the row it made and the caller's
 * next step is that row's id — a navigation, or a child created under it — so
 * a body without an id is a failure however the status read.
 */
const createdRow = <T extends { id: string }>(data: unknown): T | null =>
  isPlainObject(data) && typeof (data as { id?: unknown }).id === "string"
    ? (data as T)
    : null;
 
export class EvaluationRouter extends ScopedHistoryRouter {
  constructor(
    host: string,
    token: string | null = null,
    default_config: AxiosRequestConfig | null = null,
    headers: Dictionary<string> = {},
  ) {
    super("evaluations", host, token, default_config, headers);
  }
 
  // ── Edit history ────────────────────────────────────────────────────────────
  //
  // Two historied resources share this router, so each gets its own scope
  // rather than the inherited bare history(id) — /evaluations/{id}/history is
  // not a route. Hand one of these to <ResourceHistorySection source={...} />.
 
  /** Edit history for an experiment (`/evaluations/experiments/{id}/history`). */
  experiments = this.historyScope("experiments");
 
  /** Edit history for a test suite (`/evaluations/test-suites/{id}/history`). */
  testSuites = this.historyScope("test-suites");
 
  // ── Experiments ─────────────────────────────────────────────────────────────
 
  listExperiments = async (): Promise<Experiment[]> => {
    const res = await this.api.get<Experiment[]>(super.endpoint("experiments"));
    Eif (super.validRes(res) && Array.isArray(res.data)) return res.data;
    return [];
  };
 
  getExperiment = async (id: string): Promise<Experiment | null> => {
    const res = await this.api.get<Experiment>(
      super.endpoint(`experiments/${id}`),
    );
    Eif (super.validRes(res)) return res.data;
    return null;
  };
 
  /**
   * Create an evaluation — with its variants, when given.
   *
   * Answers null unless the response carries an id. The backend once answered
   * a 201 with `{}` (an expired row serialised bare), and a caller that took
   * that as an evaluation navigated to `/id/undefined` and posted its variants
   * under it. A null is something the caller can show as an error.
   */
  createExperiment = async (
    data: ExperimentCreate,
  ): Promise<Experiment | null> => {
    const res = await this.api.post(super.endpoint("experiments"), data);
    return super.validRes(res) ? createdRow<Experiment>(res.data) : null;
  };
 
  updateExperiment = async (
    id: string,
    data: ExperimentUpdate,
  ): Promise<Experiment | null> => {
    const res = await this.api.patch(super.endpoint(`experiments/${id}`), data);
    Eif (super.validRes(res)) return res.data as Experiment;
    return null;
  };
 
  /**
   * Copy an evaluation's setup — dataset, scoring and variants — into a new
   * one, without its runs.
   *
   * The way past the measurement lock: an evaluation that has been run
   * cannot change what it asks or how it grades, so trying another dataset
   * or another scorer means a new evaluation with a fresh baseline.
   */
  /** The variant presets and the parameters each takes. */
  listPresets = async (): Promise<PresetCatalogue> => {
    const res = await this.api.get<PresetCatalogue>(super.endpoint("presets"));
    Iif (super.validRes(res) && isPlainObject(res.data)) {
      const body = res.data as Partial<PresetCatalogue>;
      return {
        presets: Array.isArray(body.presets) ? body.presets : [],
        max_variants: body.max_variants ?? 12,
      };
    }
    return { presets: [], max_variants: 12 };
  };
 
  /**
   * Expand a preset on an experiment. `dryRun` (the default) previews the
   * variants and the cost of a run without writing anything. Rejects with
   * the backend's reason — a model that drops the setting, an agent that is
   * not yours — so the form can show it.
   */
  applyPreset = async (
    experimentId: string,
    key: string,
    params: Record<string, unknown>,
    dryRun = true,
  ): Promise<PresetResult> => {
    const res = await this.api.post<PresetResult>(
      super.endpoint(`experiments/${experimentId}/presets/${key}`),
      { params, dry_run: dryRun },
    );
    return res.data;
  };
 
  deleteExperiment = async (id: string): Promise<boolean> => {
    const res = await this.api.delete(super.endpoint(`experiments/${id}`));
    return res.status === 204;
  };
 
  // ── Experiment Variants ──────────────────────────────────────────────────────
 
  listVariants = async (experimentId: string): Promise<ExperimentVariant[]> => {
    const res = await this.api.get<ExperimentVariant[]>(
      super.endpoint(`experiments/${experimentId}/variants`),
    );
    Eif (super.validRes(res) && Array.isArray(res.data)) return res.data;
    return [];
  };
 
  createVariant = async (
    experimentId: string,
    data: VariantCreate,
  ): Promise<ExperimentVariant | null> => {
    const res = await this.api.post(
      super.endpoint(`experiments/${experimentId}/variants`),
      data,
    );
    return super.validRes(res) ? createdRow<ExperimentVariant>(res.data) : null;
  };
 
  deleteVariant = async (
    experimentId: string,
    variantId: string,
  ): Promise<boolean> => {
    const res = await this.api.delete(
      super.endpoint(`experiments/${experimentId}/variants/${variantId}`),
    );
    return res.status === 204;
  };
 
  // ── Experiment Runs ──────────────────────────────────────────────────────────
 
  listExperimentRuns = async (
    experimentId: string,
  ): Promise<ExperimentRun[]> => {
    const res = await this.api.get<ExperimentRun[]>(
      super.endpoint(`experiments/${experimentId}/runs`),
    );
    Eif (super.validRes(res) && Array.isArray(res.data)) return res.data;
    return [];
  };
 
  // ── Test Suites ──────────────────────────────────────────────────────────────
 
  /** `includeSystem` adds the gold datasets — the Datasets page's Built-in
   *  section, and pickers that choose a dataset. */
  listTestSuites = async ({
    includeSystem = false,
  }: { includeSystem?: boolean } = {}): Promise<TestSuite[]> => {
    const res = await this.api.get<TestSuite[]>(
      super.endpoint("test-suites"),
      includeSystem ? { params: { include_system: true } } : undefined,
    );
    Eif (super.validRes(res) && Array.isArray(res.data)) return res.data;
    return [];
  };
 
  getTestSuite = async (id: string): Promise<TestSuite | null> => {
    const res = await this.api.get<TestSuite>(
      super.endpoint(`test-suites/${id}`),
    );
    Eif (super.validRes(res)) return res.data;
    return null;
  };
 
  createTestSuite = async (
    data: TestSuiteCreate,
  ): Promise<TestSuite | null> => {
    const res = await this.api.post(super.endpoint("test-suites"), data);
    return super.validRes(res) ? createdRow<TestSuite>(res.data) : null;
  };
 
  updateTestSuite = async (
    id: string,
    data: TestSuiteUpdate,
  ): Promise<TestSuite | null> => {
    const res = await this.api.patch(super.endpoint(`test-suites/${id}`), data);
    Eif (super.validRes(res)) return res.data as TestSuite;
    return null;
  };
 
  /** A dataset of your own with the source's criteria, pass mark and cases
   *  — how a gold dataset is built on, since it cannot be edited. */
  copyTestSuite = async (
    id: string,
    data: TestSuiteCopy = {},
  ): Promise<TestSuite | null> => {
    const res = await this.api.post(
      super.endpoint(`test-suites/${id}/copy`),
      data,
    );
    return super.validRes(res) ? createdRow<TestSuite>(res.data) : null;
  };
 
  deleteTestSuite = async (id: string): Promise<boolean> => {
    const res = await this.api.delete(super.endpoint(`test-suites/${id}`));
    return res.status === 204;
  };
 
  // ── Test Cases ───────────────────────────────────────────────────────────────
 
  listTestCases = async (suiteId: string): Promise<TestCase[]> => {
    const res = await this.api.get<TestCase[]>(
      super.endpoint(`test-suites/${suiteId}/cases`),
    );
    Eif (super.validRes(res) && Array.isArray(res.data)) return res.data;
    return [];
  };
 
  createTestCase = async (
    suiteId: string,
    data: TestCaseCreate,
  ): Promise<TestCase | null> => {
    const res = await this.api.post(
      super.endpoint(`test-suites/${suiteId}/cases`),
      data,
    );
    return super.validRes(res) ? createdRow<TestCase>(res.data) : null;
  };
 
  deleteTestCase = async (
    suiteId: string,
    caseId: string,
  ): Promise<boolean> => {
    const res = await this.api.delete(
      super.endpoint(`test-suites/${suiteId}/cases/${caseId}`),
    );
    return res.status === 204;
  };
 
  // ── Datasets: what uses them, and every run over them ──────────────────────
  //
  // A dataset has no runs of its own. These are read-only views across the
  // evaluations that reference it.
 
  /** The evaluations that run this dataset. */
  listDatasetEvaluations = async (suiteId: string): Promise<Experiment[]> => {
    const res = await this.api.get<Experiment[]>(
      super.endpoint(`test-suites/${suiteId}/evaluations`),
    );
    Eif (super.validRes(res) && Array.isArray(res.data)) return res.data;
    return [];
  };
 
  /** Every run that asked this dataset, across evaluations, newest first. */
  listDatasetRuns = async (
    suiteId: string,
    options: {
      include_unfinished?: boolean;
      limit?: number;
      /** Only the runs that asked this content version. */
      dataset_version?: number;
    } = {},
  ): Promise<BatchReportRow[]> => {
    const res = await this.api.get<BatchReportRow[]>(
      super.endpoint(`test-suites/${suiteId}/runs`),
      { params: options },
    );
    Eif (super.validRes(res) && Array.isArray(res.data)) return res.data;
    return [];
  };
 
  /** What works best on a dataset: each experiment's newest completed run
   *  on one version (the latest by default), grouped by how it was graded. */
  getBestConfigurations = async (
    suiteId: string,
    datasetVersion?: number,
  ): Promise<BestConfigurations> => {
    const res = await this.api.get<BestConfigurations>(
      super.endpoint(`test-suites/${suiteId}/best`),
      { params: datasetVersion ? { dataset_version: datasetVersion } : {} },
    );
    Iif (super.validRes(res) && isPlainObject(res.data)) {
      const body = res.data as Partial<BestConfigurations>;
      return {
        dataset_version: body.dataset_version ?? null,
        experiments_compared: body.experiments_compared ?? 0,
        groups: Array.isArray(body.groups) ? body.groups : [],
      };
    }
    return { dataset_version: null, experiments_compared: 0, groups: [] };
  };
 
  /** A dataset's content versions, oldest first; the last is the latest. */
  listDatasetVersions = async (
    suiteId: string,
  ): Promise<DatasetVersionList> => {
    const res = await this.api.get<DatasetVersionList>(
      super.endpoint(`test-suites/${suiteId}/versions`),
    );
    if (super.validRes(res) && isPlainObject(res.data)) {
      const body = res.data as Partial<DatasetVersionList>;
      return {
        versions: Array.isArray(body.versions) ? body.versions : [],
        unversioned_runs: body.unversioned_runs ?? 0,
      };
    }
    return { versions: [], unversioned_runs: 0 };
  };
 
  /** One content version with the cases it held. Rejects on failure so the
   *  page can say so rather than render an empty version. */
  getDatasetVersion = async (
    suiteId: string,
    version: number,
  ): Promise<DatasetVersionDetail> => {
    const res = await this.api.get<DatasetVersionDetail>(
      super.endpoint(`test-suites/${suiteId}/versions/${version}`),
    );
    return res.data;
  };
 
  // ── Execution: scorers ───────────────────────────────────────────────────────
 
  /**
   * The scorer vocabulary, for the scorer picker.
   *
   * Two registries — the scorers and the group headings they sit under —
   * plus the default pass threshold, so the picker's labels, guidance and
   * settings all come from the backend rather than a second list here.
   */
  listScorers = async (): Promise<ScorerCatalogue> => {
    const res = await this.api.get<ScorerCatalogue>(super.endpoint("scorers"));
    Iif (super.validRes(res) && Array.isArray(res.data?.scorers)) {
      return {
        scorers: res.data.scorers,
        groups: Array.isArray(res.data.groups) ? res.data.groups : [],
        default_pass_threshold: res.data.default_pass_threshold ?? 0.7,
      };
    }
    return { scorers: [], groups: [], default_pass_threshold: 0.7 };
  };
 
  // ── Execution: ad-hoc comparison ─────────────────────────────────────────────
 
  /**
   * Run one prompt against several models/agents at once.
   *
   * Backs Quick try. The comparison is kept server-side under the returned
   * `comparison_id`, which `createExperiment` adopts as the first run.
   * Rejects so the caller can surface the backend's validation message rather
   * than an empty result that looks like every target returned nothing.
   */
  compare = async (data: {
    prompt: string;
    targets: EvaluationTarget[];
    system_prompt?: string;
    expected_output?: string | null;
    /** The question's label, as a dataset case carries it. */
    criteria?: CriterionItem[] | null;
    examples?: CaseExample[] | null;
    expectation?: CaseExpectation | null;
    expected_behaviour?: ExpectedBehaviour | null;
    scorer?: EvaluationScorer | null;
    /** How to judge only — criteria and checks here are refused. */
    scorer_config?: Record<string, unknown> | null;
    /** Which model grades, for the `llm` scorer. Stored on the comparison,
     *  so saving it as an evaluation carries the judge that graded it. */
    judge?: EvaluationTarget | null;
  }): Promise<Comparison> => {
    const res = await this.api.post(super.endpoint("compare"), data);
    const body = res.data as Partial<Comparison> | null;
    return {
      comparison_id:
        isPlainObject(body) && typeof body.comparison_id === "string"
          ? body.comparison_id
          : null,
      results: isPlainObject(body) && Array.isArray(body.results) ? body.results : [],
    };
  };
 
  // ── Execution: experiment batches ────────────────────────────────────────────
 
  /**
   * Queue a run: the selected variants over the evaluation's dataset.
   *
   * What is asked and how it is graded are the evaluation's own and cannot
   * be swapped per run — a run that could would not be a run of this
   * evaluation, and its verdict would compare two different things.
   */
  runExperiment = async (
    experimentId: string,
    data: {
      variant_ids?: string[];
      label?: string;
      concurrency?: number;
      repeats?: number;
    } = {},
  ): Promise<RunExperimentResponse> => {
    const res = await this.api.post<RunExperimentResponse>(
      super.endpoint(`experiments/${experimentId}/run`),
      data,
    );
    return res.data;
  };
 
  listBatches = async (experimentId: string): Promise<ExperimentBatch[]> => {
    const res = await this.api.get<ExperimentBatch[]>(
      super.endpoint(`experiments/${experimentId}/batches`),
    );
    Eif (super.validRes(res) && Array.isArray(res.data)) return res.data;
    return [];
  };
 
  cancelBatch = async (
    experimentId: string,
    batchId: string,
  ): Promise<boolean> => {
    const res = await this.api.post(
      super.endpoint(`experiments/${experimentId}/batches/${batchId}/cancel`),
      {},
    );
    return super.validRes(res);
  };
 
  /** Delete an experiment's runs — one batch, or all of them. */
  deleteExperimentRuns = async (
    experimentId: string,
    batchId?: string,
  ): Promise<boolean> => {
    const res = await this.api.delete(
      super.endpoint(`experiments/${experimentId}/runs`),
      batchId ? { params: { batch_id: batchId } } : undefined,
    );
    return res.status === 204;
  };
 
  // ── Execution: prompt optimisation ───────────────────────────────────────────
 
  /** Start an automatic search for a better prompt, over the evaluation's
   *  dataset with its scorer. */
  optimiseExperiment = async (
    experimentId: string,
    data: {
      base_variant_id: string;
      rounds?: number;
      candidates_per_round?: number;
      instructions?: string;
    },
  ): Promise<OptimiseResponse> => {
    const res = await this.api.post<OptimiseResponse>(
      super.endpoint(`experiments/${experimentId}/optimise`),
      data,
    );
    return res.data;
  };
 
  getOptimisation = async (
    experimentId: string,
  ): Promise<OptimisationState | null> => {
    const res = await this.api.get<OptimisationState | null>(
      super.endpoint(`experiments/${experimentId}/optimisation`),
    );
    // One object or nothing — an optimisation state is never a list. Checking
    // the shape rather than just truthiness matters because `[]` is truthy:
    // a caller guarding with `if (optimisation)` would let it through and
    // then read `state.history` off an array.
    Iif (super.validRes(res) && isPlainObject(res.data)) return res.data;
    return null;
  };
 
  cancelOptimisation = async (experimentId: string): Promise<boolean> => {
    const res = await this.api.post(
      super.endpoint(`experiments/${experimentId}/optimisation/cancel`),
      {},
    );
    return super.validRes(res);
  };
 
  /**
   * Adopt a winning variant's prompt as an agent's system prompt.
   *
   * Rejected with 409 when the variant scored worse than the prompt already
   * live. Pass `force` to override — the decision and the gate's reasons are
   * then recorded on the experiment.
   */
  promoteVariant = async (
    experimentId: string,
    variantId: string,
    agentId?: string,
    options: { force?: boolean; note?: string } = {},
  ): Promise<PromoteResponse> => {
    const res = await this.api.post<PromoteResponse>(
      super.endpoint(
        `experiments/${experimentId}/variants/${variantId}/promote`,
      ),
      {
        ...(agentId ? { agent_id: agentId } : {}),
        ...(options.force ? { force: true } : {}),
        ...(options.note ? { note: options.note } : {}),
      },
    );
    return res.data;
  };
 
  /** Ask the gate before promoting, so the UI can warn rather than refuse. */
  checkPromotion = async (
    experimentId: string,
    variantId: string,
    agentId?: string,
  ): Promise<PromotionGate | null> => {
    const res = await this.api.get<PromotionGate>(
      super.endpoint(
        `experiments/${experimentId}/variants/${variantId}/promotion-check`,
      ),
      agentId ? { params: { agent_id: agentId } } : undefined,
    );
    if (super.validRes(res) && isPlainObject(res.data)) return res.data;
    return null;
  };
 
  updateVariant = async (
    experimentId: string,
    variantId: string,
    data: VariantUpdate,
  ): Promise<ExperimentVariant | null> => {
    const res = await this.api.patch(
      super.endpoint(`experiments/${experimentId}/variants/${variantId}`),
      data,
    );
    Eif (super.validRes(res)) return res.data as ExperimentVariant;
    return null;
  };
 
  // ── Runs: results and the regression verdict ────────────────────────────────
 
  /** The scored cells of one run. */
  listBatchResults = async (
    experimentId: string,
    batchId: string,
  ): Promise<ExperimentRun[]> => {
    const res = await this.api.get<ExperimentRun[]>(
      super.endpoint(`experiments/${experimentId}/batches/${batchId}/results`),
    );
    if (super.validRes(res) && Array.isArray(res.data)) return res.data;
    return [];
  };
 
  /**
   * How this run compares to the evaluation's last comparable run.
   *
   * Computed on read, so a run recorded before regression detection existed
   * still reports, and an evaluation whose tolerances were retuned reports
   * against the tolerances in force now.
   */
  getBatchRegression = async (
    experimentId: string,
    batchId: string,
  ): Promise<RegressionReport | null> => {
    const res = await this.api.get<RegressionReport>(
      super.endpoint(`experiments/${experimentId}/batches/${batchId}/regression`),
    );
    if (super.validRes(res) && isPlainObject(res.data)) return res.data;
    return null;
  };
 
  /** The metrics a comparison tracks — served from the backend registry. */
  getRegressionMetrics = async (): Promise<RegressionMetricSpec[]> => {
    const res = await this.api.get<RegressionMetricSpec[]>(
      super.endpoint("regression/metrics"),
    );
    if (super.validRes(res) && Array.isArray(res.data)) return res.data;
    return [];
  };
 
  // ── Cross-experiment reporting ──────────────────────────────────────────────
 
  /**
   * Completed batches across every experiment in scope, newest first.
   *
   * Filtered server-side. This is what batches moving into their own table
   * bought — before it, "every batch in this project that scored below 0.7"
   * meant loading every experiment and walking a JSON array.
   */
  reportBatches = async (
    filters: {
      owner_organisation_id?: string;
      owner_project_id?: string;
      experiment_id?: string;
      dataset_id?: string;
      scorer?: EvaluationScorer;
      days?: number;
      min_mean_score?: number;
      max_mean_score?: number;
      limit?: number;
      /** Rows to skip, newest first — how the activity feed pages back. */
      offset?: number;
      /** Queued, running, failed and cancelled runs too — for a feed of
       *  events rather than a table of figures. */
      include_unfinished?: boolean;
    } = {},
  ): Promise<BatchReportRow[]> => {
    const res = await this.api.get<BatchReportRow[]>(
      super.endpoint("reports/batches"),
      { params: filters },
    );
    if (super.validRes(res) && Array.isArray(res.data)) return res.data;
    return [];
  };
 
  /** Every agent in scope and the evaluation evidence behind the version in
   *  force — the Governance → Evaluation → Assurance view. */
  assurance = async (
    filters: { owner_organisation_id?: string; owner_project_id?: string } = {},
  ): Promise<FleetAssurance | null> => {
    const res = await this.api.get<FleetAssurance>(
      super.endpoint("assurance"),
      { params: filters },
    );
    if (super.validRes(res) && isPlainObject(res.data)) return res.data;
    return null;
  };
 
  /**
   * The platform benchmark: CHAINR Bot and each maker's strongest model on every gold
   * dataset (or one), the same for every user.
   */
  benchmark = async (datasetId?: string): Promise<PlatformBenchmark | null> => {
    const res = await this.api.get<PlatformBenchmark>(
      super.endpoint("benchmark"),
      { params: datasetId ? { dataset_id: datasetId } : {} },
    );
    if (super.validRes(res) && isPlainObject(res.data)) {
      const body = res.data as Partial<PlatformBenchmark>;
      return {
        enabled: body.enabled === true,
        deploy_id: body.deploy_id ?? null,
        budget_usd: body.budget_usd ?? 0,
        spend_month_usd: body.spend_month_usd ?? null,
        period: body.period ?? null,
        resets_at: body.resets_at ?? null,
        datasets: Array.isArray(body.datasets) ? body.datasets : [],
        targets: Array.isArray(body.targets) ? body.targets : [],
      };
    }
    return null;
  };
 
  /**
   * Evaluate an agent as configured on the chosen datasets: one experiment
   * per dataset (found again next time), each run once.
   */
  evaluateAgent = async (
    agentId: string,
    data: { dataset_ids: string[]; repeats?: number },
  ): Promise<EvaluateAgentStarted[]> => {
    const res = await this.api.post<EvaluateAgentStarted[]>(
      super.endpoint(`agents/${agentId}/evaluate`),
      data,
    );
    if (super.validRes(res) && Array.isArray(res.data)) return res.data;
    return [];
  };
 
  /** Headline totals over the same population `reportBatches` lists. */
  reportSummary = async (
    filters: {
      owner_organisation_id?: string;
      owner_project_id?: string;
      days?: number;
    } = {},
  ): Promise<BatchReportTotals | null> => {
    const res = await this.api.get<BatchReportTotals>(
      super.endpoint("reports/summary"),
      { params: filters },
    );
    if (super.validRes(res) && isPlainObject(res.data)) return res.data;
    return null;
  };
 
  updateTestCase = async (
    suiteId: string,
    caseId: string,
    data: TestCaseUpdate,
  ): Promise<TestCase | null> => {
    const res = await this.api.patch(
      super.endpoint(`test-suites/${suiteId}/cases/${caseId}`),
      data,
    );
    Eif (super.validRes(res)) return res.data as TestCase;
    return null;
  };
 
  /** Bulk-create cases from pasted CSV, JSONL, or a JSON array. */
  importTestCases = async (
    suiteId: string,
    data: { content: string; format?: string; replace?: boolean },
  ): Promise<ImportCasesResult> => {
    const res = await this.api.post(
      super.endpoint(`test-suites/${suiteId}/cases/import`),
      data,
    );
    const body = res.data as Partial<ImportCasesResult> | null;
    return {
      created: isPlainObject(body) && Array.isArray(body.created) ? body.created : [],
      ignored: isPlainObject(body) && Array.isArray(body.ignored) ? body.ignored : [],
    };
  };
}