@valerypopoff/rivet2-evaluations 2.4.0 → 2.5.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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../src/index.ts", "../../src/types.ts", "../../src/canonical.ts", "../../src/assertions.ts", "../../src/normalization.ts", "../../src/dataTypes.ts", "../../src/runner.ts", "../../src/datasetTransfer.ts", "../../src/serialization.ts", "../../src/library.ts", "../../src/store.ts", "../../src/suiteTransfer.ts"],
4
- "sourcesContent": ["export * from './types.js';\nexport * from './canonical.js';\nexport * from './assertions.js';\nexport * from './runner.js';\nexport * from './store.js';\nexport * from './serialization.js';\nexport * from './datasetTransfer.js';\nexport * from './suiteTransfer.js';\nexport * from './dataTypes.js';\nexport * from './normalization.js';\nexport * from './library.js';\n", "import type { GraphId, Project, ProjectId } from '@valerypopoff/rivet2-core';\n\n/** Values saved in evaluation datasets, assertions, evidence, and run artifacts. */\nexport type PortableJson = null | boolean | number | string | PortableJson[] | { [key: string]: PortableJson };\n\nexport type EvaluationDatasetFieldRole = 'input' | 'expected' | 'metadata';\n\nexport type EvaluationDatasetField = {\n id: string;\n name: string;\n description?: string;\n /** Rivet data type identifier. The runner validates bindings against the target graph. */\n dataType: string;\n role: EvaluationDatasetFieldRole;\n required?: boolean;\n};\n\nexport type EvaluationDatasetCase = {\n id: string;\n name: string;\n enabled?: boolean;\n tags?: string[];\n note?: string;\n values: Record<string, PortableJson>;\n};\n\nexport type EvaluationDataset = {\n id: string;\n /**\n * Legacy project ownership retained only while importing older project\n * files. Locally persisted evaluation datasets intentionally omit it so\n * they can be reused with any currently open project.\n */\n projectId?: ProjectId;\n name: string;\n fields: EvaluationDatasetField[];\n cases: EvaluationDatasetCase[];\n /** Derived from fields and cases; stored to make snapshot reuse inspectable. */\n contentFingerprint?: string;\n};\n\nexport type EvaluationInputBinding = {\n graphInputId: string;\n datasetFieldId: string;\n};\n\nexport type EvaluationExpectedSource =\n | { kind: 'literal'; value: PortableJson }\n | { kind: 'dataset-field'; fieldId: string };\n\nexport type EvaluationAssertionOperator =\n | 'equals'\n | 'not-equals'\n | 'contains'\n | 'matches-regex'\n | 'type-is'\n | 'json-schema'\n | 'number-at-least'\n | 'number-at-most'\n | 'number-between'\n | 'array-includes'\n | 'set-overlaps'\n | 'contains-any'\n | 'contains-all';\n\nexport type EvaluationAssertion = {\n id: string;\n name: string;\n required?: boolean;\n outputPath: string;\n operator: EvaluationAssertionOperator;\n expected: EvaluationExpectedSource;\n};\n\nexport type EvaluationEvaluatorContextInput = 'case' | 'inputs' | 'expected' | 'outputs' | 'run';\n\nexport type EvaluationEvaluatorInputSource =\n | { kind: 'dataset-field'; fieldId: string }\n | { kind: 'target-output'; outputId: string }\n | { kind: 'context'; context: EvaluationEvaluatorContextInput };\n\nexport type EvaluationEvaluatorInputBinding = {\n graphInputId: string;\n source: EvaluationEvaluatorInputSource;\n};\n\nexport type EvaluationGraphEvaluator = {\n id: string;\n name: string;\n graphId: GraphId;\n /**\n * Explicit evaluator Graph Input mappings. Missing means an older evaluator\n * may use the five reserved context inputs; an empty array explicitly opts\n * into direct mapping for a graph with no required inputs.\n */\n inputBindings?: EvaluationEvaluatorInputBinding[];\n required?: boolean;\n scoreWeight?: number;\n runOnTargetError?: boolean;\n};\n\n/**\n * Pass/fail suites evaluate required assertions and evaluator verdicts.\n * Scoring evaluator graphs return scores on the user-facing 0..100 scale.\n * Runs store normalized scores internally for aggregation and compatibility.\n */\nexport type EvaluationSuiteMode = 'pass-fail' | 'scoring';\n\nexport type EvaluationThreshold =\n | { id: string; metric: 'pass-rate' | 'mean-score'; operator: 'at-least'; value: number }\n | {\n id: string;\n metric:\n | 'target-error-rate'\n | 'evaluator-error-rate'\n | 'tool-failure-rate'\n | 'average-cost'\n | 'total-cost'\n | 'average-latency-ms'\n | 'p95-latency-ms';\n operator: 'at-most';\n value: number;\n }\n | { id: string; metric: `custom:${string}`; operator: 'at-least' | 'at-most'; value: number }\n | { id: string; metric: string; operator: 'max-regression'; value: number };\n\nexport type EvaluationRunConfiguration = {\n trialCount?: number;\n concurrency?: number;\n timeoutMs?: number;\n seed?: number;\n seedGraphInputId?: string;\n recordingRetention?: 'failures-and-baselines' | 'all';\n};\n\nexport type EvaluationSuite = {\n id: string;\n name: string;\n description?: string;\n tags?: string[];\n targetGraphId: GraphId;\n datasetId: string;\n inputBindings: EvaluationInputBinding[];\n assertions: EvaluationAssertion[];\n evaluators: EvaluationGraphEvaluator[];\n /** Missing values are legacy pass/fail suites. */\n evaluationMode?: EvaluationSuiteMode;\n configuration?: EvaluationRunConfiguration;\n thresholds?: EvaluationThreshold[];\n};\n\nexport type EvaluationBaselineSnapshot = {\n id: string;\n suiteId: string;\n sourceRunId?: string;\n createdAt: string;\n provenance: EvaluationRunProvenance;\n aggregate: EvaluationAggregate;\n /** Optional for project baselines created before EvaluationRun v2. */\n purpose?: EvaluationRunPurpose;\n /** Optional for project baselines created before EvaluationRun v2. */\n qualityStatus?: EvaluationQualityStatus;\n /** Optional for project baselines created before EvaluationRun v2. */\n qualityReason?: EvaluationQualityReason;\n /** Optional for project baselines created before EvaluationRun v2. */\n accountingStatus?: EvaluationAccountingStatus;\n /** Optional for baselines created before score-capable suites existed. */\n evaluationMode?: EvaluationSuiteMode;\n cases: Array<\n Pick<\n EvaluationCaseAggregate,\n | 'caseId'\n | 'caseName'\n | 'passRate'\n | 'meanScore'\n | 'metrics'\n | 'evaluatedTrialCount'\n | 'passedTrialCount'\n | 'failedTrialCount'\n | 'notEvaluatedTrialCount'\n | 'unableToEvaluateTrialCount'\n | 'erroredTrialCount'\n | 'canceledTrialCount'\n | 'scoredTrialCount'\n | 'missingScoreTrialCount'\n >\n >;\n};\n\nexport type EvaluationProjectData = {\n version: 1;\n suites: EvaluationSuite[];\n baselines: EvaluationBaselineSnapshot[];\n};\n\n/**\n * Rivet-local evaluation resources. This is deliberately outside project\n * files so one Rivet instance can retain its evaluation library independently\n * of whichever project is currently open.\n */\nexport type EvaluationLibrary = {\n version: 1;\n data: EvaluationProjectData;\n datasets: EvaluationDataset[];\n /** Legacy project IDs whose embedded evaluation resources were imported. */\n migratedLegacyProjectIds: ProjectId[];\n};\n\nexport type EvaluationObservationStatus = 'passed' | 'failed' | 'scored' | 'error' | 'skipped';\n\nexport type EvaluationObservation = {\n id: string;\n kind: 'assertion' | 'graph';\n name: string;\n status: EvaluationObservationStatus;\n required: boolean;\n /**\n * Normalized internal score in the closed 0..1 range. Evaluator graphs\n * return their `result.score` on the user-facing 0..100 scale.\n */\n score?: number;\n /**\n * The configured importance of a graph evaluator's score. It is copied into\n * the observation so a stored run remains interpretable after its suite is\n * edited.\n */\n scoreWeight?: number;\n message?: string;\n evidence?: PortableJson;\n metrics?: Record<string, number>;\n durationMs?: number;\n costUsd?: number;\n /** Privacy-bounded physical provider and profile decisions from this evaluator graph. */\n providerAttempts?: PortableJson;\n /**\n * Replay artifact for this evaluator execution. The serialized recording\n * itself stays in the evaluation run store, never in the project or run\n * summary document.\n */\n recording?: EvaluationRecordingReference;\n};\n\nexport type EvaluationUsage = {\n inputTokens?: number;\n outputTokens?: number;\n cachedInputTokens?: number;\n reasoningTokens?: number;\n modelCallCount?: number;\n toolCallCount?: number;\n toolFailureCount?: number;\n costUsd?: number;\n hasUnknownCost?: boolean;\n};\n\nexport type EvaluationExecutionMetrics = EvaluationUsage & {\n durationMs: number;\n};\n\nexport type EvaluationRunPurpose = 'evaluation' | 'execution-benchmark';\n\nexport type EvaluationTrialExecutionStatus = 'completed' | 'error' | 'canceled';\n\nexport type EvaluationQualityStatus = 'passed' | 'failed' | 'scored' | 'not-evaluated' | 'unable-to-evaluate';\n\nexport type EvaluationAccountingStatus = 'complete' | 'partial';\n\nexport type EvaluationQualityReasonCode =\n | 'in-progress'\n | 'checks-passed'\n | 'checks-failed'\n | 'scores-complete'\n | 'scores-incomplete'\n | 'benchmark'\n | 'no-trial-quality-checks'\n | 'target-error'\n | 'required-check-error'\n | 'required-metric-unavailable'\n | 'thresholds-passed'\n | 'thresholds-failed'\n | 'canceled'\n | 'no-completed-trials';\n\nexport type EvaluationQualityReason = {\n code: EvaluationQualityReasonCode;\n message: string;\n};\n\nexport type EvaluationThresholdResult = {\n id: string;\n metric: string;\n operator: EvaluationThreshold['operator'];\n status: 'passed' | 'failed' | 'unavailable';\n expectedValue: number;\n actualValue?: number;\n baselineValue?: number;\n regression?: number;\n message: string;\n};\n\nexport type EvaluationTrial = {\n id: string;\n caseId: string;\n caseName: string;\n caseIndex: number;\n trialIndex: number;\n executionStatus: EvaluationTrialExecutionStatus;\n qualityStatus: EvaluationQualityStatus;\n qualityReason: EvaluationQualityReason;\n inputs: Record<string, PortableJson>;\n expected: Record<string, PortableJson>;\n outputs: Record<string, PortableJson>;\n observations: EvaluationObservation[];\n targetMetrics: EvaluationExecutionMetrics;\n evaluatorMetrics: EvaluationExecutionMetrics;\n totalMetrics: EvaluationExecutionMetrics;\n error?: string;\n seed?: number;\n recording?: EvaluationRecordingReference;\n /** Privacy-bounded physical provider and profile decisions from the target graph. */\n targetProviderAttempts?: PortableJson;\n};\n\nexport type EvaluationCaseAggregate = {\n caseId: string;\n caseName: string;\n /** Undefined when no trial for this case produced an authoritative quality result. */\n passRate?: number;\n /** Optional so compact baselines written before EvaluationRun v2 remain readable. */\n evaluatedTrialCount?: number;\n passedTrialCount?: number;\n failedTrialCount?: number;\n notEvaluatedTrialCount?: number;\n unableToEvaluateTrialCount?: number;\n erroredTrialCount?: number;\n canceledTrialCount?: number;\n /** Completed trials that produced a usable score in a scoring suite. */\n scoredTrialCount?: number;\n /** Requested trials that could not contribute a score. */\n missingScoreTrialCount?: number;\n /** Normalized internal score in the closed 0..1 range. */\n meanScore?: number;\n metrics: Record<string, number>;\n};\n\nexport type EvaluationAggregate = {\n trialCount: number;\n evaluatedTrialCount: number;\n notEvaluatedTrialCount: number;\n unableToEvaluateTrialCount: number;\n passedTrialCount: number;\n failedTrialCount: number;\n erroredTrialCount: number;\n canceledTrialCount: number;\n /** Completed trials that produced a usable score in a scoring suite. */\n scoredTrialCount?: number;\n /** Requested trials that could not contribute a score. */\n missingScoreTrialCount?: number;\n passRate: number;\n /** Normalized internal score in the closed 0..1 range. */\n meanScore?: number;\n averageLatencyMs: number;\n /** Optional so historical persisted runs without this newer factoid remain readable. */\n medianLatencyMs?: number;\n p95LatencyMs: number;\n /** Score distribution statistics use equal-weight per-case mean scores. */\n medianScore?: number;\n /** Score distribution statistics use equal-weight per-case mean scores. */\n p95Score?: number;\n totalCostUsd?: number;\n averageCostUsd?: number;\n targetErrorRate: number;\n evaluatorErrorRate: number;\n toolFailureRate: number;\n metrics: Record<string, number>;\n};\n\nexport type EvaluationRunProvenance = {\n projectFingerprint: string;\n suiteFingerprint: string;\n datasetFingerprint: string;\n targetFingerprint: string;\n evaluatorFingerprints: Record<string, string>;\n executionMode: string;\n accountingComplete: boolean;\n};\n\nexport type EvaluationRun = {\n version: 2;\n id: string;\n projectId: ProjectId;\n suiteId: string;\n suiteName: string;\n /** Optional user-assigned label for distinguishing retained runs. */\n name?: string;\n /**\n * Monotonically increases while a run is persisted. Stores use it to reject\n * a delayed live-progress write after a newer completed snapshot.\n * Missing means zero for recordings created before this field existed.\n */\n revision?: number;\n startedAt: string;\n completedAt?: string;\n purpose: EvaluationRunPurpose;\n /** Captures the suite semantics that produced this run. */\n evaluationMode?: EvaluationSuiteMode;\n /** Planned target executions, retained so live progress does not depend on a later suite edit. */\n requestedTrialCount?: number;\n executionStatus: 'queued' | 'running' | 'completed' | 'canceled' | 'error';\n qualityStatus: EvaluationQualityStatus;\n qualityReason: EvaluationQualityReason;\n accountingStatus: EvaluationAccountingStatus;\n provenance: EvaluationRunProvenance;\n aggregate?: EvaluationAggregate;\n /** Structured aggregate-threshold evidence for UI, reporters, and retained runs. */\n thresholdResults: EvaluationThresholdResult[];\n trials: EvaluationTrial[];\n warnings: string[];\n};\n\n/**\n * Incremental live-run protocol. A started event carries only the empty run\n * shell, a settled event carries one immutable trial, and the terminal event\n * carries the complete reporting shape once. Consumers that still need full\n * snapshots can use RunEvaluationSuiteOptions.onUpdate during the compatibility\n * period.\n */\nexport type EvaluationRunEvent =\n | {\n type: 'run-started';\n revision: number;\n run: EvaluationRun;\n }\n | {\n type: 'trial-settled';\n revision: number;\n runId: string;\n projectId: ProjectId;\n suiteId: string;\n requestedTrialCount: number;\n settledTrialCount: number;\n trial: EvaluationTrial;\n }\n | {\n type: 'run-finalized';\n revision: number;\n run: EvaluationRun;\n };\n\nexport type EvaluationRecordingReference = {\n id: string;\n retention: 'temporary' | 'failure' | 'baseline' | 'retained';\n expiresAt?: string;\n};\n\n/** A replayable execution artifact owned by an EvaluationRunStore. */\nexport type EvaluationRecordingArtifact = {\n projectId: ProjectId;\n runId: string;\n trialId: string;\n reference: EvaluationRecordingReference;\n /** ExecutionRecorder's compact serialized representation. */\n serialized: string;\n createdAt: string;\n};\n\n/**\n * Immutable, content-addressed copy of the cases used by an evaluation run.\n * It lives with the run history rather than in a compact project baseline, so\n * a later edit to a .rivet-data file cannot rewrite historical evidence.\n */\nexport type EvaluationDatasetSnapshot = {\n projectId: ProjectId;\n fingerprint: string;\n dataset: EvaluationDataset;\n createdAt: string;\n};\n\nexport type EvaluationGraphExecution = {\n outputs: Record<string, PortableJson>;\n metrics: EvaluationExecutionMetrics;\n recording?: EvaluationRecordingReference;\n providerAttempts?: PortableJson;\n};\n\n/**\n * Lets a target adapter preserve its metrics and replay reference when a\n * graph itself fails. The runner still classifies that as a target failure.\n */\nexport class EvaluationGraphExecutionError extends Error {\n readonly metrics?: EvaluationExecutionMetrics;\n readonly recording?: EvaluationRecordingReference;\n readonly providerAttempts?: PortableJson;\n\n constructor(\n message: string,\n details: Partial<Pick<EvaluationGraphExecution, 'metrics' | 'recording' | 'providerAttempts'>> = {},\n ) {\n super(message);\n this.name = 'EvaluationGraphExecutionError';\n this.metrics = details.metrics;\n this.recording = details.recording;\n this.providerAttempts = details.providerAttempts;\n }\n}\n\nexport type EvaluationGraphRunner = (input: {\n project: Project;\n graphId: GraphId;\n inputs: Record<string, PortableJson>;\n signal?: AbortSignal;\n metadata: {\n evaluationRunId: string;\n suiteId: string;\n caseId: string;\n trialIndex: number;\n phase: 'target' | 'evaluator';\n };\n}) => Promise<EvaluationGraphExecution>;\n\nexport type EvaluationRunStore = {\n put(run: EvaluationRun): Promise<void>;\n /** Sets a user-assigned run name; omit the name to restore the Unnamed label. */\n updateRunName(input: { projectId: ProjectId; runId: string; name?: string }): Promise<EvaluationRun | undefined>;\n get(input: { projectId: ProjectId; runId: string }): Promise<EvaluationRun | undefined>;\n list(input: { projectId: ProjectId; suiteId?: string }): Promise<readonly EvaluationRun[]>;\n delete(input: { projectId: ProjectId; runId: string }): Promise<void>;\n /**\n * Persists the first project-scoped snapshot for a dataset fingerprint.\n * Implementations must not rewrite an existing snapshot.\n */\n putDatasetSnapshot(snapshot: EvaluationDatasetSnapshot): Promise<void>;\n getDatasetSnapshot(input: {\n projectId: ProjectId;\n fingerprint: string;\n }): Promise<EvaluationDatasetSnapshot | undefined>;\n putRecording(artifact: EvaluationRecordingArtifact): Promise<void>;\n getRecording(input: { projectId: ProjectId; recordingId: string }): Promise<EvaluationRecordingArtifact | undefined>;\n updateRecordingRetention(input: {\n projectId: ProjectId;\n recordingId: string;\n retention: EvaluationRecordingReference['retention'];\n expiresAt?: string;\n }): Promise<boolean>;\n /** Pins all artifacts belonging to the run before its compact baseline is saved in the project. */\n promoteBaseline(input: { projectId: ProjectId; runId: string }): Promise<void>;\n /**\n * Optional V2 capability. Persists an idempotent incremental lifecycle event\n * so a host can recover settled work after a process interruption.\n */\n applyRunEvent?(event: EvaluationRunEvent): Promise<void>;\n};\n\nexport type EvaluationStoreInitialization = {\n /** A recoverable persistence warning that a host may surface to the user. */\n warning?: string;\n};\n\n/**\n * Complete persistence boundary for Evaluations. Desktop, browser, and hosted\n * Rivet instances implement this same contract so definitions and operational\n * evidence cannot silently land in different stores.\n */\nexport type EvaluationStore = EvaluationRunStore & {\n initialize?(): Promise<EvaluationStoreInitialization | void>;\n getLibrary(): Promise<EvaluationLibrary>;\n putLibrary(library: EvaluationLibrary): Promise<void>;\n};\n\nexport type EvaluationReporter = {\n report(run: EvaluationRun): Promise<void> | void;\n};\n", "import type { EvaluationDatasetSnapshot, EvaluationRecordingArtifact, PortableJson } from './types.js';\n\nexport function assertPortableJson(\n value: unknown,\n path = '$',\n stack = new Set<object>(),\n): asserts value is PortableJson {\n if (value === null || typeof value === 'string' || typeof value === 'boolean') return;\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) throw new Error(`${path} must not contain a non-finite number.`);\n return;\n }\n if (typeof value !== 'object') throw new Error(`${path} must be portable JSON.`);\n if (stack.has(value)) throw new Error(`${path} must not contain a cycle.`);\n if (Array.isArray(value)) {\n if (Object.getOwnPropertySymbols(value).length > 0) {\n throw new Error(`${path} must not contain symbol-keyed array properties.`);\n }\n stack.add(value);\n try {\n for (let index = 0; index < value.length; index += 1) {\n const descriptor = Object.getOwnPropertyDescriptor(value, index);\n if (!descriptor) throw new Error(`${path}[${index}] must not be a sparse array entry.`);\n if (!descriptor.enumerable || descriptor.get || descriptor.set) {\n throw new Error(`${path}[${index}] must be an enumerable data property.`);\n }\n assertPortableJson(descriptor.value, `${path}[${index}]`, stack);\n }\n if (Object.getOwnPropertyNames(value).length !== value.length + 1) {\n throw new Error(`${path} must not contain hidden or extra array properties.`);\n }\n } finally {\n stack.delete(value);\n }\n return;\n }\n if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) {\n throw new Error(`${path} must be a plain object.`);\n }\n if (Object.getOwnPropertySymbols(value).length > 0) {\n throw new Error(`${path} must not contain symbol-keyed object properties.`);\n }\n const ownPropertyNames = Object.getOwnPropertyNames(value);\n const keys = Object.keys(value);\n if (ownPropertyNames.length !== keys.length) {\n throw new Error(`${path} must not contain non-enumerable object properties.`);\n }\n stack.add(value);\n try {\n for (const key of keys) {\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (!descriptor || descriptor.get || descriptor.set) {\n throw new Error(`${path}.${key} must be an enumerable data property.`);\n }\n assertPortableJson(descriptor.value, `${path}.${key}`, stack);\n }\n } finally {\n stack.delete(value);\n }\n}\n\nexport function canonicalizePortableJson(value: unknown): PortableJson {\n assertPortableJson(value);\n if (value === null || typeof value !== 'object') return value;\n if (Array.isArray(value)) return value.map(canonicalizePortableJson);\n return Object.fromEntries(\n Object.keys(value)\n .sort()\n .map((key) => [key, canonicalizePortableJson(value[key])]),\n );\n}\n\n/**\n * Evaluation inputs and observations cross concurrent graph-run boundaries.\n * Clone them before handing them to an adapter so a Code or evaluator graph\n * cannot mutate a dataset case, another trial, or the persisted run model.\n */\nexport function clonePortableJson<T extends PortableJson>(value: T): T {\n assertPortableJson(value);\n return structuredClone(value);\n}\n\nexport function canonicalStringify(value: unknown): string {\n return JSON.stringify(canonicalizePortableJson(value));\n}\n\n/** Stable, synchronously available content fingerprint for project-local identities. */\nexport function fingerprint(value: unknown): string {\n const source = canonicalStringify(value);\n let hash = 0xcbf29ce484222325n;\n for (let index = 0; index < source.length; index += 1) {\n hash ^= BigInt(source.charCodeAt(index));\n hash = BigInt.asUintN(64, hash * 0x100000001b3n);\n }\n return `fnv1a64:${hash.toString(16).padStart(16, '0')}`;\n}\n\nexport function fingerprintEvaluationDataset(value: { id: unknown; fields: unknown; cases: unknown }): string {\n return fingerprint({ datasetId: value.id, fields: value.fields, cases: value.cases });\n}\n\n/**\n * A dataset fingerprint is the link between a compact run summary and its\n * historical input cases. Stores must reject a mismatched key rather than\n * accepting a snapshot that can no longer prove which cases were run.\n */\nexport function assertEvaluationDatasetSnapshot(snapshot: EvaluationDatasetSnapshot): void {\n if (\n typeof snapshot.projectId !== 'string' ||\n snapshot.projectId.length === 0 ||\n typeof snapshot.fingerprint !== 'string' ||\n snapshot.fingerprint.length === 0 ||\n typeof snapshot.createdAt !== 'string' ||\n !Number.isFinite(Date.parse(snapshot.createdAt))\n ) {\n throw new Error('An evaluation dataset snapshot has invalid identity or creation time.');\n }\n if (snapshot.dataset.projectId !== snapshot.projectId) {\n throw new Error('An evaluation dataset snapshot must belong to its project.');\n }\n if (fingerprintEvaluationDataset(snapshot.dataset) !== snapshot.fingerprint) {\n throw new Error('An evaluation dataset snapshot fingerprint must match its dataset ID, fields, and cases.');\n }\n}\n\n/** Rejects malformed replay evidence at both write and durable-read boundaries. */\nexport function assertEvaluationRecordingArtifact(value: unknown): asserts value is EvaluationRecordingArtifact {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new Error('An evaluation recording artifact must be an object.');\n }\n const artifact = value as Partial<EvaluationRecordingArtifact>;\n if (\n typeof artifact.projectId !== 'string' ||\n artifact.projectId.length === 0 ||\n typeof artifact.runId !== 'string' ||\n artifact.runId.length === 0 ||\n typeof artifact.trialId !== 'string' ||\n artifact.trialId.length === 0 ||\n typeof artifact.serialized !== 'string' ||\n typeof artifact.createdAt !== 'string' ||\n !Number.isFinite(Date.parse(artifact.createdAt))\n ) {\n throw new Error('An evaluation recording artifact has invalid identity, payload, or creation time.');\n }\n const reference = artifact.reference;\n if (\n typeof reference !== 'object' ||\n reference === null ||\n typeof reference.id !== 'string' ||\n reference.id.length === 0 ||\n !['temporary', 'failure', 'baseline', 'retained'].includes(reference.retention ?? '') ||\n (reference.expiresAt !== undefined &&\n (typeof reference.expiresAt !== 'string' || !Number.isFinite(Date.parse(reference.expiresAt))))\n ) {\n throw new Error('An evaluation recording artifact has an invalid retention reference.');\n }\n}\n", "import { assertPortableJson, canonicalStringify } from './canonical.js';\nimport type { EvaluationAssertion, EvaluationDatasetCase, EvaluationObservation, PortableJson } from './types.js';\n\nfunction readQuotedPathKey(source: string, start: number): { key: string; cursor: number } | undefined {\n const quote = source[start];\n if (quote !== '\"' && quote !== \"'\") return undefined;\n let cursor = start + 1;\n let key = '';\n while (cursor < source.length) {\n const character = source[cursor++]!;\n if (character === quote) return { key, cursor };\n if (character !== '\\\\') {\n key += character;\n continue;\n }\n const escaped = source[cursor++];\n if (escaped === undefined) return undefined;\n if (escaped === 'u') {\n const hex = source.slice(cursor, cursor + 4);\n if (!/^[0-9a-fA-F]{4}$/.test(hex)) return undefined;\n key += String.fromCharCode(Number.parseInt(hex, 16));\n cursor += 4;\n continue;\n }\n const escapes: Record<string, string> = {\n '\"': '\"',\n \"'\": \"'\",\n '\\\\': '\\\\',\n '/': '/',\n b: '\\b',\n f: '\\f',\n n: '\\n',\n r: '\\r',\n t: '\\t',\n };\n if (!(escaped in escapes)) return undefined;\n key += escapes[escaped]!;\n }\n return undefined;\n}\n\ntype EvaluationOutputPathSegment = { kind: 'property'; key: string } | { kind: 'index'; index: number };\n\nfunction parseEvaluationOutputPath(path: string): EvaluationOutputPathSegment[] | undefined {\n const source = path.trim();\n if (source === '$') return [];\n if (!source.startsWith('$') || source.length === 1) return undefined;\n let cursor = 1;\n const segments: EvaluationOutputPathSegment[] = [];\n // Validate every character. A partially parsed selector could otherwise\n // assert against a different output than the author wrote (for example\n // `$.answer!`). Dot notation intentionally remains identifier-only; quoted\n // bracket notation covers output names containing spaces, dots, or dashes.\n while (cursor < source.length) {\n if (source[cursor] === '.') {\n cursor += 1;\n while (/\\s/u.test(source[cursor] ?? '')) cursor += 1;\n const identifier = /^[A-Za-z_$][\\w$]*/u.exec(source.slice(cursor));\n if (!identifier) return undefined;\n segments.push({ kind: 'property', key: identifier[0] });\n cursor += identifier[0].length;\n } else if (source[cursor] === '[') {\n cursor += 1;\n while (/\\s/u.test(source[cursor] ?? '')) cursor += 1;\n const quoted = readQuotedPathKey(source, cursor);\n if (quoted) {\n segments.push({ kind: 'property', key: quoted.key });\n cursor = quoted.cursor;\n } else {\n const index = /^\\d+/u.exec(source.slice(cursor));\n if (!index) return undefined;\n segments.push({ kind: 'index', index: Number(index[0]) });\n cursor += index[0].length;\n }\n while (/\\s/u.test(source[cursor] ?? '')) cursor += 1;\n if (source[cursor] !== ']') return undefined;\n cursor += 1;\n } else {\n return undefined;\n }\n }\n return segments;\n}\n\n/**\n * Validates the exact JSON-path subset supported by evaluation assertions.\n * UI authoring and runtime execution intentionally share this parser so a\n * path cannot pass preflight and then resolve with different grammar.\n */\nexport function isEvaluationOutputPathSyntaxValid(path: string): boolean {\n return parseEvaluationOutputPath(path) !== undefined;\n}\n\n/** The Graph Output that owns an assertion path, including nested paths. */\nexport function getEvaluationTopLevelOutputId(path: string): string | undefined {\n const first = parseEvaluationOutputPath(path)?.[0];\n return first?.kind === 'property' ? first.key : undefined;\n}\n\nfunction getPath(value: PortableJson, path: string): PortableJson | undefined {\n const segments = parseEvaluationOutputPath(path);\n if (!segments) return undefined;\n let current: PortableJson | undefined = value;\n for (const segment of segments) {\n if (Array.isArray(current)) {\n if (segment.kind !== 'index') return undefined;\n const index = segment.index;\n if (!Number.isInteger(index) || index < 0 || index >= current.length) return undefined;\n current = current[index];\n continue;\n }\n if (segment.kind !== 'property') return undefined;\n if (current === null || typeof current !== 'object' || !Object.hasOwn(current, segment.key)) return undefined;\n current = current[segment.key];\n }\n return current;\n}\n\nfunction expectedValue(assertion: EvaluationAssertion, testCase: EvaluationDatasetCase): PortableJson {\n if (assertion.expected.kind === 'literal') return assertion.expected.value;\n const value = testCase.values[assertion.expected.fieldId];\n if (value === undefined) throw new Error(`Expected dataset field \"${assertion.expected.fieldId}\" is missing.`);\n return value;\n}\n\nfunction typeMatches(actual: PortableJson | undefined, expected: PortableJson): boolean {\n if (typeof expected !== 'string') return false;\n if (actual === undefined) return false;\n if (expected === 'array') return Array.isArray(actual);\n if (expected === 'null') return actual === null;\n if (expected === 'object') return actual !== null && typeof actual === 'object' && !Array.isArray(actual);\n return typeof actual === expected;\n}\n\nfunction expectedTextList(assertion: EvaluationAssertion, expected: PortableJson): string[] {\n if (!Array.isArray(expected) || expected.length === 0 || expected.some((value) => typeof value !== 'string')) {\n throw new Error(`Quality check \"${assertion.name}\" requires a non-empty array of expected text values.`);\n }\n return expected as string[];\n}\n\nfunction assertionConfigurationError(assertion: EvaluationAssertion, message: string): never {\n throw new Error(`Quality check \"${assertion.name}\" ${message}`);\n}\n\nconst ASSERTION_TYPE_NAMES = new Set(['array', 'boolean', 'null', 'number', 'object', 'string']);\n\nfunction expectedTypeName(assertion: EvaluationAssertion, expected: PortableJson): string {\n if (typeof expected !== 'string' || !ASSERTION_TYPE_NAMES.has(expected)) {\n assertionConfigurationError(\n assertion,\n 'requires one of these expected type names: array, boolean, null, number, object, or string.',\n );\n }\n return expected;\n}\n\nfunction expectedString(assertion: EvaluationAssertion, expected: PortableJson, description: string): string {\n if (typeof expected !== 'string') {\n assertionConfigurationError(assertion, `requires ${description} to be a string.`);\n }\n return expected;\n}\n\nfunction expectedFiniteNumber(assertion: EvaluationAssertion, expected: PortableJson, description: string): number {\n if (typeof expected !== 'number' || !Number.isFinite(expected)) {\n assertionConfigurationError(assertion, `requires ${description} to be a finite number.`);\n }\n return expected;\n}\n\nfunction expectedNumberRange(assertion: EvaluationAssertion, expected: PortableJson): [number, number] {\n if (\n !Array.isArray(expected) ||\n expected.length !== 2 ||\n typeof expected[0] !== 'number' ||\n !Number.isFinite(expected[0]) ||\n typeof expected[1] !== 'number' ||\n !Number.isFinite(expected[1])\n ) {\n assertionConfigurationError(assertion, 'requires an expected range containing exactly two finite numbers.');\n }\n if (expected[0] > expected[1]) {\n assertionConfigurationError(assertion, 'requires its expected range minimum to be no greater than its maximum.');\n }\n return expected as [number, number];\n}\n\nfunction expectedSet(assertion: EvaluationAssertion, expected: PortableJson): PortableJson[] {\n if (!Array.isArray(expected)) assertionConfigurationError(assertion, 'requires the expected set to be an array.');\n return expected;\n}\n\nfunction operatorDescription(operator: EvaluationAssertion['operator']): string {\n switch (operator) {\n case 'equals':\n return 'equals';\n case 'not-equals':\n return 'does not equal';\n case 'contains':\n return 'contains the expected text';\n case 'matches-regex':\n return 'matches the regular expression';\n case 'type-is':\n return 'has the expected type';\n case 'json-schema':\n return 'matches the JSON Schema';\n case 'number-at-least':\n return 'is at least the expected value';\n case 'number-at-most':\n return 'is at most the expected value';\n case 'number-between':\n return 'is inside the expected range';\n case 'array-includes':\n return 'includes the expected value';\n case 'set-overlaps':\n return 'overlaps the expected set';\n case 'contains-any':\n return 'contains any expected text';\n case 'contains-all':\n return 'contains every expected text';\n }\n}\n\n/**\n * Validates author-controlled expected data without needing target outputs.\n * The runner uses this before scheduling work; assertion execution uses the\n * same function so direct callers cannot observe a looser contract.\n */\nexport function validateEvaluationAssertionExpectedValue(\n assertion: EvaluationAssertion,\n expected: PortableJson,\n): void {\n assertPortableJson(expected, `quality check ${assertion.name} expected value`);\n switch (assertion.operator) {\n case 'equals':\n case 'not-equals':\n case 'array-includes':\n return;\n case 'contains':\n expectedString(assertion, expected, 'its expected text');\n return;\n case 'matches-regex': {\n const pattern = expectedString(assertion, expected, 'its expected regular expression');\n try {\n new RegExp(pattern);\n } catch {\n assertionConfigurationError(assertion, 'contains an invalid expected regular expression.');\n }\n return;\n }\n case 'type-is':\n expectedTypeName(assertion, expected);\n return;\n case 'json-schema':\n assertSupportedJsonSchema(assertion, expected);\n return;\n case 'number-at-least':\n expectedFiniteNumber(assertion, expected, 'its expected minimum');\n return;\n case 'number-at-most':\n expectedFiniteNumber(assertion, expected, 'its expected maximum');\n return;\n case 'number-between':\n expectedNumberRange(assertion, expected);\n return;\n case 'set-overlaps':\n expectedSet(assertion, expected);\n return;\n case 'contains-any':\n case 'contains-all':\n expectedTextList(assertion, expected);\n return;\n }\n}\n\nexport function validateEvaluationAssertionConfiguration(\n assertion: EvaluationAssertion,\n expected: PortableJson,\n): void {\n if (!isEvaluationOutputPathSyntaxValid(assertion.outputPath)) {\n assertionConfigurationError(assertion, `uses invalid output path \"${assertion.outputPath}\".`);\n }\n validateEvaluationAssertionExpectedValue(assertion, expected);\n}\n\nconst SUPPORTED_SCHEMA_KEYWORDS = new Set([\n 'type',\n 'enum',\n 'const',\n 'minLength',\n 'maxLength',\n 'pattern',\n 'minimum',\n 'maximum',\n 'minItems',\n 'maxItems',\n 'items',\n 'required',\n 'properties',\n 'additionalProperties',\n]);\nconst SUPPORTED_SCHEMA_TYPES = new Set(['array', 'boolean', 'integer', 'null', 'number', 'object', 'string']);\n\nfunction schemaRecord(\n assertion: EvaluationAssertion,\n schema: PortableJson,\n path: string,\n): Record<string, PortableJson> {\n if (schema === null || typeof schema !== 'object' || Array.isArray(schema)) {\n assertionConfigurationError(assertion, `requires the JSON Schema at ${path} to be an object.`);\n }\n return schema as Record<string, PortableJson>;\n}\n\nfunction assertNonNegativeInteger(\n assertion: EvaluationAssertion,\n value: PortableJson,\n path: string,\n): asserts value is number {\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {\n assertionConfigurationError(assertion, `requires ${path} to be a non-negative safe integer.`);\n }\n}\n\n/**\n * Validates the exact JSON Schema subset implemented below. Rejecting unknown\n * constraints is essential: silently ignoring one can turn a schema that\n * appears strict into a false quality pass.\n */\nfunction assertSupportedJsonSchema(\n assertion: EvaluationAssertion,\n schema: PortableJson,\n path = '$',\n): asserts schema is Record<string, PortableJson> {\n const objectSchema = schemaRecord(assertion, schema, path);\n for (const keyword of Object.keys(objectSchema)) {\n if (!SUPPORTED_SCHEMA_KEYWORDS.has(keyword)) {\n assertionConfigurationError(assertion, `uses unsupported JSON Schema keyword \"${keyword}\" at ${path}.`);\n }\n }\n\n if (objectSchema.type !== undefined) {\n if (typeof objectSchema.type !== 'string' || !SUPPORTED_SCHEMA_TYPES.has(objectSchema.type)) {\n assertionConfigurationError(\n assertion,\n `requires ${path}.type to be one of: array, boolean, integer, null, number, object, or string.`,\n );\n }\n }\n if (objectSchema.enum !== undefined && (!Array.isArray(objectSchema.enum) || objectSchema.enum.length === 0)) {\n assertionConfigurationError(assertion, `requires ${path}.enum to be a non-empty array.`);\n }\n\n for (const keyword of ['minLength', 'maxLength', 'minItems', 'maxItems'] as const) {\n if (objectSchema[keyword] !== undefined)\n assertNonNegativeInteger(assertion, objectSchema[keyword], `${path}.${keyword}`);\n }\n if (\n typeof objectSchema.minLength === 'number' &&\n typeof objectSchema.maxLength === 'number' &&\n objectSchema.minLength > objectSchema.maxLength\n ) {\n assertionConfigurationError(assertion, `requires ${path}.minLength to be no greater than ${path}.maxLength.`);\n }\n if (\n typeof objectSchema.minItems === 'number' &&\n typeof objectSchema.maxItems === 'number' &&\n objectSchema.minItems > objectSchema.maxItems\n ) {\n assertionConfigurationError(assertion, `requires ${path}.minItems to be no greater than ${path}.maxItems.`);\n }\n\n for (const keyword of ['minimum', 'maximum'] as const) {\n const value = objectSchema[keyword];\n if (value !== undefined && (typeof value !== 'number' || !Number.isFinite(value))) {\n assertionConfigurationError(assertion, `requires ${path}.${keyword} to be a finite number.`);\n }\n }\n if (\n typeof objectSchema.minimum === 'number' &&\n typeof objectSchema.maximum === 'number' &&\n objectSchema.minimum > objectSchema.maximum\n ) {\n assertionConfigurationError(assertion, `requires ${path}.minimum to be no greater than ${path}.maximum.`);\n }\n\n if (objectSchema.pattern !== undefined) {\n if (typeof objectSchema.pattern !== 'string') {\n assertionConfigurationError(assertion, `requires ${path}.pattern to be a string.`);\n }\n try {\n new RegExp(objectSchema.pattern);\n } catch {\n assertionConfigurationError(assertion, `contains an invalid regular expression at ${path}.pattern.`);\n }\n }\n if (objectSchema.required !== undefined) {\n if (\n !Array.isArray(objectSchema.required) ||\n objectSchema.required.some((key) => typeof key !== 'string' || key.length === 0) ||\n new Set(objectSchema.required).size !== objectSchema.required.length\n ) {\n assertionConfigurationError(assertion, `requires ${path}.required to contain unique, non-empty strings.`);\n }\n }\n if (objectSchema.additionalProperties !== undefined && typeof objectSchema.additionalProperties !== 'boolean') {\n assertionConfigurationError(assertion, `supports only a boolean ${path}.additionalProperties value.`);\n }\n if (objectSchema.items !== undefined) {\n assertSupportedJsonSchema(assertion, objectSchema.items, `${path}.items`);\n }\n if (objectSchema.properties !== undefined) {\n const properties = schemaRecord(assertion, objectSchema.properties, `${path}.properties`);\n for (const [key, childSchema] of Object.entries(properties)) {\n assertSupportedJsonSchema(assertion, childSchema, `${path}.properties[${JSON.stringify(key)}]`);\n }\n }\n}\n\nfunction schemaTypeMatches(actual: PortableJson, expected: string): boolean {\n if (expected === 'integer') return typeof actual === 'number' && Number.isInteger(actual);\n return typeMatches(actual, expected);\n}\n\n/** Evaluate the validated, deliberately portable JSON Schema subset. */\nfunction matchesSchema(actual: PortableJson | undefined, schema: PortableJson): boolean {\n if (actual === undefined) return false;\n const objectSchema = schema as Record<string, PortableJson>;\n const declaredType = objectSchema.type;\n if (typeof declaredType === 'string' && !schemaTypeMatches(actual, declaredType)) return false;\n if (\n Array.isArray(objectSchema.enum) &&\n !objectSchema.enum.some((candidate) => canonicalStringify(candidate) === canonicalStringify(actual ?? null))\n )\n return false;\n if (\n Object.hasOwn(objectSchema, 'const') &&\n canonicalStringify(objectSchema.const) !== canonicalStringify(actual ?? null)\n )\n return false;\n\n if (typeof actual === 'string') {\n if (typeof objectSchema.minLength === 'number' && actual.length < objectSchema.minLength) return false;\n if (typeof objectSchema.maxLength === 'number' && actual.length > objectSchema.maxLength) return false;\n if (typeof objectSchema.pattern === 'string') {\n if (!new RegExp(objectSchema.pattern).test(actual)) return false;\n }\n }\n if (typeof actual === 'number') {\n if (typeof objectSchema.minimum === 'number' && actual < objectSchema.minimum) return false;\n if (typeof objectSchema.maximum === 'number' && actual > objectSchema.maximum) return false;\n }\n if (Array.isArray(actual)) {\n if (typeof objectSchema.minItems === 'number' && actual.length < objectSchema.minItems) return false;\n if (typeof objectSchema.maxItems === 'number' && actual.length > objectSchema.maxItems) return false;\n if (objectSchema.items !== undefined && !actual.every((item) => matchesSchema(item, objectSchema.items!)))\n return false;\n }\n if (actual !== null && typeof actual === 'object' && !Array.isArray(actual)) {\n const record = actual as Record<string, PortableJson>;\n if (\n Array.isArray(objectSchema.required) &&\n !objectSchema.required.every((key) => typeof key === 'string' && Object.hasOwn(record, key))\n )\n return false;\n const properties = objectSchema.properties;\n if (properties !== undefined) {\n const propertySchemas = properties as Record<string, PortableJson>;\n for (const [key, childSchema] of Object.entries(propertySchemas)) {\n if (Object.hasOwn(record, key) && !matchesSchema(record[key], childSchema)) return false;\n }\n }\n if (objectSchema.additionalProperties === false) {\n const propertySchemas = (properties ?? {}) as Record<string, PortableJson>;\n if (Object.keys(record).some((key) => !Object.hasOwn(propertySchemas, key))) return false;\n }\n }\n return true;\n}\n\nexport function evaluateAssertion(\n assertion: EvaluationAssertion,\n outputs: Record<string, PortableJson>,\n testCase: EvaluationDatasetCase,\n): EvaluationObservation {\n const outputRoot: PortableJson = outputs;\n const actual = getPath(outputRoot, assertion.outputPath);\n const actualFound = actual !== undefined;\n const expected = expectedValue(assertion, testCase);\n validateEvaluationAssertionConfiguration(assertion, expected);\n let passed = false;\n switch (assertion.operator) {\n case 'equals':\n passed = actual !== undefined && canonicalStringify(actual) === canonicalStringify(expected);\n break;\n case 'not-equals':\n // A configured path must resolve before any comparison can pass. Treating\n // a missing value as \"not equal\" would let a typo in an output path turn\n // into a false quality pass.\n passed = actual !== undefined && canonicalStringify(actual) !== canonicalStringify(expected);\n break;\n case 'contains':\n {\n const expectedText = expected as string;\n passed = typeof actual === 'string' && actual.includes(expectedText);\n }\n break;\n case 'matches-regex':\n // Invalid author-supplied expressions are evaluator configuration\n // errors. Let the runner report that quality could not be evaluated instead\n // of reporting a normal failed quality assertion.\n {\n const pattern = new RegExp(expected as string);\n passed = typeof actual === 'string' && pattern.test(actual);\n }\n break;\n case 'type-is':\n passed = typeMatches(actual, expected);\n break;\n case 'json-schema':\n passed = matchesSchema(actual, expected);\n break;\n case 'number-at-least':\n {\n const minimum = expected as number;\n passed = typeof actual === 'number' && actual >= minimum;\n }\n break;\n case 'number-at-most':\n {\n const maximum = expected as number;\n passed = typeof actual === 'number' && actual <= maximum;\n }\n break;\n case 'number-between':\n {\n const [minimum, maximum] = expected as [number, number];\n passed = typeof actual === 'number' && actual >= minimum && actual <= maximum;\n }\n break;\n case 'array-includes':\n passed =\n Array.isArray(actual) && actual.some((item) => canonicalStringify(item) === canonicalStringify(expected));\n break;\n case 'set-overlaps':\n {\n const candidates = expected as PortableJson[];\n passed =\n Array.isArray(actual) &&\n candidates.some((candidate) =>\n actual.some((item) => canonicalStringify(item) === canonicalStringify(candidate)),\n );\n }\n break;\n case 'contains-any':\n {\n const expectedTexts = expected as string[];\n passed = typeof actual === 'string' && expectedTexts.some((candidate) => actual.includes(candidate));\n }\n break;\n case 'contains-all':\n {\n const expectedTexts = expected as string[];\n passed = typeof actual === 'string' && expectedTexts.every((candidate) => actual.includes(candidate));\n }\n break;\n }\n const requirement = operatorDescription(assertion.operator);\n return {\n id: assertion.id,\n kind: 'assertion',\n name: assertion.name,\n required: assertion.required !== false,\n status: passed ? 'passed' : 'failed',\n message: passed\n ? `Target output ${requirement}.`\n : actualFound\n ? `Target output does not satisfy the requirement: ${requirement}.`\n : `Target output path \"${assertion.outputPath}\" does not exist.`,\n evidence: {\n actual: actual ?? null,\n actualFound,\n expected,\n outputPath: assertion.outputPath,\n operator: assertion.operator,\n expectedSource: assertion.expected.kind,\n ...(assertion.expected.kind === 'dataset-field' ? { expectedFieldId: assertion.expected.fieldId } : {}),\n },\n };\n}\n", "import type {\n EvaluationAccountingStatus,\n EvaluationAggregate,\n EvaluationBaselineSnapshot,\n EvaluationQualityReason,\n EvaluationQualityStatus,\n EvaluationRun,\n EvaluationRunPurpose,\n EvaluationSuiteMode,\n EvaluationTrial,\n EvaluationTrialExecutionStatus,\n} from './types.js';\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction isQualityStatus(value: unknown): value is EvaluationQualityStatus {\n return ['passed', 'failed', 'scored', 'not-evaluated', 'unable-to-evaluate'].includes(String(value));\n}\n\nfunction isEvaluationMode(value: unknown): value is EvaluationSuiteMode {\n return value === 'pass-fail' || value === 'scoring';\n}\n\nfunction isQualityStatusForMode(status: EvaluationQualityStatus, evaluationMode: EvaluationSuiteMode): boolean {\n return evaluationMode === 'scoring' ? status !== 'passed' && status !== 'failed' : status !== 'scored';\n}\n\nfunction isExecutionStatus(value: unknown): value is EvaluationTrialExecutionStatus {\n return ['completed', 'error', 'canceled'].includes(String(value));\n}\n\nfunction isRunExecutionStatus(value: unknown): value is EvaluationRun['executionStatus'] {\n return ['queued', 'running', 'completed', 'canceled', 'error'].includes(String(value));\n}\n\nfunction isTerminalRunExecutionStatus(status: EvaluationRun['executionStatus']): boolean {\n return status === 'completed' || status === 'canceled' || status === 'error';\n}\n\nfunction reconcileRecordingReference(\n primary: EvaluationTrial['recording'],\n secondary: EvaluationTrial['recording'],\n): EvaluationTrial['recording'] {\n if (!primary) return secondary;\n if (!secondary) return primary;\n const rank = (retention: NonNullable<EvaluationTrial['recording']>['retention']): number =>\n retention === 'temporary' ? 0 : retention === 'failure' ? 1 : 2;\n return rank(secondary.retention) > rank(primary.retention) ? secondary : primary;\n}\n\n/**\n * Orders snapshots for one run without allowing an equal-revision progress\n * update to demote a terminal result. Writers and delayed UI reads share this\n * rule so persistence cannot disagree with what the workspace presents.\n */\nexport function shouldReplaceEvaluationRun(\n existing: Pick<EvaluationRun, 'executionStatus' | 'revision'> | undefined,\n incoming: Pick<EvaluationRun, 'executionStatus' | 'revision'>,\n): boolean {\n if (!existing) return true;\n const existingRevision = existing.revision ?? 0;\n const incomingRevision = incoming.revision ?? 0;\n if (incomingRevision !== existingRevision) return incomingRevision > existingRevision;\n return (\n !isTerminalRunExecutionStatus(existing.executionStatus) || isTerminalRunExecutionStatus(incoming.executionStatus)\n );\n}\n\n/**\n * Execution snapshots never own a user-assigned run name. Preserve it when a\n * runner publishes a newer progress or terminal revision after a rename.\n */\nexport function preserveEvaluationRunName(\n existing: Pick<EvaluationRun, 'name'> | undefined,\n incoming: EvaluationRun,\n): EvaluationRun {\n return existing?.name !== undefined && incoming.name === undefined ? { ...incoming, name: existing.name } : incoming;\n}\n\n/**\n * Reconciles two snapshots of the same run without discarding evidence.\n *\n * Revisions remain authoritative. Within one revision, however, persistence\n * and recording-retention updates can race with a terminal UI snapshot. Keep\n * the snapshot with the fuller trial set, while still allowing a terminal\n * snapshot to complete a progress snapshot and allowing recording references\n * and warnings to enrich already-settled evidence.\n */\nexport function reconcileEvaluationRunSnapshots(\n existing: EvaluationRun | undefined,\n incoming: EvaluationRun,\n): EvaluationRun {\n if (!existing) return incoming;\n\n const existingRevision = existing.revision ?? 0;\n const incomingRevision = incoming.revision ?? 0;\n if (incomingRevision < existingRevision) return existing;\n if (incomingRevision > existingRevision) return preserveEvaluationRunName(existing, incoming);\n if (!shouldReplaceEvaluationRun(existing, incoming)) return existing;\n\n const existingTerminal = isTerminalRunExecutionStatus(existing.executionStatus);\n const incomingTerminal = isTerminalRunExecutionStatus(incoming.executionStatus);\n const existingTrials = existing.trials ?? [];\n const incomingTrials = incoming.trials ?? [];\n const incomingIsPrimary =\n incomingTerminal !== existingTerminal ? incomingTerminal : incomingTrials.length >= existingTrials.length;\n const primary = preserveEvaluationRunName(existing, incomingIsPrimary ? incoming : existing);\n const secondary = incomingIsPrimary ? existing : incoming;\n const primaryTrials = primary.trials ?? [];\n const secondaryTrialList = secondary.trials ?? [];\n const name = existing.name ?? incoming.name;\n const primaryTrialIds = new Set(primaryTrials.map((trial) => trial.id));\n const secondaryTrials = new Map(secondaryTrialList.map((trial) => [trial.id, trial] as const));\n\n return {\n ...primary,\n trials: [\n ...primaryTrials.map((trial) => {\n const other = secondaryTrials.get(trial.id);\n if (!other) return trial;\n const secondaryObservations = new Map(\n (other.observations ?? []).map((observation) => [observation.id, observation] as const),\n );\n const primaryObservationIds = new Set((trial.observations ?? []).map((observation) => observation.id));\n const recording = reconcileRecordingReference(trial.recording, other.recording);\n return {\n ...trial,\n ...(recording === undefined ? {} : { recording }),\n observations: [\n ...(trial.observations ?? []).map((observation) => {\n const otherObservation = secondaryObservations.get(observation.id);\n const observationRecording = reconcileRecordingReference(\n observation.recording,\n otherObservation?.recording,\n );\n return observationRecording === observation.recording\n ? observation\n : {\n ...observation,\n ...(observationRecording === undefined ? {} : { recording: observationRecording }),\n };\n }),\n ...(other.observations ?? []).filter((observation) => !primaryObservationIds.has(observation.id)),\n ],\n };\n }),\n ...secondaryTrialList.filter((trial) => !primaryTrialIds.has(trial.id)),\n ],\n ...(name === undefined ? {} : { name }),\n warnings: [...new Set([...(primary.warnings ?? []), ...(secondary.warnings ?? [])])],\n };\n}\n\nfunction isPurpose(value: unknown): value is EvaluationRunPurpose {\n return value === 'evaluation' || value === 'execution-benchmark';\n}\n\nfunction isAccountingStatus(value: unknown): value is EvaluationAccountingStatus {\n return value === 'complete' || value === 'partial';\n}\n\n/** Run records keep scores normalized even though evaluator graphs use 0..100. */\nfunction isNormalizedScore(value: unknown): value is number {\n return typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 1;\n}\n\nfunction reasonForQualityStatus(\n status: EvaluationQualityStatus,\n executionStatus?: EvaluationTrialExecutionStatus,\n): EvaluationQualityReason {\n if (executionStatus === 'canceled') return { code: 'canceled', message: 'The execution was canceled.' };\n if (executionStatus === 'error' && status === 'failed') {\n return { code: 'target-error', message: 'The target graph failed before it could produce a valid result.' };\n }\n switch (status) {\n case 'passed':\n return { code: 'checks-passed', message: 'All required quality criteria passed.' };\n case 'failed':\n return { code: 'checks-failed', message: 'One or more required quality criteria failed.' };\n case 'scored':\n return { code: 'scores-complete', message: 'Every requested trial produced a score.' };\n case 'not-evaluated':\n return { code: 'no-trial-quality-checks', message: 'No per-trial quality check evaluated this result.' };\n case 'unable-to-evaluate':\n return { code: 'required-check-error', message: 'A required quality criterion could not be evaluated.' };\n }\n}\n\nfunction reasonForQualityStatusInMode(\n status: EvaluationQualityStatus,\n evaluationMode: EvaluationSuiteMode,\n executionStatus?: EvaluationTrialExecutionStatus,\n): EvaluationQualityReason {\n if (evaluationMode === 'scoring' && status === 'unable-to-evaluate') {\n return { code: 'scores-incomplete', message: 'One or more requested trials did not produce a usable score.' };\n }\n return reasonForQualityStatus(status, executionStatus);\n}\n\nfunction isTargetExecutionError(value: Record<string, unknown>, observations: readonly unknown[]): boolean {\n if (typeof value.error === 'string' && value.error.length > 0) return true;\n return observations.some(\n (observation) =>\n isRecord(observation) &&\n observation.id === 'target-error' &&\n observation.kind === 'assertion' &&\n observation.status === 'error',\n );\n}\n\nfunction legacyQualityFromObservations(\n observations: readonly unknown[],\n targetExecutionError: boolean,\n): EvaluationQualityStatus {\n if (targetExecutionError) return 'failed';\n const required = observations.filter(\n (observation) => isRecord(observation) && observation.required !== false,\n ) as Array<Record<string, unknown>>;\n if (required.some((observation) => observation.status === 'failed')) return 'failed';\n if (required.some((observation) => observation.status === 'error')) return 'unable-to-evaluate';\n if (required.some((observation) => observation.status === 'passed')) return 'passed';\n return 'not-evaluated';\n}\n\n/**\n * Scoring runs are new enough that they do not need to preserve a legacy\n * pass/fail quality label. Do still recover a useful status when a partial or\n * hand-edited scoring record lacks its derived status, but never let an old\n * `passed`/`failed` value leak into the scoring UI.\n */\nfunction scoringQualityFromObservations(observations: readonly unknown[]): EvaluationQualityStatus {\n const evaluatorObservations = observations.filter(\n (observation): observation is Record<string, unknown> => isRecord(observation) && observation.kind === 'graph',\n );\n const hasCompleteScore =\n evaluatorObservations.length > 0 &&\n evaluatorObservations.every(\n (observation) =>\n observation.status === 'scored' &&\n typeof observation.score === 'number' &&\n Number.isFinite(observation.score) &&\n observation.score >= 0 &&\n observation.score <= 1,\n );\n return hasCompleteScore ? 'scored' : 'unable-to-evaluate';\n}\n\nfunction isQualityReasonCompatible(\n reason: EvaluationQualityReason,\n status: EvaluationQualityStatus,\n purpose: EvaluationRunPurpose,\n executionStatus?: EvaluationTrialExecutionStatus | EvaluationRun['executionStatus'],\n): boolean {\n if (purpose === 'execution-benchmark') {\n return executionStatus === 'canceled' ? reason.code === 'canceled' : reason.code === 'benchmark';\n }\n if (executionStatus === 'queued' || executionStatus === 'running') return reason.code === 'in-progress';\n if (executionStatus === 'canceled') return reason.code === 'canceled';\n switch (status) {\n case 'passed':\n return reason.code === 'checks-passed' || reason.code === 'thresholds-passed';\n case 'failed':\n return reason.code === 'checks-failed' || reason.code === 'thresholds-failed' || reason.code === 'target-error';\n case 'scored':\n return reason.code === 'scores-complete';\n case 'not-evaluated':\n return reason.code === 'no-trial-quality-checks' || reason.code === 'no-completed-trials';\n case 'unable-to-evaluate':\n return (\n reason.code === 'required-check-error' ||\n reason.code === 'required-metric-unavailable' ||\n reason.code === 'scores-incomplete'\n );\n }\n}\n\nfunction normalizeQualityReason(\n value: unknown,\n fallback: EvaluationQualityReason,\n status: EvaluationQualityStatus,\n purpose: EvaluationRunPurpose,\n executionStatus?: EvaluationTrialExecutionStatus | EvaluationRun['executionStatus'],\n): EvaluationQualityReason {\n if (!isRecord(value) || typeof value.code !== 'string' || typeof value.message !== 'string') return fallback;\n const reason = value as unknown as EvaluationQualityReason;\n return isQualityReasonCompatible(reason, status, purpose, executionStatus) ? reason : fallback;\n}\n\nexport function normalizeEvaluationTrial(\n value: EvaluationTrial | unknown,\n purpose: EvaluationRunPurpose = 'evaluation',\n evaluationMode: EvaluationSuiteMode = 'pass-fail',\n): EvaluationTrial {\n if (!isRecord(value)) throw new Error('Evaluation trial must be an object.');\n const legacyStatus = value.status;\n const observations = Array.isArray(value.observations) ? value.observations : [];\n const targetExecutionError = isTargetExecutionError(value, observations);\n const executionStatus = isExecutionStatus(value.executionStatus)\n ? value.executionStatus\n : legacyStatus === 'canceled'\n ? 'canceled'\n : targetExecutionError\n ? 'error'\n : legacyStatus === 'error' &&\n !observations.some(\n (observation) =>\n isRecord(observation) && observation.required !== false && observation.status === 'error',\n )\n ? 'error'\n : 'completed';\n const qualityStatus: EvaluationQualityStatus =\n purpose === 'execution-benchmark' || executionStatus === 'canceled'\n ? 'not-evaluated'\n : executionStatus === 'error'\n ? evaluationMode === 'scoring'\n ? 'unable-to-evaluate'\n : 'failed'\n : evaluationMode === 'scoring'\n ? scoringQualityFromObservations(observations)\n : isQualityStatus(value.qualityStatus) && isQualityStatusForMode(value.qualityStatus, evaluationMode)\n ? value.qualityStatus\n : legacyQualityFromObservations(observations, targetExecutionError);\n const normalized = structuredClone(value) as Record<string, unknown>;\n // Legacy runs stored a single status that conflated execution and quality.\n // Read it above, then remove it so normalized v2 values cannot contradict\n // their authoritative executionStatus/qualityStatus pair.\n delete normalized.status;\n return {\n ...(normalized as unknown as EvaluationTrial),\n executionStatus,\n qualityStatus,\n qualityReason: normalizeQualityReason(\n value.qualityReason,\n executionStatus === 'canceled'\n ? { code: 'canceled', message: 'The execution was canceled.' }\n : purpose === 'execution-benchmark'\n ? { code: 'benchmark', message: 'This run measured execution without evaluating output quality.' }\n : reasonForQualityStatusInMode(qualityStatus, evaluationMode, executionStatus),\n qualityStatus,\n purpose,\n executionStatus,\n ),\n };\n}\n\nexport function normalizeEvaluationAggregate(\n value: EvaluationAggregate | unknown,\n trials?: readonly EvaluationTrial[],\n): EvaluationAggregate {\n if (!isRecord(value)) throw new Error('Evaluation aggregate must be an object.');\n const normalized = structuredClone(value) as unknown as EvaluationAggregate;\n // Never let a graph-facing 0..100 value (or corrupt local data) masquerade\n // as the persisted normalized score and render as an impossible 9900/100.\n if (!isNormalizedScore(normalized.meanScore)) delete normalized.meanScore;\n if (!isNormalizedScore(normalized.medianScore)) delete normalized.medianScore;\n if (!isNormalizedScore(normalized.p95Score)) delete normalized.p95Score;\n if (\n typeof normalized.medianLatencyMs !== 'number' ||\n !Number.isFinite(normalized.medianLatencyMs) ||\n normalized.medianLatencyMs < 0\n ) {\n delete normalized.medianLatencyMs;\n }\n if (trials) {\n const completed = trials.filter((trial) => trial.executionStatus === 'completed');\n const evaluated = completed.filter((trial) => trial.qualityStatus === 'passed' || trial.qualityStatus === 'failed');\n const passed = evaluated.filter((trial) => trial.qualityStatus === 'passed');\n const failed = evaluated.filter((trial) => trial.qualityStatus === 'failed');\n const notEvaluated = completed.filter((trial) => trial.qualityStatus === 'not-evaluated');\n const unable = completed.filter((trial) => trial.qualityStatus === 'unable-to-evaluate');\n const scored = completed.filter((trial) => trial.qualityStatus === 'scored');\n return {\n ...normalized,\n trialCount: trials.length,\n evaluatedTrialCount: evaluated.length,\n notEvaluatedTrialCount: notEvaluated.length,\n unableToEvaluateTrialCount: unable.length,\n passedTrialCount: passed.length,\n failedTrialCount: failed.length,\n erroredTrialCount: trials.filter((trial) => trial.executionStatus === 'error').length,\n canceledTrialCount: trials.filter((trial) => trial.executionStatus === 'canceled').length,\n ...(scored.length > 0 || normalized.scoredTrialCount !== undefined\n ? { scoredTrialCount: scored.length, missingScoreTrialCount: trials.length - scored.length }\n : {}),\n passRate: evaluated.length === 0 ? 0 : passed.length / evaluated.length,\n };\n }\n const trialCount = Number(value.trialCount ?? 0);\n const passed = Number(value.passedTrialCount ?? 0);\n const failed = Number(value.failedTrialCount ?? 0);\n const errored = Number(value.erroredTrialCount ?? 0);\n const canceled = Number(value.canceledTrialCount ?? 0);\n const evaluated = Number(value.evaluatedTrialCount ?? passed + failed);\n const unable = Number(value.unableToEvaluateTrialCount ?? 0);\n const notEvaluated = Number(\n value.notEvaluatedTrialCount ?? Math.max(0, trialCount - evaluated - unable - errored - canceled),\n );\n return {\n ...normalized,\n evaluatedTrialCount: evaluated,\n notEvaluatedTrialCount: notEvaluated,\n unableToEvaluateTrialCount: unable,\n passRate: evaluated === 0 ? 0 : passed / evaluated,\n };\n}\n\nfunction withoutAuthoritativeCost(aggregate: EvaluationAggregate): EvaluationAggregate {\n const normalized = { ...aggregate };\n delete normalized.totalCostUsd;\n delete normalized.averageCostUsd;\n return normalized;\n}\n\nexport function normalizeEvaluationBaselineSnapshot(\n value: EvaluationBaselineSnapshot | unknown,\n): EvaluationBaselineSnapshot {\n if (!isRecord(value)) throw new Error('Evaluation baseline snapshot must be an object.');\n const accountingStatus = isAccountingStatus(value.accountingStatus)\n ? value.accountingStatus\n : isRecord(value.provenance) && value.provenance.accountingComplete === false\n ? 'partial'\n : 'complete';\n const aggregate = normalizeEvaluationAggregate(value.aggregate);\n const purpose = isPurpose(value.purpose) ? value.purpose : 'evaluation';\n const evaluationMode = isEvaluationMode(value.evaluationMode) ? value.evaluationMode : 'pass-fail';\n const hasCompleteScoringAggregate =\n aggregate.trialCount > 0 &&\n aggregate.scoredTrialCount === aggregate.trialCount &&\n aggregate.missingScoreTrialCount === 0 &&\n aggregate.meanScore !== undefined;\n const qualityStatus: EvaluationQualityStatus =\n purpose === 'execution-benchmark'\n ? 'not-evaluated'\n : evaluationMode === 'scoring'\n ? hasCompleteScoringAggregate\n ? 'scored'\n : 'unable-to-evaluate'\n : isQualityStatus(value.qualityStatus) && isQualityStatusForMode(value.qualityStatus, evaluationMode)\n ? value.qualityStatus\n : aggregate.failedTrialCount > 0 || aggregate.erroredTrialCount > 0\n ? 'failed'\n : aggregate.evaluatedTrialCount > 0\n ? 'passed'\n : 'not-evaluated';\n const qualityReasonFallback =\n purpose === 'execution-benchmark'\n ? { code: 'benchmark' as const, message: 'This run measured execution without evaluating output quality.' }\n : reasonForQualityStatusInMode(qualityStatus, evaluationMode);\n return {\n ...(structuredClone(value) as unknown as EvaluationBaselineSnapshot),\n purpose,\n evaluationMode,\n qualityStatus,\n qualityReason: normalizeQualityReason(value.qualityReason, qualityReasonFallback, qualityStatus, purpose),\n accountingStatus,\n aggregate: accountingStatus === 'partial' ? withoutAuthoritativeCost(aggregate) : aggregate,\n };\n}\n\nexport function normalizeEvaluationRun(value: EvaluationRun | unknown): EvaluationRun {\n if (!isRecord(value)) throw new Error('Evaluation run must be an object.');\n const purpose = isPurpose(value.purpose) ? value.purpose : 'evaluation';\n const evaluationMode = isEvaluationMode(value.evaluationMode) ? value.evaluationMode : 'pass-fail';\n const executionStatus = isRunExecutionStatus(value.executionStatus)\n ? value.executionStatus\n : typeof value.completedAt === 'string'\n ? 'completed'\n : 'running';\n const trials = Array.isArray(value.trials)\n ? value.trials.map((trial) => normalizeEvaluationTrial(trial, purpose, evaluationMode))\n : [];\n const accountingStatus = isAccountingStatus(value.accountingStatus)\n ? value.accountingStatus\n : isRecord(value.provenance) && value.provenance.accountingComplete === false\n ? 'partial'\n : 'complete';\n let qualityStatus: EvaluationQualityStatus;\n if (purpose === 'execution-benchmark' || executionStatus === 'canceled') {\n qualityStatus = 'not-evaluated';\n } else if (executionStatus === 'error') {\n qualityStatus = evaluationMode === 'scoring' ? 'unable-to-evaluate' : 'failed';\n } else if (executionStatus === 'queued' || executionStatus === 'running') {\n qualityStatus = 'not-evaluated';\n } else if (evaluationMode === 'scoring') {\n const scored = trials.filter((trial) => trial.qualityStatus === 'scored').length;\n qualityStatus = scored > 0 && scored === trials.length ? 'scored' : 'unable-to-evaluate';\n } else if (isQualityStatus(value.qualityStatus) && isQualityStatusForMode(value.qualityStatus, evaluationMode)) {\n qualityStatus = value.qualityStatus;\n } else if (trials.some((trial) => trial.executionStatus === 'error' || trial.qualityStatus === 'failed')) {\n qualityStatus = 'failed';\n } else if (trials.some((trial) => trial.qualityStatus === 'unable-to-evaluate')) {\n qualityStatus = 'unable-to-evaluate';\n } else if (trials.some((trial) => trial.qualityStatus === 'passed')) {\n qualityStatus = 'passed';\n } else if (value.verdict === 'fail') {\n // Old runs could fail an aggregate threshold without having a per-trial\n // quality observation. Preserve that authoritative failure. Only legacy\n // success-without-evidence is reinterpreted as Not evaluated.\n qualityStatus = 'failed';\n } else {\n // Legacy runs used `pass` for a graph that merely completed. If no stored\n // required check proves quality, reinterpret it as Not evaluated instead\n // of preserving the misleading pass label.\n qualityStatus = 'not-evaluated';\n }\n const qualityReasonFallback =\n executionStatus === 'canceled'\n ? { code: 'canceled' as const, message: 'The evaluation run was canceled.' }\n : executionStatus === 'queued' || executionStatus === 'running'\n ? { code: 'in-progress' as const, message: 'The run is still in progress.' }\n : purpose === 'execution-benchmark'\n ? { code: 'benchmark' as const, message: 'This run measured execution without evaluating output quality.' }\n : (executionStatus === 'error' || trials.some((trial) => trial.executionStatus === 'error')) &&\n qualityStatus === 'failed'\n ? { code: 'target-error' as const, message: 'One or more target graph executions failed.' }\n : reasonForQualityStatusInMode(qualityStatus, evaluationMode);\n const provenance = isRecord(value.provenance)\n ? {\n ...structuredClone(value.provenance),\n accountingComplete: accountingStatus === 'complete',\n }\n : value.provenance;\n const normalized = structuredClone(value) as Record<string, unknown>;\n // As with legacy trial.status, the old verdict is input-only compatibility\n // data. New v2 values expose one unambiguous qualityStatus instead.\n delete normalized.verdict;\n const name = typeof value.name === 'string' && value.name.trim().length > 0 ? value.name.trim() : undefined;\n delete normalized.name;\n const requestedTrialCount =\n typeof value.requestedTrialCount === 'number' &&\n Number.isSafeInteger(value.requestedTrialCount) &&\n value.requestedTrialCount >= 0\n ? value.requestedTrialCount\n : undefined;\n delete normalized.requestedTrialCount;\n const aggregate = value.aggregate === undefined ? undefined : normalizeEvaluationAggregate(value.aggregate, trials);\n return {\n ...(normalized as unknown as EvaluationRun),\n version: 2,\n purpose,\n evaluationMode,\n executionStatus,\n qualityStatus,\n qualityReason: normalizeQualityReason(\n value.qualityReason,\n qualityReasonFallback,\n qualityStatus,\n purpose,\n executionStatus,\n ),\n accountingStatus,\n provenance: provenance as EvaluationRun['provenance'],\n trials,\n thresholdResults: Array.isArray(value.thresholdResults)\n ? (structuredClone(value.thresholdResults) as EvaluationRun['thresholdResults'])\n : [],\n ...(name === undefined ? {} : { name }),\n ...(requestedTrialCount === undefined ? {} : { requestedTrialCount }),\n ...(aggregate === undefined\n ? {}\n : { aggregate: accountingStatus === 'partial' ? withoutAuthoritativeCost(aggregate) : aggregate }),\n };\n}\n", "import { assertPortableJson } from './canonical.js';\nimport type { EvaluationDataset, PortableJson } from './types.js';\n\nexport const portableEvaluationDataTypes = [\n 'any',\n 'any[]',\n 'string',\n 'string[]',\n 'date',\n 'date[]',\n 'time',\n 'time[]',\n 'datetime',\n 'datetime[]',\n 'number',\n 'number[]',\n 'vector',\n 'vector[]',\n 'boolean',\n 'boolean[]',\n 'object',\n 'object[]',\n] as const;\n\nconst portableEvaluationDataTypeSet = new Set<string>(portableEvaluationDataTypes);\n\nexport function isPortableEvaluationDataType(dataType: string): boolean {\n return portableEvaluationDataTypeSet.has(dataType);\n}\n\nfunction isObject(value: PortableJson): boolean {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction isFiniteNumber(value: PortableJson): boolean {\n return typeof value === 'number' && Number.isFinite(value);\n}\n\nfunction isArrayOf(value: PortableJson, predicate: (item: PortableJson) => boolean): boolean {\n return Array.isArray(value) && value.every(predicate);\n}\n\n/**\n * Checks a portable dataset value against the Rivet data type selected for an\n * evaluation field. This is shared by authoring UI and execution validation so\n * a value cannot look valid in the editor and then fail under a different rule\n * in the runner.\n */\nexport function isEvaluationValueCompatibleWithDataType(value: PortableJson, dataType: string): boolean {\n try {\n assertPortableJson(value);\n } catch {\n return false;\n }\n\n if (dataType === 'any') return true;\n if (dataType === 'any[]') return Array.isArray(value);\n if (dataType === 'string' || dataType === 'date' || dataType === 'time' || dataType === 'datetime') {\n return typeof value === 'string';\n }\n if (dataType === 'string[]' || dataType === 'date[]' || dataType === 'time[]' || dataType === 'datetime[]') {\n return isArrayOf(value, (item) => typeof item === 'string');\n }\n if (dataType === 'number') return isFiniteNumber(value);\n if (dataType === 'number[]' || dataType === 'vector') return isArrayOf(value, isFiniteNumber);\n if (dataType === 'vector[]') {\n return isArrayOf(value, (item) => isArrayOf(item, isFiniteNumber));\n }\n if (dataType === 'boolean') return typeof value === 'boolean';\n if (dataType === 'boolean[]') return isArrayOf(value, (item) => typeof item === 'boolean');\n if (dataType === 'object') return isObject(value);\n if (dataType === 'object[]') return isArrayOf(value, isObject);\n\n // Functions, binary/media values, and provider-specific structured types\n // do not have a safe portable dataset representation here. Unknown future\n // types must also fail closed until their exact JSON contract is defined.\n return false;\n}\n\n/** Shared declared-type check for graph/dataset binding authoring and execution validation. */\nexport function areEvaluationDataTypesCompatible(sourceDataType: string, targetDataType: string): boolean {\n return sourceDataType === 'any' || targetDataType === 'any' || sourceDataType === targetDataType;\n}\n\n/**\n * Enforces the declared portable JSON contract at explicit transfer\n * boundaries. Durable local drafts remain recoverable even if an older build\n * wrote an unsupported type; imports and exports fail with the precise field\n * and case that needs repair instead of deferring the error until execution.\n */\nexport function assertEvaluationDatasetValuesMatchDeclaredTypes(dataset: EvaluationDataset): void {\n const fieldsById = new Map(dataset.fields.map((field) => [field.id, field]));\n for (const [fieldIndex, field] of dataset.fields.entries()) {\n if (!isPortableEvaluationDataType(field.dataType)) {\n throw new Error(\n `fields[${fieldIndex}].dataType \"${field.dataType}\" has no portable evaluation JSON representation.`,\n );\n }\n }\n\n for (const [caseIndex, testCase] of dataset.cases.entries()) {\n for (const [fieldId, value] of Object.entries(testCase.values)) {\n const field = fieldsById.get(fieldId);\n if (field && !isEvaluationValueCompatibleWithDataType(value, field.dataType)) {\n throw new Error(\n `cases[${caseIndex}].values.${fieldId} is not compatible with declared type \"${field.dataType}\".`,\n );\n }\n }\n }\n}\n", "import {\n evaluateAssertion,\n getEvaluationTopLevelOutputId,\n validateEvaluationAssertionConfiguration,\n} from './assertions.js';\nimport {\n assertPortableJson,\n canonicalStringify,\n clonePortableJson,\n fingerprint,\n fingerprintEvaluationDataset,\n} from './canonical.js';\nimport { normalizeEvaluationRun } from './normalization.js';\nimport { EvaluationGraphExecutionError } from './types.js';\nimport { areEvaluationDataTypesCompatible, isEvaluationValueCompatibleWithDataType } from './dataTypes.js';\nimport type {\n EvaluationAggregate,\n EvaluationBaselineSnapshot,\n EvaluationCaseAggregate,\n EvaluationDataset,\n EvaluationExecutionMetrics,\n EvaluationGraphRunner,\n EvaluationGraphEvaluator,\n EvaluationObservation,\n EvaluationProjectData,\n EvaluationQualityReason,\n EvaluationQualityStatus,\n EvaluationRun,\n EvaluationRunEvent,\n EvaluationRunPurpose,\n EvaluationRunProvenance,\n EvaluationSuite,\n EvaluationSuiteMode,\n EvaluationThreshold,\n EvaluationThresholdResult,\n EvaluationTrial,\n EvaluationTrialExecutionStatus,\n EvaluationRecordingReference,\n PortableJson,\n} from './types.js';\nimport { findAutoDelegateGraphCandidate } from '@valerypopoff/rivet2-core';\nimport type {\n ChartNode,\n GraphId,\n GraphInputNode,\n GraphOutputNode,\n NodeConnection,\n NodeGraph,\n Project,\n} from '@valerypopoff/rivet2-core';\n\nconst DEFAULT_CONCURRENCY = 4;\nconst MAX_CONCURRENCY = 32;\n\nexport const LEGACY_EVALUATOR_INPUT_IDS = ['case', 'inputs', 'expected', 'outputs', 'run'] as const;\n\nexport type RunEvaluationSuiteOptions = {\n project: Project;\n evaluationData: EvaluationProjectData;\n dataset: EvaluationDataset;\n suiteId: string;\n runGraph: EvaluationGraphRunner;\n projectFingerprint?: string;\n executionMode?: string;\n signal?: AbortSignal;\n runId?: string;\n /** An evaluation judges quality; a benchmark deliberately measures execution only. */\n purpose?: EvaluationRunPurpose;\n /** Explicit caller selection; otherwise the suite's saved baseline is used. */\n baseline?: EvaluationBaselineSnapshot;\n /** Incremental live-run transport. Prefer this over onUpdate in new integrations. */\n onEvent?: (event: EvaluationRunEvent) => void | Promise<void>;\n /** @deprecated Prefer onEvent; this clones the complete accumulated run after every trial. */\n onUpdate?: (run: EvaluationRun) => void;\n};\n\nexport function hasAuthoritativeEvaluationCriteria(suite: EvaluationSuite): boolean {\n if (getEvaluationSuiteMode(suite) === 'scoring') return suite.evaluators.length > 0;\n return (\n suite.assertions.some((assertion) => assertion.required !== false) ||\n suite.evaluators.some((evaluator) => evaluator.required !== false) ||\n (suite.thresholds?.length ?? 0) > 0\n );\n}\n\n/** Older saved suites predate scoring and therefore retain pass/fail semantics. */\nexport function getEvaluationSuiteMode(suite: Pick<EvaluationSuite, 'evaluationMode'>): EvaluationSuiteMode {\n return suite.evaluationMode === 'scoring' ? 'scoring' : 'pass-fail';\n}\n\n/** Existing evaluators with the complete reserved-input contract keep working without migration. */\nexport function usesLegacyEvaluatorInputEnvelope(\n evaluator: Pick<EvaluationGraphEvaluator, 'inputBindings'>,\n graphInputIds: readonly string[],\n): boolean {\n return (\n evaluator.inputBindings === undefined &&\n LEGACY_EVALUATOR_INPUT_IDS.every((inputId) => graphInputIds.includes(inputId))\n );\n}\n\n/**\n * Shared bounded work scheduler for evaluation adapters that need stable\n * result ordering without serializing independent cases. It deliberately has\n * no retry policy: callers own their authoritative execution semantics.\n *\n * The result array is aligned to `work`; entries that were still queued when\n * the signal was canceled stay `undefined`. Completed work is never erased.\n */\nexport type RunEvaluationWorkPoolOptions<TWork, TResult> = {\n work: readonly TWork[];\n concurrency: number;\n signal?: AbortSignal;\n execute: (work: TWork, index: number) => Promise<TResult>;\n onSettled?: (result: TResult, index: number, results: readonly (TResult | undefined)[]) => void | Promise<void>;\n};\n\nexport async function runEvaluationWorkPool<TWork, TResult>(\n options: RunEvaluationWorkPoolOptions<TWork, TResult>,\n): Promise<readonly (TResult | undefined)[]> {\n if (!Number.isSafeInteger(options.concurrency) || options.concurrency < 1) {\n throw new Error('Evaluation worker-pool concurrency must be a positive safe integer.');\n }\n const results: Array<TResult | undefined> = Array.from({ length: options.work.length });\n let nextIndex = 0;\n const worker = async () => {\n while (true) {\n // Do not dequeue a new case after cancellation. Active work receives\n // the same signal and may still settle with useful partial evidence.\n if (options.signal?.aborted) return;\n const index = nextIndex++;\n if (index >= options.work.length) return;\n const work = options.work[index]!;\n const result = await options.execute(work, index);\n results[index] = result;\n await options.onSettled?.(result, index, results);\n }\n };\n await Promise.all(Array.from({ length: Math.min(options.concurrency, options.work.length) }, worker));\n return results;\n}\n\nexport function createEmptyMetrics(): EvaluationExecutionMetrics {\n return { durationMs: 0 };\n}\n\nconst executionMetricCountKeys = [\n 'inputTokens',\n 'outputTokens',\n 'cachedInputTokens',\n 'reasoningTokens',\n 'modelCallCount',\n 'toolCallCount',\n 'toolFailureCount',\n] as const;\n\n/**\n * Graph runners are host adapters, so their TypeScript return type is not a\n * runtime trust boundary. Copy only the metrics Rivet understands and reject\n * values that would become `null` or otherwise change during JSON storage.\n */\nfunction cloneExecutionMetrics(value: EvaluationExecutionMetrics, path: string): EvaluationExecutionMetrics {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error(`${path} must be an object.`);\n }\n if (!Number.isFinite(value.durationMs) || value.durationMs < 0) {\n throw new Error(`${path}.durationMs must be a non-negative finite number.`);\n }\n const metrics: EvaluationExecutionMetrics = { durationMs: value.durationMs };\n for (const key of executionMetricCountKeys) {\n const count = value[key];\n if (count === undefined) continue;\n if (!Number.isSafeInteger(count) || count < 0) {\n throw new Error(`${path}.${key} must be a non-negative safe integer.`);\n }\n metrics[key] = count;\n }\n if (value.costUsd !== undefined) {\n if (!Number.isFinite(value.costUsd) || value.costUsd < 0) {\n throw new Error(`${path}.costUsd must be a non-negative finite number.`);\n }\n metrics.costUsd = value.costUsd;\n }\n if (value.hasUnknownCost !== undefined) {\n if (typeof value.hasUnknownCost !== 'boolean') throw new Error(`${path}.hasUnknownCost must be a boolean.`);\n metrics.hasUnknownCost = value.hasUnknownCost;\n }\n return metrics;\n}\n\nfunction tryCloneExecutionMetrics(\n value: EvaluationExecutionMetrics | undefined,\n path: string,\n): EvaluationExecutionMetrics | undefined {\n if (value === undefined) return undefined;\n try {\n return cloneExecutionMetrics(value, path);\n } catch {\n return undefined;\n }\n}\n\nfunction cloneOptionalPortableJson(value: PortableJson | undefined, path: string): PortableJson | undefined {\n if (value === undefined) return undefined;\n assertPortableJson(value, path);\n return clonePortableJson(value);\n}\n\nfunction tryCloneOptionalPortableJson(value: PortableJson | undefined, path: string): PortableJson | undefined {\n try {\n return cloneOptionalPortableJson(value, path);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Resolves the provisional recording references created while a suite is\n * running into its final retention policy. The caller persists the returned\n * references through its EvaluationRunStore.\n *\n * A successful candidate recording remains promotable for 24 hours by\n * default. Failed/error trials are retained, and `all` pins every artifact.\n * This deliberately operates per trial: one failed case must not pin every\n * otherwise-successful recording in the suite.\n */\nexport function finalizeEvaluationRecordingRetention(\n run: EvaluationRun,\n policy: 'failures-and-baselines' | 'all' = 'failures-and-baselines',\n now = Date.now(),\n): EvaluationRun {\n const retainAll = policy === 'all';\n const finalize = (reference: EvaluationRecordingReference, failed: boolean): EvaluationRecordingReference => {\n const retention: EvaluationRecordingReference['retention'] = retainAll\n ? 'retained'\n : failed\n ? 'failure'\n : 'temporary';\n return {\n id: reference.id,\n retention,\n ...(retention === 'temporary' ? { expiresAt: new Date(now + 24 * 60 * 60 * 1000).toISOString() } : {}),\n };\n };\n return {\n ...run,\n trials: run.trials.map((trial) => {\n const targetFailed =\n trial.executionStatus !== 'completed' ||\n trial.observations.some(\n (observation) =>\n observation.kind === 'assertion' &&\n observation.required &&\n (observation.status === 'failed' || observation.status === 'error'),\n );\n return {\n ...trial,\n ...(trial.recording === undefined ? {} : { recording: finalize(trial.recording, targetFailed) }),\n observations: trial.observations.map((observation) => ({\n ...observation,\n ...(observation.recording === undefined\n ? {}\n : {\n recording: finalize(\n observation.recording,\n observation.status === 'failed' || observation.status === 'error',\n ),\n }),\n })),\n };\n }),\n };\n}\n\nfunction mergeMetrics(...metrics: EvaluationExecutionMetrics[]): EvaluationExecutionMetrics {\n const numberKeys: Array<keyof EvaluationExecutionMetrics> = [\n 'durationMs',\n 'inputTokens',\n 'outputTokens',\n 'cachedInputTokens',\n 'reasoningTokens',\n 'modelCallCount',\n 'toolCallCount',\n 'toolFailureCount',\n 'costUsd',\n ];\n const merged: EvaluationExecutionMetrics = { durationMs: 0 };\n for (const key of numberKeys) {\n const value = metrics.reduce((sum, item) => sum + ((item[key] as number | undefined) ?? 0), 0);\n if (value !== 0 || key === 'durationMs') (merged as Record<string, unknown>)[key] = value;\n }\n if (metrics.some((item) => item.hasUnknownCost)) merged.hasUnknownCost = true;\n return merged;\n}\n\nfunction makeId(prefix: string): string {\n const cryptoValue = globalThis.crypto;\n if (cryptoValue?.randomUUID) return `${prefix}-${cryptoValue.randomUUID()}`;\n return `${prefix}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;\n}\n\nfunction toErrorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction throwIfAborted(signal?: AbortSignal): void {\n if (signal?.aborted) throw signal.reason ?? new DOMException('Evaluation canceled.', 'AbortError');\n}\n\nfunction isAbort(error: unknown): boolean {\n return (\n (error instanceof DOMException && error.name === 'AbortError') ||\n (typeof error === 'object' &&\n error !== null &&\n 'name' in error &&\n (error as { name?: unknown }).name === 'AbortError')\n );\n}\n\nfunction resolveSuite(data: EvaluationProjectData, id: string): EvaluationSuite {\n const suite = data.suites.find((candidate) => candidate.id === id);\n if (!suite) throw new Error(`Evaluation suite \"${id}\" does not exist.`);\n return suite;\n}\n\nfunction validateDefinitionIds(suite: EvaluationSuite): void {\n const seen = new Map<string, string>();\n for (const [kind, definitions] of [\n ['quality check', suite.assertions],\n ['evaluator graph', suite.evaluators],\n ['threshold', suite.thresholds ?? []],\n ] as const) {\n for (const definition of definitions) {\n if (typeof definition.id !== 'string' || definition.id.trim().length === 0) {\n throw new Error(`Every evaluation ${kind} must have a non-empty id.`);\n }\n const previous = seen.get(definition.id);\n if (previous) {\n throw new Error(`Evaluation ${kind} id \"${definition.id}\" duplicates a ${previous} id.`);\n }\n seen.set(definition.id, kind);\n }\n }\n}\n\nconst rateThresholdMetrics = new Set([\n 'pass-rate',\n 'mean-score',\n 'target-error-rate',\n 'evaluator-error-rate',\n 'tool-failure-rate',\n]);\n\nfunction formatThresholdResultValue(metric: string, operator: EvaluationThreshold['operator'], value: number): string {\n return operator === 'max-regression' || rateThresholdMetrics.has(metric)\n ? `${Number((value * 100).toFixed(4))}%`\n : String(value);\n}\n\nfunction validateThresholdConfiguration(threshold: EvaluationThreshold): void {\n const { metric, operator, value } = threshold as EvaluationThreshold & {\n metric: string;\n operator: string;\n value: number;\n };\n if (typeof metric !== 'string' || metric.length === 0) {\n throw new Error(`Evaluation threshold \"${threshold.id}\" must select a metric.`);\n }\n if (typeof operator !== 'string') {\n throw new Error(`Evaluation threshold \"${threshold.id}\" must select an operator.`);\n }\n if (!Number.isFinite(value)) throw new Error(`Evaluation threshold \"${threshold.id}\" must use a finite value.`);\n\n if (rateThresholdMetrics.has(metric) && (value < 0 || value > 1)) {\n throw new Error(`Evaluation threshold \"${threshold.id}\" must use a value from 0 to 1.`);\n }\n if (['average-cost', 'total-cost', 'average-latency-ms', 'p95-latency-ms'].includes(metric) && value < 0) {\n throw new Error(`Evaluation threshold \"${threshold.id}\" cannot use a negative value.`);\n }\n if (operator === 'max-regression') {\n if (value < 0) throw new Error(`Evaluation regression threshold \"${threshold.id}\" cannot be negative.`);\n return;\n }\n const expectedOperator =\n metric === 'pass-rate' || metric === 'mean-score'\n ? 'at-least'\n : metric.startsWith('custom:')\n ? undefined\n : 'at-most';\n if (\n (expectedOperator !== undefined && operator !== expectedOperator) ||\n (expectedOperator === undefined && operator !== 'at-least' && operator !== 'at-most')\n ) {\n throw new Error(`Evaluation threshold \"${threshold.id}\" uses an incompatible operator for \"${metric}\".`);\n }\n}\n\nfunction validateSuite(\n project: Project,\n suite: EvaluationSuite,\n dataset: EvaluationDataset,\n purpose: EvaluationRunPurpose,\n): void {\n const evaluationMode = getEvaluationSuiteMode(suite);\n validateDefinitionIds(suite);\n if (dataset.projectId !== undefined && dataset.projectId !== project.metadata.id) {\n throw new Error(`Evaluation dataset \"${dataset.name}\" belongs to a different project.`);\n }\n if (suite.datasetId !== dataset.id)\n throw new Error(`Suite \"${suite.name}\" is bound to a different evaluation dataset.`);\n const graph = project.graphs[suite.targetGraphId];\n if (!graph) throw new Error(`Target graph \"${suite.targetGraphId}\" does not exist.`);\n const graphInputs = graph.nodes.filter((node): node is GraphInputNode => node.type === 'graphInput');\n const graphInputIds = graphInputs.map((input) => input.data.id);\n if (new Set(graphInputIds).size !== graphInputIds.length) {\n throw new Error(`Target graph \"${suite.targetGraphId}\" has duplicate Graph Input ids.`);\n }\n const graphOutputs = graph.nodes.filter((node): node is GraphOutputNode => node.type === 'graphOutput');\n const graphOutputIds = graphOutputs.map((output) => output.data.id);\n if (new Set(graphOutputIds).size !== graphOutputIds.length) {\n throw new Error(`Target graph \"${suite.targetGraphId}\" has duplicate Graph Output ids.`);\n }\n const inputIds = new Set(graphInputIds);\n const graphInputsById = new Map(graphInputs.map((input) => [input.data.id, input]));\n const fields = new Map(dataset.fields.map((field) => [field.id, field]));\n if (fields.size !== dataset.fields.length)\n throw new Error(`Evaluation dataset \"${dataset.name}\" has duplicate field ids.`);\n const boundGraphInputs = new Set<string>();\n for (const binding of suite.inputBindings) {\n if (boundGraphInputs.has(binding.graphInputId)) {\n throw new Error(`Target graph input \"${binding.graphInputId}\" is bound more than once.`);\n }\n boundGraphInputs.add(binding.graphInputId);\n if (!inputIds.has(binding.graphInputId))\n throw new Error(`Graph input \"${binding.graphInputId}\" does not exist on the target graph.`);\n const field = fields.get(binding.datasetFieldId);\n if (!field) throw new Error(`Evaluation dataset field \"${binding.datasetFieldId}\" does not exist.`);\n if (field.role !== 'input')\n throw new Error(`Dataset field \"${field.name}\" must have the input role to bind it to a graph input.`);\n const graphInput = graphInputsById.get(binding.graphInputId)!;\n if (!areEvaluationDataTypesCompatible(field.dataType, graphInput.data.dataType)) {\n throw new Error(\n `Dataset field \"${field.name}\" (${field.dataType}) is not compatible with graph input \"${graphInput.data.id}\" (${graphInput.data.dataType}).`,\n );\n }\n }\n for (const input of graphInputs) {\n if (suite.inputBindings.some((binding) => binding.graphInputId === input.data.id)) continue;\n // A connection-driven default cannot be proven before executing the graph;\n // require an explicit dataset binding in that case instead of quietly\n // fabricating a value from the input data type.\n if (input.data.defaultValue === undefined || input.data.useDefaultValueInput) {\n throw new Error(\n `Target graph input \"${input.data.id}\" must be bound to an evaluation dataset field or have a static graph default.`,\n );\n }\n }\n\n // Validate every enabled case before the worker pool starts. The declared\n // field type is part of the dataset contract even when that field is not\n // bound directly to the target graph (for example evaluator metadata).\n for (const testCase of dataset.cases.filter((candidate) => candidate.enabled !== false)) {\n for (const [fieldId, value] of Object.entries(testCase.values)) {\n const field = fields.get(fieldId);\n if (!field) {\n throw new Error(`Case \"${testCase.name}\" supplies unknown dataset field \"${fieldId}\".`);\n }\n assertPortableJson(value, `case.${testCase.id}.${fieldId}`);\n if (!isEvaluationValueCompatibleWithDataType(value, field.dataType)) {\n throw new Error(\n `Case \"${testCase.name}\" value for \"${field.name}\" is not compatible with its declared ${field.dataType} type.`,\n );\n }\n }\n for (const binding of suite.inputBindings) {\n const value = testCase.values[binding.datasetFieldId];\n if (value === undefined) {\n const field = fields.get(binding.datasetFieldId)!;\n throw new Error(`Case \"${testCase.name}\" has no saved value for bound input field \"${field.name}\".`);\n }\n const graphInput = graphInputsById.get(binding.graphInputId)!;\n if (!isEvaluationValueCompatibleWithDataType(value, graphInput.data.dataType)) {\n throw new Error(\n `Case \"${testCase.name}\" value for \"${binding.datasetFieldId}\" is not compatible with target graph input \"${binding.graphInputId}\" (${graphInput.data.dataType}).`,\n );\n }\n }\n for (const field of dataset.fields) {\n const requiredForThisRun = field.required && (purpose === 'evaluation' || field.role === 'input');\n if (requiredForThisRun && testCase.values[field.id] === undefined) {\n throw new Error(`Case \"${testCase.name}\" is missing required field \"${field.name}\".`);\n }\n }\n }\n if (purpose === 'evaluation' && evaluationMode === 'pass-fail') {\n for (const assertion of suite.assertions) {\n const outputId = getEvaluationTopLevelOutputId(assertion.outputPath);\n if (assertion.outputPath.trim() !== '$' && outputId === undefined) {\n throw new Error(`Assertion \"${assertion.name}\" output path must start with a named target Graph Output.`);\n }\n if (outputId !== undefined && !graphOutputIds.includes(outputId)) {\n throw new Error(`Assertion \"${assertion.name}\" references missing target output \"${outputId}\".`);\n }\n if (assertion.expected.kind === 'dataset-field') {\n const field = fields.get(assertion.expected.fieldId);\n if (!field) throw new Error(`Assertion \"${assertion.name}\" references a missing expected dataset field.`);\n if (field.role !== 'expected')\n throw new Error(`Assertion \"${assertion.name}\" must reference a dataset field with the expected role.`);\n for (const testCase of dataset.cases.filter((candidate) => candidate.enabled !== false)) {\n const expected = testCase.values[field.id];\n if (expected === undefined) {\n throw new Error(`Case \"${testCase.name}\" is missing expected field \"${field.name}\".`);\n }\n validateEvaluationAssertionConfiguration(assertion, expected);\n }\n } else {\n validateEvaluationAssertionConfiguration(assertion, assertion.expected.value);\n }\n }\n }\n if (suite.configuration?.seed !== undefined) {\n const seedInputId = suite.configuration.seedGraphInputId;\n if (!seedInputId) throw new Error('A suite seed requires selecting the target graph input that receives it.');\n const seedInput = graphInputsById.get(seedInputId);\n if (!seedInput)\n throw new Error(`The selected seed graph input \"${seedInputId}\" does not exist on the target graph.`);\n if (seedInput.data.dataType !== 'number' && seedInput.data.dataType !== 'any') {\n throw new Error(`The selected seed graph input \"${seedInputId}\" must accept a number.`);\n }\n if (suite.inputBindings.some((binding) => binding.graphInputId === seedInputId)) {\n throw new Error(`The selected seed graph input \"${seedInputId}\" cannot also be bound to a dataset field.`);\n }\n }\n for (const evaluator of purpose === 'evaluation' ? suite.evaluators : []) {\n if (\n evaluator.scoreWeight !== undefined &&\n (!Number.isFinite(evaluator.scoreWeight) || evaluator.scoreWeight <= 0)\n ) {\n throw new Error(`Evaluator graph \"${evaluator.name}\" score weight must be a positive finite number.`);\n }\n const evaluatorGraph = project.graphs[evaluator.graphId];\n if (!evaluatorGraph) throw new Error(`Evaluator graph \"${evaluator.graphId}\" does not exist.`);\n const evaluatorGraphInputs = evaluatorGraph.nodes.filter(\n (node): node is GraphInputNode => node.type === 'graphInput',\n );\n const evaluatorInputIds = evaluatorGraphInputs.map((input) => input.data.id);\n if (new Set(evaluatorInputIds).size !== evaluatorInputIds.length) {\n throw new Error(`Evaluator graph \"${evaluator.name}\" has duplicate Graph Input ids.`);\n }\n const evaluatorOutputIds = evaluatorGraph.nodes\n .filter((node): node is GraphOutputNode => node.type === 'graphOutput')\n .map((output) => output.data.id);\n if (new Set(evaluatorOutputIds).size !== evaluatorOutputIds.length) {\n throw new Error(`Evaluator graph \"${evaluator.name}\" has duplicate Graph Output ids.`);\n }\n const evaluatorInputsById = new Map(evaluatorGraphInputs.map((input) => [input.data.id, input]));\n const usesLegacyInputs = usesLegacyEvaluatorInputEnvelope(evaluator, evaluatorInputIds);\n if (usesLegacyInputs) {\n for (const inputId of LEGACY_EVALUATOR_INPUT_IDS) {\n const evaluatorInput = evaluatorInputsById.get(inputId)!;\n if (evaluatorInput.data.dataType !== 'object' && evaluatorInput.data.dataType !== 'any') {\n throw new Error(\n `Evaluator graph \"${evaluator.name}\" legacy input \"${inputId}\" must accept the object or any data type.`,\n );\n }\n }\n for (const evaluatorInput of evaluatorGraphInputs) {\n if (\n LEGACY_EVALUATOR_INPUT_IDS.includes(evaluatorInput.data.id as (typeof LEGACY_EVALUATOR_INPUT_IDS)[number])\n ) {\n continue;\n }\n if (evaluatorInput.data.defaultValue === undefined || evaluatorInput.data.useDefaultValueInput) {\n throw new Error(\n `Evaluator graph \"${evaluator.name}\" input \"${evaluatorInput.data.id}\" needs a direct binding or a static graph default.`,\n );\n }\n }\n } else {\n const evaluatorBindings = evaluator.inputBindings ?? [];\n const boundEvaluatorInputs = new Set<string>();\n for (const binding of evaluatorBindings) {\n if (boundEvaluatorInputs.has(binding.graphInputId)) {\n throw new Error(\n `Evaluator graph \"${evaluator.name}\" input \"${binding.graphInputId}\" is bound more than once.`,\n );\n }\n boundEvaluatorInputs.add(binding.graphInputId);\n const evaluatorInput = evaluatorInputsById.get(binding.graphInputId);\n if (!evaluatorInput) {\n throw new Error(\n `Evaluator graph \"${evaluator.name}\" input \"${binding.graphInputId}\" does not exist on the selected graph.`,\n );\n }\n\n let sourceDataType: string;\n if (binding.source.kind === 'dataset-field') {\n const field = fields.get(binding.source.fieldId);\n if (!field) {\n throw new Error(\n `Evaluator graph \"${evaluator.name}\" binding references missing dataset field \"${binding.source.fieldId}\".`,\n );\n }\n sourceDataType = field.dataType;\n for (const testCase of dataset.cases.filter((candidate) => candidate.enabled !== false)) {\n const value = testCase.values[field.id];\n if (value === undefined) {\n throw new Error(\n `Case \"${testCase.name}\" has no saved value for evaluator input \"${binding.graphInputId}\" from dataset field \"${field.name}\".`,\n );\n }\n if (!isEvaluationValueCompatibleWithDataType(value, evaluatorInput.data.dataType)) {\n throw new Error(\n `Case \"${testCase.name}\" value from dataset field \"${field.name}\" is not compatible with evaluator input \"${binding.graphInputId}\" (${evaluatorInput.data.dataType}).`,\n );\n }\n }\n } else if (binding.source.kind === 'target-output') {\n const outputId = binding.source.outputId;\n const targetOutput = graph.nodes.find(\n (node): node is GraphOutputNode =>\n node.type === 'graphOutput' && (node.data as { id?: unknown }).id === outputId,\n );\n if (!targetOutput) {\n throw new Error(\n `Evaluator graph \"${evaluator.name}\" binding references missing target output \"${outputId}\".`,\n );\n }\n sourceDataType = targetOutput.data.dataType;\n } else if (binding.source.kind === 'context') {\n sourceDataType = 'object';\n } else {\n throw new Error(\n `Evaluator graph \"${evaluator.name}\" input \"${binding.graphInputId}\" uses an unsupported source.`,\n );\n }\n if (!areEvaluationDataTypesCompatible(sourceDataType, evaluatorInput.data.dataType)) {\n throw new Error(\n `Evaluator graph \"${evaluator.name}\" source for input \"${binding.graphInputId}\" (${sourceDataType}) is not compatible with ${evaluatorInput.data.dataType}.`,\n );\n }\n }\n for (const evaluatorInput of evaluatorGraphInputs) {\n if (boundEvaluatorInputs.has(evaluatorInput.data.id)) continue;\n if (evaluatorInput.data.defaultValue === undefined || evaluatorInput.data.useDefaultValueInput) {\n throw new Error(\n `Evaluator graph \"${evaluator.name}\" input \"${evaluatorInput.data.id}\" must be bound to a target output, dataset field, or evaluation context value, or have a static graph default.`,\n );\n }\n }\n }\n const resultOutput = evaluatorGraph.nodes.find(\n (node): node is GraphOutputNode => node.type === 'graphOutput' && (node.data as { id?: unknown }).id === 'result',\n );\n if (!resultOutput) {\n throw new Error(`Evaluator graph \"${evaluator.name}\" must declare a Graph Output named \"result\".`);\n }\n if (resultOutput.data.dataType !== 'object' && resultOutput.data.dataType !== 'any') {\n throw new Error(`Evaluator graph \"${evaluator.name}\" output \"result\" must have the object data type.`);\n }\n }\n\n if (purpose === 'evaluation' && evaluationMode === 'pass-fail') {\n const hasRequiredPerTrialCheck =\n suite.assertions.some((assertion) => assertion.required !== false) ||\n suite.evaluators.some((evaluator) => evaluator.required !== false);\n const hasEvaluator = suite.evaluators.length > 0;\n for (const threshold of suite.thresholds ?? []) {\n validateThresholdConfiguration(threshold);\n const metric = threshold.metric;\n const supportedExecutionMetric = [\n 'target-error-rate',\n 'tool-failure-rate',\n 'average-cost',\n 'total-cost',\n 'average-latency-ms',\n 'p95-latency-ms',\n ].includes(metric);\n const supportedEvaluatorMetric =\n metric === 'mean-score' ||\n metric === 'evaluator-error-rate' ||\n (metric.startsWith('custom:') && metric.length > 'custom:'.length);\n if (metric === 'pass-rate' && !hasRequiredPerTrialCheck) {\n throw new Error('A pass-rate threshold requires at least one required quality check or evaluator graph.');\n }\n if (supportedEvaluatorMetric && !hasEvaluator) {\n throw new Error(`The \"${metric}\" threshold requires at least one evaluator graph.`);\n }\n if (metric !== 'pass-rate' && !supportedExecutionMetric && !supportedEvaluatorMetric) {\n throw new Error(`Evaluation threshold metric \"${metric}\" is not supported.`);\n }\n }\n } else if (purpose === 'evaluation' && suite.evaluators.length === 0) {\n throw new Error('A scoring evaluation suite requires at least one evaluator graph.');\n }\n\n const caseIds = new Set(dataset.cases.map((testCase) => testCase.id));\n if (caseIds.size !== dataset.cases.length)\n throw new Error(`Evaluation dataset \"${dataset.name}\" has duplicate case ids.`);\n\n if (!dataset.cases.some((testCase) => testCase.enabled !== false)) {\n throw new Error(`Evaluation dataset \"${dataset.name}\" has no enabled cases.`);\n }\n\n const configuration = suite.configuration;\n if (\n configuration?.trialCount !== undefined &&\n (!Number.isSafeInteger(configuration.trialCount) || configuration.trialCount < 1)\n ) {\n throw new Error('Evaluation trial count must be a positive safe integer.');\n }\n if (\n configuration?.concurrency !== undefined &&\n (!Number.isSafeInteger(configuration.concurrency) ||\n configuration.concurrency < 1 ||\n configuration.concurrency > MAX_CONCURRENCY)\n ) {\n throw new Error(`Evaluation concurrency must be a whole number from 1 to ${MAX_CONCURRENCY}.`);\n }\n if (\n configuration?.timeoutMs !== undefined &&\n (!Number.isFinite(configuration.timeoutMs) || configuration.timeoutMs <= 0)\n ) {\n throw new Error('Evaluation timeout must be a positive number of milliseconds.');\n }\n if (configuration?.seed !== undefined && (!Number.isSafeInteger(configuration.seed) || configuration.seed < 0)) {\n throw new Error('Evaluation seed must be a non-negative safe integer.');\n }\n}\n\nfunction resolveCaseInputs(\n suite: EvaluationSuite,\n dataset: EvaluationDataset,\n testCase: EvaluationDataset['cases'][number],\n purpose: EvaluationRunPurpose,\n): {\n inputs: Record<string, PortableJson>;\n expected: Record<string, PortableJson>;\n} {\n const fields = new Map(dataset.fields.map((field) => [field.id, field]));\n const inputs: Record<string, PortableJson> = {};\n const expected: Record<string, PortableJson> = {};\n for (const field of dataset.fields) {\n const value = testCase.values[field.id];\n if (value === undefined) {\n const requiredForThisRun = field.required && (purpose === 'evaluation' || field.role === 'input');\n if (requiredForThisRun) {\n throw new Error(`Case \"${testCase.name}\" is missing required field \"${field.name}\".`);\n }\n continue;\n }\n assertPortableJson(value, `case.${field.id}`);\n if (field.role === 'expected') expected[field.id] = clonePortableJson(value);\n }\n for (const binding of suite.inputBindings) {\n const field = fields.get(binding.datasetFieldId)!;\n const value = testCase.values[field.id];\n if (value === undefined) {\n throw new Error(`Case \"${testCase.name}\" has no saved value for bound input field \"${field.name}\".`);\n }\n if (!isEvaluationValueCompatibleWithDataType(value, field.dataType)) {\n throw new Error(\n `Case \"${testCase.name}\" input \"${field.name}\" is not compatible with its declared ${field.dataType} type.`,\n );\n }\n inputs[binding.graphInputId] = clonePortableJson(value);\n }\n return { inputs, expected };\n}\n\n/**\n * Evaluators need the case identity and tags as well as its field values. Do\n * not pass the mutable dataset case object itself: this portable snapshot is\n * the stable evaluator-graph contract for a particular trial.\n */\nfunction createEvaluatorCaseInput(testCase: EvaluationDataset['cases'][number]): PortableJson {\n return {\n id: testCase.id,\n name: testCase.name,\n enabled: testCase.enabled !== false,\n ...(testCase.tags === undefined ? {} : { tags: [...testCase.tags] }),\n ...(testCase.note === undefined ? {} : { note: testCase.note }),\n values: clonePortableJson(testCase.values),\n };\n}\n\nfunction createEvaluatorGraphInputs(input: {\n evaluator: EvaluationGraphEvaluator;\n project: Project;\n testCase: EvaluationDataset['cases'][number];\n targetInputs: Record<string, PortableJson>;\n expected: Record<string, PortableJson>;\n targetOutputs: Record<string, PortableJson>;\n run: PortableJson;\n}): Record<string, PortableJson> {\n const { evaluator, project, testCase, targetInputs, expected, targetOutputs, run } = input;\n const contextValues = {\n case: createEvaluatorCaseInput(testCase),\n inputs: clonePortableJson(targetInputs),\n expected: clonePortableJson(expected),\n outputs: clonePortableJson(targetOutputs),\n run: clonePortableJson(run),\n } satisfies Record<(typeof LEGACY_EVALUATOR_INPUT_IDS)[number], PortableJson>;\n const evaluatorGraphInputs =\n project.graphs[evaluator.graphId]?.nodes.filter((node): node is GraphInputNode => node.type === 'graphInput') ?? [];\n const evaluatorGraphInputIds = evaluatorGraphInputs.map((node) => node.data.id);\n if (usesLegacyEvaluatorInputEnvelope(evaluator, evaluatorGraphInputIds)) return contextValues;\n const evaluatorInputsById = new Map(evaluatorGraphInputs.map((node) => [node.data.id, node]));\n\n const evaluatorInputs: Record<string, PortableJson> = {};\n for (const binding of evaluator.inputBindings ?? []) {\n if (binding.source.kind === 'dataset-field') {\n const value = testCase.values[binding.source.fieldId];\n if (value === undefined) {\n throw new Error(\n `Case \"${testCase.name}\" has no value for evaluator input \"${binding.graphInputId}\" from dataset field \"${binding.source.fieldId}\".`,\n );\n }\n evaluatorInputs[binding.graphInputId] = clonePortableJson(value);\n } else if (binding.source.kind === 'target-output') {\n if (!Object.hasOwn(targetOutputs, binding.source.outputId)) {\n throw new Error(\n `Target graph did not produce output \"${binding.source.outputId}\" required by evaluator input \"${binding.graphInputId}\".`,\n );\n }\n const targetOutputValue = targetOutputs[binding.source.outputId]!;\n const evaluatorInput = evaluatorInputsById.get(binding.graphInputId);\n if (evaluatorInput && !isEvaluationValueCompatibleWithDataType(targetOutputValue, evaluatorInput.data.dataType)) {\n throw new Error(\n `Target output \"${binding.source.outputId}\" is not compatible with evaluator input \"${binding.graphInputId}\" (${evaluatorInput.data.dataType}).`,\n );\n }\n evaluatorInputs[binding.graphInputId] = clonePortableJson(targetOutputValue);\n } else if (binding.source.kind === 'context') {\n evaluatorInputs[binding.graphInputId] = clonePortableJson(contextValues[binding.source.context]);\n } else {\n throw new Error(`Evaluator input \"${binding.graphInputId}\" uses an unsupported source.`);\n }\n }\n return evaluatorInputs;\n}\n\nfunction hashStableText(value: string): number {\n let hash = 0x811c9dc5;\n for (let index = 0; index < value.length; index += 1) {\n hash ^= value.charCodeAt(index);\n hash = Math.imul(hash, 0x01000193);\n }\n return hash >>> 0;\n}\n\nfunction deriveSeed(seed: number | undefined, caseId: string, trialIndex: number): number | undefined {\n if (seed == null) return undefined;\n let value = seed >>> 0;\n value = Math.imul(value ^ hashStableText(caseId), 0x45d9f3b);\n value = Math.imul(value ^ (trialIndex + 1), 0x45d9f3b);\n return (value ^ (value >>> 16)) >>> 0;\n}\n\nfunction normalizeEvaluatorResult(value: PortableJson, evaluationMode: EvaluationSuiteMode): EvaluationObservation {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error('Evaluator graph output \"result\" must be an object.');\n }\n if (evaluationMode === 'pass-fail' && typeof value.passed !== 'boolean') {\n throw new Error('Evaluator graph output \"result.passed\" must be a boolean.');\n }\n const score = value.score;\n if (\n (evaluationMode === 'scoring' || score !== undefined) &&\n (typeof score !== 'number' || !Number.isFinite(score) || score < 0 || score > 100)\n ) {\n throw new Error(\n 'Evaluator graph output \"result.score\" must be a number from 0 to 100 (for example, return 85 for 85/100).',\n );\n }\n if (value.message !== undefined && typeof value.message !== 'string') {\n throw new Error('Evaluator graph output \"result.message\" must be a string.');\n }\n if (\n value.metrics !== undefined &&\n (typeof value.metrics !== 'object' || value.metrics === null || Array.isArray(value.metrics))\n ) {\n throw new Error('Evaluator graph output \"result.metrics\" must be an object.');\n }\n const metrics = value.metrics as Record<string, PortableJson> | undefined;\n if (metrics && Object.values(metrics).some((entry) => typeof entry !== 'number' || !Number.isFinite(entry))) {\n throw new Error('Evaluator graph output \"result.metrics\" values must be finite numbers.');\n }\n if (value.evidence !== undefined) assertPortableJson(value.evidence, 'evaluator result.evidence');\n return {\n id: '',\n kind: 'graph',\n name: '',\n required: true,\n status: evaluationMode === 'scoring' ? 'scored' : value.passed ? 'passed' : 'failed',\n // Evaluator authors use the same 100-point scale shown by the UI. Runs\n // retain normalized values so historical aggregation and thresholds stay\n // backward compatible with existing evaluation records.\n ...(typeof score === 'number' ? { score: score / 100 } : {}),\n ...(typeof value.message === 'string' ? { message: value.message } : {}),\n ...(value.evidence !== undefined ? { evidence: clonePortableJson(value.evidence) } : {}),\n ...(metrics ? { metrics: clonePortableJson(metrics) as Record<string, number> } : {}),\n };\n}\n\nasync function runWithTimeout<T>(\n run: (signal: AbortSignal) => Promise<T>,\n timeoutMs: number | undefined,\n outer?: AbortSignal,\n): Promise<T> {\n throwIfAborted(outer);\n const controller = new AbortController();\n let rejectCanceled: ((reason: unknown) => void) | undefined;\n const canceled = new Promise<never>((_, reject) => {\n rejectCanceled = reject;\n });\n const abort = () => {\n const error = outer?.reason ?? new DOMException('Evaluation canceled.', 'AbortError');\n controller.abort(error);\n rejectCanceled?.(error);\n };\n outer?.addEventListener('abort', abort, { once: true });\n // `throwIfAborted` above covers the common case. This second check closes\n // the narrow race where the caller aborts while this timeout wrapper is\n // installing its listener, before the adapter has been started.\n if (outer?.aborted) {\n outer.removeEventListener('abort', abort);\n throw outer.reason ?? new DOMException('Evaluation canceled.', 'AbortError');\n }\n let timeout: ReturnType<typeof setTimeout> | undefined;\n let timeoutPromise: Promise<never> | undefined;\n if (timeoutMs != null && timeoutMs > 0) {\n timeoutPromise = new Promise<never>((_, reject) => {\n timeout = setTimeout(() => {\n const error = new DOMException('Evaluation trial timed out.', 'TimeoutError');\n controller.abort(error);\n reject(error);\n }, timeoutMs);\n });\n }\n const execution = run(controller.signal);\n try {\n return await Promise.race([execution, canceled, ...(timeoutPromise ? [timeoutPromise] : [])]);\n } finally {\n if (timeout) clearTimeout(timeout);\n outer?.removeEventListener('abort', abort);\n }\n}\n\nexport type RunEvaluationTrialOptions = {\n project: Project;\n suite: EvaluationSuite;\n dataset: EvaluationDataset;\n purpose: EvaluationRunPurpose;\n testCase: EvaluationDataset['cases'][number];\n caseIndex: number;\n trialIndex: number;\n runId: string;\n runGraph: EvaluationGraphRunner;\n signal?: AbortSignal;\n /** Stable server-owned job id. Local callers may omit it. */\n trialId?: string;\n};\n\nexport async function runEvaluationTrial(input: RunEvaluationTrialOptions): Promise<EvaluationTrial> {\n const { project, suite, dataset, purpose, testCase, caseIndex, trialIndex, runId, runGraph, signal, trialId } = input;\n const evaluationMode = getEvaluationSuiteMode(suite);\n const { inputs, expected } = resolveCaseInputs(suite, dataset, testCase, purpose);\n const seed = deriveSeed(suite.configuration?.seed, testCase.id, trialIndex);\n if (seed !== undefined && suite.configuration?.seedGraphInputId) inputs[suite.configuration.seedGraphInputId] = seed;\n const metadata = {\n evaluationRunId: runId,\n suiteId: suite.id,\n caseId: testCase.id,\n trialIndex,\n phase: 'target' as const,\n };\n let targetMetrics = createEmptyMetrics();\n let evaluatorMetrics = createEmptyMetrics();\n let outputs: Record<string, PortableJson> = {};\n let targetError: string | undefined;\n let recording: EvaluationTrial['recording'];\n let targetProviderAttempts: EvaluationTrial['targetProviderAttempts'];\n const targetStartedAt = Date.now();\n try {\n throwIfAborted(signal);\n const target = await runWithTimeout(\n (attemptSignal) => runGraph({ project, graphId: suite.targetGraphId, inputs, signal: attemptSignal, metadata }),\n suite.configuration?.timeoutMs,\n signal,\n );\n targetMetrics = cloneExecutionMetrics(target.metrics, 'target metrics');\n assertPortableJson(target.outputs, 'target outputs');\n outputs = clonePortableJson(target.outputs);\n recording = target.recording === undefined ? undefined : structuredClone(target.recording);\n targetProviderAttempts = cloneOptionalPortableJson(target.providerAttempts, 'target provider attempts');\n } catch (error) {\n if (error instanceof EvaluationGraphExecutionError) {\n const errorMetrics = tryCloneExecutionMetrics(error.metrics, 'target error metrics');\n targetMetrics = errorMetrics ?? { ...targetMetrics, hasUnknownCost: true };\n recording = error.recording === undefined ? undefined : structuredClone(error.recording);\n targetProviderAttempts = tryCloneOptionalPortableJson(error.providerAttempts, 'target error provider attempts');\n } else {\n // A plain adapter failure does not prove that no priced provider work\n // happened before the error. Do not report authoritative zero cost.\n targetMetrics = { ...targetMetrics, hasUnknownCost: true };\n }\n targetError = toErrorMessage(error);\n targetMetrics = { ...targetMetrics, durationMs: Math.max(targetMetrics.durationMs, Date.now() - targetStartedAt) };\n if (isAbort(error) || signal?.aborted) {\n const executionStatus = 'canceled' as const;\n const qualityStatus = 'not-evaluated' as const;\n return {\n id: trialId ?? makeId('trial'),\n caseId: testCase.id,\n caseName: testCase.name,\n caseIndex,\n trialIndex,\n executionStatus,\n qualityStatus,\n qualityReason: { code: 'canceled', message: 'The evaluation trial was canceled.' },\n inputs,\n expected,\n outputs,\n observations: [],\n targetMetrics,\n evaluatorMetrics,\n totalMetrics: { ...mergeMetrics(targetMetrics, evaluatorMetrics), hasUnknownCost: true },\n error: targetError,\n ...(seed === undefined ? {} : { seed }),\n ...(recording === undefined ? {} : { recording }),\n ...(targetProviderAttempts === undefined ? {} : { targetProviderAttempts }),\n };\n }\n }\n\n const observations: EvaluationObservation[] = [];\n if (purpose === 'evaluation' && targetError) {\n observations.push({\n id: 'target-error',\n kind: 'assertion',\n name: 'Target graph',\n required: true,\n status: 'error',\n message: targetError,\n });\n } else if (purpose === 'evaluation' && evaluationMode === 'pass-fail') {\n for (const assertion of suite.assertions) {\n try {\n observations.push(evaluateAssertion(assertion, outputs, testCase));\n } catch (error) {\n observations.push({\n id: assertion.id,\n kind: 'assertion',\n name: assertion.name,\n required: assertion.required !== false,\n status: 'error',\n message: toErrorMessage(error),\n });\n }\n }\n }\n\n for (const evaluator of purpose === 'evaluation' ? suite.evaluators : []) {\n if (targetError && (evaluationMode === 'scoring' || !evaluator.runOnTargetError)) {\n observations.push({\n id: evaluator.id,\n kind: 'graph',\n name: evaluator.name,\n required: evaluator.required !== false,\n status: 'skipped',\n message: 'Skipped because the target graph failed.',\n });\n continue;\n }\n const start = Date.now();\n let completedAttemptMetrics: EvaluationExecutionMetrics | undefined;\n let completedAttemptRecording: EvaluationRecordingReference | undefined;\n let completedAttemptProviderAttempts: PortableJson | undefined;\n try {\n const result = await runWithTimeout(\n (attemptSignal) =>\n runGraph({\n project,\n graphId: evaluator.graphId,\n inputs: createEvaluatorGraphInputs({\n evaluator,\n project,\n testCase,\n targetInputs: inputs,\n expected,\n targetOutputs: outputs,\n run: { targetError: targetError ?? null, caseIndex, trialIndex, seed: seed ?? null },\n }),\n signal: attemptSignal,\n metadata: { ...metadata, phase: 'evaluator' },\n }),\n suite.configuration?.timeoutMs,\n signal,\n );\n completedAttemptMetrics = cloneExecutionMetrics(result.metrics, `evaluator ${evaluator.name} metrics`);\n completedAttemptRecording = result.recording === undefined ? undefined : structuredClone(result.recording);\n completedAttemptProviderAttempts = cloneOptionalPortableJson(\n result.providerAttempts,\n `evaluator ${evaluator.name} provider attempts`,\n );\n evaluatorMetrics = mergeMetrics(evaluatorMetrics, completedAttemptMetrics);\n assertPortableJson(result.outputs, `evaluator ${evaluator.name} outputs`);\n const observation = normalizeEvaluatorResult(result.outputs.result ?? null, evaluationMode);\n observations.push({\n ...observation,\n id: evaluator.id,\n name: evaluator.name,\n required: evaluator.required !== false,\n scoreWeight: evaluator.scoreWeight ?? 1,\n durationMs: completedAttemptMetrics.durationMs || Date.now() - start,\n ...(completedAttemptMetrics.costUsd === undefined ? {} : { costUsd: completedAttemptMetrics.costUsd }),\n ...(completedAttemptProviderAttempts === undefined\n ? {}\n : { providerAttempts: completedAttemptProviderAttempts }),\n ...(completedAttemptRecording === undefined ? {} : { recording: completedAttemptRecording }),\n });\n } catch (error) {\n const executionError = error instanceof EvaluationGraphExecutionError ? error : undefined;\n const executionErrorMetrics = tryCloneExecutionMetrics(\n executionError?.metrics,\n `evaluator ${evaluator.name} error metrics`,\n );\n const failureMetrics = executionErrorMetrics ?? completedAttemptMetrics;\n const failureProviderAttempts =\n tryCloneOptionalPortableJson(\n executionError?.providerAttempts,\n `evaluator ${evaluator.name} error provider attempts`,\n ) ?? completedAttemptProviderAttempts;\n const failureRecording =\n executionError?.recording === undefined ? completedAttemptRecording : structuredClone(executionError.recording);\n if (executionErrorMetrics) {\n // A failed judge is still a physical graph execution. Its latency,\n // tokens, and cost must remain part of the run rather than vanishing\n // just because the evaluator did not return a valid result object.\n evaluatorMetrics = mergeMetrics(evaluatorMetrics, executionErrorMetrics);\n } else if (!completedAttemptMetrics) {\n // Generic adapter failures and runner timeouts do not carry an\n // EvaluationGraphExecutionError payload. Their elapsed time is still\n // physical evaluator work and must remain visible in run metrics.\n evaluatorMetrics = mergeMetrics(evaluatorMetrics, {\n durationMs: Date.now() - start,\n hasUnknownCost: true,\n });\n }\n if (isAbort(error) || signal?.aborted) {\n const executionStatus = 'canceled' as const;\n const qualityStatus = 'not-evaluated' as const;\n return {\n id: trialId ?? makeId('trial'),\n caseId: testCase.id,\n caseName: testCase.name,\n caseIndex,\n trialIndex,\n executionStatus,\n qualityStatus,\n qualityReason: { code: 'canceled', message: 'The evaluation trial was canceled.' },\n inputs,\n expected,\n outputs,\n observations,\n targetMetrics,\n evaluatorMetrics,\n totalMetrics: { ...mergeMetrics(targetMetrics, evaluatorMetrics), hasUnknownCost: true },\n error: toErrorMessage(error),\n ...(seed === undefined ? {} : { seed }),\n ...(recording === undefined ? {} : { recording }),\n ...(targetProviderAttempts === undefined ? {} : { targetProviderAttempts }),\n };\n }\n observations.push({\n id: evaluator.id,\n kind: 'graph',\n name: evaluator.name,\n required: evaluator.required !== false,\n status: 'error',\n message: toErrorMessage(error),\n durationMs: failureMetrics?.durationMs ?? Date.now() - start,\n ...(failureMetrics?.costUsd === undefined ? {} : { costUsd: failureMetrics.costUsd }),\n ...(failureProviderAttempts === undefined ? {} : { providerAttempts: failureProviderAttempts }),\n ...(failureRecording === undefined ? {} : { recording: failureRecording }),\n });\n }\n }\n\n const required = observations.filter((entry) => entry.required);\n const executionStatus: EvaluationTrialExecutionStatus = targetError === undefined ? 'completed' : 'error';\n let qualityStatus: EvaluationQualityStatus;\n let qualityReason: EvaluationQualityReason;\n if (purpose === 'execution-benchmark') {\n qualityStatus = 'not-evaluated';\n qualityReason = {\n code: 'benchmark',\n message: 'This trial measured execution without evaluating output quality.',\n };\n } else if (evaluationMode === 'scoring') {\n const scoringObservations = observations.filter((entry) => entry.kind === 'graph');\n const hasCompleteScore =\n targetError === undefined &&\n scoringObservations.length === suite.evaluators.length &&\n scoringObservations.every((entry) => entry.status === 'scored' && entry.score !== undefined);\n if (hasCompleteScore) {\n qualityStatus = 'scored';\n qualityReason = { code: 'scores-complete', message: 'All evaluator graphs returned a score for this trial.' };\n } else {\n qualityStatus = 'unable-to-evaluate';\n qualityReason = {\n code: 'scores-incomplete',\n message:\n targetError === undefined\n ? 'One or more evaluator graphs did not return a usable score for this trial.'\n : 'The target graph failed, so this trial could not contribute a score.',\n };\n }\n } else if (targetError !== undefined) {\n qualityStatus = 'failed';\n qualityReason = {\n code: 'target-error',\n message: 'The target graph failed before it could produce a valid result.',\n };\n } else if (required.some((entry) => entry.status === 'failed')) {\n qualityStatus = 'failed';\n qualityReason = { code: 'checks-failed', message: 'One or more required quality checks failed.' };\n } else if (required.some((entry) => entry.status === 'error')) {\n qualityStatus = 'unable-to-evaluate';\n qualityReason = {\n code: 'required-check-error',\n message: 'A required quality check could not be evaluated.',\n };\n } else if (required.some((entry) => entry.status === 'passed')) {\n qualityStatus = 'passed';\n qualityReason = { code: 'checks-passed', message: 'All required per-trial quality checks passed.' };\n } else {\n qualityStatus = 'not-evaluated';\n qualityReason = {\n code: 'no-trial-quality-checks',\n message: 'No required per-trial quality check evaluated this result.',\n };\n }\n const totalMetrics = mergeMetrics(targetMetrics, evaluatorMetrics);\n return {\n id: trialId ?? makeId('trial'),\n caseId: testCase.id,\n caseName: testCase.name,\n caseIndex,\n trialIndex,\n executionStatus,\n qualityStatus,\n qualityReason,\n inputs,\n expected,\n outputs,\n observations,\n targetMetrics,\n evaluatorMetrics,\n totalMetrics,\n ...(targetError === undefined ? {} : { error: targetError }),\n ...(seed === undefined ? {} : { seed }),\n ...(recording === undefined ? {} : { recording }),\n ...(targetProviderAttempts === undefined ? {} : { targetProviderAttempts }),\n };\n}\n\nfunction percentile(values: number[], percentage: number): number {\n if (values.length === 0) return 0;\n const ordered = values.slice().sort((left, right) => left - right);\n return ordered[Math.min(ordered.length - 1, Math.ceil((percentage / 100) * ordered.length) - 1)]!;\n}\n\nfunction median(values: number[]): number {\n if (values.length === 0) return 0;\n const ordered = values.slice().sort((left, right) => left - right);\n const upperIndex = Math.floor(ordered.length / 2);\n if (ordered.length % 2 !== 0) return ordered[upperIndex]!;\n return (ordered[upperIndex - 1]! + ordered[upperIndex]!) / 2;\n}\n\nfunction meanObservationScore(observations: readonly EvaluationObservation[]): number | undefined {\n let weightedScore = 0;\n let totalWeight = 0;\n for (const observation of observations) {\n if (observation.score === undefined) continue;\n // Assertions do not currently produce scores. The fallback preserves\n // compatibility with old recordings and evaluators that predate weights.\n const weight = observation.scoreWeight ?? 1;\n weightedScore += observation.score * weight;\n totalWeight += weight;\n }\n return totalWeight === 0 ? undefined : weightedScore / totalWeight;\n}\n\nfunction meanObservationMetrics(observations: readonly EvaluationObservation[]): Record<string, number> {\n const totals: Record<string, number> = {};\n const counts: Record<string, number> = {};\n for (const observation of observations) {\n for (const [name, value] of Object.entries(observation.metrics ?? {})) {\n totals[name] = (totals[name] ?? 0) + value;\n counts[name] = (counts[name] ?? 0) + 1;\n }\n }\n return Object.fromEntries(Object.entries(totals).map(([name, total]) => [name, total / counts[name]!]));\n}\n\nfunction aggregate(\n trials: EvaluationTrial[],\n evaluationMode: EvaluationSuiteMode = 'pass-fail',\n): { aggregate: EvaluationAggregate; cases: EvaluationCaseAggregate[] } {\n const incurred = trials;\n const settled = trials.filter((trial) => trial.executionStatus !== 'canceled');\n const completed = trials.filter((trial) => trial.executionStatus === 'completed');\n const evaluated = completed.filter((trial) => trial.qualityStatus === 'passed' || trial.qualityStatus === 'failed');\n const passed = evaluated.filter((trial) => trial.qualityStatus === 'passed');\n const failed = evaluated.filter((trial) => trial.qualityStatus === 'failed');\n const notEvaluated = completed.filter((trial) => trial.qualityStatus === 'not-evaluated');\n const unable = completed.filter((trial) => trial.qualityStatus === 'unable-to-evaluate');\n const errors = trials.filter((trial) => trial.executionStatus === 'error');\n const canceled = trials.filter((trial) => trial.executionStatus === 'canceled');\n // Canceled work can have partial observations and accounting. It remains\n // inspectable in the run, but must not distort completed-run quality or cost\n // thresholds.\n const settledObservations = settled.flatMap((trial) => trial.observations);\n const meanScore = meanObservationScore(settledObservations);\n const accountingComplete = !incurred.some((trial) => trial.totalMetrics.hasUnknownCost);\n const totalCostUsd = accountingComplete\n ? incurred.reduce((sum, trial) => sum + (trial.totalMetrics.costUsd ?? 0), 0)\n : undefined;\n // Evaluator metrics are per-observation measurements. Aggregating them as\n // a mean keeps a `0..1` quality score meaningful as trial count changes;\n // an evaluator that needs a total can return it as an explicit metric.\n const meanMetrics = meanObservationMetrics(settledObservations);\n const byCase = new Map<string, EvaluationTrial[]>();\n for (const trial of trials) byCase.set(trial.caseId, [...(byCase.get(trial.caseId) ?? []), trial]);\n const cases = Array.from(byCase.values()).map((caseTrials): EvaluationCaseAggregate => {\n const caseSettled = caseTrials.filter((trial) => trial.executionStatus !== 'canceled');\n const caseCompleted = caseSettled.filter((trial) => trial.executionStatus === 'completed');\n const caseEvaluated = caseCompleted.filter(\n (trial) => trial.qualityStatus === 'passed' || trial.qualityStatus === 'failed',\n );\n const casePassed = caseEvaluated.filter((trial) => trial.qualityStatus === 'passed');\n const caseFailed = caseEvaluated.filter((trial) => trial.qualityStatus === 'failed');\n const caseScored = caseCompleted.filter((trial) => trial.qualityStatus === 'scored');\n const caseObservations = caseSettled.flatMap((trial) => trial.observations);\n // A scoring trial has already proved every configured evaluator produced\n // a score. Average evaluators within a trial first, then average those\n // trials, so each case gets equal weight regardless of its evaluator set.\n const caseTrialScores = caseScored\n .map((trial) => meanObservationScore(trial.observations))\n .filter((score): score is number => score !== undefined);\n const caseMeanScore =\n evaluationMode === 'scoring'\n ? caseTrialScores.length === 0\n ? undefined\n : caseTrialScores.reduce((sum, score) => sum + score, 0) / caseTrialScores.length\n : meanObservationScore(caseObservations);\n return {\n caseId: caseTrials[0]!.caseId,\n caseName: caseTrials[0]!.caseName,\n ...(caseEvaluated.length === 0 ? {} : { passRate: casePassed.length / caseEvaluated.length }),\n evaluatedTrialCount: caseEvaluated.length,\n passedTrialCount: casePassed.length,\n failedTrialCount: caseFailed.length,\n notEvaluatedTrialCount: caseCompleted.filter((trial) => trial.qualityStatus === 'not-evaluated').length,\n unableToEvaluateTrialCount: caseCompleted.filter((trial) => trial.qualityStatus === 'unable-to-evaluate').length,\n erroredTrialCount: caseTrials.filter((trial) => trial.executionStatus === 'error').length,\n canceledTrialCount: caseTrials.filter((trial) => trial.executionStatus === 'canceled').length,\n ...(evaluationMode === 'scoring'\n ? {\n scoredTrialCount: caseScored.length,\n missingScoreTrialCount: caseTrials.length - caseScored.length,\n }\n : {}),\n ...(caseMeanScore === undefined ? {} : { meanScore: caseMeanScore }),\n metrics: meanObservationMetrics(caseObservations),\n };\n });\n const scoredTrialCount = cases.reduce((sum, testCase) => sum + (testCase.scoredTrialCount ?? 0), 0);\n const scoringCaseMeans = cases\n .map((testCase) => testCase.meanScore)\n .filter((score): score is number => score !== undefined);\n const scoringMeanScore =\n scoringCaseMeans.length === 0\n ? undefined\n : scoringCaseMeans.reduce((sum, score) => sum + score, 0) / scoringCaseMeans.length;\n const incurredLatencies = incurred.map((trial) => trial.totalMetrics.durationMs);\n const aggregateValue: EvaluationAggregate = {\n trialCount: trials.length,\n evaluatedTrialCount: evaluated.length,\n notEvaluatedTrialCount: notEvaluated.length,\n unableToEvaluateTrialCount: unable.length,\n passedTrialCount: passed.length,\n failedTrialCount: failed.length,\n erroredTrialCount: errors.length,\n canceledTrialCount: canceled.length,\n passRate: evaluated.length === 0 ? 0 : passed.length / evaluated.length,\n ...(evaluationMode === 'scoring'\n ? {\n scoredTrialCount,\n missingScoreTrialCount: trials.length - scoredTrialCount,\n ...(scoringMeanScore === undefined ? {} : { meanScore: scoringMeanScore }),\n ...(scoringCaseMeans.length === 0\n ? {}\n : {\n medianScore: median(scoringCaseMeans),\n p95Score: percentile(scoringCaseMeans, 95),\n }),\n }\n : meanScore === undefined\n ? {}\n : { meanScore }),\n averageLatencyMs:\n incurred.length === 0 ? 0 : incurredLatencies.reduce((sum, durationMs) => sum + durationMs, 0) / incurred.length,\n medianLatencyMs: median(incurredLatencies),\n p95LatencyMs: percentile(incurredLatencies, 95),\n ...(incurred.length === 0 || totalCostUsd === undefined\n ? {}\n : { totalCostUsd, averageCostUsd: totalCostUsd / incurred.length }),\n targetErrorRate: settled.length === 0 ? 0 : errors.length / settled.length,\n evaluatorErrorRate:\n settled.length === 0\n ? 0\n : settled.filter((trial) =>\n trial.observations.some((observation) => observation.kind === 'graph' && observation.status === 'error'),\n ).length / settled.length,\n toolFailureRate:\n settled.reduce((sum, trial) => sum + (trial.totalMetrics.toolCallCount ?? 0), 0) === 0\n ? 0\n : settled.reduce((sum, trial) => sum + (trial.totalMetrics.toolFailureCount ?? 0), 0) /\n settled.reduce((sum, trial) => sum + (trial.totalMetrics.toolCallCount ?? 0), 0),\n metrics: meanMetrics,\n };\n return {\n aggregate: aggregateValue,\n cases,\n };\n}\n\nfunction thresholdValue(aggregateValue: EvaluationAggregate, metric: string): number | undefined {\n switch (metric) {\n case 'pass-rate':\n return aggregateValue.evaluatedTrialCount === 0 ? undefined : aggregateValue.passRate;\n case 'mean-score':\n return aggregateValue.meanScore;\n case 'target-error-rate':\n return aggregateValue.targetErrorRate;\n case 'evaluator-error-rate':\n return aggregateValue.evaluatorErrorRate;\n case 'tool-failure-rate':\n return aggregateValue.toolFailureRate;\n case 'average-cost':\n return aggregateValue.averageCostUsd;\n case 'total-cost':\n return aggregateValue.totalCostUsd;\n case 'average-latency-ms':\n return aggregateValue.averageLatencyMs;\n case 'p95-latency-ms':\n return aggregateValue.p95LatencyMs;\n default:\n return metric.startsWith('custom:') ? aggregateValue.metrics[metric.slice('custom:'.length)] : undefined;\n }\n}\n\nfunction isHigherBetterMetric(metric: string): boolean {\n return metric === 'pass-rate' || metric === 'mean-score' || metric.startsWith('custom:');\n}\n\nfunction baselineCompatible(current: EvaluationRunProvenance, baseline: EvaluationBaselineSnapshot): boolean {\n return (\n current.executionMode === baseline.provenance.executionMode &&\n current.suiteFingerprint === baseline.provenance.suiteFingerprint &&\n current.datasetFingerprint === baseline.provenance.datasetFingerprint &&\n current.targetFingerprint === baseline.provenance.targetFingerprint &&\n canonicalStringify(current.evaluatorFingerprints) === canonicalStringify(baseline.provenance.evaluatorFingerprints)\n );\n}\n\n/**\n * Project-level values which can change a graph execution even though no node\n * or connection changed. Deliberately omit cosmetic metadata (title,\n * description, path, main-graph selection) and UI graphs: changing those must\n * not invalidate an otherwise comparable baseline.\n */\nfunction executionNodeConfiguration(node: ChartNode): Record<string, unknown> {\n return {\n id: node.id,\n type: node.type,\n title: node.title,\n data: node.data,\n variants: node.variants,\n isSplitRun: node.isSplitRun,\n isSplitSequential: node.isSplitSequential,\n splitRunMax: node.splitRunMax,\n splitRunConcurrency: node.splitRunConcurrency,\n disabled: node.disabled,\n isConditional: node.isConditional,\n };\n}\n\nfunction executionConnectionConfiguration(connection: NodeConnection): Record<string, unknown> {\n return {\n outputNodeId: connection.outputNodeId,\n inputNodeId: connection.inputNodeId,\n outputId: connection.outputId,\n inputId: connection.inputId,\n };\n}\n\nfunction executionGraphConfiguration(graph: NodeGraph): Record<string, unknown> {\n return {\n metadata: {\n id: graph.metadata?.id,\n name: graph.metadata?.name,\n attachedData: graph.metadata?.attachedData,\n },\n nodes: graph.nodes.map(executionNodeConfiguration),\n connections: graph.connections.map(executionConnectionConfiguration),\n };\n}\n\nfunction executionProjectGraphs(project: Project): Record<string, unknown> {\n return Object.fromEntries(\n Object.entries(project.graphs).map(([graphId, graph]) => [graphId, executionGraphConfiguration(graph)]),\n );\n}\n\nfunction executionProjectConfiguration(project: Project): Record<string, unknown> {\n return {\n ...(project.plugins === undefined ? {} : { plugins: project.plugins }),\n ...(project.nodePrefabs === undefined\n ? {}\n : {\n nodePrefabs: Object.fromEntries(\n Object.entries(project.nodePrefabs).map(([prefabId, prefab]) => [\n prefabId,\n { id: prefab.id, sourceNode: executionNodeConfiguration(prefab.sourceNode) },\n ]),\n ),\n }),\n ...(project.data === undefined ? {} : { data: project.data }),\n ...(project.references === undefined ? {} : { references: project.references }),\n ...(project.metadata.mcpServer === undefined ? {} : { mcpServer: project.metadata.mcpServer }),\n ...(project.metadata.knowledgeStores === undefined ? {} : { knowledgeStores: project.metadata.knowledgeStores }),\n };\n}\n\n/**\n * Rivet's live project model intentionally keeps optional fields as own\n * properties whose value is `undefined` (for example `node.description`).\n * That is valid executable state, but it is not PortableJson. Evaluation\n * datasets and graph outputs must retain the stricter contract; provenance\n * fingerprints instead mirror ordinary JSON serialization for this one\n * runtime-only boundary so those optional fields neither block a run nor\n * create a distinct baseline identity.\n */\nfunction canonicalizeExecutionFingerprintValue(value: unknown, path = '$', stack = new Set<object>()): PortableJson {\n if (value === null || typeof value === 'string' || typeof value === 'boolean') return value;\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) throw new Error(`${path} must not contain a non-finite number.`);\n return value;\n }\n if (value === undefined) return null;\n if (typeof value !== 'object') throw new Error(`${path} must be JSON-compatible to fingerprint an evaluation.`);\n if (stack.has(value)) throw new Error(`${path} must not contain a cycle.`);\n\n if (Array.isArray(value)) {\n stack.add(value);\n const normalized = Array.from(value, (entry, index) =>\n canonicalizeExecutionFingerprintValue(entry, `${path}[${index}]`, stack),\n );\n stack.delete(value);\n return normalized;\n }\n\n if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) {\n throw new Error(`${path} must be a plain object to fingerprint an evaluation.`);\n }\n\n stack.add(value);\n const normalized = Object.fromEntries(\n Object.entries(value).flatMap(([key, entry]) =>\n entry === undefined ? [] : [[key, canonicalizeExecutionFingerprintValue(entry, `${path}.${key}`, stack)]],\n ),\n );\n stack.delete(value);\n return normalized;\n}\n\nfunction fingerprintExecutionProject(value: unknown): string {\n return fingerprint(canonicalizeExecutionFingerprintValue(value));\n}\n\n/**\n * A baseline must follow every graph that a static node configuration can\n * invoke, not only Subgraph and Loop nodes. Dynamic Call Graph references\n * deliberately remain part of the owning graph fingerprint, because their\n * eventual target cannot be known before a trial runs.\n */\nfunction fingerprintGraphDependency(project: Project, graphId: GraphId): string {\n const visited = new Set<GraphId>();\n const graphEntries = Object.entries(project.graphs) as Array<[GraphId, (typeof project.graphs)[GraphId]]>;\n const asKnownGraphId = (value: unknown): GraphId | undefined => {\n return typeof value === 'string' && project.graphs[value as GraphId] ? (value as GraphId) : undefined;\n };\n const getStaticChildren = (graph: (typeof project.graphs)[GraphId]): GraphId[] => {\n const children = new Set<GraphId>();\n const autoDelegatedToolNames: string[] = [];\n const add = (value: unknown) => {\n const id = asKnownGraphId(value);\n if (id) children.add(id);\n };\n\n for (const node of graph.nodes) {\n const data = node.data as {\n autoDelegate?: unknown;\n graphId?: unknown;\n handlers?: unknown;\n name?: unknown;\n targetGraph?: unknown;\n unknownHandler?: unknown;\n useNameInput?: unknown;\n };\n switch (node.type) {\n case 'subGraph':\n case 'loopUntil':\n case 'cron':\n add(node.type === 'subGraph' ? data.graphId : data.targetGraph);\n break;\n case 'delegateFunctionCall': {\n add(data.unknownHandler);\n if (data.autoDelegate === true) {\n continue;\n }\n if (Array.isArray(data.handlers)) {\n for (const handler of data.handlers) {\n if (handler && typeof handler === 'object' && 'value' in handler) {\n add((handler as { value?: unknown }).value);\n }\n }\n }\n break;\n }\n case 'gptFunction':\n if (data.useNameInput !== true && typeof data.name === 'string' && data.name) {\n autoDelegatedToolNames.push(data.name);\n }\n break;\n }\n }\n\n if (\n graph.nodes.some(\n (node) =>\n node.type === 'delegateFunctionCall' && (node.data as { autoDelegate?: unknown }).autoDelegate === true,\n )\n ) {\n for (const toolName of autoDelegatedToolNames) {\n const resolved = findAutoDelegateGraphCandidate(\n graphEntries,\n toolName,\n ([, candidate]) => candidate.metadata?.name,\n );\n if (resolved) children.add(resolved[0]);\n }\n }\n return [...children];\n };\n const collect = (id: GraphId): unknown => {\n if (visited.has(id)) return { graphId: id, cycle: true };\n visited.add(id);\n const graph = project.graphs[id];\n if (!graph) return { graphId: id, missing: true };\n const dependencies = getStaticChildren(graph).map(collect);\n return { graph: executionGraphConfiguration(graph), dependencies };\n };\n return fingerprintExecutionProject({\n graphDependency: collect(graphId),\n projectExecutionConfiguration: executionProjectConfiguration(project),\n });\n}\n\nfunction unavailableThresholdResult(threshold: EvaluationThreshold, message: string): EvaluationThresholdResult {\n return {\n id: threshold.id,\n metric: threshold.metric,\n operator: threshold.operator,\n status: 'unavailable',\n expectedValue: threshold.value,\n message,\n };\n}\n\nexport function evaluateThresholdResults(\n aggregateValue: EvaluationAggregate,\n thresholds: EvaluationThreshold[] = [],\n baseline?: EvaluationBaselineSnapshot,\n): EvaluationThresholdResult[] {\n return thresholds.map((threshold) => {\n const actual = thresholdValue(aggregateValue, threshold.metric);\n if (actual === undefined || !Number.isFinite(actual)) {\n const message =\n threshold.metric === 'average-cost' || threshold.metric === 'total-cost'\n ? 'Some provider pricing was unavailable, so this cost requirement could not be evaluated.'\n : threshold.metric === 'pass-rate'\n ? 'No completed trial produced an evaluated pass or fail result.'\n : `The metric \"${threshold.metric}\" was unavailable.`;\n return unavailableThresholdResult(threshold, message);\n }\n\n if (threshold.operator === 'max-regression') {\n const isCostMetric = threshold.metric === 'average-cost' || threshold.metric === 'total-cost';\n if (\n isCostMetric &&\n (baseline?.accountingStatus === 'partial' || baseline?.provenance.accountingComplete === false)\n ) {\n return unavailableThresholdResult(\n threshold,\n 'The baseline has partial accounting because some provider pricing was unavailable, so this cost regression could not be evaluated.',\n );\n }\n const previous = baseline ? thresholdValue(baseline.aggregate, threshold.metric) : undefined;\n if (previous === undefined || !Number.isFinite(previous)) {\n return unavailableThresholdResult(\n threshold,\n baseline\n ? `The baseline does not contain a comparable \"${threshold.metric}\" metric.`\n : 'A compatible baseline is required for this regression requirement.',\n );\n }\n const delta = isHigherBetterMetric(threshold.metric) ? previous - actual : actual - previous;\n const zeroBaselineRegression = previous === 0 && delta > 0;\n const regression = previous === 0 ? 0 : delta / Math.abs(previous);\n const failed = zeroBaselineRegression || regression > threshold.value;\n return {\n id: threshold.id,\n metric: threshold.metric,\n operator: threshold.operator,\n status: failed ? 'failed' : 'passed',\n expectedValue: threshold.value,\n actualValue: actual,\n baselineValue: previous,\n ...(zeroBaselineRegression ? {} : { regression }),\n message: failed\n ? `Regression exceeded the allowed ${formatThresholdResultValue(\n threshold.metric,\n threshold.operator,\n threshold.value,\n )}.`\n : `Regression stayed within the allowed ${formatThresholdResultValue(\n threshold.metric,\n threshold.operator,\n threshold.value,\n )}.`,\n };\n }\n\n const passed = threshold.operator === 'at-least' ? actual >= threshold.value : actual <= threshold.value;\n return {\n id: threshold.id,\n metric: threshold.metric,\n operator: threshold.operator,\n status: passed ? 'passed' : 'failed',\n expectedValue: threshold.value,\n actualValue: actual,\n message: passed\n ? `Actual value ${formatThresholdResultValue(threshold.metric, threshold.operator, actual)} satisfied ${\n threshold.operator\n } ${formatThresholdResultValue(threshold.metric, threshold.operator, threshold.value)}.`\n : `Actual value ${formatThresholdResultValue(threshold.metric, threshold.operator, actual)} did not satisfy ${\n threshold.operator\n } ${formatThresholdResultValue(threshold.metric, threshold.operator, threshold.value)}.`,\n };\n });\n}\n\nfunction createProvenance(\n project: Project,\n suite: EvaluationSuite,\n dataset: EvaluationDataset,\n options: Pick<RunEvaluationSuiteOptions, 'purpose' | 'projectFingerprint' | 'executionMode'>,\n): EvaluationRunProvenance {\n const purpose = options.purpose ?? 'evaluation';\n const evaluationMode = getEvaluationSuiteMode(suite);\n const configuration = suite.configuration;\n const materialEvaluators = suite.evaluators.map((evaluator) => ({\n graphId: evaluator.graphId,\n inputBindings:\n evaluator.inputBindings?.slice().sort((left, right) => left.graphInputId.localeCompare(right.graphInputId)) ??\n null,\n // Normalize defaults so editing a control between its implicit and\n // explicit default does not invalidate a baseline.\n scoreWeight: evaluator.scoreWeight ?? 1,\n ...(evaluationMode === 'scoring'\n ? {}\n : { required: evaluator.required !== false, runOnTargetError: evaluator.runOnTargetError === true }),\n }));\n const materialSuiteDefinition = {\n purpose,\n evaluationMode,\n targetGraphId: suite.targetGraphId,\n datasetId: suite.datasetId,\n inputBindings: suite.inputBindings\n .slice()\n .sort((left, right) => left.graphInputId.localeCompare(right.graphInputId)),\n configuration: {\n trialCount: configuration?.trialCount ?? 1,\n concurrency: configuration?.concurrency ?? DEFAULT_CONCURRENCY,\n timeoutMs: configuration?.timeoutMs ?? null,\n seed: configuration?.seed ?? null,\n seedGraphInputId: configuration?.seedGraphInputId ?? null,\n },\n ...(purpose !== 'evaluation'\n ? {}\n : evaluationMode === 'scoring'\n ? { evaluators: materialEvaluators }\n : {\n assertions: suite.assertions,\n evaluators: materialEvaluators,\n thresholds: suite.thresholds ?? [],\n }),\n };\n return {\n projectFingerprint:\n options.projectFingerprint ??\n fingerprintExecutionProject({\n projectId: project.metadata.id,\n graphs: executionProjectGraphs(project),\n executionConfiguration: executionProjectConfiguration(project),\n }),\n // Names, descriptions, tags, and recording-retention choices do not\n // change an execution result. Quality-only definitions likewise cannot\n // stale an execution-benchmark comparison because they never ran. Pass/\n // fail assertions and thresholds are equally dormant in scoring mode.\n suiteFingerprint: fingerprint(materialSuiteDefinition),\n datasetFingerprint: fingerprintEvaluationDataset(dataset),\n targetFingerprint: fingerprintGraphDependency(project, suite.targetGraphId),\n evaluatorFingerprints:\n purpose === 'evaluation'\n ? Object.fromEntries(\n suite.evaluators.map((evaluator) => [evaluator.id, fingerprintGraphDependency(project, evaluator.graphId)]),\n )\n : {},\n executionMode: options.executionMode ?? 'unknown',\n accountingComplete: true,\n };\n}\n\nexport type EvaluationRunWorkItem = {\n testCase: EvaluationDataset['cases'][number];\n caseIndex: number;\n trialIndex: number;\n};\n\nexport type EvaluationRunPlan = {\n suite: EvaluationSuite;\n purpose: EvaluationRunPurpose;\n evaluationMode: EvaluationSuiteMode;\n work: readonly EvaluationRunWorkItem[];\n};\n\n/**\n * Validates an immutable Evaluation submission and expands its enabled cases\n * into deterministic work. Hosts can persist this plan before any graph side\n * effect, while local callers continue to use runEvaluationSuite.\n */\nexport function createEvaluationRunPlan(\n options: Pick<RunEvaluationSuiteOptions, 'project' | 'evaluationData' | 'dataset' | 'suiteId' | 'purpose'>,\n): EvaluationRunPlan {\n const suite = resolveSuite(options.evaluationData, options.suiteId);\n const purpose = options.purpose ?? 'evaluation';\n const evaluationMode = getEvaluationSuiteMode(suite);\n if (purpose === 'evaluation' && !hasAuthoritativeEvaluationCriteria(suite)) {\n throw new Error(\n evaluationMode === 'scoring'\n ? `Scoring evaluation suite \"${suite.name}\" has no evaluator graph. Add an evaluator that returns result.score or run an execution benchmark.`\n : `Evaluation suite \"${suite.name}\" has no required quality check or threshold. Add a quality criterion or run it as an execution benchmark.`,\n );\n }\n validateSuite(options.project, suite, options.dataset, purpose);\n const trialCount = Math.max(1, Math.floor(suite.configuration?.trialCount ?? 1));\n const work = options.dataset.cases\n .filter((testCase) => testCase.enabled !== false)\n .flatMap((testCase, caseIndex) =>\n Array.from({ length: trialCount }, (_, trialIndex) => ({ testCase, caseIndex, trialIndex })),\n );\n return { suite, purpose, evaluationMode, work };\n}\n\nexport type FinalizeEvaluationRunOptions = {\n run: EvaluationRun;\n trials: readonly EvaluationTrial[];\n suite: EvaluationSuite;\n evaluationData: EvaluationProjectData;\n baseline?: EvaluationBaselineSnapshot;\n canceled?: boolean;\n completedAt?: string;\n};\n\n/**\n * Applies the same aggregate, quality, accounting, and baseline semantics to\n * locally scheduled and durably hosted trials. Callers must provide every\n * settled trial in deterministic case/trial order; never synthesize retries.\n */\nexport function finalizeEvaluationRun(options: FinalizeEvaluationRunOptions): EvaluationRun {\n const run = options.run;\n const evaluationMode = getEvaluationSuiteMode(options.suite);\n run.trials = options.trials.slice();\n run.completedAt = options.completedAt ?? new Date().toISOString();\n const outcome = aggregate(run.trials, evaluationMode);\n run.aggregate = outcome.aggregate;\n run.provenance.accountingComplete = !run.trials.some((trial) => trial.totalMetrics.hasUnknownCost);\n run.accountingStatus = run.provenance.accountingComplete ? 'complete' : 'partial';\n if (run.accountingStatus === 'partial' && !run.warnings.includes('Some provider pricing was unavailable. Cost totals are unavailable, and cost requirements cannot be evaluated.')) {\n run.warnings.push('Some provider pricing was unavailable. Cost totals are unavailable, and cost requirements cannot be evaluated.');\n }\n if (options.canceled) {\n run.executionStatus = 'canceled';\n run.qualityStatus = 'not-evaluated';\n run.qualityReason = { code: 'canceled', message: 'The evaluation run was canceled.' };\n return run;\n }\n if (run.purpose === 'execution-benchmark') {\n run.executionStatus = 'completed';\n run.qualityStatus = 'not-evaluated';\n run.qualityReason = { code: 'benchmark', message: 'This run measured execution without evaluating output quality.' };\n return run;\n }\n if (evaluationMode === 'scoring') {\n run.executionStatus = 'completed';\n if ((outcome.aggregate.missingScoreTrialCount ?? run.trials.length) > 0) {\n run.qualityStatus = 'unable-to-evaluate';\n run.qualityReason = { code: 'scores-incomplete', message: 'One or more requested trials did not produce a usable score. Available averages are shown with coverage.' };\n run.warnings.push(`Score coverage is ${outcome.aggregate.scoredTrialCount ?? 0} of ${outcome.aggregate.trialCount} requested trials.`);\n } else if ((outcome.aggregate.scoredTrialCount ?? 0) > 0) {\n run.qualityStatus = 'scored';\n run.qualityReason = { code: 'scores-complete', message: 'Every requested trial produced a score. Overall score is the equal-weight average of case averages.' };\n } else {\n run.qualityStatus = 'unable-to-evaluate';\n run.qualityReason = { code: 'scores-incomplete', message: 'No requested trial produced a usable score.' };\n }\n return run;\n }\n const baseline = options.baseline ?? options.evaluationData.baselines.find((candidate) => candidate.suiteId === options.suite.id);\n const usableBaseline = baseline && baselineCompatible(run.provenance, baseline) ? baseline : undefined;\n if (baseline && !usableBaseline && !run.warnings.includes('The suite baseline is stale because its target, dataset, bindings, or evaluator definition changed.')) {\n run.warnings.push('The suite baseline is stale because its target, dataset, bindings, or evaluator definition changed.');\n }\n run.thresholdResults = evaluateThresholdResults(outcome.aggregate, options.suite.thresholds, usableBaseline);\n const hasPassRateThreshold = options.suite.thresholds?.some((threshold) => threshold.metric === 'pass-rate') ?? false;\n const hasTargetErrorRateThreshold = options.suite.thresholds?.some((threshold) => threshold.metric === 'target-error-rate') ?? false;\n const hasUngovernedCheckFailure = !hasPassRateThreshold && run.trials.some((trial) => trial.executionStatus === 'completed' && trial.qualityStatus === 'failed');\n const hasUngovernedTargetError = !hasTargetErrorRateThreshold && run.trials.some((trial) => trial.executionStatus === 'error');\n const hasThresholdFailure = run.thresholdResults.some((result) => result.status === 'failed');\n const hasUnavailableEvidence = run.trials.some((trial) => trial.qualityStatus === 'unable-to-evaluate') || run.thresholdResults.some((result) => result.status === 'unavailable');\n const hasAuthoritativePass = run.trials.some((trial) => trial.executionStatus === 'completed' && trial.qualityStatus === 'passed') || run.thresholdResults.some((result) => result.status === 'passed');\n run.executionStatus = 'completed';\n if (hasUngovernedCheckFailure || hasUngovernedTargetError || hasThresholdFailure) {\n run.qualityStatus = 'failed';\n run.qualityReason = { code: hasThresholdFailure ? 'thresholds-failed' : 'checks-failed', message: hasThresholdFailure ? 'One or more required aggregate thresholds failed.' : 'One or more target executions or required quality checks failed.' };\n } else if (hasUnavailableEvidence) {\n run.qualityStatus = 'unable-to-evaluate';\n run.qualityReason = { code: run.thresholdResults.some((result) => result.status === 'unavailable') ? 'required-metric-unavailable' : 'required-check-error', message: run.thresholdResults.some((result) => result.status === 'unavailable') ? 'A required aggregate metric could not be evaluated.' : 'A required quality check could not be evaluated.' };\n } else if (hasAuthoritativePass) {\n run.qualityStatus = 'passed';\n run.qualityReason = { code: run.thresholdResults.length > 0 ? 'thresholds-passed' : 'checks-passed', message: run.thresholdResults.length > 0 ? 'All required quality checks and aggregate thresholds passed.' : 'All required quality checks passed.' };\n } else {\n run.qualityStatus = 'not-evaluated';\n run.qualityReason = { code: 'no-completed-trials', message: 'No completed trial produced an authoritative quality result.' };\n }\n return run;\n}\nexport type CreateEvaluationRunShellOptions = Pick<\n RunEvaluationSuiteOptions,\n 'project' | 'evaluationData' | 'dataset' | 'suiteId' | 'purpose' | 'runId' | 'projectFingerprint' | 'executionMode'\n>;\n\n/** Creates a durable running shell only after the complete submission validates. */\nexport function createEvaluationRunShell(options: CreateEvaluationRunShellOptions): {\n run: EvaluationRun;\n plan: EvaluationRunPlan;\n} {\n const plan = createEvaluationRunPlan(options);\n const runId = options.runId ?? makeId('evaluation');\n const run: EvaluationRun = {\n version: 2,\n id: runId,\n projectId: options.project.metadata.id,\n suiteId: plan.suite.id,\n suiteName: plan.suite.name,\n revision: 0,\n startedAt: new Date().toISOString(),\n purpose: plan.purpose,\n evaluationMode: plan.evaluationMode,\n executionStatus: 'running',\n qualityStatus: 'not-evaluated',\n qualityReason: { code: 'in-progress', message: 'The run is still in progress.' },\n accountingStatus: 'complete',\n provenance: createProvenance(options.project, plan.suite, options.dataset, options),\n trials: [],\n thresholdResults: [],\n warnings: [],\n requestedTrialCount: plan.work.length,\n };\n return { run, plan };\n}\nexport async function runEvaluationSuite(options: RunEvaluationSuiteOptions): Promise<EvaluationRun> {\n const plan = createEvaluationRunPlan(options);\n const { suite, purpose, evaluationMode } = plan;\n const runId = options.runId ?? makeId('evaluation');\n const run: EvaluationRun = {\n version: 2,\n id: runId,\n projectId: options.project.metadata.id,\n suiteId: suite.id,\n suiteName: suite.name,\n revision: 0,\n startedAt: new Date().toISOString(),\n purpose,\n evaluationMode,\n executionStatus: 'running',\n qualityStatus: 'not-evaluated',\n qualityReason: { code: 'in-progress', message: 'The run is still in progress.' },\n accountingStatus: 'complete',\n provenance: createProvenance(options.project, suite, options.dataset, options),\n trials: [],\n thresholdResults: [],\n warnings: [],\n };\n const concurrency = Math.min(\n MAX_CONCURRENCY,\n Math.max(1, Math.floor(suite.configuration?.concurrency ?? DEFAULT_CONCURRENCY)),\n );\n const work = plan.work;\n run.requestedTrialCount = work.length;\n const settledTrials: Array<EvaluationTrial | undefined> = Array.from({ length: work.length });\n let settledTrialCount = 0;\n const nextRevision = () => {\n run.revision = (run.revision ?? 0) + 1;\n return run.revision;\n };\n const publishLegacySnapshot = () => {\n // Legacy consumers may retain earlier revisions. Keep their snapshots\n // detached, while incremental consumers avoid cloning all prior trials.\n if (!options.onUpdate) return;\n run.trials = settledTrials.filter((trial): trial is EvaluationTrial => trial !== undefined);\n options.onUpdate(structuredClone(run));\n };\n const publishStarted = async () => {\n const revision = nextRevision();\n if (options.onEvent) {\n const shell = structuredClone(run);\n shell.trials = [];\n await options.onEvent({ type: 'run-started', revision, run: shell });\n }\n publishLegacySnapshot();\n };\n const publishSettledTrial = async (trial: EvaluationTrial) => {\n const revision = nextRevision();\n await options.onEvent?.({\n type: 'trial-settled',\n revision,\n runId: run.id,\n projectId: run.projectId,\n suiteId: run.suiteId,\n requestedTrialCount: run.requestedTrialCount ?? work.length,\n settledTrialCount,\n trial: structuredClone(trial),\n });\n publishLegacySnapshot();\n };\n const publishFinalized = async () => {\n const revision = nextRevision();\n await options.onEvent?.({ type: 'run-finalized', revision, run: structuredClone(run) });\n publishLegacySnapshot();\n };\n // Publish the running shell before constructing the worker-pool promise:\n // async workers start immediately, so publishing afterwards can otherwise\n // let the first graph call race ahead of the run's initial state.\n await publishStarted();\n const workPool = runEvaluationWorkPool({\n work,\n concurrency,\n signal: options.signal,\n execute: async (task) => {\n try {\n return await runEvaluationTrial({\n ...task,\n project: options.project,\n suite,\n dataset: options.dataset,\n purpose,\n runId,\n runGraph: options.runGraph,\n signal: options.signal,\n });\n } catch (error) {\n const executionStatus = isAbort(error) ? ('canceled' as const) : ('error' as const);\n const qualityStatus =\n purpose === 'evaluation' && executionStatus === 'error'\n ? evaluationMode === 'scoring'\n ? ('unable-to-evaluate' as const)\n : ('failed' as const)\n : ('not-evaluated' as const);\n return {\n id: makeId('trial'),\n caseId: task.testCase.id,\n caseName: task.testCase.name,\n caseIndex: task.caseIndex,\n trialIndex: task.trialIndex,\n executionStatus,\n qualityStatus,\n qualityReason:\n executionStatus === 'canceled'\n ? { code: 'canceled' as const, message: 'The evaluation trial was canceled.' }\n : purpose === 'evaluation'\n ? evaluationMode === 'scoring'\n ? { code: 'scores-incomplete' as const, message: 'The target graph could not produce a score.' }\n : { code: 'target-error' as const, message: 'The target graph could not be executed.' }\n : { code: 'benchmark' as const, message: 'This benchmark trial could not be executed.' },\n inputs: {},\n expected: {},\n outputs: {},\n observations: [],\n targetMetrics: createEmptyMetrics(),\n evaluatorMetrics: createEmptyMetrics(),\n totalMetrics:\n executionStatus === 'canceled' ? { ...createEmptyMetrics(), hasUnknownCost: true } : createEmptyMetrics(),\n error: toErrorMessage(error),\n };\n }\n },\n onSettled: async (result, index) => {\n settledTrials[index] = result;\n settledTrialCount += 1;\n await publishSettledTrial(result);\n },\n });\n const results = await workPool;\n finalizeEvaluationRun({\n run,\n trials: results.filter((result): result is EvaluationTrial => result !== undefined),\n suite,\n evaluationData: options.evaluationData,\n baseline: options.baseline,\n canceled: options.signal?.aborted === true,\n });\n await publishFinalized();\n return run;\n}\n\nexport async function runEvaluationCases(\n options: RunEvaluationSuiteOptions & { caseIds: readonly string[] },\n): Promise<EvaluationRun> {\n const permitted = new Set(options.caseIds);\n return runEvaluationSuite({\n ...options,\n dataset: { ...options.dataset, cases: options.dataset.cases.filter((testCase) => permitted.has(testCase.id)) },\n });\n}\n\nexport function summarizeEvaluationRun(\n run: EvaluationRun,\n): { aggregate: EvaluationAggregate; cases: EvaluationCaseAggregate[] } | undefined {\n return run.aggregate ? aggregate(run.trials, getEvaluationSuiteMode(run)) : undefined;\n}\n\n/**\n * Baselines deliberately retain aggregate/provenance only. Raw prompts,\n * outputs, credentials, and replay artifacts remain in the run store.\n */\nexport function createEvaluationBaselineSnapshot(run: EvaluationRun): EvaluationBaselineSnapshot {\n const normalizedRun = normalizeEvaluationRun(run);\n if (normalizedRun.executionStatus !== 'completed') {\n throw new Error('Only a completed evaluation run can be promoted to a baseline.');\n }\n if (\n normalizedRun.purpose !== 'execution-benchmark' &&\n getEvaluationSuiteMode(normalizedRun) === 'scoring' &&\n normalizedRun.qualityStatus !== 'scored'\n ) {\n throw new Error('A scoring baseline needs a complete score for every requested trial.');\n }\n const summary = summarizeEvaluationRun(normalizedRun);\n if (!summary) throw new Error('Only a completed evaluation run can be promoted to a baseline.');\n return {\n id: makeId('baseline'),\n suiteId: normalizedRun.suiteId,\n sourceRunId: normalizedRun.id,\n createdAt: new Date().toISOString(),\n provenance: normalizedRun.provenance,\n aggregate: summary.aggregate,\n purpose: normalizedRun.purpose,\n evaluationMode: getEvaluationSuiteMode(normalizedRun),\n qualityStatus: normalizedRun.qualityStatus,\n qualityReason: normalizedRun.qualityReason,\n accountingStatus: normalizedRun.accountingStatus,\n cases: summary.cases,\n };\n}\n", "import { assertPortableJson, fingerprintEvaluationDataset } from './canonical.js';\nimport { assertEvaluationDatasetValuesMatchDeclaredTypes } from './dataTypes.js';\nimport type { EvaluationDataset, EvaluationDatasetCase, EvaluationDatasetField } from './types.js';\n\nconst DATASET_EXPORT_VERSION = 1;\n\ntype DatasetExportEnvelope = {\n version: typeof DATASET_EXPORT_VERSION;\n dataset: EvaluationDataset;\n};\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction requireString(value: unknown, path: string): string {\n if (typeof value !== 'string' || value.length === 0) throw new Error(`${path} must be a non-empty string.`);\n return value;\n}\n\nfunction requireText(value: unknown, path: string): string {\n if (typeof value !== 'string') throw new Error(`${path} must be a string.`);\n return value;\n}\n\nfunction parseFields(value: unknown): EvaluationDatasetField[] {\n if (!Array.isArray(value)) throw new Error('Evaluation dataset fields must be an array.');\n const ids = new Set<string>();\n return value.map((field, index) => {\n if (!isRecord(field)) throw new Error(`fields[${index}] must be an object.`);\n const id = requireString(field.id, `fields[${index}].id`);\n if (ids.has(id)) throw new Error(`Evaluation dataset has duplicate field id \"${id}\".`);\n ids.add(id);\n const role = field.role;\n if (role !== 'input' && role !== 'expected' && role !== 'metadata') {\n throw new Error(`fields[${index}].role must be input, expected, or metadata.`);\n }\n if (field.description !== undefined && typeof field.description !== 'string') {\n throw new Error(`fields[${index}].description must be a string.`);\n }\n if (field.required !== undefined && typeof field.required !== 'boolean') {\n throw new Error(`fields[${index}].required must be a boolean.`);\n }\n return {\n id,\n name: requireText(field.name, `fields[${index}].name`),\n dataType: requireString(field.dataType, `fields[${index}].dataType`),\n role,\n ...(typeof field.description === 'string' ? { description: field.description } : {}),\n ...(typeof field.required === 'boolean' ? { required: field.required } : {}),\n };\n });\n}\n\nfunction parseCases(value: unknown, fieldIds: ReadonlySet<string>): EvaluationDatasetCase[] {\n if (!Array.isArray(value)) throw new Error('Evaluation dataset cases must be an array.');\n const ids = new Set<string>();\n return value.map((testCase, index) => {\n if (!isRecord(testCase)) throw new Error(`cases[${index}] must be an object.`);\n const id = requireString(testCase.id, `cases[${index}].id`);\n if (ids.has(id)) throw new Error(`Evaluation dataset has duplicate case id \"${id}\".`);\n ids.add(id);\n if (!isRecord(testCase.values)) throw new Error(`cases[${index}].values must be an object.`);\n for (const [fieldId, fieldValue] of Object.entries(testCase.values)) {\n if (!fieldIds.has(fieldId)) throw new Error(`cases[${index}].values references unknown field \"${fieldId}\".`);\n assertPortableJson(fieldValue, `cases[${index}].values.${fieldId}`);\n }\n if (testCase.tags !== undefined && (!Array.isArray(testCase.tags) || testCase.tags.some((tag) => typeof tag !== 'string'))) {\n throw new Error(`cases[${index}].tags must be an array of strings.`);\n }\n if (testCase.note !== undefined && typeof testCase.note !== 'string') throw new Error(`cases[${index}].note must be a string.`);\n if (testCase.enabled !== undefined && typeof testCase.enabled !== 'boolean') throw new Error(`cases[${index}].enabled must be a boolean.`);\n return {\n id,\n name: requireText(testCase.name, `cases[${index}].name`),\n values: testCase.values as EvaluationDatasetCase['values'],\n ...(typeof testCase.enabled === 'boolean' ? { enabled: testCase.enabled } : {}),\n ...(Array.isArray(testCase.tags) ? { tags: testCase.tags as string[] } : {}),\n ...(typeof testCase.note === 'string' ? { note: testCase.note } : {}),\n };\n });\n}\n\n/**\n * Validates durable evaluation datasets and portable imports. `projectId` is\n * accepted solely for backwards-compatible migration from project-owned\n * datasets; newly created local datasets omit it.\n */\nexport function validateEvaluationDataset(\n value: unknown,\n scope?: Pick<EvaluationDataset, 'id' | 'projectId'>,\n): EvaluationDataset {\n if (!isRecord(value)) throw new Error('Evaluation dataset must be an object.');\n const fields = parseFields(value.fields);\n const importedProjectId =\n value.projectId === undefined ? undefined : (requireString(value.projectId, 'dataset.projectId') as EvaluationDataset['projectId']);\n const projectId = scope?.projectId ?? importedProjectId;\n const dataset: EvaluationDataset = {\n id: scope?.id ?? requireString(value.id, 'dataset.id'),\n name: requireText(value.name, 'dataset.name'),\n ...(projectId === undefined ? {} : { projectId }),\n fields,\n cases: parseCases(value.cases, new Set(fields.map((field) => field.id))),\n };\n return { ...dataset, contentFingerprint: fingerprintEvaluationDataset(dataset) };\n}\n\n/**\n * Converts a legacy project-owned dataset into the application-local form.\n * Field and case identity stay stable, so existing suite bindings continue to\n * work after migration.\n */\nexport function localizeEvaluationDataset(value: unknown, id?: string): EvaluationDataset {\n const dataset = validateEvaluationDataset(value, id === undefined ? undefined : { id });\n const { projectId: _legacyProjectId, ...localDataset } = dataset;\n return { ...localDataset, contentFingerprint: fingerprintEvaluationDataset(localDataset) };\n}\n\n/** Strict validation for explicit portable import and export boundaries. */\nexport function validateEvaluationDatasetForTransfer(\n value: unknown,\n scope?: Pick<EvaluationDataset, 'id' | 'projectId'>,\n): EvaluationDataset {\n const dataset = validateEvaluationDataset(value, scope);\n assertEvaluationDatasetValuesMatchDeclaredTypes(dataset);\n return dataset;\n}\n\n/**\n * Portable interchange envelope for a complete evaluation dataset. CSV is\n * useful for case rows; JSON is the lossless form that also carries field\n * roles and Rivet data types.\n */\nexport function serializeEvaluationDatasetJson(dataset: EvaluationDataset): string {\n const validated = validateEvaluationDatasetForTransfer(dataset);\n return JSON.stringify({ version: DATASET_EXPORT_VERSION, dataset: validated } satisfies DatasetExportEnvelope, null, 2);\n}\n\n/**\n * Reads a dataset export into a destination dataset identity. Import keeps\n * incoming field/case IDs but never lets a file overwrite another resource.\n */\nexport function deserializeEvaluationDatasetJson(\n source: string,\n scope: Pick<EvaluationDataset, 'id'>,\n): EvaluationDataset {\n let parsed: unknown;\n try {\n parsed = JSON.parse(source);\n } catch {\n throw new Error('Evaluation dataset JSON is not valid JSON.');\n }\n if (!isRecord(parsed) || parsed.version !== DATASET_EXPORT_VERSION || !isRecord(parsed.dataset)) {\n throw new Error(`Expected an evaluation dataset export with version ${DATASET_EXPORT_VERSION}.`);\n }\n const dataset = validateEvaluationDatasetForTransfer(parsed.dataset, { id: scope.id });\n const { projectId: _legacyProjectId, ...localDataset } = dataset;\n return { ...localDataset, contentFingerprint: fingerprintEvaluationDataset(localDataset) };\n}\n", "import * as yaml from 'yaml';\nimport { assertPortableJson } from './canonical.js';\nimport { normalizeEvaluationBaselineSnapshot } from './normalization.js';\nimport type { EvaluationProjectData, EvaluationSuite } from './types.js';\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction requireRecord(value: unknown, path: string): Record<string, unknown> {\n if (!isRecord(value)) throw new Error(`${path} must be an object.`);\n return value;\n}\n\nfunction requireString(value: unknown, path: string): void {\n if (typeof value !== 'string' || value.trim().length === 0) throw new Error(`${path} must be a non-empty string.`);\n}\n\nfunction requireText(value: unknown, path: string): void {\n if (typeof value !== 'string') throw new Error(`${path} must be a string.`);\n}\n\nfunction requireBoolean(value: unknown, path: string): void {\n if (typeof value !== 'boolean') throw new Error(`${path} must be a boolean.`);\n}\n\nfunction requireFiniteNumber(value: unknown, path: string): void {\n if (typeof value !== 'number' || !Number.isFinite(value)) throw new Error(`${path} must be a finite number.`);\n}\n\nfunction requireArray(value: unknown, path: string): readonly unknown[] {\n if (!Array.isArray(value)) throw new Error(`${path} must be an array.`);\n return value;\n}\n\ntype LegacyEvaluationProjectData = EvaluationProjectData & {\n selectedSuiteId?: unknown;\n selectedDatasetId?: unknown;\n};\n\n/**\n * Selection is editor workspace state, not executable project data. Older\n * project attachments can contain these fields, and previous editors could\n * put an explicit `undefined` here, which is not portable JSON. They have no\n * effect on project behavior, so discard both fields before validation.\n */\nfunction stripLegacyEditorSelections(data: LegacyEvaluationProjectData): EvaluationProjectData {\n const { selectedSuiteId: _selectedSuiteId, selectedDatasetId: _selectedDatasetId, ...projectData } = data;\n return projectData;\n}\n\nfunction validateOptionalPrimitive(\n record: Record<string, unknown>,\n key: string,\n type: 'string' | 'boolean' | 'number',\n path: string,\n): void {\n const value = record[key];\n if (value === undefined) return;\n if (type === 'number') requireFiniteNumber(value, `${path}.${key}`);\n else if (typeof value !== type) throw new Error(`${path}.${key} must be a ${type}.`);\n}\n\nconst ASSERTION_OPERATORS = new Set([\n 'equals',\n 'not-equals',\n 'contains',\n 'matches-regex',\n 'type-is',\n 'json-schema',\n 'number-at-least',\n 'number-at-most',\n 'number-between',\n 'array-includes',\n 'set-overlaps',\n 'contains-any',\n 'contains-all',\n]);\nconst EVALUATOR_CONTEXT_INPUTS = new Set(['case', 'inputs', 'expected', 'outputs', 'run']);\n\nfunction validateSuiteShape(value: unknown, index: number): asserts value is EvaluationSuite {\n const path = `evaluations.suites[${index}]`;\n const suite = requireRecord(value, path);\n for (const key of ['id', 'targetGraphId', 'datasetId']) requireString(suite[key], `${path}.${key}`);\n requireText(suite.name, `${path}.name`);\n if (\n suite.evaluationMode !== undefined &&\n suite.evaluationMode !== 'pass-fail' &&\n suite.evaluationMode !== 'scoring'\n ) {\n throw new Error(`${path}.evaluationMode must be \"pass-fail\" or \"scoring\".`);\n }\n for (const [bindingIndex, bindingValue] of requireArray(suite.inputBindings, `${path}.inputBindings`).entries()) {\n const binding = requireRecord(bindingValue, `${path}.inputBindings[${bindingIndex}]`);\n requireString(binding.graphInputId, `${path}.inputBindings[${bindingIndex}].graphInputId`);\n requireString(binding.datasetFieldId, `${path}.inputBindings[${bindingIndex}].datasetFieldId`);\n }\n for (const [assertionIndex, assertionValue] of requireArray(suite.assertions, `${path}.assertions`).entries()) {\n const assertionPath = `${path}.assertions[${assertionIndex}]`;\n const assertion = requireRecord(assertionValue, assertionPath);\n for (const key of ['id', 'outputPath']) requireString(assertion[key], `${assertionPath}.${key}`);\n requireText(assertion.name, `${assertionPath}.name`);\n if (typeof assertion.operator !== 'string' || !ASSERTION_OPERATORS.has(assertion.operator)) {\n throw new Error(`${assertionPath}.operator is not supported.`);\n }\n validateOptionalPrimitive(assertion, 'required', 'boolean', assertionPath);\n const expected = requireRecord(assertion.expected, `${assertionPath}.expected`);\n if (expected.kind === 'literal') {\n if (!Object.hasOwn(expected, 'value')) throw new Error(`${assertionPath}.expected.value is required.`);\n } else if (expected.kind === 'dataset-field') {\n requireString(expected.fieldId, `${assertionPath}.expected.fieldId`);\n } else {\n throw new Error(`${assertionPath}.expected.kind must be \"literal\" or \"dataset-field\".`);\n }\n }\n for (const [evaluatorIndex, evaluatorValue] of requireArray(suite.evaluators, `${path}.evaluators`).entries()) {\n const evaluatorPath = `${path}.evaluators[${evaluatorIndex}]`;\n const evaluator = requireRecord(evaluatorValue, evaluatorPath);\n for (const key of ['id', 'graphId']) requireString(evaluator[key], `${evaluatorPath}.${key}`);\n requireText(evaluator.name, `${evaluatorPath}.name`);\n validateOptionalPrimitive(evaluator, 'required', 'boolean', evaluatorPath);\n validateOptionalPrimitive(evaluator, 'runOnTargetError', 'boolean', evaluatorPath);\n validateOptionalPrimitive(evaluator, 'scoreWeight', 'number', evaluatorPath);\n if (evaluator.inputBindings !== undefined) {\n for (const [bindingIndex, bindingValue] of requireArray(\n evaluator.inputBindings,\n `${evaluatorPath}.inputBindings`,\n ).entries()) {\n const bindingPath = `${evaluatorPath}.inputBindings[${bindingIndex}]`;\n const binding = requireRecord(bindingValue, bindingPath);\n requireString(binding.graphInputId, `${bindingPath}.graphInputId`);\n const source = requireRecord(binding.source, `${bindingPath}.source`);\n if (source.kind === 'dataset-field') requireString(source.fieldId, `${bindingPath}.source.fieldId`);\n else if (source.kind === 'target-output') requireString(source.outputId, `${bindingPath}.source.outputId`);\n else if (source.kind === 'context') {\n if (typeof source.context !== 'string' || !EVALUATOR_CONTEXT_INPUTS.has(source.context)) {\n throw new Error(`${bindingPath}.source.context is not supported.`);\n }\n } else {\n throw new Error(`${bindingPath}.source.kind is not supported.`);\n }\n }\n }\n }\n if (suite.thresholds !== undefined) {\n for (const [thresholdIndex, thresholdValue] of requireArray(suite.thresholds, `${path}.thresholds`).entries()) {\n const thresholdPath = `${path}.thresholds[${thresholdIndex}]`;\n const threshold = requireRecord(thresholdValue, thresholdPath);\n for (const key of ['id', 'metric', 'operator']) requireString(threshold[key], `${thresholdPath}.${key}`);\n requireFiniteNumber(threshold.value, `${thresholdPath}.value`);\n }\n }\n if (suite.configuration !== undefined) {\n const configuration = requireRecord(suite.configuration, `${path}.configuration`);\n for (const key of ['trialCount', 'concurrency', 'timeoutMs', 'seed']) {\n validateOptionalPrimitive(configuration, key, 'number', `${path}.configuration`);\n }\n validateOptionalPrimitive(configuration, 'seedGraphInputId', 'string', `${path}.configuration`);\n validateOptionalPrimitive(configuration, 'recordingRetention', 'string', `${path}.configuration`);\n }\n validateOptionalPrimitive(suite, 'description', 'string', path);\n if (suite.tags !== undefined) {\n for (const [tagIndex, tag] of requireArray(suite.tags, `${path}.tags`).entries()) {\n requireString(tag, `${path}.tags[${tagIndex}]`);\n }\n }\n}\n\nfunction validateNumericRecord(value: unknown, path: string): void {\n const record = requireRecord(value, path);\n for (const [key, entry] of Object.entries(record)) requireFiniteNumber(entry, `${path}.${key}`);\n}\n\nfunction validateBaselineShape(value: unknown, index: number): void {\n const path = `evaluations.baselines[${index}]`;\n const baseline = requireRecord(value, path);\n for (const key of ['id', 'suiteId', 'createdAt']) requireString(baseline[key], `${path}.${key}`);\n validateOptionalPrimitive(baseline, 'sourceRunId', 'string', path);\n if (\n baseline.evaluationMode !== undefined &&\n baseline.evaluationMode !== 'pass-fail' &&\n baseline.evaluationMode !== 'scoring'\n ) {\n throw new Error(`${path}.evaluationMode must be \"pass-fail\" or \"scoring\".`);\n }\n const provenance = requireRecord(baseline.provenance, `${path}.provenance`);\n for (const key of [\n 'projectFingerprint',\n 'suiteFingerprint',\n 'datasetFingerprint',\n 'targetFingerprint',\n 'executionMode',\n ]) {\n requireString(provenance[key], `${path}.provenance.${key}`);\n }\n const evaluatorFingerprints = requireRecord(\n provenance.evaluatorFingerprints,\n `${path}.provenance.evaluatorFingerprints`,\n );\n for (const [key, fingerprint] of Object.entries(evaluatorFingerprints)) {\n requireString(fingerprint, `${path}.provenance.evaluatorFingerprints.${key}`);\n }\n requireBoolean(provenance.accountingComplete, `${path}.provenance.accountingComplete`);\n const aggregate = requireRecord(baseline.aggregate, `${path}.aggregate`);\n for (const key of [\n 'trialCount',\n 'passedTrialCount',\n 'failedTrialCount',\n 'erroredTrialCount',\n 'canceledTrialCount',\n 'passRate',\n 'averageLatencyMs',\n 'p95LatencyMs',\n 'targetErrorRate',\n 'evaluatorErrorRate',\n 'toolFailureRate',\n ]) {\n requireFiniteNumber(aggregate[key], `${path}.aggregate.${key}`);\n }\n for (const key of [\n 'evaluatedTrialCount',\n 'notEvaluatedTrialCount',\n 'unableToEvaluateTrialCount',\n 'meanScore',\n 'medianScore',\n 'p95Score',\n 'medianLatencyMs',\n 'totalCostUsd',\n 'averageCostUsd',\n 'scoredTrialCount',\n 'missingScoreTrialCount',\n ]) {\n validateOptionalPrimitive(aggregate, key, 'number', `${path}.aggregate`);\n }\n validateNumericRecord(aggregate.metrics, `${path}.aggregate.metrics`);\n for (const [caseIndex, caseValue] of requireArray(baseline.cases, `${path}.cases`).entries()) {\n const casePath = `${path}.cases[${caseIndex}]`;\n const caseAggregate = requireRecord(caseValue, casePath);\n requireString(caseAggregate.caseId, `${casePath}.caseId`);\n requireString(caseAggregate.caseName, `${casePath}.caseName`);\n validateNumericRecord(caseAggregate.metrics, `${casePath}.metrics`);\n for (const key of [\n 'passRate',\n 'meanScore',\n 'evaluatedTrialCount',\n 'passedTrialCount',\n 'failedTrialCount',\n 'notEvaluatedTrialCount',\n 'unableToEvaluateTrialCount',\n 'erroredTrialCount',\n 'canceledTrialCount',\n 'scoredTrialCount',\n 'missingScoreTrialCount',\n ]) {\n validateOptionalPrimitive(caseAggregate, key, 'number', casePath);\n }\n }\n}\n\nexport function createEmptyEvaluationProjectData(): EvaluationProjectData {\n return { version: 1, suites: [], baselines: [] };\n}\n\nexport function serializeEvaluationProjectData(data: EvaluationProjectData): EvaluationProjectData {\n if (data.version !== 1) throw new Error(`Unsupported evaluation data version: ${data.version}`);\n const persistentData = stripLegacyEditorSelections(data as LegacyEvaluationProjectData);\n assertPortableJson(persistentData);\n return {\n ...structuredClone(persistentData),\n baselines: persistentData.baselines.map(normalizeEvaluationBaselineSnapshot),\n };\n}\n\nexport function deserializeEvaluationProjectData(data: unknown): EvaluationProjectData {\n if (data === null || typeof data !== 'object' || Array.isArray(data))\n throw new Error('Evaluation project data must be an object.');\n const candidate = data as Partial<LegacyEvaluationProjectData>;\n if (candidate.version !== 1 || !Array.isArray(candidate.suites) || !Array.isArray(candidate.baselines)) {\n throw new Error('Unsupported or invalid evaluation project data.');\n }\n const persistentData = stripLegacyEditorSelections(candidate as LegacyEvaluationProjectData);\n assertPortableJson(persistentData);\n persistentData.suites.forEach(validateSuiteShape);\n persistentData.baselines.forEach(validateBaselineShape);\n return {\n ...structuredClone(persistentData),\n baselines: persistentData.baselines.map(normalizeEvaluationBaselineSnapshot),\n };\n}\n\nexport function serializeEvaluationProjectDataToString(data: EvaluationProjectData): string {\n return yaml.stringify(serializeEvaluationProjectData(data), null, 2);\n}\n\nexport function deserializeEvaluationProjectDataFromString(data: string): EvaluationProjectData {\n return deserializeEvaluationProjectData(yaml.parse(data));\n}\n", "import { localizeEvaluationDataset } from './datasetTransfer.js';\nimport { createEmptyEvaluationProjectData, deserializeEvaluationProjectData } from './serialization.js';\nimport type { ProjectId } from '@valerypopoff/rivet2-core';\nimport type { EvaluationLibrary, EvaluationProjectData } from './types.js';\n\nexport function createEmptyEvaluationLibrary(): EvaluationLibrary {\n return {\n version: 1,\n data: createEmptyEvaluationProjectData(),\n datasets: [],\n migratedLegacyProjectIds: [],\n };\n}\n\n/**\n * Repairs a library resource-by-resource so one malformed suite, baseline, or\n * dataset cannot hide unrelated valid resources. The top-level persistence\n * envelope is validated by the owning store before this function is called.\n */\nexport function normalizeEvaluationLibrary(value: unknown): EvaluationLibrary {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return createEmptyEvaluationLibrary();\n const candidate = value as Partial<EvaluationLibrary>;\n let data = createEmptyEvaluationProjectData();\n try {\n data = deserializeEvaluationProjectData(candidate.data);\n } catch {\n const dataCandidate =\n typeof candidate.data === 'object' && candidate.data !== null && !Array.isArray(candidate.data)\n ? (candidate.data as Partial<EvaluationProjectData>)\n : undefined;\n const suites = Array.isArray(dataCandidate?.suites)\n ? dataCandidate.suites.flatMap((suite) => {\n try {\n return [deserializeEvaluationProjectData({ version: 1, suites: [suite], baselines: [] }).suites[0]!];\n } catch {\n return [];\n }\n })\n : [];\n const baselines = Array.isArray(dataCandidate?.baselines)\n ? dataCandidate.baselines.flatMap((baseline) => {\n try {\n return [deserializeEvaluationProjectData({ version: 1, suites: [], baselines: [baseline] }).baselines[0]!];\n } catch {\n return [];\n }\n })\n : [];\n const suiteIds = new Set(suites.map((suite) => suite.id));\n data = { version: 1, suites, baselines: baselines.filter((baseline) => suiteIds.has(baseline.suiteId)) };\n }\n\n const datasets = Array.isArray(candidate.datasets)\n ? candidate.datasets.flatMap((dataset) => {\n try {\n return [localizeEvaluationDataset(dataset)];\n } catch {\n return [];\n }\n })\n : [];\n\n const suites = uniqueById(data.suites);\n const suiteIds = new Set(suites.map((suite) => suite.id));\n\n return {\n version: 1,\n data: {\n ...data,\n suites,\n baselines: uniqueById(data.baselines).filter((baseline) => suiteIds.has(baseline.suiteId)),\n },\n datasets: uniqueById(datasets),\n migratedLegacyProjectIds: Array.isArray(candidate.migratedLegacyProjectIds)\n ? Array.from(new Set(candidate.migratedLegacyProjectIds.filter((id): id is ProjectId => typeof id === 'string')))\n : [],\n };\n}\n\nfunction uniqueById<T extends { id: string }>(values: readonly T[]): T[] {\n const seen = new Set<string>();\n return values.filter((value) => {\n if (seen.has(value.id)) return false;\n seen.add(value.id);\n return true;\n });\n}\n", "import { assertEvaluationDatasetSnapshot, assertEvaluationRecordingArtifact } from './canonical.js';\nimport { normalizeEvaluationRun, reconcileEvaluationRunSnapshots } from './normalization.js';\nimport { createEmptyEvaluationLibrary, normalizeEvaluationLibrary } from './library.js';\nimport type {\n EvaluationDatasetSnapshot,\n EvaluationLibrary,\n EvaluationRecordingArtifact,\n EvaluationRun,\n EvaluationStore,\n} from './types.js';\n\nexport class InMemoryEvaluationRunStore implements EvaluationStore {\n readonly #runs = new Map<string, EvaluationRun>();\n readonly #datasetSnapshots = new Map<string, EvaluationDatasetSnapshot>();\n readonly #recordings = new Map<string, EvaluationRecordingArtifact>();\n #library: EvaluationLibrary = createEmptyEvaluationLibrary();\n\n async getLibrary(): Promise<EvaluationLibrary> {\n return structuredClone(this.#library);\n }\n\n async putLibrary(library: EvaluationLibrary): Promise<void> {\n this.#library = structuredClone(normalizeEvaluationLibrary(library));\n }\n\n async put(run: EvaluationRun): Promise<void> {\n const normalized = normalizeEvaluationRun(run);\n const key = `${normalized.projectId}/${normalized.id}`;\n const existing = this.#runs.get(key);\n const next = reconcileEvaluationRunSnapshots(existing, normalized);\n if (next === existing) return;\n this.#runs.set(key, structuredClone(next));\n }\n\n async updateRunName(input: { projectId: string; runId: string; name?: string }): Promise<EvaluationRun | undefined> {\n const key = `${input.projectId}/${input.runId}`;\n const existing = this.#runs.get(key);\n if (!existing) return undefined;\n const renamed = normalizeEvaluationRun({ ...existing, name: input.name });\n this.#runs.set(key, structuredClone(renamed));\n return structuredClone(renamed);\n }\n\n async get(input: { projectId: string; runId: string }): Promise<EvaluationRun | undefined> {\n const run = this.#runs.get(`${input.projectId}/${input.runId}`);\n return run ? normalizeEvaluationRun(run) : undefined;\n }\n\n async list(input: { projectId: string; suiteId?: string }): Promise<readonly EvaluationRun[]> {\n return Array.from(this.#runs.values())\n .filter(\n (run) => run.projectId === input.projectId && (input.suiteId === undefined || run.suiteId === input.suiteId),\n )\n .sort((left, right) => right.startedAt.localeCompare(left.startedAt))\n .map(normalizeEvaluationRun);\n }\n\n async delete(input: { projectId: string; runId: string }): Promise<void> {\n this.#runs.delete(`${input.projectId}/${input.runId}`);\n for (const [key, artifact] of this.#recordings) {\n if (artifact.projectId === input.projectId && artifact.runId === input.runId) this.#recordings.delete(key);\n }\n }\n\n async putDatasetSnapshot(snapshot: EvaluationDatasetSnapshot): Promise<void> {\n assertEvaluationDatasetSnapshot(snapshot);\n const key = `${snapshot.projectId}/${snapshot.fingerprint}`;\n // A content-addressed historical snapshot must never be rewritten by a\n // later edit of the live evaluation dataset.\n if (this.#datasetSnapshots.has(key)) return;\n this.#datasetSnapshots.set(key, structuredClone(snapshot));\n }\n\n async getDatasetSnapshot(input: {\n projectId: string;\n fingerprint: string;\n }): Promise<EvaluationDatasetSnapshot | undefined> {\n const snapshot = this.#datasetSnapshots.get(`${input.projectId}/${input.fingerprint}`);\n return snapshot ? structuredClone(snapshot) : undefined;\n }\n\n async putRecording(artifact: EvaluationRecordingArtifact): Promise<void> {\n assertEvaluationRecordingArtifact(artifact);\n const key = `${artifact.projectId}/${artifact.reference.id}`;\n const existing = this.#recordings.get(key);\n if (existing && (existing.runId !== artifact.runId || existing.trialId !== artifact.trialId)) {\n throw new Error('An evaluation recording ID cannot be reassigned to another run or trial.');\n }\n const next = structuredClone(artifact);\n // Artifact persistence never owns retention transitions. A duplicate or\n // delayed write keeps whatever explicit update/promotion already decided.\n if (existing) next.reference = structuredClone(existing.reference);\n this.#recordings.set(key, next);\n }\n\n async getRecording(input: {\n projectId: string;\n recordingId: string;\n }): Promise<EvaluationRecordingArtifact | undefined> {\n const artifact = this.#recordings.get(`${input.projectId}/${input.recordingId}`);\n if (!artifact) return undefined;\n if (\n artifact.reference.retention === 'temporary' &&\n artifact.reference.expiresAt &&\n Date.parse(artifact.reference.expiresAt) <= Date.now()\n ) {\n this.#recordings.delete(`${input.projectId}/${input.recordingId}`);\n return undefined;\n }\n return structuredClone(artifact);\n }\n\n async updateRecordingRetention(input: {\n projectId: string;\n recordingId: string;\n retention: EvaluationRecordingArtifact['reference']['retention'];\n expiresAt?: string;\n }): Promise<boolean> {\n const key = `${input.projectId}/${input.recordingId}`;\n const artifact = this.#recordings.get(key);\n if (!artifact) return false;\n artifact.reference = {\n id: artifact.reference.id,\n retention: input.retention,\n ...(input.expiresAt === undefined ? {} : { expiresAt: input.expiresAt }),\n };\n return true;\n }\n\n async promoteBaseline(input: { projectId: string; runId: string }): Promise<void> {\n for (const artifact of this.#recordings.values()) {\n if (artifact.projectId !== input.projectId || artifact.runId !== input.runId) continue;\n artifact.reference = { id: artifact.reference.id, retention: 'baseline' };\n }\n }\n}\n", "import { localizeEvaluationDataset, validateEvaluationDatasetForTransfer } from './datasetTransfer.js';\nimport { deserializeEvaluationProjectData } from './serialization.js';\nimport type { EvaluationDataset, EvaluationSuite } from './types.js';\n\nconst SUITE_BUNDLE_EXPORT_VERSION = 1;\n\ntype SuiteBundleExportEnvelope = {\n version: typeof SUITE_BUNDLE_EXPORT_VERSION;\n suite: EvaluationSuite;\n dataset: EvaluationDataset;\n};\n\nexport type EvaluationSuiteBundle = {\n suite: EvaluationSuite;\n dataset: EvaluationDataset;\n};\n\nexport type EvaluationSuiteBundleImportScope = {\n suiteId: string;\n datasetId: string;\n};\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction requireNonEmptyString(value: string, name: string): void {\n if (value.trim().length === 0) throw new Error(`${name} must be a non-empty string.`);\n}\n\nfunction validateEvaluationSuite(value: unknown): EvaluationSuite {\n return deserializeEvaluationProjectData({ version: 1, suites: [value], baselines: [] }).suites[0]!;\n}\n\nfunction validateBundle(value: unknown): EvaluationSuiteBundle {\n if (\n !isRecord(value) ||\n value.version !== SUITE_BUNDLE_EXPORT_VERSION ||\n !isRecord(value.suite) ||\n !isRecord(value.dataset)\n ) {\n throw new Error(`Expected an evaluation suite export with version ${SUITE_BUNDLE_EXPORT_VERSION}.`);\n }\n const suite = validateEvaluationSuite(value.suite);\n const dataset = validateEvaluationDatasetForTransfer(value.dataset);\n if (suite.datasetId !== dataset.id) {\n throw new Error('The evaluation suite export must include the dataset referenced by its suite.');\n }\n return { suite, dataset };\n}\n\n/**\n * A portable suite bundle includes the suite definition and its referenced\n * dataset. It intentionally excludes graphs, baselines, recordings, and run\n * history, which belong to the destination project or its run store.\n */\nexport function serializeEvaluationSuiteBundleJson(suite: EvaluationSuite, dataset: EvaluationDataset): string {\n const bundle = validateBundle({ version: SUITE_BUNDLE_EXPORT_VERSION, suite, dataset });\n return JSON.stringify(\n { version: SUITE_BUNDLE_EXPORT_VERSION, ...bundle } satisfies SuiteBundleExportEnvelope,\n null,\n 2,\n );\n}\n\n/**\n * Imports a bundle as new local evaluation resources. Field and case IDs remain stable\n * so the imported suite's bindings and expected-value references still point\n * to its imported dataset; suite and dataset identities are always supplied by\n * the destination to avoid overwriting existing resources.\n */\nexport function deserializeEvaluationSuiteBundleJson(\n source: string,\n scope: EvaluationSuiteBundleImportScope,\n): EvaluationSuiteBundle {\n let parsed: unknown;\n try {\n parsed = JSON.parse(source);\n } catch {\n throw new Error('Evaluation suite JSON is not valid JSON.');\n }\n\n requireNonEmptyString(scope.suiteId, 'suiteId');\n requireNonEmptyString(scope.datasetId, 'datasetId');\n\n const bundle = validateBundle(parsed);\n const dataset = localizeEvaluationDataset(bundle.dataset, scope.datasetId);\n return {\n dataset,\n suite: {\n ...bundle.suite,\n id: scope.suiteId,\n datasetId: dataset.id,\n },\n };\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACweO,IAAM,gCAAN,cAA4C,MAAM;AAAA,EAC9C;AAAA,EACA;AAAA,EACA;AAAA,EAET,YACE,SACA,UAAiG,CAAC,GAClG;AACA,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,UAAU,QAAQ;AACvB,SAAK,YAAY,QAAQ;AACzB,SAAK,mBAAmB,QAAQ;AAAA,EAClC;AACF;;;ACrfO,SAAS,mBACd,OACA,OAAO,KACP,QAAQ,oBAAI,IAAY,GACO;AAC/B,MAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,OAAO,UAAU,UAAW;AAC/E,MAAI,OAAO,UAAU,UAAU;AAC7B,QAAI,CAAC,OAAO,SAAS,KAAK,EAAG,OAAM,IAAI,MAAM,GAAG,IAAI,wCAAwC;AAC5F;AAAA,EACF;AACA,MAAI,OAAO,UAAU,SAAU,OAAM,IAAI,MAAM,GAAG,IAAI,yBAAyB;AAC/E,MAAI,MAAM,IAAI,KAAK,EAAG,OAAM,IAAI,MAAM,GAAG,IAAI,4BAA4B;AACzE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ClD;AAAA,IACA;AAAA,EACF;AACF;AAQO,SAAS,qCACd,QACA,OACuB;AACvB,MAAI;AACJ,MAAI;AACF,aAAS,KAAK,MAAM,MAAM;AAAA,EAC5B,QAAQ;AACN,UAAM,IAAI,MAAM,0CAA0C;AAAA,EAC5D;AAEA,wBAAsB,MAAM,SAAS,SAAS;AAC9C,wBAAsB,MAAM,WAAW,WAAW;AAElD,QAAM,SAAS,eAAe,MAAM;AACpC,QAAM,UAAU,0BAA0B,OAAO,SAAS,MAAM,SAAS;AACzE,SAAO;AAAA,IACL;AAAA,IACA,OAAO;AAAA,MACL,GAAG,OAAO;AAAA,MACV,IAAI,MAAM;AAAA,MACV,WAAW,QAAQ;AAAA,IACrB;AAAA,EACF;AACF;",
3
+ "sources": ["../../src/index.ts", "../../src/types.ts", "../../src/canonical.ts", "../../src/assertions.ts", "../../src/normalization.ts", "../../src/dataTypes.ts", "../../src/runner.ts", "../../src/datasetTransfer.ts", "../../src/serialization.ts", "../../src/library.ts", "../../src/store.ts", "../../src/suiteTransfer.ts", "../../src/librarySync.ts"],
4
+ "sourcesContent": ["export * from './types.js';\nexport * from './canonical.js';\nexport * from './assertions.js';\nexport * from './runner.js';\nexport * from './store.js';\nexport * from './serialization.js';\nexport * from './datasetTransfer.js';\nexport * from './suiteTransfer.js';\nexport * from './dataTypes.js';\nexport * from './normalization.js';\nexport * from './library.js';\nexport * from './librarySync.js';\n", "import type { GraphId, Project, ProjectId } from '@valerypopoff/rivet2-core';\n\n/** Values saved in evaluation datasets, assertions, evidence, and run artifacts. */\nexport type PortableJson = null | boolean | number | string | PortableJson[] | { [key: string]: PortableJson };\n\nexport type EvaluationDatasetFieldRole = 'input' | 'expected' | 'metadata';\n\nexport type EvaluationDatasetField = {\n id: string;\n name: string;\n description?: string;\n /** Rivet data type identifier. The runner validates bindings against the target graph. */\n dataType: string;\n role: EvaluationDatasetFieldRole;\n required?: boolean;\n};\n\nexport type EvaluationDatasetCase = {\n id: string;\n name: string;\n enabled?: boolean;\n tags?: string[];\n note?: string;\n values: Record<string, PortableJson>;\n};\n\nexport type EvaluationDataset = {\n id: string;\n /**\n * Legacy project ownership retained only while importing older project\n * files. Locally persisted evaluation datasets intentionally omit it so\n * they can be reused with any currently open project.\n */\n projectId?: ProjectId;\n name: string;\n fields: EvaluationDatasetField[];\n cases: EvaluationDatasetCase[];\n /** Derived from fields and cases; stored to make snapshot reuse inspectable. */\n contentFingerprint?: string;\n};\n\nexport type EvaluationInputBinding = {\n graphInputId: string;\n datasetFieldId: string;\n};\n\nexport type EvaluationExpectedSource =\n | { kind: 'literal'; value: PortableJson }\n | { kind: 'dataset-field'; fieldId: string };\n\nexport type EvaluationAssertionOperator =\n | 'equals'\n | 'not-equals'\n | 'contains'\n | 'matches-regex'\n | 'type-is'\n | 'json-schema'\n | 'number-at-least'\n | 'number-at-most'\n | 'number-between'\n | 'array-includes'\n | 'set-overlaps'\n | 'contains-any'\n | 'contains-all';\n\nexport type EvaluationAssertion = {\n id: string;\n name: string;\n required?: boolean;\n outputPath: string;\n operator: EvaluationAssertionOperator;\n expected: EvaluationExpectedSource;\n};\n\nexport type EvaluationEvaluatorContextInput = 'case' | 'inputs' | 'expected' | 'outputs' | 'run';\n\nexport type EvaluationEvaluatorInputSource =\n | { kind: 'dataset-field'; fieldId: string }\n | { kind: 'target-output'; outputId: string }\n | { kind: 'context'; context: EvaluationEvaluatorContextInput };\n\nexport type EvaluationEvaluatorInputBinding = {\n graphInputId: string;\n source: EvaluationEvaluatorInputSource;\n};\n\nexport type EvaluationGraphEvaluator = {\n id: string;\n name: string;\n graphId: GraphId;\n /**\n * Explicit evaluator Graph Input mappings. Missing means an older evaluator\n * may use the five reserved context inputs; an empty array explicitly opts\n * into direct mapping for a graph with no required inputs.\n */\n inputBindings?: EvaluationEvaluatorInputBinding[];\n required?: boolean;\n scoreWeight?: number;\n runOnTargetError?: boolean;\n};\n\n/**\n * Pass/fail suites evaluate required assertions and evaluator verdicts.\n * Scoring evaluator graphs return scores on the user-facing 0..100 scale.\n * Runs store normalized scores internally for aggregation and compatibility.\n */\nexport type EvaluationSuiteMode = 'pass-fail' | 'scoring';\n\nexport type EvaluationThreshold =\n | { id: string; metric: 'pass-rate' | 'mean-score'; operator: 'at-least'; value: number }\n | {\n id: string;\n metric:\n | 'target-error-rate'\n | 'evaluator-error-rate'\n | 'tool-failure-rate'\n | 'average-cost'\n | 'total-cost'\n | 'average-latency-ms'\n | 'p95-latency-ms';\n operator: 'at-most';\n value: number;\n }\n | { id: string; metric: `custom:${string}`; operator: 'at-least' | 'at-most'; value: number }\n | { id: string; metric: string; operator: 'max-regression'; value: number };\n\nexport type EvaluationRunConfiguration = {\n trialCount?: number;\n concurrency?: number;\n timeoutMs?: number;\n seed?: number;\n seedGraphInputId?: string;\n recordingRetention?: 'failures-and-baselines' | 'all';\n};\n\nexport type EvaluationSuite = {\n id: string;\n name: string;\n description?: string;\n tags?: string[];\n targetGraphId: GraphId;\n datasetId: string;\n inputBindings: EvaluationInputBinding[];\n assertions: EvaluationAssertion[];\n evaluators: EvaluationGraphEvaluator[];\n /** Missing values are legacy pass/fail suites. */\n evaluationMode?: EvaluationSuiteMode;\n configuration?: EvaluationRunConfiguration;\n thresholds?: EvaluationThreshold[];\n};\n\nexport type EvaluationBaselineSnapshot = {\n id: string;\n suiteId: string;\n sourceRunId?: string;\n createdAt: string;\n provenance: EvaluationRunProvenance;\n aggregate: EvaluationAggregate;\n /** Optional for project baselines created before EvaluationRun v2. */\n purpose?: EvaluationRunPurpose;\n /** Optional for project baselines created before EvaluationRun v2. */\n qualityStatus?: EvaluationQualityStatus;\n /** Optional for project baselines created before EvaluationRun v2. */\n qualityReason?: EvaluationQualityReason;\n /** Optional for project baselines created before EvaluationRun v2. */\n accountingStatus?: EvaluationAccountingStatus;\n /** Optional for baselines created before score-capable suites existed. */\n evaluationMode?: EvaluationSuiteMode;\n cases: Array<\n Pick<\n EvaluationCaseAggregate,\n | 'caseId'\n | 'caseName'\n | 'passRate'\n | 'meanScore'\n | 'metrics'\n | 'evaluatedTrialCount'\n | 'passedTrialCount'\n | 'failedTrialCount'\n | 'notEvaluatedTrialCount'\n | 'unableToEvaluateTrialCount'\n | 'erroredTrialCount'\n | 'canceledTrialCount'\n | 'scoredTrialCount'\n | 'missingScoreTrialCount'\n >\n >;\n};\n\nexport type EvaluationProjectData = {\n version: 1;\n suites: EvaluationSuite[];\n baselines: EvaluationBaselineSnapshot[];\n};\n\n/**\n * Rivet-local evaluation resources. This is deliberately outside project\n * files so one Rivet instance can retain its evaluation library independently\n * of whichever project is currently open.\n */\nexport type EvaluationLibrary = {\n version: 1;\n data: EvaluationProjectData;\n datasets: EvaluationDataset[];\n /** Legacy project IDs whose embedded evaluation resources were imported. */\n migratedLegacyProjectIds: ProjectId[];\n};\n\n/**\n * A collaboration boundary for the shared evaluation library. A suite owns\n * its baselines because a baseline is only meaningful with that suite; a\n * dataset is independently editable and reusable by many suites.\n */\nexport type EvaluationLibraryResourceKind = 'suite' | 'dataset';\n\nexport type EvaluationLibraryResourceVersions = {\n suites: Record<string, string>;\n datasets: Record<string, string>;\n};\n\n/** A server-authoritative library snapshot used by collaborative hosts. */\nexport type EvaluationLibrarySyncSnapshot = {\n revision: number;\n library: EvaluationLibrary;\n resourceVersions: EvaluationLibraryResourceVersions;\n};\n\n/**\n * A validated, external change token for the shared evaluation library.\n * `epoch` identifies one SSE generation so reconnects can require a resync\n * even when a server's revision counter has not advanced.\n */\nexport type EvaluationLibraryInvalidation = {\n epoch: string;\n revision: number;\n};\n\n/** The durable value for one independently synchronized library resource. */\nexport type EvaluationLibrarySuiteBundle = {\n suite: EvaluationSuite;\n baselines: EvaluationBaselineSnapshot[];\n};\n\nexport type EvaluationLibraryResourceValue =\n | { kind: 'suite'; id: string; value: EvaluationLibrarySuiteBundle | undefined }\n | { kind: 'dataset'; id: string; value: EvaluationDataset | undefined };\n\n/**\n * Every mutation is an all-or-nothing resource batch. Existing resources use\n * their opaque version token; null means that creation requires the resource\n * to remain absent.\n */\nexport type EvaluationLibraryMutationChange =\n | {\n kind: 'put-suite';\n id: string;\n expectedVersion: string | null;\n suite: EvaluationSuite;\n baselines: EvaluationBaselineSnapshot[];\n }\n | { kind: 'delete-suite'; id: string; expectedVersion: string }\n | {\n kind: 'put-dataset';\n id: string;\n expectedVersion: string | null;\n dataset: EvaluationDataset;\n }\n | { kind: 'delete-dataset'; id: string; expectedVersion: string };\n\nexport type EvaluationLibraryMutation = {\n changes: EvaluationLibraryMutationChange[];\n};\n\nexport type EvaluationLibraryConflictResource = {\n kind: EvaluationLibraryResourceKind;\n id: string;\n expectedVersion: string | null;\n currentVersion: string | null;\n};\n\n/**\n * A conflict is deliberately expressed with both values. Hosts use this to\n * present an explicit choice instead of silently overwriting either editor.\n */\nexport type EvaluationLibraryConflictDraft = EvaluationLibraryConflictResource & {\n local: EvaluationLibraryResourceValue;\n server: EvaluationLibraryResourceValue;\n};\n\nexport type EvaluationLibrarySyncIssue =\n | {\n id: string;\n kind: 'conflict';\n message: string;\n conflicts: readonly EvaluationLibraryConflictDraft[];\n }\n | {\n id: string;\n kind: 'retryable' | 'failed';\n message: string;\n };\n\nexport type EvaluationLibraryConflictResolution = {\n issueId: string;\n kind: EvaluationLibraryResourceKind;\n id: string;\n action: 'use-server' | 'keep-mine-as-copy';\n};\n\n/** A host can expose this optional capability without changing local stores. */\nexport type EvaluationLibrarySyncStore = {\n getLibrarySyncSnapshot(): Promise<EvaluationLibrarySyncSnapshot>;\n mutateLibrary(input: EvaluationLibraryMutation): Promise<EvaluationLibrarySyncSnapshot>;\n subscribeLibraryInvalidation?(listener: (invalidation: EvaluationLibraryInvalidation) => void): () => void;\n /** An unresolved hosted save requiring an explicit user decision. */\n subscribeLibrarySyncIssue?(listener: (issue: EvaluationLibrarySyncIssue | undefined) => void): () => void;\n resolveLibraryConflict?(input: EvaluationLibraryConflictResolution): Promise<EvaluationLibrary>;\n retryLibrarySync?(): Promise<EvaluationLibrary>;\n};\n\nexport type EvaluationObservationStatus = 'passed' | 'failed' | 'scored' | 'error' | 'skipped';\n\nexport type EvaluationObservation = {\n id: string;\n kind: 'assertion' | 'graph';\n name: string;\n status: EvaluationObservationStatus;\n required: boolean;\n /**\n * Normalized internal score in the closed 0..1 range. Evaluator graphs\n * return their `result.score` on the user-facing 0..100 scale.\n */\n score?: number;\n /**\n * The configured importance of a graph evaluator's score. It is copied into\n * the observation so a stored run remains interpretable after its suite is\n * edited.\n */\n scoreWeight?: number;\n message?: string;\n evidence?: PortableJson;\n metrics?: Record<string, number>;\n durationMs?: number;\n costUsd?: number;\n /** Privacy-bounded physical provider and profile decisions from this evaluator graph. */\n providerAttempts?: PortableJson;\n /**\n * Replay artifact for this evaluator execution. The serialized recording\n * itself stays in the evaluation run store, never in the project or run\n * summary document.\n */\n recording?: EvaluationRecordingReference;\n};\n\nexport type EvaluationUsage = {\n inputTokens?: number;\n outputTokens?: number;\n cachedInputTokens?: number;\n reasoningTokens?: number;\n modelCallCount?: number;\n toolCallCount?: number;\n toolFailureCount?: number;\n costUsd?: number;\n hasUnknownCost?: boolean;\n};\n\nexport type EvaluationExecutionMetrics = EvaluationUsage & {\n durationMs: number;\n};\n\nexport type EvaluationRunPurpose = 'evaluation' | 'execution-benchmark';\n\nexport type EvaluationTrialExecutionStatus = 'completed' | 'error' | 'canceled';\n\nexport type EvaluationQualityStatus = 'passed' | 'failed' | 'scored' | 'not-evaluated' | 'unable-to-evaluate';\n\nexport type EvaluationAccountingStatus = 'complete' | 'partial';\n\nexport type EvaluationQualityReasonCode =\n | 'in-progress'\n | 'checks-passed'\n | 'checks-failed'\n | 'scores-complete'\n | 'scores-incomplete'\n | 'benchmark'\n | 'no-trial-quality-checks'\n | 'target-error'\n | 'required-check-error'\n | 'required-metric-unavailable'\n | 'thresholds-passed'\n | 'thresholds-failed'\n | 'canceled'\n | 'no-completed-trials';\n\nexport type EvaluationQualityReason = {\n code: EvaluationQualityReasonCode;\n message: string;\n};\n\nexport type EvaluationThresholdResult = {\n id: string;\n metric: string;\n operator: EvaluationThreshold['operator'];\n status: 'passed' | 'failed' | 'unavailable';\n expectedValue: number;\n actualValue?: number;\n baselineValue?: number;\n regression?: number;\n message: string;\n};\n\nexport type EvaluationTrial = {\n id: string;\n caseId: string;\n caseName: string;\n caseIndex: number;\n trialIndex: number;\n executionStatus: EvaluationTrialExecutionStatus;\n qualityStatus: EvaluationQualityStatus;\n qualityReason: EvaluationQualityReason;\n inputs: Record<string, PortableJson>;\n expected: Record<string, PortableJson>;\n outputs: Record<string, PortableJson>;\n observations: EvaluationObservation[];\n targetMetrics: EvaluationExecutionMetrics;\n evaluatorMetrics: EvaluationExecutionMetrics;\n totalMetrics: EvaluationExecutionMetrics;\n error?: string;\n seed?: number;\n recording?: EvaluationRecordingReference;\n /** Privacy-bounded physical provider and profile decisions from the target graph. */\n targetProviderAttempts?: PortableJson;\n};\n\nexport type EvaluationCaseAggregate = {\n caseId: string;\n caseName: string;\n /** Undefined when no trial for this case produced an authoritative quality result. */\n passRate?: number;\n /** Optional so compact baselines written before EvaluationRun v2 remain readable. */\n evaluatedTrialCount?: number;\n passedTrialCount?: number;\n failedTrialCount?: number;\n notEvaluatedTrialCount?: number;\n unableToEvaluateTrialCount?: number;\n erroredTrialCount?: number;\n canceledTrialCount?: number;\n /** Completed trials that produced a usable score in a scoring suite. */\n scoredTrialCount?: number;\n /** Requested trials that could not contribute a score. */\n missingScoreTrialCount?: number;\n /** Normalized internal score in the closed 0..1 range. */\n meanScore?: number;\n metrics: Record<string, number>;\n};\n\nexport type EvaluationAggregate = {\n trialCount: number;\n evaluatedTrialCount: number;\n notEvaluatedTrialCount: number;\n unableToEvaluateTrialCount: number;\n passedTrialCount: number;\n failedTrialCount: number;\n erroredTrialCount: number;\n canceledTrialCount: number;\n /** Completed trials that produced a usable score in a scoring suite. */\n scoredTrialCount?: number;\n /** Requested trials that could not contribute a score. */\n missingScoreTrialCount?: number;\n passRate: number;\n /** Normalized internal score in the closed 0..1 range. */\n meanScore?: number;\n averageLatencyMs: number;\n /** Optional so historical persisted runs without this newer factoid remain readable. */\n medianLatencyMs?: number;\n p95LatencyMs: number;\n /** Score distribution statistics use equal-weight per-case mean scores. */\n medianScore?: number;\n /** Score distribution statistics use equal-weight per-case mean scores. */\n p95Score?: number;\n totalCostUsd?: number;\n averageCostUsd?: number;\n targetErrorRate: number;\n evaluatorErrorRate: number;\n toolFailureRate: number;\n metrics: Record<string, number>;\n};\n\nexport type EvaluationRunProvenance = {\n projectFingerprint: string;\n suiteFingerprint: string;\n datasetFingerprint: string;\n targetFingerprint: string;\n evaluatorFingerprints: Record<string, string>;\n executionMode: string;\n accountingComplete: boolean;\n};\n\nexport type EvaluationRun = {\n version: 2;\n id: string;\n projectId: ProjectId;\n suiteId: string;\n suiteName: string;\n /** Optional user-assigned label for distinguishing retained runs. */\n name?: string;\n /**\n * Monotonically increases while a run is persisted. Stores use it to reject\n * a delayed live-progress write after a newer completed snapshot.\n * Missing means zero for recordings created before this field existed.\n */\n revision?: number;\n startedAt: string;\n completedAt?: string;\n purpose: EvaluationRunPurpose;\n /** Captures the suite semantics that produced this run. */\n evaluationMode?: EvaluationSuiteMode;\n /** Planned target executions, retained so live progress does not depend on a later suite edit. */\n requestedTrialCount?: number;\n executionStatus: 'queued' | 'running' | 'completed' | 'canceled' | 'error';\n qualityStatus: EvaluationQualityStatus;\n qualityReason: EvaluationQualityReason;\n accountingStatus: EvaluationAccountingStatus;\n provenance: EvaluationRunProvenance;\n aggregate?: EvaluationAggregate;\n /** Structured aggregate-threshold evidence for UI, reporters, and retained runs. */\n thresholdResults: EvaluationThresholdResult[];\n trials: EvaluationTrial[];\n warnings: string[];\n};\n\n/**\n * Incremental live-run protocol. A started event carries only the empty run\n * shell, a settled event carries one immutable trial, and the terminal event\n * carries the complete reporting shape once. Consumers that still need full\n * snapshots can use RunEvaluationSuiteOptions.onUpdate during the compatibility\n * period.\n */\nexport type EvaluationRunEvent =\n | {\n type: 'run-started';\n revision: number;\n run: EvaluationRun;\n }\n | {\n type: 'trial-settled';\n revision: number;\n runId: string;\n projectId: ProjectId;\n suiteId: string;\n requestedTrialCount: number;\n settledTrialCount: number;\n trial: EvaluationTrial;\n }\n | {\n type: 'run-finalized';\n revision: number;\n run: EvaluationRun;\n };\n\nexport type EvaluationRecordingReference = {\n id: string;\n retention: 'temporary' | 'failure' | 'baseline' | 'retained';\n expiresAt?: string;\n};\n\n/** A replayable execution artifact owned by an EvaluationRunStore. */\nexport type EvaluationRecordingArtifact = {\n projectId: ProjectId;\n runId: string;\n trialId: string;\n reference: EvaluationRecordingReference;\n /** ExecutionRecorder's compact serialized representation. */\n serialized: string;\n createdAt: string;\n};\n\n/**\n * Immutable, content-addressed copy of the cases used by an evaluation run.\n * It lives with the run history rather than in a compact project baseline, so\n * a later edit to a .rivet-data file cannot rewrite historical evidence.\n */\nexport type EvaluationDatasetSnapshot = {\n projectId: ProjectId;\n fingerprint: string;\n dataset: EvaluationDataset;\n createdAt: string;\n};\n\nexport type EvaluationGraphExecution = {\n outputs: Record<string, PortableJson>;\n metrics: EvaluationExecutionMetrics;\n recording?: EvaluationRecordingReference;\n providerAttempts?: PortableJson;\n};\n\n/**\n * Lets a target adapter preserve its metrics and replay reference when a\n * graph itself fails. The runner still classifies that as a target failure.\n */\nexport class EvaluationGraphExecutionError extends Error {\n readonly metrics?: EvaluationExecutionMetrics;\n readonly recording?: EvaluationRecordingReference;\n readonly providerAttempts?: PortableJson;\n\n constructor(\n message: string,\n details: Partial<Pick<EvaluationGraphExecution, 'metrics' | 'recording' | 'providerAttempts'>> = {},\n ) {\n super(message);\n this.name = 'EvaluationGraphExecutionError';\n this.metrics = details.metrics;\n this.recording = details.recording;\n this.providerAttempts = details.providerAttempts;\n }\n}\n\nexport type EvaluationGraphRunner = (input: {\n project: Project;\n graphId: GraphId;\n inputs: Record<string, PortableJson>;\n signal?: AbortSignal;\n metadata: {\n evaluationRunId: string;\n suiteId: string;\n caseId: string;\n trialIndex: number;\n phase: 'target' | 'evaluator';\n };\n}) => Promise<EvaluationGraphExecution>;\n\nexport type EvaluationRunStore = {\n put(run: EvaluationRun): Promise<void>;\n /** Sets a user-assigned run name; omit the name to restore the Unnamed label. */\n updateRunName(input: { projectId: ProjectId; runId: string; name?: string }): Promise<EvaluationRun | undefined>;\n get(input: { projectId: ProjectId; runId: string }): Promise<EvaluationRun | undefined>;\n list(input: { projectId: ProjectId; suiteId?: string }): Promise<readonly EvaluationRun[]>;\n delete(input: { projectId: ProjectId; runId: string }): Promise<void>;\n /**\n * Persists the first project-scoped snapshot for a dataset fingerprint.\n * Implementations must not rewrite an existing snapshot.\n */\n putDatasetSnapshot(snapshot: EvaluationDatasetSnapshot): Promise<void>;\n getDatasetSnapshot(input: {\n projectId: ProjectId;\n fingerprint: string;\n }): Promise<EvaluationDatasetSnapshot | undefined>;\n putRecording(artifact: EvaluationRecordingArtifact): Promise<void>;\n getRecording(input: { projectId: ProjectId; recordingId: string }): Promise<EvaluationRecordingArtifact | undefined>;\n updateRecordingRetention(input: {\n projectId: ProjectId;\n recordingId: string;\n retention: EvaluationRecordingReference['retention'];\n expiresAt?: string;\n }): Promise<boolean>;\n /** Pins all artifacts belonging to the run before its compact baseline is saved in the project. */\n promoteBaseline(input: { projectId: ProjectId; runId: string }): Promise<void>;\n /**\n * Optional V2 capability. Persists an idempotent incremental lifecycle event\n * so a host can recover settled work after a process interruption.\n */\n applyRunEvent?(event: EvaluationRunEvent): Promise<void>;\n};\n\nexport type EvaluationStoreInitialization = {\n /** A recoverable persistence warning that a host may surface to the user. */\n warning?: string;\n};\n\n/**\n * Complete persistence boundary for Evaluations. Desktop, browser, and hosted\n * Rivet instances implement this same contract so definitions and operational\n * evidence cannot silently land in different stores.\n */\nexport type EvaluationStore = EvaluationRunStore & {\n initialize?(): Promise<EvaluationStoreInitialization | void>;\n getLibrary(): Promise<EvaluationLibrary>;\n putLibrary(library: EvaluationLibrary): Promise<void>;\n /** Optional hosted capability for resource-scoped collaborative saves. */\n getLibrarySyncSnapshot?: EvaluationLibrarySyncStore['getLibrarySyncSnapshot'];\n mutateLibrary?: EvaluationLibrarySyncStore['mutateLibrary'];\n subscribeLibraryInvalidation?: EvaluationLibrarySyncStore['subscribeLibraryInvalidation'];\n subscribeLibrarySyncIssue?: EvaluationLibrarySyncStore['subscribeLibrarySyncIssue'];\n resolveLibraryConflict?: EvaluationLibrarySyncStore['resolveLibraryConflict'];\n retryLibrarySync?: EvaluationLibrarySyncStore['retryLibrarySync'];\n};\n\nexport type EvaluationReporter = {\n report(run: EvaluationRun): Promise<void> | void;\n};\n", "import type { EvaluationDatasetSnapshot, EvaluationRecordingArtifact, PortableJson } from './types.js';\n\nexport function assertPortableJson(\n value: unknown,\n path = '$',\n stack = new Set<object>(),\n): asserts value is PortableJson {\n if (value === null || typeof value === 'string' || typeof value === 'boolean') return;\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) throw new Error(`${path} must not contain a non-finite number.`);\n return;\n }\n if (typeof value !== 'object') throw new Error(`${path} must be portable JSON.`);\n if (stack.has(value)) throw new Error(`${path} must not contain a cycle.`);\n if (Array.isArray(value)) {\n if (Object.getOwnPropertySymbols(value).length > 0) {\n throw new Error(`${path} must not contain symbol-keyed array properties.`);\n }\n stack.add(value);\n try {\n for (let index = 0; index < value.length; index += 1) {\n const descriptor = Object.getOwnPropertyDescriptor(value, index);\n if (!descriptor) throw new Error(`${path}[${index}] must not be a sparse array entry.`);\n if (!descriptor.enumerable || descriptor.get || descriptor.set) {\n throw new Error(`${path}[${index}] must be an enumerable data property.`);\n }\n assertPortableJson(descriptor.value, `${path}[${index}]`, stack);\n }\n if (Object.getOwnPropertyNames(value).length !== value.length + 1) {\n throw new Error(`${path} must not contain hidden or extra array properties.`);\n }\n } finally {\n stack.delete(value);\n }\n return;\n }\n if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) {\n throw new Error(`${path} must be a plain object.`);\n }\n if (Object.getOwnPropertySymbols(value).length > 0) {\n throw new Error(`${path} must not contain symbol-keyed object properties.`);\n }\n const ownPropertyNames = Object.getOwnPropertyNames(value);\n const keys = Object.keys(value);\n if (ownPropertyNames.length !== keys.length) {\n throw new Error(`${path} must not contain non-enumerable object properties.`);\n }\n stack.add(value);\n try {\n for (const key of keys) {\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (!descriptor || descriptor.get || descriptor.set) {\n throw new Error(`${path}.${key} must be an enumerable data property.`);\n }\n assertPortableJson(descriptor.value, `${path}.${key}`, stack);\n }\n } finally {\n stack.delete(value);\n }\n}\n\nexport function canonicalizePortableJson(value: unknown): PortableJson {\n assertPortableJson(value);\n if (value === null || typeof value !== 'object') return value;\n if (Array.isArray(value)) return value.map(canonicalizePortableJson);\n return Object.fromEntries(\n Object.keys(value)\n .sort()\n .map((key) => [key, canonicalizePortableJson(value[key])]),\n );\n}\n\n/**\n * Evaluation inputs and observations cross concurrent graph-run boundaries.\n * Clone them before handing them to an adapter so a Code or evaluator graph\n * cannot mutate a dataset case, another trial, or the persisted run model.\n */\nexport function clonePortableJson<T extends PortableJson>(value: T): T {\n assertPortableJson(value);\n return structuredClone(value);\n}\n\nexport function canonicalStringify(value: unknown): string {\n return JSON.stringify(canonicalizePortableJson(value));\n}\n\n/** Stable, synchronously available content fingerprint for project-local identities. */\nexport function fingerprint(value: unknown): string {\n const source = canonicalStringify(value);\n let hash = 0xcbf29ce484222325n;\n for (let index = 0; index < source.length; index += 1) {\n hash ^= BigInt(source.charCodeAt(index));\n hash = BigInt.asUintN(64, hash * 0x100000001b3n);\n }\n return `fnv1a64:${hash.toString(16).padStart(16, '0')}`;\n}\n\nexport function fingerprintEvaluationDataset(value: { id: unknown; fields: unknown; cases: unknown }): string {\n return fingerprint({ datasetId: value.id, fields: value.fields, cases: value.cases });\n}\n\n/**\n * A dataset fingerprint is the link between a compact run summary and its\n * historical input cases. Stores must reject a mismatched key rather than\n * accepting a snapshot that can no longer prove which cases were run.\n */\nexport function assertEvaluationDatasetSnapshot(snapshot: EvaluationDatasetSnapshot): void {\n if (\n typeof snapshot.projectId !== 'string' ||\n snapshot.projectId.length === 0 ||\n typeof snapshot.fingerprint !== 'string' ||\n snapshot.fingerprint.length === 0 ||\n typeof snapshot.createdAt !== 'string' ||\n !Number.isFinite(Date.parse(snapshot.createdAt))\n ) {\n throw new Error('An evaluation dataset snapshot has invalid identity or creation time.');\n }\n if (snapshot.dataset.projectId !== snapshot.projectId) {\n throw new Error('An evaluation dataset snapshot must belong to its project.');\n }\n if (fingerprintEvaluationDataset(snapshot.dataset) !== snapshot.fingerprint) {\n throw new Error('An evaluation dataset snapshot fingerprint must match its dataset ID, fields, and cases.');\n }\n}\n\n/** Rejects malformed replay evidence at both write and durable-read boundaries. */\nexport function assertEvaluationRecordingArtifact(value: unknown): asserts value is EvaluationRecordingArtifact {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new Error('An evaluation recording artifact must be an object.');\n }\n const artifact = value as Partial<EvaluationRecordingArtifact>;\n if (\n typeof artifact.projectId !== 'string' ||\n artifact.projectId.length === 0 ||\n typeof artifact.runId !== 'string' ||\n artifact.runId.length === 0 ||\n typeof artifact.trialId !== 'string' ||\n artifact.trialId.length === 0 ||\n typeof artifact.serialized !== 'string' ||\n typeof artifact.createdAt !== 'string' ||\n !Number.isFinite(Date.parse(artifact.createdAt))\n ) {\n throw new Error('An evaluation recording artifact has invalid identity, payload, or creation time.');\n }\n const reference = artifact.reference;\n if (\n typeof reference !== 'object' ||\n reference === null ||\n typeof reference.id !== 'string' ||\n reference.id.length === 0 ||\n !['temporary', 'failure', 'baseline', 'retained'].includes(reference.retention ?? '') ||\n (reference.expiresAt !== undefined &&\n (typeof reference.expiresAt !== 'string' || !Number.isFinite(Date.parse(reference.expiresAt))))\n ) {\n throw new Error('An evaluation recording artifact has an invalid retention reference.');\n }\n}\n", "import { assertPortableJson, canonicalStringify } from './canonical.js';\nimport type { EvaluationAssertion, EvaluationDatasetCase, EvaluationObservation, PortableJson } from './types.js';\n\nfunction readQuotedPathKey(source: string, start: number): { key: string; cursor: number } | undefined {\n const quote = source[start];\n if (quote !== '\"' && quote !== \"'\") return undefined;\n let cursor = start + 1;\n let key = '';\n while (cursor < source.length) {\n const character = source[cursor++]!;\n if (character === quote) return { key, cursor };\n if (character !== '\\\\') {\n key += character;\n continue;\n }\n const escaped = source[cursor++];\n if (escaped === undefined) return undefined;\n if (escaped === 'u') {\n const hex = source.slice(cursor, cursor + 4);\n if (!/^[0-9a-fA-F]{4}$/.test(hex)) return undefined;\n key += String.fromCharCode(Number.parseInt(hex, 16));\n cursor += 4;\n continue;\n }\n const escapes: Record<string, string> = {\n '\"': '\"',\n \"'\": \"'\",\n '\\\\': '\\\\',\n '/': '/',\n b: '\\b',\n f: '\\f',\n n: '\\n',\n r: '\\r',\n t: '\\t',\n };\n if (!(escaped in escapes)) return undefined;\n key += escapes[escaped]!;\n }\n return undefined;\n}\n\ntype EvaluationOutputPathSegment = { kind: 'property'; key: string } | { kind: 'index'; index: number };\n\nfunction parseEvaluationOutputPath(path: string): EvaluationOutputPathSegment[] | undefined {\n const source = path.trim();\n if (source === '$') return [];\n if (!source.startsWith('$') || source.length === 1) return undefined;\n let cursor = 1;\n const segments: EvaluationOutputPathSegment[] = [];\n // Validate every character. A partially parsed selector could otherwise\n // assert against a different output than the author wrote (for example\n // `$.answer!`). Dot notation intentionally remains identifier-only; quoted\n // bracket notation covers output names containing spaces, dots, or dashes.\n while (cursor < source.length) {\n if (source[cursor] === '.') {\n cursor += 1;\n while (/\\s/u.test(source[cursor] ?? '')) cursor += 1;\n const identifier = /^[A-Za-z_$][\\w$]*/u.exec(source.slice(cursor));\n if (!identifier) return undefined;\n segments.push({ kind: 'property', key: identifier[0] });\n cursor += identifier[0].length;\n } else if (source[cursor] === '[') {\n cursor += 1;\n while (/\\s/u.test(source[cursor] ?? '')) cursor += 1;\n const quoted = readQuotedPathKey(source, cursor);\n if (quoted) {\n segments.push({ kind: 'property', key: quoted.key });\n cursor = quoted.cursor;\n } else {\n const index = /^\\d+/u.exec(source.slice(cursor));\n if (!index) return undefined;\n segments.push({ kind: 'index', index: Number(index[0]) });\n cursor += index[0].length;\n }\n while (/\\s/u.test(source[cursor] ?? '')) cursor += 1;\n if (source[cursor] !== ']') return undefined;\n cursor += 1;\n } else {\n return undefined;\n }\n }\n return segments;\n}\n\n/**\n * Validates the exact JSON-path subset supported by evaluation assertions.\n * UI authoring and runtime execution intentionally share this parser so a\n * path cannot pass preflight and then resolve with different grammar.\n */\nexport function isEvaluationOutputPathSyntaxValid(path: string): boolean {\n return parseEvaluationOutputPath(path) !== undefined;\n}\n\n/** The Graph Output that owns an assertion path, including nested paths. */\nexport function getEvaluationTopLevelOutputId(path: string): string | undefined {\n const first = parseEvaluationOutputPath(path)?.[0];\n return first?.kind === 'property' ? first.key : undefined;\n}\n\nfunction getPath(value: PortableJson, path: string): PortableJson | undefined {\n const segments = parseEvaluationOutputPath(path);\n if (!segments) return undefined;\n let current: PortableJson | undefined = value;\n for (const segment of segments) {\n if (Array.isArray(current)) {\n if (segment.kind !== 'index') return undefined;\n const index = segment.index;\n if (!Number.isInteger(index) || index < 0 || index >= current.length) return undefined;\n current = current[index];\n continue;\n }\n if (segment.kind !== 'property') return undefined;\n if (current === null || typeof current !== 'object' || !Object.hasOwn(current, segment.key)) return undefined;\n current = current[segment.key];\n }\n return current;\n}\n\nfunction expectedValue(assertion: EvaluationAssertion, testCase: EvaluationDatasetCase): PortableJson {\n if (assertion.expected.kind === 'literal') return assertion.expected.value;\n const value = testCase.values[assertion.expected.fieldId];\n if (value === undefined) throw new Error(`Expected dataset field \"${assertion.expected.fieldId}\" is missing.`);\n return value;\n}\n\nfunction typeMatches(actual: PortableJson | undefined, expected: PortableJson): boolean {\n if (typeof expected !== 'string') return false;\n if (actual === undefined) return false;\n if (expected === 'array') return Array.isArray(actual);\n if (expected === 'null') return actual === null;\n if (expected === 'object') return actual !== null && typeof actual === 'object' && !Array.isArray(actual);\n return typeof actual === expected;\n}\n\nfunction expectedTextList(assertion: EvaluationAssertion, expected: PortableJson): string[] {\n if (!Array.isArray(expected) || expected.length === 0 || expected.some((value) => typeof value !== 'string')) {\n throw new Error(`Quality check \"${assertion.name}\" requires a non-empty array of expected text values.`);\n }\n return expected as string[];\n}\n\nfunction assertionConfigurationError(assertion: EvaluationAssertion, message: string): never {\n throw new Error(`Quality check \"${assertion.name}\" ${message}`);\n}\n\nconst ASSERTION_TYPE_NAMES = new Set(['array', 'boolean', 'null', 'number', 'object', 'string']);\n\nfunction expectedTypeName(assertion: EvaluationAssertion, expected: PortableJson): string {\n if (typeof expected !== 'string' || !ASSERTION_TYPE_NAMES.has(expected)) {\n assertionConfigurationError(\n assertion,\n 'requires one of these expected type names: array, boolean, null, number, object, or string.',\n );\n }\n return expected;\n}\n\nfunction expectedString(assertion: EvaluationAssertion, expected: PortableJson, description: string): string {\n if (typeof expected !== 'string') {\n assertionConfigurationError(assertion, `requires ${description} to be a string.`);\n }\n return expected;\n}\n\nfunction expectedFiniteNumber(assertion: EvaluationAssertion, expected: PortableJson, description: string): number {\n if (typeof expected !== 'number' || !Number.isFinite(expected)) {\n assertionConfigurationError(assertion, `requires ${description} to be a finite number.`);\n }\n return expected;\n}\n\nfunction expectedNumberRange(assertion: EvaluationAssertion, expected: PortableJson): [number, number] {\n if (\n !Array.isArray(expected) ||\n expected.length !== 2 ||\n typeof expected[0] !== 'number' ||\n !Number.isFinite(expected[0]) ||\n typeof expected[1] !== 'number' ||\n !Number.isFinite(expected[1])\n ) {\n assertionConfigurationError(assertion, 'requires an expected range containing exactly two finite numbers.');\n }\n if (expected[0] > expected[1]) {\n assertionConfigurationError(assertion, 'requires its expected range minimum to be no greater than its maximum.');\n }\n return expected as [number, number];\n}\n\nfunction expectedSet(assertion: EvaluationAssertion, expected: PortableJson): PortableJson[] {\n if (!Array.isArray(expected)) assertionConfigurationError(assertion, 'requires the expected set to be an array.');\n return expected;\n}\n\nfunction operatorDescription(operator: EvaluationAssertion['operator']): string {\n switch (operator) {\n case 'equals':\n return 'equals';\n case 'not-equals':\n return 'does not equal';\n case 'contains':\n return 'contains the expected text';\n case 'matches-regex':\n return 'matches the regular expression';\n case 'type-is':\n return 'has the expected type';\n case 'json-schema':\n return 'matches the JSON Schema';\n case 'number-at-least':\n return 'is at least the expected value';\n case 'number-at-most':\n return 'is at most the expected value';\n case 'number-between':\n return 'is inside the expected range';\n case 'array-includes':\n return 'includes the expected value';\n case 'set-overlaps':\n return 'overlaps the expected set';\n case 'contains-any':\n return 'contains any expected text';\n case 'contains-all':\n return 'contains every expected text';\n }\n}\n\n/**\n * Validates author-controlled expected data without needing target outputs.\n * The runner uses this before scheduling work; assertion execution uses the\n * same function so direct callers cannot observe a looser contract.\n */\nexport function validateEvaluationAssertionExpectedValue(\n assertion: EvaluationAssertion,\n expected: PortableJson,\n): void {\n assertPortableJson(expected, `quality check ${assertion.name} expected value`);\n switch (assertion.operator) {\n case 'equals':\n case 'not-equals':\n case 'array-includes':\n return;\n case 'contains':\n expectedString(assertion, expected, 'its expected text');\n return;\n case 'matches-regex': {\n const pattern = expectedString(assertion, expected, 'its expected regular expression');\n try {\n new RegExp(pattern);\n } catch {\n assertionConfigurationError(assertion, 'contains an invalid expected regular expression.');\n }\n return;\n }\n case 'type-is':\n expectedTypeName(assertion, expected);\n return;\n case 'json-schema':\n assertSupportedJsonSchema(assertion, expected);\n return;\n case 'number-at-least':\n expectedFiniteNumber(assertion, expected, 'its expected minimum');\n return;\n case 'number-at-most':\n expectedFiniteNumber(assertion, expected, 'its expected maximum');\n return;\n case 'number-between':\n expectedNumberRange(assertion, expected);\n return;\n case 'set-overlaps':\n expectedSet(assertion, expected);\n return;\n case 'contains-any':\n case 'contains-all':\n expectedTextList(assertion, expected);\n return;\n }\n}\n\nexport function validateEvaluationAssertionConfiguration(\n assertion: EvaluationAssertion,\n expected: PortableJson,\n): void {\n if (!isEvaluationOutputPathSyntaxValid(assertion.outputPath)) {\n assertionConfigurationError(assertion, `uses invalid output path \"${assertion.outputPath}\".`);\n }\n validateEvaluationAssertionExpectedValue(assertion, expected);\n}\n\nconst SUPPORTED_SCHEMA_KEYWORDS = new Set([\n 'type',\n 'enum',\n 'const',\n 'minLength',\n 'maxLength',\n 'pattern',\n 'minimum',\n 'maximum',\n 'minItems',\n 'maxItems',\n 'items',\n 'required',\n 'properties',\n 'additionalProperties',\n]);\nconst SUPPORTED_SCHEMA_TYPES = new Set(['array', 'boolean', 'integer', 'null', 'number', 'object', 'string']);\n\nfunction schemaRecord(\n assertion: EvaluationAssertion,\n schema: PortableJson,\n path: string,\n): Record<string, PortableJson> {\n if (schema === null || typeof schema !== 'object' || Array.isArray(schema)) {\n assertionConfigurationError(assertion, `requires the JSON Schema at ${path} to be an object.`);\n }\n return schema as Record<string, PortableJson>;\n}\n\nfunction assertNonNegativeInteger(\n assertion: EvaluationAssertion,\n value: PortableJson,\n path: string,\n): asserts value is number {\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {\n assertionConfigurationError(assertion, `requires ${path} to be a non-negative safe integer.`);\n }\n}\n\n/**\n * Validates the exact JSON Schema subset implemented below. Rejecting unknown\n * constraints is essential: silently ignoring one can turn a schema that\n * appears strict into a false quality pass.\n */\nfunction assertSupportedJsonSchema(\n assertion: EvaluationAssertion,\n schema: PortableJson,\n path = '$',\n): asserts schema is Record<string, PortableJson> {\n const objectSchema = schemaRecord(assertion, schema, path);\n for (const keyword of Object.keys(objectSchema)) {\n if (!SUPPORTED_SCHEMA_KEYWORDS.has(keyword)) {\n assertionConfigurationError(assertion, `uses unsupported JSON Schema keyword \"${keyword}\" at ${path}.`);\n }\n }\n\n if (objectSchema.type !== undefined) {\n if (typeof objectSchema.type !== 'string' || !SUPPORTED_SCHEMA_TYPES.has(objectSchema.type)) {\n assertionConfigurationError(\n assertion,\n `requires ${path}.type to be one of: array, boolean, integer, null, number, object, or string.`,\n );\n }\n }\n if (objectSchema.enum !== undefined && (!Array.isArray(objectSchema.enum) || objectSchema.enum.length === 0)) {\n assertionConfigurationError(assertion, `requires ${path}.enum to be a non-empty array.`);\n }\n\n for (const keyword of ['minLength', 'maxLength', 'minItems', 'maxItems'] as const) {\n if (objectSchema[keyword] !== undefined)\n assertNonNegativeInteger(assertion, objectSchema[keyword], `${path}.${keyword}`);\n }\n if (\n typeof objectSchema.minLength === 'number' &&\n typeof objectSchema.maxLength === 'number' &&\n objectSchema.minLength > objectSchema.maxLength\n ) {\n assertionConfigurationError(assertion, `requires ${path}.minLength to be no greater than ${path}.maxLength.`);\n }\n if (\n typeof objectSchema.minItems === 'number' &&\n typeof objectSchema.maxItems === 'number' &&\n objectSchema.minItems > objectSchema.maxItems\n ) {\n assertionConfigurationError(assertion, `requires ${path}.minItems to be no greater than ${path}.maxItems.`);\n }\n\n for (const keyword of ['minimum', 'maximum'] as const) {\n const value = objectSchema[keyword];\n if (value !== undefined && (typeof value !== 'number' || !Number.isFinite(value))) {\n assertionConfigurationError(assertion, `requires ${path}.${keyword} to be a finite number.`);\n }\n }\n if (\n typeof objectSchema.minimum === 'number' &&\n typeof objectSchema.maximum === 'number' &&\n objectSchema.minimum > objectSchema.maximum\n ) {\n assertionConfigurationError(assertion, `requires ${path}.minimum to be no greater than ${path}.maximum.`);\n }\n\n if (objectSchema.pattern !== undefined) {\n if (typeof objectSchema.pattern !== 'string') {\n assertionConfigurationError(assertion, `requires ${path}.pattern to be a string.`);\n }\n try {\n new RegExp(objectSchema.pattern);\n } catch {\n assertionConfigurationError(assertion, `contains an invalid regular expression at ${path}.pattern.`);\n }\n }\n if (objectSchema.required !== undefined) {\n if (\n !Array.isArray(objectSchema.required) ||\n objectSchema.required.some((key) => typeof key !== 'string' || key.length === 0) ||\n new Set(objectSchema.required).size !== objectSchema.required.length\n ) {\n assertionConfigurationError(assertion, `requires ${path}.required to contain unique, non-empty strings.`);\n }\n }\n if (objectSchema.additionalProperties !== undefined && typeof objectSchema.additionalProperties !== 'boolean') {\n assertionConfigurationError(assertion, `supports only a boolean ${path}.additionalProperties value.`);\n }\n if (objectSchema.items !== undefined) {\n assertSupportedJsonSchema(assertion, objectSchema.items, `${path}.items`);\n }\n if (objectSchema.properties !== undefined) {\n const properties = schemaRecord(assertion, objectSchema.properties, `${path}.properties`);\n for (const [key, childSchema] of Object.entries(properties)) {\n assertSupportedJsonSchema(assertion, childSchema, `${path}.properties[${JSON.stringify(key)}]`);\n }\n }\n}\n\nfunction schemaTypeMatches(actual: PortableJson, expected: string): boolean {\n if (expected === 'integer') return typeof actual === 'number' && Number.isInteger(actual);\n return typeMatches(actual, expected);\n}\n\n/** Evaluate the validated, deliberately portable JSON Schema subset. */\nfunction matchesSchema(actual: PortableJson | undefined, schema: PortableJson): boolean {\n if (actual === undefined) return false;\n const objectSchema = schema as Record<string, PortableJson>;\n const declaredType = objectSchema.type;\n if (typeof declaredType === 'string' && !schemaTypeMatches(actual, declaredType)) return false;\n if (\n Array.isArray(objectSchema.enum) &&\n !objectSchema.enum.some((candidate) => canonicalStringify(candidate) === canonicalStringify(actual ?? null))\n )\n return false;\n if (\n Object.hasOwn(objectSchema, 'const') &&\n canonicalStringify(objectSchema.const) !== canonicalStringify(actual ?? null)\n )\n return false;\n\n if (typeof actual === 'string') {\n if (typeof objectSchema.minLength === 'number' && actual.length < objectSchema.minLength) return false;\n if (typeof objectSchema.maxLength === 'number' && actual.length > objectSchema.maxLength) return false;\n if (typeof objectSchema.pattern === 'string') {\n if (!new RegExp(objectSchema.pattern).test(actual)) return false;\n }\n }\n if (typeof actual === 'number') {\n if (typeof objectSchema.minimum === 'number' && actual < objectSchema.minimum) return false;\n if (typeof objectSchema.maximum === 'number' && actual > objectSchema.maximum) return false;\n }\n if (Array.isArray(actual)) {\n if (typeof objectSchema.minItems === 'number' && actual.length < objectSchema.minItems) return false;\n if (typeof objectSchema.maxItems === 'number' && actual.length > objectSchema.maxItems) return false;\n if (objectSchema.items !== undefined && !actual.every((item) => matchesSchema(item, objectSchema.items!)))\n return false;\n }\n if (actual !== null && typeof actual === 'object' && !Array.isArray(actual)) {\n const record = actual as Record<string, PortableJson>;\n if (\n Array.isArray(objectSchema.required) &&\n !objectSchema.required.every((key) => typeof key === 'string' && Object.hasOwn(record, key))\n )\n return false;\n const properties = objectSchema.properties;\n if (properties !== undefined) {\n const propertySchemas = properties as Record<string, PortableJson>;\n for (const [key, childSchema] of Object.entries(propertySchemas)) {\n if (Object.hasOwn(record, key) && !matchesSchema(record[key], childSchema)) return false;\n }\n }\n if (objectSchema.additionalProperties === false) {\n const propertySchemas = (properties ?? {}) as Record<string, PortableJson>;\n if (Object.keys(record).some((key) => !Object.hasOwn(propertySchemas, key))) return false;\n }\n }\n return true;\n}\n\nexport function evaluateAssertion(\n assertion: EvaluationAssertion,\n outputs: Record<string, PortableJson>,\n testCase: EvaluationDatasetCase,\n): EvaluationObservation {\n const outputRoot: PortableJson = outputs;\n const actual = getPath(outputRoot, assertion.outputPath);\n const actualFound = actual !== undefined;\n const expected = expectedValue(assertion, testCase);\n validateEvaluationAssertionConfiguration(assertion, expected);\n let passed = false;\n switch (assertion.operator) {\n case 'equals':\n passed = actual !== undefined && canonicalStringify(actual) === canonicalStringify(expected);\n break;\n case 'not-equals':\n // A configured path must resolve before any comparison can pass. Treating\n // a missing value as \"not equal\" would let a typo in an output path turn\n // into a false quality pass.\n passed = actual !== undefined && canonicalStringify(actual) !== canonicalStringify(expected);\n break;\n case 'contains':\n {\n const expectedText = expected as string;\n passed = typeof actual === 'string' && actual.includes(expectedText);\n }\n break;\n case 'matches-regex':\n // Invalid author-supplied expressions are evaluator configuration\n // errors. Let the runner report that quality could not be evaluated instead\n // of reporting a normal failed quality assertion.\n {\n const pattern = new RegExp(expected as string);\n passed = typeof actual === 'string' && pattern.test(actual);\n }\n break;\n case 'type-is':\n passed = typeMatches(actual, expected);\n break;\n case 'json-schema':\n passed = matchesSchema(actual, expected);\n break;\n case 'number-at-least':\n {\n const minimum = expected as number;\n passed = typeof actual === 'number' && actual >= minimum;\n }\n break;\n case 'number-at-most':\n {\n const maximum = expected as number;\n passed = typeof actual === 'number' && actual <= maximum;\n }\n break;\n case 'number-between':\n {\n const [minimum, maximum] = expected as [number, number];\n passed = typeof actual === 'number' && actual >= minimum && actual <= maximum;\n }\n break;\n case 'array-includes':\n passed =\n Array.isArray(actual) && actual.some((item) => canonicalStringify(item) === canonicalStringify(expected));\n break;\n case 'set-overlaps':\n {\n const candidates = expected as PortableJson[];\n passed =\n Array.isArray(actual) &&\n candidates.some((candidate) =>\n actual.some((item) => canonicalStringify(item) === canonicalStringify(candidate)),\n );\n }\n break;\n case 'contains-any':\n {\n const expectedTexts = expected as string[];\n passed = typeof actual === 'string' && expectedTexts.some((candidate) => actual.includes(candidate));\n }\n break;\n case 'contains-all':\n {\n const expectedTexts = expected as string[];\n passed = typeof actual === 'string' && expectedTexts.every((candidate) => actual.includes(candidate));\n }\n break;\n }\n const requirement = operatorDescription(assertion.operator);\n return {\n id: assertion.id,\n kind: 'assertion',\n name: assertion.name,\n required: assertion.required !== false,\n status: passed ? 'passed' : 'failed',\n message: passed\n ? `Target output ${requirement}.`\n : actualFound\n ? `Target output does not satisfy the requirement: ${requirement}.`\n : `Target output path \"${assertion.outputPath}\" does not exist.`,\n evidence: {\n actual: actual ?? null,\n actualFound,\n expected,\n outputPath: assertion.outputPath,\n operator: assertion.operator,\n expectedSource: assertion.expected.kind,\n ...(assertion.expected.kind === 'dataset-field' ? { expectedFieldId: assertion.expected.fieldId } : {}),\n },\n };\n}\n", "import type {\n EvaluationAccountingStatus,\n EvaluationAggregate,\n EvaluationBaselineSnapshot,\n EvaluationQualityReason,\n EvaluationQualityStatus,\n EvaluationRun,\n EvaluationRunPurpose,\n EvaluationSuiteMode,\n EvaluationTrial,\n EvaluationTrialExecutionStatus,\n} from './types.js';\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction isQualityStatus(value: unknown): value is EvaluationQualityStatus {\n return ['passed', 'failed', 'scored', 'not-evaluated', 'unable-to-evaluate'].includes(String(value));\n}\n\nfunction isEvaluationMode(value: unknown): value is EvaluationSuiteMode {\n return value === 'pass-fail' || value === 'scoring';\n}\n\nfunction isQualityStatusForMode(status: EvaluationQualityStatus, evaluationMode: EvaluationSuiteMode): boolean {\n return evaluationMode === 'scoring' ? status !== 'passed' && status !== 'failed' : status !== 'scored';\n}\n\nfunction isExecutionStatus(value: unknown): value is EvaluationTrialExecutionStatus {\n return ['completed', 'error', 'canceled'].includes(String(value));\n}\n\nfunction isRunExecutionStatus(value: unknown): value is EvaluationRun['executionStatus'] {\n return ['queued', 'running', 'completed', 'canceled', 'error'].includes(String(value));\n}\n\nfunction isTerminalRunExecutionStatus(status: EvaluationRun['executionStatus']): boolean {\n return status === 'completed' || status === 'canceled' || status === 'error';\n}\n\nfunction reconcileRecordingReference(\n primary: EvaluationTrial['recording'],\n secondary: EvaluationTrial['recording'],\n): EvaluationTrial['recording'] {\n if (!primary) return secondary;\n if (!secondary) return primary;\n const rank = (retention: NonNullable<EvaluationTrial['recording']>['retention']): number =>\n retention === 'temporary' ? 0 : retention === 'failure' ? 1 : 2;\n return rank(secondary.retention) > rank(primary.retention) ? secondary : primary;\n}\n\n/**\n * Orders snapshots for one run without allowing an equal-revision progress\n * update to demote a terminal result. Writers and delayed UI reads share this\n * rule so persistence cannot disagree with what the workspace presents.\n */\nexport function shouldReplaceEvaluationRun(\n existing: Pick<EvaluationRun, 'executionStatus' | 'revision'> | undefined,\n incoming: Pick<EvaluationRun, 'executionStatus' | 'revision'>,\n): boolean {\n if (!existing) return true;\n const existingRevision = existing.revision ?? 0;\n const incomingRevision = incoming.revision ?? 0;\n if (incomingRevision !== existingRevision) return incomingRevision > existingRevision;\n return (\n !isTerminalRunExecutionStatus(existing.executionStatus) || isTerminalRunExecutionStatus(incoming.executionStatus)\n );\n}\n\n/**\n * Execution snapshots never own a user-assigned run name. Preserve it when a\n * runner publishes a newer progress or terminal revision after a rename.\n */\nexport function preserveEvaluationRunName(\n existing: Pick<EvaluationRun, 'name'> | undefined,\n incoming: EvaluationRun,\n): EvaluationRun {\n return existing?.name !== undefined && incoming.name === undefined ? { ...incoming, name: existing.name } : incoming;\n}\n\n/**\n * Reconciles two snapshots of the same run without discarding evidence.\n *\n * Revisions remain authoritative. Within one revision, however, persistence\n * and recording-retention updates can race with a terminal UI snapshot. Keep\n * the snapshot with the fuller trial set, while still allowing a terminal\n * snapshot to complete a progress snapshot and allowing recording references\n * and warnings to enrich already-settled evidence.\n */\nexport function reconcileEvaluationRunSnapshots(\n existing: EvaluationRun | undefined,\n incoming: EvaluationRun,\n): EvaluationRun {\n if (!existing) return incoming;\n\n const existingRevision = existing.revision ?? 0;\n const incomingRevision = incoming.revision ?? 0;\n if (incomingRevision < existingRevision) return existing;\n if (incomingRevision > existingRevision) return preserveEvaluationRunName(existing, incoming);\n if (!shouldReplaceEvaluationRun(existing, incoming)) return existing;\n\n const existingTerminal = isTerminalRunExecutionStatus(existing.executionStatus);\n const incomingTerminal = isTerminalRunExecutionStatus(incoming.executionStatus);\n const existingTrials = existing.trials ?? [];\n const incomingTrials = incoming.trials ?? [];\n const incomingIsPrimary =\n incomingTerminal !== existingTerminal ? incomingTerminal : incomingTrials.length >= existingTrials.length;\n const primary = preserveEvaluationRunName(existing, incomingIsPrimary ? incoming : existing);\n const secondary = incomingIsPrimary ? existing : incoming;\n const primaryTrials = primary.trials ?? [];\n const secondaryTrialList = secondary.trials ?? [];\n const name = existing.name ?? incoming.name;\n const primaryTrialIds = new Set(primaryTrials.map((trial) => trial.id));\n const secondaryTrials = new Map(secondaryTrialList.map((trial) => [trial.id, trial] as const));\n\n return {\n ...primary,\n trials: [\n ...primaryTrials.map((trial) => {\n const other = secondaryTrials.get(trial.id);\n if (!other) return trial;\n const secondaryObservations = new Map(\n (other.observations ?? []).map((observation) => [observation.id, observation] as const),\n );\n const primaryObservationIds = new Set((trial.observations ?? []).map((observation) => observation.id));\n const recording = reconcileRecordingReference(trial.recording, other.recording);\n return {\n ...trial,\n ...(recording === undefined ? {} : { recording }),\n observations: [\n ...(trial.observations ?? []).map((observation) => {\n const otherObservation = secondaryObservations.get(observation.id);\n const observationRecording = reconcileRecordingReference(\n observation.recording,\n otherObservation?.recording,\n );\n return observationRecording === observation.recording\n ? observation\n : {\n ...observation,\n ...(observationRecording === undefined ? {} : { recording: observationRecording }),\n };\n }),\n ...(other.observations ?? []).filter((observation) => !primaryObservationIds.has(observation.id)),\n ],\n };\n }),\n ...secondaryTrialList.filter((trial) => !primaryTrialIds.has(trial.id)),\n ],\n ...(name === undefined ? {} : { name }),\n warnings: [...new Set([...(primary.warnings ?? []), ...(secondary.warnings ?? [])])],\n };\n}\n\nfunction isPurpose(value: unknown): value is EvaluationRunPurpose {\n return value === 'evaluation' || value === 'execution-benchmark';\n}\n\nfunction isAccountingStatus(value: unknown): value is EvaluationAccountingStatus {\n return value === 'complete' || value === 'partial';\n}\n\n/** Run records keep scores normalized even though evaluator graphs use 0..100. */\nfunction isNormalizedScore(value: unknown): value is number {\n return typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 1;\n}\n\nfunction reasonForQualityStatus(\n status: EvaluationQualityStatus,\n executionStatus?: EvaluationTrialExecutionStatus,\n): EvaluationQualityReason {\n if (executionStatus === 'canceled') return { code: 'canceled', message: 'The execution was canceled.' };\n if (executionStatus === 'error' && status === 'failed') {\n return { code: 'target-error', message: 'The target graph failed before it could produce a valid result.' };\n }\n switch (status) {\n case 'passed':\n return { code: 'checks-passed', message: 'All required quality criteria passed.' };\n case 'failed':\n return { code: 'checks-failed', message: 'One or more required quality criteria failed.' };\n case 'scored':\n return { code: 'scores-complete', message: 'Every requested trial produced a score.' };\n case 'not-evaluated':\n return { code: 'no-trial-quality-checks', message: 'No per-trial quality check evaluated this result.' };\n case 'unable-to-evaluate':\n return { code: 'required-check-error', message: 'A required quality criterion could not be evaluated.' };\n }\n}\n\nfunction reasonForQualityStatusInMode(\n status: EvaluationQualityStatus,\n evaluationMode: EvaluationSuiteMode,\n executionStatus?: EvaluationTrialExecutionStatus,\n): EvaluationQualityReason {\n if (evaluationMode === 'scoring' && status === 'unable-to-evaluate') {\n return { code: 'scores-incomplete', message: 'One or more requested trials did not produce a usable score.' };\n }\n return reasonForQualityStatus(status, executionStatus);\n}\n\nfunction isTargetExecutionError(value: Record<string, unknown>, observations: readonly unknown[]): boolean {\n if (typeof value.error === 'string' && value.error.length > 0) return true;\n return observations.some(\n (observation) =>\n isRecord(observation) &&\n observation.id === 'target-error' &&\n observation.kind === 'assertion' &&\n observation.status === 'error',\n );\n}\n\nfunction legacyQualityFromObservations(\n observations: readonly unknown[],\n targetExecutionError: boolean,\n): EvaluationQualityStatus {\n if (targetExecutionError) return 'failed';\n const required = observations.filter(\n (observation) => isRecord(observation) && observation.required !== false,\n ) as Array<Record<string, unknown>>;\n if (required.some((observation) => observation.status === 'failed')) return 'failed';\n if (required.some((observation) => observation.status === 'error')) return 'unable-to-evaluate';\n if (required.some((observation) => observation.status === 'passed')) return 'passed';\n return 'not-evaluated';\n}\n\n/**\n * Scoring runs are new enough that they do not need to preserve a legacy\n * pass/fail quality label. Do still recover a useful status when a partial or\n * hand-edited scoring record lacks its derived status, but never let an old\n * `passed`/`failed` value leak into the scoring UI.\n */\nfunction scoringQualityFromObservations(observations: readonly unknown[]): EvaluationQualityStatus {\n const evaluatorObservations = observations.filter(\n (observation): observation is Record<string, unknown> => isRecord(observation) && observation.kind === 'graph',\n );\n const hasCompleteScore =\n evaluatorObservations.length > 0 &&\n evaluatorObservations.every(\n (observation) =>\n observation.status === 'scored' &&\n typeof observation.score === 'number' &&\n Number.isFinite(observation.score) &&\n observation.score >= 0 &&\n observation.score <= 1,\n );\n return hasCompleteScore ? 'scored' : 'unable-to-evaluate';\n}\n\nfunction isQualityReasonCompatible(\n reason: EvaluationQualityReason,\n status: EvaluationQualityStatus,\n purpose: EvaluationRunPurpose,\n executionStatus?: EvaluationTrialExecutionStatus | EvaluationRun['executionStatus'],\n): boolean {\n if (purpose === 'execution-benchmark') {\n return executionStatus === 'canceled' ? reason.code === 'canceled' : reason.code === 'benchmark';\n }\n if (executionStatus === 'queued' || executionStatus === 'running') return reason.code === 'in-progress';\n if (executionStatus === 'canceled') return reason.code === 'canceled';\n switch (status) {\n case 'passed':\n return reason.code === 'checks-passed' || reason.code === 'thresholds-passed';\n case 'failed':\n return reason.code === 'checks-failed' || reason.code === 'thresholds-failed' || reason.code === 'target-error';\n case 'scored':\n return reason.code === 'scores-complete';\n case 'not-evaluated':\n return reason.code === 'no-trial-quality-checks' || reason.code === 'no-completed-trials';\n case 'unable-to-evaluate':\n return (\n reason.code === 'required-check-error' ||\n reason.code === 'required-metric-unavailable' ||\n reason.code === 'scores-incomplete'\n );\n }\n}\n\nfunction normalizeQualityReason(\n value: unknown,\n fallback: EvaluationQualityReason,\n status: EvaluationQualityStatus,\n purpose: EvaluationRunPurpose,\n executionStatus?: EvaluationTrialExecutionStatus | EvaluationRun['executionStatus'],\n): EvaluationQualityReason {\n if (!isRecord(value) || typeof value.code !== 'string' || typeof value.message !== 'string') return fallback;\n const reason = value as unknown as EvaluationQualityReason;\n return isQualityReasonCompatible(reason, status, purpose, executionStatus) ? reason : fallback;\n}\n\nexport function normalizeEvaluationTrial(\n value: EvaluationTrial | unknown,\n purpose: EvaluationRunPurpose = 'evaluation',\n evaluationMode: EvaluationSuiteMode = 'pass-fail',\n): EvaluationTrial {\n if (!isRecord(value)) throw new Error('Evaluation trial must be an object.');\n const legacyStatus = value.status;\n const observations = Array.isArray(value.observations) ? value.observations : [];\n const targetExecutionError = isTargetExecutionError(value, observations);\n const executionStatus = isExecutionStatus(value.executionStatus)\n ? value.executionStatus\n : legacyStatus === 'canceled'\n ? 'canceled'\n : targetExecutionError\n ? 'error'\n : legacyStatus === 'error' &&\n !observations.some(\n (observation) =>\n isRecord(observation) && observation.required !== false && observation.status === 'error',\n )\n ? 'error'\n : 'completed';\n const qualityStatus: EvaluationQualityStatus =\n purpose === 'execution-benchmark' || executionStatus === 'canceled'\n ? 'not-evaluated'\n : executionStatus === 'error'\n ? evaluationMode === 'scoring'\n ? 'unable-to-evaluate'\n : 'failed'\n : evaluationMode === 'scoring'\n ? scoringQualityFromObservations(observations)\n : isQualityStatus(value.qualityStatus) && isQualityStatusForMode(value.qualityStatus, evaluationMode)\n ? value.qualityStatus\n : legacyQualityFromObservations(observations, targetExecutionError);\n const normalized = structuredClone(value) as Record<string, unknown>;\n // Legacy runs stored a single status that conflated execution and quality.\n // Read it above, then remove it so normalized v2 values cannot contradict\n // their authoritative executionStatus/qualityStatus pair.\n delete normalized.status;\n return {\n ...(normalized as unknown as EvaluationTrial),\n executionStatus,\n qualityStatus,\n qualityReason: normalizeQualityReason(\n value.qualityReason,\n executionStatus === 'canceled'\n ? { code: 'canceled', message: 'The execution was canceled.' }\n : purpose === 'execution-benchmark'\n ? { code: 'benchmark', message: 'This run measured execution without evaluating output quality.' }\n : reasonForQualityStatusInMode(qualityStatus, evaluationMode, executionStatus),\n qualityStatus,\n purpose,\n executionStatus,\n ),\n };\n}\n\nexport function normalizeEvaluationAggregate(\n value: EvaluationAggregate | unknown,\n trials?: readonly EvaluationTrial[],\n): EvaluationAggregate {\n if (!isRecord(value)) throw new Error('Evaluation aggregate must be an object.');\n const normalized = structuredClone(value) as unknown as EvaluationAggregate;\n // Never let a graph-facing 0..100 value (or corrupt local data) masquerade\n // as the persisted normalized score and render as an impossible 9900/100.\n if (!isNormalizedScore(normalized.meanScore)) delete normalized.meanScore;\n if (!isNormalizedScore(normalized.medianScore)) delete normalized.medianScore;\n if (!isNormalizedScore(normalized.p95Score)) delete normalized.p95Score;\n if (\n typeof normalized.medianLatencyMs !== 'number' ||\n !Number.isFinite(normalized.medianLatencyMs) ||\n normalized.medianLatencyMs < 0\n ) {\n delete normalized.medianLatencyMs;\n }\n if (trials) {\n const completed = trials.filter((trial) => trial.executionStatus === 'completed');\n const evaluated = completed.filter((trial) => trial.qualityStatus === 'passed' || trial.qualityStatus === 'failed');\n const passed = evaluated.filter((trial) => trial.qualityStatus === 'passed');\n const failed = evaluated.filter((trial) => trial.qualityStatus === 'failed');\n const notEvaluated = completed.filter((trial) => trial.qualityStatus === 'not-evaluated');\n const unable = completed.filter((trial) => trial.qualityStatus === 'unable-to-evaluate');\n const scored = completed.filter((trial) => trial.qualityStatus === 'scored');\n return {\n ...normalized,\n trialCount: trials.length,\n evaluatedTrialCount: evaluated.length,\n notEvaluatedTrialCount: notEvaluated.length,\n unableToEvaluateTrialCount: unable.length,\n passedTrialCount: passed.length,\n failedTrialCount: failed.length,\n erroredTrialCount: trials.filter((trial) => trial.executionStatus === 'error').length,\n canceledTrialCount: trials.filter((trial) => trial.executionStatus === 'canceled').length,\n ...(scored.length > 0 || normalized.scoredTrialCount !== undefined\n ? { scoredTrialCount: scored.length, missingScoreTrialCount: trials.length - scored.length }\n : {}),\n passRate: evaluated.length === 0 ? 0 : passed.length / evaluated.length,\n };\n }\n const trialCount = Number(value.trialCount ?? 0);\n const passed = Number(value.passedTrialCount ?? 0);\n const failed = Number(value.failedTrialCount ?? 0);\n const errored = Number(value.erroredTrialCount ?? 0);\n const canceled = Number(value.canceledTrialCount ?? 0);\n const evaluated = Number(value.evaluatedTrialCount ?? passed + failed);\n const unable = Number(value.unableToEvaluateTrialCount ?? 0);\n const notEvaluated = Number(\n value.notEvaluatedTrialCount ?? Math.max(0, trialCount - evaluated - unable - errored - canceled),\n );\n return {\n ...normalized,\n evaluatedTrialCount: evaluated,\n notEvaluatedTrialCount: notEvaluated,\n unableToEvaluateTrialCount: unable,\n passRate: evaluated === 0 ? 0 : passed / evaluated,\n };\n}\n\nfunction withoutAuthoritativeCost(aggregate: EvaluationAggregate): EvaluationAggregate {\n const normalized = { ...aggregate };\n delete normalized.totalCostUsd;\n delete normalized.averageCostUsd;\n return normalized;\n}\n\nexport function normalizeEvaluationBaselineSnapshot(\n value: EvaluationBaselineSnapshot | unknown,\n): EvaluationBaselineSnapshot {\n if (!isRecord(value)) throw new Error('Evaluation baseline snapshot must be an object.');\n const accountingStatus = isAccountingStatus(value.accountingStatus)\n ? value.accountingStatus\n : isRecord(value.provenance) && value.provenance.accountingComplete === false\n ? 'partial'\n : 'complete';\n const aggregate = normalizeEvaluationAggregate(value.aggregate);\n const purpose = isPurpose(value.purpose) ? value.purpose : 'evaluation';\n const evaluationMode = isEvaluationMode(value.evaluationMode) ? value.evaluationMode : 'pass-fail';\n const hasCompleteScoringAggregate =\n aggregate.trialCount > 0 &&\n aggregate.scoredTrialCount === aggregate.trialCount &&\n aggregate.missingScoreTrialCount === 0 &&\n aggregate.meanScore !== undefined;\n const qualityStatus: EvaluationQualityStatus =\n purpose === 'execution-benchmark'\n ? 'not-evaluated'\n : evaluationMode === 'scoring'\n ? hasCompleteScoringAggregate\n ? 'scored'\n : 'unable-to-evaluate'\n : isQualityStatus(value.qualityStatus) && isQualityStatusForMode(value.qualityStatus, evaluationMode)\n ? value.qualityStatus\n : aggregate.failedTrialCount > 0 || aggregate.erroredTrialCount > 0\n ? 'failed'\n : aggregate.evaluatedTrialCount > 0\n ? 'passed'\n : 'not-evaluated';\n const qualityReasonFallback =\n purpose === 'execution-benchmark'\n ? { code: 'benchmark' as const, message: 'This run measured execution without evaluating output quality.' }\n : reasonForQualityStatusInMode(qualityStatus, evaluationMode);\n return {\n ...(structuredClone(value) as unknown as EvaluationBaselineSnapshot),\n purpose,\n evaluationMode,\n qualityStatus,\n qualityReason: normalizeQualityReason(value.qualityReason, qualityReasonFallback, qualityStatus, purpose),\n accountingStatus,\n aggregate: accountingStatus === 'partial' ? withoutAuthoritativeCost(aggregate) : aggregate,\n };\n}\n\nexport function normalizeEvaluationRun(value: EvaluationRun | unknown): EvaluationRun {\n if (!isRecord(value)) throw new Error('Evaluation run must be an object.');\n const purpose = isPurpose(value.purpose) ? value.purpose : 'evaluation';\n const evaluationMode = isEvaluationMode(value.evaluationMode) ? value.evaluationMode : 'pass-fail';\n const executionStatus = isRunExecutionStatus(value.executionStatus)\n ? value.executionStatus\n : typeof value.completedAt === 'string'\n ? 'completed'\n : 'running';\n const trials = Array.isArray(value.trials)\n ? value.trials.map((trial) => normalizeEvaluationTrial(trial, purpose, evaluationMode))\n : [];\n const accountingStatus = isAccountingStatus(value.accountingStatus)\n ? value.accountingStatus\n : isRecord(value.provenance) && value.provenance.accountingComplete === false\n ? 'partial'\n : 'complete';\n let qualityStatus: EvaluationQualityStatus;\n if (purpose === 'execution-benchmark' || executionStatus === 'canceled') {\n qualityStatus = 'not-evaluated';\n } else if (executionStatus === 'error') {\n qualityStatus = evaluationMode === 'scoring' ? 'unable-to-evaluate' : 'failed';\n } else if (executionStatus === 'queued' || executionStatus === 'running') {\n qualityStatus = 'not-evaluated';\n } else if (evaluationMode === 'scoring') {\n const scored = trials.filter((trial) => trial.qualityStatus === 'scored').length;\n qualityStatus = scored > 0 && scored === trials.length ? 'scored' : 'unable-to-evaluate';\n } else if (isQualityStatus(value.qualityStatus) && isQualityStatusForMode(value.qualityStatus, evaluationMode)) {\n qualityStatus = value.qualityStatus;\n } else if (trials.some((trial) => trial.executionStatus === 'error' || trial.qualityStatus === 'failed')) {\n qualityStatus = 'failed';\n } else if (trials.some((trial) => trial.qualityStatus === 'unable-to-evaluate')) {\n qualityStatus = 'unable-to-evaluate';\n } else if (trials.some((trial) => trial.qualityStatus === 'passed')) {\n qualityStatus = 'passed';\n } else if (value.verdict === 'fail') {\n // Old runs could fail an aggregate threshold without having a per-trial\n // quality observation. Preserve that authoritative failure. Only legacy\n // success-without-evidence is reinterpreted as Not evaluated.\n qualityStatus = 'failed';\n } else {\n // Legacy runs used `pass` for a graph that merely completed. If no stored\n // required check proves quality, reinterpret it as Not evaluated instead\n // of preserving the misleading pass label.\n qualityStatus = 'not-evaluated';\n }\n const qualityReasonFallback =\n executionStatus === 'canceled'\n ? { code: 'canceled' as const, message: 'The evaluation run was canceled.' }\n : executionStatus === 'queued' || executionStatus === 'running'\n ? { code: 'in-progress' as const, message: 'The run is still in progress.' }\n : purpose === 'execution-benchmark'\n ? { code: 'benchmark' as const, message: 'This run measured execution without evaluating output quality.' }\n : (executionStatus === 'error' || trials.some((trial) => trial.executionStatus === 'error')) &&\n qualityStatus === 'failed'\n ? { code: 'target-error' as const, message: 'One or more target graph executions failed.' }\n : reasonForQualityStatusInMode(qualityStatus, evaluationMode);\n const provenance = isRecord(value.provenance)\n ? {\n ...structuredClone(value.provenance),\n accountingComplete: accountingStatus === 'complete',\n }\n : value.provenance;\n const normalized = structuredClone(value) as Record<string, unknown>;\n // As with legacy trial.status, the old verdict is input-only compatibility\n // data. New v2 values expose one unambiguous qualityStatus instead.\n delete normalized.verdict;\n const name = typeof value.name === 'string' && value.name.trim().length > 0 ? value.name.trim() : undefined;\n delete normalized.name;\n const requestedTrialCount =\n typeof value.requestedTrialCount === 'number' &&\n Number.isSafeInteger(value.requestedTrialCount) &&\n value.requestedTrialCount >= 0\n ? value.requestedTrialCount\n : undefined;\n delete normalized.requestedTrialCount;\n const aggregate = value.aggregate === undefined ? undefined : normalizeEvaluationAggregate(value.aggregate, trials);\n return {\n ...(normalized as unknown as EvaluationRun),\n version: 2,\n purpose,\n evaluationMode,\n executionStatus,\n qualityStatus,\n qualityReason: normalizeQualityReason(\n value.qualityReason,\n qualityReasonFallback,\n qualityStatus,\n purpose,\n executionStatus,\n ),\n accountingStatus,\n provenance: provenance as EvaluationRun['provenance'],\n trials,\n thresholdResults: Array.isArray(value.thresholdResults)\n ? (structuredClone(value.thresholdResults) as EvaluationRun['thresholdResults'])\n : [],\n ...(name === undefined ? {} : { name }),\n ...(requestedTrialCount === undefined ? {} : { requestedTrialCount }),\n ...(aggregate === undefined\n ? {}\n : { aggregate: accountingStatus === 'partial' ? withoutAuthoritativeCost(aggregate) : aggregate }),\n };\n}\n", "import { assertPortableJson } from './canonical.js';\nimport type { EvaluationDataset, PortableJson } from './types.js';\n\nexport const portableEvaluationDataTypes = [\n 'any',\n 'any[]',\n 'string',\n 'string[]',\n 'date',\n 'date[]',\n 'time',\n 'time[]',\n 'datetime',\n 'datetime[]',\n 'number',\n 'number[]',\n 'vector',\n 'vector[]',\n 'boolean',\n 'boolean[]',\n 'object',\n 'object[]',\n] as const;\n\nconst portableEvaluationDataTypeSet = new Set<string>(portableEvaluationDataTypes);\n\nexport function isPortableEvaluationDataType(dataType: string): boolean {\n return portableEvaluationDataTypeSet.has(dataType);\n}\n\nfunction isObject(value: PortableJson): boolean {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction isFiniteNumber(value: PortableJson): boolean {\n return typeof value === 'number' && Number.isFinite(value);\n}\n\nfunction isArrayOf(value: PortableJson, predicate: (item: PortableJson) => boolean): boolean {\n return Array.isArray(value) && value.every(predicate);\n}\n\n/**\n * Checks a portable dataset value against the Rivet data type selected for an\n * evaluation field. This is shared by authoring UI and execution validation so\n * a value cannot look valid in the editor and then fail under a different rule\n * in the runner.\n */\nexport function isEvaluationValueCompatibleWithDataType(value: PortableJson, dataType: string): boolean {\n try {\n assertPortableJson(value);\n } catch {\n return false;\n }\n\n if (dataType === 'any') return true;\n if (dataType === 'any[]') return Array.isArray(value);\n if (dataType === 'string' || dataType === 'date' || dataType === 'time' || dataType === 'datetime') {\n return typeof value === 'string';\n }\n if (dataType === 'string[]' || dataType === 'date[]' || dataType === 'time[]' || dataType === 'datetime[]') {\n return isArrayOf(value, (item) => typeof item === 'string');\n }\n if (dataType === 'number') return isFiniteNumber(value);\n if (dataType === 'number[]' || dataType === 'vector') return isArrayOf(value, isFiniteNumber);\n if (dataType === 'vector[]') {\n return isArrayOf(value, (item) => isArrayOf(item, isFiniteNumber));\n }\n if (dataType === 'boolean') return typeof value === 'boolean';\n if (dataType === 'boolean[]') return isArrayOf(value, (item) => typeof item === 'boolean');\n if (dataType === 'object') return isObject(value);\n if (dataType === 'object[]') return isArrayOf(value, isObject);\n\n // Functions, binary/media values, and provider-specific structured types\n // do not have a safe portable dataset representation here. Unknown future\n // types must also fail closed until their exact JSON contract is defined.\n return false;\n}\n\n/** Shared declared-type check for graph/dataset binding authoring and execution validation. */\nexport function areEvaluationDataTypesCompatible(sourceDataType: string, targetDataType: string): boolean {\n return sourceDataType === 'any' || targetDataType === 'any' || sourceDataType === targetDataType;\n}\n\n/**\n * Enforces the declared portable JSON contract at explicit transfer\n * boundaries. Durable local drafts remain recoverable even if an older build\n * wrote an unsupported type; imports and exports fail with the precise field\n * and case that needs repair instead of deferring the error until execution.\n */\nexport function assertEvaluationDatasetValuesMatchDeclaredTypes(dataset: EvaluationDataset): void {\n const fieldsById = new Map(dataset.fields.map((field) => [field.id, field]));\n for (const [fieldIndex, field] of dataset.fields.entries()) {\n if (!isPortableEvaluationDataType(field.dataType)) {\n throw new Error(\n `fields[${fieldIndex}].dataType \"${field.dataType}\" has no portable evaluation JSON representation.`,\n );\n }\n }\n\n for (const [caseIndex, testCase] of dataset.cases.entries()) {\n for (const [fieldId, value] of Object.entries(testCase.values)) {\n const field = fieldsById.get(fieldId);\n if (field && !isEvaluationValueCompatibleWithDataType(value, field.dataType)) {\n throw new Error(\n `cases[${caseIndex}].values.${fieldId} is not compatible with declared type \"${field.dataType}\".`,\n );\n }\n }\n }\n}\n", "import {\n evaluateAssertion,\n getEvaluationTopLevelOutputId,\n validateEvaluationAssertionConfiguration,\n} from './assertions.js';\nimport {\n assertPortableJson,\n canonicalStringify,\n clonePortableJson,\n fingerprint,\n fingerprintEvaluationDataset,\n} from './canonical.js';\nimport { normalizeEvaluationRun } from './normalization.js';\nimport { EvaluationGraphExecutionError } from './types.js';\nimport { areEvaluationDataTypesCompatible, isEvaluationValueCompatibleWithDataType } from './dataTypes.js';\nimport type {\n EvaluationAggregate,\n EvaluationBaselineSnapshot,\n EvaluationCaseAggregate,\n EvaluationDataset,\n EvaluationExecutionMetrics,\n EvaluationGraphRunner,\n EvaluationGraphEvaluator,\n EvaluationObservation,\n EvaluationProjectData,\n EvaluationQualityReason,\n EvaluationQualityStatus,\n EvaluationRun,\n EvaluationRunEvent,\n EvaluationRunPurpose,\n EvaluationRunProvenance,\n EvaluationSuite,\n EvaluationSuiteMode,\n EvaluationThreshold,\n EvaluationThresholdResult,\n EvaluationTrial,\n EvaluationTrialExecutionStatus,\n EvaluationRecordingReference,\n PortableJson,\n} from './types.js';\nimport { findAutoDelegateGraphCandidate } from '@valerypopoff/rivet2-core';\nimport type {\n ChartNode,\n GraphId,\n GraphInputNode,\n GraphOutputNode,\n NodeConnection,\n NodeGraph,\n Project,\n} from '@valerypopoff/rivet2-core';\n\nconst DEFAULT_CONCURRENCY = 4;\nconst MAX_CONCURRENCY = 32;\n\nexport const LEGACY_EVALUATOR_INPUT_IDS = ['case', 'inputs', 'expected', 'outputs', 'run'] as const;\n\nexport type RunEvaluationSuiteOptions = {\n project: Project;\n evaluationData: EvaluationProjectData;\n dataset: EvaluationDataset;\n suiteId: string;\n runGraph: EvaluationGraphRunner;\n projectFingerprint?: string;\n executionMode?: string;\n signal?: AbortSignal;\n runId?: string;\n /** An evaluation judges quality; a benchmark deliberately measures execution only. */\n purpose?: EvaluationRunPurpose;\n /** Explicit caller selection; otherwise the suite's saved baseline is used. */\n baseline?: EvaluationBaselineSnapshot;\n /** Incremental live-run transport. Prefer this over onUpdate in new integrations. */\n onEvent?: (event: EvaluationRunEvent) => void | Promise<void>;\n /** @deprecated Prefer onEvent; this clones the complete accumulated run after every trial. */\n onUpdate?: (run: EvaluationRun) => void;\n};\n\nexport function hasAuthoritativeEvaluationCriteria(suite: EvaluationSuite): boolean {\n if (getEvaluationSuiteMode(suite) === 'scoring') return suite.evaluators.length > 0;\n return (\n suite.assertions.some((assertion) => assertion.required !== false) ||\n suite.evaluators.some((evaluator) => evaluator.required !== false) ||\n (suite.thresholds?.length ?? 0) > 0\n );\n}\n\n/** Older saved suites predate scoring and therefore retain pass/fail semantics. */\nexport function getEvaluationSuiteMode(suite: Pick<EvaluationSuite, 'evaluationMode'>): EvaluationSuiteMode {\n return suite.evaluationMode === 'scoring' ? 'scoring' : 'pass-fail';\n}\n\n/** Existing evaluators with the complete reserved-input contract keep working without migration. */\nexport function usesLegacyEvaluatorInputEnvelope(\n evaluator: Pick<EvaluationGraphEvaluator, 'inputBindings'>,\n graphInputIds: readonly string[],\n): boolean {\n return (\n evaluator.inputBindings === undefined &&\n LEGACY_EVALUATOR_INPUT_IDS.every((inputId) => graphInputIds.includes(inputId))\n );\n}\n\n/**\n * Shared bounded work scheduler for evaluation adapters that need stable\n * result ordering without serializing independent cases. It deliberately has\n * no retry policy: callers own their authoritative execution semantics.\n *\n * The result array is aligned to `work`; entries that were still queued when\n * the signal was canceled stay `undefined`. Completed work is never erased.\n */\nexport type RunEvaluationWorkPoolOptions<TWork, TResult> = {\n work: readonly TWork[];\n concurrency: number;\n signal?: AbortSignal;\n execute: (work: TWork, index: number) => Promise<TResult>;\n onSettled?: (result: TResult, index: number, results: readonly (TResult | undefined)[]) => void | Promise<void>;\n};\n\nexport async function runEvaluationWorkPool<TWork, TResult>(\n options: RunEvaluationWorkPoolOptions<TWork, TResult>,\n): Promise<readonly (TResult | undefined)[]> {\n if (!Number.isSafeInteger(options.concurrency) || options.concurrency < 1) {\n throw new Error('Evaluation worker-pool concurrency must be a positive safe integer.');\n }\n const results: Array<TResult | undefined> = Array.from({ length: options.work.length });\n let nextIndex = 0;\n const worker = async () => {\n while (true) {\n // Do not dequeue a new case after cancellation. Active work receives\n // the same signal and may still settle with useful partial evidence.\n if (options.signal?.aborted) return;\n const index = nextIndex++;\n if (index >= options.work.length) return;\n const work = options.work[index]!;\n const result = await options.execute(work, index);\n results[index] = result;\n await options.onSettled?.(result, index, results);\n }\n };\n await Promise.all(Array.from({ length: Math.min(options.concurrency, options.work.length) }, worker));\n return results;\n}\n\nexport function createEmptyMetrics(): EvaluationExecutionMetrics {\n return { durationMs: 0 };\n}\n\nconst executionMetricCountKeys = [\n 'inputTokens',\n 'outputTokens',\n 'cachedInputTokens',\n 'reasoningTokens',\n 'modelCallCount',\n 'toolCallCount',\n 'toolFailureCount',\n] as const;\n\n/**\n * Graph runners are host adapters, so their TypeScript return type is not a\n * runtime trust boundary. Copy only the metrics Rivet understands and reject\n * values that would become `null` or otherwise change during JSON storage.\n */\nfunction cloneExecutionMetrics(value: EvaluationExecutionMetrics, path: string): EvaluationExecutionMetrics {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error(`${path} must be an object.`);\n }\n if (!Number.isFinite(value.durationMs) || value.durationMs < 0) {\n throw new Error(`${path}.durationMs must be a non-negative finite number.`);\n }\n const metrics: EvaluationExecutionMetrics = { durationMs: value.durationMs };\n for (const key of executionMetricCountKeys) {\n const count = value[key];\n if (count === undefined) continue;\n if (!Number.isSafeInteger(count) || count < 0) {\n throw new Error(`${path}.${key} must be a non-negative safe integer.`);\n }\n metrics[key] = count;\n }\n if (value.costUsd !== undefined) {\n if (!Number.isFinite(value.costUsd) || value.costUsd < 0) {\n throw new Error(`${path}.costUsd must be a non-negative finite number.`);\n }\n metrics.costUsd = value.costUsd;\n }\n if (value.hasUnknownCost !== undefined) {\n if (typeof value.hasUnknownCost !== 'boolean') throw new Error(`${path}.hasUnknownCost must be a boolean.`);\n metrics.hasUnknownCost = value.hasUnknownCost;\n }\n return metrics;\n}\n\nfunction tryCloneExecutionMetrics(\n value: EvaluationExecutionMetrics | undefined,\n path: string,\n): EvaluationExecutionMetrics | undefined {\n if (value === undefined) return undefined;\n try {\n return cloneExecutionMetrics(value, path);\n } catch {\n return undefined;\n }\n}\n\nfunction cloneOptionalPortableJson(value: PortableJson | undefined, path: string): PortableJson | undefined {\n if (value === undefined) return undefined;\n assertPortableJson(value, path);\n return clonePortableJson(value);\n}\n\nfunction tryCloneOptionalPortableJson(value: PortableJson | undefined, path: string): PortableJson | undefined {\n try {\n return cloneOptionalPortableJson(value, path);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Resolves the provisional recording references created while a suite is\n * running into its final retention policy. The caller persists the returned\n * references through its EvaluationRunStore.\n *\n * A successful candidate recording remains promotable for 24 hours by\n * default. Failed/error trials are retained, and `all` pins every artifact.\n * This deliberately operates per trial: one failed case must not pin every\n * otherwise-successful recording in the suite.\n */\nexport function finalizeEvaluationRecordingRetention(\n run: EvaluationRun,\n policy: 'failures-and-baselines' | 'all' = 'failures-and-baselines',\n now = Date.now(),\n): EvaluationRun {\n const retainAll = policy === 'all';\n const finalize = (reference: EvaluationRecordingReference, failed: boolean): EvaluationRecordingReference => {\n const retention: EvaluationRecordingReference['retention'] = retainAll\n ? 'retained'\n : failed\n ? 'failure'\n : 'temporary';\n return {\n id: reference.id,\n retention,\n ...(retention === 'temporary' ? { expiresAt: new Date(now + 24 * 60 * 60 * 1000).toISOString() } : {}),\n };\n };\n return {\n ...run,\n trials: run.trials.map((trial) => {\n const targetFailed =\n trial.executionStatus !== 'completed' ||\n trial.observations.some(\n (observation) =>\n observation.kind === 'assertion' &&\n observation.required &&\n (observation.status === 'failed' || observation.status === 'error'),\n );\n return {\n ...trial,\n ...(trial.recording === undefined ? {} : { recording: finalize(trial.recording, targetFailed) }),\n observations: trial.observations.map((observation) => ({\n ...observation,\n ...(observation.recording === undefined\n ? {}\n : {\n recording: finalize(\n observation.recording,\n observation.status === 'failed' || observation.status === 'error',\n ),\n }),\n })),\n };\n }),\n };\n}\n\nfunction mergeMetrics(...metrics: EvaluationExecutionMetrics[]): EvaluationExecutionMetrics {\n const numberKeys: Array<keyof EvaluationExecutionMetrics> = [\n 'durationMs',\n 'inputTokens',\n 'outputTokens',\n 'cachedInputTokens',\n 'reasoningTokens',\n 'modelCallCount',\n 'toolCallCount',\n 'toolFailureCount',\n 'costUsd',\n ];\n const merged: EvaluationExecutionMetrics = { durationMs: 0 };\n for (const key of numberKeys) {\n const value = metrics.reduce((sum, item) => sum + ((item[key] as number | undefined) ?? 0), 0);\n if (value !== 0 || key === 'durationMs') (merged as Record<string, unknown>)[key] = value;\n }\n if (metrics.some((item) => item.hasUnknownCost)) merged.hasUnknownCost = true;\n return merged;\n}\n\nfunction makeId(prefix: string): string {\n const cryptoValue = globalThis.crypto;\n if (cryptoValue?.randomUUID) return `${prefix}-${cryptoValue.randomUUID()}`;\n return `${prefix}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;\n}\n\nfunction toErrorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction throwIfAborted(signal?: AbortSignal): void {\n if (signal?.aborted) throw signal.reason ?? new DOMException('Evaluation canceled.', 'AbortError');\n}\n\nfunction isAbort(error: unknown): boolean {\n return (\n (error instanceof DOMException && error.name === 'AbortError') ||\n (typeof error === 'object' &&\n error !== null &&\n 'name' in error &&\n (error as { name?: unknown }).name === 'AbortError')\n );\n}\n\nfunction resolveSuite(data: EvaluationProjectData, id: string): EvaluationSuite {\n const suite = data.suites.find((candidate) => candidate.id === id);\n if (!suite) throw new Error(`Evaluation suite \"${id}\" does not exist.`);\n return suite;\n}\n\nfunction validateDefinitionIds(suite: EvaluationSuite): void {\n const seen = new Map<string, string>();\n for (const [kind, definitions] of [\n ['quality check', suite.assertions],\n ['evaluator graph', suite.evaluators],\n ['threshold', suite.thresholds ?? []],\n ] as const) {\n for (const definition of definitions) {\n if (typeof definition.id !== 'string' || definition.id.trim().length === 0) {\n throw new Error(`Every evaluation ${kind} must have a non-empty id.`);\n }\n const previous = seen.get(definition.id);\n if (previous) {\n throw new Error(`Evaluation ${kind} id \"${definition.id}\" duplicates a ${previous} id.`);\n }\n seen.set(definition.id, kind);\n }\n }\n}\n\nconst rateThresholdMetrics = new Set([\n 'pass-rate',\n 'mean-score',\n 'target-error-rate',\n 'evaluator-error-rate',\n 'tool-failure-rate',\n]);\n\nfunction formatThresholdResultValue(metric: string, operator: EvaluationThreshold['operator'], value: number): string {\n return operator === 'max-regression' || rateThresholdMetrics.has(metric)\n ? `${Number((value * 100).toFixed(4))}%`\n : String(value);\n}\n\nfunction validateThresholdConfiguration(threshold: EvaluationThreshold): void {\n const { metric, operator, value } = threshold as EvaluationThreshold & {\n metric: string;\n operator: string;\n value: number;\n };\n if (typeof metric !== 'string' || metric.length === 0) {\n throw new Error(`Evaluation threshold \"${threshold.id}\" must select a metric.`);\n }\n if (typeof operator !== 'string') {\n throw new Error(`Evaluation threshold \"${threshold.id}\" must select an operator.`);\n }\n if (!Number.isFinite(value)) throw new Error(`Evaluation threshold \"${threshold.id}\" must use a finite value.`);\n\n if (rateThresholdMetrics.has(metric) && (value < 0 || value > 1)) {\n throw new Error(`Evaluation threshold \"${threshold.id}\" must use a value from 0 to 1.`);\n }\n if (['average-cost', 'total-cost', 'average-latency-ms', 'p95-latency-ms'].includes(metric) && value < 0) {\n throw new Error(`Evaluation threshold \"${threshold.id}\" cannot use a negative value.`);\n }\n if (operator === 'max-regression') {\n if (value < 0) throw new Error(`Evaluation regression threshold \"${threshold.id}\" cannot be negative.`);\n return;\n }\n const expectedOperator =\n metric === 'pass-rate' || metric === 'mean-score'\n ? 'at-least'\n : metric.startsWith('custom:')\n ? undefined\n : 'at-most';\n if (\n (expectedOperator !== undefined && operator !== expectedOperator) ||\n (expectedOperator === undefined && operator !== 'at-least' && operator !== 'at-most')\n ) {\n throw new Error(`Evaluation threshold \"${threshold.id}\" uses an incompatible operator for \"${metric}\".`);\n }\n}\n\nfunction validateSuite(\n project: Project,\n suite: EvaluationSuite,\n dataset: EvaluationDataset,\n purpose: EvaluationRunPurpose,\n): void {\n const evaluationMode = getEvaluationSuiteMode(suite);\n validateDefinitionIds(suite);\n if (dataset.projectId !== undefined && dataset.projectId !== project.metadata.id) {\n throw new Error(`Evaluation dataset \"${dataset.name}\" belongs to a different project.`);\n }\n if (suite.datasetId !== dataset.id)\n throw new Error(`Suite \"${suite.name}\" is bound to a different evaluation dataset.`);\n const graph = project.graphs[suite.targetGraphId];\n if (!graph) throw new Error(`Target graph \"${suite.targetGraphId}\" does not exist.`);\n const graphInputs = graph.nodes.filter((node): node is GraphInputNode => node.type === 'graphInput');\n const graphInputIds = graphInputs.map((input) => input.data.id);\n if (new Set(graphInputIds).size !== graphInputIds.length) {\n throw new Error(`Target graph \"${suite.targetGraphId}\" has duplicate Graph Input ids.`);\n }\n const graphOutputs = graph.nodes.filter((node): node is GraphOutputNode => node.type === 'graphOutput');\n const graphOutputIds = graphOutputs.map((output) => output.data.id);\n if (new Set(graphOutputIds).size !== graphOutputIds.length) {\n throw new Error(`Target graph \"${suite.targetGraphId}\" has duplicate Graph Output ids.`);\n }\n const inputIds = new Set(graphInputIds);\n const graphInputsById = new Map(graphInputs.map((input) => [input.data.id, input]));\n const fields = new Map(dataset.fields.map((field) => [field.id, field]));\n if (fields.size !== dataset.fields.length)\n throw new Error(`Evaluation dataset \"${dataset.name}\" has duplicate field ids.`);\n const boundGraphInputs = new Set<string>();\n for (const binding of suite.inputBindings) {\n if (boundGraphInputs.has(binding.graphInputId)) {\n throw new Error(`Target graph input \"${binding.graphInputId}\" is bound more than once.`);\n }\n boundGraphInputs.add(binding.graphInputId);\n if (!inputIds.has(binding.graphInputId))\n throw new Error(`Graph input \"${binding.graphInputId}\" does not exist on the target graph.`);\n const field = fields.get(binding.datasetFieldId);\n if (!field) throw new Error(`Evaluation dataset field \"${binding.datasetFieldId}\" does not exist.`);\n if (field.role !== 'input')\n throw new Error(`Dataset field \"${field.name}\" must have the input role to bind it to a graph input.`);\n const graphInput = graphInputsById.get(binding.graphInputId)!;\n if (!areEvaluationDataTypesCompatible(field.dataType, graphInput.data.dataType)) {\n throw new Error(\n `Dataset field \"${field.name}\" (${field.dataType}) is not compatible with graph input \"${graphInput.data.id}\" (${graphInput.data.dataType}).`,\n );\n }\n }\n for (const input of graphInputs) {\n if (suite.inputBindings.some((binding) => binding.graphInputId === input.data.id)) continue;\n // A connection-driven default cannot be proven before executing the graph;\n // require an explicit dataset binding in that case instead of quietly\n // fabricating a value from the input data type.\n if (input.data.defaultValue === undefined || input.data.useDefaultValueInput) {\n throw new Error(\n `Target graph input \"${input.data.id}\" must be bound to an evaluation dataset field or have a static graph default.`,\n );\n }\n }\n\n // Validate every enabled case before the worker pool starts. The declared\n // field type is part of the dataset contract even when that field is not\n // bound directly to the target graph (for example evaluator metadata).\n for (const testCase of dataset.cases.filter((candidate) => candidate.enabled !== false)) {\n for (const [fieldId, value] of Object.entries(testCase.values)) {\n const field = fields.get(fieldId);\n if (!field) {\n throw new Error(`Case \"${testCase.name}\" supplies unknown dataset field \"${fieldId}\".`);\n }\n assertPortableJson(value, `case.${testCase.id}.${fieldId}`);\n if (!isEvaluationValueCompatibleWithDataType(value, field.dataType)) {\n throw new Error(\n `Case \"${testCase.name}\" value for \"${field.name}\" is not compatible with its declared ${field.dataType} type.`,\n );\n }\n }\n for (const binding of suite.inputBindings) {\n const value = testCase.values[binding.datasetFieldId];\n if (value === undefined) {\n const field = fields.get(binding.datasetFieldId)!;\n throw new Error(`Case \"${testCase.name}\" has no saved value for bound input field \"${field.name}\".`);\n }\n const graphInput = graphInputsById.get(binding.graphInputId)!;\n if (!isEvaluationValueCompatibleWithDataType(value, graphInput.data.dataType)) {\n throw new Error(\n `Case \"${testCase.name}\" value for \"${binding.datasetFieldId}\" is not compatible with target graph input \"${binding.graphInputId}\" (${graphInput.data.dataType}).`,\n );\n }\n }\n for (const field of dataset.fields) {\n const requiredForThisRun = field.required && (purpose === 'evaluation' || field.role === 'input');\n if (requiredForThisRun && testCase.values[field.id] === undefined) {\n throw new Error(`Case \"${testCase.name}\" is missing required field \"${field.name}\".`);\n }\n }\n }\n if (purpose === 'evaluation' && evaluationMode === 'pass-fail') {\n for (const assertion of suite.assertions) {\n const outputId = getEvaluationTopLevelOutputId(assertion.outputPath);\n if (assertion.outputPath.trim() !== '$' && outputId === undefined) {\n throw new Error(`Assertion \"${assertion.name}\" output path must start with a named target Graph Output.`);\n }\n if (outputId !== undefined && !graphOutputIds.includes(outputId)) {\n throw new Error(`Assertion \"${assertion.name}\" references missing target output \"${outputId}\".`);\n }\n if (assertion.expected.kind === 'dataset-field') {\n const field = fields.get(assertion.expected.fieldId);\n if (!field) throw new Error(`Assertion \"${assertion.name}\" references a missing expected dataset field.`);\n if (field.role !== 'expected')\n throw new Error(`Assertion \"${assertion.name}\" must reference a dataset field with the expected role.`);\n for (const testCase of dataset.cases.filter((candidate) => candidate.enabled !== false)) {\n const expected = testCase.values[field.id];\n if (expected === undefined) {\n throw new Error(`Case \"${testCase.name}\" is missing expected field \"${field.name}\".`);\n }\n validateEvaluationAssertionConfiguration(assertion, expected);\n }\n } else {\n validateEvaluationAssertionConfiguration(assertion, assertion.expected.value);\n }\n }\n }\n if (suite.configuration?.seed !== undefined) {\n const seedInputId = suite.configuration.seedGraphInputId;\n if (!seedInputId) throw new Error('A suite seed requires selecting the target graph input that receives it.');\n const seedInput = graphInputsById.get(seedInputId);\n if (!seedInput)\n throw new Error(`The selected seed graph input \"${seedInputId}\" does not exist on the target graph.`);\n if (seedInput.data.dataType !== 'number' && seedInput.data.dataType !== 'any') {\n throw new Error(`The selected seed graph input \"${seedInputId}\" must accept a number.`);\n }\n if (suite.inputBindings.some((binding) => binding.graphInputId === seedInputId)) {\n throw new Error(`The selected seed graph input \"${seedInputId}\" cannot also be bound to a dataset field.`);\n }\n }\n for (const evaluator of purpose === 'evaluation' ? suite.evaluators : []) {\n if (\n evaluator.scoreWeight !== undefined &&\n (!Number.isFinite(evaluator.scoreWeight) || evaluator.scoreWeight <= 0)\n ) {\n throw new Error(`Evaluator graph \"${evaluator.name}\" score weight must be a positive finite number.`);\n }\n const evaluatorGraph = project.graphs[evaluator.graphId];\n if (!evaluatorGraph) throw new Error(`Evaluator graph \"${evaluator.graphId}\" does not exist.`);\n const evaluatorGraphInputs = evaluatorGraph.nodes.filter(\n (node): node is GraphInputNode => node.type === 'graphInput',\n );\n const evaluatorInputIds = evaluatorGraphInputs.map((input) => input.data.id);\n if (new Set(evaluatorInputIds).size !== evaluatorInputIds.length) {\n throw new Error(`Evaluator graph \"${evaluator.name}\" has duplicate Graph Input ids.`);\n }\n const evaluatorOutputIds = evaluatorGraph.nodes\n .filter((node): node is GraphOutputNode => node.type === 'graphOutput')\n .map((output) => output.data.id);\n if (new Set(evaluatorOutputIds).size !== evaluatorOutputIds.length) {\n throw new Error(`Evaluator graph \"${evaluator.name}\" has duplicate Graph Output ids.`);\n }\n const evaluatorInputsById = new Map(evaluatorGraphInputs.map((input) => [input.data.id, input]));\n const usesLegacyInputs = usesLegacyEvaluatorInputEnvelope(evaluator, evaluatorInputIds);\n if (usesLegacyInputs) {\n for (const inputId of LEGACY_EVALUATOR_INPUT_IDS) {\n const evaluatorInput = evaluatorInputsById.get(inputId)!;\n if (evaluatorInput.data.dataType !== 'object' && evaluatorInput.data.dataType !== 'any') {\n throw new Error(\n `Evaluator graph \"${evaluator.name}\" legacy input \"${inputId}\" must accept the object or any data type.`,\n );\n }\n }\n for (const evaluatorInput of evaluatorGraphInputs) {\n if (\n LEGACY_EVALUATOR_INPUT_IDS.includes(evaluatorInput.data.id as (typeof LEGACY_EVALUATOR_INPUT_IDS)[number])\n ) {\n continue;\n }\n if (evaluatorInput.data.defaultValue === undefined || evaluatorInput.data.useDefaultValueInput) {\n throw new Error(\n `Evaluator graph \"${evaluator.name}\" input \"${evaluatorInput.data.id}\" needs a direct binding or a static graph default.`,\n );\n }\n }\n } else {\n const evaluatorBindings = evaluator.inputBindings ?? [];\n const boundEvaluatorInputs = new Set<string>();\n for (const binding of evaluatorBindings) {\n if (boundEvaluatorInputs.has(binding.graphInputId)) {\n throw new Error(\n `Evaluator graph \"${evaluator.name}\" input \"${binding.graphInputId}\" is bound more than once.`,\n );\n }\n boundEvaluatorInputs.add(binding.graphInputId);\n const evaluatorInput = evaluatorInputsById.get(binding.graphInputId);\n if (!evaluatorInput) {\n throw new Error(\n `Evaluator graph \"${evaluator.name}\" input \"${binding.graphInputId}\" does not exist on the selected graph.`,\n );\n }\n\n let sourceDataType: string;\n if (binding.source.kind === 'dataset-field') {\n const field = fields.get(binding.source.fieldId);\n if (!field) {\n throw new Error(\n `Evaluator graph \"${evaluator.name}\" binding references missing dataset field \"${binding.source.fieldId}\".`,\n );\n }\n sourceDataType = field.dataType;\n for (const testCase of dataset.cases.filter((candidate) => candidate.enabled !== false)) {\n const value = testCase.values[field.id];\n if (value === undefined) {\n throw new Error(\n `Case \"${testCase.name}\" has no saved value for evaluator input \"${binding.graphInputId}\" from dataset field \"${field.name}\".`,\n );\n }\n if (!isEvaluationValueCompatibleWithDataType(value, evaluatorInput.data.dataType)) {\n throw new Error(\n `Case \"${testCase.name}\" value from dataset field \"${field.name}\" is not compatible with evaluator input \"${binding.graphInputId}\" (${evaluatorInput.data.dataType}).`,\n );\n }\n }\n } else if (binding.source.kind === 'target-output') {\n const outputId = binding.source.outputId;\n const targetOutput = graph.nodes.find(\n (node): node is GraphOutputNode =>\n node.type === 'graphOutput' && (node.data as { id?: unknown }).id === outputId,\n );\n if (!targetOutput) {\n throw new Error(\n `Evaluator graph \"${evaluator.name}\" binding references missing target output \"${outputId}\".`,\n );\n }\n sourceDataType = targetOutput.data.dataType;\n } else if (binding.source.kind === 'context') {\n sourceDataType = 'object';\n } else {\n throw new Error(\n `Evaluator graph \"${evaluator.name}\" input \"${binding.graphInputId}\" uses an unsupported source.`,\n );\n }\n if (!areEvaluationDataTypesCompatible(sourceDataType, evaluatorInput.data.dataType)) {\n throw new Error(\n `Evaluator graph \"${evaluator.name}\" source for input \"${binding.graphInputId}\" (${sourceDataType}) is not compatible with ${evaluatorInput.data.dataType}.`,\n );\n }\n }\n for (const evaluatorInput of evaluatorGraphInputs) {\n if (boundEvaluatorInputs.has(evaluatorInput.data.id)) continue;\n if (evaluatorInput.data.defaultValue === undefined || evaluatorInput.data.useDefaultValueInput) {\n throw new Error(\n `Evaluator graph \"${evaluator.name}\" input \"${evaluatorInput.data.id}\" must be bound to a target output, dataset field, or evaluation context value, or have a static graph default.`,\n );\n }\n }\n }\n const resultOutput = evaluatorGraph.nodes.find(\n (node): node is GraphOutputNode => node.type === 'graphOutput' && (node.data as { id?: unknown }).id === 'result',\n );\n if (!resultOutput) {\n throw new Error(`Evaluator graph \"${evaluator.name}\" must declare a Graph Output named \"result\".`);\n }\n if (resultOutput.data.dataType !== 'object' && resultOutput.data.dataType !== 'any') {\n throw new Error(`Evaluator graph \"${evaluator.name}\" output \"result\" must have the object data type.`);\n }\n }\n\n if (purpose === 'evaluation' && evaluationMode === 'pass-fail') {\n const hasRequiredPerTrialCheck =\n suite.assertions.some((assertion) => assertion.required !== false) ||\n suite.evaluators.some((evaluator) => evaluator.required !== false);\n const hasEvaluator = suite.evaluators.length > 0;\n for (const threshold of suite.thresholds ?? []) {\n validateThresholdConfiguration(threshold);\n const metric = threshold.metric;\n const supportedExecutionMetric = [\n 'target-error-rate',\n 'tool-failure-rate',\n 'average-cost',\n 'total-cost',\n 'average-latency-ms',\n 'p95-latency-ms',\n ].includes(metric);\n const supportedEvaluatorMetric =\n metric === 'mean-score' ||\n metric === 'evaluator-error-rate' ||\n (metric.startsWith('custom:') && metric.length > 'custom:'.length);\n if (metric === 'pass-rate' && !hasRequiredPerTrialCheck) {\n throw new Error('A pass-rate threshold requires at least one required quality check or evaluator graph.');\n }\n if (supportedEvaluatorMetric && !hasEvaluator) {\n throw new Error(`The \"${metric}\" threshold requires at least one evaluator graph.`);\n }\n if (metric !== 'pass-rate' && !supportedExecutionMetric && !supportedEvaluatorMetric) {\n throw new Error(`Evaluation threshold metric \"${metric}\" is not supported.`);\n }\n }\n } else if (purpose === 'evaluation' && suite.evaluators.length === 0) {\n throw new Error('A scoring evaluation suite requires at least one evaluator graph.');\n }\n\n const caseIds = new Set(dataset.cases.map((testCase) => testCase.id));\n if (caseIds.size !== dataset.cases.length)\n throw new Error(`Evaluation dataset \"${dataset.name}\" has duplicate case ids.`);\n\n if (!dataset.cases.some((testCase) => testCase.enabled !== false)) {\n throw new Error(`Evaluation dataset \"${dataset.name}\" has no enabled cases.`);\n }\n\n const configuration = suite.configuration;\n if (\n configuration?.trialCount !== undefined &&\n (!Number.isSafeInteger(configuration.trialCount) || configuration.trialCount < 1)\n ) {\n throw new Error('Evaluation trial count must be a positive safe integer.');\n }\n if (\n configuration?.concurrency !== undefined &&\n (!Number.isSafeInteger(configuration.concurrency) ||\n configuration.concurrency < 1 ||\n configuration.concurrency > MAX_CONCURRENCY)\n ) {\n throw new Error(`Evaluation concurrency must be a whole number from 1 to ${MAX_CONCURRENCY}.`);\n }\n if (\n configuration?.timeoutMs !== undefined &&\n (!Number.isFinite(configuration.timeoutMs) || configuration.timeoutMs <= 0)\n ) {\n throw new Error('Evaluation timeout must be a positive number of milliseconds.');\n }\n if (configuration?.seed !== undefined && (!Number.isSafeInteger(configuration.seed) || configuration.seed < 0)) {\n throw new Error('Evaluation seed must be a non-negative safe integer.');\n }\n}\n\nfunction resolveCaseInputs(\n suite: EvaluationSuite,\n dataset: EvaluationDataset,\n testCase: EvaluationDataset['cases'][number],\n purpose: EvaluationRunPurpose,\n): {\n inputs: Record<string, PortableJson>;\n expected: Record<string, PortableJson>;\n} {\n const fields = new Map(dataset.fields.map((field) => [field.id, field]));\n const inputs: Record<string, PortableJson> = {};\n const expected: Record<string, PortableJson> = {};\n for (const field of dataset.fields) {\n const value = testCase.values[field.id];\n if (value === undefined) {\n const requiredForThisRun = field.required && (purpose === 'evaluation' || field.role === 'input');\n if (requiredForThisRun) {\n throw new Error(`Case \"${testCase.name}\" is missing required field \"${field.name}\".`);\n }\n continue;\n }\n assertPortableJson(value, `case.${field.id}`);\n if (field.role === 'expected') expected[field.id] = clonePortableJson(value);\n }\n for (const binding of suite.inputBindings) {\n const field = fields.get(binding.datasetFieldId)!;\n const value = testCase.values[field.id];\n if (value === undefined) {\n throw new Error(`Case \"${testCase.name}\" has no saved value for bound input field \"${field.name}\".`);\n }\n if (!isEvaluationValueCompatibleWithDataType(value, field.dataType)) {\n throw new Error(\n `Case \"${testCase.name}\" input \"${field.name}\" is not compatible with its declared ${field.dataType} type.`,\n );\n }\n inputs[binding.graphInputId] = clonePortableJson(value);\n }\n return { inputs, expected };\n}\n\n/**\n * Evaluators need the case identity and tags as well as its field values. Do\n * not pass the mutable dataset case object itself: this portable snapshot is\n * the stable evaluator-graph contract for a particular trial.\n */\nfunction createEvaluatorCaseInput(testCase: EvaluationDataset['cases'][number]): PortableJson {\n return {\n id: testCase.id,\n name: testCase.name,\n enabled: testCase.enabled !== false,\n ...(testCase.tags === undefined ? {} : { tags: [...testCase.tags] }),\n ...(testCase.note === undefined ? {} : { note: testCase.note }),\n values: clonePortableJson(testCase.values),\n };\n}\n\nfunction createEvaluatorGraphInputs(input: {\n evaluator: EvaluationGraphEvaluator;\n project: Project;\n testCase: EvaluationDataset['cases'][number];\n targetInputs: Record<string, PortableJson>;\n expected: Record<string, PortableJson>;\n targetOutputs: Record<string, PortableJson>;\n run: PortableJson;\n}): Record<string, PortableJson> {\n const { evaluator, project, testCase, targetInputs, expected, targetOutputs, run } = input;\n const contextValues = {\n case: createEvaluatorCaseInput(testCase),\n inputs: clonePortableJson(targetInputs),\n expected: clonePortableJson(expected),\n outputs: clonePortableJson(targetOutputs),\n run: clonePortableJson(run),\n } satisfies Record<(typeof LEGACY_EVALUATOR_INPUT_IDS)[number], PortableJson>;\n const evaluatorGraphInputs =\n project.graphs[evaluator.graphId]?.nodes.filter((node): node is GraphInputNode => node.type === 'graphInput') ?? [];\n const evaluatorGraphInputIds = evaluatorGraphInputs.map((node) => node.data.id);\n if (usesLegacyEvaluatorInputEnvelope(evaluator, evaluatorGraphInputIds)) return contextValues;\n const evaluatorInputsById = new Map(evaluatorGraphInputs.map((node) => [node.data.id, node]));\n\n const evaluatorInputs: Record<string, PortableJson> = {};\n for (const binding of evaluator.inputBindings ?? []) {\n if (binding.source.kind === 'dataset-field') {\n const value = testCase.values[binding.source.fieldId];\n if (value === undefined) {\n throw new Error(\n `Case \"${testCase.name}\" has no value for evaluator input \"${binding.graphInputId}\" from dataset field \"${binding.source.fieldId}\".`,\n );\n }\n evaluatorInputs[binding.graphInputId] = clonePortableJson(value);\n } else if (binding.source.kind === 'target-output') {\n if (!Object.hasOwn(targetOutputs, binding.source.outputId)) {\n throw new Error(\n `Target graph did not produce output \"${binding.source.outputId}\" required by evaluator input \"${binding.graphInputId}\".`,\n );\n }\n const targetOutputValue = targetOutputs[binding.source.outputId]!;\n const evaluatorInput = evaluatorInputsById.get(binding.graphInputId);\n if (evaluatorInput && !isEvaluationValueCompatibleWithDataType(targetOutputValue, evaluatorInput.data.dataType)) {\n throw new Error(\n `Target output \"${binding.source.outputId}\" is not compatible with evaluator input \"${binding.graphInputId}\" (${evaluatorInput.data.dataType}).`,\n );\n }\n evaluatorInputs[binding.graphInputId] = clonePortableJson(targetOutputValue);\n } else if (binding.source.kind === 'context') {\n evaluatorInputs[binding.graphInputId] = clonePortableJson(contextValues[binding.source.context]);\n } else {\n throw new Error(`Evaluator input \"${binding.graphInputId}\" uses an unsupported source.`);\n }\n }\n return evaluatorInputs;\n}\n\nfunction hashStableText(value: string): number {\n let hash = 0x811c9dc5;\n for (let index = 0; index < value.length; index += 1) {\n hash ^= value.charCodeAt(index);\n hash = Math.imul(hash, 0x01000193);\n }\n return hash >>> 0;\n}\n\nfunction deriveSeed(seed: number | undefined, caseId: string, trialIndex: number): number | undefined {\n if (seed == null) return undefined;\n let value = seed >>> 0;\n value = Math.imul(value ^ hashStableText(caseId), 0x45d9f3b);\n value = Math.imul(value ^ (trialIndex + 1), 0x45d9f3b);\n return (value ^ (value >>> 16)) >>> 0;\n}\n\nfunction normalizeEvaluatorResult(value: PortableJson, evaluationMode: EvaluationSuiteMode): EvaluationObservation {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error('Evaluator graph output \"result\" must be an object.');\n }\n if (evaluationMode === 'pass-fail' && typeof value.passed !== 'boolean') {\n throw new Error('Evaluator graph output \"result.passed\" must be a boolean.');\n }\n const score = value.score;\n if (\n (evaluationMode === 'scoring' || score !== undefined) &&\n (typeof score !== 'number' || !Number.isFinite(score) || score < 0 || score > 100)\n ) {\n throw new Error(\n 'Evaluator graph output \"result.score\" must be a number from 0 to 100 (for example, return 85 for 85/100).',\n );\n }\n if (value.message !== undefined && typeof value.message !== 'string') {\n throw new Error('Evaluator graph output \"result.message\" must be a string.');\n }\n if (\n value.metrics !== undefined &&\n (typeof value.metrics !== 'object' || value.metrics === null || Array.isArray(value.metrics))\n ) {\n throw new Error('Evaluator graph output \"result.metrics\" must be an object.');\n }\n const metrics = value.metrics as Record<string, PortableJson> | undefined;\n if (metrics && Object.values(metrics).some((entry) => typeof entry !== 'number' || !Number.isFinite(entry))) {\n throw new Error('Evaluator graph output \"result.metrics\" values must be finite numbers.');\n }\n if (value.evidence !== undefined) assertPortableJson(value.evidence, 'evaluator result.evidence');\n return {\n id: '',\n kind: 'graph',\n name: '',\n required: true,\n status: evaluationMode === 'scoring' ? 'scored' : value.passed ? 'passed' : 'failed',\n // Evaluator authors use the same 100-point scale shown by the UI. Runs\n // retain normalized values so historical aggregation and thresholds stay\n // backward compatible with existing evaluation records.\n ...(typeof score === 'number' ? { score: score / 100 } : {}),\n ...(typeof value.message === 'string' ? { message: value.message } : {}),\n ...(value.evidence !== undefined ? { evidence: clonePortableJson(value.evidence) } : {}),\n ...(metrics ? { metrics: clonePortableJson(metrics) as Record<string, number> } : {}),\n };\n}\n\nasync function runWithTimeout<T>(\n run: (signal: AbortSignal) => Promise<T>,\n timeoutMs: number | undefined,\n outer?: AbortSignal,\n): Promise<T> {\n throwIfAborted(outer);\n const controller = new AbortController();\n let rejectCanceled: ((reason: unknown) => void) | undefined;\n const canceled = new Promise<never>((_, reject) => {\n rejectCanceled = reject;\n });\n const abort = () => {\n const error = outer?.reason ?? new DOMException('Evaluation canceled.', 'AbortError');\n controller.abort(error);\n rejectCanceled?.(error);\n };\n outer?.addEventListener('abort', abort, { once: true });\n // `throwIfAborted` above covers the common case. This second check closes\n // the narrow race where the caller aborts while this timeout wrapper is\n // installing its listener, before the adapter has been started.\n if (outer?.aborted) {\n outer.removeEventListener('abort', abort);\n throw outer.reason ?? new DOMException('Evaluation canceled.', 'AbortError');\n }\n let timeout: ReturnType<typeof setTimeout> | undefined;\n let timeoutPromise: Promise<never> | undefined;\n if (timeoutMs != null && timeoutMs > 0) {\n timeoutPromise = new Promise<never>((_, reject) => {\n timeout = setTimeout(() => {\n const error = new DOMException('Evaluation trial timed out.', 'TimeoutError');\n controller.abort(error);\n reject(error);\n }, timeoutMs);\n });\n }\n const execution = run(controller.signal);\n try {\n return await Promise.race([execution, canceled, ...(timeoutPromise ? [timeoutPromise] : [])]);\n } finally {\n if (timeout) clearTimeout(timeout);\n outer?.removeEventListener('abort', abort);\n }\n}\n\nexport type RunEvaluationTrialOptions = {\n project: Project;\n suite: EvaluationSuite;\n dataset: EvaluationDataset;\n purpose: EvaluationRunPurpose;\n testCase: EvaluationDataset['cases'][number];\n caseIndex: number;\n trialIndex: number;\n runId: string;\n runGraph: EvaluationGraphRunner;\n signal?: AbortSignal;\n /** Stable server-owned job id. Local callers may omit it. */\n trialId?: string;\n};\n\nexport async function runEvaluationTrial(input: RunEvaluationTrialOptions): Promise<EvaluationTrial> {\n const { project, suite, dataset, purpose, testCase, caseIndex, trialIndex, runId, runGraph, signal, trialId } = input;\n const evaluationMode = getEvaluationSuiteMode(suite);\n const { inputs, expected } = resolveCaseInputs(suite, dataset, testCase, purpose);\n const seed = deriveSeed(suite.configuration?.seed, testCase.id, trialIndex);\n if (seed !== undefined && suite.configuration?.seedGraphInputId) inputs[suite.configuration.seedGraphInputId] = seed;\n const metadata = {\n evaluationRunId: runId,\n suiteId: suite.id,\n caseId: testCase.id,\n trialIndex,\n phase: 'target' as const,\n };\n let targetMetrics = createEmptyMetrics();\n let evaluatorMetrics = createEmptyMetrics();\n let outputs: Record<string, PortableJson> = {};\n let targetError: string | undefined;\n let recording: EvaluationTrial['recording'];\n let targetProviderAttempts: EvaluationTrial['targetProviderAttempts'];\n const targetStartedAt = Date.now();\n try {\n throwIfAborted(signal);\n const target = await runWithTimeout(\n (attemptSignal) => runGraph({ project, graphId: suite.targetGraphId, inputs, signal: attemptSignal, metadata }),\n suite.configuration?.timeoutMs,\n signal,\n );\n targetMetrics = cloneExecutionMetrics(target.metrics, 'target metrics');\n assertPortableJson(target.outputs, 'target outputs');\n outputs = clonePortableJson(target.outputs);\n recording = target.recording === undefined ? undefined : structuredClone(target.recording);\n targetProviderAttempts = cloneOptionalPortableJson(target.providerAttempts, 'target provider attempts');\n } catch (error) {\n if (error instanceof EvaluationGraphExecutionError) {\n const errorMetrics = tryCloneExecutionMetrics(error.metrics, 'target error metrics');\n targetMetrics = errorMetrics ?? { ...targetMetrics, hasUnknownCost: true };\n recording = error.recording === undefined ? undefined : structuredClone(error.recording);\n targetProviderAttempts = tryCloneOptionalPortableJson(error.providerAttempts, 'target error provider attempts');\n } else {\n // A plain adapter failure does not prove that no priced provider work\n // happened before the error. Do not report authoritative zero cost.\n targetMetrics = { ...targetMetrics, hasUnknownCost: true };\n }\n targetError = toErrorMessage(error);\n targetMetrics = { ...targetMetrics, durationMs: Math.max(targetMetrics.durationMs, Date.now() - targetStartedAt) };\n if (isAbort(error) || signal?.aborted) {\n const executionStatus = 'canceled' as const;\n const qualityStatus = 'not-evaluated' as const;\n return {\n id: trialId ?? makeId('trial'),\n caseId: testCase.id,\n caseName: testCase.name,\n caseIndex,\n trialIndex,\n executionStatus,\n qualityStatus,\n qualityReason: { code: 'canceled', message: 'The evaluation trial was canceled.' },\n inputs,\n expected,\n outputs,\n observations: [],\n targetMetrics,\n evaluatorMetrics,\n totalMetrics: { ...mergeMetrics(targetMetrics, evaluatorMetrics), hasUnknownCost: true },\n error: targetError,\n ...(seed === undefined ? {} : { seed }),\n ...(recording === undefined ? {} : { recording }),\n ...(targetProviderAttempts === undefined ? {} : { targetProviderAttempts }),\n };\n }\n }\n\n const observations: EvaluationObservation[] = [];\n if (purpose === 'evaluation' && targetError) {\n observations.push({\n id: 'target-error',\n kind: 'assertion',\n name: 'Target graph',\n required: true,\n status: 'error',\n message: targetError,\n });\n } else if (purpose === 'evaluation' && evaluationMode === 'pass-fail') {\n for (const assertion of suite.assertions) {\n try {\n observations.push(evaluateAssertion(assertion, outputs, testCase));\n } catch (error) {\n observations.push({\n id: assertion.id,\n kind: 'assertion',\n name: assertion.name,\n required: assertion.required !== false,\n status: 'error',\n message: toErrorMessage(error),\n });\n }\n }\n }\n\n for (const evaluator of purpose === 'evaluation' ? suite.evaluators : []) {\n if (targetError && (evaluationMode === 'scoring' || !evaluator.runOnTargetError)) {\n observations.push({\n id: evaluator.id,\n kind: 'graph',\n name: evaluator.name,\n required: evaluator.required !== false,\n status: 'skipped',\n message: 'Skipped because the target graph failed.',\n });\n continue;\n }\n const start = Date.now();\n let completedAttemptMetrics: EvaluationExecutionMetrics | undefined;\n let completedAttemptRecording: EvaluationRecordingReference | undefined;\n let completedAttemptProviderAttempts: PortableJson | undefined;\n try {\n const result = await runWithTimeout(\n (attemptSignal) =>\n runGraph({\n project,\n graphId: evaluator.graphId,\n inputs: createEvaluatorGraphInputs({\n evaluator,\n project,\n testCase,\n targetInputs: inputs,\n expected,\n targetOutputs: outputs,\n run: { targetError: targetError ?? null, caseIndex, trialIndex, seed: seed ?? null },\n }),\n signal: attemptSignal,\n metadata: { ...metadata, phase: 'evaluator' },\n }),\n suite.configuration?.timeoutMs,\n signal,\n );\n completedAttemptMetrics = cloneExecutionMetrics(result.metrics, `evaluator ${evaluator.name} metrics`);\n completedAttemptRecording = result.recording === undefined ? undefined : structuredClone(result.recording);\n completedAttemptProviderAttempts = cloneOptionalPortableJson(\n result.providerAttempts,\n `evaluator ${evaluator.name} provider attempts`,\n );\n evaluatorMetrics = mergeMetrics(evaluatorMetrics, completedAttemptMetrics);\n assertPortableJson(result.outputs, `evaluator ${evaluator.name} outputs`);\n const observation = normalizeEvaluatorResult(result.outputs.result ?? null, evaluationMode);\n observations.push({\n ...observation,\n id: evaluator.id,\n name: evaluator.name,\n required: evaluator.required !== false,\n scoreWeight: evaluator.scoreWeight ?? 1,\n durationMs: completedAttemptMetrics.durationMs || Date.now() - start,\n ...(completedAttemptMetrics.costUsd === undefined ? {} : { costUsd: completedAttemptMetrics.costUsd }),\n ...(completedAttemptProviderAttempts === undefined\n ? {}\n : { providerAttempts: completedAttemptProviderAttempts }),\n ...(completedAttemptRecording === undefined ? {} : { recording: completedAttemptRecording }),\n });\n } catch (error) {\n const executionError = error instanceof EvaluationGraphExecutionError ? error : undefined;\n const executionErrorMetrics = tryCloneExecutionMetrics(\n executionError?.metrics,\n `evaluator ${evaluator.name} error metrics`,\n );\n const failureMetrics = executionErrorMetrics ?? completedAttemptMetrics;\n const failureProviderAttempts =\n tryCloneOptionalPortableJson(\n executionError?.providerAttempts,\n `evaluator ${evaluator.name} error provider attempts`,\n ) ?? completedAttemptProviderAttempts;\n const failureRecording =\n executionError?.recording === undefined ? completedAttemptRecording : structuredClone(executionError.recording);\n if (executionErrorMetrics) {\n // A failed judge is still a physical graph execution. Its latency,\n // tokens, and cost must remain part of the run rather than vanishing\n // just because the evaluator did not return a valid result object.\n evaluatorMetrics = mergeMetrics(evaluatorMetrics, executionErrorMetrics);\n } else if (!completedAttemptMetrics) {\n // Generic adapter failures and runner timeouts do not carry an\n // EvaluationGraphExecutionError payload. Their elapsed time is still\n // physical evaluator work and must remain visible in run metrics.\n evaluatorMetrics = mergeMetrics(evaluatorMetrics, {\n durationMs: Date.now() - start,\n hasUnknownCost: true,\n });\n }\n if (isAbort(error) || signal?.aborted) {\n const executionStatus = 'canceled' as const;\n const qualityStatus = 'not-evaluated' as const;\n return {\n id: trialId ?? makeId('trial'),\n caseId: testCase.id,\n caseName: testCase.name,\n caseIndex,\n trialIndex,\n executionStatus,\n qualityStatus,\n qualityReason: { code: 'canceled', message: 'The evaluation trial was canceled.' },\n inputs,\n expected,\n outputs,\n observations,\n targetMetrics,\n evaluatorMetrics,\n totalMetrics: { ...mergeMetrics(targetMetrics, evaluatorMetrics), hasUnknownCost: true },\n error: toErrorMessage(error),\n ...(seed === undefined ? {} : { seed }),\n ...(recording === undefined ? {} : { recording }),\n ...(targetProviderAttempts === undefined ? {} : { targetProviderAttempts }),\n };\n }\n observations.push({\n id: evaluator.id,\n kind: 'graph',\n name: evaluator.name,\n required: evaluator.required !== false,\n status: 'error',\n message: toErrorMessage(error),\n durationMs: failureMetrics?.durationMs ?? Date.now() - start,\n ...(failureMetrics?.costUsd === undefined ? {} : { costUsd: failureMetrics.costUsd }),\n ...(failureProviderAttempts === undefined ? {} : { providerAttempts: failureProviderAttempts }),\n ...(failureRecording === undefined ? {} : { recording: failureRecording }),\n });\n }\n }\n\n const required = observations.filter((entry) => entry.required);\n const executionStatus: EvaluationTrialExecutionStatus = targetError === undefined ? 'completed' : 'error';\n let qualityStatus: EvaluationQualityStatus;\n let qualityReason: EvaluationQualityReason;\n if (purpose === 'execution-benchmark') {\n qualityStatus = 'not-evaluated';\n qualityReason = {\n code: 'benchmark',\n message: 'This trial measured execution without evaluating output quality.',\n };\n } else if (evaluationMode === 'scoring') {\n const scoringObservations = observations.filter((entry) => entry.kind === 'graph');\n const hasCompleteScore =\n targetError === undefined &&\n scoringObservations.length === suite.evaluators.length &&\n scoringObservations.every((entry) => entry.status === 'scored' && entry.score !== undefined);\n if (hasCompleteScore) {\n qualityStatus = 'scored';\n qualityReason = { code: 'scores-complete', message: 'All evaluator graphs returned a score for this trial.' };\n } else {\n qualityStatus = 'unable-to-evaluate';\n qualityReason = {\n code: 'scores-incomplete',\n message:\n targetError === undefined\n ? 'One or more evaluator graphs did not return a usable score for this trial.'\n : 'The target graph failed, so this trial could not contribute a score.',\n };\n }\n } else if (targetError !== undefined) {\n qualityStatus = 'failed';\n qualityReason = {\n code: 'target-error',\n message: 'The target graph failed before it could produce a valid result.',\n };\n } else if (required.some((entry) => entry.status === 'failed')) {\n qualityStatus = 'failed';\n qualityReason = { code: 'checks-failed', message: 'One or more required quality checks failed.' };\n } else if (required.some((entry) => entry.status === 'error')) {\n qualityStatus = 'unable-to-evaluate';\n qualityReason = {\n code: 'required-check-error',\n message: 'A required quality check could not be evaluated.',\n };\n } else if (required.some((entry) => entry.status === 'passed')) {\n qualityStatus = 'passed';\n qualityReason = { code: 'checks-passed', message: 'All required per-trial quality checks passed.' };\n } else {\n qualityStatus = 'not-evaluated';\n qualityReason = {\n code: 'no-trial-quality-checks',\n message: 'No required per-trial quality check evaluated this result.',\n };\n }\n const totalMetrics = mergeMetrics(targetMetrics, evaluatorMetrics);\n return {\n id: trialId ?? makeId('trial'),\n caseId: testCase.id,\n caseName: testCase.name,\n caseIndex,\n trialIndex,\n executionStatus,\n qualityStatus,\n qualityReason,\n inputs,\n expected,\n outputs,\n observations,\n targetMetrics,\n evaluatorMetrics,\n totalMetrics,\n ...(targetError === undefined ? {} : { error: targetError }),\n ...(seed === undefined ? {} : { seed }),\n ...(recording === undefined ? {} : { recording }),\n ...(targetProviderAttempts === undefined ? {} : { targetProviderAttempts }),\n };\n}\n\nfunction percentile(values: number[], percentage: number): number {\n if (values.length === 0) return 0;\n const ordered = values.slice().sort((left, right) => left - right);\n return ordered[Math.min(ordered.length - 1, Math.ceil((percentage / 100) * ordered.length) - 1)]!;\n}\n\nfunction median(values: number[]): number {\n if (values.length === 0) return 0;\n const ordered = values.slice().sort((left, right) => left - right);\n const upperIndex = Math.floor(ordered.length / 2);\n if (ordered.length % 2 !== 0) return ordered[upperIndex]!;\n return (ordered[upperIndex - 1]! + ordered[upperIndex]!) / 2;\n}\n\nfunction meanObservationScore(observations: readonly EvaluationObservation[]): number | undefined {\n let weightedScore = 0;\n let totalWeight = 0;\n for (const observation of observations) {\n if (observation.score === undefined) continue;\n // Assertions do not currently produce scores. The fallback preserves\n // compatibility with old recordings and evaluators that predate weights.\n const weight = observation.scoreWeight ?? 1;\n weightedScore += observation.score * weight;\n totalWeight += weight;\n }\n return totalWeight === 0 ? undefined : weightedScore / totalWeight;\n}\n\nfunction meanObservationMetrics(observations: readonly EvaluationObservation[]): Record<string, number> {\n const totals: Record<string, number> = {};\n const counts: Record<string, number> = {};\n for (const observation of observations) {\n for (const [name, value] of Object.entries(observation.metrics ?? {})) {\n totals[name] = (totals[name] ?? 0) + value;\n counts[name] = (counts[name] ?? 0) + 1;\n }\n }\n return Object.fromEntries(Object.entries(totals).map(([name, total]) => [name, total / counts[name]!]));\n}\n\nfunction aggregate(\n trials: EvaluationTrial[],\n evaluationMode: EvaluationSuiteMode = 'pass-fail',\n): { aggregate: EvaluationAggregate; cases: EvaluationCaseAggregate[] } {\n const incurred = trials;\n const settled = trials.filter((trial) => trial.executionStatus !== 'canceled');\n const completed = trials.filter((trial) => trial.executionStatus === 'completed');\n const evaluated = completed.filter((trial) => trial.qualityStatus === 'passed' || trial.qualityStatus === 'failed');\n const passed = evaluated.filter((trial) => trial.qualityStatus === 'passed');\n const failed = evaluated.filter((trial) => trial.qualityStatus === 'failed');\n const notEvaluated = completed.filter((trial) => trial.qualityStatus === 'not-evaluated');\n const unable = completed.filter((trial) => trial.qualityStatus === 'unable-to-evaluate');\n const errors = trials.filter((trial) => trial.executionStatus === 'error');\n const canceled = trials.filter((trial) => trial.executionStatus === 'canceled');\n // Canceled work can have partial observations and accounting. It remains\n // inspectable in the run, but must not distort completed-run quality or cost\n // thresholds.\n const settledObservations = settled.flatMap((trial) => trial.observations);\n const meanScore = meanObservationScore(settledObservations);\n const accountingComplete = !incurred.some((trial) => trial.totalMetrics.hasUnknownCost);\n const totalCostUsd = accountingComplete\n ? incurred.reduce((sum, trial) => sum + (trial.totalMetrics.costUsd ?? 0), 0)\n : undefined;\n // Evaluator metrics are per-observation measurements. Aggregating them as\n // a mean keeps a `0..1` quality score meaningful as trial count changes;\n // an evaluator that needs a total can return it as an explicit metric.\n const meanMetrics = meanObservationMetrics(settledObservations);\n const byCase = new Map<string, EvaluationTrial[]>();\n for (const trial of trials) byCase.set(trial.caseId, [...(byCase.get(trial.caseId) ?? []), trial]);\n const cases = Array.from(byCase.values()).map((caseTrials): EvaluationCaseAggregate => {\n const caseSettled = caseTrials.filter((trial) => trial.executionStatus !== 'canceled');\n const caseCompleted = caseSettled.filter((trial) => trial.executionStatus === 'completed');\n const caseEvaluated = caseCompleted.filter(\n (trial) => trial.qualityStatus === 'passed' || trial.qualityStatus === 'failed',\n );\n const casePassed = caseEvaluated.filter((trial) => trial.qualityStatus === 'passed');\n const caseFailed = caseEvaluated.filter((trial) => trial.qualityStatus === 'failed');\n const caseScored = caseCompleted.filter((trial) => trial.qualityStatus === 'scored');\n const caseObservations = caseSettled.flatMap((trial) => trial.observations);\n // A scoring trial has already proved every configured evaluator produced\n // a score. Average evaluators within a trial first, then average those\n // trials, so each case gets equal weight regardless of its evaluator set.\n const caseTrialScores = caseScored\n .map((trial) => meanObservationScore(trial.observations))\n .filter((score): score is number => score !== undefined);\n const caseMeanScore =\n evaluationMode === 'scoring'\n ? caseTrialScores.length === 0\n ? undefined\n : caseTrialScores.reduce((sum, score) => sum + score, 0) / caseTrialScores.length\n : meanObservationScore(caseObservations);\n return {\n caseId: caseTrials[0]!.caseId,\n caseName: caseTrials[0]!.caseName,\n ...(caseEvaluated.length === 0 ? {} : { passRate: casePassed.length / caseEvaluated.length }),\n evaluatedTrialCount: caseEvaluated.length,\n passedTrialCount: casePassed.length,\n failedTrialCount: caseFailed.length,\n notEvaluatedTrialCount: caseCompleted.filter((trial) => trial.qualityStatus === 'not-evaluated').length,\n unableToEvaluateTrialCount: caseCompleted.filter((trial) => trial.qualityStatus === 'unable-to-evaluate').length,\n erroredTrialCount: caseTrials.filter((trial) => trial.executionStatus === 'error').length,\n canceledTrialCount: caseTrials.filter((trial) => trial.executionStatus === 'canceled').length,\n ...(evaluationMode === 'scoring'\n ? {\n scoredTrialCount: caseScored.length,\n missingScoreTrialCount: caseTrials.length - caseScored.length,\n }\n : {}),\n ...(caseMeanScore === undefined ? {} : { meanScore: caseMeanScore }),\n metrics: meanObservationMetrics(caseObservations),\n };\n });\n const scoredTrialCount = cases.reduce((sum, testCase) => sum + (testCase.scoredTrialCount ?? 0), 0);\n const scoringCaseMeans = cases\n .map((testCase) => testCase.meanScore)\n .filter((score): score is number => score !== undefined);\n const scoringMeanScore =\n scoringCaseMeans.length === 0\n ? undefined\n : scoringCaseMeans.reduce((sum, score) => sum + score, 0) / scoringCaseMeans.length;\n const incurredLatencies = incurred.map((trial) => trial.totalMetrics.durationMs);\n const aggregateValue: EvaluationAggregate = {\n trialCount: trials.length,\n evaluatedTrialCount: evaluated.length,\n notEvaluatedTrialCount: notEvaluated.length,\n unableToEvaluateTrialCount: unable.length,\n passedTrialCount: passed.length,\n failedTrialCount: failed.length,\n erroredTrialCount: errors.length,\n canceledTrialCount: canceled.length,\n passRate: evaluated.length === 0 ? 0 : passed.length / evaluated.length,\n ...(evaluationMode === 'scoring'\n ? {\n scoredTrialCount,\n missingScoreTrialCount: trials.length - scoredTrialCount,\n ...(scoringMeanScore === undefined ? {} : { meanScore: scoringMeanScore }),\n ...(scoringCaseMeans.length === 0\n ? {}\n : {\n medianScore: median(scoringCaseMeans),\n p95Score: percentile(scoringCaseMeans, 95),\n }),\n }\n : meanScore === undefined\n ? {}\n : { meanScore }),\n averageLatencyMs:\n incurred.length === 0 ? 0 : incurredLatencies.reduce((sum, durationMs) => sum + durationMs, 0) / incurred.length,\n medianLatencyMs: median(incurredLatencies),\n p95LatencyMs: percentile(incurredLatencies, 95),\n ...(incurred.length === 0 || totalCostUsd === undefined\n ? {}\n : { totalCostUsd, averageCostUsd: totalCostUsd / incurred.length }),\n targetErrorRate: settled.length === 0 ? 0 : errors.length / settled.length,\n evaluatorErrorRate:\n settled.length === 0\n ? 0\n : settled.filter((trial) =>\n trial.observations.some((observation) => observation.kind === 'graph' && observation.status === 'error'),\n ).length / settled.length,\n toolFailureRate:\n settled.reduce((sum, trial) => sum + (trial.totalMetrics.toolCallCount ?? 0), 0) === 0\n ? 0\n : settled.reduce((sum, trial) => sum + (trial.totalMetrics.toolFailureCount ?? 0), 0) /\n settled.reduce((sum, trial) => sum + (trial.totalMetrics.toolCallCount ?? 0), 0),\n metrics: meanMetrics,\n };\n return {\n aggregate: aggregateValue,\n cases,\n };\n}\n\nfunction thresholdValue(aggregateValue: EvaluationAggregate, metric: string): number | undefined {\n switch (metric) {\n case 'pass-rate':\n return aggregateValue.evaluatedTrialCount === 0 ? undefined : aggregateValue.passRate;\n case 'mean-score':\n return aggregateValue.meanScore;\n case 'target-error-rate':\n return aggregateValue.targetErrorRate;\n case 'evaluator-error-rate':\n return aggregateValue.evaluatorErrorRate;\n case 'tool-failure-rate':\n return aggregateValue.toolFailureRate;\n case 'average-cost':\n return aggregateValue.averageCostUsd;\n case 'total-cost':\n return aggregateValue.totalCostUsd;\n case 'average-latency-ms':\n return aggregateValue.averageLatencyMs;\n case 'p95-latency-ms':\n return aggregateValue.p95LatencyMs;\n default:\n return metric.startsWith('custom:') ? aggregateValue.metrics[metric.slice('custom:'.length)] : undefined;\n }\n}\n\nfunction isHigherBetterMetric(metric: string): boolean {\n return metric === 'pass-rate' || metric === 'mean-score' || metric.startsWith('custom:');\n}\n\nfunction baselineCompatible(current: EvaluationRunProvenance, baseline: EvaluationBaselineSnapshot): boolean {\n return (\n current.executionMode === baseline.provenance.executionMode &&\n current.suiteFingerprint === baseline.provenance.suiteFingerprint &&\n current.datasetFingerprint === baseline.provenance.datasetFingerprint &&\n current.targetFingerprint === baseline.provenance.targetFingerprint &&\n canonicalStringify(current.evaluatorFingerprints) === canonicalStringify(baseline.provenance.evaluatorFingerprints)\n );\n}\n\n/**\n * Project-level values which can change a graph execution even though no node\n * or connection changed. Deliberately omit cosmetic metadata (title,\n * description, path, main-graph selection) and UI graphs: changing those must\n * not invalidate an otherwise comparable baseline.\n */\nfunction executionNodeConfiguration(node: ChartNode): Record<string, unknown> {\n return {\n id: node.id,\n type: node.type,\n title: node.title,\n data: node.data,\n variants: node.variants,\n isSplitRun: node.isSplitRun,\n isSplitSequential: node.isSplitSequential,\n splitRunMax: node.splitRunMax,\n splitRunConcurrency: node.splitRunConcurrency,\n disabled: node.disabled,\n isConditional: node.isConditional,\n };\n}\n\nfunction executionConnectionConfiguration(connection: NodeConnection): Record<string, unknown> {\n return {\n outputNodeId: connection.outputNodeId,\n inputNodeId: connection.inputNodeId,\n outputId: connection.outputId,\n inputId: connection.inputId,\n };\n}\n\nfunction executionGraphConfiguration(graph: NodeGraph): Record<string, unknown> {\n return {\n metadata: {\n id: graph.metadata?.id,\n name: graph.metadata?.name,\n attachedData: graph.metadata?.attachedData,\n },\n nodes: graph.nodes.map(executionNodeConfiguration),\n connections: graph.connections.map(executionConnectionConfiguration),\n };\n}\n\nfunction executionProjectGraphs(project: Project): Record<string, unknown> {\n return Object.fromEntries(\n Object.entries(project.graphs).map(([graphId, graph]) => [graphId, executionGraphConfiguration(graph)]),\n );\n}\n\nfunction executionProjectConfiguration(project: Project): Record<string, unknown> {\n return {\n ...(project.plugins === undefined ? {} : { plugins: project.plugins }),\n ...(project.nodePrefabs === undefined\n ? {}\n : {\n nodePrefabs: Object.fromEntries(\n Object.entries(project.nodePrefabs).map(([prefabId, prefab]) => [\n prefabId,\n { id: prefab.id, sourceNode: executionNodeConfiguration(prefab.sourceNode) },\n ]),\n ),\n }),\n ...(project.data === undefined ? {} : { data: project.data }),\n ...(project.references === undefined ? {} : { references: project.references }),\n ...(project.metadata.mcpServer === undefined ? {} : { mcpServer: project.metadata.mcpServer }),\n ...(project.metadata.knowledgeStores === undefined ? {} : { knowledgeStores: project.metadata.knowledgeStores }),\n };\n}\n\n/**\n * Rivet's live project model intentionally keeps optional fields as own\n * properties whose value is `undefined` (for example `node.description`).\n * That is valid executable state, but it is not PortableJson. Evaluation\n * datasets and graph outputs must retain the stricter contract; provenance\n * fingerprints instead mirror ordinary JSON serialization for this one\n * runtime-only boundary so those optional fields neither block a run nor\n * create a distinct baseline identity.\n */\nfunction canonicalizeExecutionFingerprintValue(value: unknown, path = '$', stack = new Set<object>()): PortableJson {\n if (value === null || typeof value === 'string' || typeof value === 'boolean') return value;\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) throw new Error(`${path} must not contain a non-finite number.`);\n return value;\n }\n if (value === undefined) return null;\n if (typeof value !== 'object') throw new Error(`${path} must be JSON-compatible to fingerprint an evaluation.`);\n if (stack.has(value)) throw new Error(`${path} must not contain a cycle.`);\n\n if (Array.isArray(value)) {\n stack.add(value);\n const normalized = Array.from(value, (entry, index) =>\n canonicalizeExecutionFingerprintValue(entry, `${path}[${index}]`, stack),\n );\n stack.delete(value);\n return normalized;\n }\n\n if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) {\n throw new Error(`${path} must be a plain object to fingerprint an evaluation.`);\n }\n\n stack.add(value);\n const normalized = Object.fromEntries(\n Object.entries(value).flatMap(([key, entry]) =>\n entry === undefined ? [] : [[key, canonicalizeExecutionFingerprintValue(entry, `${path}.${key}`, stack)]],\n ),\n );\n stack.delete(value);\n return normalized;\n}\n\nfunction fingerprintExecutionProject(value: unknown): string {\n return fingerprint(canonicalizeExecutionFingerprintValue(value));\n}\n\n/**\n * A baseline must follow every graph that a static node configuration can\n * invoke, not only Subgraph and Loop nodes. Dynamic Call Graph references\n * deliberately remain part of the owning graph fingerprint, because their\n * eventual target cannot be known before a trial runs.\n */\nfunction fingerprintGraphDependency(project: Project, graphId: GraphId): string {\n const visited = new Set<GraphId>();\n const graphEntries = Object.entries(project.graphs) as Array<[GraphId, (typeof project.graphs)[GraphId]]>;\n const asKnownGraphId = (value: unknown): GraphId | undefined => {\n return typeof value === 'string' && project.graphs[value as GraphId] ? (value as GraphId) : undefined;\n };\n const getStaticChildren = (graph: (typeof project.graphs)[GraphId]): GraphId[] => {\n const children = new Set<GraphId>();\n const autoDelegatedToolNames: string[] = [];\n const add = (value: unknown) => {\n const id = asKnownGraphId(value);\n if (id) children.add(id);\n };\n\n for (const node of graph.nodes) {\n const data = node.data as {\n autoDelegate?: unknown;\n graphId?: unknown;\n handlers?: unknown;\n name?: unknown;\n targetGraph?: unknown;\n unknownHandler?: unknown;\n useNameInput?: unknown;\n };\n switch (node.type) {\n case 'subGraph':\n case 'loopUntil':\n case 'cron':\n add(node.type === 'subGraph' ? data.graphId : data.targetGraph);\n break;\n case 'delegateFunctionCall': {\n add(data.unknownHandler);\n if (data.autoDelegate === true) {\n continue;\n }\n if (Array.isArray(data.handlers)) {\n for (const handler of data.handlers) {\n if (handler && typeof handler === 'object' && 'value' in handler) {\n add((handler as { value?: unknown }).value);\n }\n }\n }\n break;\n }\n case 'gptFunction':\n if (data.useNameInput !== true && typeof data.name === 'string' && data.name) {\n autoDelegatedToolNames.push(data.name);\n }\n break;\n }\n }\n\n if (\n graph.nodes.some(\n (node) =>\n node.type === 'delegateFunctionCall' && (node.data as { autoDelegate?: unknown }).autoDelegate === true,\n )\n ) {\n for (const toolName of autoDelegatedToolNames) {\n const resolved = findAutoDelegateGraphCandidate(\n graphEntries,\n toolName,\n ([, candidate]) => candidate.metadata?.name,\n );\n if (resolved) children.add(resolved[0]);\n }\n }\n return [...children];\n };\n const collect = (id: GraphId): unknown => {\n if (visited.has(id)) return { graphId: id, cycle: true };\n visited.add(id);\n const graph = project.graphs[id];\n if (!graph) return { graphId: id, missing: true };\n const dependencies = getStaticChildren(graph).map(collect);\n return { graph: executionGraphConfiguration(graph), dependencies };\n };\n return fingerprintExecutionProject({\n graphDependency: collect(graphId),\n projectExecutionConfiguration: executionProjectConfiguration(project),\n });\n}\n\nfunction unavailableThresholdResult(threshold: EvaluationThreshold, message: string): EvaluationThresholdResult {\n return {\n id: threshold.id,\n metric: threshold.metric,\n operator: threshold.operator,\n status: 'unavailable',\n expectedValue: threshold.value,\n message,\n };\n}\n\nexport function evaluateThresholdResults(\n aggregateValue: EvaluationAggregate,\n thresholds: EvaluationThreshold[] = [],\n baseline?: EvaluationBaselineSnapshot,\n): EvaluationThresholdResult[] {\n return thresholds.map((threshold) => {\n const actual = thresholdValue(aggregateValue, threshold.metric);\n if (actual === undefined || !Number.isFinite(actual)) {\n const message =\n threshold.metric === 'average-cost' || threshold.metric === 'total-cost'\n ? 'Some provider pricing was unavailable, so this cost requirement could not be evaluated.'\n : threshold.metric === 'pass-rate'\n ? 'No completed trial produced an evaluated pass or fail result.'\n : `The metric \"${threshold.metric}\" was unavailable.`;\n return unavailableThresholdResult(threshold, message);\n }\n\n if (threshold.operator === 'max-regression') {\n const isCostMetric = threshold.metric === 'average-cost' || threshold.metric === 'total-cost';\n if (\n isCostMetric &&\n (baseline?.accountingStatus === 'partial' || baseline?.provenance.accountingComplete === false)\n ) {\n return unavailableThresholdResult(\n threshold,\n 'The baseline has partial accounting because some provider pricing was unavailable, so this cost regression could not be evaluated.',\n );\n }\n const previous = baseline ? thresholdValue(baseline.aggregate, threshold.metric) : undefined;\n if (previous === undefined || !Number.isFinite(previous)) {\n return unavailableThresholdResult(\n threshold,\n baseline\n ? `The baseline does not contain a comparable \"${threshold.metric}\" metric.`\n : 'A compatible baseline is required for this regression requirement.',\n );\n }\n const delta = isHigherBetterMetric(threshold.metric) ? previous - actual : actual - previous;\n const zeroBaselineRegression = previous === 0 && delta > 0;\n const regression = previous === 0 ? 0 : delta / Math.abs(previous);\n const failed = zeroBaselineRegression || regression > threshold.value;\n return {\n id: threshold.id,\n metric: threshold.metric,\n operator: threshold.operator,\n status: failed ? 'failed' : 'passed',\n expectedValue: threshold.value,\n actualValue: actual,\n baselineValue: previous,\n ...(zeroBaselineRegression ? {} : { regression }),\n message: failed\n ? `Regression exceeded the allowed ${formatThresholdResultValue(\n threshold.metric,\n threshold.operator,\n threshold.value,\n )}.`\n : `Regression stayed within the allowed ${formatThresholdResultValue(\n threshold.metric,\n threshold.operator,\n threshold.value,\n )}.`,\n };\n }\n\n const passed = threshold.operator === 'at-least' ? actual >= threshold.value : actual <= threshold.value;\n return {\n id: threshold.id,\n metric: threshold.metric,\n operator: threshold.operator,\n status: passed ? 'passed' : 'failed',\n expectedValue: threshold.value,\n actualValue: actual,\n message: passed\n ? `Actual value ${formatThresholdResultValue(threshold.metric, threshold.operator, actual)} satisfied ${\n threshold.operator\n } ${formatThresholdResultValue(threshold.metric, threshold.operator, threshold.value)}.`\n : `Actual value ${formatThresholdResultValue(threshold.metric, threshold.operator, actual)} did not satisfy ${\n threshold.operator\n } ${formatThresholdResultValue(threshold.metric, threshold.operator, threshold.value)}.`,\n };\n });\n}\n\nfunction createProvenance(\n project: Project,\n suite: EvaluationSuite,\n dataset: EvaluationDataset,\n options: Pick<RunEvaluationSuiteOptions, 'purpose' | 'projectFingerprint' | 'executionMode'>,\n): EvaluationRunProvenance {\n const purpose = options.purpose ?? 'evaluation';\n const evaluationMode = getEvaluationSuiteMode(suite);\n const configuration = suite.configuration;\n const materialEvaluators = suite.evaluators.map((evaluator) => ({\n graphId: evaluator.graphId,\n inputBindings:\n evaluator.inputBindings?.slice().sort((left, right) => left.graphInputId.localeCompare(right.graphInputId)) ??\n null,\n // Normalize defaults so editing a control between its implicit and\n // explicit default does not invalidate a baseline.\n scoreWeight: evaluator.scoreWeight ?? 1,\n ...(evaluationMode === 'scoring'\n ? {}\n : { required: evaluator.required !== false, runOnTargetError: evaluator.runOnTargetError === true }),\n }));\n const materialSuiteDefinition = {\n purpose,\n evaluationMode,\n targetGraphId: suite.targetGraphId,\n datasetId: suite.datasetId,\n inputBindings: suite.inputBindings\n .slice()\n .sort((left, right) => left.graphInputId.localeCompare(right.graphInputId)),\n configuration: {\n trialCount: configuration?.trialCount ?? 1,\n concurrency: configuration?.concurrency ?? DEFAULT_CONCURRENCY,\n timeoutMs: configuration?.timeoutMs ?? null,\n seed: configuration?.seed ?? null,\n seedGraphInputId: configuration?.seedGraphInputId ?? null,\n },\n ...(purpose !== 'evaluation'\n ? {}\n : evaluationMode === 'scoring'\n ? { evaluators: materialEvaluators }\n : {\n assertions: suite.assertions,\n evaluators: materialEvaluators,\n thresholds: suite.thresholds ?? [],\n }),\n };\n return {\n projectFingerprint:\n options.projectFingerprint ??\n fingerprintExecutionProject({\n projectId: project.metadata.id,\n graphs: executionProjectGraphs(project),\n executionConfiguration: executionProjectConfiguration(project),\n }),\n // Names, descriptions, tags, and recording-retention choices do not\n // change an execution result. Quality-only definitions likewise cannot\n // stale an execution-benchmark comparison because they never ran. Pass/\n // fail assertions and thresholds are equally dormant in scoring mode.\n suiteFingerprint: fingerprint(materialSuiteDefinition),\n datasetFingerprint: fingerprintEvaluationDataset(dataset),\n targetFingerprint: fingerprintGraphDependency(project, suite.targetGraphId),\n evaluatorFingerprints:\n purpose === 'evaluation'\n ? Object.fromEntries(\n suite.evaluators.map((evaluator) => [evaluator.id, fingerprintGraphDependency(project, evaluator.graphId)]),\n )\n : {},\n executionMode: options.executionMode ?? 'unknown',\n accountingComplete: true,\n };\n}\n\nexport type EvaluationRunWorkItem = {\n testCase: EvaluationDataset['cases'][number];\n caseIndex: number;\n trialIndex: number;\n};\n\nexport type EvaluationRunPlan = {\n suite: EvaluationSuite;\n purpose: EvaluationRunPurpose;\n evaluationMode: EvaluationSuiteMode;\n work: readonly EvaluationRunWorkItem[];\n};\n\n/**\n * Validates an immutable Evaluation submission and expands its enabled cases\n * into deterministic work. Hosts can persist this plan before any graph side\n * effect, while local callers continue to use runEvaluationSuite.\n */\nexport function createEvaluationRunPlan(\n options: Pick<RunEvaluationSuiteOptions, 'project' | 'evaluationData' | 'dataset' | 'suiteId' | 'purpose'>,\n): EvaluationRunPlan {\n const suite = resolveSuite(options.evaluationData, options.suiteId);\n const purpose = options.purpose ?? 'evaluation';\n const evaluationMode = getEvaluationSuiteMode(suite);\n if (purpose === 'evaluation' && !hasAuthoritativeEvaluationCriteria(suite)) {\n throw new Error(\n evaluationMode === 'scoring'\n ? `Scoring evaluation suite \"${suite.name}\" has no evaluator graph. Add an evaluator that returns result.score or run an execution benchmark.`\n : `Evaluation suite \"${suite.name}\" has no required quality check or threshold. Add a quality criterion or run it as an execution benchmark.`,\n );\n }\n validateSuite(options.project, suite, options.dataset, purpose);\n const trialCount = Math.max(1, Math.floor(suite.configuration?.trialCount ?? 1));\n const work = options.dataset.cases\n .filter((testCase) => testCase.enabled !== false)\n .flatMap((testCase, caseIndex) =>\n Array.from({ length: trialCount }, (_, trialIndex) => ({ testCase, caseIndex, trialIndex })),\n );\n return { suite, purpose, evaluationMode, work };\n}\n\nexport type FinalizeEvaluationRunOptions = {\n run: EvaluationRun;\n trials: readonly EvaluationTrial[];\n suite: EvaluationSuite;\n evaluationData: EvaluationProjectData;\n baseline?: EvaluationBaselineSnapshot;\n canceled?: boolean;\n completedAt?: string;\n};\n\n/**\n * Applies the same aggregate, quality, accounting, and baseline semantics to\n * locally scheduled and durably hosted trials. Callers must provide every\n * settled trial in deterministic case/trial order; never synthesize retries.\n */\nexport function finalizeEvaluationRun(options: FinalizeEvaluationRunOptions): EvaluationRun {\n const run = options.run;\n const evaluationMode = getEvaluationSuiteMode(options.suite);\n run.trials = options.trials.slice();\n run.completedAt = options.completedAt ?? new Date().toISOString();\n const outcome = aggregate(run.trials, evaluationMode);\n run.aggregate = outcome.aggregate;\n run.provenance.accountingComplete = !run.trials.some((trial) => trial.totalMetrics.hasUnknownCost);\n run.accountingStatus = run.provenance.accountingComplete ? 'complete' : 'partial';\n if (run.accountingStatus === 'partial' && !run.warnings.includes('Some provider pricing was unavailable. Cost totals are unavailable, and cost requirements cannot be evaluated.')) {\n run.warnings.push('Some provider pricing was unavailable. Cost totals are unavailable, and cost requirements cannot be evaluated.');\n }\n if (options.canceled) {\n run.executionStatus = 'canceled';\n run.qualityStatus = 'not-evaluated';\n run.qualityReason = { code: 'canceled', message: 'The evaluation run was canceled.' };\n return run;\n }\n if (run.purpose === 'execution-benchmark') {\n run.executionStatus = 'completed';\n run.qualityStatus = 'not-evaluated';\n run.qualityReason = { code: 'benchmark', message: 'This run measured execution without evaluating output quality.' };\n return run;\n }\n if (evaluationMode === 'scoring') {\n run.executionStatus = 'completed';\n if ((outcome.aggregate.missingScoreTrialCount ?? run.trials.length) > 0) {\n run.qualityStatus = 'unable-to-evaluate';\n run.qualityReason = { code: 'scores-incomplete', message: 'One or more requested trials did not produce a usable score. Available averages are shown with coverage.' };\n run.warnings.push(`Score coverage is ${outcome.aggregate.scoredTrialCount ?? 0} of ${outcome.aggregate.trialCount} requested trials.`);\n } else if ((outcome.aggregate.scoredTrialCount ?? 0) > 0) {\n run.qualityStatus = 'scored';\n run.qualityReason = { code: 'scores-complete', message: 'Every requested trial produced a score. Overall score is the equal-weight average of case averages.' };\n } else {\n run.qualityStatus = 'unable-to-evaluate';\n run.qualityReason = { code: 'scores-incomplete', message: 'No requested trial produced a usable score.' };\n }\n return run;\n }\n const baseline = options.baseline ?? options.evaluationData.baselines.find((candidate) => candidate.suiteId === options.suite.id);\n const usableBaseline = baseline && baselineCompatible(run.provenance, baseline) ? baseline : undefined;\n if (baseline && !usableBaseline && !run.warnings.includes('The suite baseline is stale because its target, dataset, bindings, or evaluator definition changed.')) {\n run.warnings.push('The suite baseline is stale because its target, dataset, bindings, or evaluator definition changed.');\n }\n run.thresholdResults = evaluateThresholdResults(outcome.aggregate, options.suite.thresholds, usableBaseline);\n const hasPassRateThreshold = options.suite.thresholds?.some((threshold) => threshold.metric === 'pass-rate') ?? false;\n const hasTargetErrorRateThreshold = options.suite.thresholds?.some((threshold) => threshold.metric === 'target-error-rate') ?? false;\n const hasUngovernedCheckFailure = !hasPassRateThreshold && run.trials.some((trial) => trial.executionStatus === 'completed' && trial.qualityStatus === 'failed');\n const hasUngovernedTargetError = !hasTargetErrorRateThreshold && run.trials.some((trial) => trial.executionStatus === 'error');\n const hasThresholdFailure = run.thresholdResults.some((result) => result.status === 'failed');\n const hasUnavailableEvidence = run.trials.some((trial) => trial.qualityStatus === 'unable-to-evaluate') || run.thresholdResults.some((result) => result.status === 'unavailable');\n const hasAuthoritativePass = run.trials.some((trial) => trial.executionStatus === 'completed' && trial.qualityStatus === 'passed') || run.thresholdResults.some((result) => result.status === 'passed');\n run.executionStatus = 'completed';\n if (hasUngovernedCheckFailure || hasUngovernedTargetError || hasThresholdFailure) {\n run.qualityStatus = 'failed';\n run.qualityReason = { code: hasThresholdFailure ? 'thresholds-failed' : 'checks-failed', message: hasThresholdFailure ? 'One or more required aggregate thresholds failed.' : 'One or more target executions or required quality checks failed.' };\n } else if (hasUnavailableEvidence) {\n run.qualityStatus = 'unable-to-evaluate';\n run.qualityReason = { code: run.thresholdResults.some((result) => result.status === 'unavailable') ? 'required-metric-unavailable' : 'required-check-error', message: run.thresholdResults.some((result) => result.status === 'unavailable') ? 'A required aggregate metric could not be evaluated.' : 'A required quality check could not be evaluated.' };\n } else if (hasAuthoritativePass) {\n run.qualityStatus = 'passed';\n run.qualityReason = { code: run.thresholdResults.length > 0 ? 'thresholds-passed' : 'checks-passed', message: run.thresholdResults.length > 0 ? 'All required quality checks and aggregate thresholds passed.' : 'All required quality checks passed.' };\n } else {\n run.qualityStatus = 'not-evaluated';\n run.qualityReason = { code: 'no-completed-trials', message: 'No completed trial produced an authoritative quality result.' };\n }\n return run;\n}\nexport type CreateEvaluationRunShellOptions = Pick<\n RunEvaluationSuiteOptions,\n 'project' | 'evaluationData' | 'dataset' | 'suiteId' | 'purpose' | 'runId' | 'projectFingerprint' | 'executionMode'\n>;\n\n/** Creates a durable running shell only after the complete submission validates. */\nexport function createEvaluationRunShell(options: CreateEvaluationRunShellOptions): {\n run: EvaluationRun;\n plan: EvaluationRunPlan;\n} {\n const plan = createEvaluationRunPlan(options);\n const runId = options.runId ?? makeId('evaluation');\n const run: EvaluationRun = {\n version: 2,\n id: runId,\n projectId: options.project.metadata.id,\n suiteId: plan.suite.id,\n suiteName: plan.suite.name,\n revision: 0,\n startedAt: new Date().toISOString(),\n purpose: plan.purpose,\n evaluationMode: plan.evaluationMode,\n executionStatus: 'running',\n qualityStatus: 'not-evaluated',\n qualityReason: { code: 'in-progress', message: 'The run is still in progress.' },\n accountingStatus: 'complete',\n provenance: createProvenance(options.project, plan.suite, options.dataset, options),\n trials: [],\n thresholdResults: [],\n warnings: [],\n requestedTrialCount: plan.work.length,\n };\n return { run, plan };\n}\nexport async function runEvaluationSuite(options: RunEvaluationSuiteOptions): Promise<EvaluationRun> {\n const plan = createEvaluationRunPlan(options);\n const { suite, purpose, evaluationMode } = plan;\n const runId = options.runId ?? makeId('evaluation');\n const run: EvaluationRun = {\n version: 2,\n id: runId,\n projectId: options.project.metadata.id,\n suiteId: suite.id,\n suiteName: suite.name,\n revision: 0,\n startedAt: new Date().toISOString(),\n purpose,\n evaluationMode,\n executionStatus: 'running',\n qualityStatus: 'not-evaluated',\n qualityReason: { code: 'in-progress', message: 'The run is still in progress.' },\n accountingStatus: 'complete',\n provenance: createProvenance(options.project, suite, options.dataset, options),\n trials: [],\n thresholdResults: [],\n warnings: [],\n };\n const concurrency = Math.min(\n MAX_CONCURRENCY,\n Math.max(1, Math.floor(suite.configuration?.concurrency ?? DEFAULT_CONCURRENCY)),\n );\n const work = plan.work;\n run.requestedTrialCount = work.length;\n const settledTrials: Array<EvaluationTrial | undefined> = Array.from({ length: work.length });\n let settledTrialCount = 0;\n const nextRevision = () => {\n run.revision = (run.revision ?? 0) + 1;\n return run.revision;\n };\n const publishLegacySnapshot = () => {\n // Legacy consumers may retain earlier revisions. Keep their snapshots\n // detached, while incremental consumers avoid cloning all prior trials.\n if (!options.onUpdate) return;\n run.trials = settledTrials.filter((trial): trial is EvaluationTrial => trial !== undefined);\n options.onUpdate(structuredClone(run));\n };\n const publishStarted = async () => {\n const revision = nextRevision();\n if (options.onEvent) {\n const shell = structuredClone(run);\n shell.trials = [];\n await options.onEvent({ type: 'run-started', revision, run: shell });\n }\n publishLegacySnapshot();\n };\n const publishSettledTrial = async (trial: EvaluationTrial) => {\n const revision = nextRevision();\n await options.onEvent?.({\n type: 'trial-settled',\n revision,\n runId: run.id,\n projectId: run.projectId,\n suiteId: run.suiteId,\n requestedTrialCount: run.requestedTrialCount ?? work.length,\n settledTrialCount,\n trial: structuredClone(trial),\n });\n publishLegacySnapshot();\n };\n const publishFinalized = async () => {\n const revision = nextRevision();\n await options.onEvent?.({ type: 'run-finalized', revision, run: structuredClone(run) });\n publishLegacySnapshot();\n };\n // Publish the running shell before constructing the worker-pool promise:\n // async workers start immediately, so publishing afterwards can otherwise\n // let the first graph call race ahead of the run's initial state.\n await publishStarted();\n const workPool = runEvaluationWorkPool({\n work,\n concurrency,\n signal: options.signal,\n execute: async (task) => {\n try {\n return await runEvaluationTrial({\n ...task,\n project: options.project,\n suite,\n dataset: options.dataset,\n purpose,\n runId,\n runGraph: options.runGraph,\n signal: options.signal,\n });\n } catch (error) {\n const executionStatus = isAbort(error) ? ('canceled' as const) : ('error' as const);\n const qualityStatus =\n purpose === 'evaluation' && executionStatus === 'error'\n ? evaluationMode === 'scoring'\n ? ('unable-to-evaluate' as const)\n : ('failed' as const)\n : ('not-evaluated' as const);\n return {\n id: makeId('trial'),\n caseId: task.testCase.id,\n caseName: task.testCase.name,\n caseIndex: task.caseIndex,\n trialIndex: task.trialIndex,\n executionStatus,\n qualityStatus,\n qualityReason:\n executionStatus === 'canceled'\n ? { code: 'canceled' as const, message: 'The evaluation trial was canceled.' }\n : purpose === 'evaluation'\n ? evaluationMode === 'scoring'\n ? { code: 'scores-incomplete' as const, message: 'The target graph could not produce a score.' }\n : { code: 'target-error' as const, message: 'The target graph could not be executed.' }\n : { code: 'benchmark' as const, message: 'This benchmark trial could not be executed.' },\n inputs: {},\n expected: {},\n outputs: {},\n observations: [],\n targetMetrics: createEmptyMetrics(),\n evaluatorMetrics: createEmptyMetrics(),\n totalMetrics:\n executionStatus === 'canceled' ? { ...createEmptyMetrics(), hasUnknownCost: true } : createEmptyMetrics(),\n error: toErrorMessage(error),\n };\n }\n },\n onSettled: async (result, index) => {\n settledTrials[index] = result;\n settledTrialCount += 1;\n await publishSettledTrial(result);\n },\n });\n const results = await workPool;\n finalizeEvaluationRun({\n run,\n trials: results.filter((result): result is EvaluationTrial => result !== undefined),\n suite,\n evaluationData: options.evaluationData,\n baseline: options.baseline,\n canceled: options.signal?.aborted === true,\n });\n await publishFinalized();\n return run;\n}\n\nexport async function runEvaluationCases(\n options: RunEvaluationSuiteOptions & { caseIds: readonly string[] },\n): Promise<EvaluationRun> {\n const permitted = new Set(options.caseIds);\n return runEvaluationSuite({\n ...options,\n dataset: { ...options.dataset, cases: options.dataset.cases.filter((testCase) => permitted.has(testCase.id)) },\n });\n}\n\nexport function summarizeEvaluationRun(\n run: EvaluationRun,\n): { aggregate: EvaluationAggregate; cases: EvaluationCaseAggregate[] } | undefined {\n return run.aggregate ? aggregate(run.trials, getEvaluationSuiteMode(run)) : undefined;\n}\n\n/**\n * Baselines deliberately retain aggregate/provenance only. Raw prompts,\n * outputs, credentials, and replay artifacts remain in the run store.\n */\nexport function createEvaluationBaselineSnapshot(run: EvaluationRun): EvaluationBaselineSnapshot {\n const normalizedRun = normalizeEvaluationRun(run);\n if (normalizedRun.executionStatus !== 'completed') {\n throw new Error('Only a completed evaluation run can be promoted to a baseline.');\n }\n if (\n normalizedRun.purpose !== 'execution-benchmark' &&\n getEvaluationSuiteMode(normalizedRun) === 'scoring' &&\n normalizedRun.qualityStatus !== 'scored'\n ) {\n throw new Error('A scoring baseline needs a complete score for every requested trial.');\n }\n const summary = summarizeEvaluationRun(normalizedRun);\n if (!summary) throw new Error('Only a completed evaluation run can be promoted to a baseline.');\n return {\n id: makeId('baseline'),\n suiteId: normalizedRun.suiteId,\n sourceRunId: normalizedRun.id,\n createdAt: new Date().toISOString(),\n provenance: normalizedRun.provenance,\n aggregate: summary.aggregate,\n purpose: normalizedRun.purpose,\n evaluationMode: getEvaluationSuiteMode(normalizedRun),\n qualityStatus: normalizedRun.qualityStatus,\n qualityReason: normalizedRun.qualityReason,\n accountingStatus: normalizedRun.accountingStatus,\n cases: summary.cases,\n };\n}\n", "import { assertPortableJson, fingerprintEvaluationDataset } from './canonical.js';\nimport { assertEvaluationDatasetValuesMatchDeclaredTypes } from './dataTypes.js';\nimport type { EvaluationDataset, EvaluationDatasetCase, EvaluationDatasetField } from './types.js';\n\nconst DATASET_EXPORT_VERSION = 1;\n\ntype DatasetExportEnvelope = {\n version: typeof DATASET_EXPORT_VERSION;\n dataset: EvaluationDataset;\n};\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction requireString(value: unknown, path: string): string {\n if (typeof value !== 'string' || value.length === 0) throw new Error(`${path} must be a non-empty string.`);\n return value;\n}\n\nfunction requireText(value: unknown, path: string): string {\n if (typeof value !== 'string') throw new Error(`${path} must be a string.`);\n return value;\n}\n\nfunction parseFields(value: unknown): EvaluationDatasetField[] {\n if (!Array.isArray(value)) throw new Error('Evaluation dataset fields must be an array.');\n const ids = new Set<string>();\n return value.map((field, index) => {\n if (!isRecord(field)) throw new Error(`fields[${index}] must be an object.`);\n const id = requireString(field.id, `fields[${index}].id`);\n if (ids.has(id)) throw new Error(`Evaluation dataset has duplicate field id \"${id}\".`);\n ids.add(id);\n const role = field.role;\n if (role !== 'input' && role !== 'expected' && role !== 'metadata') {\n throw new Error(`fields[${index}].role must be input, expected, or metadata.`);\n }\n if (field.description !== undefined && typeof field.description !== 'string') {\n throw new Error(`fields[${index}].description must be a string.`);\n }\n if (field.required !== undefined && typeof field.required !== 'boolean') {\n throw new Error(`fields[${index}].required must be a boolean.`);\n }\n return {\n id,\n name: requireText(field.name, `fields[${index}].name`),\n dataType: requireString(field.dataType, `fields[${index}].dataType`),\n role,\n ...(typeof field.description === 'string' ? { description: field.description } : {}),\n ...(typeof field.required === 'boolean' ? { required: field.required } : {}),\n };\n });\n}\n\nfunction parseCases(value: unknown, fieldIds: ReadonlySet<string>): EvaluationDatasetCase[] {\n if (!Array.isArray(value)) throw new Error('Evaluation dataset cases must be an array.');\n const ids = new Set<string>();\n return value.map((testCase, index) => {\n if (!isRecord(testCase)) throw new Error(`cases[${index}] must be an object.`);\n const id = requireString(testCase.id, `cases[${index}].id`);\n if (ids.has(id)) throw new Error(`Evaluation dataset has duplicate case id \"${id}\".`);\n ids.add(id);\n if (!isRecord(testCase.values)) throw new Error(`cases[${index}].values must be an object.`);\n for (const [fieldId, fieldValue] of Object.entries(testCase.values)) {\n if (!fieldIds.has(fieldId)) throw new Error(`cases[${index}].values references unknown field \"${fieldId}\".`);\n assertPortableJson(fieldValue, `cases[${index}].values.${fieldId}`);\n }\n if (testCase.tags !== undefined && (!Array.isArray(testCase.tags) || testCase.tags.some((tag) => typeof tag !== 'string'))) {\n throw new Error(`cases[${index}].tags must be an array of strings.`);\n }\n if (testCase.note !== undefined && typeof testCase.note !== 'string') throw new Error(`cases[${index}].note must be a string.`);\n if (testCase.enabled !== undefined && typeof testCase.enabled !== 'boolean') throw new Error(`cases[${index}].enabled must be a boolean.`);\n return {\n id,\n name: requireText(testCase.name, `cases[${index}].name`),\n values: testCase.values as EvaluationDatasetCase['values'],\n ...(typeof testCase.enabled === 'boolean' ? { enabled: testCase.enabled } : {}),\n ...(Array.isArray(testCase.tags) ? { tags: testCase.tags as string[] } : {}),\n ...(typeof testCase.note === 'string' ? { note: testCase.note } : {}),\n };\n });\n}\n\n/**\n * Validates durable evaluation datasets and portable imports. `projectId` is\n * accepted solely for backwards-compatible migration from project-owned\n * datasets; newly created local datasets omit it.\n */\nexport function validateEvaluationDataset(\n value: unknown,\n scope?: Pick<EvaluationDataset, 'id' | 'projectId'>,\n): EvaluationDataset {\n if (!isRecord(value)) throw new Error('Evaluation dataset must be an object.');\n const fields = parseFields(value.fields);\n const importedProjectId =\n value.projectId === undefined ? undefined : (requireString(value.projectId, 'dataset.projectId') as EvaluationDataset['projectId']);\n const projectId = scope?.projectId ?? importedProjectId;\n const dataset: EvaluationDataset = {\n id: scope?.id ?? requireString(value.id, 'dataset.id'),\n name: requireText(value.name, 'dataset.name'),\n ...(projectId === undefined ? {} : { projectId }),\n fields,\n cases: parseCases(value.cases, new Set(fields.map((field) => field.id))),\n };\n return { ...dataset, contentFingerprint: fingerprintEvaluationDataset(dataset) };\n}\n\n/**\n * Converts a legacy project-owned dataset into the application-local form.\n * Field and case identity stay stable, so existing suite bindings continue to\n * work after migration.\n */\nexport function localizeEvaluationDataset(value: unknown, id?: string): EvaluationDataset {\n const dataset = validateEvaluationDataset(value, id === undefined ? undefined : { id });\n const { projectId: _legacyProjectId, ...localDataset } = dataset;\n return { ...localDataset, contentFingerprint: fingerprintEvaluationDataset(localDataset) };\n}\n\n/** Strict validation for explicit portable import and export boundaries. */\nexport function validateEvaluationDatasetForTransfer(\n value: unknown,\n scope?: Pick<EvaluationDataset, 'id' | 'projectId'>,\n): EvaluationDataset {\n const dataset = validateEvaluationDataset(value, scope);\n assertEvaluationDatasetValuesMatchDeclaredTypes(dataset);\n return dataset;\n}\n\n/**\n * Portable interchange envelope for a complete evaluation dataset. CSV is\n * useful for case rows; JSON is the lossless form that also carries field\n * roles and Rivet data types.\n */\nexport function serializeEvaluationDatasetJson(dataset: EvaluationDataset): string {\n const validated = validateEvaluationDatasetForTransfer(dataset);\n return JSON.stringify({ version: DATASET_EXPORT_VERSION, dataset: validated } satisfies DatasetExportEnvelope, null, 2);\n}\n\n/**\n * Reads a dataset export into a destination dataset identity. Import keeps\n * incoming field/case IDs but never lets a file overwrite another resource.\n */\nexport function deserializeEvaluationDatasetJson(\n source: string,\n scope: Pick<EvaluationDataset, 'id'>,\n): EvaluationDataset {\n let parsed: unknown;\n try {\n parsed = JSON.parse(source);\n } catch {\n throw new Error('Evaluation dataset JSON is not valid JSON.');\n }\n if (!isRecord(parsed) || parsed.version !== DATASET_EXPORT_VERSION || !isRecord(parsed.dataset)) {\n throw new Error(`Expected an evaluation dataset export with version ${DATASET_EXPORT_VERSION}.`);\n }\n const dataset = validateEvaluationDatasetForTransfer(parsed.dataset, { id: scope.id });\n const { projectId: _legacyProjectId, ...localDataset } = dataset;\n return { ...localDataset, contentFingerprint: fingerprintEvaluationDataset(localDataset) };\n}\n", "import * as yaml from 'yaml';\nimport { assertPortableJson } from './canonical.js';\nimport { normalizeEvaluationBaselineSnapshot } from './normalization.js';\nimport type { EvaluationProjectData, EvaluationSuite } from './types.js';\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction requireRecord(value: unknown, path: string): Record<string, unknown> {\n if (!isRecord(value)) throw new Error(`${path} must be an object.`);\n return value;\n}\n\nfunction requireString(value: unknown, path: string): void {\n if (typeof value !== 'string' || value.trim().length === 0) throw new Error(`${path} must be a non-empty string.`);\n}\n\nfunction requireText(value: unknown, path: string): void {\n if (typeof value !== 'string') throw new Error(`${path} must be a string.`);\n}\n\nfunction requireBoolean(value: unknown, path: string): void {\n if (typeof value !== 'boolean') throw new Error(`${path} must be a boolean.`);\n}\n\nfunction requireFiniteNumber(value: unknown, path: string): void {\n if (typeof value !== 'number' || !Number.isFinite(value)) throw new Error(`${path} must be a finite number.`);\n}\n\nfunction requireArray(value: unknown, path: string): readonly unknown[] {\n if (!Array.isArray(value)) throw new Error(`${path} must be an array.`);\n return value;\n}\n\ntype LegacyEvaluationProjectData = EvaluationProjectData & {\n selectedSuiteId?: unknown;\n selectedDatasetId?: unknown;\n};\n\n/**\n * Selection is editor workspace state, not executable project data. Older\n * project attachments can contain these fields, and previous editors could\n * put an explicit `undefined` here, which is not portable JSON. They have no\n * effect on project behavior, so discard both fields before validation.\n */\nfunction stripLegacyEditorSelections(data: LegacyEvaluationProjectData): EvaluationProjectData {\n const { selectedSuiteId: _selectedSuiteId, selectedDatasetId: _selectedDatasetId, ...projectData } = data;\n return projectData;\n}\n\nfunction validateOptionalPrimitive(\n record: Record<string, unknown>,\n key: string,\n type: 'string' | 'boolean' | 'number',\n path: string,\n): void {\n const value = record[key];\n if (value === undefined) return;\n if (type === 'number') requireFiniteNumber(value, `${path}.${key}`);\n else if (typeof value !== type) throw new Error(`${path}.${key} must be a ${type}.`);\n}\n\nconst ASSERTION_OPERATORS = new Set([\n 'equals',\n 'not-equals',\n 'contains',\n 'matches-regex',\n 'type-is',\n 'json-schema',\n 'number-at-least',\n 'number-at-most',\n 'number-between',\n 'array-includes',\n 'set-overlaps',\n 'contains-any',\n 'contains-all',\n]);\nconst EVALUATOR_CONTEXT_INPUTS = new Set(['case', 'inputs', 'expected', 'outputs', 'run']);\n\nfunction validateSuiteShape(value: unknown, index: number): asserts value is EvaluationSuite {\n const path = `evaluations.suites[${index}]`;\n const suite = requireRecord(value, path);\n for (const key of ['id', 'targetGraphId', 'datasetId']) requireString(suite[key], `${path}.${key}`);\n requireText(suite.name, `${path}.name`);\n if (\n suite.evaluationMode !== undefined &&\n suite.evaluationMode !== 'pass-fail' &&\n suite.evaluationMode !== 'scoring'\n ) {\n throw new Error(`${path}.evaluationMode must be \"pass-fail\" or \"scoring\".`);\n }\n for (const [bindingIndex, bindingValue] of requireArray(suite.inputBindings, `${path}.inputBindings`).entries()) {\n const binding = requireRecord(bindingValue, `${path}.inputBindings[${bindingIndex}]`);\n requireString(binding.graphInputId, `${path}.inputBindings[${bindingIndex}].graphInputId`);\n requireString(binding.datasetFieldId, `${path}.inputBindings[${bindingIndex}].datasetFieldId`);\n }\n for (const [assertionIndex, assertionValue] of requireArray(suite.assertions, `${path}.assertions`).entries()) {\n const assertionPath = `${path}.assertions[${assertionIndex}]`;\n const assertion = requireRecord(assertionValue, assertionPath);\n for (const key of ['id', 'outputPath']) requireString(assertion[key], `${assertionPath}.${key}`);\n requireText(assertion.name, `${assertionPath}.name`);\n if (typeof assertion.operator !== 'string' || !ASSERTION_OPERATORS.has(assertion.operator)) {\n throw new Error(`${assertionPath}.operator is not supported.`);\n }\n validateOptionalPrimitive(assertion, 'required', 'boolean', assertionPath);\n const expected = requireRecord(assertion.expected, `${assertionPath}.expected`);\n if (expected.kind === 'literal') {\n if (!Object.hasOwn(expected, 'value')) throw new Error(`${assertionPath}.expected.value is required.`);\n } else if (expected.kind === 'dataset-field') {\n requireString(expected.fieldId, `${assertionPath}.expected.fieldId`);\n } else {\n throw new Error(`${assertionPath}.expected.kind must be \"literal\" or \"dataset-field\".`);\n }\n }\n for (const [evaluatorIndex, evaluatorValue] of requireArray(suite.evaluators, `${path}.evaluators`).entries()) {\n const evaluatorPath = `${path}.evaluators[${evaluatorIndex}]`;\n const evaluator = requireRecord(evaluatorValue, evaluatorPath);\n for (const key of ['id', 'graphId']) requireString(evaluator[key], `${evaluatorPath}.${key}`);\n requireText(evaluator.name, `${evaluatorPath}.name`);\n validateOptionalPrimitive(evaluator, 'required', 'boolean', evaluatorPath);\n validateOptionalPrimitive(evaluator, 'runOnTargetError', 'boolean', evaluatorPath);\n validateOptionalPrimitive(evaluator, 'scoreWeight', 'number', evaluatorPath);\n if (evaluator.inputBindings !== undefined) {\n for (const [bindingIndex, bindingValue] of requireArray(\n evaluator.inputBindings,\n `${evaluatorPath}.inputBindings`,\n ).entries()) {\n const bindingPath = `${evaluatorPath}.inputBindings[${bindingIndex}]`;\n const binding = requireRecord(bindingValue, bindingPath);\n requireString(binding.graphInputId, `${bindingPath}.graphInputId`);\n const source = requireRecord(binding.source, `${bindingPath}.source`);\n if (source.kind === 'dataset-field') requireString(source.fieldId, `${bindingPath}.source.fieldId`);\n else if (source.kind === 'target-output') requireString(source.outputId, `${bindingPath}.source.outputId`);\n else if (source.kind === 'context') {\n if (typeof source.context !== 'string' || !EVALUATOR_CONTEXT_INPUTS.has(source.context)) {\n throw new Error(`${bindingPath}.source.context is not supported.`);\n }\n } else {\n throw new Error(`${bindingPath}.source.kind is not supported.`);\n }\n }\n }\n }\n if (suite.thresholds !== undefined) {\n for (const [thresholdIndex, thresholdValue] of requireArray(suite.thresholds, `${path}.thresholds`).entries()) {\n const thresholdPath = `${path}.thresholds[${thresholdIndex}]`;\n const threshold = requireRecord(thresholdValue, thresholdPath);\n for (const key of ['id', 'metric', 'operator']) requireString(threshold[key], `${thresholdPath}.${key}`);\n requireFiniteNumber(threshold.value, `${thresholdPath}.value`);\n }\n }\n if (suite.configuration !== undefined) {\n const configuration = requireRecord(suite.configuration, `${path}.configuration`);\n for (const key of ['trialCount', 'concurrency', 'timeoutMs', 'seed']) {\n validateOptionalPrimitive(configuration, key, 'number', `${path}.configuration`);\n }\n validateOptionalPrimitive(configuration, 'seedGraphInputId', 'string', `${path}.configuration`);\n validateOptionalPrimitive(configuration, 'recordingRetention', 'string', `${path}.configuration`);\n }\n validateOptionalPrimitive(suite, 'description', 'string', path);\n if (suite.tags !== undefined) {\n for (const [tagIndex, tag] of requireArray(suite.tags, `${path}.tags`).entries()) {\n requireString(tag, `${path}.tags[${tagIndex}]`);\n }\n }\n}\n\nfunction validateNumericRecord(value: unknown, path: string): void {\n const record = requireRecord(value, path);\n for (const [key, entry] of Object.entries(record)) requireFiniteNumber(entry, `${path}.${key}`);\n}\n\nfunction validateBaselineShape(value: unknown, index: number): void {\n const path = `evaluations.baselines[${index}]`;\n const baseline = requireRecord(value, path);\n for (const key of ['id', 'suiteId', 'createdAt']) requireString(baseline[key], `${path}.${key}`);\n validateOptionalPrimitive(baseline, 'sourceRunId', 'string', path);\n if (\n baseline.evaluationMode !== undefined &&\n baseline.evaluationMode !== 'pass-fail' &&\n baseline.evaluationMode !== 'scoring'\n ) {\n throw new Error(`${path}.evaluationMode must be \"pass-fail\" or \"scoring\".`);\n }\n const provenance = requireRecord(baseline.provenance, `${path}.provenance`);\n for (const key of [\n 'projectFingerprint',\n 'suiteFingerprint',\n 'datasetFingerprint',\n 'targetFingerprint',\n 'executionMode',\n ]) {\n requireString(provenance[key], `${path}.provenance.${key}`);\n }\n const evaluatorFingerprints = requireRecord(\n provenance.evaluatorFingerprints,\n `${path}.provenance.evaluatorFingerprints`,\n );\n for (const [key, fingerprint] of Object.entries(evaluatorFingerprints)) {\n requireString(fingerprint, `${path}.provenance.evaluatorFingerprints.${key}`);\n }\n requireBoolean(provenance.accountingComplete, `${path}.provenance.accountingComplete`);\n const aggregate = requireRecord(baseline.aggregate, `${path}.aggregate`);\n for (const key of [\n 'trialCount',\n 'passedTrialCount',\n 'failedTrialCount',\n 'erroredTrialCount',\n 'canceledTrialCount',\n 'passRate',\n 'averageLatencyMs',\n 'p95LatencyMs',\n 'targetErrorRate',\n 'evaluatorErrorRate',\n 'toolFailureRate',\n ]) {\n requireFiniteNumber(aggregate[key], `${path}.aggregate.${key}`);\n }\n for (const key of [\n 'evaluatedTrialCount',\n 'notEvaluatedTrialCount',\n 'unableToEvaluateTrialCount',\n 'meanScore',\n 'medianScore',\n 'p95Score',\n 'medianLatencyMs',\n 'totalCostUsd',\n 'averageCostUsd',\n 'scoredTrialCount',\n 'missingScoreTrialCount',\n ]) {\n validateOptionalPrimitive(aggregate, key, 'number', `${path}.aggregate`);\n }\n validateNumericRecord(aggregate.metrics, `${path}.aggregate.metrics`);\n for (const [caseIndex, caseValue] of requireArray(baseline.cases, `${path}.cases`).entries()) {\n const casePath = `${path}.cases[${caseIndex}]`;\n const caseAggregate = requireRecord(caseValue, casePath);\n requireString(caseAggregate.caseId, `${casePath}.caseId`);\n requireString(caseAggregate.caseName, `${casePath}.caseName`);\n validateNumericRecord(caseAggregate.metrics, `${casePath}.metrics`);\n for (const key of [\n 'passRate',\n 'meanScore',\n 'evaluatedTrialCount',\n 'passedTrialCount',\n 'failedTrialCount',\n 'notEvaluatedTrialCount',\n 'unableToEvaluateTrialCount',\n 'erroredTrialCount',\n 'canceledTrialCount',\n 'scoredTrialCount',\n 'missingScoreTrialCount',\n ]) {\n validateOptionalPrimitive(caseAggregate, key, 'number', casePath);\n }\n }\n}\n\nexport function createEmptyEvaluationProjectData(): EvaluationProjectData {\n return { version: 1, suites: [], baselines: [] };\n}\n\nexport function serializeEvaluationProjectData(data: EvaluationProjectData): EvaluationProjectData {\n if (data.version !== 1) throw new Error(`Unsupported evaluation data version: ${data.version}`);\n const persistentData = stripLegacyEditorSelections(data as LegacyEvaluationProjectData);\n assertPortableJson(persistentData);\n return {\n ...structuredClone(persistentData),\n baselines: persistentData.baselines.map(normalizeEvaluationBaselineSnapshot),\n };\n}\n\nexport function deserializeEvaluationProjectData(data: unknown): EvaluationProjectData {\n if (data === null || typeof data !== 'object' || Array.isArray(data))\n throw new Error('Evaluation project data must be an object.');\n const candidate = data as Partial<LegacyEvaluationProjectData>;\n if (candidate.version !== 1 || !Array.isArray(candidate.suites) || !Array.isArray(candidate.baselines)) {\n throw new Error('Unsupported or invalid evaluation project data.');\n }\n const persistentData = stripLegacyEditorSelections(candidate as LegacyEvaluationProjectData);\n assertPortableJson(persistentData);\n persistentData.suites.forEach(validateSuiteShape);\n persistentData.baselines.forEach(validateBaselineShape);\n return {\n ...structuredClone(persistentData),\n baselines: persistentData.baselines.map(normalizeEvaluationBaselineSnapshot),\n };\n}\n\nexport function serializeEvaluationProjectDataToString(data: EvaluationProjectData): string {\n return yaml.stringify(serializeEvaluationProjectData(data), null, 2);\n}\n\nexport function deserializeEvaluationProjectDataFromString(data: string): EvaluationProjectData {\n return deserializeEvaluationProjectData(yaml.parse(data));\n}\n", "import { localizeEvaluationDataset } from './datasetTransfer.js';\nimport { createEmptyEvaluationProjectData, deserializeEvaluationProjectData } from './serialization.js';\nimport type { ProjectId } from '@valerypopoff/rivet2-core';\nimport type { EvaluationLibrary, EvaluationProjectData } from './types.js';\n\nexport function createEmptyEvaluationLibrary(): EvaluationLibrary {\n return {\n version: 1,\n data: createEmptyEvaluationProjectData(),\n datasets: [],\n migratedLegacyProjectIds: [],\n };\n}\n\n/**\n * Repairs a library resource-by-resource so one malformed suite, baseline, or\n * dataset cannot hide unrelated valid resources. The top-level persistence\n * envelope is validated by the owning store before this function is called.\n */\nexport function normalizeEvaluationLibrary(value: unknown): EvaluationLibrary {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return createEmptyEvaluationLibrary();\n const candidate = value as Partial<EvaluationLibrary>;\n let data = createEmptyEvaluationProjectData();\n try {\n data = deserializeEvaluationProjectData(candidate.data);\n } catch {\n const dataCandidate =\n typeof candidate.data === 'object' && candidate.data !== null && !Array.isArray(candidate.data)\n ? (candidate.data as Partial<EvaluationProjectData>)\n : undefined;\n const suites = Array.isArray(dataCandidate?.suites)\n ? dataCandidate.suites.flatMap((suite) => {\n try {\n return [deserializeEvaluationProjectData({ version: 1, suites: [suite], baselines: [] }).suites[0]!];\n } catch {\n return [];\n }\n })\n : [];\n const baselines = Array.isArray(dataCandidate?.baselines)\n ? dataCandidate.baselines.flatMap((baseline) => {\n try {\n return [deserializeEvaluationProjectData({ version: 1, suites: [], baselines: [baseline] }).baselines[0]!];\n } catch {\n return [];\n }\n })\n : [];\n const suiteIds = new Set(suites.map((suite) => suite.id));\n data = { version: 1, suites, baselines: baselines.filter((baseline) => suiteIds.has(baseline.suiteId)) };\n }\n\n const datasets = Array.isArray(candidate.datasets)\n ? candidate.datasets.flatMap((dataset) => {\n try {\n return [localizeEvaluationDataset(dataset)];\n } catch {\n return [];\n }\n })\n : [];\n\n const suites = uniqueById(data.suites);\n const suiteIds = new Set(suites.map((suite) => suite.id));\n\n return {\n version: 1,\n data: {\n ...data,\n suites,\n baselines: uniqueById(data.baselines).filter((baseline) => suiteIds.has(baseline.suiteId)),\n },\n datasets: uniqueById(datasets),\n migratedLegacyProjectIds: Array.isArray(candidate.migratedLegacyProjectIds)\n ? Array.from(new Set(candidate.migratedLegacyProjectIds.filter((id): id is ProjectId => typeof id === 'string')))\n : [],\n };\n}\n\nfunction uniqueById<T extends { id: string }>(values: readonly T[]): T[] {\n const seen = new Set<string>();\n return values.filter((value) => {\n if (seen.has(value.id)) return false;\n seen.add(value.id);\n return true;\n });\n}\n", "import { assertEvaluationDatasetSnapshot, assertEvaluationRecordingArtifact } from './canonical.js';\nimport { normalizeEvaluationRun, reconcileEvaluationRunSnapshots } from './normalization.js';\nimport { createEmptyEvaluationLibrary, normalizeEvaluationLibrary } from './library.js';\nimport type {\n EvaluationDatasetSnapshot,\n EvaluationLibrary,\n EvaluationRecordingArtifact,\n EvaluationRun,\n EvaluationStore,\n} from './types.js';\n\nexport class InMemoryEvaluationRunStore implements EvaluationStore {\n readonly #runs = new Map<string, EvaluationRun>();\n readonly #datasetSnapshots = new Map<string, EvaluationDatasetSnapshot>();\n readonly #recordings = new Map<string, EvaluationRecordingArtifact>();\n #library: EvaluationLibrary = createEmptyEvaluationLibrary();\n\n async getLibrary(): Promise<EvaluationLibrary> {\n return structuredClone(this.#library);\n }\n\n async putLibrary(library: EvaluationLibrary): Promise<void> {\n this.#library = structuredClone(normalizeEvaluationLibrary(library));\n }\n\n async put(run: EvaluationRun): Promise<void> {\n const normalized = normalizeEvaluationRun(run);\n const key = `${normalized.projectId}/${normalized.id}`;\n const existing = this.#runs.get(key);\n const next = reconcileEvaluationRunSnapshots(existing, normalized);\n if (next === existing) return;\n this.#runs.set(key, structuredClone(next));\n }\n\n async updateRunName(input: { projectId: string; runId: string; name?: string }): Promise<EvaluationRun | undefined> {\n const key = `${input.projectId}/${input.runId}`;\n const existing = this.#runs.get(key);\n if (!existing) return undefined;\n const renamed = normalizeEvaluationRun({ ...existing, name: input.name });\n this.#runs.set(key, structuredClone(renamed));\n return structuredClone(renamed);\n }\n\n async get(input: { projectId: string; runId: string }): Promise<EvaluationRun | undefined> {\n const run = this.#runs.get(`${input.projectId}/${input.runId}`);\n return run ? normalizeEvaluationRun(run) : undefined;\n }\n\n async list(input: { projectId: string; suiteId?: string }): Promise<readonly EvaluationRun[]> {\n return Array.from(this.#runs.values())\n .filter(\n (run) => run.projectId === input.projectId && (input.suiteId === undefined || run.suiteId === input.suiteId),\n )\n .sort((left, right) => right.startedAt.localeCompare(left.startedAt))\n .map(normalizeEvaluationRun);\n }\n\n async delete(input: { projectId: string; runId: string }): Promise<void> {\n this.#runs.delete(`${input.projectId}/${input.runId}`);\n for (const [key, artifact] of this.#recordings) {\n if (artifact.projectId === input.projectId && artifact.runId === input.runId) this.#recordings.delete(key);\n }\n }\n\n async putDatasetSnapshot(snapshot: EvaluationDatasetSnapshot): Promise<void> {\n assertEvaluationDatasetSnapshot(snapshot);\n const key = `${snapshot.projectId}/${snapshot.fingerprint}`;\n // A content-addressed historical snapshot must never be rewritten by a\n // later edit of the live evaluation dataset.\n if (this.#datasetSnapshots.has(key)) return;\n this.#datasetSnapshots.set(key, structuredClone(snapshot));\n }\n\n async getDatasetSnapshot(input: {\n projectId: string;\n fingerprint: string;\n }): Promise<EvaluationDatasetSnapshot | undefined> {\n const snapshot = this.#datasetSnapshots.get(`${input.projectId}/${input.fingerprint}`);\n return snapshot ? structuredClone(snapshot) : undefined;\n }\n\n async putRecording(artifact: EvaluationRecordingArtifact): Promise<void> {\n assertEvaluationRecordingArtifact(artifact);\n const key = `${artifact.projectId}/${artifact.reference.id}`;\n const existing = this.#recordings.get(key);\n if (existing && (existing.runId !== artifact.runId || existing.trialId !== artifact.trialId)) {\n throw new Error('An evaluation recording ID cannot be reassigned to another run or trial.');\n }\n const next = structuredClone(artifact);\n // Artifact persistence never owns retention transitions. A duplicate or\n // delayed write keeps whatever explicit update/promotion already decided.\n if (existing) next.reference = structuredClone(existing.reference);\n this.#recordings.set(key, next);\n }\n\n async getRecording(input: {\n projectId: string;\n recordingId: string;\n }): Promise<EvaluationRecordingArtifact | undefined> {\n const artifact = this.#recordings.get(`${input.projectId}/${input.recordingId}`);\n if (!artifact) return undefined;\n if (\n artifact.reference.retention === 'temporary' &&\n artifact.reference.expiresAt &&\n Date.parse(artifact.reference.expiresAt) <= Date.now()\n ) {\n this.#recordings.delete(`${input.projectId}/${input.recordingId}`);\n return undefined;\n }\n return structuredClone(artifact);\n }\n\n async updateRecordingRetention(input: {\n projectId: string;\n recordingId: string;\n retention: EvaluationRecordingArtifact['reference']['retention'];\n expiresAt?: string;\n }): Promise<boolean> {\n const key = `${input.projectId}/${input.recordingId}`;\n const artifact = this.#recordings.get(key);\n if (!artifact) return false;\n artifact.reference = {\n id: artifact.reference.id,\n retention: input.retention,\n ...(input.expiresAt === undefined ? {} : { expiresAt: input.expiresAt }),\n };\n return true;\n }\n\n async promoteBaseline(input: { projectId: string; runId: string }): Promise<void> {\n for (const artifact of this.#recordings.values()) {\n if (artifact.projectId !== input.projectId || artifact.runId !== input.runId) continue;\n artifact.reference = { id: artifact.reference.id, retention: 'baseline' };\n }\n }\n}\n", "import { localizeEvaluationDataset, validateEvaluationDatasetForTransfer } from './datasetTransfer.js';\nimport { deserializeEvaluationProjectData } from './serialization.js';\nimport type { EvaluationDataset, EvaluationSuite } from './types.js';\n\nconst SUITE_BUNDLE_EXPORT_VERSION = 1;\n\ntype SuiteBundleExportEnvelope = {\n version: typeof SUITE_BUNDLE_EXPORT_VERSION;\n suite: EvaluationSuite;\n dataset: EvaluationDataset;\n};\n\nexport type EvaluationSuiteBundle = {\n suite: EvaluationSuite;\n dataset: EvaluationDataset;\n};\n\nexport type EvaluationSuiteBundleImportScope = {\n suiteId: string;\n datasetId: string;\n};\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction requireNonEmptyString(value: string, name: string): void {\n if (value.trim().length === 0) throw new Error(`${name} must be a non-empty string.`);\n}\n\nfunction validateEvaluationSuite(value: unknown): EvaluationSuite {\n return deserializeEvaluationProjectData({ version: 1, suites: [value], baselines: [] }).suites[0]!;\n}\n\nfunction validateBundle(value: unknown): EvaluationSuiteBundle {\n if (\n !isRecord(value) ||\n value.version !== SUITE_BUNDLE_EXPORT_VERSION ||\n !isRecord(value.suite) ||\n !isRecord(value.dataset)\n ) {\n throw new Error(`Expected an evaluation suite export with version ${SUITE_BUNDLE_EXPORT_VERSION}.`);\n }\n const suite = validateEvaluationSuite(value.suite);\n const dataset = validateEvaluationDatasetForTransfer(value.dataset);\n if (suite.datasetId !== dataset.id) {\n throw new Error('The evaluation suite export must include the dataset referenced by its suite.');\n }\n return { suite, dataset };\n}\n\n/**\n * A portable suite bundle includes the suite definition and its referenced\n * dataset. It intentionally excludes graphs, baselines, recordings, and run\n * history, which belong to the destination project or its run store.\n */\nexport function serializeEvaluationSuiteBundleJson(suite: EvaluationSuite, dataset: EvaluationDataset): string {\n const bundle = validateBundle({ version: SUITE_BUNDLE_EXPORT_VERSION, suite, dataset });\n return JSON.stringify(\n { version: SUITE_BUNDLE_EXPORT_VERSION, ...bundle } satisfies SuiteBundleExportEnvelope,\n null,\n 2,\n );\n}\n\n/**\n * Imports a bundle as new local evaluation resources. Field and case IDs remain stable\n * so the imported suite's bindings and expected-value references still point\n * to its imported dataset; suite and dataset identities are always supplied by\n * the destination to avoid overwriting existing resources.\n */\nexport function deserializeEvaluationSuiteBundleJson(\n source: string,\n scope: EvaluationSuiteBundleImportScope,\n): EvaluationSuiteBundle {\n let parsed: unknown;\n try {\n parsed = JSON.parse(source);\n } catch {\n throw new Error('Evaluation suite JSON is not valid JSON.');\n }\n\n requireNonEmptyString(scope.suiteId, 'suiteId');\n requireNonEmptyString(scope.datasetId, 'datasetId');\n\n const bundle = validateBundle(parsed);\n const dataset = localizeEvaluationDataset(bundle.dataset, scope.datasetId);\n return {\n dataset,\n suite: {\n ...bundle.suite,\n id: scope.suiteId,\n datasetId: dataset.id,\n },\n };\n}\n", "import { canonicalStringify } from './canonical.js';\nimport { normalizeEvaluationLibrary } from './library.js';\nimport type {\n EvaluationLibrary,\n EvaluationLibraryMutation,\n EvaluationLibraryMutationChange,\n EvaluationLibraryResourceValue,\n EvaluationLibraryResourceVersions,\n EvaluationLibrarySuiteBundle,\n} from './types.js';\n\nexport type { EvaluationLibraryResourceValue, EvaluationLibrarySuiteBundle } from './types.js';\n\n/**\n * Matches the server's canonical resource versioning while retaining the\n * meaningful distinction between an absent resource and a present JSON value.\n */\nexport function evaluationLibraryValueEquals(left: unknown, right: unknown): boolean {\n if (left === undefined || right === undefined) return left === right;\n return canonicalStringify(left) === canonicalStringify(right);\n}\n\nexport function getEvaluationSuiteBundle(\n library: EvaluationLibrary,\n id: string,\n): EvaluationLibrarySuiteBundle | undefined {\n const suite = library.data.suites.find((candidate) => candidate.id === id);\n if (!suite) return undefined;\n return {\n suite,\n baselines: library.data.baselines.filter((baseline) => baseline.suiteId === id),\n };\n}\n\nexport function getEvaluationLibraryResource(\n library: EvaluationLibrary,\n kind: 'suite' | 'dataset',\n id: string,\n): EvaluationLibraryResourceValue {\n if (kind === 'suite') return { kind, id, value: getEvaluationSuiteBundle(library, id) };\n return { kind, id, value: library.datasets.find((dataset) => dataset.id === id) };\n}\n\nfunction resourceIds(library: EvaluationLibrary, kind: 'suite' | 'dataset'): Set<string> {\n return new Set(kind === 'suite' ? library.data.suites.map((suite) => suite.id) : library.datasets.map((dataset) => dataset.id));\n}\n\n/**\n * Builds the smallest resource batch between two already normalized library\n * snapshots. Legacy migration metadata deliberately has its own explicit\n * server operation and is not silently folded into an editor mutation.\n */\nexport function diffEvaluationLibraryMutation(\n previous: EvaluationLibrary,\n next: EvaluationLibrary,\n versions: EvaluationLibraryResourceVersions,\n): EvaluationLibraryMutation | undefined {\n const changes: EvaluationLibraryMutationChange[] = [];\n for (const kind of ['dataset', 'suite'] as const) {\n const ids = new Set([...resourceIds(previous, kind), ...resourceIds(next, kind)]);\n for (const id of [...ids].sort()) {\n if (kind === 'suite') {\n const before = getEvaluationSuiteBundle(previous, id);\n const after = getEvaluationSuiteBundle(next, id);\n if (evaluationLibraryValueEquals(before, after)) continue;\n const currentVersion = versions.suites[id];\n if (before !== undefined && currentVersion === undefined) {\n throw new Error(`The suite \"${id}\" has no synchronization version.`);\n }\n const expectedVersion = before === undefined ? null : currentVersion!;\n if (after === undefined) {\n changes.push({ kind: 'delete-suite', id, expectedVersion: expectedVersion! });\n } else {\n changes.push({\n kind: 'put-suite',\n id,\n expectedVersion,\n suite: after.suite,\n baselines: after.baselines,\n });\n }\n } else {\n const before = previous.datasets.find((dataset) => dataset.id === id);\n const after = next.datasets.find((dataset) => dataset.id === id);\n if (evaluationLibraryValueEquals(before, after)) continue;\n const currentVersion = versions.datasets[id];\n if (before !== undefined && currentVersion === undefined) {\n throw new Error(`The dataset \"${id}\" has no synchronization version.`);\n }\n const expectedVersion = before === undefined ? null : currentVersion!;\n if (after === undefined) {\n changes.push({ kind: 'delete-dataset', id, expectedVersion: expectedVersion! });\n } else {\n changes.push({ kind: 'put-dataset', id, expectedVersion, dataset: after });\n }\n }\n }\n }\n return changes.length === 0 ? undefined : { changes };\n}\n\nfunction replaceById<T extends { id: string }>(items: readonly T[], value: T): T[] {\n const index = items.findIndex((item) => item.id === value.id);\n if (index === -1) return [...items, value];\n return items.map((item) => (item.id === value.id ? value : item));\n}\n\n/** Applies a server-validated resource batch while preserving unrelated resources. */\nexport function applyEvaluationLibraryMutation(\n library: EvaluationLibrary,\n mutation: EvaluationLibraryMutation,\n): EvaluationLibrary {\n let suites = library.data.suites;\n let baselines = library.data.baselines;\n let datasets = library.datasets;\n for (const change of mutation.changes) {\n switch (change.kind) {\n case 'put-suite':\n suites = replaceById(suites, change.suite);\n baselines = [...baselines.filter((baseline) => baseline.suiteId !== change.id), ...change.baselines];\n break;\n case 'delete-suite':\n suites = suites.filter((suite) => suite.id !== change.id);\n baselines = baselines.filter((baseline) => baseline.suiteId !== change.id);\n break;\n case 'put-dataset':\n datasets = replaceById(datasets, change.dataset);\n break;\n case 'delete-dataset':\n datasets = datasets.filter((dataset) => dataset.id !== change.id);\n break;\n }\n }\n return normalizeEvaluationLibrary({\n version: 1,\n data: { version: 1, suites, baselines },\n datasets,\n migratedLegacyProjectIds: library.migratedLegacyProjectIds,\n });\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACwlBO,IAAM,gCAAN,cAA4C,MAAM;AAAA,EAC9C;AAAA,EACA;AAAA,EACA;AAAA,EAET,YACE,SACA,UAAiG,CAAC,GAClG;AACA,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,UAAU,QAAQ;AACvB,SAAK,YAAY,QAAQ;AACzB,SAAK,mBAAmB,QAAQ;AAAA,EAClC;AACF;;;ACr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AO,OAAO,CAAC,UAAU,MAAM,OAAO,OAAO,EAAE;AACxD,oBAAY,UAAU,OAAO,CAAC,aAAa,SAAS,YAAY,OAAO,EAAE;AACzE;AAAA,MACF,KAAK;AACH,mBAAW,YAAY,UAAU,OAAO,OAAO;AAC/C;AAAA,MACF,KAAK;AACH,mBAAW,SAAS,OAAO,CAAC,YAAY,QAAQ,OAAO,OAAO,EAAE;AAChE;AAAA,IACJ;AAAA,EACF;AACA,SAAO,2BAA2B;AAAA,IAChC,SAAS;AAAA,IACT,MAAM,EAAE,SAAS,GAAG,QAAQ,UAAU;AAAA,IACtC;AAAA,IACA,0BAA0B,QAAQ;AAAA,EACpC,CAAC;AACH;",
6
6
  "names": ["evaluated", "passed", "failed", "notEvaluated", "unable", "aggregate", "executionStatus", "qualityStatus", "normalized", "_a", "isRecord", "isRecord", "requireString", "requireText", "thresholdValue", "fingerprint", "aggregate", "suites", "suiteIds", "isRecord"]
7
7
  }