@mcpjam/cli 4.0.0 → 4.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -2,16 +2,16 @@
2
2
  import { Command, CommanderError, Option } from 'commander';
3
3
  import { realpathSync, readFileSync, existsSync, mkdirSync, writeFileSync, unlinkSync, statSync, closeSync, renameSync, openSync } from 'fs';
4
4
  import { pathToFileURL } from 'url';
5
- import { probeMcpServer, redactForTelemetry, runServerDoctor, collectServerSnapshot, serializeStableServerSnapshot, serializeServerSnapshot, buildServerDiffReport, classifyMcpHeader, validateToolCallResult, isCallToolResultError, buildToolCallValidationReport, listResources, readResource, SubscriptionCoordinator, listTools, listPrompts, getPrompt, MCPAppsConformanceTest, scoreFromAppsResult, MCPAppsConformanceSuite, MCPTasksConformanceTest, scoreFromTasksResult, runOAuthLogin, OAuthConformanceTest, scoreFromOAuthResult, OAuthConformanceSuite, runXaaFlow, MCPConformanceTest, scoreFromProtocolResult, MCPConformanceSuite, runConformance, isConformanceReportingConfigured, reportConformanceRun, reportConformanceRunSafely, OPENAI_SUBMISSION_MODES, withEphemeralClient, diffServerSnapshots, ServerSnapshotFormatError, renderStructuredRunJUnitXml, renderStructuredRunJson, DEFAULT_SUBSCRIPTION_RECONNECT_POLICY, isKnownProtocolVersion, describeConformanceScore, toConformanceReport, buildConformanceRunReport, renderConformanceReportJUnitXml, renderConformanceReportJson, formatOAuthConformanceHuman, formatOAuthConformanceSuiteHuman, fetchOAuthMetadata, executeOAuthProxy, executeDebugOAuthProxy, normalizeRegistrationStrategy, normalizeXaaClientAuth, normalizeIdentityAssertionFormat, IDENTITY_ASSERTION_FORMATS, XAA_CONFIDENTIAL_CIMD_ORIGIN, getLocalConfidentialCimdProvider, MCP_PROTOCOL_VERSIONS, gatherClaudeReadinessEvidence, gradeClaudeReadiness, gatherOpenAIReadinessEvidence, xmldomParseXml, gradeOpenAIReadiness, openUrlInBrowser, buildEvalRunReport, buildEvalDecisionSummaryFromIterations, MCPClientManager, decodeMcpHeaderValue, canDeclareTasksExtension, createStrictElicitationContentValidator, MCP_APPS_CHECK_CATEGORIES, MCP_APPS_CHECK_IDS, MCP_TASKS_CHECK_CATEGORIES, MCP_TASKS_CHECK_IDS, OAuthProxyError, isLoopbackHost, MCP_CHECK_CATEGORIES, MCP_CHECK_IDS, OPENAI_SUBMISSION_MODE_SHAPES, createDirectoryPluginFileSource, collectZipArchiveObservations, createZipPluginFileSource, generateRandomString, generateCodeChallenge, createInteractiveAuthorizationSession, formatEvalDecisionSummary, formatGateReport, detectFlakyCases, evaluateCompareGates, buildRunCompareReport, loadEvalSuiteFile, formatSuiteFileFindings, serializeEvalSuiteFile, MAX_SUITE_FILE_BYTES, buildCorpus, HostedOnlyCaseError, verifyCorpusLock, TaskLifecycleEngine, driveTaskToTerminal, extensionTaskToObservation, legacyTaskToObservation, evaluateGates, gateInputFromPlatformRun, calculateLatencyStats, CORPUS_LOCK_VERSION, canonicalDigest, passRateFractionFromPercent, suiteFilePointer, isUnknownTaskError, isMCPTasksWireError, LEGACY_TASK_STATUSES } from '@mcpjam/sdk';
5
+ import { probeMcpServer, redactForTelemetry, runServerDoctor, collectServerSnapshot, serializeStableServerSnapshot, serializeServerSnapshot, buildServerDiffReport, classifyMcpHeader, validateToolCallResult, isCallToolResultError, buildToolCallValidationReport, listResources, readResource, SubscriptionCoordinator, listTools, listPrompts, getPrompt, MCPAppsConformanceTest, scoreFromAppsResult, MCPAppsConformanceSuite, MCPTasksConformanceTest, scoreFromTasksResult, runOAuthLogin, OAuthConformanceTest, scoreFromOAuthResult, OAuthConformanceSuite, runXaaFlow, MCPConformanceTest, scoreFromProtocolResult, MCPConformanceSuite, runConformance, isConformanceReportingConfigured, reportConformanceRun, reportConformanceRunSafely, OPENAI_SUBMISSION_MODES, withEphemeralClient, diffServerSnapshots, ServerSnapshotFormatError, renderStructuredRunJUnitXml, renderStructuredRunHtml, renderStructuredRunJson, DEFAULT_SUBSCRIPTION_RECONNECT_POLICY, isKnownProtocolVersion, describeConformanceScore, toConformanceReport, buildConformanceRunReport, renderConformanceReportJUnitXml, renderConformanceReportJson, formatOAuthConformanceHuman, formatOAuthConformanceSuiteHuman, fetchOAuthMetadata, executeOAuthProxy, executeDebugOAuthProxy, normalizeRegistrationStrategy, normalizeXaaClientAuth, normalizeIdentityAssertionFormat, IDENTITY_ASSERTION_FORMATS, XAA_CONFIDENTIAL_CIMD_ORIGIN, getLocalConfidentialCimdProvider, MCP_PROTOCOL_VERSIONS, gatherClaudeReadinessEvidence, gradeClaudeReadiness, gatherOpenAIReadinessEvidence, xmldomParseXml, gradeOpenAIReadiness, openUrlInBrowser, buildEvalRunReport, buildEvalDecisionSummaryFromIterations, MCPClientManager, decodeMcpHeaderValue, canDeclareTasksExtension, createStrictElicitationContentValidator, MCP_APPS_CHECK_CATEGORIES, MCP_APPS_CHECK_IDS, MCP_TASKS_CHECK_CATEGORIES, MCP_TASKS_CHECK_IDS, OAuthProxyError, isLoopbackHost, MCP_CHECK_CATEGORIES, MCP_CHECK_IDS, OPENAI_SUBMISSION_MODE_SHAPES, createDirectoryPluginFileSource, collectZipArchiveObservations, createZipPluginFileSource, generateRandomString, generateCodeChallenge, createInteractiveAuthorizationSession, loadEvalSuiteFile, formatEvalDecisionSummary, gateOutcomeVerdict, formatGateReport, detectFlakyCases, evaluateCompareGates, buildRunCompareReport, formatSuiteFileFindings, serializeEvalSuiteFile, MAX_SUITE_FILE_BYTES, buildCorpus, HostedOnlyCaseError, verifyCorpusLock, TaskLifecycleEngine, driveTaskToTerminal, extensionTaskToObservation, legacyTaskToObservation, canonicalDigest, evaluateGates, gateInputFromPlatformRun, calculateLatencyStats, CORPUS_LOCK_VERSION, passRateFractionFromPercent, DEFAULT_MIN_EFFECT_SIZE, DEFAULT_MIN_SAMPLE_SIZE, suiteFilePointer, isUnknownTaskError, isMCPTasksWireError, LEGACY_TASK_STATUSES } from '@mcpjam/sdk';
6
6
  import path7, { join, dirname, basename } from 'path';
7
7
  import { randomUUID, randomBytes, createHash } from 'crypto';
8
8
  import { mkdir, writeFile, readFile, chmod, rename, rm, open, unlink, stat } from 'fs/promises';
9
9
  import { spawn } from 'child_process';
10
10
  import { createRequire } from 'module';
11
11
  import os, { homedir } from 'os';
12
- import { getRegistryDirectoryServerOperation, listOrganizationsOperation, listProjectsOperation, createProjectOperation, updateProjectOperation, deleteProjectOperation, connectProjectServerOperation, getProjectServerConnectionStatusOperation, listChatSessionsOperation, resolveProject, createTunnelOperation, listEvalSuiteRunsOperation, getEvalRunOperation, cancelEvalRunOperation, requestEvalRunJudgeOperation, listEvalCheckReposOperation, connectEvalCheckRepoOperation, listEvalRunIterationsOperation, getEvalIterationTraceOperation, getEvalRunStepsOperation, getEvalSuiteOperation, updateEvalSuiteOperation, deleteEvalSuiteOperation, setEvalSuiteScheduleOperation, setEvalSuiteEnvironmentsOperation, listEvalCasesOperation, getEvalCaseOperation, runEvalCaseOperation, createEvalCaseOperation, updateEvalCaseOperation, deleteEvalCaseOperation, generateEvalCasesOperation, createHostOperation, updateHostOperation, setHostServersOperation, duplicateHostOperation, createEnvironmentOperation, ensureAdhocEnvironmentOperation, nameEnvironmentOperation, updateEnvironmentOperation, createImageOperation, validateImageBlueprintOperation, updateImageOperation, PlatformApiError, installRegistryServerOperation, installRegistryDirectoryServerOperation, getProjectServerOperation, DEFAULT_PLATFORM_API_BASE_URL, projectResolutionError, listProjectServersOperation, createProjectServerOperation, updateProjectServerOperation, deleteProjectServerOperation, showServersOperation, isPlatformApiError, createEvalSuiteOperation, listEvalSuitesOperation, runEvalSuiteOperation, resolveEnvironmentOperation, listHostsOperation, getHostOperation, deleteHostOperation, listEnvironmentsOperation, getEnvironmentOperation, getEnvironmentCapabilitiesOperation, archiveEnvironmentOperation, restoreEnvironmentOperation, listImagesOperation, getImageOperation, buildImageOperation, listImageBuildsOperation, useImageOperation, resetComputerOperation, promoteImageOperation, deleteImageOperation, listJourneysOperation, listJourneyRunsOperation, getJourneyRunOperation, launchJourneyRunOperation, cancelJourneyRunOperation, listJourneyRunSessionsOperation, listScenariosOperation, getScenarioOperation, publishScenarioOperation, unpublishScenarioOperation, PlatformApiClient, getCapabilitiesOperation, searchSessionsOperation, sendChatMessageOperation, getChatSessionOperation, getChatSessionTraceOperation, listPersonasOperation, getPersonaOperation, createPersonaOperation, updatePersonaOperation, deletePersonaOperation, generatePersonasOperation, getJourneyOperation, createJourneyOperation, updateJourneyOperation, archiveJourneyOperation, generateJourneysOperation, getSwarmOverviewOperation, getJourneyRunScorecardOperation, listSwarmFindingsOperation, dismissSwarmFindingOperation, undismissSwarmFindingOperation, getWaveInsightsOperation, requestWaveInsightsOperation, cancelWaveInsightsOperation, listSwarmsOperation, getSwarmOperation, createSwarmOperation, updateSwarmOperation, archiveSwarmOperation, getUserTestingScenarioOperation, listUserTestingSessionsOperation, getUserTestingSessionOperation, getUserTestingMetricsOperation, getUserTestingUsageOperation, listUserTestingFindingsOperation, getUserTestingSignalsOperation, getUserTestingInsightsOperation, requestUserTestingInsightsOperation, cancelUserTestingInsightsOperation, dismissUserTestingFindingOperation, undismissUserTestingFindingOperation, updateUserTestingScenarioOperation, setUserTestingGuestExecutionOperation, rotateUserTestingLinkOperation, upsertUserTestingMemberOperation, removeUserTestingMemberOperation, rebindUserTestingScenarioOperation, startClaudeReadinessRunOperation, startOpenAIReadinessRunOperation, getReadinessRunOperation, listReadinessRunsOperation, cancelReadinessRunOperation, getReadinessReportOperation, listRegistryDirectorySourcesOperation, searchRegistryDirectoryOperation, listRegistryServersOperation, listRegistryConnectionsOperation, uninstallRegistryServerOperation } from '@mcpjam/sdk/platform';
12
+ import { getRegistryDirectoryServerOperation, listOrganizationsOperation, listProjectsOperation, createProjectOperation, updateProjectOperation, deleteProjectOperation, connectProjectServerOperation, getProjectServerConnectionStatusOperation, listChatSessionsOperation, resolveProject, createTunnelOperation, listEvalSuiteRunsOperation, runEvalSuiteOperation, getEvalRunOperation, cancelEvalRunOperation, requestEvalRunJudgeOperation, listEvalCheckReposOperation, connectEvalCheckRepoOperation, listEvalRunIterationsOperation, getEvalIterationTraceOperation, getEvalRunStepsOperation, getEvalSuiteOperation, updateEvalSuiteOperation, deleteEvalSuiteOperation, setEvalSuiteScheduleOperation, setEvalSuiteEnvironmentsOperation, listEvalCasesOperation, getEvalCaseOperation, runEvalCaseOperation, createEvalCaseOperation, updateEvalCaseOperation, deleteEvalCaseOperation, generateEvalCasesOperation, createHostOperation, updateHostOperation, setHostServersOperation, duplicateHostOperation, createEnvironmentOperation, ensureAdhocEnvironmentOperation, nameEnvironmentOperation, updateEnvironmentOperation, createImageOperation, validateImageBlueprintOperation, updateImageOperation, PlatformApiError, installRegistryServerOperation, installRegistryDirectoryServerOperation, getProjectServerOperation, DEFAULT_PLATFORM_API_BASE_URL, projectResolutionError, listProjectServersOperation, createProjectServerOperation, updateProjectServerOperation, deleteProjectServerOperation, showServersOperation, isPlatformApiError, createEvalSuiteOperation, listEvalSuitesOperation, resolveEnvironmentOperation, listHostsOperation, getHostOperation, deleteHostOperation, listEnvironmentsOperation, getEnvironmentOperation, getEnvironmentCapabilitiesOperation, archiveEnvironmentOperation, restoreEnvironmentOperation, listImagesOperation, getImageOperation, buildImageOperation, listImageBuildsOperation, useImageOperation, resetComputerOperation, promoteImageOperation, deleteImageOperation, listJourneysOperation, listJourneyRunsOperation, getJourneyRunOperation, launchJourneyRunOperation, cancelJourneyRunOperation, listJourneyRunSessionsOperation, listScenariosOperation, getScenarioOperation, publishScenarioOperation, unpublishScenarioOperation, PlatformApiClient, getCapabilitiesOperation, searchSessionsOperation, sendChatMessageOperation, getChatSessionOperation, getChatSessionTraceOperation, listPersonasOperation, getPersonaOperation, createPersonaOperation, updatePersonaOperation, deletePersonaOperation, generatePersonasOperation, getJourneyOperation, createJourneyOperation, updateJourneyOperation, archiveJourneyOperation, generateJourneysOperation, getSwarmOverviewOperation, getJourneyRunScorecardOperation, listSwarmFindingsOperation, dismissSwarmFindingOperation, undismissSwarmFindingOperation, getWaveInsightsOperation, requestWaveInsightsOperation, cancelWaveInsightsOperation, listSwarmsOperation, getSwarmOperation, createSwarmOperation, updateSwarmOperation, archiveSwarmOperation, getUserTestingScenarioOperation, listUserTestingSessionsOperation, getUserTestingSessionOperation, getUserTestingMetricsOperation, getUserTestingUsageOperation, listUserTestingFindingsOperation, getUserTestingSignalsOperation, getUserTestingInsightsOperation, requestUserTestingInsightsOperation, cancelUserTestingInsightsOperation, dismissUserTestingFindingOperation, undismissUserTestingFindingOperation, updateUserTestingScenarioOperation, setUserTestingGuestExecutionOperation, rotateUserTestingLinkOperation, upsertUserTestingMemberOperation, removeUserTestingMemberOperation, rebindUserTestingScenarioOperation, startClaudeReadinessRunOperation, startOpenAIReadinessRunOperation, getReadinessRunOperation, listReadinessRunsOperation, cancelReadinessRunOperation, getReadinessReportOperation, listRegistryDirectorySourcesOperation, searchRegistryDirectoryOperation, listRegistryServersOperation, listRegistryConnectionsOperation, uninstallRegistryServerOperation } from '@mcpjam/sdk/platform';
13
13
  import { isDeepStrictEqual } from 'util';
14
- import { evalSuiteFileSchema, MAX_BATCH_CREATE_CASES, isOpaqueId } from '@mcpjam/sdk/contract';
14
+ import { MAX_BATCH_CREATE_CASES, evalSuiteFileSchema, isOpaqueId } from '@mcpjam/sdk/contract';
15
15
  import { HOST_TEMPLATES as HOST_TEMPLATES$1, HOST_TEMPLATE_IDS, seedHostTemplate } from '@mcpjam/sdk/host-config/templates';
16
16
  import http from 'http';
17
17
  import https from 'https';
@@ -27,7 +27,7 @@ import { PostHog } from 'posthog-node';
27
27
 
28
28
  // package.json
29
29
  var package_default = {
30
- version: "4.0.0"};
30
+ version: "4.2.0"};
31
31
  function conformanceExitCode(result) {
32
32
  if (result.outcome === "incomplete") return 3;
33
33
  if (result.outcome === "failed") return 1;
@@ -496,6 +496,10 @@ function renderConformanceReporterResult(result, reporter) {
496
496
  return JSON.stringify(renderConformanceReportJson(report));
497
497
  case "junit-xml":
498
498
  return renderConformanceReportJUnitXml(report);
499
+ case "html":
500
+ throw usageError(
501
+ 'The "html" reporter is not available for this command yet. Use "json-summary" or "junit-xml".'
502
+ );
499
503
  }
500
504
  }
501
505
  function renderConformanceForCli(result, reporter, format) {
@@ -579,11 +583,11 @@ function parseReporterFormat(value) {
579
583
  if (value === void 0) {
580
584
  return void 0;
581
585
  }
582
- if (value === "json-summary" || value === "junit-xml") {
586
+ if (value === "json-summary" || value === "junit-xml" || value === "html") {
583
587
  return value;
584
588
  }
585
589
  throw usageError(
586
- `Invalid reporter "${value}". Use "json-summary" or "junit-xml".`
590
+ `Invalid reporter "${value}". Use "json-summary", "junit-xml", or "html".`
587
591
  );
588
592
  }
589
593
  function writeReporterResult(reporter, report) {
@@ -591,6 +595,10 @@ function writeReporterResult(reporter, report) {
591
595
  process.stdout.write(renderStructuredRunJUnitXml(report));
592
596
  return;
593
597
  }
598
+ if (reporter === "html") {
599
+ process.stdout.write(renderStructuredRunHtml(report));
600
+ return;
601
+ }
594
602
  writeResult(renderStructuredRunJson(report), "json");
595
603
  }
596
604
  function writeEvalDecisionSummary(format, summary, destination = process.stdout) {
@@ -618,7 +626,7 @@ async function writeJsonArtifact(outputPath, payload) {
618
626
  }
619
627
  async function writeReporterArtifact(outputPath, reporter, report) {
620
628
  const resolvedPath = path7.resolve(process.cwd(), outputPath);
621
- const body = reporter === "junit-xml" ? renderStructuredRunJUnitXml(report) : `${JSON.stringify(renderStructuredRunJson(report), null, 2)}
629
+ const body = reporter === "junit-xml" ? renderStructuredRunJUnitXml(report) : reporter === "html" ? renderStructuredRunHtml(report) : `${JSON.stringify(renderStructuredRunJson(report), null, 2)}
622
630
  `;
623
631
  try {
624
632
  return await writeFileAtomic(resolvedPath, body, { createParents: true });
@@ -5128,23 +5136,6 @@ function percentToFraction(percent) {
5128
5136
  if (!Number.isFinite(value)) return null;
5129
5137
  return plainDecimal(value) === normalized ? value : null;
5130
5138
  }
5131
- function fractionToPercent(fraction) {
5132
- if (!Number.isFinite(fraction)) return null;
5133
- const text = plainDecimal(fraction);
5134
- const match = /^(-?)(\d+)(?:\.(\d+))?$/.exec(text);
5135
- if (!match) return null;
5136
- const [, sign, whole, decimals = ""] = match;
5137
- const digits = `${whole}${decimals}`;
5138
- const newPoint = whole.length + 2;
5139
- const padded = digits.padEnd(newPoint, "0");
5140
- const shifted = newPoint >= padded.length ? `${padded}.0` : `${padded.slice(0, newPoint)}.${padded.slice(newPoint)}`;
5141
- const stripped = `${sign}${shifted}`.replace(/^(-?)0+(?=\d)/, "$1").replace(/\.?0+$/, "");
5142
- const normalized = stripped === "" || stripped === "-" ? "0" : stripped;
5143
- const value = Number(normalized);
5144
- if (!Number.isFinite(value)) return null;
5145
- if (plainDecimal(value) !== normalized) return null;
5146
- return percentToFraction(value) === fraction ? value : null;
5147
- }
5148
5139
  function plainDecimal(value) {
5149
5140
  const text = value.toString();
5150
5141
  const match = /^(-?)(\d)(?:\.(\d+))?e-(\d+)$/.exec(text);
@@ -5588,6 +5579,8 @@ function fileCaseToCreateBody(testCase) {
5588
5579
  title: testCase.title,
5589
5580
  steps: testCase.steps,
5590
5581
  iterations: testCase.repetitions,
5582
+ repetitions: testCase.repetitions,
5583
+ passThreshold: testCase.passThreshold,
5591
5584
  ...testCase.expectedOutput !== void 0 ? { expectedOutput: testCase.expectedOutput } : {},
5592
5585
  ...testCase.isNegativeTest ? { isNegative: true } : {},
5593
5586
  models: fileCaseModels(testCase),
@@ -5599,6 +5592,8 @@ function fileCaseToUpdateBody(testCase) {
5599
5592
  title: testCase.title,
5600
5593
  steps: testCase.steps,
5601
5594
  iterations: testCase.repetitions,
5595
+ repetitions: testCase.repetitions,
5596
+ passThreshold: testCase.passThreshold,
5602
5597
  expectedOutput: testCase.expectedOutput ?? "",
5603
5598
  isNegative: testCase.isNegativeTest,
5604
5599
  models: fileCaseModels(testCase),
@@ -5622,26 +5617,6 @@ function refuseUnsupportedHostedSemantics(loaded) {
5622
5617
  SUITE_FILE_RUN_INVALID_EXIT_CODE
5623
5618
  );
5624
5619
  }
5625
- const validity = loaded.authored.defaults.validity;
5626
- if (validity.minEligibleTrials !== void 0 || validity.minCompletionRate !== void 0 || validity.maxEvaluatorErrorRate !== void 0) {
5627
- throw cliError(
5628
- "VALIDITY_UNSUPPORTED",
5629
- "defaults.validity sets a gate the hosted runner does not enforce (minEligibleTrials, minCompletionRate, or maxEvaluatorErrorRate). A run could be reported as a pass or fail when the file would call it INVALID. Leave validity as {} \u2014 or run the suite locally.",
5630
- SUITE_FILE_RUN_INVALID_EXIT_CODE
5631
- );
5632
- }
5633
- }
5634
- function refusePerCasePassThreshold(loaded) {
5635
- const suiteThreshold = loaded.resolved.defaults.passThreshold;
5636
- for (const testCase of loaded.resolved.enabledCases) {
5637
- if (testCase.passThreshold !== suiteThreshold) {
5638
- throw cliError(
5639
- "CASE_PASS_THRESHOLD",
5640
- `Hosted runs grade every case against the suite's defaults.passThreshold (${suiteThreshold}); case "${testCase.id}" overrides passThreshold to ${testCase.passThreshold}. The platform has no per-case pass threshold, so this file is refused rather than graded against a different bar than it declares.`,
5641
- SUITE_FILE_RUN_INVALID_EXIT_CODE
5642
- );
5643
- }
5644
- }
5645
5620
  }
5646
5621
  function refuseRepetitions(loaded) {
5647
5622
  const suiteReps = loaded.resolved.defaults.repetitions;
@@ -5841,7 +5816,7 @@ function deriveFileRunIdempotencyKey(params) {
5841
5816
  environments: params.knobs.environment ?? (params.fileEnvironment ? [params.fileEnvironment] : null),
5842
5817
  hosts: params.knobs.host ?? null,
5843
5818
  allTargets: params.knobs.allTargets === true,
5844
- iterations: params.knobs.iterations ?? null,
5819
+ repetitions: params.knobs.repetitions ?? params.knobs.iterations ?? null,
5845
5820
  cases: params.knobs.case ?? null,
5846
5821
  excludeSkills: params.knobs.excludeSkills === true,
5847
5822
  refreshSnapshot: params.knobs.refreshSnapshot === true,
@@ -5905,17 +5880,8 @@ async function executeEvalRunFromFile(context, params) {
5905
5880
  throw suiteFileLoadError(params.label, loaded);
5906
5881
  }
5907
5882
  refuseRepetitions(loaded);
5908
- refusePerCasePassThreshold(loaded);
5909
5883
  refuseEmptyEnabledSet(loaded);
5910
5884
  refuseUnsupportedHostedSemantics(loaded);
5911
- const passPercent = fractionToPercent(loaded.resolved.defaults.passThreshold);
5912
- if (passPercent === null) {
5913
- throw cliError(
5914
- "PASS_THRESHOLD",
5915
- `defaults.passThreshold ${loaded.resolved.defaults.passThreshold} cannot be converted to a hosted percent without losing a digit.`,
5916
- SUITE_FILE_RUN_INVALID_EXIT_CODE
5917
- );
5918
- }
5919
5885
  const sourceHash = sha256HexOfBuffer(params.source.buffer);
5920
5886
  const authored = loaded.authored;
5921
5887
  const servers = authored.target.servers ?? [];
@@ -5928,6 +5894,12 @@ async function executeEvalRunFromFile(context, params) {
5928
5894
  ...authored.suite.description !== void 0 ? { description: authored.suite.description } : {},
5929
5895
  sourceHash,
5930
5896
  ...authored.provenance ? { provenance: authored.provenance } : {},
5897
+ verdictPolicyVersion: 2,
5898
+ verdictPolicyDefaults: {
5899
+ repetitions: loaded.resolved.defaults.repetitions,
5900
+ passThreshold: loaded.resolved.defaults.passThreshold,
5901
+ validity: loaded.resolved.defaults.validity
5902
+ },
5931
5903
  environment: {
5932
5904
  servers: servers.map((server) => server.name),
5933
5905
  ...servers.some((server) => server.id) ? {
@@ -5941,8 +5913,7 @@ async function executeEvalRunFromFile(context, params) {
5941
5913
  modelId: authored.defaults.model,
5942
5914
  ...authored.defaults.systemPrompt !== void 0 ? { systemPrompt: authored.defaults.systemPrompt } : {},
5943
5915
  ...authored.defaults.temperature !== void 0 ? { temperature: authored.defaults.temperature } : {}
5944
- },
5945
- defaultPassCriteria: { minimumPassRate: passPercent }
5916
+ }
5946
5917
  }
5947
5918
  },
5948
5919
  { signal: context.signal }
@@ -6010,7 +5981,7 @@ async function executeEvalRunFromFile(context, params) {
6010
5981
  ...knobs.environment?.length === 1 ? { environment: knobs.environment[0] } : knobs.environment?.length ? { environments: knobs.environment } : fileEnvironment ? { environment: fileEnvironment } : {},
6011
5982
  ...knobs.host?.length === 1 ? { host: knobs.host[0] } : knobs.host?.length ? { hosts: knobs.host } : fileHosts?.length === 1 ? { host: fileHosts[0] } : fileHosts?.length ? { hosts: fileHosts } : {},
6012
5983
  ...knobs.allTargets ? { allAttached: true } : {},
6013
- ...knobs.iterations !== void 0 ? { iterations: knobs.iterations } : {},
5984
+ ...knobs.repetitions !== void 0 || knobs.iterations !== void 0 ? { repetitions: knobs.repetitions ?? knobs.iterations } : {},
6014
5985
  cases: runCases,
6015
5986
  ...knobs.excludeSkills ? { excludeSkills: true } : {},
6016
5987
  ...knobs.refreshSnapshot ? { refreshSnapshot: true } : {},
@@ -6019,7 +5990,12 @@ async function executeEvalRunFromFile(context, params) {
6019
5990
  ...knobs.matchOptions ? { matchOptions: knobs.matchOptions } : {},
6020
5991
  ...knobs.compose ? { compose: knobs.compose } : {}
6021
5992
  },
6022
- { client: context.client, signal: context.signal }
5993
+ {
5994
+ client: context.client,
5995
+ signal: context.signal,
5996
+ onDisclosure: context.onDisclosure,
5997
+ onDisclosureUnavailable: context.onDisclosureUnavailable
5998
+ }
6023
5999
  );
6024
6000
  }
6025
6001
  var DEFAULT_CORPUS_LOCK_PATH = "mcpjam-evals.lock.json";
@@ -6224,94 +6200,11 @@ var NON_VERDICT_STATUSES = /* @__PURE__ */ new Set(["cancelled", "timed_out", "f
6224
6200
  function isNonVerdictRunStatus(status) {
6225
6201
  return status !== void 0 && NON_VERDICT_STATUSES.has(status);
6226
6202
  }
6203
+ function isNonVerdictRunResult(result) {
6204
+ return result === "inconclusive";
6205
+ }
6227
6206
  var EVAL_GATE_INCOMPLETE_EXIT_CODE = 3;
6228
6207
  var EVAL_GATE_USAGE_EXIT_CODE = 2;
6229
- function parsePercent(raw, flag) {
6230
- const value = raw.trim() === "" ? NaN : Number(raw);
6231
- if (!Number.isFinite(value) || value < 0 || value > 100) {
6232
- throw usageError(`${flag} must be a number between 0 and 100, got "${raw}".`);
6233
- }
6234
- return passRateFractionFromPercent(value);
6235
- }
6236
- function parseScorerMap(entries, flag, parseValue) {
6237
- const out = /* @__PURE__ */ Object.create(null);
6238
- for (const entry of entries) {
6239
- const index = entry.indexOf("=");
6240
- if (index <= 0) {
6241
- throw usageError(`${flag} must be <scorerId>=<value>, got "${entry}".`);
6242
- }
6243
- const scorerId = entry.slice(0, index).trim();
6244
- if (!scorerId) {
6245
- throw usageError(`${flag} is missing a scorer id in "${entry}".`);
6246
- }
6247
- if (Object.prototype.hasOwnProperty.call(out, scorerId)) {
6248
- throw usageError(
6249
- `${flag} names "${scorerId}" more than once; pass one threshold per scorer.`
6250
- );
6251
- }
6252
- out[scorerId] = parseValue(entry.slice(index + 1).trim(), flag);
6253
- }
6254
- return out;
6255
- }
6256
- function parseUnit(raw, flag) {
6257
- const value = raw.trim() === "" ? NaN : Number(raw);
6258
- if (!Number.isFinite(value) || value < 0 || value > 1) {
6259
- throw usageError(`${flag} must be a number between 0 and 1, got "${raw}".`);
6260
- }
6261
- return value;
6262
- }
6263
- function policyFromOptions(options) {
6264
- const policy = {};
6265
- if (options.minPassRatePercent !== void 0) {
6266
- policy.minimumPassRate = parsePercent(
6267
- options.minPassRatePercent,
6268
- "--min-pass-rate-percent"
6269
- );
6270
- }
6271
- if (options.noGatingScoreErrors) policy.noGatingScoreErrors = true;
6272
- if (options.minScorerPassRate?.length) {
6273
- policy.minimumScorerPassRate = parseScorerMap(
6274
- options.minScorerPassRate,
6275
- "--min-scorer-pass-rate",
6276
- parsePercent
6277
- );
6278
- }
6279
- if (options.minMeanScore?.length) {
6280
- policy.minimumMeanScore = parseScorerMap(
6281
- options.minMeanScore,
6282
- "--min-mean-score",
6283
- parseUnit
6284
- );
6285
- }
6286
- return policy;
6287
- }
6288
- function policyNeedsIterations(policy) {
6289
- return Boolean(
6290
- policy.noGatingScoreErrors || policy.minimumScorerPassRate || policy.minimumMeanScore || policy.maximumTotalTokens !== void 0 || // p95 comes from iteration durations, exactly like tokens come from
6291
- // iteration counts. Omitting it here would leave the latency gate
6292
- // permanently non-gateable — the fetch that could decide it never runs.
6293
- policy.maximumP95LatencyMs !== void 0
6294
- );
6295
- }
6296
- function reportForRun(run, iterations, policy) {
6297
- return evaluateGates(gateInputFromPlatformRun(run, iterations), policy);
6298
- }
6299
-
6300
- // src/lib/eval-iterations.ts
6301
- async function fetchAllIterations(client, signal, projectId, runId) {
6302
- const items = [];
6303
- let cursor;
6304
- for (let page = 0; page < 100; page += 1) {
6305
- const result = await client.listEvalRunIterations(
6306
- { projectId, runId, ...cursor ? { cursor } : {}, limit: 200 },
6307
- { signal }
6308
- );
6309
- items.push(...result.items);
6310
- if (!result.nextCursor) return { items, complete: true };
6311
- cursor = result.nextCursor;
6312
- }
6313
- return { items, complete: false };
6314
- }
6315
6208
 
6316
6209
  // src/lib/eval-compare.ts
6317
6210
  function parseNonNegativeInteger2(raw, flag) {
@@ -6437,6 +6330,374 @@ function flakyInputFrom(iterations) {
6437
6330
  passed: iteration.result === "passed"
6438
6331
  }));
6439
6332
  }
6333
+ async function fetchAllIterations(client, signal, projectId, runId) {
6334
+ const items = [];
6335
+ let cursor;
6336
+ for (let page = 0; page < 100; page += 1) {
6337
+ const result = await client.listEvalRunIterations(
6338
+ { projectId, runId, ...cursor ? { cursor } : {}, limit: 200 },
6339
+ { signal }
6340
+ );
6341
+ items.push(...result.items);
6342
+ if (!result.nextCursor) return { items, complete: true };
6343
+ cursor = result.nextCursor;
6344
+ }
6345
+ return { items, complete: false };
6346
+ }
6347
+ function p95Of(iterations) {
6348
+ if (!iterations?.complete) return void 0;
6349
+ const durations = iterations.items.map((iteration) => iteration.durationMs).filter((ms) => typeof ms === "number");
6350
+ if (durations.length === 0 || durations.length !== iterations.items.length) {
6351
+ return void 0;
6352
+ }
6353
+ return calculateLatencyStats(durations).p95;
6354
+ }
6355
+
6356
+ // src/lib/eval-gate.ts
6357
+ function parsePercent(raw, flag) {
6358
+ const value = raw.trim() === "" ? NaN : Number(raw);
6359
+ if (!Number.isFinite(value) || value < 0 || value > 100) {
6360
+ throw usageError(`${flag} must be a number between 0 and 100, got "${raw}".`);
6361
+ }
6362
+ return passRateFractionFromPercent(value);
6363
+ }
6364
+ function parseScorerMap(entries, flag, parseValue) {
6365
+ const out = /* @__PURE__ */ Object.create(null);
6366
+ for (const entry of entries) {
6367
+ const index = entry.indexOf("=");
6368
+ if (index <= 0) {
6369
+ throw usageError(`${flag} must be <scorerId>=<value>, got "${entry}".`);
6370
+ }
6371
+ const scorerId = entry.slice(0, index).trim();
6372
+ if (!scorerId) {
6373
+ throw usageError(`${flag} is missing a scorer id in "${entry}".`);
6374
+ }
6375
+ if (Object.prototype.hasOwnProperty.call(out, scorerId)) {
6376
+ throw usageError(
6377
+ `${flag} names "${scorerId}" more than once; pass one threshold per scorer.`
6378
+ );
6379
+ }
6380
+ out[scorerId] = parseValue(entry.slice(index + 1).trim(), flag);
6381
+ }
6382
+ return out;
6383
+ }
6384
+ function parseUnit(raw, flag) {
6385
+ const value = raw.trim() === "" ? NaN : Number(raw);
6386
+ if (!Number.isFinite(value) || value < 0 || value > 1) {
6387
+ throw usageError(`${flag} must be a number between 0 and 1, got "${raw}".`);
6388
+ }
6389
+ return value;
6390
+ }
6391
+ function policyFromOptions(options) {
6392
+ const policy = {};
6393
+ if (options.minPassRatePercent !== void 0) {
6394
+ policy.minimumPassRate = parsePercent(
6395
+ options.minPassRatePercent,
6396
+ "--min-pass-rate-percent"
6397
+ );
6398
+ }
6399
+ if (options.noGatingScoreErrors) policy.noGatingScoreErrors = true;
6400
+ if (options.minScorerPassRate?.length) {
6401
+ policy.minimumScorerPassRate = parseScorerMap(
6402
+ options.minScorerPassRate,
6403
+ "--min-scorer-pass-rate",
6404
+ parsePercent
6405
+ );
6406
+ }
6407
+ if (options.minMeanScore?.length) {
6408
+ policy.minimumMeanScore = parseScorerMap(
6409
+ options.minMeanScore,
6410
+ "--min-mean-score",
6411
+ parseUnit
6412
+ );
6413
+ }
6414
+ return policy;
6415
+ }
6416
+ function policyNeedsIterations(policy) {
6417
+ return Boolean(
6418
+ policy.noGatingScoreErrors || policy.minimumScorerPassRate || policy.minimumMeanScore || policy.maximumTotalTokens !== void 0 || // p95 comes from iteration durations, exactly like tokens come from
6419
+ // iteration counts. Omitting it here would leave the latency gate
6420
+ // permanently non-gateable — the fetch that could decide it never runs.
6421
+ policy.maximumP95LatencyMs !== void 0
6422
+ );
6423
+ }
6424
+ function reportForRun(run, iterations, policy) {
6425
+ return evaluateGates(gateInputFromPlatformRun(run, iterations), policy);
6426
+ }
6427
+ var SHA_LIKE_BASELINE = /^[0-9a-f]{40}$/i;
6428
+ function assertRunIdBaseline(baseline, runId) {
6429
+ const normalized = baseline.trim();
6430
+ if (normalized === "") {
6431
+ throw usageError(
6432
+ `--baseline must not be blank. Pass a run id, or omit the flag entirely to gate on absolute thresholds only.`
6433
+ );
6434
+ }
6435
+ if (normalized === runId) {
6436
+ throw usageError(
6437
+ `--baseline "${baseline}" is the same as --run "${runId}". A run cannot be its own baseline \u2014 pass a different, earlier run id.`
6438
+ );
6439
+ }
6440
+ if (SHA_LIKE_BASELINE.test(normalized)) {
6441
+ throw usageError(
6442
+ `--baseline "${baseline}" looks like a git SHA. SHA baselines are not supported yet; pass a run id. (Source-SHA baseline resolution is a follow-up step, gated on a backend index that does not exist yet.)`
6443
+ );
6444
+ }
6445
+ return normalized;
6446
+ }
6447
+ function comparePolicyFromGateOptions(options) {
6448
+ const hasComparativeFlag = options.minSampleSize !== void 0 || options.minEffectSizePercent !== void 0 || options.gateDeterministicRegressions === true || options.maxP95LatencyIncreaseMs !== void 0;
6449
+ if (hasComparativeFlag && !options.baseline) {
6450
+ throw usageError(
6451
+ "--min-sample-size, --min-effect-size-percent, --gate-deterministic-regressions, and --max-p95-latency-increase-ms tune the baseline regression gate; pass --baseline to enable it."
6452
+ );
6453
+ }
6454
+ return comparePolicyFromOptions({
6455
+ gateRegressions: Boolean(options.baseline),
6456
+ minSampleSize: options.minSampleSize,
6457
+ minEffectSizePercent: options.minEffectSizePercent,
6458
+ gateDeterministicRegressions: options.gateDeterministicRegressions,
6459
+ maxP95LatencyIncreaseMs: options.maxP95LatencyIncreaseMs
6460
+ });
6461
+ }
6462
+ function baselineNotFoundReason(error) {
6463
+ const details = error?.details;
6464
+ return typeof details === "object" && details !== null && details.reason === "BASELINE_NOT_FOUND";
6465
+ }
6466
+ var OUTCOME_RANK = {
6467
+ passed: 0,
6468
+ incomplete: 1,
6469
+ failed: 2,
6470
+ usage_error: 3
6471
+ };
6472
+ function mergeGateReports(threshold, comparative) {
6473
+ return {
6474
+ outcome: OUTCOME_RANK[comparative.outcome] > OUTCOME_RANK[threshold.outcome] ? comparative.outcome : threshold.outcome,
6475
+ verdicts: [...threshold.verdicts, ...comparative.verdicts],
6476
+ // The run being gated IS the compare side of the baseline comparison, so
6477
+ // its own score integrity — already computed by `evaluateGates` above —
6478
+ // is the one meaning that survives the merge. The comparison's own
6479
+ // (base+compare) combined integrity is recorded separately in the
6480
+ // baseline provenance, not lost.
6481
+ scoreIntegrity: threshold.scoreIntegrity
6482
+ };
6483
+ }
6484
+ function incompatibilityReasonsFor(row, runEvaluationConfigChanged) {
6485
+ const reasons = [];
6486
+ if (row.status === "new_case") reasons.push("case_added");
6487
+ if (row.status === "removed_case") reasons.push("case_removed");
6488
+ if (row.configChanged) reasons.push("scenario_config_changed");
6489
+ if (row.evaluationConfigChanged || runEvaluationConfigChanged) {
6490
+ reasons.push("evaluation_config_changed");
6491
+ }
6492
+ if (row.base.outcome !== "absent" && row.compare.outcome !== "absent" && row.base.iterationIds.length !== row.compare.iterationIds.length) {
6493
+ reasons.push("iteration_weighting_unequal");
6494
+ }
6495
+ return reasons;
6496
+ }
6497
+ function buildBaselineProvenance(requestedBaseline, compare, input, policy) {
6498
+ const classified = compare.cases.map((row) => ({
6499
+ row,
6500
+ reasons: incompatibilityReasonsFor(
6501
+ row,
6502
+ compare.scoreContract.evaluationConfigChanged
6503
+ )
6504
+ }));
6505
+ return {
6506
+ requestedBaseline,
6507
+ baseline: compare.baseline,
6508
+ baseRunId: compare.baseRun.id,
6509
+ compareRunId: compare.compareRun.id,
6510
+ // The RESOLVED policy that produced this verdict, defaults filled in —
6511
+ // an archived report must be self-describing without cross-referencing
6512
+ // the CLI invocation that produced it. `null` means the gate was not
6513
+ // asked for, not "asked for with a threshold of nothing".
6514
+ policy: {
6515
+ passRateRegression: policy.passRateRegression ? {
6516
+ minSampleSize: policy.passRateRegression.minSampleSize ?? DEFAULT_MIN_SAMPLE_SIZE,
6517
+ minEffectSize: policy.passRateRegression.minEffectSize ?? DEFAULT_MIN_EFFECT_SIZE
6518
+ } : null,
6519
+ noDeterministicRegressions: policy.noDeterministicRegressions === true,
6520
+ maximumP95LatencyIncreaseMs: policy.maximumP95LatencyIncreaseMs ?? null
6521
+ },
6522
+ compatibility: {
6523
+ caseSetChanged: input.caseSetChanged,
6524
+ scenarioConfigChanged: input.scenarioConfigChanged,
6525
+ evaluationConfigChanged: input.evaluationConfigChanged,
6526
+ iterationWeightingEqual: input.iterationWeightingEqual,
6527
+ baseScoreIntegrity: compare.scoreContract.base.scoreIntegrity,
6528
+ compareScoreIntegrity: compare.scoreContract.compare.scoreIntegrity,
6529
+ // The pin names "comparable case ids" explicitly: which cases an
6530
+ // archived report's verdict actually covers, and which ones a
6531
+ // `caseSetChanged: true` flag alone does not name.
6532
+ comparableCaseIds: classified.filter(({ reasons }) => reasons.length === 0).map(({ row }) => row.caseKey),
6533
+ incompatibleCases: classified.filter(({ reasons }) => reasons.length > 0).map(({ row, reasons }) => ({
6534
+ caseKey: row.caseKey,
6535
+ status: row.status,
6536
+ reasons
6537
+ }))
6538
+ },
6539
+ // Dimensions the pinned contract requires but the `/compare` wire does
6540
+ // not carry today (E4b / backend follow-up work). Never invented, never
6541
+ // silently dropped.
6542
+ notRecorded: {
6543
+ modelProvider: "notRecorded",
6544
+ hostHarness: "notRecorded",
6545
+ serverEnvironmentIdentity: "notRecorded",
6546
+ configHashesBeyondEvaluationConfigHash: "notRecorded"
6547
+ }
6548
+ };
6549
+ }
6550
+ async function evaluateBaselineComparison(input) {
6551
+ let compare;
6552
+ try {
6553
+ compare = await input.client.compareEvalRun(
6554
+ {
6555
+ projectId: input.projectId,
6556
+ runId: input.runId,
6557
+ baseRunId: input.baseline
6558
+ },
6559
+ { signal: input.signal }
6560
+ );
6561
+ } catch (error) {
6562
+ const reason = baselineNotFoundReason(error);
6563
+ const detail = error instanceof Error ? error.message : String(error);
6564
+ return {
6565
+ report: {
6566
+ outcome: "incomplete",
6567
+ scoreIntegrity: "unknown",
6568
+ verdicts: [
6569
+ {
6570
+ gate: "baseline",
6571
+ status: "non_gateable",
6572
+ message: reason ? `no baseline to compare against: ${detail}` : `could not compare against the baseline: ${detail}`
6573
+ }
6574
+ ]
6575
+ }
6576
+ };
6577
+ }
6578
+ if (compare.baseRun.completedAt === null || compare.compareRun.completedAt === null) {
6579
+ return {
6580
+ report: {
6581
+ outcome: "incomplete",
6582
+ scoreIntegrity: "unknown",
6583
+ verdicts: [
6584
+ {
6585
+ gate: "baseline",
6586
+ status: "non_gateable",
6587
+ message: "both runs must be completed before they can be compared"
6588
+ }
6589
+ ]
6590
+ }
6591
+ };
6592
+ }
6593
+ const needsLatency = input.policy.maximumP95LatencyIncreaseMs !== void 0;
6594
+ let baseIterations;
6595
+ let compareIterationsForLatency = input.compareIterations;
6596
+ if (needsLatency) {
6597
+ try {
6598
+ [baseIterations, compareIterationsForLatency] = await Promise.all([
6599
+ fetchAllIterations(
6600
+ input.client,
6601
+ input.signal,
6602
+ input.projectId,
6603
+ compare.baseRun.id
6604
+ ),
6605
+ input.compareIterations ?? fetchAllIterations(
6606
+ input.client,
6607
+ input.signal,
6608
+ input.projectId,
6609
+ compare.compareRun.id
6610
+ )
6611
+ ]);
6612
+ } catch {
6613
+ baseIterations = void 0;
6614
+ compareIterationsForLatency = void 0;
6615
+ }
6616
+ }
6617
+ const compareInput = compareGateInputFrom(compare, {
6618
+ baseP95Ms: p95Of(baseIterations),
6619
+ compareP95Ms: p95Of(compareIterationsForLatency)
6620
+ });
6621
+ return {
6622
+ report: evaluateCompareGates(compareInput, input.policy),
6623
+ provenance: buildBaselineProvenance(
6624
+ input.baseline,
6625
+ compare,
6626
+ compareInput,
6627
+ input.policy
6628
+ )
6629
+ };
6630
+ }
6631
+
6632
+ // src/lib/eval-run-exit-code.ts
6633
+ var SEVERITY_ORDER = [1, 3, 4, 5, 0];
6634
+ function worstOf(codes) {
6635
+ for (const code of SEVERITY_ORDER) {
6636
+ if (codes.includes(code)) return code;
6637
+ }
6638
+ return 0;
6639
+ }
6640
+ function runExitCode(run) {
6641
+ const codes = [];
6642
+ if (isNonVerdictRunStatus(run.status)) {
6643
+ codes.push(5);
6644
+ } else if (isNonVerdictRunResult(run.result)) {
6645
+ codes.push(5);
6646
+ } else if (run.result === "failed") {
6647
+ codes.push(1);
6648
+ } else if (run.result === "passed") {
6649
+ codes.push(0);
6650
+ } else {
6651
+ codes.push(5);
6652
+ }
6653
+ if (run.reportingFailed) {
6654
+ codes.push(classifyWaitErrorExitCode(run.reportingFailedErrorCode));
6655
+ }
6656
+ return worstOf(codes);
6657
+ }
6658
+ function evalRunWaitExitCode(input) {
6659
+ const codes = [];
6660
+ if (input.launchOutcome !== "started") {
6661
+ codes.push(4);
6662
+ }
6663
+ for (const run of input.runs) {
6664
+ codes.push(runExitCode(run));
6665
+ }
6666
+ for (const waitError of input.waitErrors) {
6667
+ codes.push(classifyWaitErrorExitCode(waitError.errorCode));
6668
+ }
6669
+ return worstOf(codes);
6670
+ }
6671
+ var AUTH_SHAPED_CODES = /* @__PURE__ */ new Set([
6672
+ "UNAUTHORIZED",
6673
+ "FORBIDDEN",
6674
+ "OAUTH_REQUIRED"
6675
+ ]);
6676
+ var INVALID_SHAPED_CODES = /* @__PURE__ */ new Set([
6677
+ "VALIDATION_ERROR",
6678
+ "NOT_FOUND",
6679
+ "CONFLICT",
6680
+ "UNSUPPORTED"
6681
+ ]);
6682
+ var BILLING_SHAPED_DETAIL_CODES = /* @__PURE__ */ new Set([
6683
+ "billing_limit_reached",
6684
+ "billing_feature_not_included"
6685
+ ]);
6686
+ function isBillingShapedDetail(details) {
6687
+ if (!details || typeof details !== "object") return false;
6688
+ const inner = details.code;
6689
+ return typeof inner === "string" && BILLING_SHAPED_DETAIL_CODES.has(inner);
6690
+ }
6691
+ function classifyLaunchErrorExitCode(code, details) {
6692
+ if (isBillingShapedDetail(details)) return 4;
6693
+ if (code !== void 0 && AUTH_SHAPED_CODES.has(code)) return 3;
6694
+ if (code !== void 0 && INVALID_SHAPED_CODES.has(code)) return 2;
6695
+ return 4;
6696
+ }
6697
+ function classifyWaitErrorExitCode(code) {
6698
+ if (code !== void 0 && AUTH_SHAPED_CODES.has(code)) return 3;
6699
+ return 5;
6700
+ }
6440
6701
 
6441
6702
  // src/lib/terminal-image.ts
6442
6703
  var ESC = "\x1B";
@@ -6584,6 +6845,67 @@ function writeRunGroupSummary(format, webOrigin, result) {
6584
6845
  );
6585
6846
  }
6586
6847
  }
6848
+ function writeRunDisclosure(format, disclosure, stream = process.stdout) {
6849
+ if (format !== "human" || !disclosure) return;
6850
+ const lines = ["Pre-run disclosure:"];
6851
+ if (disclosure.execution) {
6852
+ const execution = disclosure.execution;
6853
+ const locus = execution.locus.known === true ? execution.locus.hosted ? "MCPJam-hosted" : "your own machine" : "unknown";
6854
+ lines.push(` Execution: ${execution.engine} \xB7 ${locus}`);
6855
+ if (execution.models.length > 0) {
6856
+ for (const model of execution.models) {
6857
+ const destination = model.byok?.baseUrlHost ? model.byok.baseUrlHost : model.rail.managed ? `${model.rail.possibleDestinations.join(" or ")} (currently: ${model.rail.outcomeIfRunNow.destination})` : model.tenantEgress;
6858
+ lines.push(` Model: ${model.modelId} \u2014 ${destination}`);
6859
+ }
6860
+ } else if (execution.modelsUnresolved) {
6861
+ lines.push(` Models: not derivable \u2014 ${execution.modelsUnresolved.reason}`);
6862
+ }
6863
+ if (execution.sandbox.engaged) {
6864
+ lines.push(` Sandbox: engaged (${execution.sandbox.vendor ?? "?"})`);
6865
+ }
6866
+ } else if (disclosure.executionAbsence) {
6867
+ const { kind, reason } = disclosure.executionAbsence;
6868
+ lines.push(
6869
+ kind === "ingested-run" ? ` Execution: none \u2014 this run was ingested, MCPJam did not execute it (${reason})` : ` Execution: not yet resolved \u2014 this run WILL execute and WILL call models, they are just not derivable yet (${reason})`
6870
+ );
6871
+ }
6872
+ lines.push(
6873
+ ` Capture: ${disclosure.capture.captureLevel} \xB7 reporting ${disclosure.capture.reportingMode}`
6874
+ );
6875
+ lines.push(
6876
+ ` Redaction: ${disclosure.capture.redaction.kind}` + (disclosure.capture.redaction.isDlp ? "" : ` \u2014 NOT a DLP system (${disclosure.capture.redaction.limitation})`)
6877
+ );
6878
+ lines.push(
6879
+ ` Export defaults: ${disclosure.capture.exportDefaults.includeContent ? "includes content" : "excludes content"} (${disclosure.capture.exportDefaults.note})`
6880
+ );
6881
+ const firingAnalysis = disclosure.analysis.filter(
6882
+ (touchpoint) => typeof touchpoint.fires === "string"
6883
+ );
6884
+ if (firingAnalysis.length > 0) {
6885
+ for (const touchpoint of firingAnalysis) {
6886
+ const firesLabel = touchpoint.fires === "auto-on-completion" ? "fires automatically on completion" : "fires only if explicitly requested";
6887
+ lines.push(
6888
+ ` Analysis: ${touchpoint.label} ${firesLabel}, may send evidence to ${touchpoint.destinations.join(", ")}`
6889
+ );
6890
+ }
6891
+ } else {
6892
+ lines.push(" Analysis: no analyzer/judge touchpoint can fire for this run");
6893
+ }
6894
+ lines.push(
6895
+ disclosure.retention.effectiveToday === "kept-indefinitely" ? " Retention: kept indefinitely" : ` Retention: swept after ${disclosure.retention.policyDays ?? "?"} day(s)`
6896
+ );
6897
+ lines.push(
6898
+ disclosure.region.stated ? ` Region: ${disclosure.region.value}` : " Region: not stated"
6899
+ );
6900
+ const engaged = disclosure.subprocessors.filter((entry) => entry.engaged);
6901
+ if (engaged.length > 0) {
6902
+ lines.push(
6903
+ ` Subprocessors: ${engaged.map((entry) => entry.vendor).join(", ")}`
6904
+ );
6905
+ }
6906
+ stream.write(`${lines.join("\n")}
6907
+ `);
6908
+ }
6587
6909
  function writeRunLink(format, webOrigin, run) {
6588
6910
  if (format !== "human") return;
6589
6911
  const suiteId = run.suiteId?.trim();
@@ -6919,17 +7241,27 @@ function launchFailureCases(result) {
6919
7241
  ];
6920
7242
  });
6921
7243
  }
6922
- function gateReportCase(report) {
7244
+ function gateReportCase(report, baselineProvenance) {
6923
7245
  const passed = report.outcome === "passed";
6924
7246
  return {
6925
7247
  id: "gate",
6926
7248
  title: "Eval gate",
6927
7249
  category: "gate",
6928
7250
  passed,
7251
+ // Only a real FAILED gate is a confirmed regression. `incomplete` and
7252
+ // `usage_error` still fail this row (nothing was established either
7253
+ // way), but reporting them as `breaking` — the same class a genuine
7254
+ // failure gets — would claim a defect the run never observed. Mirrors
7255
+ // `gateCase` in sdk/src/run-compare.ts.
7256
+ classification: report.outcome === "failed" ? "breaking" : passed ? "non_breaking" : "informational",
6929
7257
  ...passed ? {} : {
6930
7258
  error: report.verdicts.filter((verdict) => verdict.status !== "passed").map((verdict) => verdict.message).join("; ")
6931
7259
  },
6932
- details: report
7260
+ // The baseline provenance rides along on the case row too, not only in
7261
+ // the report's top-level metadata: `--reporter junit-xml` has no other
7262
+ // place to carry it, and a regression visible in the exit code but
7263
+ // absent from the artifact is a reporting bug.
7264
+ details: baselineProvenance ? { ...report, baseline: baselineProvenance } : report
6933
7265
  };
6934
7266
  }
6935
7267
  var DEFAULT_GATE_WAIT_TIMEOUT_MS = 6e5;
@@ -6941,6 +7273,8 @@ async function runEvalGate(options, command) {
6941
7273
  ...options,
6942
7274
  noGatingScoreErrors: options.gatingScoreErrors === false
6943
7275
  });
7276
+ const baseline = options.baseline !== void 0 ? assertRunIdBaseline(options.baseline, options.run) : void 0;
7277
+ const comparePolicy = comparePolicyFromGateOptions(options);
6944
7278
  const waitTimeoutMs = options.waitTimeout !== void 0 ? parsePositiveInteger(options.waitTimeout, "--wait-timeout") : DEFAULT_GATE_WAIT_TIMEOUT_MS;
6945
7279
  const resolved = resolveCloudProjectArgs(options);
6946
7280
  let decisionSummary;
@@ -7014,7 +7348,7 @@ async function runEvalGate(options, command) {
7014
7348
  iterationError = error instanceof Error ? error.message : String(error);
7015
7349
  }
7016
7350
  }
7017
- if (isNonVerdictRunStatus(run.status)) {
7351
+ if (isNonVerdictRunStatus(run.status) || isNonVerdictRunResult(run.result)) {
7018
7352
  return {
7019
7353
  report: {
7020
7354
  outcome: "incomplete",
@@ -7023,7 +7357,7 @@ async function runEvalGate(options, command) {
7023
7357
  {
7024
7358
  gate: "run",
7025
7359
  status: "non_gateable",
7026
- message: `run is ${run.status}; no verdict was established`
7360
+ message: isNonVerdictRunResult(run.result) ? "run is inconclusive; no verdict was established" : `run is ${run.status}; no verdict was established`
7027
7361
  }
7028
7362
  ]
7029
7363
  },
@@ -7044,34 +7378,47 @@ async function runEvalGate(options, command) {
7044
7378
  }
7045
7379
  );
7046
7380
  }
7047
- if (iterationError) {
7381
+ const thresholdReport = iterationError ? {
7382
+ outcome: "incomplete",
7383
+ scoreIntegrity: "unknown",
7384
+ verdicts: [
7385
+ {
7386
+ gate: "fetch",
7387
+ status: "non_gateable",
7388
+ message: `could not read the run: ${iterationError}`
7389
+ }
7390
+ ]
7391
+ } : reportForRun(
7392
+ run,
7393
+ policyNeedsIterations(policy) ? iterations : void 0,
7394
+ policy
7395
+ );
7396
+ const iterationsComplete = iterationError ? false : iterations?.complete ?? !needsReport;
7397
+ if (!baseline) {
7048
7398
  return {
7049
- report: {
7050
- outcome: "incomplete",
7051
- scoreIntegrity: "unknown",
7052
- verdicts: [
7053
- {
7054
- gate: "fetch",
7055
- status: "non_gateable",
7056
- message: `could not read the run: ${iterationError}`
7057
- }
7058
- ]
7059
- },
7399
+ report: thresholdReport,
7060
7400
  run,
7061
- iterations: [],
7062
- iterationsComplete: false,
7063
- iterationError
7401
+ iterations: iterations?.items ?? [],
7402
+ iterationsComplete,
7403
+ ...iterationError ? { iterationError } : {}
7064
7404
  };
7065
7405
  }
7406
+ const baselineResult = await evaluateBaselineComparison({
7407
+ client,
7408
+ signal,
7409
+ projectId: project.id,
7410
+ runId: options.run,
7411
+ baseline,
7412
+ policy: comparePolicy,
7413
+ compareIterations: iterations
7414
+ });
7066
7415
  return {
7067
- report: reportForRun(
7068
- run,
7069
- policyNeedsIterations(policy) ? iterations : void 0,
7070
- policy
7071
- ),
7416
+ report: mergeGateReports(thresholdReport, baselineResult.report),
7072
7417
  run,
7073
7418
  iterations: iterations?.items ?? [],
7074
- iterationsComplete: iterations?.complete ?? !needsReport
7419
+ iterationsComplete,
7420
+ ...iterationError ? { iterationError } : {},
7421
+ ...baselineResult.provenance ? { baselineProvenance: baselineResult.provenance } : {}
7075
7422
  };
7076
7423
  }
7077
7424
  );
@@ -7080,23 +7427,36 @@ async function runEvalGate(options, command) {
7080
7427
  throw error;
7081
7428
  }
7082
7429
  const detail = error instanceof Error ? error.message : String(error);
7083
- writeResult(
7084
- {
7085
- gate: {
7086
- outcome: "incomplete",
7087
- scoreIntegrity: "unknown",
7088
- verdicts: [
7089
- {
7090
- gate: "fetch",
7091
- status: "non_gateable",
7092
- message: `could not read the run: ${detail}`
7093
- }
7094
- ]
7095
- },
7096
- exitCode: EVAL_GATE_INCOMPLETE_EXIT_CODE
7097
- },
7098
- globalOptions.format
7099
- );
7430
+ const report = {
7431
+ outcome: "incomplete",
7432
+ scoreIntegrity: "unknown",
7433
+ verdicts: [
7434
+ {
7435
+ gate: "fetch",
7436
+ status: "non_gateable",
7437
+ message: `could not read the run: ${detail}`
7438
+ }
7439
+ ]
7440
+ };
7441
+ const structured2 = needsReport ? buildEvalRunReport([], {
7442
+ cases: [gateReportCase(report)],
7443
+ verdict: gateOutcomeVerdict(report.outcome)
7444
+ }) : void 0;
7445
+ if (options.out && structured2) {
7446
+ await writeReporterArtifact(
7447
+ options.out,
7448
+ reporter ?? "json-summary",
7449
+ structured2
7450
+ );
7451
+ }
7452
+ if (reporter && structured2) {
7453
+ writeReporterResult(reporter, structured2);
7454
+ } else {
7455
+ writeResult(
7456
+ { gate: report, exitCode: EVAL_GATE_INCOMPLETE_EXIT_CODE },
7457
+ globalOptions.format
7458
+ );
7459
+ }
7100
7460
  setProcessExitCode(EVAL_GATE_INCOMPLETE_EXIT_CODE);
7101
7461
  return;
7102
7462
  }
@@ -7111,8 +7471,10 @@ async function runEvalGate(options, command) {
7111
7471
  }
7112
7472
  ] : [],
7113
7473
  {
7114
- cases: [gateReportCase(outcome.report)],
7115
- ...decisionSummary ? { decisionSummary } : {}
7474
+ cases: [gateReportCase(outcome.report, outcome.baselineProvenance)],
7475
+ verdict: gateOutcomeVerdict(outcome.report.outcome),
7476
+ ...decisionSummary ? { decisionSummary } : {},
7477
+ ...outcome.baselineProvenance ? { metadata: { baselineComparison: outcome.baselineProvenance } } : {}
7116
7478
  }
7117
7479
  ) : void 0;
7118
7480
  if (options.out && structured) {
@@ -7429,21 +7791,9 @@ var EMPTY_DIFF = {
7429
7791
  delta: null,
7430
7792
  percentDelta: null
7431
7793
  };
7432
- function p95Of(iterations) {
7433
- if (!iterations?.complete) return void 0;
7434
- const durations = iterations.items.map((iteration) => iteration.durationMs).filter((ms) => typeof ms === "number");
7435
- if (durations.length === 0 || durations.length !== iterations.items.length) {
7436
- return void 0;
7437
- }
7438
- return calculateLatencyStats(durations).p95;
7439
- }
7440
- function baselineNotFoundReason(error) {
7441
- const details = error?.details;
7442
- return typeof details === "object" && details !== null && details.reason === "BASELINE_NOT_FOUND";
7443
- }
7444
7794
  async function writeCompareResult(args, structured) {
7445
7795
  if (args.out && structured) {
7446
- await writeJsonArtifact(args.out, structured);
7796
+ await writeReporterArtifact(args.out, args.reporter ?? "json-summary", structured);
7447
7797
  }
7448
7798
  if (args.reporter && structured) {
7449
7799
  writeReporterResult(args.reporter, structured);
@@ -7707,9 +8057,13 @@ function registerEvalCommands(program) {
7707
8057
  ).option(
7708
8058
  "--all-targets",
7709
8059
  "Run EVERY attached environment (or, if none, every attached host) \u2014 one PAID RUN per target"
8060
+ ).option(
8061
+ "--repetitions <n>",
8062
+ "Run each case this many times under verdict policy 2 (1-10)",
8063
+ (v) => parseIntOption(v, "--repetitions")
7710
8064
  ).option(
7711
8065
  "--iterations <n>",
7712
- "Run each case this many times (1-10)",
8066
+ "Deprecated alias for --repetitions",
7713
8067
  (v) => parseIntOption(v, "--iterations")
7714
8068
  ).option(
7715
8069
  "--case <id-or-title...>",
@@ -7734,7 +8088,7 @@ function registerEvalCommands(program) {
7734
8088
  "--wait-timeout <ms>",
7735
8089
  "Maximum time to wait for completion (default: 600000)"
7736
8090
  ).option(
7737
- "--reporter <json-summary|junit-xml>",
8091
+ "--reporter <json-summary|junit-xml|html>",
7738
8092
  "Render the completed run report to stdout"
7739
8093
  ).option(
7740
8094
  "--out <path>",
@@ -7768,6 +8122,11 @@ function registerEvalCommands(program) {
7768
8122
  if (!options.file && !options.suite) {
7769
8123
  throw usageError("Provide --suite <id-or-name> or --file <path>.");
7770
8124
  }
8125
+ if (options.repetitions !== void 0 && options.iterations !== void 0) {
8126
+ throw usageError(
8127
+ "Use either --repetitions or its deprecated --iterations alias, not both."
8128
+ );
8129
+ }
7771
8130
  if ((options.reporter !== void 0 || options.out !== void 0) && !options.wait) {
7772
8131
  throw usageError("--reporter and --out require --wait.");
7773
8132
  }
@@ -7779,67 +8138,114 @@ function registerEvalCommands(program) {
7779
8138
  const waitTimeoutMs = options.waitTimeout !== void 0 ? parsePositiveInteger(options.waitTimeout, "--wait-timeout") : DEFAULT_RUN_WAIT_TIMEOUT_MS;
7780
8139
  let webOrigin = DEFAULT_PLATFORM_ORIGIN;
7781
8140
  const resolved = resolveCloudProjectArgs(options);
7782
- const result = await runPlatformOperation(
7783
- platformOptionsOf(command),
7784
- globalOptions.timeout,
7785
- (context) => {
7786
- webOrigin = context.webOrigin;
7787
- if (options.file) {
7788
- const source = readSuiteFileInput(options.file);
7789
- return executeEvalRunFromFile(
7790
- { client: context.client, signal: context.signal },
7791
- {
7792
- source,
7793
- label: options.file === "-" ? "<stdin>" : options.file,
7794
- projectSelector: resolved.project ?? options.project,
7795
- knobs: {
7796
- ...options.server ? { server: options.server } : {},
7797
- ...options.environment ? { environment: options.environment } : {},
7798
- ...options.host ? { host: options.host } : {},
7799
- ...options.allTargets ? { allTargets: true } : {},
7800
- ...options.iterations !== void 0 ? { iterations: options.iterations } : {},
7801
- ...options.case?.length ? { case: options.case } : {},
7802
- ...options.excludeSkills ? { excludeSkills: true } : {},
7803
- ...options.refreshSnapshot ? { refreshSnapshot: true } : {},
7804
- ...options.notes !== void 0 ? { notes: options.notes } : {},
7805
- ...options.minPassRate !== void 0 ? { minPassRate: options.minPassRate } : {},
7806
- ...options.matchOptions ? {
7807
- matchOptions: parseMatchOptionsOption(
7808
- options.matchOptions
7809
- )
7810
- } : {},
7811
- ...options.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {},
7812
- ...composeField(options)
8141
+ if (options.wait) {
8142
+ try {
8143
+ preflightCloudCredentials(platformOptionsOf(command));
8144
+ } catch (error) {
8145
+ if (error instanceof CliError && error.exitCode === 2) throw error;
8146
+ if (error instanceof CliError) {
8147
+ throw new CliError(error.code, error.message, 3, error.details);
8148
+ }
8149
+ throw error;
8150
+ }
8151
+ }
8152
+ let result;
8153
+ try {
8154
+ result = await runPlatformOperation(
8155
+ platformOptionsOf(command),
8156
+ globalOptions.timeout,
8157
+ (context) => {
8158
+ webOrigin = context.webOrigin;
8159
+ const onDisclosure = (disclosure) => {
8160
+ writeRunDisclosure(
8161
+ globalOptions.format,
8162
+ disclosure,
8163
+ reporter === void 0 ? process.stdout : process.stderr
8164
+ );
8165
+ };
8166
+ const onDisclosureUnavailable = (reason) => {
8167
+ if (globalOptions.format !== "human") return;
8168
+ const stream = reporter === void 0 ? process.stdout : process.stderr;
8169
+ stream.write(`Pre-run disclosure unavailable: ${reason}
8170
+ `);
8171
+ };
8172
+ if (options.file) {
8173
+ const source = readSuiteFileInput(options.file);
8174
+ return executeEvalRunFromFile(
8175
+ {
8176
+ client: context.client,
8177
+ signal: context.signal,
8178
+ onDisclosure,
8179
+ onDisclosureUnavailable
8180
+ },
8181
+ {
8182
+ source,
8183
+ label: options.file === "-" ? "<stdin>" : options.file,
8184
+ projectSelector: resolved.project ?? options.project,
8185
+ knobs: {
8186
+ ...options.server ? { server: options.server } : {},
8187
+ ...options.environment ? { environment: options.environment } : {},
8188
+ ...options.host ? { host: options.host } : {},
8189
+ ...options.allTargets ? { allTargets: true } : {},
8190
+ ...options.repetitions !== void 0 || options.iterations !== void 0 ? { repetitions: options.repetitions ?? options.iterations } : {},
8191
+ ...options.case?.length ? { case: options.case } : {},
8192
+ ...options.excludeSkills ? { excludeSkills: true } : {},
8193
+ ...options.refreshSnapshot ? { refreshSnapshot: true } : {},
8194
+ ...options.notes !== void 0 ? { notes: options.notes } : {},
8195
+ ...options.minPassRate !== void 0 ? { minPassRate: options.minPassRate } : {},
8196
+ ...options.matchOptions ? {
8197
+ matchOptions: parseMatchOptionsOption(
8198
+ options.matchOptions
8199
+ )
8200
+ } : {},
8201
+ ...options.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {},
8202
+ ...composeField(options)
8203
+ }
7813
8204
  }
8205
+ );
8206
+ }
8207
+ return runEvalSuiteOperation.execute(
8208
+ {
8209
+ project: resolved.project ?? options.project,
8210
+ suite: options.suite,
8211
+ ...options.server ? { servers: options.server } : {},
8212
+ // ONE value maps to the singular field, several to the plural:
8213
+ // the op rejects sending both, and the singular carries the
8214
+ // long-standing description a caller may already rely on.
8215
+ ...selectorField("environment", "environments", options.environment),
8216
+ ...selectorField("host", "hosts", options.host),
8217
+ ...options.allTargets ? { allAttached: true } : {},
8218
+ ...options.repetitions !== void 0 ? { repetitions: options.repetitions } : options.iterations !== void 0 ? { iterations: options.iterations } : {},
8219
+ ...options.case?.length ? { cases: options.case } : {},
8220
+ ...options.excludeSkills ? { excludeSkills: true } : {},
8221
+ ...options.refreshSnapshot ? { refreshSnapshot: true } : {},
8222
+ ...options.notes !== void 0 ? { notes: options.notes } : {},
8223
+ ...options.minPassRate !== void 0 ? { minPassRate: options.minPassRate } : {},
8224
+ ...options.matchOptions ? { matchOptions: parseMatchOptionsOption(options.matchOptions) } : {},
8225
+ ...options.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {},
8226
+ ...composeField(options)
8227
+ },
8228
+ {
8229
+ client: context.client,
8230
+ signal: context.signal,
8231
+ onDisclosure,
8232
+ onDisclosureUnavailable
7814
8233
  }
7815
8234
  );
7816
- }
7817
- return runEvalSuiteOperation.execute(
7818
- {
7819
- project: resolved.project ?? options.project,
7820
- suite: options.suite,
7821
- ...options.server ? { servers: options.server } : {},
7822
- // ONE value maps to the singular field, several to the plural:
7823
- // the op rejects sending both, and the singular carries the
7824
- // long-standing description a caller may already rely on.
7825
- ...selectorField("environment", "environments", options.environment),
7826
- ...selectorField("host", "hosts", options.host),
7827
- ...options.allTargets ? { allAttached: true } : {},
7828
- ...options.iterations !== void 0 ? { iterations: options.iterations } : {},
7829
- ...options.case?.length ? { cases: options.case } : {},
7830
- ...options.excludeSkills ? { excludeSkills: true } : {},
7831
- ...options.refreshSnapshot ? { refreshSnapshot: true } : {},
7832
- ...options.notes !== void 0 ? { notes: options.notes } : {},
7833
- ...options.minPassRate !== void 0 ? { minPassRate: options.minPassRate } : {},
7834
- ...options.matchOptions ? { matchOptions: parseMatchOptionsOption(options.matchOptions) } : {},
7835
- ...options.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {},
7836
- ...composeField(options)
7837
- },
7838
- { client: context.client, signal: context.signal }
8235
+ },
8236
+ { projectScope: resolved.projectScope }
8237
+ );
8238
+ } catch (error) {
8239
+ if (options.wait && error instanceof CliError && error.exitCode !== 2) {
8240
+ throw new CliError(
8241
+ error.code,
8242
+ error.message,
8243
+ classifyLaunchErrorExitCode(error.code, error.details),
8244
+ error.details
7839
8245
  );
7840
- },
7841
- { projectScope: resolved.projectScope }
7842
- );
8246
+ }
8247
+ throw error;
8248
+ }
7843
8249
  if (!options.wait) {
7844
8250
  writeResult(result, globalOptions.format);
7845
8251
  writeRunGroupSummary(globalOptions.format, webOrigin, result);
@@ -7849,6 +8255,17 @@ function registerEvalCommands(program) {
7849
8255
  return;
7850
8256
  }
7851
8257
  const needsReport = reporter !== void 0 || options.out !== void 0;
8258
+ try {
8259
+ preflightCloudCredentials(platformOptionsOf(command));
8260
+ } catch (error) {
8261
+ writeResult({ launch: result, runs: [] }, globalOptions.format);
8262
+ writeRunGroupSummary(globalOptions.format, webOrigin, result);
8263
+ if (error instanceof CliError && error.exitCode === 2) throw error;
8264
+ if (error instanceof CliError) {
8265
+ throw new CliError(error.code, error.message, 3, error.details);
8266
+ }
8267
+ throw error;
8268
+ }
7852
8269
  const completion = await runPlatformOperation(
7853
8270
  platformOptionsOf(command),
7854
8271
  Math.max(globalOptions.timeout, waitTimeoutMs),
@@ -7871,22 +8288,31 @@ function registerEvalCommands(program) {
7871
8288
  return {
7872
8289
  ok: false,
7873
8290
  runId: target.runId,
7874
- error: error instanceof Error ? error.message : String(error)
8291
+ error: error instanceof Error ? error.message : String(error),
8292
+ ...isPlatformApiError(error) ? { errorCode: error.code } : {}
7875
8293
  };
7876
8294
  }
7877
8295
  })
7878
8296
  );
7879
8297
  const runs = waited.flatMap((entry) => entry.ok ? [entry.run] : []);
7880
8298
  const waitErrors = waited.flatMap(
7881
- (entry) => !entry.ok ? [{ runId: entry.runId, error: entry.error }] : []
8299
+ (entry) => !entry.ok ? [
8300
+ {
8301
+ runId: entry.runId,
8302
+ error: entry.error,
8303
+ ...entry.errorCode ? { errorCode: entry.errorCode } : {}
8304
+ }
8305
+ ] : []
7882
8306
  );
7883
8307
  if (!needsReport) {
7884
8308
  return {
7885
8309
  runs,
7886
8310
  waitErrors,
7887
- reportInputs: []
8311
+ reportInputs: [],
8312
+ iterationErrorCodes: /* @__PURE__ */ new Map()
7888
8313
  };
7889
8314
  }
8315
+ const iterationErrorCodes = /* @__PURE__ */ new Map();
7890
8316
  const reportInputs = await Promise.all(
7891
8317
  runs.map(async (run) => {
7892
8318
  try {
@@ -7902,6 +8328,9 @@ function registerEvalCommands(program) {
7902
8328
  iterationsComplete: iterations.complete
7903
8329
  };
7904
8330
  } catch (error) {
8331
+ if (isPlatformApiError(error)) {
8332
+ iterationErrorCodes.set(run.id, error.code);
8333
+ }
7905
8334
  return {
7906
8335
  run,
7907
8336
  iterations: [],
@@ -7911,7 +8340,7 @@ function registerEvalCommands(program) {
7911
8340
  }
7912
8341
  })
7913
8342
  );
7914
- return { runs, waitErrors, reportInputs };
8343
+ return { runs, waitErrors, reportInputs, iterationErrorCodes };
7915
8344
  },
7916
8345
  {
7917
8346
  projectScope: resolved.projectScope,
@@ -7935,12 +8364,36 @@ function registerEvalCommands(program) {
7935
8364
  ...result.runGroupId ? { runGroupId: result.runGroupId } : {}
7936
8365
  }
7937
8366
  }) : void 0;
8367
+ const reportingErrors = completion.reportInputs.filter(
8368
+ (input) => !input.iterationsComplete || input.iterationError
8369
+ );
8370
+ const reportingFailedRunIds = new Set(
8371
+ reportingErrors.map((input) => input.run.id)
8372
+ );
8373
+ const runOutcomes = completion.runs.map(
8374
+ (run) => ({
8375
+ status: run.status,
8376
+ result: run.result,
8377
+ reportingFailed: reportingFailedRunIds.has(run.id),
8378
+ reportingFailedErrorCode: completion.iterationErrorCodes.get(run.id)
8379
+ })
8380
+ );
8381
+ const code = evalRunWaitExitCode({
8382
+ launchOutcome: result.outcome,
8383
+ runs: runOutcomes,
8384
+ waitErrors: completion.waitErrors
8385
+ });
8386
+ let outWriteError;
7938
8387
  if (options.out && report) {
7939
- await writeReporterArtifact(
7940
- options.out,
7941
- reporter ?? "json-summary",
7942
- report
7943
- );
8388
+ try {
8389
+ await writeReporterArtifact(
8390
+ options.out,
8391
+ reporter ?? "json-summary",
8392
+ report
8393
+ );
8394
+ } catch (error) {
8395
+ outWriteError = error instanceof Error ? error.message : String(error);
8396
+ }
7944
8397
  }
7945
8398
  if (reporter && report) {
7946
8399
  writeReporterResult(reporter, report);
@@ -7951,18 +8404,20 @@ function registerEvalCommands(program) {
7951
8404
  );
7952
8405
  writeRunGroupSummary(globalOptions.format, webOrigin, result);
7953
8406
  }
7954
- const reportingErrors = completion.reportInputs.filter(
7955
- (input) => !input.iterationsComplete || input.iterationError
7956
- );
8407
+ if (outWriteError !== void 0) {
8408
+ throw cliError("OUT_WRITE_FAILED", outWriteError, worstOf([code, 4]));
8409
+ }
7957
8410
  if (reportingErrors.length > 0 || completion.waitErrors.length > 0) {
7958
8411
  const affectedRunIds = [
7959
8412
  ...reportingErrors.map((input) => input.run.id),
7960
8413
  ...completion.waitErrors.map((entry) => entry.runId)
7961
8414
  ];
7962
- throw operationalError(
8415
+ throw cliError(
8416
+ "OPERATIONAL_ERROR",
7963
8417
  needsReport ? `Completed eval run report is incomplete for: ${affectedRunIds.join(
7964
8418
  ", "
7965
8419
  )}.` : `Did not observe completion for: ${affectedRunIds.join(", ")}.`,
8420
+ code,
7966
8421
  {
7967
8422
  // Machine-readable, because the message is not: a pipeline that
7968
8423
  // needs to resume or cancel these runs should not have to parse
@@ -7972,9 +8427,7 @@ function registerEvalCommands(program) {
7972
8427
  }
7973
8428
  );
7974
8429
  }
7975
- if (result.outcome !== "started") {
7976
- setProcessExitCode(1);
7977
- }
8430
+ setProcessExitCode(code);
7978
8431
  }
7979
8432
  );
7980
8433
  addProjectOption(
@@ -8163,11 +8616,26 @@ function registerEvalCommands(program) {
8163
8616
  "Minimum mean score for one scorer (repeatable)",
8164
8617
  collectRepeatable,
8165
8618
  []
8619
+ ).option(
8620
+ "--baseline <runId>",
8621
+ "Baseline run ID to gate a regression delta against (SHA baselines are not supported yet)"
8622
+ ).option(
8623
+ "--min-sample-size <n>",
8624
+ "Iterations required on EACH side before a pass-rate regression is decidable (default 5); requires --baseline"
8625
+ ).option(
8626
+ "--min-effect-size-percent <0-100>",
8627
+ "Smallest pass-rate drop worth failing on, as a percentage (default 1); requires --baseline"
8628
+ ).option(
8629
+ "--gate-deterministic-regressions",
8630
+ "Fail if a deterministic gating scorer flipped from passed to failed; requires --baseline"
8631
+ ).option(
8632
+ "--max-p95-latency-increase-ms <ms>",
8633
+ "Fail if p95 end-to-end latency rose by more than this many milliseconds vs the baseline; requires --baseline"
8166
8634
  ).option("--wait", "Poll until the run reaches a terminal status").option(
8167
8635
  "--wait-timeout <ms>",
8168
8636
  "Give up waiting after this many milliseconds (default 600000)"
8169
8637
  ).option(
8170
- "--reporter <json-summary|junit-xml>",
8638
+ "--reporter <json-summary|junit-xml|html>",
8171
8639
  "Write a structured report to stdout instead of the default output"
8172
8640
  ).option(
8173
8641
  "--out <path>",
@@ -8200,9 +8668,12 @@ function registerEvalCommands(program) {
8200
8668
  "--max-p95-latency-increase-ms <ms>",
8201
8669
  "Fail if p95 end-to-end latency rose by more than this many milliseconds"
8202
8670
  ).option(
8203
- "--reporter <json-summary|junit-xml>",
8671
+ "--reporter <json-summary|junit-xml|html>",
8204
8672
  "Write a structured report to stdout instead of the default output"
8205
- ).option("--out <path>", "Write the structured report to a JSON file").action(
8673
+ ).option(
8674
+ "--out <path>",
8675
+ "Atomically write the structured report selected by --reporter (default: json-summary)"
8676
+ ).action(
8206
8677
  async (options, command) => {
8207
8678
  await runEvalCompare(options, command);
8208
8679
  }
@@ -8603,9 +9074,13 @@ function registerEvalCommands(program) {
8603
9074
  ).option(
8604
9075
  "--host <id-or-name>",
8605
9076
  "Attached host to run against, so the run is stamped with that host's config"
9077
+ ).option(
9078
+ "--repetitions <n>",
9079
+ "Run the case this many times under verdict policy 2 (1-10)",
9080
+ (v) => parseIntOption(v, "--repetitions")
8606
9081
  ).option(
8607
9082
  "--iterations <n>",
8608
- "Run the case this many times (1-10)",
9083
+ "Deprecated alias for --repetitions",
8609
9084
  (v) => parseIntOption(v, "--iterations")
8610
9085
  ).option(
8611
9086
  "--idempotency-key <key>",
@@ -8627,6 +9102,11 @@ function registerEvalCommands(program) {
8627
9102
  "Project-shared skill IDs to pin on the composed stack"
8628
9103
  ).action(
8629
9104
  async (options, command) => {
9105
+ if (options.repetitions !== void 0 && options.iterations !== void 0) {
9106
+ throw usageError(
9107
+ "Use either --repetitions or its deprecated --iterations alias, not both."
9108
+ );
9109
+ }
8630
9110
  await executeOp(
8631
9111
  runEvalCaseOperation,
8632
9112
  {
@@ -8636,7 +9116,7 @@ function registerEvalCommands(program) {
8636
9116
  ...options.server?.length ? { servers: options.server } : {},
8637
9117
  ...options.environment ? { environment: options.environment } : {},
8638
9118
  ...options.host ? { host: options.host } : {},
8639
- ...options.iterations !== void 0 ? { iterations: options.iterations } : {},
9119
+ ...options.repetitions !== void 0 ? { repetitions: options.repetitions } : options.iterations !== void 0 ? { iterations: options.iterations } : {},
8640
9120
  ...options.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {},
8641
9121
  ...composeField(options)
8642
9122
  },
@@ -13622,6 +14102,11 @@ function registerConformanceRunCommand(program) {
13622
14102
  const reporter = parseReporterFormat(
13623
14103
  options.reporter
13624
14104
  );
14105
+ if (reporter === "html") {
14106
+ throw usageError(
14107
+ 'The "html" reporter is not available for this command yet. Use "json-summary" or "junit-xml".'
14108
+ );
14109
+ }
13625
14110
  const format = resolveConformanceOutputFormatForCli(
13626
14111
  globalOptions.format,
13627
14112
  process.stdout.isTTY,
@@ -15686,7 +16171,7 @@ function registerServerCommands(program) {
15686
16171
  "Diff failure policy: breaking, any, or none"
15687
16172
  ).option(
15688
16173
  "--reporter <reporter>",
15689
- "Structured reporter output: json-summary or junit-xml"
16174
+ "Structured reporter output: json-summary, junit-xml, or html"
15690
16175
  ).option("--out <path>", "Write the raw diff JSON artifact to a file")
15691
16176
  )
15692
16177
  ).action(async (options, command) => {
@@ -17934,7 +18419,7 @@ function registerToolsCommands(program) {
17934
18419
  "Evaluate the tool-call outcome policy against isError"
17935
18420
  ).option(
17936
18421
  "--reporter <reporter>",
17937
- "Structured reporter output: json-summary or junit-xml"
18422
+ "Structured reporter output: json-summary, junit-xml, or html"
17938
18423
  ).option(
17939
18424
  "--debug-out <path>",
17940
18425
  "Write a structured debug artifact to a file"