@mcpjam/cli 4.1.0 → 5.0.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, GATE_WAIVER_MAX_REASON_LENGTH, GATE_WAIVER_REASON_NOTICE, 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, formatEvalRunDecisionSummary, gateOutcomeVerdict, applyGateWaiver, formatGateReport, formatGateWaiverLine, detectFlakyCases, evaluateCompareGates, buildRunCompareReport, formatSuiteFileFindings, serializeEvalSuiteFile, MAX_SUITE_FILE_BYTES, buildCorpus, HostedOnlyCaseError, verifyCorpusLock, TaskLifecycleEngine, driveTaskToTerminal, extensionTaskToObservation, legacyTaskToObservation, canonicalDigest, readEvalRunDecisionSummary as readEvalRunDecisionSummary$1, buildEvalRunDecisionSummary, evaluateGates, gateInputFromPlatformRun, isGateWaiverInForce, 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.1.0"};
30
+ version: "5.0.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,11 +595,15 @@ 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) {
597
605
  if (format !== "human" || !summary) return;
598
- destination.write(`${formatEvalDecisionSummary(summary)}
606
+ destination.write(`${formatEvalRunDecisionSummary(summary)}
599
607
  `);
600
608
  }
601
609
  async function writeJsonArtifact(outputPath, payload) {
@@ -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 });
@@ -6172,6 +6180,14 @@ function evalGateExitCode(report) {
6172
6180
  switch (report.outcome) {
6173
6181
  case "passed":
6174
6182
  return 0;
6183
+ // An authorized, recorded, time-boxed override of a real failure. Exit 0,
6184
+ // because unblocking the release is what a waiver is FOR — but it reaches
6185
+ // 0 by its own named outcome rather than by being turned into `passed`
6186
+ // upstream, so nothing downstream has to reconstruct which of the two
6187
+ // happened. The report, and every artifact built from it, still says the
6188
+ // gate failed and was waived.
6189
+ case "waived":
6190
+ return 0;
6175
6191
  case "failed":
6176
6192
  return 1;
6177
6193
  case "usage_error":
@@ -6197,92 +6213,6 @@ function isNonVerdictRunResult(result) {
6197
6213
  }
6198
6214
  var EVAL_GATE_INCOMPLETE_EXIT_CODE = 3;
6199
6215
  var EVAL_GATE_USAGE_EXIT_CODE = 2;
6200
- function parsePercent(raw, flag) {
6201
- const value = raw.trim() === "" ? NaN : Number(raw);
6202
- if (!Number.isFinite(value) || value < 0 || value > 100) {
6203
- throw usageError(`${flag} must be a number between 0 and 100, got "${raw}".`);
6204
- }
6205
- return passRateFractionFromPercent(value);
6206
- }
6207
- function parseScorerMap(entries, flag, parseValue) {
6208
- const out = /* @__PURE__ */ Object.create(null);
6209
- for (const entry of entries) {
6210
- const index = entry.indexOf("=");
6211
- if (index <= 0) {
6212
- throw usageError(`${flag} must be <scorerId>=<value>, got "${entry}".`);
6213
- }
6214
- const scorerId = entry.slice(0, index).trim();
6215
- if (!scorerId) {
6216
- throw usageError(`${flag} is missing a scorer id in "${entry}".`);
6217
- }
6218
- if (Object.prototype.hasOwnProperty.call(out, scorerId)) {
6219
- throw usageError(
6220
- `${flag} names "${scorerId}" more than once; pass one threshold per scorer.`
6221
- );
6222
- }
6223
- out[scorerId] = parseValue(entry.slice(index + 1).trim(), flag);
6224
- }
6225
- return out;
6226
- }
6227
- function parseUnit(raw, flag) {
6228
- const value = raw.trim() === "" ? NaN : Number(raw);
6229
- if (!Number.isFinite(value) || value < 0 || value > 1) {
6230
- throw usageError(`${flag} must be a number between 0 and 1, got "${raw}".`);
6231
- }
6232
- return value;
6233
- }
6234
- function policyFromOptions(options) {
6235
- const policy = {};
6236
- if (options.minPassRatePercent !== void 0) {
6237
- policy.minimumPassRate = parsePercent(
6238
- options.minPassRatePercent,
6239
- "--min-pass-rate-percent"
6240
- );
6241
- }
6242
- if (options.noGatingScoreErrors) policy.noGatingScoreErrors = true;
6243
- if (options.minScorerPassRate?.length) {
6244
- policy.minimumScorerPassRate = parseScorerMap(
6245
- options.minScorerPassRate,
6246
- "--min-scorer-pass-rate",
6247
- parsePercent
6248
- );
6249
- }
6250
- if (options.minMeanScore?.length) {
6251
- policy.minimumMeanScore = parseScorerMap(
6252
- options.minMeanScore,
6253
- "--min-mean-score",
6254
- parseUnit
6255
- );
6256
- }
6257
- return policy;
6258
- }
6259
- function policyNeedsIterations(policy) {
6260
- return Boolean(
6261
- policy.noGatingScoreErrors || policy.minimumScorerPassRate || policy.minimumMeanScore || policy.maximumTotalTokens !== void 0 || // p95 comes from iteration durations, exactly like tokens come from
6262
- // iteration counts. Omitting it here would leave the latency gate
6263
- // permanently non-gateable — the fetch that could decide it never runs.
6264
- policy.maximumP95LatencyMs !== void 0
6265
- );
6266
- }
6267
- function reportForRun(run, iterations, policy) {
6268
- return evaluateGates(gateInputFromPlatformRun(run, iterations), policy);
6269
- }
6270
-
6271
- // src/lib/eval-iterations.ts
6272
- async function fetchAllIterations(client, signal, projectId, runId) {
6273
- const items = [];
6274
- let cursor;
6275
- for (let page = 0; page < 100; page += 1) {
6276
- const result = await client.listEvalRunIterations(
6277
- { projectId, runId, ...cursor ? { cursor } : {}, limit: 200 },
6278
- { signal }
6279
- );
6280
- items.push(...result.items);
6281
- if (!result.nextCursor) return { items, complete: true };
6282
- cursor = result.nextCursor;
6283
- }
6284
- return { items, complete: false };
6285
- }
6286
6216
 
6287
6217
  // src/lib/eval-compare.ts
6288
6218
  function parseNonNegativeInteger2(raw, flag) {
@@ -6408,6 +6338,506 @@ function flakyInputFrom(iterations) {
6408
6338
  passed: iteration.result === "passed"
6409
6339
  }));
6410
6340
  }
6341
+ async function fetchAllIterations(client, signal, projectId, runId) {
6342
+ const items = [];
6343
+ let cursor;
6344
+ for (let page = 0; page < 100; page += 1) {
6345
+ const result = await client.listEvalRunIterations(
6346
+ { projectId, runId, ...cursor ? { cursor } : {}, limit: 200 },
6347
+ { signal }
6348
+ );
6349
+ items.push(...result.items);
6350
+ if (!result.nextCursor) return { items, complete: true };
6351
+ cursor = result.nextCursor;
6352
+ }
6353
+ return { items, complete: false };
6354
+ }
6355
+ function p95Of(iterations) {
6356
+ if (!iterations?.complete) return void 0;
6357
+ const durations = iterations.items.map((iteration) => iteration.durationMs).filter((ms) => typeof ms === "number");
6358
+ if (durations.length === 0 || durations.length !== iterations.items.length) {
6359
+ return void 0;
6360
+ }
6361
+ return calculateLatencyStats(durations).p95;
6362
+ }
6363
+
6364
+ // src/lib/eval-gate.ts
6365
+ function parsePercent(raw, flag) {
6366
+ const value = raw.trim() === "" ? NaN : Number(raw);
6367
+ if (!Number.isFinite(value) || value < 0 || value > 100) {
6368
+ throw usageError(`${flag} must be a number between 0 and 100, got "${raw}".`);
6369
+ }
6370
+ return passRateFractionFromPercent(value);
6371
+ }
6372
+ function parseScorerMap(entries, flag, parseValue) {
6373
+ const out = /* @__PURE__ */ Object.create(null);
6374
+ for (const entry of entries) {
6375
+ const index = entry.indexOf("=");
6376
+ if (index <= 0) {
6377
+ throw usageError(`${flag} must be <scorerId>=<value>, got "${entry}".`);
6378
+ }
6379
+ const scorerId = entry.slice(0, index).trim();
6380
+ if (!scorerId) {
6381
+ throw usageError(`${flag} is missing a scorer id in "${entry}".`);
6382
+ }
6383
+ if (Object.prototype.hasOwnProperty.call(out, scorerId)) {
6384
+ throw usageError(
6385
+ `${flag} names "${scorerId}" more than once; pass one threshold per scorer.`
6386
+ );
6387
+ }
6388
+ out[scorerId] = parseValue(entry.slice(index + 1).trim(), flag);
6389
+ }
6390
+ return out;
6391
+ }
6392
+ function parseUnit(raw, flag) {
6393
+ const value = raw.trim() === "" ? NaN : Number(raw);
6394
+ if (!Number.isFinite(value) || value < 0 || value > 1) {
6395
+ throw usageError(`${flag} must be a number between 0 and 1, got "${raw}".`);
6396
+ }
6397
+ return value;
6398
+ }
6399
+ function policyFromOptions(options) {
6400
+ const policy = {};
6401
+ if (options.minPassRatePercent !== void 0) {
6402
+ policy.minimumPassRate = parsePercent(
6403
+ options.minPassRatePercent,
6404
+ "--min-pass-rate-percent"
6405
+ );
6406
+ }
6407
+ if (options.noGatingScoreErrors) policy.noGatingScoreErrors = true;
6408
+ if (options.minScorerPassRate?.length) {
6409
+ policy.minimumScorerPassRate = parseScorerMap(
6410
+ options.minScorerPassRate,
6411
+ "--min-scorer-pass-rate",
6412
+ parsePercent
6413
+ );
6414
+ }
6415
+ if (options.minMeanScore?.length) {
6416
+ policy.minimumMeanScore = parseScorerMap(
6417
+ options.minMeanScore,
6418
+ "--min-mean-score",
6419
+ parseUnit
6420
+ );
6421
+ }
6422
+ return policy;
6423
+ }
6424
+ function policyNeedsIterations(policy) {
6425
+ return Boolean(
6426
+ policy.noGatingScoreErrors || policy.minimumScorerPassRate || policy.minimumMeanScore || policy.maximumTotalTokens !== void 0 || // p95 comes from iteration durations, exactly like tokens come from
6427
+ // iteration counts. Omitting it here would leave the latency gate
6428
+ // permanently non-gateable — the fetch that could decide it never runs.
6429
+ policy.maximumP95LatencyMs !== void 0
6430
+ );
6431
+ }
6432
+ function reportForRun(run, iterations, policy) {
6433
+ return evaluateGates(gateInputFromPlatformRun(run, iterations), policy);
6434
+ }
6435
+ var SHA_LIKE_BASELINE = /^[0-9a-f]{40}$/i;
6436
+ function assertRunIdBaseline(baseline, runId) {
6437
+ const normalized = baseline.trim();
6438
+ if (normalized === "") {
6439
+ throw usageError(
6440
+ `--baseline must not be blank. Pass a run id, or omit the flag entirely to gate on absolute thresholds only.`
6441
+ );
6442
+ }
6443
+ if (normalized === runId) {
6444
+ throw usageError(
6445
+ `--baseline "${baseline}" is the same as --run "${runId}". A run cannot be its own baseline \u2014 pass a different, earlier run id.`
6446
+ );
6447
+ }
6448
+ if (SHA_LIKE_BASELINE.test(normalized)) {
6449
+ throw usageError(
6450
+ `--baseline "${baseline}" looks like a git commit SHA. Pass it as --baseline-sha to pin the baseline by source SHA, or pass a run id to --baseline.`
6451
+ );
6452
+ }
6453
+ return normalized;
6454
+ }
6455
+ function assertCommitShaBaseline(baselineSha) {
6456
+ const normalized = baselineSha.trim();
6457
+ if (normalized === "") {
6458
+ throw usageError(
6459
+ `--baseline-sha must not be blank. Pass a commit SHA, or omit the flag entirely to gate on absolute thresholds only.`
6460
+ );
6461
+ }
6462
+ return normalized;
6463
+ }
6464
+ function resolveBaselineSelector(input) {
6465
+ if (input.baseline !== void 0 && input.baselineSha !== void 0) {
6466
+ throw usageError(
6467
+ `--baseline and --baseline-sha are mutually exclusive. Pass a run id to --baseline, or a source commit SHA to --baseline-sha, not both.`
6468
+ );
6469
+ }
6470
+ if (input.baselineSha !== void 0) {
6471
+ return {
6472
+ kind: "commitSha",
6473
+ commitSha: assertCommitShaBaseline(input.baselineSha)
6474
+ };
6475
+ }
6476
+ if (input.baseline !== void 0) {
6477
+ return {
6478
+ kind: "run",
6479
+ runId: assertRunIdBaseline(input.baseline, input.runId)
6480
+ };
6481
+ }
6482
+ return void 0;
6483
+ }
6484
+ function compareBaseSelector(input) {
6485
+ if (input.baseRun !== void 0 && input.baseSha !== void 0) {
6486
+ throw usageError(
6487
+ `--base-run and --base-sha are mutually exclusive. Pass a run id to --base-run, or a source commit SHA to --base-sha, not both.`
6488
+ );
6489
+ }
6490
+ if (input.baseSha !== void 0) {
6491
+ const normalized = input.baseSha.trim();
6492
+ if (normalized === "") {
6493
+ throw usageError(
6494
+ `--base-sha must not be blank. Pass a commit SHA, or omit the flag to compare against the nearest earlier completed run.`
6495
+ );
6496
+ }
6497
+ return { baseCommitSha: normalized };
6498
+ }
6499
+ if (input.baseRun !== void 0) {
6500
+ const normalized = input.baseRun.trim();
6501
+ if (normalized === "") {
6502
+ throw usageError(
6503
+ `--base-run must not be blank. Pass a run id, or omit the flag to compare against the nearest earlier completed run.`
6504
+ );
6505
+ }
6506
+ return { baseRunId: normalized };
6507
+ }
6508
+ return {};
6509
+ }
6510
+ function baselineCompareParams(baseline) {
6511
+ return baseline.kind === "run" ? { baseRunId: baseline.runId } : { baseCommitSha: baseline.commitSha };
6512
+ }
6513
+ function comparePolicyFromGateOptions(options) {
6514
+ const hasComparativeFlag = options.minSampleSize !== void 0 || options.minEffectSizePercent !== void 0 || options.gateDeterministicRegressions === true || options.maxP95LatencyIncreaseMs !== void 0;
6515
+ const hasBaseline = Boolean(options.baseline) || Boolean(options.baselineSha);
6516
+ if (hasComparativeFlag && !hasBaseline) {
6517
+ throw usageError(
6518
+ "--min-sample-size, --min-effect-size-percent, --gate-deterministic-regressions, and --max-p95-latency-increase-ms tune the baseline regression gate; pass --baseline or --baseline-sha to enable it."
6519
+ );
6520
+ }
6521
+ return comparePolicyFromOptions({
6522
+ gateRegressions: hasBaseline,
6523
+ minSampleSize: options.minSampleSize,
6524
+ minEffectSizePercent: options.minEffectSizePercent,
6525
+ gateDeterministicRegressions: options.gateDeterministicRegressions,
6526
+ maxP95LatencyIncreaseMs: options.maxP95LatencyIncreaseMs
6527
+ });
6528
+ }
6529
+ function baselineNotFoundReason(error) {
6530
+ const details = error?.details;
6531
+ return typeof details === "object" && details !== null && details.reason === "BASELINE_NOT_FOUND";
6532
+ }
6533
+ var OUTCOME_RANK = {
6534
+ passed: 0,
6535
+ // UNREACHABLE by construction: a waiver is folded in by `applyGateWaiver`
6536
+ // AFTER the two halves are merged, so no input to this function can carry
6537
+ // it. Ranked with `passed` rather than left to a lookup miss (`undefined`,
6538
+ // whose every comparison is false, would silently pin the merged outcome to
6539
+ // whichever side was evaluated first) — and ranked LOWEST deliberately: if
6540
+ // one half were ever waived, an unwaived failure on the other half must
6541
+ // still win. A waiver granted over the threshold gate is not consent to
6542
+ // ship a baseline regression.
6543
+ waived: 0,
6544
+ incomplete: 1,
6545
+ failed: 2,
6546
+ usage_error: 3
6547
+ };
6548
+ function mergeGateReports(threshold, comparative) {
6549
+ return {
6550
+ outcome: OUTCOME_RANK[comparative.outcome] > OUTCOME_RANK[threshold.outcome] ? comparative.outcome : threshold.outcome,
6551
+ verdicts: [...threshold.verdicts, ...comparative.verdicts],
6552
+ // The run being gated IS the compare side of the baseline comparison, so
6553
+ // its own score integrity — already computed by `evaluateGates` above —
6554
+ // is the one meaning that survives the merge. The comparison's own
6555
+ // (base+compare) combined integrity is recorded separately in the
6556
+ // baseline provenance, not lost.
6557
+ scoreIntegrity: threshold.scoreIntegrity
6558
+ };
6559
+ }
6560
+ function incompatibilityReasonsFor(row, runEvaluationConfigChanged) {
6561
+ const reasons = [];
6562
+ if (row.status === "new_case") reasons.push("case_added");
6563
+ if (row.status === "removed_case") reasons.push("case_removed");
6564
+ if (row.configChanged) reasons.push("scenario_config_changed");
6565
+ if (row.evaluationConfigChanged || runEvaluationConfigChanged) {
6566
+ reasons.push("evaluation_config_changed");
6567
+ }
6568
+ if (row.base.outcome !== "absent" && row.compare.outcome !== "absent" && row.base.iterationIds.length !== row.compare.iterationIds.length) {
6569
+ reasons.push("iteration_weighting_unequal");
6570
+ }
6571
+ return reasons;
6572
+ }
6573
+ function buildBaselineProvenance(requestedBaseline, compare, input, policy) {
6574
+ const classified = compare.cases.map((row) => ({
6575
+ row,
6576
+ reasons: incompatibilityReasonsFor(
6577
+ row,
6578
+ compare.scoreContract.evaluationConfigChanged
6579
+ )
6580
+ }));
6581
+ const requested = {
6582
+ requestedBaselineKind: requestedBaseline.kind,
6583
+ ...requestedBaseline.kind === "run" ? { requestedBaselineRunId: requestedBaseline.runId } : { requestedBaselineCommitSha: requestedBaseline.commitSha },
6584
+ // The RESOLVED source SHA as the backend echoed it, kept separate from
6585
+ // the requested one: a mixed-version backend can resolve without echoing,
6586
+ // and silently presenting the request as the answer would fabricate
6587
+ // confirmation the server never gave.
6588
+ ...typeof compare.baseline.baseCommitSha === "string" ? { resolvedBaselineCommitSha: compare.baseline.baseCommitSha } : {}
6589
+ };
6590
+ const ambiguity = typeof compare.baseline.matchCount === "number" ? {
6591
+ baselineMatchCount: compare.baseline.matchCount,
6592
+ baselineMatchCountTruncated: compare.baseline.matchCountTruncated === true,
6593
+ baselineMatchUnique: false
6594
+ } : { baselineMatchUnique: true };
6595
+ return {
6596
+ ...requested,
6597
+ ...ambiguity,
6598
+ baseline: compare.baseline,
6599
+ baseRunId: compare.baseRun.id,
6600
+ compareRunId: compare.compareRun.id,
6601
+ // The RESOLVED policy that produced this verdict, defaults filled in —
6602
+ // an archived report must be self-describing without cross-referencing
6603
+ // the CLI invocation that produced it. `null` means the gate was not
6604
+ // asked for, not "asked for with a threshold of nothing".
6605
+ policy: {
6606
+ passRateRegression: policy.passRateRegression ? {
6607
+ minSampleSize: policy.passRateRegression.minSampleSize ?? DEFAULT_MIN_SAMPLE_SIZE,
6608
+ minEffectSize: policy.passRateRegression.minEffectSize ?? DEFAULT_MIN_EFFECT_SIZE
6609
+ } : null,
6610
+ noDeterministicRegressions: policy.noDeterministicRegressions === true,
6611
+ maximumP95LatencyIncreaseMs: policy.maximumP95LatencyIncreaseMs ?? null
6612
+ },
6613
+ compatibility: {
6614
+ caseSetChanged: input.caseSetChanged,
6615
+ scenarioConfigChanged: input.scenarioConfigChanged,
6616
+ evaluationConfigChanged: input.evaluationConfigChanged,
6617
+ iterationWeightingEqual: input.iterationWeightingEqual,
6618
+ baseScoreIntegrity: compare.scoreContract.base.scoreIntegrity,
6619
+ compareScoreIntegrity: compare.scoreContract.compare.scoreIntegrity,
6620
+ // The pin names "comparable case ids" explicitly: which cases an
6621
+ // archived report's verdict actually covers, and which ones a
6622
+ // `caseSetChanged: true` flag alone does not name.
6623
+ comparableCaseIds: classified.filter(({ reasons }) => reasons.length === 0).map(({ row }) => row.caseKey),
6624
+ incompatibleCases: classified.filter(({ reasons }) => reasons.length > 0).map(({ row, reasons }) => ({
6625
+ caseKey: row.caseKey,
6626
+ status: row.status,
6627
+ reasons
6628
+ }))
6629
+ },
6630
+ // Dimensions the pinned contract requires but the `/compare` wire does
6631
+ // not carry today (E4b / backend follow-up work). Never invented, never
6632
+ // silently dropped.
6633
+ notRecorded: {
6634
+ modelProvider: "notRecorded",
6635
+ hostHarness: "notRecorded",
6636
+ serverEnvironmentIdentity: "notRecorded",
6637
+ configHashesBeyondEvaluationConfigHash: "notRecorded"
6638
+ }
6639
+ };
6640
+ }
6641
+ async function evaluateBaselineComparison(input) {
6642
+ let compare;
6643
+ try {
6644
+ compare = await input.client.compareEvalRun(
6645
+ {
6646
+ projectId: input.projectId,
6647
+ runId: input.runId,
6648
+ // Exactly ONE of `baseRunId` / `baseCommitSha` — sending both is a 400
6649
+ // at the route and at the action alike.
6650
+ ...baselineCompareParams(input.baseline)
6651
+ },
6652
+ { signal: input.signal }
6653
+ );
6654
+ } catch (error) {
6655
+ const reason = baselineNotFoundReason(error);
6656
+ const detail = error instanceof Error ? error.message : String(error);
6657
+ return {
6658
+ report: {
6659
+ outcome: "incomplete",
6660
+ scoreIntegrity: "unknown",
6661
+ verdicts: [
6662
+ {
6663
+ gate: "baseline",
6664
+ status: "non_gateable",
6665
+ message: reason ? `no baseline to compare against: ${detail}` : `could not compare against the baseline: ${detail}`
6666
+ }
6667
+ ]
6668
+ }
6669
+ };
6670
+ }
6671
+ if (compare.baseRun.completedAt === null || compare.compareRun.completedAt === null) {
6672
+ return {
6673
+ report: {
6674
+ outcome: "incomplete",
6675
+ scoreIntegrity: "unknown",
6676
+ verdicts: [
6677
+ {
6678
+ gate: "baseline",
6679
+ status: "non_gateable",
6680
+ message: "both runs must be completed before they can be compared"
6681
+ }
6682
+ ]
6683
+ }
6684
+ };
6685
+ }
6686
+ const needsLatency = input.policy.maximumP95LatencyIncreaseMs !== void 0;
6687
+ let baseIterations;
6688
+ let compareIterationsForLatency = input.compareIterations;
6689
+ if (needsLatency) {
6690
+ try {
6691
+ [baseIterations, compareIterationsForLatency] = await Promise.all([
6692
+ fetchAllIterations(
6693
+ input.client,
6694
+ input.signal,
6695
+ input.projectId,
6696
+ compare.baseRun.id
6697
+ ),
6698
+ input.compareIterations ?? fetchAllIterations(
6699
+ input.client,
6700
+ input.signal,
6701
+ input.projectId,
6702
+ compare.compareRun.id
6703
+ )
6704
+ ]);
6705
+ } catch {
6706
+ baseIterations = void 0;
6707
+ compareIterationsForLatency = void 0;
6708
+ }
6709
+ }
6710
+ const compareInput = compareGateInputFrom(compare, {
6711
+ baseP95Ms: p95Of(baseIterations),
6712
+ compareP95Ms: p95Of(compareIterationsForLatency)
6713
+ });
6714
+ return {
6715
+ report: evaluateCompareGates(compareInput, input.policy),
6716
+ provenance: buildBaselineProvenance(
6717
+ input.baseline,
6718
+ compare,
6719
+ compareInput,
6720
+ input.policy
6721
+ )
6722
+ };
6723
+ }
6724
+ function activeWaiverForRun(run, now = Date.now()) {
6725
+ const waiver = run?.gateWaiver;
6726
+ if (!waiver) return void 0;
6727
+ if (waiver.active !== true) return void 0;
6728
+ if (waiver.revokedAt !== null) return void 0;
6729
+ if (!isGateWaiverInForce(waiver, now)) return void 0;
6730
+ return {
6731
+ id: waiver.id,
6732
+ reason: waiver.reason,
6733
+ expiresAt: waiver.expiresAt,
6734
+ createdAt: waiver.createdAt,
6735
+ createdBy: waiver.createdBy,
6736
+ createdByEmail: waiver.createdByEmail,
6737
+ policySnapshot: waiver.policySnapshot
6738
+ };
6739
+ }
6740
+ var DURATION_UNIT_MS = {
6741
+ m: 6e4,
6742
+ h: 36e5,
6743
+ d: 864e5
6744
+ };
6745
+ function parseWaiverExpiry(raw, now = Date.now()) {
6746
+ const match = /^(\d+)\s*([mhd])$/i.exec(raw.trim());
6747
+ if (!match) {
6748
+ throw usageError(
6749
+ `--expires-in must be a duration like 30m, 12h, or 7d, got "${raw}".`
6750
+ );
6751
+ }
6752
+ const amount = Number(match[1]);
6753
+ if (!Number.isFinite(amount) || amount <= 0) {
6754
+ throw usageError(`--expires-in must be greater than zero, got "${raw}".`);
6755
+ }
6756
+ return now + amount * DURATION_UNIT_MS[match[2].toLowerCase()];
6757
+ }
6758
+
6759
+ // src/lib/eval-run-exit-code.ts
6760
+ var SEVERITY_ORDER = [1, 3, 4, 5, 0];
6761
+ function worstOf(codes) {
6762
+ for (const code of SEVERITY_ORDER) {
6763
+ if (codes.includes(code)) return code;
6764
+ }
6765
+ return 0;
6766
+ }
6767
+ function runExitCode(run) {
6768
+ const codes = [];
6769
+ if (isNonVerdictRunStatus(run.status)) {
6770
+ codes.push(5);
6771
+ } else if (isNonVerdictRunResult(run.result)) {
6772
+ codes.push(5);
6773
+ } else if (run.result === "failed") {
6774
+ codes.push(1);
6775
+ } else if (run.result === "passed") {
6776
+ codes.push(0);
6777
+ } else {
6778
+ codes.push(5);
6779
+ }
6780
+ if (run.reportingFailed) {
6781
+ codes.push(classifyWaitErrorExitCode(run.reportingFailedErrorCode));
6782
+ }
6783
+ return worstOf(codes);
6784
+ }
6785
+ function evalRunWaitExitCode(input) {
6786
+ const codes = [];
6787
+ if (input.launchOutcome !== "started") {
6788
+ codes.push(4);
6789
+ }
6790
+ for (const run of input.runs) {
6791
+ codes.push(runExitCode(run));
6792
+ }
6793
+ for (const waitError of input.waitErrors) {
6794
+ codes.push(classifyWaitErrorExitCode(waitError.errorCode));
6795
+ }
6796
+ return worstOf(codes);
6797
+ }
6798
+ var AUTH_SHAPED_CODES = /* @__PURE__ */ new Set([
6799
+ "UNAUTHORIZED",
6800
+ "FORBIDDEN",
6801
+ "OAUTH_REQUIRED"
6802
+ ]);
6803
+ var INVALID_SHAPED_CODES = /* @__PURE__ */ new Set([
6804
+ "VALIDATION_ERROR",
6805
+ "NOT_FOUND",
6806
+ "CONFLICT",
6807
+ "UNSUPPORTED"
6808
+ ]);
6809
+ var BILLING_SHAPED_DETAIL_CODES = /* @__PURE__ */ new Set([
6810
+ "billing_limit_reached",
6811
+ "billing_feature_not_included"
6812
+ ]);
6813
+ function isBillingShapedDetail(details) {
6814
+ if (!details || typeof details !== "object") return false;
6815
+ const inner = details.code;
6816
+ return typeof inner === "string" && BILLING_SHAPED_DETAIL_CODES.has(inner);
6817
+ }
6818
+ function classifyLaunchErrorExitCode(code, details) {
6819
+ if (isBillingShapedDetail(details)) return 4;
6820
+ if (code !== void 0 && AUTH_SHAPED_CODES.has(code)) return 3;
6821
+ if (code !== void 0 && INVALID_SHAPED_CODES.has(code)) return 2;
6822
+ return 4;
6823
+ }
6824
+ function classifyWaitErrorExitCode(code) {
6825
+ if (code !== void 0 && AUTH_SHAPED_CODES.has(code)) return 3;
6826
+ return 5;
6827
+ }
6828
+ function decisionSummaryFromIterations(input) {
6829
+ return buildEvalRunDecisionSummary({
6830
+ projectId: input.projectId,
6831
+ run: input.run,
6832
+ iterations: input.iterations.items,
6833
+ page: { complete: input.iterations.complete }
6834
+ });
6835
+ }
6836
+ async function readEvalRunDecisionSummary(client, signal, projectId, run) {
6837
+ return readEvalRunDecisionSummary$1(client, signal, projectId, run, {
6838
+ limit: 200
6839
+ });
6840
+ }
6411
6841
 
6412
6842
  // src/lib/terminal-image.ts
6413
6843
  var ESC = "\x1B";
@@ -6951,28 +7381,65 @@ function launchFailureCases(result) {
6951
7381
  ];
6952
7382
  });
6953
7383
  }
6954
- function gateReportCase(report) {
6955
- const passed = report.outcome === "passed";
7384
+ function gateReportCase(report, baselineProvenance) {
7385
+ const waived = report.outcome === "waived";
7386
+ const passed = report.outcome === "passed" || waived;
6956
7387
  return {
6957
7388
  id: "gate",
6958
- title: "Eval gate",
7389
+ title: waived ? "Eval gate (WAIVED)" : "Eval gate",
6959
7390
  category: "gate",
6960
7391
  passed,
6961
- ...passed ? {} : {
6962
- error: report.verdicts.filter((verdict) => verdict.status !== "passed").map((verdict) => verdict.message).join("; ")
7392
+ // Only a real FAILED gate is a confirmed regression. `incomplete` and
7393
+ // `usage_error` still fail this row (nothing was established either
7394
+ // way), but reporting them as `breaking` — the same class a genuine
7395
+ // failure gets — would claim a defect the run never observed. Mirrors
7396
+ // `gateCase` in sdk/src/run-compare.ts.
7397
+ classification: report.outcome === "failed" ? "breaking" : waived ? "informational" : passed ? "non_breaking" : "informational",
7398
+ // The failing verdicts are carried on a WAIVED case too. The waiver
7399
+ // explains why the build was not blocked; it is not a reason to stop
7400
+ // saying what failed.
7401
+ ...passed && !waived ? {} : {
7402
+ error: report.verdicts.filter(
7403
+ (verdict) => verdict.status !== "passed" && verdict.status !== "waived"
7404
+ ).map((verdict) => verdict.message).join("; ")
6963
7405
  },
6964
- details: report
7406
+ ...report.waiver ? {
7407
+ waiver: {
7408
+ id: report.waiver.id,
7409
+ reason: report.waiver.reason,
7410
+ expiresAt: report.waiver.expiresAt,
7411
+ createdAt: report.waiver.createdAt,
7412
+ createdBy: report.waiver.createdBy,
7413
+ createdByEmail: report.waiver.createdByEmail,
7414
+ policySnapshot: report.waiver.policySnapshot
7415
+ }
7416
+ } : {},
7417
+ // The baseline provenance rides along on the case row too, not only in
7418
+ // the report's top-level metadata: `--reporter junit-xml` has no other
7419
+ // place to carry it, and a regression visible in the exit code but
7420
+ // absent from the artifact is a reporting bug.
7421
+ details: baselineProvenance ? { ...report, baseline: baselineProvenance } : report
6965
7422
  };
6966
7423
  }
6967
7424
  var DEFAULT_GATE_WAIT_TIMEOUT_MS = 6e5;
6968
7425
  async function runEvalGate(options, command) {
6969
7426
  const globalOptions = getGlobalOptions(command);
7427
+ const runId = options.run?.trim();
7428
+ if (!runId) {
7429
+ throw usageError("--run <id> is required. Pass the eval run to gate.");
7430
+ }
6970
7431
  const reporter = parseReporterFormat(options.reporter);
6971
7432
  const needsReport = reporter !== void 0 || options.out !== void 0;
6972
7433
  const policy = policyFromOptions({
6973
7434
  ...options,
6974
7435
  noGatingScoreErrors: options.gatingScoreErrors === false
6975
7436
  });
7437
+ const baseline = resolveBaselineSelector({
7438
+ baseline: options.baseline,
7439
+ baselineSha: options.baselineSha,
7440
+ runId
7441
+ });
7442
+ const comparePolicy = comparePolicyFromGateOptions(options);
6976
7443
  const waitTimeoutMs = options.waitTimeout !== void 0 ? parsePositiveInteger(options.waitTimeout, "--wait-timeout") : DEFAULT_GATE_WAIT_TIMEOUT_MS;
6977
7444
  const resolved = resolveCloudProjectArgs(options);
6978
7445
  let decisionSummary;
@@ -6992,11 +7459,17 @@ async function runEvalGate(options, command) {
6992
7459
  const project = resolution.project;
6993
7460
  const deadline = Date.now() + waitTimeoutMs;
6994
7461
  let run = await client.getEvalRun(
6995
- { projectId: project.id, runId: options.run },
7462
+ { projectId: project.id, runId },
6996
7463
  { signal }
6997
7464
  );
6998
7465
  while (!TERMINAL_RUN_STATUSES.has(run.status)) {
6999
7466
  if (!options.wait) {
7467
+ decisionSummary = await readEvalRunDecisionSummary(
7468
+ client,
7469
+ signal,
7470
+ project.id,
7471
+ run
7472
+ );
7000
7473
  return {
7001
7474
  report: {
7002
7475
  outcome: "incomplete",
@@ -7008,10 +7481,17 @@ async function runEvalGate(options, command) {
7008
7481
  message: `run is ${run.status}; pass --wait, or gate it once it finishes`
7009
7482
  }
7010
7483
  ]
7011
- }
7484
+ },
7485
+ run
7012
7486
  };
7013
7487
  }
7014
7488
  if (Date.now() >= deadline) {
7489
+ decisionSummary = await readEvalRunDecisionSummary(
7490
+ client,
7491
+ signal,
7492
+ project.id,
7493
+ run
7494
+ );
7015
7495
  return {
7016
7496
  report: {
7017
7497
  outcome: "incomplete",
@@ -7023,12 +7503,13 @@ async function runEvalGate(options, command) {
7023
7503
  message: `run still ${run.status} after ${waitTimeoutMs}ms`
7024
7504
  }
7025
7505
  ]
7026
- }
7506
+ },
7507
+ run
7027
7508
  };
7028
7509
  }
7029
7510
  await new Promise((resolve) => setTimeout(resolve, 3e3));
7030
7511
  run = await client.getEvalRun(
7031
- { projectId: project.id, runId: options.run },
7512
+ { projectId: project.id, runId },
7032
7513
  { signal }
7033
7514
  );
7034
7515
  }
@@ -7040,13 +7521,23 @@ async function runEvalGate(options, command) {
7040
7521
  client,
7041
7522
  signal,
7042
7523
  project.id,
7043
- options.run
7524
+ runId
7044
7525
  );
7045
7526
  } catch (error) {
7046
7527
  iterationError = error instanceof Error ? error.message : String(error);
7047
7528
  }
7048
7529
  }
7049
7530
  if (isNonVerdictRunStatus(run.status) || isNonVerdictRunResult(run.result)) {
7531
+ decisionSummary = iterations && iterationError === void 0 ? decisionSummaryFromIterations({
7532
+ projectId: project.id,
7533
+ run,
7534
+ iterations
7535
+ }) : await readEvalRunDecisionSummary(
7536
+ client,
7537
+ signal,
7538
+ project.id,
7539
+ run
7540
+ );
7050
7541
  return {
7051
7542
  report: {
7052
7543
  outcome: "incomplete",
@@ -7066,44 +7557,60 @@ async function runEvalGate(options, command) {
7066
7557
  };
7067
7558
  }
7068
7559
  if (iterations) {
7069
- decisionSummary = buildEvalDecisionSummaryFromIterations(
7070
- iterations.items,
7560
+ decisionSummary = decisionSummaryFromIterations({
7561
+ projectId: project.id,
7562
+ run,
7563
+ iterations
7564
+ });
7565
+ } else {
7566
+ decisionSummary = await readEvalRunDecisionSummary(
7567
+ client,
7568
+ signal,
7569
+ project.id,
7570
+ run
7571
+ );
7572
+ }
7573
+ const thresholdReport = iterationError ? {
7574
+ outcome: "incomplete",
7575
+ scoreIntegrity: "unknown",
7576
+ verdicts: [
7071
7577
  {
7072
- total: run.summary?.total,
7073
- passed: run.summary?.passed,
7074
- failed: run.summary?.failed,
7075
- iterationWalkComplete: iterations.complete
7578
+ gate: "fetch",
7579
+ status: "non_gateable",
7580
+ message: `could not read the run: ${iterationError}`
7076
7581
  }
7077
- );
7078
- }
7079
- if (iterationError) {
7582
+ ]
7583
+ } : reportForRun(
7584
+ run,
7585
+ policyNeedsIterations(policy) ? iterations : void 0,
7586
+ policy
7587
+ );
7588
+ const iterationsComplete = iterationError ? false : iterations?.complete ?? !needsReport;
7589
+ if (!baseline) {
7080
7590
  return {
7081
- report: {
7082
- outcome: "incomplete",
7083
- scoreIntegrity: "unknown",
7084
- verdicts: [
7085
- {
7086
- gate: "fetch",
7087
- status: "non_gateable",
7088
- message: `could not read the run: ${iterationError}`
7089
- }
7090
- ]
7091
- },
7591
+ report: thresholdReport,
7092
7592
  run,
7093
- iterations: [],
7094
- iterationsComplete: false,
7095
- iterationError
7593
+ iterations: iterations?.items ?? [],
7594
+ iterationsComplete,
7595
+ ...iterationError ? { iterationError } : {}
7096
7596
  };
7097
7597
  }
7598
+ const baselineResult = await evaluateBaselineComparison({
7599
+ client,
7600
+ signal,
7601
+ projectId: project.id,
7602
+ runId,
7603
+ baseline,
7604
+ policy: comparePolicy,
7605
+ compareIterations: iterations
7606
+ });
7098
7607
  return {
7099
- report: reportForRun(
7100
- run,
7101
- policyNeedsIterations(policy) ? iterations : void 0,
7102
- policy
7103
- ),
7608
+ report: mergeGateReports(thresholdReport, baselineResult.report),
7104
7609
  run,
7105
7610
  iterations: iterations?.items ?? [],
7106
- iterationsComplete: iterations?.complete ?? !needsReport
7611
+ iterationsComplete,
7612
+ ...iterationError ? { iterationError } : {},
7613
+ ...baselineResult.provenance ? { baselineProvenance: baselineResult.provenance } : {}
7107
7614
  };
7108
7615
  }
7109
7616
  );
@@ -7112,27 +7619,44 @@ async function runEvalGate(options, command) {
7112
7619
  throw error;
7113
7620
  }
7114
7621
  const detail = error instanceof Error ? error.message : String(error);
7115
- writeResult(
7116
- {
7117
- gate: {
7118
- outcome: "incomplete",
7119
- scoreIntegrity: "unknown",
7120
- verdicts: [
7121
- {
7122
- gate: "fetch",
7123
- status: "non_gateable",
7124
- message: `could not read the run: ${detail}`
7125
- }
7126
- ]
7127
- },
7128
- exitCode: EVAL_GATE_INCOMPLETE_EXIT_CODE
7129
- },
7130
- globalOptions.format
7131
- );
7622
+ const report2 = {
7623
+ outcome: "incomplete",
7624
+ scoreIntegrity: "unknown",
7625
+ verdicts: [
7626
+ {
7627
+ gate: "fetch",
7628
+ status: "non_gateable",
7629
+ message: `could not read the run: ${detail}`
7630
+ }
7631
+ ]
7632
+ };
7633
+ const structured2 = needsReport ? buildEvalRunReport([], {
7634
+ cases: [gateReportCase(report2)],
7635
+ verdict: gateOutcomeVerdict(report2.outcome)
7636
+ }) : void 0;
7637
+ if (options.out && structured2) {
7638
+ await writeReporterArtifact(
7639
+ options.out,
7640
+ reporter ?? "json-summary",
7641
+ structured2
7642
+ );
7643
+ }
7644
+ if (reporter && structured2) {
7645
+ writeReporterResult(reporter, structured2);
7646
+ } else {
7647
+ writeResult(
7648
+ { gate: report2, exitCode: EVAL_GATE_INCOMPLETE_EXIT_CODE },
7649
+ globalOptions.format
7650
+ );
7651
+ }
7132
7652
  setProcessExitCode(EVAL_GATE_INCOMPLETE_EXIT_CODE);
7133
7653
  return;
7134
7654
  }
7135
- const exitCode = evalGateExitCode(outcome.report);
7655
+ const report = applyGateWaiver(
7656
+ outcome.report,
7657
+ activeWaiverForRun(outcome.run)
7658
+ );
7659
+ const exitCode = evalGateExitCode(report);
7136
7660
  const structured = needsReport ? buildEvalRunReport(
7137
7661
  outcome.run ? [
7138
7662
  {
@@ -7143,8 +7667,10 @@ async function runEvalGate(options, command) {
7143
7667
  }
7144
7668
  ] : [],
7145
7669
  {
7146
- cases: [gateReportCase(outcome.report)],
7147
- ...decisionSummary ? { decisionSummary } : {}
7670
+ cases: [gateReportCase(report, outcome.baselineProvenance)],
7671
+ verdict: gateOutcomeVerdict(report.outcome),
7672
+ ...decisionSummary ? { decisionSummary } : {},
7673
+ ...outcome.baselineProvenance ? { metadata: { baselineComparison: outcome.baselineProvenance } } : {}
7148
7674
  }
7149
7675
  ) : void 0;
7150
7676
  if (options.out && structured) {
@@ -7157,10 +7683,17 @@ async function runEvalGate(options, command) {
7157
7683
  if (reporter && structured) {
7158
7684
  writeReporterResult(reporter, structured);
7159
7685
  } else {
7160
- writeResult({ gate: outcome.report, exitCode }, globalOptions.format);
7686
+ writeResult(
7687
+ globalOptions.format === "json" ? {
7688
+ gate: report,
7689
+ exitCode,
7690
+ ...decisionSummary ? { decisionSummary } : {}
7691
+ } : { gate: report, exitCode },
7692
+ globalOptions.format
7693
+ );
7161
7694
  }
7162
7695
  if (globalOptions.format === "human" && !reporter) {
7163
- process.stderr.write(`${formatGateReport(outcome.report)}
7696
+ process.stderr.write(`${formatGateReport(report)}
7164
7697
  `);
7165
7698
  writeEvalDecisionSummary(
7166
7699
  globalOptions.format,
@@ -7172,9 +7705,110 @@ async function runEvalGate(options, command) {
7172
7705
  setProcessExitCode(exitCode);
7173
7706
  }
7174
7707
  }
7708
+ function gateSubcommandScope(command) {
7709
+ const parentOptions = command.parent?.opts() ?? {};
7710
+ const run = parentOptions.run?.trim();
7711
+ if (!run) {
7712
+ throw usageError("--run <id> is required. Pass the eval run to act on.");
7713
+ }
7714
+ return {
7715
+ run,
7716
+ ...parentOptions.project !== void 0 ? { project: parentOptions.project } : {}
7717
+ };
7718
+ }
7719
+ async function runEvalGateWaive(options, command) {
7720
+ const globalOptions = getGlobalOptions(command);
7721
+ const scope = gateSubcommandScope(command);
7722
+ const expiresAt = parseWaiverExpiry(options.expiresIn);
7723
+ const resolved = resolveCloudProjectArgs(scope);
7724
+ if (globalOptions.format === "human") {
7725
+ process.stderr.write(`Gate waiver reason: ${GATE_WAIVER_REASON_NOTICE}
7726
+ `);
7727
+ }
7728
+ const result = await runPlatformOperation(
7729
+ platformOptionsOf(command),
7730
+ globalOptions.timeout,
7731
+ async ({ client, signal }) => {
7732
+ const projects = await client.listProjects({}, { signal });
7733
+ const resolution = resolveProject(projects.items, resolved.project);
7734
+ if (!resolution.ok) {
7735
+ throw usageError(
7736
+ appendProjectLinkHint(resolution.message, resolved.projectScope)
7737
+ );
7738
+ }
7739
+ return await client.createGateWaiver(
7740
+ {
7741
+ projectId: resolution.project.id,
7742
+ runId: scope.run,
7743
+ reason: options.reason,
7744
+ expiresAt
7745
+ },
7746
+ { signal }
7747
+ );
7748
+ }
7749
+ );
7750
+ writeResult(result, globalOptions.format);
7751
+ if (globalOptions.format === "human") {
7752
+ process.stderr.write(
7753
+ `${result.status === "conflict" ? "A waiver was already in force over this run; it was NOT replaced." : "Gate waived."} ${formatGateWaiverLine(result.waiver)}
7754
+ `
7755
+ );
7756
+ process.stderr.write(
7757
+ `Republished ${result.republishedChecks} GitHub check run(s).
7758
+ `
7759
+ );
7760
+ }
7761
+ }
7762
+ async function runEvalGateUnwaive(options, command) {
7763
+ const globalOptions = getGlobalOptions(command);
7764
+ const scope = gateSubcommandScope(command);
7765
+ const resolved = resolveCloudProjectArgs(scope);
7766
+ const result = await runPlatformOperation(
7767
+ platformOptionsOf(command),
7768
+ globalOptions.timeout,
7769
+ async ({ client, signal }) => {
7770
+ const projects = await client.listProjects({}, { signal });
7771
+ const resolution = resolveProject(projects.items, resolved.project);
7772
+ if (!resolution.ok) {
7773
+ throw usageError(
7774
+ appendProjectLinkHint(resolution.message, resolved.projectScope)
7775
+ );
7776
+ }
7777
+ const projectId = resolution.project.id;
7778
+ let waiverId = options.waiver?.trim();
7779
+ if (!waiverId) {
7780
+ const { waiver } = await client.getGateWaiver(
7781
+ { projectId, runId: scope.run },
7782
+ { signal }
7783
+ );
7784
+ if (!waiver) {
7785
+ throw usageError(
7786
+ `No waiver is in force over run "${scope.run}". Pass --waiver <id> to revoke a specific one.`
7787
+ );
7788
+ }
7789
+ waiverId = waiver.id;
7790
+ }
7791
+ return await client.revokeGateWaiver(
7792
+ { projectId, runId: scope.run, waiverId },
7793
+ { signal }
7794
+ );
7795
+ }
7796
+ );
7797
+ writeResult(result, globalOptions.format);
7798
+ if (globalOptions.format === "human") {
7799
+ process.stderr.write(
7800
+ `${result.status === "already_revoked" ? "This waiver was already revoked; the existing revocation stands." : "Gate waiver revoked."} Republished ${result.republishedChecks} GitHub check run(s).
7801
+ `
7802
+ );
7803
+ }
7804
+ }
7175
7805
  async function runEvalCompare(options, command) {
7176
7806
  const globalOptions = getGlobalOptions(command);
7177
7807
  const policy = comparePolicyFromOptions(options);
7808
+ const baseSelector = compareBaseSelector({
7809
+ baseRun: options.baseRun,
7810
+ baseSha: options.baseSha
7811
+ });
7178
7812
  const reporter = parseReporterFormat(options.reporter);
7179
7813
  const resolved = resolveCloudProjectArgs(options);
7180
7814
  let outcome;
@@ -7195,7 +7829,7 @@ async function runEvalCompare(options, command) {
7195
7829
  {
7196
7830
  projectId: project.id,
7197
7831
  runId: options.run,
7198
- ...options.baseRun ? { baseRunId: options.baseRun } : {}
7832
+ ...baseSelector
7199
7833
  },
7200
7834
  { signal }
7201
7835
  );
@@ -7243,18 +7877,20 @@ async function runEvalCompare(options, command) {
7243
7877
  baseP95Ms: p95Of(baseIterations),
7244
7878
  compareP95Ms: p95Of(compareIterations)
7245
7879
  });
7880
+ const compareRunDetail = await client.getEvalRun(
7881
+ { projectId: project.id, runId: compare.compareRun.id },
7882
+ { signal }
7883
+ ).catch(() => void 0);
7246
7884
  return {
7247
7885
  report: evaluateCompareGates(input, policy),
7248
7886
  compare,
7249
- decisionSummary: compareIterations ? buildEvalDecisionSummaryFromIterations(
7250
- compareIterations.items,
7251
- {
7252
- total: compare.compareRun.summary?.total,
7253
- passed: compare.compareRun.summary?.passed,
7254
- failed: compare.compareRun.summary?.failed,
7255
- iterationWalkComplete: compareIterations.complete
7256
- }
7257
- ) : void 0,
7887
+ // About the COMPARE side only. A baseline's own failures are a
7888
+ // different run's diagnostics and would read here as this run's.
7889
+ decisionSummary: compareIterations && compareRunDetail ? decisionSummaryFromIterations({
7890
+ projectId: project.id,
7891
+ run: compareRunDetail,
7892
+ iterations: compareIterations
7893
+ }) : void 0,
7258
7894
  // Reported, NEVER gated. See `detectFlakyCases`.
7259
7895
  flakyCases: compareIterations?.complete ? detectFlakyCases(flakyInputFrom(compareIterations.items)) : []
7260
7896
  };
@@ -7303,6 +7939,11 @@ async function runEvalCompare(options, command) {
7303
7939
  if (globalOptions.format === "human" && !reporter) {
7304
7940
  process.stderr.write(`${formatGateReport(outcome.report)}
7305
7941
  `);
7942
+ writeEvalDecisionSummary(
7943
+ globalOptions.format,
7944
+ outcome.decisionSummary,
7945
+ process.stderr
7946
+ );
7306
7947
  }
7307
7948
  if (exitCode !== 0) {
7308
7949
  setProcessExitCode(exitCode);
@@ -7461,21 +8102,9 @@ var EMPTY_DIFF = {
7461
8102
  delta: null,
7462
8103
  percentDelta: null
7463
8104
  };
7464
- function p95Of(iterations) {
7465
- if (!iterations?.complete) return void 0;
7466
- const durations = iterations.items.map((iteration) => iteration.durationMs).filter((ms) => typeof ms === "number");
7467
- if (durations.length === 0 || durations.length !== iterations.items.length) {
7468
- return void 0;
7469
- }
7470
- return calculateLatencyStats(durations).p95;
7471
- }
7472
- function baselineNotFoundReason(error) {
7473
- const details = error?.details;
7474
- return typeof details === "object" && details !== null && details.reason === "BASELINE_NOT_FOUND";
7475
- }
7476
8105
  async function writeCompareResult(args, structured) {
7477
8106
  if (args.out && structured) {
7478
- await writeJsonArtifact(args.out, structured);
8107
+ await writeReporterArtifact(args.out, args.reporter ?? "json-summary", structured);
7479
8108
  }
7480
8109
  if (args.reporter && structured) {
7481
8110
  writeReporterResult(args.reporter, structured);
@@ -7770,7 +8399,7 @@ function registerEvalCommands(program) {
7770
8399
  "--wait-timeout <ms>",
7771
8400
  "Maximum time to wait for completion (default: 600000)"
7772
8401
  ).option(
7773
- "--reporter <json-summary|junit-xml>",
8402
+ "--reporter <json-summary|junit-xml|html>",
7774
8403
  "Render the completed run report to stdout"
7775
8404
  ).option(
7776
8405
  "--out <path>",
@@ -7820,90 +8449,114 @@ function registerEvalCommands(program) {
7820
8449
  const waitTimeoutMs = options.waitTimeout !== void 0 ? parsePositiveInteger(options.waitTimeout, "--wait-timeout") : DEFAULT_RUN_WAIT_TIMEOUT_MS;
7821
8450
  let webOrigin = DEFAULT_PLATFORM_ORIGIN;
7822
8451
  const resolved = resolveCloudProjectArgs(options);
7823
- const result = await runPlatformOperation(
7824
- platformOptionsOf(command),
7825
- globalOptions.timeout,
7826
- (context) => {
7827
- webOrigin = context.webOrigin;
7828
- const onDisclosure = (disclosure) => {
7829
- writeRunDisclosure(
7830
- globalOptions.format,
7831
- disclosure,
7832
- reporter === void 0 ? process.stdout : process.stderr
7833
- );
7834
- };
7835
- const onDisclosureUnavailable = (reason) => {
7836
- if (globalOptions.format !== "human") return;
7837
- const stream = reporter === void 0 ? process.stdout : process.stderr;
7838
- stream.write(`Pre-run disclosure unavailable: ${reason}
8452
+ if (options.wait) {
8453
+ try {
8454
+ preflightCloudCredentials(platformOptionsOf(command));
8455
+ } catch (error) {
8456
+ if (error instanceof CliError && error.exitCode === 2) throw error;
8457
+ if (error instanceof CliError) {
8458
+ throw new CliError(error.code, error.message, 3, error.details);
8459
+ }
8460
+ throw error;
8461
+ }
8462
+ }
8463
+ let result;
8464
+ try {
8465
+ result = await runPlatformOperation(
8466
+ platformOptionsOf(command),
8467
+ globalOptions.timeout,
8468
+ (context) => {
8469
+ webOrigin = context.webOrigin;
8470
+ const onDisclosure = (disclosure) => {
8471
+ writeRunDisclosure(
8472
+ globalOptions.format,
8473
+ disclosure,
8474
+ reporter === void 0 ? process.stdout : process.stderr
8475
+ );
8476
+ };
8477
+ const onDisclosureUnavailable = (reason) => {
8478
+ if (globalOptions.format !== "human") return;
8479
+ const stream = reporter === void 0 ? process.stdout : process.stderr;
8480
+ stream.write(`Pre-run disclosure unavailable: ${reason}
7839
8481
  `);
7840
- };
7841
- if (options.file) {
7842
- const source = readSuiteFileInput(options.file);
7843
- return executeEvalRunFromFile(
8482
+ };
8483
+ if (options.file) {
8484
+ const source = readSuiteFileInput(options.file);
8485
+ return executeEvalRunFromFile(
8486
+ {
8487
+ client: context.client,
8488
+ signal: context.signal,
8489
+ onDisclosure,
8490
+ onDisclosureUnavailable
8491
+ },
8492
+ {
8493
+ source,
8494
+ label: options.file === "-" ? "<stdin>" : options.file,
8495
+ projectSelector: resolved.project ?? options.project,
8496
+ knobs: {
8497
+ ...options.server ? { server: options.server } : {},
8498
+ ...options.environment ? { environment: options.environment } : {},
8499
+ ...options.host ? { host: options.host } : {},
8500
+ ...options.allTargets ? { allTargets: true } : {},
8501
+ ...options.repetitions !== void 0 || options.iterations !== void 0 ? { repetitions: options.repetitions ?? options.iterations } : {},
8502
+ ...options.case?.length ? { case: options.case } : {},
8503
+ ...options.excludeSkills ? { excludeSkills: true } : {},
8504
+ ...options.refreshSnapshot ? { refreshSnapshot: true } : {},
8505
+ ...options.notes !== void 0 ? { notes: options.notes } : {},
8506
+ ...options.minPassRate !== void 0 ? { minPassRate: options.minPassRate } : {},
8507
+ ...options.matchOptions ? {
8508
+ matchOptions: parseMatchOptionsOption(
8509
+ options.matchOptions
8510
+ )
8511
+ } : {},
8512
+ ...options.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {},
8513
+ ...composeField(options)
8514
+ }
8515
+ }
8516
+ );
8517
+ }
8518
+ return runEvalSuiteOperation.execute(
8519
+ {
8520
+ project: resolved.project ?? options.project,
8521
+ suite: options.suite,
8522
+ ...options.server ? { servers: options.server } : {},
8523
+ // ONE value maps to the singular field, several to the plural:
8524
+ // the op rejects sending both, and the singular carries the
8525
+ // long-standing description a caller may already rely on.
8526
+ ...selectorField("environment", "environments", options.environment),
8527
+ ...selectorField("host", "hosts", options.host),
8528
+ ...options.allTargets ? { allAttached: true } : {},
8529
+ ...options.repetitions !== void 0 ? { repetitions: options.repetitions } : options.iterations !== void 0 ? { iterations: options.iterations } : {},
8530
+ ...options.case?.length ? { cases: options.case } : {},
8531
+ ...options.excludeSkills ? { excludeSkills: true } : {},
8532
+ ...options.refreshSnapshot ? { refreshSnapshot: true } : {},
8533
+ ...options.notes !== void 0 ? { notes: options.notes } : {},
8534
+ ...options.minPassRate !== void 0 ? { minPassRate: options.minPassRate } : {},
8535
+ ...options.matchOptions ? { matchOptions: parseMatchOptionsOption(options.matchOptions) } : {},
8536
+ ...options.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {},
8537
+ ...composeField(options)
8538
+ },
7844
8539
  {
7845
8540
  client: context.client,
7846
8541
  signal: context.signal,
7847
8542
  onDisclosure,
7848
8543
  onDisclosureUnavailable
7849
- },
7850
- {
7851
- source,
7852
- label: options.file === "-" ? "<stdin>" : options.file,
7853
- projectSelector: resolved.project ?? options.project,
7854
- knobs: {
7855
- ...options.server ? { server: options.server } : {},
7856
- ...options.environment ? { environment: options.environment } : {},
7857
- ...options.host ? { host: options.host } : {},
7858
- ...options.allTargets ? { allTargets: true } : {},
7859
- ...options.repetitions !== void 0 || options.iterations !== void 0 ? { repetitions: options.repetitions ?? options.iterations } : {},
7860
- ...options.case?.length ? { case: options.case } : {},
7861
- ...options.excludeSkills ? { excludeSkills: true } : {},
7862
- ...options.refreshSnapshot ? { refreshSnapshot: true } : {},
7863
- ...options.notes !== void 0 ? { notes: options.notes } : {},
7864
- ...options.minPassRate !== void 0 ? { minPassRate: options.minPassRate } : {},
7865
- ...options.matchOptions ? {
7866
- matchOptions: parseMatchOptionsOption(
7867
- options.matchOptions
7868
- )
7869
- } : {},
7870
- ...options.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {},
7871
- ...composeField(options)
7872
- }
7873
8544
  }
7874
8545
  );
7875
- }
7876
- return runEvalSuiteOperation.execute(
7877
- {
7878
- project: resolved.project ?? options.project,
7879
- suite: options.suite,
7880
- ...options.server ? { servers: options.server } : {},
7881
- // ONE value maps to the singular field, several to the plural:
7882
- // the op rejects sending both, and the singular carries the
7883
- // long-standing description a caller may already rely on.
7884
- ...selectorField("environment", "environments", options.environment),
7885
- ...selectorField("host", "hosts", options.host),
7886
- ...options.allTargets ? { allAttached: true } : {},
7887
- ...options.repetitions !== void 0 ? { repetitions: options.repetitions } : options.iterations !== void 0 ? { iterations: options.iterations } : {},
7888
- ...options.case?.length ? { cases: options.case } : {},
7889
- ...options.excludeSkills ? { excludeSkills: true } : {},
7890
- ...options.refreshSnapshot ? { refreshSnapshot: true } : {},
7891
- ...options.notes !== void 0 ? { notes: options.notes } : {},
7892
- ...options.minPassRate !== void 0 ? { minPassRate: options.minPassRate } : {},
7893
- ...options.matchOptions ? { matchOptions: parseMatchOptionsOption(options.matchOptions) } : {},
7894
- ...options.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {},
7895
- ...composeField(options)
7896
- },
7897
- {
7898
- client: context.client,
7899
- signal: context.signal,
7900
- onDisclosure,
7901
- onDisclosureUnavailable
7902
- }
8546
+ },
8547
+ { projectScope: resolved.projectScope }
8548
+ );
8549
+ } catch (error) {
8550
+ if (options.wait && error instanceof CliError && error.exitCode !== 2) {
8551
+ throw new CliError(
8552
+ error.code,
8553
+ error.message,
8554
+ classifyLaunchErrorExitCode(error.code, error.details),
8555
+ error.details
7903
8556
  );
7904
- },
7905
- { projectScope: resolved.projectScope }
7906
- );
8557
+ }
8558
+ throw error;
8559
+ }
7907
8560
  if (!options.wait) {
7908
8561
  writeResult(result, globalOptions.format);
7909
8562
  writeRunGroupSummary(globalOptions.format, webOrigin, result);
@@ -7913,6 +8566,17 @@ function registerEvalCommands(program) {
7913
8566
  return;
7914
8567
  }
7915
8568
  const needsReport = reporter !== void 0 || options.out !== void 0;
8569
+ try {
8570
+ preflightCloudCredentials(platformOptionsOf(command));
8571
+ } catch (error) {
8572
+ writeResult({ launch: result, runs: [] }, globalOptions.format);
8573
+ writeRunGroupSummary(globalOptions.format, webOrigin, result);
8574
+ if (error instanceof CliError && error.exitCode === 2) throw error;
8575
+ if (error instanceof CliError) {
8576
+ throw new CliError(error.code, error.message, 3, error.details);
8577
+ }
8578
+ throw error;
8579
+ }
7916
8580
  const completion = await runPlatformOperation(
7917
8581
  platformOptionsOf(command),
7918
8582
  Math.max(globalOptions.timeout, waitTimeoutMs),
@@ -7935,22 +8599,38 @@ function registerEvalCommands(program) {
7935
8599
  return {
7936
8600
  ok: false,
7937
8601
  runId: target.runId,
7938
- error: error instanceof Error ? error.message : String(error)
8602
+ error: error instanceof Error ? error.message : String(error),
8603
+ ...isPlatformApiError(error) ? { errorCode: error.code } : {}
7939
8604
  };
7940
8605
  }
7941
8606
  })
7942
8607
  );
7943
8608
  const runs = waited.flatMap((entry) => entry.ok ? [entry.run] : []);
7944
8609
  const waitErrors = waited.flatMap(
7945
- (entry) => !entry.ok ? [{ runId: entry.runId, error: entry.error }] : []
8610
+ (entry) => !entry.ok ? [
8611
+ {
8612
+ runId: entry.runId,
8613
+ error: entry.error,
8614
+ ...entry.errorCode ? { errorCode: entry.errorCode } : {}
8615
+ }
8616
+ ] : []
7946
8617
  );
7947
8618
  if (!needsReport) {
8619
+ const soloSummary = globalOptions.format === "human" && result.targets.length === 1 && runs.length === 1 && TERMINAL_RUN_STATUSES.has(runs[0].status) ? await readEvalRunDecisionSummary(
8620
+ client,
8621
+ signal,
8622
+ result.project.id,
8623
+ runs[0]
8624
+ ) : void 0;
7948
8625
  return {
7949
8626
  runs,
7950
8627
  waitErrors,
7951
- reportInputs: []
8628
+ reportInputs: [],
8629
+ iterationErrorCodes: /* @__PURE__ */ new Map(),
8630
+ ...soloSummary ? { decisionSummary: soloSummary } : {}
7952
8631
  };
7953
8632
  }
8633
+ const iterationErrorCodes = /* @__PURE__ */ new Map();
7954
8634
  const reportInputs = await Promise.all(
7955
8635
  runs.map(async (run) => {
7956
8636
  try {
@@ -7966,6 +8646,9 @@ function registerEvalCommands(program) {
7966
8646
  iterationsComplete: iterations.complete
7967
8647
  };
7968
8648
  } catch (error) {
8649
+ if (isPlatformApiError(error)) {
8650
+ iterationErrorCodes.set(run.id, error.code);
8651
+ }
7969
8652
  return {
7970
8653
  run,
7971
8654
  iterations: [],
@@ -7975,7 +8658,22 @@ function registerEvalCommands(program) {
7975
8658
  }
7976
8659
  })
7977
8660
  );
7978
- return { runs, waitErrors, reportInputs };
8661
+ const solo = result.targets.length === 1 && runs.length === 1 && reportInputs.length === 1 ? reportInputs[0] : void 0;
8662
+ const decisionSummary = solo && solo.iterationError === void 0 ? decisionSummaryFromIterations({
8663
+ projectId: result.project.id,
8664
+ run: solo.run,
8665
+ iterations: {
8666
+ items: [...solo.iterations],
8667
+ complete: solo.iterationsComplete
8668
+ }
8669
+ }) : void 0;
8670
+ return {
8671
+ runs,
8672
+ waitErrors,
8673
+ reportInputs,
8674
+ iterationErrorCodes,
8675
+ ...decisionSummary ? { decisionSummary } : {}
8676
+ };
7979
8677
  },
7980
8678
  {
7981
8679
  projectScope: resolved.projectScope,
@@ -7997,14 +8695,39 @@ function registerEvalCommands(program) {
7997
8695
  project: result.project,
7998
8696
  suite: result.suite,
7999
8697
  ...result.runGroupId ? { runGroupId: result.runGroupId } : {}
8000
- }
8698
+ },
8699
+ ...completion.decisionSummary ? { decisionSummary: completion.decisionSummary } : {}
8001
8700
  }) : void 0;
8701
+ const reportingErrors = completion.reportInputs.filter(
8702
+ (input) => !input.iterationsComplete || input.iterationError
8703
+ );
8704
+ const reportingFailedRunIds = new Set(
8705
+ reportingErrors.map((input) => input.run.id)
8706
+ );
8707
+ const runOutcomes = completion.runs.map(
8708
+ (run) => ({
8709
+ status: run.status,
8710
+ result: run.result,
8711
+ reportingFailed: reportingFailedRunIds.has(run.id),
8712
+ reportingFailedErrorCode: completion.iterationErrorCodes.get(run.id)
8713
+ })
8714
+ );
8715
+ const code = evalRunWaitExitCode({
8716
+ launchOutcome: result.outcome,
8717
+ runs: runOutcomes,
8718
+ waitErrors: completion.waitErrors
8719
+ });
8720
+ let outWriteError;
8002
8721
  if (options.out && report) {
8003
- await writeReporterArtifact(
8004
- options.out,
8005
- reporter ?? "json-summary",
8006
- report
8007
- );
8722
+ try {
8723
+ await writeReporterArtifact(
8724
+ options.out,
8725
+ reporter ?? "json-summary",
8726
+ report
8727
+ );
8728
+ } catch (error) {
8729
+ outWriteError = error instanceof Error ? error.message : String(error);
8730
+ }
8008
8731
  }
8009
8732
  if (reporter && report) {
8010
8733
  writeReporterResult(reporter, report);
@@ -8014,19 +8737,26 @@ function registerEvalCommands(program) {
8014
8737
  globalOptions.format
8015
8738
  );
8016
8739
  writeRunGroupSummary(globalOptions.format, webOrigin, result);
8740
+ writeEvalDecisionSummary(
8741
+ globalOptions.format,
8742
+ completion.decisionSummary,
8743
+ process.stdout
8744
+ );
8745
+ }
8746
+ if (outWriteError !== void 0) {
8747
+ throw cliError("OUT_WRITE_FAILED", outWriteError, worstOf([code, 4]));
8017
8748
  }
8018
- const reportingErrors = completion.reportInputs.filter(
8019
- (input) => !input.iterationsComplete || input.iterationError
8020
- );
8021
8749
  if (reportingErrors.length > 0 || completion.waitErrors.length > 0) {
8022
8750
  const affectedRunIds = [
8023
8751
  ...reportingErrors.map((input) => input.run.id),
8024
8752
  ...completion.waitErrors.map((entry) => entry.runId)
8025
8753
  ];
8026
- throw operationalError(
8754
+ throw cliError(
8755
+ "OPERATIONAL_ERROR",
8027
8756
  needsReport ? `Completed eval run report is incomplete for: ${affectedRunIds.join(
8028
8757
  ", "
8029
8758
  )}.` : `Did not observe completion for: ${affectedRunIds.join(", ")}.`,
8759
+ code,
8030
8760
  {
8031
8761
  // Machine-readable, because the message is not: a pipeline that
8032
8762
  // needs to resume or cancel these runs should not have to parse
@@ -8036,9 +8766,7 @@ function registerEvalCommands(program) {
8036
8766
  }
8037
8767
  );
8038
8768
  }
8039
- if (result.outcome !== "started") {
8040
- setProcessExitCode(1);
8041
- }
8769
+ setProcessExitCode(code);
8042
8770
  }
8043
8771
  );
8044
8772
  addProjectOption(
@@ -8061,25 +8789,8 @@ function registerEvalCommands(program) {
8061
8789
  },
8062
8790
  { client: context.client, signal: context.signal }
8063
8791
  );
8064
- if (globalOptions.format === "human" && TERMINAL_RUN_STATUSES.has(result2.run.status) && result2.run.result === "failed") {
8065
- try {
8066
- const iterations = await fetchAllIterations(
8067
- context.client,
8068
- context.signal,
8069
- result2.project.id,
8070
- result2.run.id
8071
- );
8072
- decisionSummary = buildEvalDecisionSummaryFromIterations(
8073
- iterations.items,
8074
- {
8075
- total: result2.run.summary?.total,
8076
- passed: result2.run.summary?.passed,
8077
- failed: result2.run.summary?.failed,
8078
- iterationWalkComplete: iterations.complete
8079
- }
8080
- );
8081
- } catch {
8082
- }
8792
+ if (globalOptions.format === "human" && TERMINAL_RUN_STATUSES.has(result2.run.status) && result2.run.result !== "passed") {
8793
+ decisionSummary = result2.decisionSummary;
8083
8794
  }
8084
8795
  return result2;
8085
8796
  },
@@ -8088,18 +8799,22 @@ function registerEvalCommands(program) {
8088
8799
  quiet: globalOptions.quiet
8089
8800
  }
8090
8801
  );
8091
- writeResult(result, globalOptions.format);
8802
+ const resultForOutput = globalOptions.format === "human" ? (() => {
8803
+ const { decisionSummary: _decisionSummary, ...humanResult } = result;
8804
+ return humanResult;
8805
+ })() : result;
8806
+ writeResult(resultForOutput, globalOptions.format);
8092
8807
  writeJudgeSummary(globalOptions.format, result.run.judges);
8093
- writeRunLink(globalOptions.format, webOrigin, {
8094
- projectId: result.project.id,
8095
- suiteId: result.run.suiteId,
8096
- runId: result.run.id
8097
- });
8098
8808
  writeEvalDecisionSummary(
8099
8809
  globalOptions.format,
8100
8810
  decisionSummary,
8101
8811
  process.stdout
8102
8812
  );
8813
+ writeRunLink(globalOptions.format, webOrigin, {
8814
+ projectId: result.project.id,
8815
+ suiteId: result.run.suiteId,
8816
+ runId: result.run.id
8817
+ });
8103
8818
  }
8104
8819
  );
8105
8820
  addProjectOption(
@@ -8207,10 +8922,10 @@ function registerEvalCommands(program) {
8207
8922
  );
8208
8923
  }
8209
8924
  );
8210
- addProjectOption(
8925
+ const gateCommand = addProjectOption(
8211
8926
  evals.command("gate").description(
8212
- "Apply a pass/fail policy to a finished eval run and set an exit code (0 pass, 1 eval failure, 2 usage, 3 incomplete)"
8213
- ).requiredOption("--run <id>", "Eval run ID (from `eval run`)")
8927
+ "Apply a pass/fail policy to a finished eval run and set an exit code (0 pass or waived, 1 eval failure, 2 usage, 3 incomplete)"
8928
+ ).option("--run <id>", "Eval run ID (from `eval run`)")
8214
8929
  ).option(
8215
8930
  "--min-pass-rate-percent <0-100>",
8216
8931
  "Minimum share of iterations that must pass, as a percentage"
@@ -8227,11 +8942,29 @@ function registerEvalCommands(program) {
8227
8942
  "Minimum mean score for one scorer (repeatable)",
8228
8943
  collectRepeatable,
8229
8944
  []
8945
+ ).option(
8946
+ "--baseline <runId>",
8947
+ "Baseline run ID to gate a regression delta against; mutually exclusive with --baseline-sha"
8948
+ ).option(
8949
+ "--baseline-sha <sha>",
8950
+ "Baseline source commit SHA, resolved to the completed run in this suite recorded against it; mutually exclusive with --baseline"
8951
+ ).option(
8952
+ "--min-sample-size <n>",
8953
+ "Iterations required on EACH side before a pass-rate regression is decidable (default 5); requires --baseline or --baseline-sha"
8954
+ ).option(
8955
+ "--min-effect-size-percent <0-100>",
8956
+ "Smallest pass-rate drop worth failing on, as a percentage (default 1); requires --baseline or --baseline-sha"
8957
+ ).option(
8958
+ "--gate-deterministic-regressions",
8959
+ "Fail if a deterministic gating scorer flipped from passed to failed; requires --baseline or --baseline-sha"
8960
+ ).option(
8961
+ "--max-p95-latency-increase-ms <ms>",
8962
+ "Fail if p95 end-to-end latency rose by more than this many milliseconds vs the baseline; requires --baseline or --baseline-sha"
8230
8963
  ).option("--wait", "Poll until the run reaches a terminal status").option(
8231
8964
  "--wait-timeout <ms>",
8232
8965
  "Give up waiting after this many milliseconds (default 600000)"
8233
8966
  ).option(
8234
- "--reporter <json-summary|junit-xml>",
8967
+ "--reporter <json-summary|junit-xml|html>",
8235
8968
  "Write a structured report to stdout instead of the default output"
8236
8969
  ).option(
8237
8970
  "--out <path>",
@@ -8241,13 +8974,35 @@ function registerEvalCommands(program) {
8241
8974
  await runEvalGate(options, command);
8242
8975
  }
8243
8976
  );
8977
+ gateCommand.command("waive").description(
8978
+ "Override a FAILING run's gate until an expiry you name. Does not make the run pass: the run keeps its result, and the waiver is named in every report and check."
8979
+ ).requiredOption(
8980
+ "--reason <text>",
8981
+ `Why the gate is being overridden (max ${GATE_WAIVER_MAX_REASON_LENGTH} characters). ${GATE_WAIVER_REASON_NOTICE}`
8982
+ ).requiredOption(
8983
+ "--expires-in <duration>",
8984
+ "How long the waiver lasts, e.g. 30m, 12h, 7d. Capped at 30 days by the platform \u2014 there is no permanent waiver."
8985
+ ).action(async (options, command) => {
8986
+ await runEvalGateWaive(options, command);
8987
+ });
8988
+ gateCommand.command("unwaive").description(
8989
+ "Revoke a gate waiver, putting the gate and the GitHub Check Run back. Idempotent."
8990
+ ).option(
8991
+ "--waiver <id>",
8992
+ "Waiver ID to revoke. Omit to revoke the waiver currently in force over --run."
8993
+ ).action(async (options, command) => {
8994
+ await runEvalGateUnwaive(options, command);
8995
+ });
8244
8996
  addProjectOption(
8245
8997
  evals.command("compare").description(
8246
8998
  "Compare a finished eval run against a baseline and set an exit code (0 pass, 1 regression, 2 usage, 3 incomplete)"
8247
8999
  ).requiredOption("--run <id>", "Eval run ID to compare")
8248
9000
  ).option(
8249
9001
  "--base-run <id>",
8250
- "Baseline run ID (defaults to the nearest earlier completed run in the same suite)"
9002
+ "Baseline run ID (defaults to the nearest earlier completed run in the same suite); mutually exclusive with --base-sha"
9003
+ ).option(
9004
+ "--base-sha <sha>",
9005
+ "Baseline source commit SHA, resolved to the completed run in this suite recorded against it; mutually exclusive with --base-run"
8251
9006
  ).option(
8252
9007
  "--gate-regressions",
8253
9008
  "Fail on a statistically significant pass-rate regression"
@@ -8264,9 +9019,12 @@ function registerEvalCommands(program) {
8264
9019
  "--max-p95-latency-increase-ms <ms>",
8265
9020
  "Fail if p95 end-to-end latency rose by more than this many milliseconds"
8266
9021
  ).option(
8267
- "--reporter <json-summary|junit-xml>",
9022
+ "--reporter <json-summary|junit-xml|html>",
8268
9023
  "Write a structured report to stdout instead of the default output"
8269
- ).option("--out <path>", "Write the structured report to a JSON file").action(
9024
+ ).option(
9025
+ "--out <path>",
9026
+ "Atomically write the structured report selected by --reporter (default: json-summary)"
9027
+ ).action(
8270
9028
  async (options, command) => {
8271
9029
  await runEvalCompare(options, command);
8272
9030
  }
@@ -13695,6 +14453,11 @@ function registerConformanceRunCommand(program) {
13695
14453
  const reporter = parseReporterFormat(
13696
14454
  options.reporter
13697
14455
  );
14456
+ if (reporter === "html") {
14457
+ throw usageError(
14458
+ 'The "html" reporter is not available for this command yet. Use "json-summary" or "junit-xml".'
14459
+ );
14460
+ }
13698
14461
  const format = resolveConformanceOutputFormatForCli(
13699
14462
  globalOptions.format,
13700
14463
  process.stdout.isTTY,
@@ -15759,7 +16522,7 @@ function registerServerCommands(program) {
15759
16522
  "Diff failure policy: breaking, any, or none"
15760
16523
  ).option(
15761
16524
  "--reporter <reporter>",
15762
- "Structured reporter output: json-summary or junit-xml"
16525
+ "Structured reporter output: json-summary, junit-xml, or html"
15763
16526
  ).option("--out <path>", "Write the raw diff JSON artifact to a file")
15764
16527
  )
15765
16528
  ).action(async (options, command) => {
@@ -18007,7 +18770,7 @@ function registerToolsCommands(program) {
18007
18770
  "Evaluate the tool-call outcome policy against isError"
18008
18771
  ).option(
18009
18772
  "--reporter <reporter>",
18010
- "Structured reporter output: json-summary or junit-xml"
18773
+ "Structured reporter output: json-summary, junit-xml, or html"
18011
18774
  ).option(
18012
18775
  "--debug-out <path>",
18013
18776
  "Write a structured debug artifact to a file"