UNPKG

@mastra/core

Version:
3,279 lines • 119 kB
import { S as resolveObservabilityContext } from "./observability-D3dpuDDk.js";
import { i as MastraError } from "./error-oh2DLsP2.js";
import { at as loadStepResults, nn as isSupportedLanguageModel } from "./stream-sJ8FGaH9.js";
import { o as MASTRA_RESOURCE_ID_KEY, u as RequestContext } from "./request-context-COnZHt2-.js";
import { Fi as assertSupportedPatterns, cl as ScorerRunError, il as validateAndSaveScore, nl as flushBeforeTraceRead } from "./run-registry-Ca8idv6o.js";
import { t as EntityType } from "./storage-Cc50aQAp.js";
import { a as getOrCreateSpan } from "./utils-DU_pU5SK.js";
import { t as deepEqual } from "./deep-equal-d1xU02ag.js";
import { Cr as extractWorkflowTrajectory, Sr as extractTrajectoryFromTrace, mn as BATCH_DELETE_TRACES_MAX_IDS, xr as extractTrajectory } from "./constants-Bkej7sJF.js";
import { isZodType } from "@mastra/schema-compat";
import { zodToJsonSchema } from "@mastra/schema-compat/zod-to-json";
// src/datasets/experiment/agent-model.ts
/** `agentModel` swaps an agent's model, so it is meaningless for workflows, scorers and inline tasks. */
function assertAgentModelTarget(config) {
	if (config.agentModel && (config.task || config.targetType !== "agent")) throw new MastraError({
		id: "EXPERIMENT_INVALID_AGENT_MODEL",
		domain: "STORAGE",
		category: "USER",
		text: "agentModel is only supported for agent targets (targetType: \"agent\")"
	});
}
/** `provider/modelId` label for a model config. Reads only identifying fields, so credentials never leak. */
function agentModelLabel(model) {
	if (typeof model === "string") return model;
	const m = model;
	if (typeof m.id === "string") return m.id;
	const provider = m.providerId ?? m.provider;
	return typeof provider === "string" && typeof m.modelId === "string" ? `${provider}/${m.modelId}` : String(m.modelId ?? "unknown");
}
/** Experiment metadata with the override recorded as `agentModel`, so runs on different models can be told apart. */
function withAgentModelMetadata(metadata, agentModel) {
	return agentModel ? {
		...metadata,
		agentModel: agentModelLabel(agentModel)
	} : metadata;
}
// src/datasets/experiment/events.ts
var ExperimentEventDispatcher = class {
	abortController = new AbortController();
	#observer;
	#experimentId;
	#sequence = 0;
	#tail = Promise.resolve();
	#failure;
	get failure() {
		return this.#failure;
	}
	constructor(experimentId, observer) {
		this.#experimentId = experimentId;
		this.#observer = observer;
	}
	emit(input) {
		const event = {
			...input,
			version: 1,
			sequence: ++this.#sequence,
			timestamp: (/* @__PURE__ */ new Date()).toISOString()
		};
		const delivery = this.#tail.then(async () => {
			if (this.#failure) throw this.#failure;
			try {
				await this.#observer(event);
			} catch (error) {
				this.#failure = new MastraError({
					id: "EXPERIMENT_EVENT_OBSERVER_FAILED",
					domain: "EVAL",
					category: "USER",
					details: {
						experimentId: this.#experimentId,
						eventType: event.type,
						eventSequence: event.sequence
					},
					text: `Experiment event observer failed while handling "${event.type}".`
				}, error);
				this.abortController.abort(this.#failure);
				throw this.#failure;
			}
		});
		this.#tail = delivery.catch(() => {});
		return delivery;
	}
};
function toExperimentJsonValue(value, seen = /* @__PURE__ */ new WeakSet()) {
	if (value === null || typeof value === "string" || typeof value === "boolean") return value;
	if (typeof value === "number") return Number.isFinite(value) ? value : null;
	if (typeof value === "bigint") return value.toString();
	if (typeof value === "undefined" || typeof value === "function" || typeof value === "symbol") return null;
	if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value.toISOString();
	if (value instanceof Error) return {
		name: value.name,
		message: value.message
	};
	if (typeof value !== "object") return String(value);
	if (seen.has(value)) return null;
	seen.add(value);
	if (Array.isArray(value)) {
		const result = value.map((entry) => toExperimentJsonValue(entry, seen));
		seen.delete(value);
		return result;
	}
	const result = {};
	for (const [key, entry] of Object.entries(value)) result[key] = toExperimentJsonValue(entry, seen);
	seen.delete(value);
	return result;
}
function createItemCompletedEvent(base, itemIndex, result, traceId) {
	return {
		...base,
		type: "experiment.item.completed",
		itemIndex,
		itemId: result.itemId,
		itemVersion: result.itemVersion,
		status: result.error ? "failed" : "succeeded",
		input: toExperimentJsonValue(result.input),
		output: toExperimentJsonValue(result.output),
		groundTruth: toExperimentJsonValue(result.groundTruth),
		metadata: toExperimentJsonValue(result.metadata ?? null),
		error: toExperimentJsonValue(result.error),
		persistenceError: toExperimentJsonValue(result.persistenceError ?? null),
		scores: toExperimentJsonValue(result.scores),
		toolMockReport: toExperimentJsonValue(result.toolMockReport ?? null),
		retryCount: result.retryCount,
		startedAt: result.startedAt.toISOString(),
		completedAt: result.completedAt.toISOString(),
		traceId
	};
}
// src/datasets/experiment/tool-mocks.ts
/** Deterministic failure codes surfaced via `ExecutionResult.error.code`. */
const TOOL_MOCK_MISMATCH = "TOOL_MOCK_MISMATCH";
const TOOL_MOCK_EXHAUSTED = "TOOL_MOCK_EXHAUSTED";
const TOOL_MOCK_NOT_DECLARED = "TOOL_MOCK_NOT_DECLARED";
/**
* Per-item mock matcher. Built fresh for each item run; consumption is tracked
* in local state so repeated `(toolName, args)` mocks are served top-to-bottom.
*
* Tool execution must be forced sequential while an item has mocks so that
* ordered consumption is deterministic (the matcher itself is order-sensitive).
*/
var ToolMockMatcher = class {
	unmockedToolPolicy;
	#entries;
	#served = [];
	#liveCalls = [];
	#failure;
	constructor(mocks, unmockedToolPolicy = "allow") {
		this.unmockedToolPolicy = unmockedToolPolicy;
		this.#entries = (mocks ?? []).map((mock, mockIndex) => ({
			mockIndex,
			toolName: mock.toolName,
			args: mock.args,
			output: mock.output,
			matchArgs: mock.matchArgs ?? "strict",
			consumed: false
		}));
	}
	/** True when the item declares at least one mock (tool execution should run sequentially). */
	get hasMocks() {
		return this.#entries.length > 0;
	}
	/**
	* Resolve a single tool call:
	* - no mock for this tool → `live`
	* - unconsumed mock whose args match (deep-equal for `strict`, always for
	*   `ignore`) → `serve`
	* - tool is mocked but no unconsumed entry matches → `fail`
	*   (`TOOL_MOCK_EXHAUSTED` if args matched but all consumed, else `TOOL_MOCK_MISMATCH`)
	*/
	resolve(toolName, args) {
		if (this.#failure) return {
			kind: "fail",
			code: this.#failure.code
		};
		const candidates = this.#entries.filter((entry) => entry.toolName === toolName);
		if (candidates.length === 0) {
			if (this.unmockedToolPolicy === "deny") {
				this.#failure = {
					code: TOOL_MOCK_NOT_DECLARED,
					toolName,
					args
				};
				return {
					kind: "fail",
					code: TOOL_MOCK_NOT_DECLARED
				};
			}
			this.#liveCalls.push({
				toolName,
				args
			});
			return { kind: "live" };
		}
		const argsMatch = (entry) => entry.matchArgs === "ignore" || deepEqual(entry.args, args);
		const next = candidates.find((entry) => !entry.consumed && argsMatch(entry));
		if (next) {
			next.consumed = true;
			this.#served.push({
				mockIndex: next.mockIndex,
				toolName,
				args
			});
			return {
				kind: "serve",
				output: next.output
			};
		}
		const code = candidates.some((entry) => argsMatch(entry)) ? TOOL_MOCK_EXHAUSTED : TOOL_MOCK_MISMATCH;
		this.#failure ??= {
			code,
			toolName,
			args
		};
		return {
			kind: "fail",
			code
		};
	}
	/** Build the diagnostic report for this item run. */
	report() {
		const unconsumed = this.#entries.filter((entry) => !entry.consumed).map((entry) => ({
			mockIndex: entry.mockIndex,
			toolName: entry.toolName,
			args: entry.args
		}));
		return {
			served: this.#served,
			unconsumed,
			liveCalls: this.#liveCalls,
			...this.#failure ? { failure: this.#failure } : {}
		};
	}
};
// src/datasets/experiment/executor.ts
/**
* Execute a dataset item against a scorer (LLM-as-judge calibration).
* item.input should contain exactly what the scorer expects - direct passthrough.
* For calibration: item.input = { input, output, groundTruth } (user structures it)
*/
async function executeScorer(scorer, item) {
	try {
		const result = await scorer.run(item.input);
		const score = typeof result.score === "number" && !isNaN(result.score) ? result.score : null;
		if (score === null && result.score !== void 0) console.warn(`Scorer ${scorer.id} returned invalid score: ${result.score}`);
		return {
			output: {
				score,
				reason: typeof result.reason === "string" ? result.reason : null,
				...result.notScorable ? { notScorable: result.notScorable } : {}
			},
			error: null,
			traceId: null
		};
	} catch (error) {
		return {
			output: null,
			error: {
				message: error instanceof Error ? error.message : String(error),
				stack: error instanceof Error ? error.stack : void 0
			},
			traceId: null
		};
	}
}
/** Maximum number of suspend/resume cycles to prevent infinite loops */
const MAX_RESUME_CYCLES = 10;
/**
* Execute a dataset item against a target (agent, workflow, scorer, processor).
* Phase 2: agent/workflow. Phase 4: scorer. Processor deferred.
*/
async function executeTarget(target, targetType, item, options) {
	let traceId = null;
	try {
		const signal = options?.signal;
		if (signal?.aborted) throw signal.reason ?? new DOMException("The operation was aborted.", "AbortError");
		let executionPromise;
		switch (targetType) {
			case "agent":
				executionPromise = executeAgent(target, item, signal, options?.requestContext, options?.experimentId, options?.versions, options?.toolMocks, options?.unmockedToolPolicy, (assignedTraceId) => {
					traceId = assignedTraceId;
				}, options?.agentModel);
				break;
			case "workflow":
				executionPromise = executeWorkflow(target, item, options?.requestContext, options?.experimentId);
				break;
			case "scorer":
				executionPromise = executeScorer(target, item);
				break;
			case "processor": throw new Error(`Target type '${targetType}' not yet supported.`);
			default: throw new Error(`Unknown target type: ${targetType}`);
		}
		if (signal) return await raceWithSignal(executionPromise, signal);
		return await executionPromise;
	} catch (error) {
		return {
			output: null,
			error: {
				message: error instanceof Error ? error.message : String(error),
				stack: error instanceof Error ? error.stack : void 0
			},
			traceId
		};
	}
}
/**
* Race a promise against an AbortSignal. Rejects with the signal's reason when aborted.
*/
function raceWithSignal(promise, signal) {
	if (signal.aborted) return Promise.reject(signal.reason ?? new DOMException("The operation was aborted.", "AbortError"));
	return new Promise((resolve, reject) => {
		const onAbort = () => {
			reject(signal.reason ?? new DOMException("The operation was aborted.", "AbortError"));
		};
		signal.addEventListener("abort", onAbort, { once: true });
		promise.then((value) => {
			signal.removeEventListener("abort", onAbort);
			resolve(value);
		}, (err) => {
			signal.removeEventListener("abort", onAbort);
			reject(err);
		});
	});
}
/**
* Execute a dataset item against an agent.
* Uses generate() for both v1 and v2 models.
*/
async function executeAgent(agent, item, signal, requestContext, experimentId, versions, toolMocks, unmockedToolPolicy, onTraceIdAssigned, agentModel) {
	const reqCtx = requestContext ? new RequestContext(Object.entries(requestContext)) : void 0;
	const useLegacy = !agentModel && !isSupportedLanguageModel(await agent.getModel({ requestContext: reqCtx }));
	const input = item.input;
	const contextResourceId = requestContext?.[MASTRA_RESOURCE_ID_KEY];
	const injectedThreadId = (Boolean(contextResourceId) || contextResourceId === void 0) && !requestContext?.["mastra__threadId"] && typeof agent.hasOwnMemory === "function" && agent.hasOwnMemory() ? globalThis.crypto.randomUUID() : void 0;
	const memoryOption = injectedThreadId ? { memory: {
		thread: {
			id: injectedThreadId,
			...experimentId || item.id ? { metadata: {
				...experimentId ? { experimentId } : {},
				...item.id ? { experimentItemId: item.id } : {}
			} } : {}
		},
		resource: contextResourceId ? String(contextResourceId) : `dataset-experiment:${experimentId ?? globalThis.crypto.randomUUID()}:thread:${injectedThreadId}`,
		options: { generateTitle: false }
	} } : void 0;
	const matcher = new ToolMockMatcher(toolMocks, unmockedToolPolicy);
	const shouldInterceptTools = matcher.hasMocks || matcher.unmockedToolPolicy === "deny";
	const mockAbort = shouldInterceptTools ? new AbortController() : void 0;
	const mockHooks = shouldInterceptTools ? buildToolMockHooks(agent, matcher, mockAbort) : void 0;
	const generateSignal = mockAbort && signal ? AbortSignal.any([signal, mockAbort.signal]) : mockAbort?.signal ?? signal;
	const mockConcurrency = shouldInterceptTools ? { toolCallConcurrency: 1 } : void 0;
	const assignedTraceId = globalThis.crypto.randomUUID().replaceAll("-", "");
	onTraceIdAssigned?.(assignedTraceId);
	const tracingOptions = {
		traceId: assignedTraceId,
		...experimentId || agentModel ? { metadata: {
			...experimentId ? { experimentId } : {},
			...agentModel ? { agentModel: agentModelLabel(agentModel) } : {}
		} } : {}
	};
	let rawResult;
	try {
		rawResult = !useLegacy ? await agent.generate(input, {
			scorers: {},
			returnScorerData: true,
			abortSignal: generateSignal,
			...memoryOption,
			...reqCtx ? { requestContext: reqCtx } : {},
			tracingOptions,
			...versions ? { versions } : {},
			...agentModel ? { model: agentModel } : {},
			...mockHooks ? { hooks: mockHooks } : {},
			...mockConcurrency ?? {}
		}) : await agent.generateLegacy(input, {
			scorers: {},
			returnScorerData: true,
			abortSignal: generateSignal,
			...memoryOption,
			...reqCtx ? { requestContext: reqCtx } : {},
			tracingOptions,
			...mockHooks ? { hooks: mockHooks } : {},
			...mockConcurrency ?? {}
		});
	} catch (error) {
		const mockReport = shouldInterceptTools ? matcher.report() : void 0;
		if (mockReport?.failure) return toolMockFailureResult(mockReport, assignedTraceId);
		throw error;
	}
	const result = rawResult;
	const traceId = result.traceId ?? null;
	const scoringData = result.scoringData;
	const toolMockReport = shouldInterceptTools ? matcher.report() : void 0;
	if (toolMockReport?.failure) return toolMockFailureResult(toolMockReport, traceId ?? assignedTraceId);
	return {
		output: {
			text: result.text,
			object: result.object,
			toolCalls: result.toolCalls,
			toolResults: result.toolResults,
			sources: result.sources,
			files: result.files,
			usage: result.usage,
			reasoningText: result.reasoningText,
			traceId,
			error: result.error ? {
				message: result.error.message,
				stack: result.error.stack
			} : null
		},
		error: null,
		traceId,
		scorerInput: scoringData?.input,
		scorerOutput: scoringData?.output,
		...toolMockReport ? { toolMockReport } : {}
	};
}
/** Build the deterministic, non-retryable failure result for a mis-called mock. */
function toolMockFailureResult(report, traceId) {
	const failure = report.failure;
	return {
		output: null,
		error: {
			message: failure.code === "TOOL_MOCK_NOT_DECLARED" ? `Tool "${failure.toolName}" was called without a declared mock (${failure.code}).` : `Mocked tool "${failure.toolName}" was called with arguments that did not match an available mock (${failure.code}).`,
			code: failure.code
		},
		traceId,
		toolMockReport: report
	};
}
/**
* Compose item-level tool mocks with the agent's configured tool hooks into a
* single set of run-level hooks.
*
* Composition order (per spec):
*  1. User `beforeToolCall` (if `{ proceed: false }`, short-circuit — the mock is
*     left unconsumed and reported as such; user `afterToolCall` is NOT called,
*     matching the agent's own short-circuit behavior).
*  2. Mock matcher — `serve` returns the mocked output; `fail` aborts the run so
*     the model cannot call any further (possibly unmocked, side-effecting) tools
*     live; `live` falls through to the real tool.
*  3. User `afterToolCall` runs for served mocks (the agent skips its own on
*     short-circuit, so it is invoked here to honor the documented composition).
*
* Ordered consumption of repeated `(toolName, args)` mocks is deterministic because
* the caller forces `toolCallConcurrency: 1` when mocks exist, so tool calls arrive
* (and consume) in the provider's call order — no mutex needed.
*/
function buildToolMockHooks(agent, matcher, mockAbort) {
	const userHooks = agent.getConfiguredToolHooks();
	return {
		beforeToolCall: async (context) => {
			const userResult = await userHooks?.beforeToolCall?.(context);
			if (userResult?.proceed === false) return userResult;
			const resolution = matcher.resolve(context.toolName, context.input);
			if (resolution.kind === "serve") {
				recordMockedToolCallSpan(context, resolution.output, true);
				await userHooks?.afterToolCall?.({
					...context,
					output: resolution.output
				});
				return {
					proceed: false,
					output: resolution.output
				};
			}
			if (resolution.kind === "fail") {
				const output = { error: resolution.code };
				recordMockedToolCallSpan(context, output, false);
				mockAbort.abort(/* @__PURE__ */ new Error(`Tool mock failure for "${context.toolName}" (${resolution.code})`));
				return {
					proceed: false,
					output
				};
			}
		},
		afterToolCall: userHooks?.afterToolCall
	};
}
/**
* Record a `tool_call` span for a tool call the mock matcher short-circuited.
*
* The real tool never runs, so `CoreToolBuilder` never opens its span and the
* trace would show only model steps. This span mirrors the builder's shape and
* is flagged `mocked: true` so trace readers can tell a mock-intercepted call
* (served, mismatched, exhausted or denied) from a live call. Without a current
* span (observability off) nothing is recorded.
*/
function recordMockedToolCallSpan(context, output, success) {
	const invocation = context.context;
	getOrCreateSpan({
		type: "tool_call",
		name: `tool: '${context.toolName}'`,
		input: context.input,
		entityType: EntityType.TOOL,
		entityId: context.toolName,
		entityName: context.toolName,
		attributes: {
			toolType: "tool",
			toolCallId: invocation?.toolCallId,
			mocked: true
		},
		tracingPolicy: invocation?.tracingContext?.currentSpan?.tracingPolicy,
		tracingContext: invocation?.tracingContext,
		requestContext: invocation?.requestContext
	})?.end({
		output,
		attributes: { success }
	});
}
/**
* Extract resume data from item fields and metadata.
*
* Checks top-level `resumeSteps`/`resumeData` first (inline data path),
* then falls back to `metadata.resumeSteps`/`metadata.resumeData` (storage-backed path).
*
* Supports two shapes:
* 1. Keyed by step ID: `resumeSteps: { "step-id": <payload> }`
*    Used when the workflow may suspend on multiple steps and each needs distinct data.
* 2. Flat payload: `resumeData: <payload>`
*    Used when the workflow has a single suspended step (auto-detected).
*/
function extractResumeData(item) {
	return {
		perStep: item.resumeSteps !== void 0 ? item.resumeSteps : item.metadata?.resumeSteps,
		flat: item.resumeData !== void 0 ? item.resumeData : item.metadata?.resumeData
	};
}
/**
* Execute a dataset item against a workflow.
* Creates a run with scorers disabled to avoid double-scoring.
*
* When the workflow suspends, checks for resume data in `item.metadata`
* (via `resumeSteps` keyed by step ID or `resumeData` for single-step workflows)
* and automatically resumes. Loops through multiple suspend/resume cycles up to
* MAX_RESUME_CYCLES to support multi-step suspend workflows.
*
* Mirrors `executeWorkflow` in evals/run so dataset experiments and runEvals
* produce the same observability spans and scoring data for workflow targets.
*/
async function executeWorkflow(workflow, item, requestContext, experimentId) {
	const reqCtx = requestContext ? new RequestContext(Object.entries(requestContext)) : void 0;
	const observabilityContext = resolveObservabilityContext({});
	const tracingOptions = experimentId ? { tracingOptions: { metadata: { experimentId } } } : {};
	const run = await workflow.createRun({ disableScorers: true });
	let result = await run.start({
		inputData: item.input,
		...reqCtx ? { requestContext: reqCtx } : {},
		...observabilityContext,
		...tracingOptions
	});
	const { perStep, flat } = extractResumeData(item);
	if (perStep !== void 0 || flat !== void 0) {
		let cycle = 0;
		while (result.status === "suspended" && cycle < MAX_RESUME_CYCLES) {
			cycle++;
			const suspendedPaths = result.suspended ?? [];
			if (suspendedPaths.length === 0) break;
			let stepToResume;
			let stepResumeData;
			for (const suspendedPath of suspendedPaths) {
				const suspendedStep = suspendedPath?.[0];
				if (!suspendedStep) continue;
				const perStepValue = perStep?.[suspendedStep];
				const candidate = perStepValue !== void 0 ? perStepValue : flat;
				if (candidate === void 0) continue;
				stepToResume = suspendedStep;
				stepResumeData = candidate;
				break;
			}
			if (stepToResume === void 0) break;
			result = await run.resume({
				resumeData: stepResumeData,
				step: stepToResume,
				...reqCtx ? { requestContext: reqCtx } : {},
				...observabilityContext,
				...tracingOptions
			});
		}
	}
	return handleWorkflowResult({
		...result,
		steps: await loadStepResults(result.steps)
	});
}
/**
* Map a terminal WorkflowResult to an ExecutionResult.
* Uses a loose `result: any` parameter because WorkflowResult is heavily generic;
* status-narrowing guards below keep accesses safe.
*/
function handleWorkflowResult(result) {
	const traceId = result.traceId ?? null;
	const spanId = result.spanId ?? null;
	if (result.status === "success") return {
		output: result.result,
		error: null,
		traceId,
		spanId,
		stepResults: result.steps,
		stepExecutionPath: result.stepExecutionPath
	};
	if (result.status === "failed") return {
		output: null,
		error: {
			message: result.error?.message ?? "Workflow failed",
			stack: result.error?.stack
		},
		traceId,
		spanId,
		stepResults: result.steps,
		stepExecutionPath: result.stepExecutionPath
	};
	if (result.status === "tripwire") return {
		output: null,
		error: { message: `Workflow tripwire: ${result.tripwire?.reason ?? "Unknown reason"}` },
		traceId,
		spanId,
		stepResults: result.steps,
		stepExecutionPath: result.stepExecutionPath
	};
	if (result.status === "suspended") return {
		output: result.suspendPayload ?? null,
		error: { message: "Workflow suspended — provide resume data via item.resumeSteps/item.resumeData (or metadata.resumeSteps/metadata.resumeData) to auto-resume" },
		traceId,
		spanId,
		stepResults: result.steps,
		stepExecutionPath: result.stepExecutionPath
	};
	if (result.status === "paused") return {
		output: null,
		error: { message: "Workflow paused - not yet supported in dataset experiments" },
		traceId,
		spanId,
		stepResults: result.steps,
		stepExecutionPath: result.stepExecutionPath
	};
	return {
		output: null,
		error: { message: `Workflow ended with unexpected status: ${result.status}` },
		traceId,
		spanId
	};
}
// src/datasets/experiment/resolve-target.ts
/**
* Resolve a target from Mastra's registries by type and ID.
* When `agentVersion` is provided for an agent target, the returned agent
* will have the versioned config applied (via `applyStoredOverrides`).
*
* The result is wrapped in `{ target }` because `Workflow` has a `.then`
* method for step chaining, which makes it thenable. Returning a thenable
* from an async function causes the Promise machinery to attempt to unwrap
* it, which hangs forever since the builder `.then` never invokes its
* callbacks. Wrapping in a plain object avoids the unwrap.
*/
async function resolveTarget(mastra, targetType, targetId, agentVersion) {
	let resolved = null;
	switch (targetType) {
		case "agent":
			try {
				if (agentVersion) resolved = await mastra.getAgentById(targetId, { versionId: agentVersion });
				else resolved = mastra.getAgentById(targetId);
			} catch {
				try {
					if (agentVersion) resolved = await mastra.getAgent(targetId, { versionId: agentVersion });
					else resolved = mastra.getAgent(targetId);
				} catch {}
			}
			break;
		case "workflow":
			try {
				resolved = mastra.getWorkflowById(targetId);
			} catch {
				try {
					resolved = mastra.getWorkflow(targetId);
				} catch {}
			}
			break;
		case "scorer": try {
			resolved = mastra.getScorerById(targetId) ?? null;
		} catch {}
	}
	return resolved ? { target: resolved } : null;
}
// src/datasets/experiment/scorer.ts
function toScorerTargetEntityType(targetType) {
	switch (targetType) {
		case "agent": return EntityType.AGENT;
		case "workflow": return EntityType.WORKFLOW_RUN;
		case "scorer": return EntityType.SCORER;
		default: return;
	}
}
function getItemScorerById(mastra, scorerId) {
	try {
		return mastra.getScorerById(scorerId) ?? null;
	} catch {
		return null;
	}
}
/**
* Resolve scorers from mixed array of instances and string IDs.
* String IDs are looked up from Mastra's scorer registry.
*/
function resolveScorers(mastra, scorers) {
	if (!scorers || scorers.length === 0) return [];
	return scorers.map((scorer) => {
		if (typeof scorer === "string") {
			const resolved = mastra.getScorerById(scorer);
			if (!resolved) {
				console.warn(`Scorer not found: ${scorer}`);
				return null;
			}
			return resolved;
		}
		return scorer;
	}).filter((s) => s !== null);
}
const EXPERIMENT_ITEM_SCORER_NOT_FOUND = "EXPERIMENT_ITEM_SCORER_NOT_FOUND";
/**
* Create a run-scoped resolver for item scorer IDs. Resolutions, including misses,
* are cached so concurrent items hydrate a stored scorer at most once per run.
*/
function createItemScorerResolver(mastra) {
	const resolutionCache = /* @__PURE__ */ new Map();
	const resolveById = (scorerId) => {
		const cached = resolutionCache.get(scorerId);
		if (cached) return cached;
		const resolution = (async () => {
			let scorer = getItemScorerById(mastra, scorerId);
			if (scorer) return scorer;
			const editor = mastra.getEditor?.();
			if (editor) {
				try {
					await editor.scorer.getById(scorerId);
				} catch {}
				scorer = getItemScorerById(mastra, scorerId);
			}
			return scorer;
		})();
		resolutionCache.set(scorerId, resolution);
		return resolution;
	};
	return async (scorerIds) => {
		const uniqueIds = [...new Set(scorerIds)];
		const resolved = await Promise.all(uniqueIds.map(async (id) => ({
			id,
			scorer: await resolveById(id)
		})));
		return {
			scorers: resolved.flatMap(({ scorer }) => scorer ? [scorer] : []),
			missingIds: resolved.flatMap(({ id, scorer }) => scorer ? [] : [id])
		};
	};
}
/**
* Attempt to extract a Trajectory from the observability trace store.
* Falls back to undefined if storage is unavailable or the trace has no spans.
* Callers flush observability first (see `flushForTrajectoryScorers`).
*/
async function extractTrajectoryFromStorage(storage, traceId) {
	if (!storage || !traceId) return void 0;
	try {
		const observabilityStore = await storage.getStore("observability");
		if (!observabilityStore) return void 0;
		const trace = await observabilityStore.getTrace({ traceId });
		if (!trace?.spans?.length) return void 0;
		return extractTrajectoryFromTrace(trace.spans);
	} catch (error) {
		console.warn(`Failed to read trace ${traceId}; trajectory scorers get a flat trajectory from the run output instead:`, error);
		return;
	}
}
/** Flush before the trace read, only when a trajectory scorer will read the trace. */
async function flushForTrajectoryScorers(mastra, scorers, traceId) {
	if (scorers.some((s) => s.type === "trajectory")) await flushBeforeTraceRead(mastra, traceId);
}
/**
* Run all scorers for a single item result.
* Errors are isolated per scorer - one failing scorer doesn't affect others.
* Trajectory scorers (scorer.type === 'trajectory') receive a pre-extracted
* Trajectory as their output, mirroring the dispatch runEvals performs.
*
* `persistScores: false` suppresses score writes while leaving `storage` usable
* for reads. The two are deliberately separate parameters: `storage` is also the
* source for trajectory extraction, so nulling it to stop writes would silently
* downgrade trajectory scorers to the raw-message fallback.
*/
/**
* Deterministic score id for experiment score rows. Retried executions of the
* same (experiment, item, attempt, scorer) produce the same id, so the scores
* store upserts (latest wins) instead of accumulating duplicate rows.
*/
function experimentScoreId(experimentId, itemId, attempt, scorerId) {
	return `${experimentScoreKey(experimentId, itemId, attempt)}:${scorerId}`;
}
/** Prefix shared by all scores of one (experiment, item, attempt) execution. */
function experimentScoreKey(experimentId, itemId, attempt) {
	return `expscore:${experimentId}:${itemId}:${attempt}`;
}
async function runScorersForItem(scorers, item, output, storage, runId, targetType, targetId, itemId, scorerInput, scorerOutput, traceId, workflowData, persistScores = true, stableScoreKey) {
	if (scorers.length === 0) return [];
	const hasTrajectoryScorer = scorers.some((s) => s.type === "trajectory");
	let trajectoryOutput;
	if (hasTrajectoryScorer) trajectoryOutput = await extractTrajectoryFromStorage(storage, traceId) ?? (scorerOutput ? extractTrajectory(scorerOutput) : workflowData?.stepResults ? extractWorkflowTrajectory(workflowData.stepResults, workflowData.stepExecutionPath) : { steps: [] });
	const targetCorrelationContext = {
		...traceId ? { traceId } : {},
		entityType: toScorerTargetEntityType(targetType),
		entityId: targetId,
		entityName: targetId,
		experimentId: runId
	};
	return (await Promise.allSettled(scorers.map(async (scorer) => {
		const { result, promptMetadata } = await runScorerSafe(scorer, item, output, scorerInput, scorerOutput, targetType, traceId, targetCorrelationContext, scorer.type === "trajectory" ? trajectoryOutput : void 0, workflowData, persistScores);
		if (persistScores && storage && result.error === null && result.score !== null) try {
			await validateAndSaveScore(storage, {
				...stableScoreKey ? { id: `${stableScoreKey}:${scorer.id}` } : {},
				scorerId: scorer.id,
				score: result.score,
				reason: result.reason ?? void 0,
				input: item.input,
				output,
				additionalContext: item.metadata,
				entityType: targetType.toUpperCase(),
				entityId: itemId,
				source: "TEST",
				runId,
				traceId,
				scorer: {
					id: scorer.id,
					name: scorer.name,
					description: scorer.description ?? "",
					hasJudge: !!scorer.judge
				},
				entity: {
					id: targetId,
					name: targetId
				},
				...promptMetadata
			});
		} catch (saveError) {
			console.warn(`Failed to save score for scorer ${scorer.id}:`, saveError);
		}
		return result;
	}))).map((s, i) => {
		if (s.status === "fulfilled") return s.value;
		const scorer = scorers[i];
		return {
			scorerId: scorer.id,
			scorerName: scorer.name,
			score: null,
			reason: null,
			error: String(s.reason),
			targetScope: scorer.type === "trajectory" ? "trajectory" : "span"
		};
	});
}
function extractScorerRunFields(scoreResult) {
	if (typeof scoreResult !== "object" || scoreResult === null) return {
		score: null,
		reason: null,
		promptMetadata: {}
	};
	const fields = scoreResult;
	const str = (key) => typeof fields[key] === "string" ? fields[key] : void 0;
	const obj = (key) => {
		const value = fields[key];
		return typeof value === "object" && value !== null ? value : void 0;
	};
	const notScorable = obj("notScorable");
	return {
		score: typeof fields.score === "number" ? fields.score : null,
		reason: typeof fields.reason === "string" ? fields.reason : null,
		...notScorable && typeof notScorable.step === "string" ? { notScorable: {
			step: notScorable.step,
			...typeof notScorable.reason === "string" ? { reason: notScorable.reason } : {}
		} } : {},
		promptMetadata: {
			generateScorePrompt: str("generateScorePrompt"),
			generateReasonPrompt: str("generateReasonPrompt"),
			preprocessStepResult: obj("preprocessStepResult"),
			preprocessPrompt: str("preprocessPrompt"),
			analyzeStepResult: obj("analyzeStepResult"),
			analyzePrompt: str("analyzePrompt")
		}
	};
}
/**
* Run a single scorer safely, catching any errors.
* Returns both the ScorerResult and prompt metadata for DB persistence.
* When trajectoryOutput is provided the scorer receives it as run.output,
* honoring the type: 'trajectory' contract.
*/
async function runScorerSafe(scorer, item, output, scorerInput, scorerOutput, targetType, targetTraceId, targetCorrelationContext, trajectoryOutput, workflowData, persistScores = true) {
	try {
		const effectiveOutput = trajectoryOutput ?? scorerOutput ?? output;
		const effectiveScope = trajectoryOutput ? "trajectory" : "span";
		const targetMetadata = !trajectoryOutput && workflowData && (workflowData.stepResults || workflowData.stepExecutionPath) ? {
			...workflowData.stepResults ? { stepResults: workflowData.stepResults } : {},
			...workflowData.stepExecutionPath ? { stepExecutionPath: workflowData.stepExecutionPath } : {}
		} : void 0;
		const scoreResult = await scorer.run({
			input: scorerInput ?? item.input,
			output: effectiveOutput,
			groundTruth: item.groundTruth,
			expectedTrajectory: item.expectedTrajectory,
			scoreSource: "experiment",
			targetScope: effectiveScope,
			targetEntityType: toScorerTargetEntityType(targetType),
			targetTraceId,
			...workflowData?.spanId ? { targetSpanId: workflowData.spanId } : {},
			...targetCorrelationContext ? { targetCorrelationContext } : {},
			...targetMetadata ? { targetMetadata } : {},
			_internal: { emitObservabilityScore: persistScores }
		});
		if (typeof scoreResult !== "object" || scoreResult === null) return {
			result: {
				scorerId: scorer.id,
				scorerName: scorer.name,
				score: null,
				reason: null,
				error: `Scorer ${scorer.name} (${scorer.id}) returned invalid result: expected object, got ${scoreResult === null ? "null" : typeof scoreResult} (${String(scoreResult)})`
			},
			promptMetadata: {}
		};
		const { score, reason, notScorable, promptMetadata } = extractScorerRunFields(scoreResult);
		return {
			result: {
				scorerId: scorer.id,
				scorerName: scorer.name,
				score,
				reason,
				error: null,
				...notScorable ? { notScorable } : {},
				targetScope: effectiveScope
			},
			promptMetadata
		};
	} catch (error) {
		if (error instanceof ScorerRunError) {
			const { score, reason, promptMetadata } = extractScorerRunFields(error.result);
			return {
				result: {
					scorerId: scorer.id,
					scorerName: scorer.name,
					score,
					reason,
					error: error.message,
					failedStep: error.failedStep,
					completedSteps: error.completedSteps,
					targetScope: trajectoryOutput ? "trajectory" : "span"
				},
				promptMetadata
			};
		}
		return {
			result: {
				scorerId: scorer.id,
				scorerName: scorer.name,
				score: null,
				reason: null,
				error: error instanceof Error ? error.message : String(error),
				targetScope: trajectoryOutput ? "trajectory" : "span"
			},
			promptMetadata: {}
		};
	}
}
/**
* Resolve step-scoped scorers from a `Record<stepId, (MastraScorer | string)[]>`.
* String IDs are looked up from Mastra's scorer registry; missing IDs are skipped
* with a warning (matching `resolveScorers`).
*/
function resolveStepScorers(mastra, stepsConfig) {
	if (!stepsConfig) return {};
	const resolved = {};
	for (const [stepId, scorers] of Object.entries(stepsConfig)) {
		const stepScorers = resolveScorers(mastra, scorers);
		if (stepScorers.length > 0) resolved[stepId] = stepScorers;
	}
	return resolved;
}
/**
* Run step-scoped scorers for a single workflow item. Mirrors the per-step
* dispatch in `runEvals`: each scorer runs against `stepResult.payload` and
* `stepResult.output`, with `targetScope: 'span'` and
* `targetEntityType: WORKFLOW_STEP`. The returned `ScorerResult` carries the
* originating `stepId` so callers can disambiguate per-step results in the
* flat `scores` array. Steps whose result is missing or did not succeed
* surface as an error `ScorerResult` rather than disappearing silently.
*
* Errors are isolated per scorer (consistent with `runScorersForItem`); a
* failing scorer produces a `ScorerResult` with `error` set, not a throw.
*/
async function runStepScorersForItem(stepScorers, item, workflowData, storage, runId, targetType, targetId, itemId, traceId, persistScores = true) {
	const stepIds = Object.keys(stepScorers);
	if (stepIds.length === 0) return [];
	const results = [];
	const stepResults = workflowData?.stepResults;
	for (const stepId of stepIds) {
		const scorers = stepScorers[stepId];
		const stepResult = stepResults?.[stepId];
		if (!stepResult || stepResult.status !== "success" || stepResult.output === void 0) {
			for (const scorer of scorers) results.push({
				scorerId: scorer.id,
				scorerName: scorer.name,
				score: null,
				reason: null,
				error: `Step "${stepId}" did not produce a successful output (status: ${stepResult?.status ?? "missing"})`,
				targetScope: "span",
				stepId
			});
			continue;
		}
		const stepInput = stepResult.payload !== void 0 ? stepResult.payload : item.input;
		const stepOutput = stepResult.output;
		const targetCorrelationContext = {
			...traceId ? { traceId } : {},
			entityType: EntityType.WORKFLOW_STEP,
			entityId: stepId,
			entityName: stepId,
			experimentId: runId
		};
		const settled = await Promise.allSettled(scorers.map(async (scorer) => {
			try {
				const scoreResult = await scorer.run({
					input: stepInput,
					output: stepOutput,
					groundTruth: item.groundTruth,
					expectedTrajectory: item.expectedTrajectory,
					scoreSource: "experiment",
					targetScope: "span",
					targetEntityType: EntityType.WORKFLOW_STEP,
					targetTraceId: traceId,
					...targetCorrelationContext ? { targetCorrelationContext } : {},
					_internal: { emitObservabilityScore: persistScores }
				});
				if (typeof scoreResult !== "object" || scoreResult === null) return {
					scorerId: scorer.id,
					scorerName: scorer.name,
					score: null,
					reason: null,
					error: `Scorer ${scorer.name} (${scorer.id}) returned invalid result on step ${stepId}`,
					targetScope: "span",
					stepId
				};
				const { score, reason, notScorable } = extractScorerRunFields(scoreResult);
				if (persistScores && storage && score !== null) try {
					await validateAndSaveScore(storage, {
						scorerId: scorer.id,
						score,
						reason: reason ?? void 0,
						input: stepInput,
						output: stepOutput,
						additionalContext: {
							...item.metadata,
							stepId
						},
						entityType: "STEP",
						entityId: itemId,
						source: "TEST",
						runId,
						traceId,
						scorer: {
							id: scorer.id,
							name: scorer.name,
							description: scorer.description ?? "",
							hasJudge: !!scorer.judge
						},
						entity: {
							id: targetId,
							name: targetId
						}
					});
				} catch (saveError) {
					console.warn(`Failed to save score for step scorer ${scorer.id} on ${stepId}:`, saveError);
				}
				return {
					scorerId: scorer.id,
					scorerName: scorer.name,
					score,
					reason,
					error: null,
					...notScorable ? { notScorable } : {},
					targetScope: "span",
					stepId
				};
			} catch (error) {
				if (error instanceof ScorerRunError) {
					const { score, reason } = extractScorerRunFields(error.result);
					return {
						scorerId: scorer.id,
						scorerName: scorer.name,
						score,
						reason,
						error: error.message,
						failedStep: error.failedStep,
						completedSteps: error.completedSteps,
						targetScope: "span",
						stepId
					};
				}
				return {
					scorerId: scorer.id,
					scorerName: scorer.name,
					score: null,
					reason: null,
					error: error instanceof Error ? error.message : String(error),
					targetScope: "span",
					stepId
				};
			}
		}));
		for (let i = 0; i < settled.length; i++) {
			const s = settled[i];
			if (s.status === "fulfilled") results.push(s.value);
			else {
				const scorer = scorers[i];
				results.push({
					scorerId: scorer.id,
					scorerName: scorer.name,
					score: null,
					reason: null,
					error: String(s.reason),
					targetScope: "span",
					stepId
				});
			}
		}
	}
	return results;
}
// src/datasets/experiment/analytics/aggregate.ts
/**
* Compute the arithmetic mean of an array of numbers.
*
* @param values - Array of numbers to average
* @returns Mean value, or 0 if array is empty
*/
function computeMean(values) {
	if (values.length === 0) return 0;
	return values.reduce((acc, val) => acc + val, 0) / values.length;
}
/**
* Compute aggregate statistics for a set of scores.
*
* Metrics:
* - errorRate: proportion of items with null scores (errors)
* - passRate: proportion of scored items meeting threshold
* - avgScore: mean of non-null scores
*
* @param scores - Score records from storage
* @param passThreshold - Absolute threshold for pass (score >= threshold)
* @returns ScorerStats with all computed metrics
*/
function computeScorerStats(scores, passThreshold = .5) {
	const totalItems = scores.length;
	if (totalItems === 0) return {
		errorRate: 0,
		errorCount: 0,
		passRate: 0,
		passCount: 0,
		avgScore: 0,
		scoreCount: 0,
		totalItems: 0
	};
	const validScores = [];
	let errorCount = 0;
	for (const score of scores) if (score.score === null || score.score === void 0) errorCount++;
	else validScores.push(score.score);
	const scoreCount = validScores.length;
	const errorRate = errorCount / totalItems;
	const passCount = validScores.filter((s) => s >= passThreshold).length;
	const passRate = scoreCount > 0 ? passCount / scoreCount : 0;
	const avgScore = computeMean(validScores);
	return {
		errorRate,
		errorCount,
		passRate,
		passCount,
		avgScore,
		scoreCount,
		totalItems
	};
}
/**
* Determine if a score delta represents a regression.
*
* @param delta - Score difference (experiment B - experiment A)
* @param threshold - Absolute threshold for regression detection
* @param direction - Score direction ('higher-is-better' or 'lower-is-better')
* @returns True if delta represents a regression
*
* @example
* // Higher is better (default): negative delta is bad
* isRegression(-0.1, 0.05, 'higher-is-better') // true (dropped more than 0.05)
* isRegression(-0.01, 0.05, 'higher-is-better') // false (within tolerance)
*
* // Lower is better: positive delta is bad
* isRegression(0.1, 0.05, 'lower-is-better') // true (increased more than 0.05)
*/
function isRegression(delta, threshold, direction = "higher-is-better") {
	if (direction === "higher-is-better") return delta < -threshold;
	return delta > threshold;
}
// src/datasets/experiment/analytics/compare.ts
/**
* Default threshold when not specified: no tolerance for regression.
*/
const DEFAULT_THRESHOLD = {
	value: 0,
	direction: "higher-is-better"
};
/**
* Default pass threshold for computing pass rate.
*/
const DEFAULT_PASS_THRESHOLD = .5;
/**
* Compare two experiments to detect score regressions.
*
* @param mastra - Mastra instance for storage access
* @param config - Comparison configuration
* @returns ComparisonResult with per-scorer and per-item comparisons
*
* @example
* ```typescript
* const result = await compareExperiments(mastra, {
*   experimentIdA: 'baseline-experiment-id',
*   experimentIdB: 'candidate-experiment-id',
*   thresholds: {
*     'accuracy': { value: 0.05, direction: 'higher-is-better' },
*     'latency': { value: 100, direction: 'lower-is-better' },
*   },
* });
*
* if (result.hasRegression) {
*   console.log('Quality regression detected!');
* }
* ```
*/
async function compareExperiments(mastra, config) {
	const { experimentIdA, experimentIdB, thresholds = {} } = config;
	const warnings = [];
	const storage = mastra.getStorage();
	if (!storage) throw new Error("Storage not configured. Configure storage in Mastra instance.");
	const experimentsStore = await storage.getStore("experiments");
	const scoresStore = await storage.getStore("scores");
	if (!experimentsStore) throw new Error("ExperimentsStorage not configured.");
	if (!scoresStore) throw new Error("ScoresStorage not configured.");
	const [experimentA, experimentB] = await Promise.all([experimentsStore.getExperimentById({ id: experimentIdA }), experimentsStore.getExperimentById({ id: experimentIdB })]);
	if (!experimentA) throw new Error(`Experiment not found: ${experimentIdA}`);
	if (!experimentB) throw new Error(`Experiment not found: ${experimentIdB}`);
	const versionMismatch = experimentA.datasetVersion !== experimentB.datasetVersion;
	if (versionMismatch) warnings.push(`Experiments have different dataset versions: ${experimentA.datasetVersion} vs ${experimentB.datasetVersion}`);
	const [resultsA, resultsB] = await Promise.all([experimentsStore.listExperimentResults({
		experimentId: experimentIdA,
		pagination: {
			page: 0,
			perPage: false
		}
	}), experimentsStore.listExperimentResults({
		experimentId: experimentIdB,
		pagination: {
			page: 0,
			perPage: false
		}
	})]);
	const [scoresA, scoresB] = await Promise.all([scoresStore.listScoresByRunId({
		runId: experimentIdA,
		pagination: {
			page: 0,
			perPage: false
		}
	}), scoresStore.listScoresByRunId({
		runId: experimentIdB,
		pagination: {
			page: 0,
			perPage: false
		}
	})]);
	if (resultsA.results.length === 0 && resultsB.results.length === 0) {
		warnings.push("Both experiments have no results.");
		return buildEmptyResult(experimentA, experimentB, versionMismatch, warnings);
	}
	if (resultsA.results.length === 0) warnings.push("Experiment A has no results.");
	if (resultsB.results.length === 0) warnings.push("Experiment B has no results.");
	const itemIdsA = new Set(resultsA.results.map((r) => r.itemId));
	const itemIdsB = new Set(resultsB.results.map((r) => r.itemId));
	if ([...itemIdsA].filter((id) => itemIdsB.has(id)).length === 0) warnings.push("No overlapping items between experiments.");
	const scoresMapA = groupScoresByScorerAndItem(scoresA.scores);
	const scoresMapB = groupScoresByScorerAndItem(scoresB.scores);
	const allScorerIds = /* @__PURE__ */ new Set([...scoresMapA.keys(), ...scoresMapB.keys()]);
	const scorerEntries = [];
	let hasRegression = false;
	for (const scorerId of allScorerIds) {
		const scoresArrayA = [...scoresMapA.get(scorerId)?.values() ?? []];
		const scoresArrayB = [...scoresMapB.get(scorerId)?.values() ?? []];
		const thresholdConfig = (Object.hasOwn(thresholds, scorerId) ? thresholds[scorerId] : void 0) ?? DEFAULT_THRESHOLD;
		const threshold = thresholdConfig.value;
		const direction = thresholdConfig.direction ?? "higher-is-better";
		const statsA = computeScorerStats(scoresArrayA, DEFAULT_PASS_THRESHOLD);
		const statsB = computeScorerStats(scoresArrayB, DEFAULT_PASS_THRESHOLD);
		const delta = statsB.avgScore - statsA.avgScore;
		const regressed = isRegression(delta, threshold, direction);
		if (regressed) hasRegression = true;
		scorerEntries.push([scorerId, {
			statsA,
			statsB,
			delta,
			regressed,
			threshold
		}]);
	}
	const scorers = Object.fromEntries(scorerEntries);
	const allItemIds = /* @__PURE__ */ new Set([...itemIdsA, ...itemIdsB]);
	const items = [];
	for (const itemId of allItemIds) {
		const inBothExperiments = itemIdsA.has(itemId) && itemIdsB.has(itemId);
		const scorerIds = [...allScorerIds];
		items.push({
			itemId,
			inBothExperiments,
			scoresA: Object.fromEntries(scorerIds.map((scorerId) => [scorerId, scoresMapA.get(scorerId)?.get(itemId)?.score ?? null])),
			scoresB: Object.fromEntries(scorerIds.map((scorerId) => [scorerId, scoresMapB.get(scorerId)?.get(itemId)?.score ?? null]))
		});
	}
	return {
		experimentA: {
			id: experimentA.id,
			datasetVersion: experimentA.datasetVersion
		},
		experimentB: {
			id: experimentB.id,
			datasetVersion: experimentB.datasetVersion
		},
		versionMismatch,
		hasRegression,
		scorers,
		items,
		warnings
	};
}
/**
* Group scores by scorer ID, then by item ID.
*/
function groupScoresByScorerAndItem(scores) {
	const grouped = /* @__PURE__ */ new Map();
	for (const score of scores) {
		const itemId = score.entityId;
		let items = grouped.get(score.scorerId);
		if (!items) {
			items = /* @__PURE__ */ new Map();
			grouped.set(score.scorerId, items);
		}
		const attempts = items.get(itemId);
		if (attempts) attempts.push(score);
		else items.set(itemId, [score]);
	}
	const result = /* @__PURE__ */ new Map();
	for (const [scorerId, items] of grouped) {
		const averaged = /* @__PURE__ */ new Map();
		result.set(scorerId, averaged);
		for (const [itemId, attempts] of items) {
			const first = attempts[0];
			const validScores = attempts.map((attempt) => attempt.score).filter((score) => score !== null && score !== void 0);
			averaged.set(itemId, {
				...first,
				score: validScores.length > 0 ? validScores.reduce((sum, score) => sum + score, 0) / validScores.length : first.score
			});
		}
	}
	return result;
}
/**
* Build an empty comparison result for edge cases.
*/
function buildEmptyResult(experimentA, experimentB, versionMismatch, warnings) {
	return {
		experimentA: {
			id: experimentA.id,
			datasetVersion: experimentA.datasetVersion
		},
		experimentB: {
			id: experimentB.id,
			datasetVersion: experimentB.datasetVersion
		},
		versionMismatch,
		hasRegression: false,
		scorers: {},
		items: [],
		warnings
	};
}
// src/datasets/experiment/item.ts
/**
* Execute one experiment item: resolve the experiment's target, run it against
* the item, run the resolved scorers, and upsert the result row keyed by
* `(experimentId, itemId, attempt)` so a retried caller (e.g. a retried
* Temporal activity) converges on a single row.
*
* Scorer precedence mirrors the in-process runner: experiment `scorerIds` →
* item `scorerIds` → dataset `scorerIds` → none. An item scorer reference to
* an unregistered scorer is a deterministic preflight failure
* ({@link EXPERIMENT_ITEM_SCORER_NOT_FOUND}): the target is not executed and
* the error is recorded on the row.
*
* Deliberately excludes the runner's loop-level concerns: hooks, event
* dispatch, tool mocks, and internal retries — retries/timeouts belong to the
* caller's orchestrator.
*/
async function executeExperimentItem(args) {
	const { mastra, experiment, item } = args;
	const attempt = args.attempt ?? 0;
	if (experiment.targetType === null || experiment.targetId === null) throw new MastraError({
		id: "EXPERIMENT_HAS_NO_TARGET",
		text: `Experiment ${experiment.id} has no target; results must be ingested via submitExperimentResult`,
		domain: "STORAGE",
		category: "USER"
	});
	const resolved = await resolveTarget(mastra, experiment.targetType, experiment.targetId, experiment.agentVersion ?? void 0);
	if (!resolved) throw new MastraError({
		id: "EXPERIMENT_TARGET_NOT_FOUND",
		text: `Target not found: ${experiment.targetType} "${experiment.targetId}"`,
		domain: "STORAGE",
		category: "USER"
	});
	let scorers = [];
	let scorerConfigError = null;
	if (experiment.scorerIds != null) scorers = resolveScorers(mastra, [...new Set(experiment.scorerIds)]);
	else if (item.scorerIds !== void 0) {
		const resolution = await createItemScorerResolver(mastra)(item.scorerIds);
		scorers = resolution.scorers;
		if (resolution.missingIds.length > 0) scorerConfigError = {
			code: EXPERIMENT_ITEM_SCORER_NOT_FOUND,
			message: `Item scorer configuration references unregistered scorer IDs: ${resolution.missingIds.join(", ")}`
		};
	} else scorers = resolveScorers(mastra, [...new Set(args.datasetScorerIds ?? [])]);
	const storage = mastra.getStorage();
	const experimentsStore = await storage?.getStore("experiments");
	if (!experimentsStore) throw new MastraError({
		id: "EXPERIMENTS_STORAGE_NOT_CONFIGURED",
		text: "ExperimentsStorage not configured. Configure storage in the Mastra instance.",
		domain: "STORAGE",
		category: "USER"
	});
	const startedAt = /* @__PURE__ */ new Date();
	const mergedRequestContext = args.requestContext || item.requestContext ? {
		...args.requestContext,
		...item.requestContext
	} : void 0;
	const execResult = scorerConfigError ? {
		output: null,
		error: scorerConfigError,
		traceId: null
	} : await executeTarget(resolved.target, experiment.targetType, item, {
		requestContext: mergedRequestContext,
		experimentId: experiment.id
	});
	const completedAt = /* @__PURE__ */ new Date();
	let scores = [];
	if (!scorerConfigError) {
		const workflowData = execResult.stepResults || execResult.stepExecutionPath ? {
			stepResults: execResult.stepResults,
			stepExecutionPath: execResult.stepExecutionPath,
			spanId: execResult.spanId
		} : void 0;
		await flushForTrajectoryScorers(mastra, scorers, execResult.traceId);
		scores = await runScorersForItem(scorers, item, execResult.output, storage ?? null, experiment.id, experiment.targetType, experiment.targetId, item.id, execResult.scorerInput, execResult.scorerOutput, execResult.traceId ?? void 0, workflowData, true, experimentScoreKey(experiment.id, item.id, attempt));
	}
	return {
		result: await experimentsStore.upsertExperimentResult({
			experimentId: experiment.id,
			itemId: item.id,
			attempt,
			itemDatasetVersion: item.datasetVersion,
			input: item.input,
			output: execResult.output,
			groundTruth: item.groundTruth ?? null,
			error: execResult.error,
			startedAt,
			completedAt,
			retryCount: 0,
			traceId: execResult.traceId,
			organizationId: args.organizationId ?? null,
			projectId: args.projectId ?? null
		}),
		scores
	};
}
// src/datasets/experiment/index.ts
/** Error code recorded on an item whose `beforeEach` hook threw. */
const EXPERIMENT_ITEM_BEFORE_EACH_FAILED = "EXPERIMENT_ITEM_BEFORE_EACH_FAILED";
const errorMessage = (err) => err instanceof Error ? err.message : String(err);
/**
* Run a dataset experiment against a target with optional scoring.
*
* Executes all items in the dataset concurrently (up to maxConcurrency) against
* the specified target (agent or workflow). Optionally applies scorers to each
* result and persists both results and scores to storage.
*
* @param mastra - Mastra instance for storage and target resolution
* @param config - Experiment configuration
* @returns ExperimentSummary with results and scores
*
* @example
* ```typescript
* const summary = await runExperiment(mastra, {
*   datasetId: 'my-dataset',
*   targetType: 'agent',
*   targetId: 'my-agent',
*   scorers: [accuracyScorer, latencyScorer],
*   maxConcurrency: 10,
* });
* console.log(`${summary.succeededCount}/${summary.totalItems} succeeded`);
* ```
*/
async function runExperiment(mastra, config) {
	const { datasetId, targetType, targetId, scorers: scorerInput, version, maxConcurrency = 5, signal, onEvent, itemTimeout, maxRetries = 0, experimentId: providedExperimentId, name, description, metadata, provenance, grouping, requestContext: globalRequestContext, agentVersion, versions, persistence, beforeAll, afterAll, beforeEach, afterEach } = config;
	const persistExperiments = persistence?.experiments !== "none";
	const persistScores = persistence?.scores !== "none";
	const startedAt = /* @__PURE__ */ new Date();
	const experimentId = providedExperimentId ?? crypto.randomUUID();
	const eventDispatcher = onEvent ? new ExperimentEventDispatcher(experimentId, onEvent) : void 0;
	const executionSignal = eventDispatcher ? signal ? AbortSignal.any([signal, eventDispatcher.abortController.signal]) : eventDispatcher.abortController.signal : signal;
	const eventTarget = {
		type: targetType ?? "task",
		id: targetId ?? "inline"
	};
	const hookArgs = {
		experimentId,
		mastra,
		signal: executionSignal
	};
	let afterAllRan = false;
	/**
	* Teardown counterpart to `beforeAll`. Idempotent so it can be invoked from
	* every exit path (normal return, failed return, observer-error rethrow)
	* without double-running. Errors are logged, never propagated — teardown must
	* not mask the run's real outcome.
	*/
	const runAfterAll = async (summary) => {
		if (!afterAll || afterAllRan) return;
		afterAllRan = true;
		try {
			await afterAll({
				...hookArgs,
				summary
			});
		} catch (hookError) {
			mastra.getLogger()?.error(`Experiment ${experimentId} afterAll hook failed: ${errorMessage(hookError)}`, { error: hookError });
		}
	};
	const storage = mastra.getStorage();
	const datasetsStore = await storage?.getStore("datasets");
	const experimentsStore = persistExperiments ? await storage?.getStore("experiments") : void 0;
	const markFailedForObserverError = async (counts) => {
		if (!experimentsStore) return;
		try {
			await experimentsStore.updateExperiment({
				id: experimentId,
				status: "failed",
				...counts
			});
		} catch {}
	};
	const markFailedOnSetupError = async (err) => {
		if (providedExperimentId && experimentsStore) try {
			await experimentsStore.updateExperiment({
				id: experimentId,
				status: "failed",
				completedAt: /* @__PURE__ */ new Date()
			});
		} catch (updateErr) {
			mastra.getLogger()?.error(`Failed to mark experiment ${experimentId} as failed: ${updateErr}`);
		}
		throw err;
	};
	let items;
	let datasetVersion;
	let datasetRecord;
	try {
		if (config.data) {
			items = (typeof config.data === "function" ? await config.data() : config.data).map((dataItem) => {
				return {
					id: dataItem.id ?? crypto.randomUUID(),
					datasetVersion: null,
					input: dataItem.input,
					groundTruth: dataItem.groundTruth,
					expectedTrajectory: dataItem.expectedTrajectory,
					requestContext: dataItem.requestContext,
					metadata: dataItem.metadata,
					resumeSteps: dataItem.resumeSteps,
					resumeData: dataItem.resumeData,
					toolMocks: dataItem.toolMocks,
					unmockedToolPolicy: dataItem.unmockedToolPolicy,
					scorerIds: dataItem.scorerIds
				};
			});
			datasetVersion = null;
		} else if (datasetId) {
			if (!datasetsStore) throw new Error("DatasetsStorage not configured. Configure storage in Mastra instance.");
			datasetRecord = await datasetsStore.getDatasetById({
				id: datasetId,
				filters: config.filters
			});
			if (!datasetRecord) throw new MastraError({
				id: "DATASET_NOT_FOUND",
				text: `Dataset not found: ${datasetId}`,
				domain: "STORAGE",
				category: "USER"
			});
			datasetVersion = version ?? datasetRecord.version;
			const versionItems = await datasetsStore.getItemsByVersion({
				datasetId,
				version: datasetVersion
			});
			if (versionItems.length === 0) throw new MastraError({
				id: "EXPERIMENT_NO_ITEMS",
				text: `No items in dataset ${datasetId} at version ${datasetVersion}`,
				domain: "STORAGE",
				category: "USER"
			});
			items = versionItems.map((v) => ({
				id: v.id,
				datasetVersion: v.datasetVersion,
				input: v.input,
				groundTruth: v.groundTruth,
				expectedTrajectory: v.expectedTrajectory ?? void 0,
				requestContext: v.requestContext ?? void 0,
				metadata: v.metadata ?? void 0,
				toolMocks: v.toolMocks ?? void 0,
				unmockedToolPolicy: v.unmockedToolPolicy ?? void 0,
				scorerIds: v.scorerIds ?? void 0
			}));
		} else throw new Error("No data source: provide datasetId or data");
	} catch (err) {
		await markFailedOnSetupError(err);
		throw err;
	}
	let execFn;
	try {
		assertAgentModelTarget(config);
		if (config.task) {
			const taskFn = config.task;
			execFn = async (item, itemSignal) => {
				try {
					return {
						output: await taskFn({
							input: item.input,
							mastra,
							groundTruth: item.groundTruth,
							metadata: item.metadata,
							signal: itemSignal
						}),
						error: null,
						traceId: null
					};
				} catch (err) {
					return {
						output: null,
						error: {
							message: err instanceof Error ? err.message : String(err),
							stack: err instanceof Error ? err.stack : void 0
						},
						traceId: null
					};
				}
			};
		} else if (targetType && targetId) {
			const resolved = await resolveTarget(mastra, targetType, targetId, agentVersion);
			if (!resolved) throw new Error(`Target not found: ${targetType}/${targetId}`);
			const { target } = resolved;
			execFn = (item, itemSignal) => {
				const mergedRequestContext = globalRequestContext || item.requestContext ? {
					...globalRequestContext,
					...item.requestContext
				} : void 0;
				return executeTarget(target, targetType, item, {
					signal: itemSignal,
					requestContext: mergedRequestContext,
					experimentId,
					versions,
					agentModel: config.agentModel,
					toolMocks: targetType === "agent" ? item.toolMocks : void 0,
					unmockedToolPolicy: targetType === "agent" ? item.unmockedToolPolicy ?? config.unmockedToolPolicy ?? "allow" : void 0
				});
			};
		} else throw new Error("No task: provide targetType+targetId or task");
	} catch (err) {
		await markFailedOnSetupError(err);
		throw err;
	}
	const itemsWithToolMocks = items.filter((item) => item.toolMocks?.length).length;
	if (targetType !== "agent" && itemsWithToolMocks > 0) mastra.getLogger()?.warn(`Experiment target is "${config.task ? "task" : targetType}" but ${itemsWithToolMocks} of ${items.length} dataset items declare toolMocks. Tool mocks only apply to agent targets and will be ignored.`);
	const hasRunLevelScorers = scorerInput !== void 0;
	let stepsConfigInput;
	let flatScorerInput;
	if (scorerInput !== void 0) {
		if (Array.isArray(scorerInput)) flatScorerInput = scorerInput;
		else {
			flatScorerInput = [];
			if ("agent" in scorerInput && scorerInput.agent) flatScorerInput.push(...scorerInput.agent);
			if ("workflow" in scorerInput && scorerInput.workflow) flatScorerInput.push(...scorerInput.workflow);
			if ("trajectory" in scorerInput && scorerInput.trajectory) flatScorerInput.push(...scorerInput.trajectory);
			if ("steps" in scorerInput && scorerInput.steps) stepsConfigInput = scorerInput.steps;
		}
	}
	if (flatScorerInput?.length) {
		const seen = /* @__PURE__ */ new Set();
		flatScorerInput = flatScorerInput.filter((entry) => {
			if (typeof entry !== "string") return true;
			if (seen.has(entry)) return false;
			seen.add(entry);
			return true;
		});
	}
	const runLevelScorers = hasRunLevelScorers ? resolveScorers(mastra, flatScorerInput) : [];
	const runLevelStepScorers = hasRunLevelScorers ? resolveStepScorers(mastra, stepsConfigInput) : {};
	const resolveItemScorers = createItemScorerResolver(mastra);
	const datasetScorers = !hasRunLevelScorers && items.some((item) => item.scorerIds === void 0) ? resolveScorers(mastra, [...new Set(datasetRecord?.scorerIds ?? [])]) : [];
	if (experimentsStore) {
		if (!providedExperimentId) await experimentsStore.createExperiment({
			id: experimentId,
			name,
			description,
			metadata: withAgentModelMetadata(metadata, config.agentModel),
			provenance,
			experimentSetId: grouping?.experimentSetId,
			comparisonId: grouping?.comparisonId,
			variantId: grouping?.variantId,
			trialIndex: grouping?.trialIndex,
			datasetId: datasetId ?? null,
			datasetVersion,
			targetType: targetType ?? "agent",
			targetId: targetId ?? "inline",
			totalItems: items.length,
			agentVersion,
			organizationId: datasetRecord?.organizationId ?? null,
			projectId: datasetRecord?.projectId ?? null
		});
		await experimentsStore.updateExperiment({
			id: experimentId,
			status: "running",
			totalItems: items.length,
			startedAt
		});
	}
	if (eventDispatcher) try {
		await eventDispatcher.emit({
			type: "experiment.run.started",
			experimentId,
			target: eventTarget,
			status: "running",
			datasetId: datasetRecord?.id ?? null,
			datasetVersion,
			totalItems: items.length
		});
	} catch (observerError) {
		await markFailedForObserverError({
			succeededCount: 0,
			failedCount: 0,
			skippedCount: items.length,
			completedAt: /* @__PURE__ */ new Date()
		});
		throw observerError;
	}
	let succeededCount = 0;
	let failedCount = 0;
	let persistenceFailures = 0;
	const results = new Array(items.length);
	const PROGRESS_UPDATE_INTERVAL = 2e3;
	let lastProgressUpdate = 0;
	try {
		if (beforeAll) await beforeAll(hookArgs);
		const pMap = (await import("p-map")).default;
		await pMap(items.map((item, idx) => ({
			item,
			idx
		})), async ({ item, idx }) => {
			if (eventDispatcher?.failure) return;
			try {
				if (executionSignal?.aborted) throw new DOMException("Aborted", "AbortError");
				const itemStartedAt = /* @__PURE__ */ new Date();
				const metadataSnapshot = item.metadata === void 0 ? void 0 : structuredClone(item.metadata);
				const cloneMetadataSnapshot = () => metadataSnapshot === void 0 ? void 0 : structuredClone(metadataSnapshot);
				const itemWithMetadataSnapshot = () => ({
					...item,
					metadata: cloneMetadataSnapshot()
				});
				let itemScorers;
				let itemStepScorers = {};
				let scorerConfigError = null;
				if (hasRunLevelScorers) {
					itemScorers = runLevelScorers;
					itemStepScorers = runLevelStepScorers;
				} else if (item.scorerIds !== void 0) {
					const resolution = await resolveItemScorers(item.scorerIds);
					itemScorers = resolution.scorers;
					if (resolution.missingIds.length > 0) scorerConfigError = {
						code: EXPERIMENT_ITEM_SCORER_NOT_FOUND,
						message: `Item scorer configuration references unregistered scorer IDs: ${resolution.missingIds.join(", ")}`
					};
				} else itemScorers = datasetScorers;
				let itemSignal = executionSignal;
				if (itemTimeout) {
					const timeoutSignal = AbortSignal.timeout(itemTimeout);
					itemSignal = executionSignal ? AbortSignal.any([executionSignal, timeoutSignal]) : timeoutSignal;
				}
				let beforeEachError = null;
				if (beforeEach && !scorerConfigError) try {
					await beforeEach({
						...hookArgs,
						item: {
							id: item.id,
							input: item.input,
							groundTruth: item.groundTruth,
							metadata: cloneMetadataSnapshot()
						}
					});
				} catch (hookError) {
					beforeEachError = {
						code: EXPERIMENT_ITEM_BEFORE_EACH_FAILED,
						message: `beforeEach hook failed: ${errorMessage(hookError)}`,
						stack: hookError instanceof Error ? hookError.stack : void 0
					};
				}
				let retryCount = 0;
				const preflightError = scorerConfigError ?? beforeEachError;
				let execResult = preflightError ? {
					output: null,
					error: preflightError,
					traceId: null
				} : await execFn(itemWithMetadataSnapshot(), itemSignal);
				while (execResult.error && !preflightError && retryCount < maxRetries) {
					if (execResult.error.message.toLowerCase().includes("abort")) break;
					if (execResult.error.code === "TOOL_MOCK_MISMATCH" || execResult.error.code === "TOOL_MOCK_EXHAUSTED" || execResult.error.code === "TOOL_MOCK_NOT_DECLARED") break;
					retryCount++;
					const delay = Math.min(1e3 * Math.pow(2, retryCount - 1), 3e4);
					const jitter = delay * .2 * Math.random();
					await new Promise((r) => setTimeout(r, delay + jitter));
					if (executionSignal?.aborted) throw new DOMException("Aborted", "AbortError");
					execResult = await execFn(itemWithMetadataSnapshot(), itemSignal);
				}
				const itemCompletedAt = /* @__PURE__ */ new Date();
				const itemResult = {
					itemId: item.id,
					itemVersion: item.datasetVersion ?? 0,
					input: item.input,
					output: execResult.output,
					groundTruth: item.groundTruth ?? null,
					metadata: cloneMetadataSnapshot(),
					error: execResult.error,
					startedAt: itemStartedAt,
					completedAt: itemCompletedAt,
					retryCount,
					persistenceError: null,
					...execResult.toolMockReport ? { toolMockReport: execResult.toolMockReport } : {}
				};
				let itemScores = [];
				if (!preflightError) {
					const workflowData = execResult.stepResults || execResult.stepExecutionPath ? {
						stepResults: execResult.stepResults,
						stepExecutionPath: execResult.stepExecutionPath,
						spanId: execResult.spanId
					} : void 0;
					await flushForTrajectoryScorers(mastra, itemScorers, execResult.traceId);
					const flatScores = await runScorersForItem(itemScorers, itemWithMetadataSnapshot(), execResult.output, storage ?? null, experimentId, targetType ?? "agent", targetId ?? "inline", item.id, execResult.scorerInput, execResult.scorerOutput, execResult.traceId ?? void 0, workflowData, persistScores);
					const stepScores = await runStepScorersForItem(itemStepScorers, itemWithMetadataSnapshot(), workflowData, storage ?? null, experimentId, targetType ?? "agent", targetId ?? "inline", item.id, execResult.traceId ?? void 0, persistScores);
					itemScores = [...flatScores, ...stepScores];
				}
				if (experimentsStore) try {
					await experimentsStore.addExperimentResult({
						experimentId,
						itemId: item.id,
						itemDatasetVersion: item.datasetVersion,
						input: item.input,
						output: execResult.output,
						groundTruth: item.groundTruth ?? null,
						metadata: cloneMetadataSnapshot(),
						error: execResult.error,
						startedAt: itemStartedAt,
						completedAt: itemCompletedAt,
						retryCount,
						traceId: execResult.traceId,
						organizationId: datasetRecord?.organizationId ?? null,
						projectId: datasetRecord?.projectId ?? null,
						...execResult.toolMockReport ? { toolMockReport: execResult.toolMockReport } : {}
					});
				} catch (persistError) {
					persistenceFailures++;
					itemResult.persistenceError = { message: persistError instanceof Error ? persistError.message : String(persistError) };
					mastra.getLogger()?.error(`Failed to persist experiment result for item ${item.id} in experiment ${experimentId}: ${itemResult.persistenceError.message}`, { error: persistError });
				}
				results[idx] = {
					...itemResult,
					scores: itemScores
				};
				if (execResult.error) failedCount++;
				else succeededCount++;
				if (afterEach && !beforeEachError) try {
					await afterEach({
						...hookArgs,
						item: {
							id: item.id,
							input: item.input,
							groundTruth: item.groundTruth,
							metadata: cloneMetadataSnapshot()
						},
						result: {
							...results[idx],
							metadata: cloneMetadataSnapshot()
						}
					});
				} catch (hookError) {
					mastra.getLogger()?.error(`Experiment ${experimentId} afterEach hook failed for item ${item.id}: ${errorMessage(hookError)}`, { error: hookError });
				}
				if (experimentsStore) {
					const now = Date.now();
					if (now - lastProgressUpdate >= PROGRESS_UPDATE_INTERVAL) {
						lastProgressUpdate = now;
						try {
							await experimentsStore.updateExperiment({
								id: experimentId,
								succeededCount,
								failedCount
							});
						} catch {}
					}
				}
				if (eventDispatcher) await eventDispatcher.emit(createItemCompletedEvent({
					experimentId,
					target: eventTarget
				}, idx, results[idx], execResult.traceId ?? null));
			} catch (error) {
				if (eventDispatcher?.failure) return;
				throw error;
			}
		}, { concurrency: maxConcurrency });
		if (eventDispatcher?.failure) throw eventDispatcher.failure;
	} catch (error) {
		const completedAt = /* @__PURE__ */ new Date();
		const skippedCount = items.length - succeededCount - failedCount;
		const observerError = eventDispatcher?.failure;
		const summary = {
			experimentId,
			status: "failed",
			totalItems: items.length,
			succeededCount,
			failedCount,
			skippedCount,
			persistenceFailures,
			completedWithErrors: false,
			startedAt,
			completedAt,
			results: results.filter(Boolean)
		};
		if (observerError) {
			await runAfterAll(summary);
			await markFailedForObserverError({
				succeededCount,
				failedCount,
				skippedCount,
				completedAt
			});
			throw observerError;
		}
		const terminalError = error instanceof AggregateError ? error.errors[0] ?? error : error;
		if (eventDispatcher) try {
			await eventDispatcher.emit({
				type: "experiment.run.finished",
				experimentId,
				target: eventTarget,
				status: "failed",
				outcome: executionSignal?.aborted ? "cancelled" : "failed",
				error: toExperimentJsonValue(terminalError),
				totalItems: summary.totalItems,
				succeededCount,
				failedCount,
				skippedCount,
				persistenceFailures,
				completedWithErrors: false,
				startedAt: startedAt.toISOString(),
				completedAt: completedAt.toISOString()
			});
		} catch (observerError) {
			await runAfterAll(summary);
			await markFailedForObserverError({
				succeededCount,
				failedCount,
				skippedCount,
				completedAt
			});
			throw observerError;
		}
		if (experimentsStore) await experimentsStore.updateExperiment({
			id: experimentId,
			status: "failed",
			succeededCount,
			failedCount,
			skippedCount,
			completedAt
		});
		await runAfterAll(summary);
		return summary;
	}
	const completedAt = /* @__PURE__ */ new Date();
	const status = failedCount === items.length ? "failed" : "completed";
	const completedWithErrors = status === "completed" && failedCount > 0;
	const skippedCount = items.length - succeededCount - failedCount;
	const summary = {
		experimentId,
		status,
		totalItems: items.length,
		succeededCount,
		failedCount,
		skippedCount,
		persistenceFailures,
		completedWithErrors,
		startedAt,
		completedAt,
		results
	};
	if (eventDispatcher) try {
		await eventDispatcher.emit({
			type: "experiment.run.finished",
			experimentId,
			target: eventTarget,
			status,
			outcome: executionSignal?.aborted ? "cancelled" : status,
			error: null,
			totalItems: items.length,
			succeededCount,
			failedCount,
			skippedCount,
			persistenceFailures,
			completedWithErrors,
			startedAt: startedAt.toISOString(),
			completedAt: completedAt.toISOString()
		});
	} catch (observerError) {
		await runAfterAll(summary);
		await markFailedForObserverError({
			succeededCount,
			failedCount,
			skippedCount,
			completedAt
		});
		throw observerError;
	}
	if (experimentsStore) await experimentsStore.updateExperiment({
		id: experimentId,
		status,
		succeededCount,
		failedCount,
		skippedCount,
		completedAt
	});
	await runAfterAll(summary);
	return summary;
}
// src/datasets/experiment-traces.ts
/** Page size used when walking an experiment's results to collect trace ids. */
const TRACE_ID_COLLECTION_PAGE_SIZE = 100;
/**
* Storage error ids that mean "this adapter cannot run the trace cascade".
* They are downgraded to a warning so relational experiment deletion still
* succeeds on stores without an observability domain (or without tenant-scoped
* trace deletion) instead of failing the whole delete.
*/
const UNSUPPORTED_CASCADE_ERROR_IDS = /* @__PURE__ */ new Set(["OBSERVABILITY_STORAGE_BATCH_DELETE_TRACES_NOT_IMPLEMENTED", "OBSERVABILITY_STORAGE_BATCH_DELETE_TRACES_SCOPE_NOT_SUPPORTED"]);
function isUnsupportedCascadeError(error) {
	const id = error?.id;
	return typeof id === "string" && UNSUPPORTED_CASCADE_ERROR_IDS.has(id);
}
/** Collects the distinct, non-null trace ids recorded on an experiment's results. */
async function collectExperimentTraceIds(args) {
	const traceIds = /* @__PURE__ */ new Set();
	let page = 0;
	for (;;) {
		const { results, pagination } = await args.experimentsStore.listExperimentResults({
			experimentId: args.experimentId,
			...args.filters !== void 0 ? { filters: args.filters } : {},
			pagination: {
				page,
				perPage: TRACE_ID_COLLECTION_PAGE_SIZE
			}
		});
		for (const result of results) if (result.traceId) traceIds.add(result.traceId);
		if (!pagination.hasMore || results.length === 0) break;
		page += 1;
	}
	return [...traceIds];
}
/**
* Deletes the observability traces produced by an experiment, along with everything
* `batchDeleteTraces` cascades to (spans, trace roots/branches, and trace-linked
* scores, feedback, metrics and logs).
*
* Trace ids come from the experiment's own result rows, which are read with the
* caller's tenancy filters — so only traces belonging to the caller's experiment
* are ever collected. The tenant scope is forwarded to storage as defense in depth.
*
* Must run *before* the relational delete: `deleteExperiment` cascades away the
* result rows that carry the trace ids.
*
* @returns the trace ids that were passed to the cascade, or an empty array when
* the experiment recorded none or the store cannot perform the cascade.
*/
async function deleteExperimentTraces(args) {
	const traceIds = await collectExperimentTraceIds({
		experimentsStore: args.experimentsStore,
		experimentId: args.experimentId,
		...args.filters !== void 0 ? { filters: args.filters } : {}
	});
	if (traceIds.length === 0) return [];
	const observabilityStore = await args.storage.getStore("observability");
	if (!observabilityStore) {
		args.logger?.warn(`Skipping trace deletion for experiment ${args.experimentId}: storage has no observability domain. ${traceIds.length} trace(s) were left in place.`);
		return [];
	}
	const organizationId = args.filters?.organizationId;
	for (let i = 0; i < traceIds.length; i += BATCH_DELETE_TRACES_MAX_IDS) try {
		await observabilityStore.batchDeleteTraces({
			traceIds: traceIds.slice(i, i + BATCH_DELETE_TRACES_MAX_IDS),
			...organizationId !== void 0 ? { organizationId } : {}
		});
	} catch (error) {
		if (!isUnsupportedCascadeError(error) || i > 0) throw error;
		args.logger?.warn(`Skipping trace deletion for experiment ${args.experimentId}: ${error.message}. ${traceIds.length} trace(s) were left in place.`);
		return [];
	}
	return traceIds;
}
// src/datasets/dataset.ts
/**
* Public API for interacting with a single dataset.
*
* Provides methods for item CRUD, versioning, and experiment management.
* Obtained via `DatasetsManager.get()` or `DatasetsManager.create()`.
*/
var Dataset = class {
	id;
	#mastra;
	#datasetsStore;
	#experimentsStore;
	/**
	* Tenancy read-scope carried by the handle. When set, all internal reads
	* ({@link Dataset.getDetails}, {@link Dataset.startExperimentAsync}) and item
	* mutations forward these filters to storage so cross-tenant reads/mutations
	* over a leaked dataset id are rejected as NOT_FOUND (or silent no-op for
	* deletes) rather than succeeding.
	*/
	#scope;
	constructor(id, mastra, scope) {
		this.id = id;
		this.#mastra = mastra;
		this.#scope = scope;
	}
	async #getDatasetsStore() {
		if (this.#datasetsStore) return this.#datasetsStore;
		const storage = this.#mastra.getStorage();
		if (!storage) throw new MastraError({
			id: "DATASETS_STORAGE_NOT_CONFIGURED",
			text: "Storage not configured. Configure storage in Mastra instance.",
			domain: "STORAGE",
			category: "USER"
		});
		const store = await storage.getStore("datasets");
		if (!store) throw new MastraError({
			id: "DATASETS_STORE_NOT_AVAILABLE",
			text: "Datasets store not available. Ensure your storage adapter provides a datasets domain.",
			domain: "STORAGE",
			category: "USER"
		});
		this.#datasetsStore = store;
		return store;
	}
	async #getExperimentsStore() {
		if (this.#experimentsStore) return this.#experimentsStore;
		const storage = this.#mastra.getStorage();
		if (!storage) throw new MastraError({
			id: "DATASETS_STORAGE_NOT_CONFIGURED",
			text: "Storage not configured. Configure storage in Mastra instance.",
			domain: "STORAGE",
			category: "USER"
		});
		const store = await storage.getStore("experiments");
		if (!store) throw new MastraError({
			id: "EXPERIMENTS_STORE_NOT_AVAILABLE",
			text: "Experiments store not available. Ensure your storage adapter provides an experiments domain.",
			domain: "STORAGE",
			category: "USER"
		});
		this.#experimentsStore = store;
		return store;
	}
	/**
	* Preflight tenancy gate for storage APIs whose signatures don't accept
	* `filters`. When the handle has a `#scope`, a scoped `getDatasetById` is
	* used to prove the dataset exists in the caller's tenancy; on miss we
	* throw NOT_FOUND, mirroring {@link Dataset.getDetails}. Callers that must
	* return a non-throwing empty result (e.g. list endpoints) should catch and
	* translate.
	*/
	async #assertScope() {
		if (!this.#scope) return;
		if (!await (await this.#getDatasetsStore()).getDatasetById({
			id: this.id,
			filters: this.#scope
		})) throw new MastraError({
			id: "DATASET_NOT_FOUND",
			text: `Dataset not found: ${this.id}`,
			domain: "STORAGE",
			category: "USER"
		});
	}
	/**
	* Ownership gate: verifies a child record's `datasetId` matches `this.id`.
	* Prevents a valid scoped handle from reading/mutating child records
	* (items, experiments, results) that live under a different dataset — even
	* one in the same tenant. Returns `null` when the record is missing or
	* belongs to a different dataset, so callers can either return null or
	* translate to NOT_FOUND depending on their contract.
	*/
	#ownsChild(record) {
		if (!record) return null;
		if (record.datasetId !== this.id) return null;
		return record;
	}
	/**
	* Get the full dataset record from storage.
	*/
	async getDetails() {
		const record = await (await this.#getDatasetsStore()).getDatasetById({
			id: this.id,
			filters: this.#scope
		});
		if (!record) throw new MastraError({
			id: "DATASET_NOT_FOUND",
			text: `Dataset not found: ${this.id}`,
			domain: "STORAGE",
			category: "USER"
		});
		return record;
	}
	/**
	* Update dataset metadata and/or schemas.
	*
	* Accepts Zod schemas for `inputSchema` / `groundTruthSchema` (widened to
	* `unknown`); they are normalized to JSON Schema before being forwarded to
	* the storage-canonical {@link UpdateDatasetInput} shape. All other fields
	* mirror {@link UpdateDatasetInput} exactly (minus `id`, which is supplied
	* from `this.id`).
	*/
	async update(input) {
		const store = await this.#getDatasetsStore();
		let { inputSchema, groundTruthSchema, ...rest } = input;
		if (inputSchema !== void 0 && inputSchema !== null && isZodType(inputSchema)) inputSchema = zodToJsonSchema(inputSchema);
		if (groundTruthSchema !== void 0 && groundTruthSchema !== null && isZodType(groundTruthSchema)) groundTruthSchema = zodToJsonSchema(groundTruthSchema);
		return store.updateDataset({
			id: this.id,
			...rest,
			inputSchema,
			groundTruthSchema,
			filters: this.#scope
		});
	}
	/**
	* Add a single item to the dataset.
	*/
	async addItem(input) {
		return (await this.#getDatasetsStore()).addItem({
			datasetId: this.id,
			...input,
			filters: this.#scope
		});
	}
	/**
	* Add multiple items to the dataset in bulk.
	*/
	async addItems(input) {
		return (await this.#getDatasetsStore()).batchInsertItems({
			datasetId: this.id,
			items: input.items,
			filters: this.#scope
		});
	}
	/**
	* Get a single item by ID, optionally at a specific version.
	*/
	async getItem(args) {
		await this.#assertScope();
		const item = await (await this.#getDatasetsStore()).getItemById({
			id: args.itemId,
			datasetVersion: args.version
		});
		return this.#ownsChild(item);
	}
	/**
	* List items in the dataset, optionally at a specific version, with
	* optional substring search and pagination.
	*
	* Return shape depends on the arguments:
	*
	* - When `version` is the only argument provided (no `search`, `page`, or
	*   `perPage`), returns a bare `DatasetItem[]` snapshot of every item at
	*   that version. This shape is retained for callers that predate
	*   server-side pagination on the versioned path; new code should pass
	*   `page` / `perPage` (or `search`) to opt into the paginated shape.
	* - In all other cases (no arguments, or `search` / `page` / `perPage`
	*   provided with or without `version`), returns the paginated
	*   `{ items, pagination }` shape.
	*
	* @deprecated The `DatasetItem[]` branch of the return type is retained
	* for backwards compatibility with the `version`-only call form; pass
	* `page` / `perPage` (or `search`) to always receive the paginated
	* `{ items, pagination }` shape.
	*/
	async listItems(args) {
		const store = await this.#getDatasetsStore();
		if (args?.version !== void 0 && args.search === void 0 && args.page === void 0 && args.perPage === void 0) {
			await this.#assertScope();
			return store.getItemsByVersion({
				datasetId: this.id,
				version: args.version
			});
		}
		return store.listItems({
			datasetId: this.id,
			...args?.version !== void 0 ? { version: args.version } : {},
			...args?.search ? { search: args.search } : {},
			...args?.orderBy !== void 0 ? { orderBy: args.orderBy } : {},
			pagination: {
				page: args?.page ?? 0,
				perPage: args?.perPage ?? 20
			},
			filters: this.#scope
		});
	}
	/**
	* Update an existing item in the dataset. Only the provided payload fields
	* are patched.
	*/
	async updateItem(input) {
		const store = await this.#getDatasetsStore();
		const { itemId, ...rest } = input;
		return store.updateItem({
			id: itemId,
			datasetId: this.id,
			...rest,
			filters: this.#scope
		});
	}
	/**
	* Delete a single item from the dataset.
	*/
	async deleteItem(args) {
		return (await this.#getDatasetsStore()).deleteItem({
			id: args.itemId,
			datasetId: this.id,
			filters: this.#scope
		});
	}
	/**
	* Permanently scrub user-supplied content from every version of an item and
	* from experiment results that reference it.
	*/
	async purgeItem(args) {
		return (await this.#getDatasetsStore()).purgeItem({
			id: args.itemId,
			datasetId: this.id,
			filters: this.#scope
		});
	}
	/**
	* Delete multiple items from the dataset in bulk.
	*/
	async deleteItems(args) {
		return (await this.#getDatasetsStore()).batchDeleteItems({
			datasetId: this.id,
			itemIds: args.itemIds,
			filters: this.#scope
		});
	}
	/**
	* List all versions of this dataset.
	*/
	async listVersions(args) {
		await this.#assertScope();
		return (await this.#getDatasetsStore()).listDatasetVersions({
			datasetId: this.id,
			pagination: {
				page: args?.page ?? 0,
				perPage: args?.perPage ?? 20
			}
		});
	}
	/**
	* Get full SCD-2 history of a specific item across all dataset versions.
	*/
	async getItemHistory(args) {
		await this.#assertScope();
		return (await (await this.#getDatasetsStore()).getItemHistory(args.itemId)).filter((row) => row.datasetId === this.id);
	}
	/**
	* Run an experiment on this dataset and wait for completion.
	*/
	async startExperiment(config) {
		return runExperiment(this.#mastra, {
			datasetId: this.id,
			...config,
			filters: this.#scope
		});
	}
	/**
	* Start an experiment asynchronously (fire-and-forget).
	* Returns immediately with the experiment ID and pending status.
	*/
	async startExperimentAsync(config) {
		assertAgentModelTarget(config);
		const experimentsStore = config.persistence?.experiments !== "none" ? await this.#getExperimentsStore() : void 0;
		const datasetsStore = await this.#getDatasetsStore();
		const dataset = await datasetsStore.getDatasetById({
			id: this.id,
			filters: this.#scope
		});
		if (!dataset) throw new MastraError({
			id: "DATASET_NOT_FOUND",
			text: `Dataset not found: ${this.id}`,
			domain: "STORAGE",
			category: "USER"
		});
		const targetVersion = config.version ?? dataset.version;
		const items = await datasetsStore.getItemsByVersion({
			datasetId: this.id,
			version: targetVersion
		});
		if (items.length === 0) throw new MastraError({
			id: "EXPERIMENT_NO_ITEMS",
			text: `Cannot run experiment: dataset "${this.id}" has no items at version ${targetVersion}`,
			domain: "STORAGE",
			category: "USER"
		});
		const experimentId = crypto.randomUUID();
		if (experimentsStore) await experimentsStore.createExperiment({
			id: experimentId,
			datasetId: this.id,
			datasetVersion: targetVersion,
			targetType: config.targetType ?? "agent",
			targetId: config.targetId ?? "inline",
			totalItems: items.length,
			name: config.name,
			description: config.description,
			metadata: withAgentModelMetadata(config.metadata, config.agentModel),
			provenance: config.provenance,
			experimentSetId: config.grouping?.experimentSetId,
			comparisonId: config.grouping?.comparisonId,
			variantId: config.grouping?.variantId,
			trialIndex: config.grouping?.trialIndex,
			agentVersion: config.agentVersion,
			organizationId: dataset.organizationId ?? null,
			projectId: dataset.projectId ?? null
		});
		runExperiment(this.#mastra, {
			datasetId: this.id,
			experimentId,
			...config,
			version: targetVersion,
			filters: this.#scope
		}).catch(async (err) => {
			if (experimentsStore) await experimentsStore.updateExperiment({
				id: experimentId,
				status: "failed",
				completedAt: /* @__PURE__ */ new Date()
			}).catch(() => {});
			this.#mastra.getLogger()?.error(`Experiment ${experimentId} failed: ${err?.message ?? err}`);
		});
		return {
			experimentId,
			status: "pending",
			totalItems: items.length
		};
	}
	/**
	* List experiments (runs) for this dataset, with optional filters and
	* pagination. All filters are pushed to the storage layer.
	*
	* @param args.targetType   Restrict to a specific target type (e.g. `agent`).
	* @param args.targetId     Restrict to a specific target ID.
	* @param args.agentVersion Restrict to a specific agent version — useful for
	*                          baseline vs variant read patterns.
	* @param args.status       Restrict to a specific experiment status.
	* @param args.filters      Multi-tenant scoping filters (organization/project).
	* @param args.page         Page number. Defaults to `0`.
	* @param args.perPage      Page size. Defaults to `20`.
	*/
	async listExperiments(args) {
		await this.#assertScope();
		return (await this.#getExperimentsStore()).listExperiments({
			datasetId: this.id,
			...args?.targetType !== void 0 ? { targetType: args.targetType } : {},
			...args?.targetId !== void 0 ? { targetId: args.targetId } : {},
			...args?.agentVersion !== void 0 ? { agentVersion: args.agentVersion } : {},
			...args?.status !== void 0 ? { status: args.status } : {},
			...args?.experimentSetId !== void 0 ? { experimentSetId: args.experimentSetId } : {},
			...args?.comparisonId !== void 0 ? { comparisonId: args.comparisonId } : {},
			...args?.variantId !== void 0 ? { variantId: args.variantId } : {},
			...args?.trialIndex !== void 0 ? { trialIndex: args.trialIndex } : {},
			...args?.filters !== void 0 ? { filters: args.filters } : {},
			...args?.orderBy !== void 0 ? { orderBy: args.orderBy } : {},
			pagination: {
				page: args?.page ?? 0,
				perPage: args?.perPage ?? 20
			}
		});
	}
	/**
	* Verify the experiment belongs to this dataset (and, by extension, to the
	* handle's tenancy scope which was enforced when the handle was minted).
	* Throws NOT_FOUND on missing or cross-dataset experiments so cross-tenant
	* mutation via a valid scoped handle + a known foreign experimentId is
	* rejected.
	*/
	async #assertExperimentOwnership(experimentId) {
		await this.#assertScope();
		const experiment = await (await this.#getExperimentsStore()).getExperimentById({
			id: experimentId,
			filters: this.#scope
		});
		if (!experiment || experiment.datasetId !== this.id) throw new MastraError({
			id: "EXPERIMENT_NOT_FOUND",
			text: `Experiment not found: ${experimentId}`,
			domain: "STORAGE",
			category: "USER"
		});
	}
	/**
	* Get a specific experiment (run) by ID.
	*/
	async getExperiment(args) {
		await this.#assertScope();
		const experiment = await (await this.#getExperimentsStore()).getExperimentById({
			id: args.experimentId,
			filters: this.#scope
		});
		if (!experiment || experiment.datasetId !== this.id) return null;
		return experiment;
	}
	/**
	* Update an experiment's user-facing label (name, description, metadata).
	* Status and counters are owned by the runtime and cannot be changed here.
	* Throws EXPERIMENT_NOT_FOUND for unknown or cross-dataset experiments.
	*/
	async updateExperiment(args) {
		await this.#getOwnedExperiment(args.experimentId);
		return (await this.#getExperimentsStore()).updateExperiment({
			id: args.experimentId,
			...args.name !== void 0 ? { name: args.name } : {},
			...args.description !== void 0 ? { description: args.description } : {},
			...args.metadata !== void 0 ? { metadata: args.metadata } : {}
		});
	}
	/**
	* List results for a specific experiment, with optional filters and
	* pagination. All filters are pushed to the storage layer.
	*
	* @param args.experimentId The experiment whose results to list.
	* @param args.traceId      Restrict to results linked to a specific trace.
	* @param args.status       Restrict to a specific per-result review status.
	* @param args.tags         Restrict to results that have *all* of these tags.
	* @param args.filters      Multi-tenant scoping filters (organization/project).
	* @param args.page         Page number. Defaults to `0`.
	* @param args.perPage      Page size. Defaults to `20`.
	*/
	async listExperimentResults(args) {
		await this.#assertExperimentOwnership(args.experimentId);
		return (await this.#getExperimentsStore()).listExperimentResults({
			experimentId: args.experimentId,
			...args.traceId !== void 0 ? { traceId: args.traceId } : {},
			...args.status !== void 0 ? { status: args.status } : {},
			...args.tags !== void 0 ? { tags: args.tags } : {},
			...args.filters !== void 0 ? { filters: args.filters } : {},
			...args.orderBy !== void 0 ? { orderBy: args.orderBy } : {},
			pagination: {
				page: args?.page ?? 0,
				perPage: args?.perPage ?? 20
			}
		});
	}
	/**
	* Update an experiment result's status or tags.
	*/
	async updateExperimentResult(input) {
		if (!input.experimentId) throw new MastraError({
			id: "EXPERIMENT_RESULT_MISSING_EXPERIMENT_ID",
			text: "updateExperimentResult requires experimentId when called via a Dataset handle",
			domain: "STORAGE",
			category: "USER"
		});
		await this.#assertExperimentOwnership(input.experimentId);
		return (await this.#getExperimentsStore()).updateExperimentResult(input);
	}
	/**
	* Load an experiment owned by this dataset (tenancy + dataset ownership).
	* Used by the caller-driven methods so a caller cannot mutate another
	* dataset's (or tenant's) experiment.
	*/
	async #getOwnedExperiment(experimentId) {
		await this.#assertScope();
		const experiment = await (await this.#getExperimentsStore()).getExperimentById({
			id: experimentId,
			filters: this.#scope
		});
		if (!experiment || experiment.datasetId !== this.id) throw new MastraError({
			id: "EXPERIMENT_NOT_FOUND",
			text: `Experiment not found: ${experimentId}`,
			domain: "STORAGE",
			category: "USER"
		});
		return experiment;
	}
	/**
	* Create an experiment whose execution loop is owned by the caller
	* (e.g. a Temporal workflow). No runner is spawned. Two shapes:
	*
	* - With `targetType`/`targetId`: the caller drives the loop and Mastra
	*   executes each item on demand via {@link Dataset.runExperimentItem}.
	*   Optional `scorers` are pinned on the experiment as the run-level
	*   scorer source.
	* - Without a target: pure ingestion — the caller executes and scores
	*   everything itself and upserts rows via
	*   {@link Dataset.submitExperimentResult}.
	*
	* Either way the caller closes the run with
	* {@link Dataset.finalizeExperiment}.
	*
	* Idempotent on `id`: passing a caller-supplied id (e.g. a workflow run id)
	* and retrying the create converges on the same experiment instead of
	* creating duplicates.
	*/
	async createExperiment(args) {
		const experimentsStore = await this.#getExperimentsStore();
		const datasetsStore = await this.#getDatasetsStore();
		const hasTargetType = args?.targetType !== void 0;
		if (hasTargetType !== (args?.targetId !== void 0)) throw new MastraError({
			id: "EXPERIMENT_INVALID_TARGET",
			text: `targetType and targetId must be provided together (got targetType: ${args?.targetType ?? "none"}, targetId: ${args?.targetId ?? "none"})`,
			domain: "STORAGE",
			category: "USER"
		});
		if (args?.scorers?.length && !hasTargetType) throw new MastraError({
			id: "EXPERIMENT_INVALID_TARGET",
			text: "scorers require a target: without a target Mastra never executes or scores items; submit flat scores via submitExperimentResult instead",
			domain: "STORAGE",
			category: "USER"
		});
		if (hasTargetType) {
			if (!await resolveTarget(this.#mastra, args.targetType, args.targetId)) throw new MastraError({
				id: "EXPERIMENT_TARGET_NOT_FOUND",
				text: `Target not found: ${args.targetType} "${args.targetId}"`,
				domain: "STORAGE",
				category: "USER"
			});
		}
		const dataset = await datasetsStore.getDatasetById({
			id: this.id,
			filters: this.#scope
		});
		if (!dataset) throw new MastraError({
			id: "DATASET_NOT_FOUND",
			text: `Dataset not found: ${this.id}`,
			domain: "STORAGE",
			category: "USER"
		});
		if (args?.id) {
			const existing = await experimentsStore.getExperimentById({
				id: args.id,
				filters: this.#scope
			});
			if (existing) {
				if (!(existing.datasetId === this.id && existing.targetType === (args.targetType ?? null) && existing.targetId === (args.targetId ?? null))) throw new MastraError({
					id: "EXPERIMENT_ID_CONFLICT",
					text: `Experiment id ${args.id} already exists and does not match this experiment's dataset or target`,
					domain: "STORAGE",
					category: "USER"
				});
				let status = existing.status;
				let startedAt = existing.startedAt ?? null;
				if (existing.status === "pending") {
					startedAt = /* @__PURE__ */ new Date();
					await experimentsStore.updateExperiment({
						id: existing.id,
						status: "running",
						startedAt
					});
					status = "running";
				}
				return {
					experimentId: existing.id,
					status,
					totalItems: existing.totalItems,
					datasetVersion: existing.datasetVersion ?? dataset.version,
					startedAt
				};
			}
		}
		const targetVersion = args?.version ?? dataset.version;
		const items = await datasetsStore.getItemsByVersion({
			datasetId: this.id,
			version: targetVersion
		});
		if (items.length === 0) throw new MastraError({
			id: "EXPERIMENT_NO_ITEMS",
			text: `Cannot create experiment: dataset "${this.id}" has no items at version ${targetVersion}`,
			domain: "STORAGE",
			category: "USER"
		});
		const experimentId = args?.id ?? crypto.randomUUID();
		try {
			await experimentsStore.createExperiment({
				id: experimentId,
				datasetId: this.id,
				datasetVersion: targetVersion,
				targetType: args?.targetType ?? null,
				targetId: args?.targetId ?? null,
				scorerIds: args?.scorers?.length ? args.scorers : null,
				totalItems: items.length,
				name: args?.name,
				description: args?.description,
				metadata: args?.metadata,
				provenance: args?.provenance,
				experimentSetId: args?.grouping?.experimentSetId,
				comparisonId: args?.grouping?.comparisonId,
				variantId: args?.grouping?.variantId,
				trialIndex: args?.grouping?.trialIndex,
				organizationId: dataset.organizationId ?? null,
				projectId: dataset.projectId ?? null
			});
		} catch (createError) {
			if (!args?.id) throw createError;
			const existing = await experimentsStore.getExperimentById({
				id: args.id,
				filters: this.#scope
			});
			if (!existing) throw createError;
			if (!(existing.datasetId === this.id && existing.targetType === (args.targetType ?? null) && existing.targetId === (args.targetId ?? null))) throw new MastraError({
				id: "EXPERIMENT_ID_CONFLICT",
				text: `Experiment id ${args.id} already exists and does not match this experiment's dataset or target`,
				domain: "STORAGE",
				category: "USER"
			});
			return {
				experimentId: existing.id,
				status: existing.status,
				totalItems: existing.totalItems,
				datasetVersion: existing.datasetVersion ?? dataset.version,
				startedAt: existing.startedAt ?? null
			};
		}
		const startedAt = /* @__PURE__ */ new Date();
		await experimentsStore.updateExperiment({
			id: experimentId,
			status: "running",
			startedAt
		});
		return {
			experimentId,
			status: "running",
			totalItems: items.length,
			datasetVersion: targetVersion,
			startedAt
		};
	}
	/**
	* Execute one experiment item server-side: run the experiment's target
	* against the item, run the resolved scorers, and upsert the result row
	* keyed by `(experimentId, itemId, attempt)`.
	*
	* Built for caller-driven loops (mode 2): a durable orchestrator (e.g. a
	* Temporal workflow) fans out one call per item and owns retries/timeouts —
	* a retried call converges on the same row. Requires an experiment created
	* with a target via {@link Dataset.createExperiment}.
	*
	* Scorer precedence: experiment `scorers` → item `scorerIds` → dataset
	* `scorerIds` → none.
	*/
	async runExperimentItem(args) {
		const experiment = await this.#getOwnedExperiment(args.experimentId);
		if (experiment.targetType === null) throw new MastraError({
			id: "EXPERIMENT_HAS_NO_TARGET",
			text: `Experiment ${args.experimentId} has no target; ingest results via submitExperimentResult instead`,
			domain: "STORAGE",
			category: "USER"
		});
		if (experiment.status === "completed" || experiment.status === "failed") throw new MastraError({
			id: "EXPERIMENT_ALREADY_FINALIZED",
			text: `Experiment ${args.experimentId} is already ${experiment.status}; no further items can be run`,
			domain: "STORAGE",
			category: "USER"
		});
		const datasetsStore = await this.#getDatasetsStore();
		const dataset = await datasetsStore.getDatasetById({
			id: this.id,
			filters: this.#scope
		});
		const item = await datasetsStore.getItemById({
			id: args.itemId,
			datasetVersion: experiment.datasetVersion ?? void 0
		});
		if (!item || item.datasetId !== this.id) throw new MastraError({
			id: "DATASET_ITEM_NOT_FOUND",
			text: `Item ${args.itemId} not found in dataset ${this.id} at version ${experiment.datasetVersion}`,
			domain: "STORAGE",
			category: "USER"
		});
		return executeExperimentItem({
			mastra: this.#mastra,
			experiment,
			item: {
				id: item.id,
				datasetVersion: item.datasetVersion,
				input: item.input,
				groundTruth: item.groundTruth,
				expectedTrajectory: item.expectedTrajectory ?? void 0,
				requestContext: item.requestContext ?? void 0,
				metadata: item.metadata ?? void 0,
				scorerIds: item.scorerIds ?? void 0
			},
			datasetScorerIds: dataset?.scorerIds ?? null,
			attempt: args.attempt ?? 0,
			requestContext: args.requestContext,
			organizationId: experiment.organizationId ?? dataset?.organizationId ?? null,
			projectId: experiment.projectId ?? dataset?.projectId ?? null
		});
	}
	/**
	* Submit (or re-submit) one item result for a target-less (pure-ingestion)
	* experiment created with {@link Dataset.createExperiment}.
	*
	* Upsert semantics: the row is identified by the natural key
	* `(experimentId, itemId, attempt)`, so a retried submission (e.g. a
	* retried Temporal activity) converges on a single row instead of
	* duplicating. `attempt` defaults to `0`; use it only for intentional
	* repeated trials of the same item.
	*
	* `input` / `groundTruth` default to the dataset item's values at the
	* experiment's pinned dataset version when omitted.
	*
	* Inline `scores` are persisted to the scores store keyed by
	* `runId = experimentId`, the same shape the native runner writes, so
	* comparisons and Studio aggregation work unchanged. Score persistence is
	* best-effort and never fails the submission.
	*/
	async submitExperimentResult(args) {
		const experiment = await this.#getOwnedExperiment(args.experimentId);
		if (experiment.targetType !== null) throw new MastraError({
			id: "EXPERIMENT_HAS_TARGET",
			text: `Experiment ${args.experimentId} has a target (${experiment.targetType} "${experiment.targetId}"); results are produced by Mastra, not ingested. Use runExperimentItem instead.`,
			domain: "STORAGE",
			category: "USER"
		});
		if (experiment.status === "completed" || experiment.status === "failed") throw new MastraError({
			id: "EXPERIMENT_ALREADY_FINALIZED",
			text: `Experiment ${args.experimentId} is already ${experiment.status}; no further results can be submitted`,
			domain: "STORAGE",
			category: "USER"
		});
		const item = await (await this.#getDatasetsStore()).getItemById({
			id: args.itemId,
			datasetVersion: experiment.datasetVersion ?? void 0
		});
		if (!item || item.datasetId !== this.id) throw new MastraError({
			id: "DATASET_ITEM_NOT_FOUND",
			text: `Item ${args.itemId} not found in dataset ${this.id} at version ${experiment.datasetVersion}`,
			domain: "STORAGE",
			category: "USER"
		});
		const experimentsStore = await this.#getExperimentsStore();
		const now = /* @__PURE__ */ new Date();
		const result = await experimentsStore.upsertExperimentResult({
			experimentId: args.experimentId,
			itemId: args.itemId,
			attempt: args.attempt ?? 0,
			itemDatasetVersion: experiment.datasetVersion,
			input: args.input !== void 0 ? args.input : item.input,
			output: args.output ?? null,
			groundTruth: args.groundTruth !== void 0 ? args.groundTruth : item.groundTruth ?? null,
			metadata: item.metadata,
			error: args.error ?? null,
			startedAt: args.startedAt ?? now,
			completedAt: args.completedAt ?? now,
			retryCount: 0,
			traceId: args.traceId ?? null,
			organizationId: experiment.organizationId ?? null,
			projectId: experiment.projectId ?? null
		});
		if (args.scores?.length) {
			const storage = this.#mastra.getStorage();
			if (storage) for (const score of args.scores) try {
				await validateAndSaveScore(storage, {
					id: experimentScoreId(args.experimentId, args.itemId, args.attempt ?? 0, score.scorerId),
					scorerId: score.scorerId,
					score: score.score,
					reason: score.reason,
					input: result.input,
					output: result.output,
					additionalContext: score.metadata,
					entityType: "EXTERNAL",
					entityId: args.itemId,
					source: "TEST",
					runId: args.experimentId,
					traceId: args.traceId,
					scorer: {
						id: score.scorerId,
						name: score.scorerName ?? score.scorerId,
						description: "",
						hasJudge: false
					},
					entity: {
						id: "external",
						name: "external"
					}
				});
			} catch (saveError) {
				this.#mastra.getLogger()?.warn(`Failed to save external score for scorer ${score.scorerId}: ${saveError}`);
			}
		}
		return result;
	}
	/**
	* Finalize a caller-driven experiment: compute per-item
	* succeeded/failed/skipped counts from the persisted result rows and mark
	* the experiment completed. The caller sends no bookkeeping — the server is
	* the source of truth. Works for both targeted (runExperimentItem) and
	* target-less (submitExperimentResult) experiments.
	*
	* Idempotent: finalizing an already-completed experiment recomputes nothing
	* and returns the stored record.
	*/
	async finalizeExperiment(args) {
		const experiment = await this.#getOwnedExperiment(args.experimentId);
		if (experiment.status === "completed" || experiment.status === "failed") return experiment;
		const experimentsStore = await this.#getExperimentsStore();
		const itemSucceeded = /* @__PURE__ */ new Map();
		let page = 0;
		const perPage = 100;
		while (true) {
			const { results, pagination } = await experimentsStore.listExperimentResults({
				experimentId: args.experimentId,
				pagination: {
					page,
					perPage
				}
			});
			for (const result of results) {
				const succeeded = !result.error;
				itemSucceeded.set(result.itemId, (itemSucceeded.get(result.itemId) ?? false) || succeeded);
			}
			if (!pagination.hasMore || results.length === 0) break;
			page++;
		}
		let succeededCount = 0;
		let failedCount = 0;
		for (const succeeded of itemSucceeded.values()) if (succeeded) succeededCount++;
		else failedCount++;
		const skippedCount = Math.max(0, experiment.totalItems - itemSucceeded.size);
		return experimentsStore.updateExperiment({
			id: args.experimentId,
			status: "completed",
			succeededCount,
			failedCount,
			skippedCount,
			completedAt: /* @__PURE__ */ new Date()
		});
	}
	/**
	* Delete an experiment (run) by ID.
	*
	* The ownership check above already refuses cross-tenant / cross-dataset
	* requests, but we still forward `this.#scope` to storage so the delete
	* is defense-in-depth: a leaked handle or race that skipped the assertion
	* still cannot delete another tenant's experiment (storage silently no-ops
	* on tenancy mismatch).
	*
	* Also deletes the observability traces this experiment produced, cascading to
	* their spans and trace-linked signals. An experiment's traces are excluded from
	* normal trace reads, so leaving them behind would make them invisible but
	* still-retained data. Stores without an observability domain (or without
	* tenant-scoped trace deletion) log a warning and skip the trace cascade so the
	* relational delete still succeeds.
	*/
	async deleteExperiment(args) {
		await this.#assertExperimentOwnership(args.experimentId);
		const experimentsStore = await this.#getExperimentsStore();
		const storage = this.#mastra.getStorage();
		if (storage) await deleteExperimentTraces({
			storage,
			experimentsStore,
			experimentId: args.experimentId,
			...this.#scope !== void 0 ? { filters: this.#scope } : {},
			logger: this.#mastra.getLogger()
		});
		return experimentsStore.deleteExperiment({
			id: args.experimentId,
			filters: this.#scope
		});
	}
};
// src/datasets/manager.ts
/**
* Build a {@link DatasetTenancyFilters} from public manager args. Returns
* `undefined` when neither field is set (preserves legacy unscoped behavior).
* Null values are coerced away — `DatasetTenancyFilters` is `string | undefined`
* only, matching the existing `listDatasets` filter contract.
*/
function scopeFromArgs(args) {
	const scope = {};
	if (typeof args.organizationId === "string") scope.organizationId = args.organizationId;
	if (typeof args.projectId === "string") scope.projectId = args.projectId;
	return scope.organizationId === void 0 && scope.projectId === void 0 ? void 0 : scope;
}
/**
* Public API for managing datasets.
*
* Provides methods for dataset CRUD and cross-dataset experiment operations.
* Typically accessed via `mastra.datasets` (Phase 4).
*/
var DatasetsManager = class {
	#mastra;
	#datasetsStore;
	#experimentsStore;
	constructor(mastra) {
		this.#mastra = mastra;
	}
	async #getDatasetsStore() {
		if (this.#datasetsStore) return this.#datasetsStore;
		const storage = this.#mastra.getStorage();
		if (!storage) throw new MastraError({
			id: "DATASETS_STORAGE_NOT_CONFIGURED",
			text: "Storage not configured. Configure storage in Mastra instance.",
			domain: "STORAGE",
			category: "USER"
		});
		const store = await storage.getStore("datasets");
		if (!store) throw new MastraError({
			id: "DATASETS_STORE_NOT_AVAILABLE",
			text: "Datasets store not available. Ensure your storage adapter provides a datasets domain.",
			domain: "STORAGE",
			category: "USER"
		});
		this.#datasetsStore = store;
		return store;
	}
	async #getExperimentsStore() {
		if (this.#experimentsStore) return this.#experimentsStore;
		const storage = this.#mastra.getStorage();
		if (!storage) throw new MastraError({
			id: "DATASETS_STORAGE_NOT_CONFIGURED",
			text: "Storage not configured. Configure storage in Mastra instance.",
			domain: "STORAGE",
			category: "USER"
		});
		const store = await storage.getStore("experiments");
		if (!store) throw new MastraError({
			id: "EXPERIMENTS_STORE_NOT_AVAILABLE",
			text: "Experiments store not available. Ensure your storage adapter provides an experiments domain.",
			domain: "STORAGE",
			category: "USER"
		});
		this.#experimentsStore = store;
		return store;
	}
	/**
	* Create a new dataset.
	*
	* Accepts Zod schemas for `inputSchema` / `groundTruthSchema` (typed as
	* `unknown` here); they are normalized to JSON Schema via `zodToJsonSchema`
	* before being forwarded to the storage-canonical
	* {@link import('../storage/types.js').CreateDatasetInput} shape. All other
	* fields mirror `CreateDatasetInput` exactly.
	*/
	async create(input) {
		const store = await this.#getDatasetsStore();
		let { inputSchema, groundTruthSchema, ...rest } = input;
		if (inputSchema !== void 0 && isZodType(inputSchema)) inputSchema = zodToJsonSchema(inputSchema);
		if (groundTruthSchema !== void 0 && isZodType(groundTruthSchema)) groundTruthSchema = zodToJsonSchema(groundTruthSchema);
		assertSupportedPatterns(inputSchema);
		assertSupportedPatterns(groundTruthSchema);
		const result = await store.createDataset({
			...rest,
			inputSchema,
			groundTruthSchema
		});
		const createScope = scopeFromArgs(input);
		return new Dataset(result.id, this.#mastra, createScope);
	}
	/**
	* Get an existing dataset by ID, optionally scoped to a tenant.
	*
	* When `organizationId` / `projectId` are provided, the read is scoped to
	* that tenancy: a dataset row that exists but belongs to a different tenant
	* returns NOT_FOUND (same 404 as a truly missing row) rather than leaking
	* cross-tenant existence. The returned {@link Dataset} handle carries the
	* scope forward on all subsequent reads and item mutations.
	*/
	async get(args) {
		const store = await this.#getDatasetsStore();
		const scope = scopeFromArgs(args);
		if (!await store.getDatasetById({
			id: args.id,
			filters: scope
		})) throw new MastraError({
			id: "DATASET_NOT_FOUND",
			text: "Dataset not found",
			domain: "STORAGE",
			category: "USER"
		});
		return new Dataset(args.id, this.#mastra, scope);
	}
	/**
	* List all datasets with pagination.
	*
	* Supports optional tenancy and candidate-identity filters. When omitted, all
	* datasets visible to the configured storage instance are returned.
	*/
	async list(args) {
		return (await this.#getDatasetsStore()).listDatasets({
			pagination: {
				page: args?.page ?? 0,
				perPage: args?.perPage ?? 20
			},
			...args?.filters ? { filters: args.filters } : {},
			...args?.orderBy ? { orderBy: args.orderBy } : {}
		});
	}
	/**
	* Delete a dataset by ID, optionally scoped to a tenant.
	*
	* When `organizationId` / `projectId` are provided, the delete is scoped to
	* that tenancy: a dataset row in another tenant is a silent no-op (no error)
	* so cross-tenant existence is not leaked via error timing/text.
	*/
	async delete(args) {
		return (await this.#getDatasetsStore()).deleteDataset({
			id: args.id,
			filters: scopeFromArgs(args)
		});
	}
	/**
	* Get a specific experiment (run) by ID, optionally scoped to a tenant.
	*
	* When `organizationId` / `projectId` are provided, the read is scoped to
	* that tenancy: an experiment row that exists but belongs to a different
	* tenant returns `null` (same as a truly missing row) rather than leaking
	* cross-tenant existence via error timing/text.
	*/
	async getExperiment(args) {
		return (await this.#getExperimentsStore()).getExperimentById({
			id: args.experimentId,
			filters: scopeFromArgs(args)
		});
	}
	/**
	* Delete an experiment (run) by ID, optionally scoped to a tenant.
	*
	* Unlike {@link Dataset.deleteExperiment} this does not require the experiment
	* to still belong to a dataset, so it can clean up experiments orphaned by
	* dataset deletion (their `datasetId` is nulled out).
	*
	* When `organizationId` / `projectId` are provided, the delete is scoped to
	* that tenancy: an experiment row in another tenant is a silent no-op (no
	* error) so cross-tenant existence is not leaked via error timing/text.
	*
	* The experiment's traces are deleted too: they are excluded from normal trace
	* reads, so leaving them behind would make them invisible but still-retained
	* data. Stores without an observability domain — or without tenant-scoped trace
	* deletion — log a warning and skip the trace cascade so the experiment itself
	* is still deleted.
	*/
	async deleteExperiment(args) {
		const experimentsStore = await this.#getExperimentsStore();
		const filters = scopeFromArgs(args);
		const storage = this.#mastra.getStorage();
		if (storage) await deleteExperimentTraces({
			storage,
			experimentsStore,
			experimentId: args.experimentId,
			...filters !== void 0 ? { filters } : {},
			logger: this.#mastra.getLogger()
		});
		return experimentsStore.deleteExperiment({
			id: args.experimentId,
			filters
		});
	}
	/**
	* Compare two or more experiments.
	*
	* Each contender is compared pairwise against the baseline with the internal
	* `compareExperiments` function; the pairs are then merged so every item has
	* a result entry for every experiment (or `null` when it did not run the item).
	*/
	async compareExperiments(args) {
		const experimentIds = [...new Set(args.experimentIds)];
		if (experimentIds.length < 2) throw new MastraError({
			id: "COMPARE_INVALID_INPUT",
			text: "compareExperiments requires at least 2 distinct experiment IDs.",
			domain: "STORAGE",
			category: "USER"
		});
		const baselineId = args.baselineId ?? experimentIds[0];
		if (!experimentIds.includes(baselineId)) throw new MastraError({
			id: "COMPARE_INVALID_INPUT",
			text: `baselineId "${baselineId}" must be one of experimentIds.`,
			domain: "STORAGE",
			category: "USER"
		});
		const contenderIds = experimentIds.filter((id) => id !== baselineId);
		const experimentsStore = await this.#getExperimentsStore();
		const filters = scopeFromArgs(args);
		if (filters) {
			const missingIndex = (await Promise.all(experimentIds.map((id) => experimentsStore.getExperimentById({
				id,
				filters
			})))).findIndex((experiment) => !experiment);
			if (missingIndex !== -1) throw new MastraError({
				id: "EXPERIMENT_NOT_FOUND",
				text: `Experiment not found: ${experimentIds[missingIndex]}`,
				domain: "STORAGE",
				category: "USER"
			});
		}
		const [pairs, resultLists] = await Promise.all([Promise.all(contenderIds.map((contenderId) => compareExperiments(this.#mastra, {
			experimentIdA: baselineId,
			experimentIdB: contenderId
		}))), Promise.all(experimentIds.map((experimentId) => experimentsStore.listExperimentResults({
			experimentId,
			pagination: {
				page: 0,
				perPage: false
			}
		})))]);
		const resultsByExperiment = new Map(experimentIds.map((experimentId, index) => [experimentId, new Map(resultLists[index].results.map((result) => [result.itemId, result]))]));
		const scores = new Map(experimentIds.map((experimentId) => [experimentId, /* @__PURE__ */ new Map()]));
		const itemIds = /* @__PURE__ */ new Set();
		pairs.forEach((pair, index) => {
			const contenderId = contenderIds[index];
			for (const item of pair.items) {
				itemIds.add(item.itemId);
				const baselineScores = scores.get(baselineId);
				baselineScores.set(item.itemId, {
					...baselineScores.get(item.itemId),
					...item.scoresA
				});
				scores.get(contenderId).set(item.itemId, item.scoresB);
			}
		});
		return {
			baselineId,
			items: [...itemIds].map((itemId) => {
				let source;
				const results = Object.fromEntries(experimentIds.map((experimentId) => {
					const result = resultsByExperiment.get(experimentId).get(itemId);
					source ??= result;
					return [experimentId, result ? {
						output: result.output,
						scores: scores.get(experimentId).get(itemId) ?? {}
					} : null];
				}));
				return {
					itemId,
					input: source?.input ?? null,
					groundTruth: source?.groundTruth ?? null,
					results
				};
			})
		};
	}
};
export { TOOL_MOCK_NOT_DECLARED as _, executeExperimentItem as a, computeScorerStats as c, resolveScorers as d, runScorersForItem as f, TOOL_MOCK_MISMATCH as g, TOOL_MOCK_EXHAUSTED as h, runExperiment as i, isRegression as l, executeTarget as m, Dataset as n, compareExperiments as o, resolveTarget as p, EXPERIMENT_ITEM_BEFORE_EACH_FAILED as r, computeMean as s, DatasetsManager as t, EXPERIMENT_ITEM_SCORER_NOT_FOUND as u, ToolMockMatcher as v };

//# sourceMappingURL=manager-DHcGDPph.js.map