vieval 0.0.4 → 0.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +6 -3
  2. package/dist/bin/vieval.d.mts +1 -0
  3. package/dist/bin/vieval.mjs +33 -0
  4. package/dist/bin/vieval.mjs.map +1 -0
  5. package/dist/cli/index.d.mts +32 -0
  6. package/dist/cli/index.mjs +1 -2582
  7. package/dist/cli-DayPXzHX.mjs +2593 -0
  8. package/dist/cli-DayPXzHX.mjs.map +1 -0
  9. package/dist/config.d.mts +1 -1
  10. package/dist/config.mjs +17 -2
  11. package/dist/config.mjs.map +1 -0
  12. package/dist/core/assertions/index.d.mts +314 -2
  13. package/dist/core/assertions/index.mjs +182 -1
  14. package/dist/core/assertions/index.mjs.map +1 -0
  15. package/dist/core/inference-executors/index.d.mts +1 -1
  16. package/dist/core/inference-executors/index.mjs +1 -1
  17. package/dist/core/processors/results/index.d.mts +1 -1
  18. package/dist/core/runner/index.d.mts +1 -1
  19. package/dist/core/runner/index.mjs +635 -1
  20. package/dist/core/runner/index.mjs.map +1 -0
  21. package/dist/{env-C7X81PWa.mjs → env-BFSjny07.mjs} +1 -1
  22. package/dist/{env-C7X81PWa.mjs.map → env-BFSjny07.mjs.map} +1 -1
  23. package/dist/{env-DtpjACOW.d.mts → env-BTq3dV7C.d.mts} +1 -1
  24. package/dist/{expect-extensions-BOzwV5EJ.mjs → expect-extensions-QLXESWjn.mjs} +2 -2
  25. package/dist/{expect-extensions-BOzwV5EJ.mjs.map → expect-extensions-QLXESWjn.mjs.map} +1 -1
  26. package/dist/expect.d.mts +10 -2
  27. package/dist/expect.mjs +16 -1
  28. package/dist/expect.mjs.map +1 -0
  29. package/dist/{index-BDMEAmf2.d.mts → index-OEdqjQSe.d.mts} +2 -2
  30. package/dist/index.d.mts +3 -3
  31. package/dist/index.mjs +4 -4
  32. package/dist/{models-DIGdOUpJ.mjs → models-D_MsBtYw.mjs} +1 -1
  33. package/dist/{models-DIGdOUpJ.mjs.map → models-D_MsBtYw.mjs.map} +1 -1
  34. package/dist/plugins/chat-models/index.d.mts +1 -1
  35. package/dist/plugins/chat-models/index.mjs +1 -1
  36. package/dist/{registry-CHJcTN2W.mjs → registry-CwcMMjnZ.mjs} +3 -3
  37. package/dist/{registry-CHJcTN2W.mjs.map → registry-CwcMMjnZ.mjs.map} +1 -1
  38. package/dist/testing/expect-extensions.d.mts +1 -1
  39. package/dist/testing/expect-extensions.mjs +1 -1
  40. package/package.json +3 -3
  41. package/dist/assertions-DcAjfVDA.mjs +0 -183
  42. package/dist/assertions-DcAjfVDA.mjs.map +0 -1
  43. package/dist/cli/index.mjs.map +0 -1
  44. package/dist/config-CHN24egi.mjs +0 -17
  45. package/dist/config-CHN24egi.mjs.map +0 -1
  46. package/dist/expect-B2vaoRVZ.d.mts +0 -10
  47. package/dist/expect-CaXiUkwY.mjs +0 -17
  48. package/dist/expect-CaXiUkwY.mjs.map +0 -1
  49. package/dist/index-C3gPFmcR.d.mts +0 -314
  50. package/dist/runner-Dpy-eivM.mjs +0 -636
  51. package/dist/runner-Dpy-eivM.mjs.map +0 -1
@@ -0,0 +1,2593 @@
1
+ import { c as loadRawVievalConfig, l as loadVievalCliConfig, n as consumeModuleRegistrations, o as detectCliConfigMode, r as endModuleRegistration, t as beginModuleRegistration } from "./registry-CwcMMjnZ.mjs";
2
+ import { RunnerExecutionError, collectEvalEntries, createFilesystemTaskCacheRuntime, createRunnerRuntimeContext, createRunnerSchedule, createTaskExecutionContext, runScheduledTasks } from "./core/runner/index.mjs";
3
+ import process from "node:process";
4
+ import { errorMessageFrom } from "@moeru/std";
5
+ import meow from "meow";
6
+ import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
7
+ import { access, mkdir, writeFile } from "node:fs/promises";
8
+ import { glob } from "tinyglobby";
9
+ import { pathToFileURL } from "node:url";
10
+ import { randomUUID } from "node:crypto";
11
+ import c from "tinyrainbow";
12
+ import { existsSync, readFileSync } from "node:fs";
13
+ import { uniq } from "es-toolkit";
14
+ import { createVitest } from "vitest/node";
15
+ import { stripVTControlCharacters } from "node:util";
16
+ import stringWidth from "fast-string-width";
17
+ //#region src/cli/comparison-config.ts
18
+ const supportedWorkspaceConfigFileNames = [
19
+ "vieval.config.ts",
20
+ "vieval.config.mts",
21
+ "vieval.config.cts",
22
+ "vieval.config.js",
23
+ "vieval.config.mjs",
24
+ "vieval.config.cjs",
25
+ "vieval.config.json"
26
+ ];
27
+ async function isReadableFile(filePath) {
28
+ try {
29
+ await access(filePath);
30
+ return true;
31
+ } catch {
32
+ return false;
33
+ }
34
+ }
35
+ function normalizeGlobInput(patterns) {
36
+ if (patterns == null) return [];
37
+ return (typeof patterns === "string" ? [patterns] : patterns).map((pattern) => pattern.trim()).filter((pattern) => pattern.length > 0);
38
+ }
39
+ function normalizeMethodShape(method, configDirectory, index) {
40
+ const id = method.id.trim();
41
+ const workspace = method.workspace.trim();
42
+ const project = method.project.trim();
43
+ const configFilePath = method.configFilePath?.trim();
44
+ if (id.length === 0) throw new Error(`Comparison method #${index + 1} is missing id.`);
45
+ if (workspace.length === 0) throw new Error(`Comparison method "${id}" is missing workspace.`);
46
+ if (project.length === 0) throw new Error(`Comparison method "${id}" is missing project.`);
47
+ const resolvedWorkspace = isAbsolute(workspace) ? workspace : resolve(configDirectory, workspace);
48
+ return {
49
+ configFilePath: configFilePath == null || configFilePath.length === 0 ? void 0 : isAbsolute(configFilePath) ? configFilePath : resolve(configDirectory, configFilePath),
50
+ id,
51
+ project,
52
+ workspace: resolvedWorkspace
53
+ };
54
+ }
55
+ async function findWorkspaceConfigFile(workspaceDirectory) {
56
+ for (const fileName of supportedWorkspaceConfigFileNames) {
57
+ const candidate = join(workspaceDirectory, fileName);
58
+ if (await isReadableFile(candidate)) return candidate;
59
+ }
60
+ return null;
61
+ }
62
+ function createDiscoveredMethodId(configDirectory, workspace, projectName) {
63
+ const relativeWorkspace = relative(configDirectory, workspace);
64
+ return `${(relativeWorkspace.length > 0 ? relativeWorkspace : basename(workspace)).replaceAll("\\", "/")}:${projectName}`;
65
+ }
66
+ async function discoverMethodsFromWorkspaceGlobs(args) {
67
+ const includes = normalizeGlobInput(args.comparison.includesWorkspaces);
68
+ if (includes.length === 0) return [];
69
+ const discoveredWorkspaceDirectories = await glob(includes, {
70
+ absolute: true,
71
+ cwd: args.configDirectory,
72
+ ignore: normalizeGlobInput(args.comparison.excludesWorkspaces),
73
+ onlyDirectories: true
74
+ });
75
+ const methods = [];
76
+ for (const workspaceDirectory of discoveredWorkspaceDirectories.sort((left, right) => left.localeCompare(right))) {
77
+ const configFilePath = await findWorkspaceConfigFile(workspaceDirectory);
78
+ if (configFilePath == null) continue;
79
+ const loadedWorkspaceConfig = await loadVievalCliConfig({
80
+ configFilePath,
81
+ cwd: workspaceDirectory
82
+ });
83
+ for (const project of loadedWorkspaceConfig.projects) methods.push({
84
+ configFilePath,
85
+ id: createDiscoveredMethodId(args.configDirectory, workspaceDirectory, project.name),
86
+ project: project.name,
87
+ workspace: workspaceDirectory
88
+ });
89
+ }
90
+ return methods;
91
+ }
92
+ function validateMethodIdsAreUnique(methods) {
93
+ const methodIds = methods.map((method) => method.id);
94
+ const duplicatedMethodId = methodIds.find((methodId, index) => methodIds.indexOf(methodId) !== index);
95
+ if (duplicatedMethodId != null) throw new Error(`Duplicate comparison method id "${duplicatedMethodId}".`);
96
+ }
97
+ function assertComparisonMode(config) {
98
+ const mode = detectCliConfigMode(config);
99
+ if (mode !== "comparisons") throw new Error(`Expected comparison-mode config, but received ${mode}-mode config.`);
100
+ }
101
+ function selectComparisonConfig(comparisons, comparisonId) {
102
+ if (comparisons.length === 0) throw new Error("Comparison config requires at least one comparisons entry.");
103
+ if (comparisonId == null || comparisonId.trim().length === 0) {
104
+ if (comparisons.length > 1) throw new Error(`Multiple comparisons found. Provide --comparison. Available ids: ${comparisons.map((item) => item.id).join(", ")}`);
105
+ return comparisons[0];
106
+ }
107
+ const selected = comparisons.find((item) => item.id === comparisonId);
108
+ if (selected == null) throw new Error(`Unknown comparison id "${comparisonId}".`);
109
+ return selected;
110
+ }
111
+ function normalizeBenchmark(comparison) {
112
+ const benchmarkId = comparison.benchmark.id.trim();
113
+ const sharedCaseNamespace = comparison.benchmark.sharedCaseNamespace.trim();
114
+ if (benchmarkId.length === 0) throw new Error("Comparison config requires benchmark.id.");
115
+ if (sharedCaseNamespace.length === 0) throw new Error("Comparison config requires benchmark.sharedCaseNamespace.");
116
+ return {
117
+ id: benchmarkId,
118
+ sharedCaseNamespace
119
+ };
120
+ }
121
+ /**
122
+ * Loads and validates comparison-mode data from `vieval.config.*`.
123
+ */
124
+ async function loadVievalComparisonConfig(options = {}) {
125
+ const cwd = options.cwd ?? process.cwd();
126
+ try {
127
+ const loaded = await loadRawVievalConfig({
128
+ configFilePath: options.configFilePath,
129
+ cwd
130
+ });
131
+ if (loaded.configFilePath == null || loaded.config == null) throw new Error("Failed to find vieval config. Expected vieval.config.*");
132
+ assertComparisonMode(loaded.config);
133
+ const selectedComparison = selectComparisonConfig(loaded.config.comparisons, options.comparisonId);
134
+ const configDirectory = dirname(loaded.configFilePath);
135
+ const explicitMethods = (selectedComparison.methods ?? []).map((method, index) => normalizeMethodShape(method, configDirectory, index));
136
+ const discoveredMethods = await discoverMethodsFromWorkspaceGlobs({
137
+ comparison: selectedComparison,
138
+ configDirectory
139
+ });
140
+ const methods = [...explicitMethods, ...discoveredMethods];
141
+ if (methods.length === 0) throw new Error("Comparison config resolved zero methods. Configure methods or includesWorkspaces.");
142
+ validateMethodIdsAreUnique(methods);
143
+ return {
144
+ config: {
145
+ benchmark: normalizeBenchmark(selectedComparison),
146
+ methods
147
+ },
148
+ configFilePath: loaded.configFilePath
149
+ };
150
+ } catch (error) {
151
+ const errorMessage = errorMessageFrom(error) ?? "Unknown comparison config loading error.";
152
+ const resolvedPath = options.configFilePath ?? "vieval.config";
153
+ throw new Error(`Failed to load comparison config "${resolvedPath}": ${errorMessage}`);
154
+ }
155
+ }
156
+ //#endregion
157
+ //#region src/cli/report-compare.ts
158
+ /**
159
+ * Builds a compact compare report sorted by hybrid/exact score.
160
+ */
161
+ function buildCompareReportArtifact(args) {
162
+ const rows = args.methods.map((method) => {
163
+ const overall = method.output.projects[0]?.result?.overall;
164
+ return {
165
+ exactAverage: overall?.exactAverage ?? null,
166
+ hybridAverage: overall?.hybridAverage ?? null,
167
+ methodId: method.methodId,
168
+ runCount: overall?.runCount ?? 0
169
+ };
170
+ });
171
+ rows.sort((left, right) => {
172
+ const leftHybrid = left.hybridAverage ?? Number.NEGATIVE_INFINITY;
173
+ const rightHybrid = right.hybridAverage ?? Number.NEGATIVE_INFINITY;
174
+ if (leftHybrid !== rightHybrid) return rightHybrid - leftHybrid;
175
+ const leftExact = left.exactAverage ?? Number.NEGATIVE_INFINITY;
176
+ return (right.exactAverage ?? Number.NEGATIVE_INFINITY) - leftExact;
177
+ });
178
+ return {
179
+ benchmarkId: args.benchmarkId,
180
+ methods: rows,
181
+ reportPath: args.reportPath
182
+ };
183
+ }
184
+ /**
185
+ * Writes compare report artifact as JSON.
186
+ */
187
+ async function writeCompareReportArtifact(args) {
188
+ const outputPath = resolve(args.outputPath);
189
+ await mkdir(dirname(outputPath), { recursive: true });
190
+ await writeFile(outputPath, `${JSON.stringify(args.artifact, null, 2)}\n`, "utf-8");
191
+ return outputPath;
192
+ }
193
+ //#endregion
194
+ //#region src/cli/discovery.ts
195
+ /**
196
+ * Discovers eval files using include/exclude globs relative to project root.
197
+ *
198
+ * Before:
199
+ * - Absolute path file list from recursive filesystem walk
200
+ *
201
+ * After:
202
+ * - Filtered absolute path list matching include/exclude rules
203
+ */
204
+ async function discoverEvalFiles(options) {
205
+ return uniq(await glob([...options.include], {
206
+ absolute: true,
207
+ cwd: options.root,
208
+ ignore: [...options.exclude],
209
+ onlyFiles: true
210
+ })).sort((left, right) => left.localeCompare(right));
211
+ }
212
+ //#endregion
213
+ //#region src/cli/module-runtime.ts
214
+ /**
215
+ * Loads eval modules and returns a normalized eval-module map.
216
+ *
217
+ * Use when:
218
+ * - CLI collection needs Vite/Vitest-powered module resolution and transforms
219
+ * - eval files should be imported with the same runtime semantics as Vitest
220
+ *
221
+ * Expects:
222
+ * - `projectRoot` points at the project that owns the eval files
223
+ * - each `evalFilePaths` entry is an absolute file path
224
+ *
225
+ * Returns:
226
+ * - eval modules keyed by stable file href + optional registration suffixes
227
+ */
228
+ async function loadEvalModulesWithVitestRuntime(evalFilePaths, projectRoot) {
229
+ const loadedModules = {};
230
+ const runtime = await createVitest("test", {
231
+ config: false,
232
+ root: projectRoot,
233
+ run: false,
234
+ silent: true,
235
+ watch: false
236
+ });
237
+ try {
238
+ for (const evalFilePath of evalFilePaths) {
239
+ const moduleHref = pathToFileURL(evalFilePath).href;
240
+ beginModuleRegistration(moduleHref);
241
+ try {
242
+ const moduleValue = await runtime.import(moduleHref);
243
+ const registeredDefinitions = consumeModuleRegistrations(moduleHref);
244
+ const defaultDefinition = moduleValue.default;
245
+ const definitions = [...registeredDefinitions, ...defaultDefinition == null ? [] : [defaultDefinition]];
246
+ const deduplicatedDefinitions = definitions.filter((definition, index) => {
247
+ const key = `${definition.name}::${definition.description}::${definition.task?.id ?? ""}`;
248
+ return definitions.findIndex((candidate) => `${candidate.name}::${candidate.description}::${candidate.task?.id ?? ""}` === key) === index;
249
+ });
250
+ if (deduplicatedDefinitions.length === 0) continue;
251
+ for (const [definitionIndex, definition] of deduplicatedDefinitions.entries()) {
252
+ const moduleKey = definitionIndex === 0 ? moduleHref : `${moduleHref}#registration-${definitionIndex + 1}`;
253
+ loadedModules[moduleKey] = { default: definition };
254
+ }
255
+ } finally {
256
+ endModuleRegistration();
257
+ }
258
+ }
259
+ } finally {
260
+ await runtime.close();
261
+ }
262
+ return loadedModules;
263
+ }
264
+ //#endregion
265
+ //#region src/cli/reporters/noop-reporter.ts
266
+ /**
267
+ * Creates a reporter that intentionally does nothing.
268
+ *
269
+ * Use when:
270
+ * - terminal output should stay silent
271
+ * - reporter wiring needs a safe default for tests or non-interactive runs
272
+ *
273
+ * Expects:
274
+ * - callers may invoke any lifecycle method in any order that matches the run
275
+ *
276
+ * Returns:
277
+ * - a stable reporter implementation with no observable side effects
278
+ */
279
+ function createNoopReporter() {
280
+ return {
281
+ onRunStart(_payload) {},
282
+ onTaskQueued(_payload) {},
283
+ onTaskStart(_payload) {},
284
+ onCaseStart(_payload) {},
285
+ onCaseEnd(_payload) {},
286
+ onTaskEnd(_payload) {},
287
+ onRunEnd(_payload) {},
288
+ dispose() {}
289
+ };
290
+ }
291
+ //#endregion
292
+ //#region src/cli/reporters/summary-reporter.ts
293
+ const POINTER = "❯";
294
+ const TREE_NODE_END = "└";
295
+ const TREE_NODE_MIDDLE = "├";
296
+ var SummaryReporterStateMachine = class {
297
+ options;
298
+ taskCounters = createCounterState();
299
+ caseCounters = createCounterState();
300
+ tasks = /* @__PURE__ */ new Map();
301
+ queueOrderCounter = 0;
302
+ startedAtMs = 0;
303
+ startTime = "";
304
+ constructor(options) {
305
+ this.options = options;
306
+ }
307
+ /**
308
+ * Handles run startup.
309
+ *
310
+ * Use when:
311
+ * - a new CLI run is starting and the summary state must reset
312
+ *
313
+ * Expects:
314
+ * - `totalTasks` matches the scheduled task count for the run
315
+ *
316
+ * Returns:
317
+ * - no direct value
318
+ */
319
+ onRunStart(payload) {
320
+ this.tasks.clear();
321
+ this.queueOrderCounter = 0;
322
+ resetCounterState(this.taskCounters, payload.totalTasks);
323
+ resetCounterState(this.caseCounters, 0);
324
+ this.startedAtMs = this.options.getNow();
325
+ this.startTime = formatTimeString(new Date(this.options.getWallClockNow()));
326
+ }
327
+ /**
328
+ * Handles task queue events.
329
+ *
330
+ * Use when:
331
+ * - a scheduled task becomes visible in the live summary before it starts
332
+ *
333
+ * Expects:
334
+ * - `taskId` is stable across later lifecycle events
335
+ *
336
+ * Returns:
337
+ * - no direct value
338
+ */
339
+ onTaskQueued(payload) {
340
+ const task = this.getOrCreateTaskState(payload.taskId);
341
+ if (task.state === "finished") return;
342
+ task.displayName = payload.displayName ?? task.displayName;
343
+ task.projectName = payload.projectName ?? task.projectName;
344
+ this.syncTaskTotalCases(task, payload.totalCases);
345
+ }
346
+ /**
347
+ * Handles task start events.
348
+ *
349
+ * Use when:
350
+ * - a queued task begins executing
351
+ *
352
+ * Expects:
353
+ * - the task was previously queued or can be synthesized from its identifier
354
+ *
355
+ * Returns:
356
+ * - no direct value
357
+ */
358
+ onTaskStart(payload) {
359
+ const task = this.getOrCreateTaskState(payload.taskId);
360
+ if (task.state === "finished") return;
361
+ task.state = "running";
362
+ task.startedAt ??= this.options.getNow();
363
+ }
364
+ /**
365
+ * Handles case start events.
366
+ *
367
+ * Use when:
368
+ * - a running task starts one case and slow-case tracking may begin
369
+ *
370
+ * Expects:
371
+ * - `caseId` is stable for the lifetime of the running case
372
+ *
373
+ * Returns:
374
+ * - no direct value
375
+ */
376
+ onCaseStart(payload) {
377
+ const task = this.getOrCreateTaskState(payload.taskId);
378
+ if (task.state === "finished") return;
379
+ task.state = "running";
380
+ task.startedAt ??= this.options.getNow();
381
+ if (task.settledCaseIds.has(payload.caseId) || task.runningCases.has(payload.caseId)) return;
382
+ task.caseOrderCounter += 1;
383
+ task.runningCases.set(payload.caseId, {
384
+ caseId: payload.caseId,
385
+ caseName: payload.caseName ?? payload.caseId,
386
+ order: task.caseOrderCounter,
387
+ startedAt: this.options.getNow()
388
+ });
389
+ this.syncTaskTotalCases(task);
390
+ }
391
+ /**
392
+ * Handles case completion.
393
+ *
394
+ * Use when:
395
+ * - a running case settles and counters must advance
396
+ *
397
+ * Expects:
398
+ * - duplicate completion for the same `caseId` is ignored
399
+ *
400
+ * Returns:
401
+ * - no direct value
402
+ */
403
+ onCaseEnd(payload) {
404
+ const task = this.getOrCreateTaskState(payload.taskId);
405
+ if (task.state === "finished") return;
406
+ if (task.settledCaseIds.has(payload.caseId)) {
407
+ task.runningCases.delete(payload.caseId);
408
+ return;
409
+ }
410
+ task.settledCaseIds.add(payload.caseId);
411
+ task.runningCases.delete(payload.caseId);
412
+ task.completedCases += 1;
413
+ this.syncTaskTotalCases(task);
414
+ this.caseCounters.completed += 1;
415
+ if (payload.state === "passed") {
416
+ this.caseCounters.passed += 1;
417
+ return;
418
+ }
419
+ if (payload.state === "failed") {
420
+ this.caseCounters.failed += 1;
421
+ return;
422
+ }
423
+ this.caseCounters.skipped += 1;
424
+ }
425
+ /**
426
+ * Handles task completion.
427
+ *
428
+ * Use when:
429
+ * - a task leaves the active window and contributes to terminal totals
430
+ *
431
+ * Expects:
432
+ * - duplicate task completion for the same task is ignored
433
+ *
434
+ * Returns:
435
+ * - no direct value
436
+ */
437
+ onTaskEnd(payload) {
438
+ const task = this.getOrCreateTaskState(payload.taskId);
439
+ if (task.state === "finished") return;
440
+ this.syncTaskTotalCases(task);
441
+ task.state = "finished";
442
+ task.taskResult = payload.state;
443
+ task.runningCases.clear();
444
+ this.taskCounters.completed += 1;
445
+ if (payload.state === "passed") {
446
+ this.taskCounters.passed += 1;
447
+ return;
448
+ }
449
+ if (payload.state === "failed") {
450
+ this.taskCounters.failed += 1;
451
+ return;
452
+ }
453
+ this.taskCounters.skipped += 1;
454
+ }
455
+ /**
456
+ * Handles run completion.
457
+ *
458
+ * Use when:
459
+ * - the caller has final task totals and wants the footer normalized
460
+ *
461
+ * Expects:
462
+ * - payload counters are final terminal task totals
463
+ *
464
+ * Returns:
465
+ * - no direct value
466
+ */
467
+ onRunEnd(payload) {
468
+ this.taskCounters.total = payload.totalTasks;
469
+ this.taskCounters.passed = payload.passedTasks;
470
+ this.taskCounters.failed = payload.failedTasks;
471
+ this.taskCounters.skipped = payload.skippedTasks;
472
+ this.taskCounters.completed = payload.passedTasks + payload.failedTasks + payload.skippedTasks;
473
+ }
474
+ /**
475
+ * Releases reporter resources.
476
+ *
477
+ * Use when:
478
+ * - CLI cleanup runs from a `finally` block
479
+ *
480
+ * Expects:
481
+ * - repeated calls are safe
482
+ *
483
+ * Returns:
484
+ * - no direct value
485
+ */
486
+ dispose() {}
487
+ /**
488
+ * Builds the current live summary window rows.
489
+ *
490
+ * Use when:
491
+ * - the live reporter or tests need a snapshot of the active window
492
+ *
493
+ * Expects:
494
+ * - `maxRows`, when present, keeps footer rows visible
495
+ *
496
+ * Returns:
497
+ * - terminal rows in display order
498
+ */
499
+ getWindowRows(options) {
500
+ const activeRows = this.createActiveRows();
501
+ const footerRows = this.createFooterRows();
502
+ const maxRows = options?.maxRows;
503
+ const activeBlock = [
504
+ "",
505
+ ...activeRows,
506
+ ...activeRows.length > 0 ? [""] : []
507
+ ];
508
+ const footerBlock = [...footerRows, ""];
509
+ if (maxRows == null || maxRows <= 0) return [...activeBlock, ...footerBlock];
510
+ if (maxRows <= footerBlock.length) return footerBlock.slice(-maxRows);
511
+ const availableActiveRows = Math.max(0, maxRows - footerBlock.length);
512
+ return [...activeBlock.slice(0, availableActiveRows), ...footerBlock];
513
+ }
514
+ createActiveRows() {
515
+ const activeTasks = Array.from(this.tasks.values()).filter((task) => task.state !== "finished").sort(compareActiveTasks);
516
+ const rows = [];
517
+ for (const task of activeTasks) {
518
+ const suffix = task.state === "queued" ? c.dim(" [queued]") : ` ${task.completedCases}/${task.totalCases}`;
519
+ const badge = formatProjectBadge(task.projectName, this.options.isTTY);
520
+ rows.push(c.bold(c.yellow(` ${POINTER} `)) + badge + task.displayName + c.dim(suffix));
521
+ const slowCases = Array.from(task.runningCases.values()).filter((activeCase) => this.options.getNow() - activeCase.startedAt >= this.options.slowThresholdMs).sort((left, right) => left.order - right.order);
522
+ for (const [index, activeCase] of slowCases.entries()) {
523
+ const icon = index === slowCases.length - 1 ? TREE_NODE_END : TREE_NODE_MIDDLE;
524
+ const elapsed = Math.max(0, this.options.getNow() - activeCase.startedAt);
525
+ rows.push(c.bold(c.yellow(` ${icon} `)) + activeCase.caseName + c.bold(c.yellow(` ${formatDuration$1(elapsed)}`)));
526
+ }
527
+ }
528
+ return rows;
529
+ }
530
+ createFooterRows() {
531
+ return [
532
+ padSummaryTitle("Tasks") + formatCounterState(this.taskCounters),
533
+ padSummaryTitle("Cases") + formatCounterState(this.caseCounters),
534
+ padSummaryTitle("Start at") + this.startTime,
535
+ padSummaryTitle("Duration") + formatDuration$1(Math.max(0, this.options.getNow() - this.startedAtMs))
536
+ ];
537
+ }
538
+ getOrCreateTaskState(taskId) {
539
+ const existing = this.tasks.get(taskId);
540
+ if (existing != null) return existing;
541
+ const created = {
542
+ caseOrderCounter: 0,
543
+ completedCases: 0,
544
+ displayName: taskId,
545
+ projectName: void 0,
546
+ queueOrder: this.queueOrderCounter,
547
+ runningCases: /* @__PURE__ */ new Map(),
548
+ settledCaseIds: /* @__PURE__ */ new Set(),
549
+ startedAt: void 0,
550
+ state: "queued",
551
+ taskId,
552
+ taskResult: void 0,
553
+ totalCases: 0
554
+ };
555
+ this.queueOrderCounter += 1;
556
+ this.tasks.set(taskId, created);
557
+ return created;
558
+ }
559
+ syncTaskTotalCases(task, reportedTotalCases) {
560
+ const observedTotalCases = task.completedCases + task.runningCases.size;
561
+ task.totalCases = Math.max(task.totalCases, reportedTotalCases ?? 0, observedTotalCases);
562
+ this.caseCounters.total = sumTaskCaseTotals(this.tasks.values());
563
+ }
564
+ };
565
+ /**
566
+ * Creates the live summary reporter state machine for `vieval` CLI runs.
567
+ *
568
+ * Use when:
569
+ * - the CLI wants Vitest-style active rows and live counters
570
+ * - tests need a deterministic reporter surface without touching the terminal
571
+ *
572
+ * Expects:
573
+ * - queue/start/end events describe task lifecycle in order
574
+ * - `getNow()` remains monotonic within one run
575
+ * - `getWallClockNow()` returns the wall-clock run start timestamp
576
+ *
577
+ * Returns:
578
+ * - a reporter compatible with the base CLI lifecycle plus `getWindowRows()`
579
+ *
580
+ * Call stack:
581
+ *
582
+ * {@link createSummaryReporter}
583
+ * -> {@link SummaryReporterStateMachine.onTaskQueued}
584
+ * -> {@link SummaryReporterStateMachine.onCaseStart}
585
+ * -> {@link SummaryReporterStateMachine.getWindowRows}
586
+ */
587
+ function createSummaryReporter(options) {
588
+ return new SummaryReporterStateMachine(options);
589
+ }
590
+ function createCounterState() {
591
+ return {
592
+ completed: 0,
593
+ failed: 0,
594
+ passed: 0,
595
+ skipped: 0,
596
+ total: 0
597
+ };
598
+ }
599
+ function resetCounterState(counter, total) {
600
+ counter.completed = 0;
601
+ counter.failed = 0;
602
+ counter.passed = 0;
603
+ counter.skipped = 0;
604
+ counter.total = total;
605
+ }
606
+ function sumTaskCaseTotals(tasks) {
607
+ let total = 0;
608
+ for (const task of tasks) total += task.totalCases;
609
+ return total;
610
+ }
611
+ function compareActiveTasks(left, right) {
612
+ const leftProject = left.projectName ?? "";
613
+ const rightProject = right.projectName ?? "";
614
+ if (leftProject !== rightProject) return leftProject.localeCompare(rightProject);
615
+ const displayNameOrder = left.displayName.localeCompare(right.displayName);
616
+ if (displayNameOrder !== 0) return displayNameOrder;
617
+ return left.queueOrder - right.queueOrder;
618
+ }
619
+ function padSummaryTitle(label) {
620
+ return `${c.dim(label.padEnd(8))} `;
621
+ }
622
+ function formatCounterState(counter) {
623
+ return [
624
+ c.bold(c.green(`${counter.passed} passed`)),
625
+ counter.failed > 0 ? c.bold(c.red(`${counter.failed} failed`)) : c.dim(`${counter.failed} failed`),
626
+ counter.skipped > 0 ? c.yellow(`${counter.skipped} skipped`) : c.dim(`${counter.skipped} skipped`)
627
+ ].join(c.dim(" | ")) + c.gray(` (${counter.total})`);
628
+ }
629
+ function formatTimeString(date) {
630
+ return date.toTimeString().split(" ")[0] ?? "";
631
+ }
632
+ function formatDuration$1(durationMs) {
633
+ if (durationMs >= 1e3) return `${(durationMs / 1e3).toFixed(2)}s`;
634
+ return `${Math.round(durationMs)}ms`;
635
+ }
636
+ function formatProjectBadge(projectName, isTTY) {
637
+ if (projectName == null || projectName.length === 0) return "";
638
+ if (!isTTY || !c.isColorSupported) return `|${projectName}| `;
639
+ const backgroundPool = [
640
+ c.bgYellow,
641
+ c.bgCyan,
642
+ c.bgGreen,
643
+ c.bgMagenta
644
+ ];
645
+ const background = backgroundPool[projectName.split("").reduce((accumulator, character, index) => accumulator + character.charCodeAt(0) + index, 0) % backgroundPool.length];
646
+ return `${c.black(background(` ${projectName} `))} `;
647
+ }
648
+ //#endregion
649
+ //#region src/cli/reporters/index.ts
650
+ /**
651
+ * Creates the default CLI reporter for the current output mode.
652
+ *
653
+ * Use when:
654
+ * - interactive terminals should use the live summary reporter
655
+ * - non-interactive environments should stay silent with the noop reporter
656
+ *
657
+ * Expects:
658
+ * - `isTTY` decides whether the live summary reporter can be used
659
+ *
660
+ * Returns:
661
+ * - a summary reporter for TTY runs, otherwise a noop reporter
662
+ */
663
+ function createCliReporter(options) {
664
+ if (!options.isTTY) return createNoopReporter();
665
+ return createSummaryReporter(options);
666
+ }
667
+ //#endregion
668
+ //#region src/cli/reporters/renderers/windowed-renderer.ts
669
+ const DEFAULT_RENDER_INTERVAL_MS = 1e3;
670
+ const ESC = "\x1B[";
671
+ const CARRIAGE_RETURN = "\r";
672
+ const CLEAR_LINE = `${ESC}K`;
673
+ const MOVE_CURSOR_ONE_ROW_UP = `${ESC}1A`;
674
+ const SYNC_START = `${ESC}?2026h`;
675
+ const SYNC_END = `${ESC}?2026l`;
676
+ /**
677
+ * Renders a dynamic window at the bottom of the terminal.
678
+ *
679
+ * Use when:
680
+ * - a reporter needs in-place TTY updates without leaking terminal control codes into tests
681
+ * - callers want Vitest-style redraw behavior with injected output/timer dependencies
682
+ *
683
+ * Expects:
684
+ * - `start()` runs before `schedule()`
685
+ * - `finish()` or `dispose()` may be called multiple times safely
686
+ *
687
+ * Returns:
688
+ * - no direct value; all effects are emitted through the injected callbacks
689
+ *
690
+ * Call stack:
691
+ *
692
+ * {@link WindowRenderer.start}
693
+ * -> periodic schedule callback
694
+ * -> {@link WindowRenderer.schedule}
695
+ * -> {@link WindowRenderer.renderWindow}
696
+ */
697
+ var WindowRenderer = class {
698
+ options;
699
+ renderInterval;
700
+ renderScheduled = false;
701
+ renderScheduleVersion = 0;
702
+ windowHeight = 0;
703
+ started = false;
704
+ finished = false;
705
+ bufferedOutput = "";
706
+ constructor(options) {
707
+ if (options.createInterval && options.clearInterval) {
708
+ this.options = {
709
+ createInterval: (callback, intervalMs) => {
710
+ const timer = options.createInterval(callback, intervalMs);
711
+ return {
712
+ clear: () => options.clearInterval(timer),
713
+ unref: timer.unref?.bind(timer)
714
+ };
715
+ },
716
+ getColumns: options.getColumns,
717
+ getWindow: options.getWindow,
718
+ intervalMs: options.intervalMs ?? DEFAULT_RENDER_INTERVAL_MS,
719
+ queueRenderReset: options.queueRenderReset ?? defaultQueueRenderReset,
720
+ supportsAnsiWindowing: options.supportsAnsiWindowing ?? true,
721
+ writeOutput: options.writeOutput
722
+ };
723
+ return;
724
+ }
725
+ this.options = {
726
+ createInterval: defaultCreateInterval,
727
+ getColumns: options.getColumns,
728
+ getWindow: options.getWindow,
729
+ intervalMs: options.intervalMs ?? DEFAULT_RENDER_INTERVAL_MS,
730
+ queueRenderReset: options.queueRenderReset ?? defaultQueueRenderReset,
731
+ supportsAnsiWindowing: options.supportsAnsiWindowing ?? true,
732
+ writeOutput: options.writeOutput
733
+ };
734
+ }
735
+ /**
736
+ * Starts the periodic refresh loop.
737
+ *
738
+ * Use when:
739
+ * - the live reporter is about to emit in-place updates
740
+ *
741
+ * Expects:
742
+ * - repeated calls are harmless and keep the existing timer
743
+ *
744
+ * Returns:
745
+ * - no direct value
746
+ */
747
+ start() {
748
+ if (this.started && !this.finished) return;
749
+ this.started = true;
750
+ this.finished = false;
751
+ this.renderScheduleVersion += 1;
752
+ if (!this.renderInterval) {
753
+ this.renderInterval = this.options.createInterval(() => this.schedule(), this.options.intervalMs);
754
+ this.renderInterval.unref?.();
755
+ }
756
+ }
757
+ /**
758
+ * Queues a render if one is not already in flight.
759
+ *
760
+ * Use when:
761
+ * - reporter state changes and the bottom window should refresh
762
+ *
763
+ * Expects:
764
+ * - the renderer has been started
765
+ *
766
+ * Returns:
767
+ * - no direct value
768
+ */
769
+ schedule() {
770
+ if (!this.started || this.finished || this.renderScheduled) return;
771
+ const renderScheduleVersion = this.renderScheduleVersion;
772
+ this.renderScheduled = true;
773
+ this.renderWindow();
774
+ this.options.queueRenderReset(() => {
775
+ if (this.renderScheduleVersion !== renderScheduleVersion) return;
776
+ this.renderScheduled = false;
777
+ });
778
+ }
779
+ /**
780
+ * Clears the rendered window and stops the refresh loop.
781
+ *
782
+ * Use when:
783
+ * - the live reporter is transitioning to final static output
784
+ *
785
+ * Expects:
786
+ * - repeated calls are safe
787
+ *
788
+ * Returns:
789
+ * - no direct value
790
+ */
791
+ finish() {
792
+ if (this.finished) return;
793
+ this.finished = true;
794
+ this.started = false;
795
+ this.renderScheduleVersion += 1;
796
+ this.renderScheduled = false;
797
+ this.stopInterval();
798
+ this.clearWindow();
799
+ this.flushBufferedOutput();
800
+ }
801
+ /**
802
+ * Stops the renderer and clears any visible window state.
803
+ *
804
+ * Use when:
805
+ * - cleanup needs to happen from a `finally` block or interrupted run
806
+ *
807
+ * Expects:
808
+ * - callers may invoke it more than once
809
+ *
810
+ * Returns:
811
+ * - no direct value
812
+ */
813
+ dispose() {
814
+ this.finish();
815
+ }
816
+ /**
817
+ * Alias for disposal to match Vitest's renderer lifecycle naming.
818
+ *
819
+ * Use when:
820
+ * - adapting code that expects `stop()`
821
+ *
822
+ * Expects:
823
+ * - callers want the same semantics as `dispose()`
824
+ *
825
+ * Returns:
826
+ * - no direct value
827
+ */
828
+ stop() {
829
+ this.dispose();
830
+ }
831
+ /**
832
+ * Writes reporter output through the renderer lifecycle.
833
+ *
834
+ * Use when:
835
+ * - emitting log lines that must appear above the live ANSI window
836
+ * - callers need deterministic buffering behavior in tests
837
+ *
838
+ * Expects:
839
+ * - active ANSI window mode buffers until `schedule()` or `finish()`
840
+ * - inactive or non-windowed mode writes directly
841
+ *
842
+ * Returns:
843
+ * - no direct value
844
+ */
845
+ write(message) {
846
+ if (!this.isActiveWindowMode()) {
847
+ this.writeOutput(message);
848
+ return;
849
+ }
850
+ this.bufferedOutput += message;
851
+ }
852
+ renderWindow() {
853
+ const windowContent = this.options.getWindow();
854
+ const rowCount = getRenderedRowCount(windowContent, this.options.getColumns());
855
+ if (this.options.supportsAnsiWindowing) {
856
+ this.writeOutput(SYNC_START);
857
+ this.clearWindow();
858
+ }
859
+ this.flushBufferedOutput();
860
+ this.writeOutput(windowContent.join("\n"));
861
+ if (this.options.supportsAnsiWindowing) {
862
+ this.writeOutput(SYNC_END);
863
+ this.windowHeight = rowCount;
864
+ return;
865
+ }
866
+ this.writeOutput("\n");
867
+ this.windowHeight = 0;
868
+ }
869
+ clearWindow() {
870
+ if (!this.options.supportsAnsiWindowing || this.windowHeight === 0) return;
871
+ this.writeOutput(`${CARRIAGE_RETURN}${CLEAR_LINE}`);
872
+ for (let rowIndex = 1; rowIndex < this.windowHeight; rowIndex += 1) this.writeOutput(`${CARRIAGE_RETURN}${MOVE_CURSOR_ONE_ROW_UP}${CLEAR_LINE}`);
873
+ this.windowHeight = 0;
874
+ }
875
+ stopInterval() {
876
+ if (!this.renderInterval) return;
877
+ this.renderInterval.clear();
878
+ this.renderInterval = void 0;
879
+ }
880
+ writeOutput(message) {
881
+ this.options.writeOutput(message);
882
+ }
883
+ flushBufferedOutput() {
884
+ if (this.bufferedOutput.length === 0) return;
885
+ this.writeOutput(this.bufferedOutput);
886
+ this.bufferedOutput = "";
887
+ }
888
+ isActiveWindowMode() {
889
+ return this.started && !this.finished && this.options.supportsAnsiWindowing;
890
+ }
891
+ };
892
+ function defaultCreateInterval(callback, intervalMs) {
893
+ const timer = globalThis.setInterval(callback, intervalMs);
894
+ return {
895
+ clear: () => globalThis.clearInterval(timer),
896
+ unref: timer.unref?.bind(timer)
897
+ };
898
+ }
899
+ function defaultQueueRenderReset(callback) {
900
+ setTimeout(callback, 100).unref();
901
+ }
902
+ /** Calculate the rendered row count for the supplied rows and terminal width. */
903
+ function getRenderedRowCount(rows, columns) {
904
+ const safeColumns = Math.max(1, columns);
905
+ let count = 0;
906
+ for (const row of rows) {
907
+ const text = stripVTControlCharacters(row);
908
+ count += Math.max(1, Math.ceil(getTextDisplayWidth(text) / safeColumns));
909
+ }
910
+ return count;
911
+ }
912
+ function getTextDisplayWidth(text) {
913
+ return stringWidth(stripVTControlCharacters(text));
914
+ }
915
+ //#endregion
916
+ //#region src/cli/reporters/vitest-compat-reporter.ts
917
+ function isReporterReferenceTuple(reference) {
918
+ return Array.isArray(reference);
919
+ }
920
+ function isAbsoluteLikePath(value) {
921
+ return value.startsWith("/") || value.startsWith("./") || value.startsWith("../") || /^[A-Z]:[\\/]/i.test(value);
922
+ }
923
+ async function loadReporterModule(path) {
924
+ if (isAbsoluteLikePath(path)) return import(pathToFileURL(path).href);
925
+ return import(path);
926
+ }
927
+ function normalizeReporterReference(reference) {
928
+ if (isReporterReferenceTuple(reference)) return {
929
+ options: reference[1],
930
+ value: reference[0]
931
+ };
932
+ return {
933
+ options: void 0,
934
+ value: reference
935
+ };
936
+ }
937
+ function createReporterInstance(moduleValue, options) {
938
+ const value = moduleValue.default ?? moduleValue;
939
+ if (value == null) return null;
940
+ if (typeof value === "function") return new value(options);
941
+ if (typeof value === "object") return value;
942
+ return null;
943
+ }
944
+ async function emitToReporters(reporters, callback) {
945
+ await Promise.all(reporters.map(async (reporter) => {
946
+ try {
947
+ await callback(reporter);
948
+ } catch {}
949
+ }));
950
+ }
951
+ /**
952
+ * Creates a project-level vitest-compatible reporter bridge.
953
+ *
954
+ * Use when:
955
+ * - `vieval` should reuse vitest-like reporter callbacks without changing CLI output contracts
956
+ *
957
+ * Expects:
958
+ * - references point to modules whose default export is a reporter instance or constructor
959
+ *
960
+ * Returns:
961
+ * - `null` when no reporter references are configured
962
+ */
963
+ async function createVievalVitestCompatReporterBridge(options) {
964
+ if (options.references.length === 0) return null;
965
+ const loadedReporters = [];
966
+ for (const reference of options.references) {
967
+ const normalized = normalizeReporterReference(reference);
968
+ try {
969
+ const instance = createReporterInstance(typeof normalized.value === "string" ? await loadReporterModule(normalized.value) : normalized.value, normalized.options);
970
+ if (instance != null) loadedReporters.push(instance);
971
+ } catch {}
972
+ }
973
+ if (loadedReporters.length === 0) return null;
974
+ const modulesByTaskId = /* @__PURE__ */ new Map();
975
+ const casesByCompositeId = /* @__PURE__ */ new Map();
976
+ function getOrCreateModule(taskId) {
977
+ const existing = modulesByTaskId.get(taskId);
978
+ if (existing != null) return existing;
979
+ const created = {
980
+ id: taskId,
981
+ name: taskId,
982
+ projectName: options.projectName
983
+ };
984
+ modulesByTaskId.set(taskId, created);
985
+ return created;
986
+ }
987
+ function getOrCreateCase(taskId, caseId) {
988
+ const compositeId = `${taskId}::${caseId}`;
989
+ const existing = casesByCompositeId.get(compositeId);
990
+ if (existing != null) return existing;
991
+ const created = {
992
+ id: caseId,
993
+ module: getOrCreateModule(taskId),
994
+ name: caseId,
995
+ state: "pending"
996
+ };
997
+ casesByCompositeId.set(compositeId, created);
998
+ return created;
999
+ }
1000
+ return {
1001
+ async onCaseEnd(payload) {
1002
+ const taskCase = getOrCreateCase(payload.taskId, payload.caseId);
1003
+ taskCase.state = payload.state;
1004
+ await emitToReporters(loadedReporters, (reporter) => reporter.onTestCaseResult?.(taskCase));
1005
+ },
1006
+ async onCaseStart(payload) {
1007
+ const taskCase = getOrCreateCase(payload.taskId, payload.caseId);
1008
+ await emitToReporters(loadedReporters, (reporter) => reporter.onTestCaseReady?.(taskCase));
1009
+ },
1010
+ async onRunEnd(run) {
1011
+ const modules = [...modulesByTaskId.values()];
1012
+ const errors = run.failed ? [{ message: "vieval run failed" }] : [];
1013
+ await emitToReporters(loadedReporters, (reporter) => reporter.onTestRunEnd?.(modules, errors, run.failed ? "failed" : "passed"));
1014
+ },
1015
+ async onRunStart() {
1016
+ const specifications = [...modulesByTaskId.values()].map((module) => ({
1017
+ moduleId: module.id,
1018
+ projectName: module.projectName
1019
+ }));
1020
+ await emitToReporters(loadedReporters, (reporter) => reporter.onTestRunStart?.(specifications));
1021
+ },
1022
+ async onTaskEnd(payload) {
1023
+ const module = getOrCreateModule(payload.taskId);
1024
+ if (payload.state === "failed") {
1025
+ const syntheticCase = getOrCreateCase(payload.taskId, `${payload.taskId}:task`);
1026
+ syntheticCase.state = "failed";
1027
+ await emitToReporters(loadedReporters, (reporter) => reporter.onTestCaseResult?.(syntheticCase));
1028
+ }
1029
+ await emitToReporters(loadedReporters, (reporter) => reporter.onTestModuleEnd?.(module));
1030
+ },
1031
+ async onTaskQueued(payload) {
1032
+ const module = getOrCreateModule(payload.taskId);
1033
+ await emitToReporters(loadedReporters, (reporter) => reporter.onTestModuleQueued?.(module));
1034
+ await emitToReporters(loadedReporters, (reporter) => reporter.onTestModuleCollected?.(module));
1035
+ },
1036
+ async onTaskStart(payload) {
1037
+ const module = getOrCreateModule(payload.taskId);
1038
+ await emitToReporters(loadedReporters, (reporter) => reporter.onTestModuleStart?.(module));
1039
+ }
1040
+ };
1041
+ }
1042
+ //#endregion
1043
+ //#region src/cli/run.ts
1044
+ /**
1045
+ * Returns true when output contains at least one failing project/task/case outcome.
1046
+ */
1047
+ function hasRunFailures(output) {
1048
+ return output.projects.some((project) => {
1049
+ if (project.errorMessage != null) return true;
1050
+ if (project.caseSummary != null && project.caseSummary.failed > 0) return true;
1051
+ return (project.caseFailures?.length ?? 0) > 0;
1052
+ });
1053
+ }
1054
+ function shouldUseColor() {
1055
+ if (process.env.NO_COLOR != null) return false;
1056
+ const forceColor = process.env.FORCE_COLOR;
1057
+ if (forceColor != null) return forceColor !== "0";
1058
+ return process.stdout.isTTY === true;
1059
+ }
1060
+ function createColorPalette(enabled) {
1061
+ if (!enabled) return {
1062
+ black: (value) => value,
1063
+ bgCyan: (value) => value,
1064
+ bgGreen: (value) => value,
1065
+ bgMagenta: (value) => value,
1066
+ bgYellow: (value) => value,
1067
+ dim: (value) => value,
1068
+ gray: (value) => value,
1069
+ green: (value) => value,
1070
+ red: (value) => value,
1071
+ yellow: (value) => value
1072
+ };
1073
+ return {
1074
+ black: (value) => c.black(value),
1075
+ bgCyan: (value) => c.bgCyan(value),
1076
+ bgGreen: (value) => c.bgGreen(value),
1077
+ bgMagenta: (value) => c.bgMagenta(value),
1078
+ bgYellow: (value) => c.bgYellow(value),
1079
+ dim: (value) => c.dim(value),
1080
+ gray: (value) => c.gray(value),
1081
+ green: (value) => c.green(value),
1082
+ red: (value) => c.red(value),
1083
+ yellow: (value) => c.yellow(value)
1084
+ };
1085
+ }
1086
+ function createProjectBadge(name, colors, colorEnabled) {
1087
+ if (!colorEnabled || !c.isColorSupported) return `|${name}| `;
1088
+ const labelColorPool = [
1089
+ colors.bgYellow,
1090
+ colors.bgCyan,
1091
+ colors.bgGreen,
1092
+ colors.bgMagenta
1093
+ ];
1094
+ const background = labelColorPool[name.split("").reduce((accumulator, char, index) => accumulator + char.charCodeAt(0) + index, 0) % labelColorPool.length];
1095
+ return `${colors.black(background(` ${name} `))} `;
1096
+ }
1097
+ function formatDuration(durationMs, colors) {
1098
+ if (durationMs == null) return "";
1099
+ const rounded = Math.round(durationMs);
1100
+ return (rounded > 1e3 ? colors.yellow : colors.green)(` ${rounded}${colors.dim("ms")}`);
1101
+ }
1102
+ function filterProjectsByName(projects, names) {
1103
+ if (names.length === 0) return [...projects];
1104
+ const nameSet = new Set(names);
1105
+ return projects.filter((project) => nameSet.has(project.name));
1106
+ }
1107
+ function sanitizeIdentitySegment(value) {
1108
+ const normalized = value.trim();
1109
+ if (normalized.length === 0) return "default";
1110
+ return normalized.replace(/[^\w.-]+/g, "-");
1111
+ }
1112
+ function createRunIdentity(options) {
1113
+ const workspaceId = sanitizeIdentitySegment(options.workspace ?? "default-workspace");
1114
+ const experimentId = sanitizeIdentitySegment(options.experiment ?? "default-experiment");
1115
+ return {
1116
+ attemptId: sanitizeIdentitySegment(options.attempt ?? `attempt-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}`),
1117
+ experimentId,
1118
+ runId: `run-${Date.now()}-${randomUUID().slice(0, 8)}`,
1119
+ workspaceId
1120
+ };
1121
+ }
1122
+ function deriveReportProjectId(output) {
1123
+ const uniqueProjectNames = [...new Set(output.projects.map((project) => project.name))];
1124
+ if (uniqueProjectNames.length === 1) return sanitizeIdentitySegment(uniqueProjectNames[0] ?? "default-project");
1125
+ return "multi-project";
1126
+ }
1127
+ function createEventRecorder(identity) {
1128
+ const events = [];
1129
+ const taskProjectMap = /* @__PURE__ */ new Map();
1130
+ return {
1131
+ events,
1132
+ record(event, payload, metadata) {
1133
+ const maybeTaskPayload = payload;
1134
+ const taskId = metadata?.taskId ?? maybeTaskPayload?.taskId;
1135
+ const caseId = metadata?.caseId ?? payload?.caseId;
1136
+ const projectName = metadata?.projectName ?? maybeTaskPayload?.projectName;
1137
+ if (taskId != null && projectName != null) taskProjectMap.set(taskId, projectName);
1138
+ events.push({
1139
+ attemptId: identity.attemptId,
1140
+ caseId,
1141
+ data: payload,
1142
+ event,
1143
+ experimentId: identity.experimentId,
1144
+ projectId: taskId == null ? void 0 : taskProjectMap.get(taskId),
1145
+ runId: identity.runId,
1146
+ schemaVersion: 1,
1147
+ taskId,
1148
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1149
+ version: 1,
1150
+ workspaceId: identity.workspaceId
1151
+ });
1152
+ }
1153
+ };
1154
+ }
1155
+ function createReporterWithEventCapture(reporter, recordEvent) {
1156
+ return {
1157
+ dispose() {
1158
+ reporter.dispose();
1159
+ },
1160
+ onCaseEnd(payload) {
1161
+ recordEvent("CaseEnded", payload);
1162
+ reporter.onCaseEnd(payload);
1163
+ },
1164
+ onCaseStart(payload) {
1165
+ recordEvent("CaseStarted", payload);
1166
+ reporter.onCaseStart(payload);
1167
+ },
1168
+ onRunEnd(payload) {
1169
+ recordEvent("RunEnded", payload);
1170
+ reporter.onRunEnd(payload);
1171
+ },
1172
+ onRunStart(payload) {
1173
+ recordEvent("RunStarted", payload);
1174
+ reporter.onRunStart(payload);
1175
+ },
1176
+ onTaskEnd(payload) {
1177
+ recordEvent("TaskEnded", payload);
1178
+ reporter.onTaskEnd(payload);
1179
+ },
1180
+ onTaskQueued(payload) {
1181
+ recordEvent("TaskQueued", payload);
1182
+ reporter.onTaskQueued(payload);
1183
+ },
1184
+ onTaskStart(payload) {
1185
+ recordEvent("TaskStarted", payload);
1186
+ reporter.onTaskStart(payload);
1187
+ }
1188
+ };
1189
+ }
1190
+ function applyRunEnvironment(env) {
1191
+ const envEntries = Object.entries(env);
1192
+ if (envEntries.length === 0) return () => {};
1193
+ const snapshot = /* @__PURE__ */ new Map();
1194
+ for (const [key, value] of envEntries) {
1195
+ snapshot.set(key, {
1196
+ existed: Object.hasOwn(process.env, key),
1197
+ value: process.env[key]
1198
+ });
1199
+ if (value == null) {
1200
+ delete process.env[key];
1201
+ continue;
1202
+ }
1203
+ process.env[key] = value;
1204
+ }
1205
+ return () => {
1206
+ for (const [key, previous] of snapshot.entries()) {
1207
+ if (previous.existed) {
1208
+ if (previous.value == null) {
1209
+ delete process.env[key];
1210
+ continue;
1211
+ }
1212
+ process.env[key] = previous.value;
1213
+ continue;
1214
+ }
1215
+ delete process.env[key];
1216
+ }
1217
+ };
1218
+ }
1219
+ function isSummaryReporter(reporter) {
1220
+ return "getWindowRows" in reporter;
1221
+ }
1222
+ function createRunReporter(options) {
1223
+ const reporter = createCliReporter({
1224
+ getColumns: options?.getColumns ?? (() => process.stdout.columns ?? 80),
1225
+ getNow: options?.getNow ?? (() => Date.now()),
1226
+ getWallClockNow: options?.getWallClockNow ?? (() => Date.now()),
1227
+ isTTY: options?.isTTY ?? process.stdout.isTTY === true,
1228
+ slowThresholdMs: options?.slowThresholdMs ?? 300,
1229
+ writeError: options?.writeError ?? ((value) => process.stderr.write(value)),
1230
+ writeOutput: options?.writeOutput ?? ((value) => process.stdout.write(value))
1231
+ });
1232
+ if (!isSummaryReporter(reporter)) return {
1233
+ ...reporter,
1234
+ onCaseStart(payload) {
1235
+ reporter.onCaseStart(payload);
1236
+ },
1237
+ onTaskQueued(payload) {
1238
+ reporter.onTaskQueued(payload);
1239
+ }
1240
+ };
1241
+ const rendererBaseOptions = {
1242
+ getColumns: options?.getColumns ?? (() => process.stdout.columns ?? 80),
1243
+ getWindow: () => reporter.getWindowRows(),
1244
+ queueRenderReset: options?.queueRenderReset,
1245
+ supportsAnsiWindowing: options?.supportsAnsiWindowing,
1246
+ writeOutput: options?.writeOutput ?? ((value) => process.stdout.write(value))
1247
+ };
1248
+ const renderer = options?.clearInterval != null && options.createInterval != null ? new WindowRenderer({
1249
+ ...rendererBaseOptions,
1250
+ clearInterval: options.clearInterval,
1251
+ createInterval: options.createInterval
1252
+ }) : new WindowRenderer(rendererBaseOptions);
1253
+ renderer.start();
1254
+ function scheduleRender() {
1255
+ renderer.schedule();
1256
+ }
1257
+ return {
1258
+ dispose() {
1259
+ reporter.dispose();
1260
+ renderer.dispose();
1261
+ },
1262
+ onCaseEnd(payload) {
1263
+ reporter.onCaseEnd(payload);
1264
+ scheduleRender();
1265
+ },
1266
+ onCaseStart(payload) {
1267
+ reporter.onCaseStart(payload);
1268
+ scheduleRender();
1269
+ },
1270
+ onRunEnd(payload) {
1271
+ reporter.onRunEnd(payload);
1272
+ scheduleRender();
1273
+ },
1274
+ onRunStart(payload) {
1275
+ reporter.onRunStart(payload);
1276
+ scheduleRender();
1277
+ },
1278
+ onTaskEnd(payload) {
1279
+ reporter.onTaskEnd(payload);
1280
+ scheduleRender();
1281
+ },
1282
+ onTaskQueued(payload) {
1283
+ reporter.onTaskQueued(payload);
1284
+ scheduleRender();
1285
+ },
1286
+ onTaskStart(payload) {
1287
+ reporter.onTaskStart(payload);
1288
+ scheduleRender();
1289
+ }
1290
+ };
1291
+ }
1292
+ function createTaskQueuePayload(task, projectName) {
1293
+ return {
1294
+ displayName: task.entry.name,
1295
+ projectName,
1296
+ taskId: task.id
1297
+ };
1298
+ }
1299
+ function createTaskCaseReporterId(payload) {
1300
+ return `${payload.index}:${encodeURIComponent(payload.name)}`;
1301
+ }
1302
+ function createTaskReporterHooks(task, reporter, projectName, recordEvent, projectCaseCounters, projectCaseFailures, vitestCompatReporter) {
1303
+ function syncCaseTotal(total) {
1304
+ reporter.onTaskQueued({
1305
+ taskId: task.id,
1306
+ totalCases: total
1307
+ });
1308
+ }
1309
+ return {
1310
+ onCaseEnd(payload) {
1311
+ const caseId = createTaskCaseReporterId(payload);
1312
+ if (projectCaseCounters != null) {
1313
+ const projectCaseId = `${task.id}:${caseId}`;
1314
+ if (!projectCaseCounters.seenCaseIds.has(projectCaseId)) {
1315
+ projectCaseCounters.seenCaseIds.add(projectCaseId);
1316
+ if (payload.state === "passed") projectCaseCounters.passed += 1;
1317
+ else if (payload.state === "failed") projectCaseCounters.failed += 1;
1318
+ else projectCaseCounters.skipped += 1;
1319
+ }
1320
+ }
1321
+ syncCaseTotal(payload.total);
1322
+ if (payload.state === "failed" && payload.errorMessage != null && projectCaseFailures != null) projectCaseFailures.push({
1323
+ caseId,
1324
+ caseName: payload.name,
1325
+ errorMessage: payload.errorMessage,
1326
+ taskId: task.id
1327
+ });
1328
+ reporter.onCaseEnd({
1329
+ caseId,
1330
+ errorMessage: payload.errorMessage,
1331
+ state: payload.state,
1332
+ taskId: task.id
1333
+ });
1334
+ vitestCompatReporter?.onCaseEnd({
1335
+ caseId,
1336
+ errorMessage: payload.errorMessage,
1337
+ state: payload.state,
1338
+ taskId: task.id
1339
+ });
1340
+ },
1341
+ onCaseStart(payload) {
1342
+ const caseId = createTaskCaseReporterId(payload);
1343
+ syncCaseTotal(payload.total);
1344
+ reporter.onCaseStart({
1345
+ caseId,
1346
+ caseName: payload.name,
1347
+ taskId: task.id
1348
+ });
1349
+ vitestCompatReporter?.onCaseStart({
1350
+ caseId,
1351
+ taskId: task.id
1352
+ });
1353
+ },
1354
+ onEvent(payload) {
1355
+ recordEvent(payload.event, payload.data, {
1356
+ caseId: payload.caseId,
1357
+ projectName,
1358
+ taskId: task.id
1359
+ });
1360
+ }
1361
+ };
1362
+ }
1363
+ function createCliTaskExecutionContext(task, models, cacheRootDirectory, cacheProjectName, workspaceId, reporter, projectName, recordEvent, projectCaseCounters, projectCaseFailures, vitestCompatReporter) {
1364
+ return {
1365
+ ...createTaskExecutionContext({
1366
+ cache: createFilesystemTaskCacheRuntime({
1367
+ cacheRootDirectory,
1368
+ projectName: cacheProjectName,
1369
+ workspaceId
1370
+ }),
1371
+ models,
1372
+ task
1373
+ }),
1374
+ reporterHooks: createTaskReporterHooks(task, reporter, projectName, recordEvent, projectCaseCounters, projectCaseFailures, vitestCompatReporter)
1375
+ };
1376
+ }
1377
+ function resolveTaskReporterHooks(task, context, reporter, projectName, recordEvent, projectCaseCounters, projectCaseFailures, vitestCompatReporter) {
1378
+ return context.reporterHooks ?? createTaskReporterHooks(task, reporter, projectName, recordEvent, projectCaseCounters, projectCaseFailures, vitestCompatReporter);
1379
+ }
1380
+ function getFailedTaskId(error) {
1381
+ if (error instanceof RunnerExecutionError) return error.taskId;
1382
+ return null;
1383
+ }
1384
+ function createAutoTaskExecutor(reporter, projectName, recordEvent, projectCaseCounters, projectCaseFailures, vitestCompatReporter) {
1385
+ return async (task, context) => {
1386
+ const taskDefinition = task.entry.task;
1387
+ if (taskDefinition == null) throw new Error(`Missing eval task definition for entry "${task.entry.id}".`);
1388
+ const output = await taskDefinition.run({
1389
+ cache: context.cache,
1390
+ model: context.model,
1391
+ reporterHooks: resolveTaskReporterHooks(task, context, reporter, projectName, recordEvent, projectCaseCounters, projectCaseFailures, vitestCompatReporter),
1392
+ task
1393
+ });
1394
+ return {
1395
+ entryId: task.entry.id,
1396
+ id: task.id,
1397
+ matrix: task.matrix,
1398
+ inferenceExecutorId: task.inferenceExecutor.id,
1399
+ scores: [...output.scores]
1400
+ };
1401
+ };
1402
+ }
1403
+ function cloneScheduledTaskMatrix(task) {
1404
+ return {
1405
+ eval: { ...task.matrix.eval },
1406
+ meta: { ...task.matrix.meta },
1407
+ run: { ...task.matrix.run }
1408
+ };
1409
+ }
1410
+ function createProjectMatrixSummary(tasks) {
1411
+ if (tasks.length === 0) return null;
1412
+ const runAxes = /* @__PURE__ */ new Set();
1413
+ const evalAxes = /* @__PURE__ */ new Set();
1414
+ const runRows = /* @__PURE__ */ new Set();
1415
+ const evalRows = /* @__PURE__ */ new Set();
1416
+ for (const task of tasks) {
1417
+ Object.keys(task.matrix.run).forEach((axis) => runAxes.add(axis));
1418
+ Object.keys(task.matrix.eval).forEach((axis) => evalAxes.add(axis));
1419
+ runRows.add(task.matrix.meta.runRowId);
1420
+ evalRows.add(task.matrix.meta.evalRowId);
1421
+ }
1422
+ return {
1423
+ evalAxes: [...evalAxes].sort(),
1424
+ evalRows: evalRows.size,
1425
+ runAxes: [...runAxes].sort(),
1426
+ runRows: runRows.size
1427
+ };
1428
+ }
1429
+ async function prepareProject(project) {
1430
+ const startedAt = Date.now();
1431
+ try {
1432
+ const runtimeContext = await createRunnerRuntimeContext({
1433
+ cwd: project.root,
1434
+ fallbackProjectRootDirectory: project.root
1435
+ });
1436
+ const evalFilePaths = await discoverEvalFiles({
1437
+ exclude: project.exclude,
1438
+ include: project.include,
1439
+ root: project.root
1440
+ });
1441
+ const entries = collectEvalEntries(await loadEvalModulesWithVitestRuntime(evalFilePaths, project.root), runtimeContext);
1442
+ const tasks = createRunnerSchedule({
1443
+ evalMatrix: project.evalMatrix,
1444
+ entries,
1445
+ inferenceExecutors: project.inferenceExecutors,
1446
+ runMatrix: project.runMatrix
1447
+ });
1448
+ const canAutoExecuteEntryTasks = entries.some((entry) => entry.task != null) && project.models.length > 0;
1449
+ if (project.executor == null && !canAutoExecuteEntryTasks) return {
1450
+ kind: "summary",
1451
+ summary: {
1452
+ caseSummary: null,
1453
+ caseFailures: [],
1454
+ discoveredEvalFileCount: evalFilePaths.length,
1455
+ durationMs: Date.now() - startedAt,
1456
+ entryCount: entries.length,
1457
+ errorMessage: null,
1458
+ executed: false,
1459
+ matrixSummary: createProjectMatrixSummary(tasks),
1460
+ name: project.name,
1461
+ result: null,
1462
+ taskCount: tasks.length
1463
+ }
1464
+ };
1465
+ return {
1466
+ kind: "prepared",
1467
+ prepared: {
1468
+ discoveredEvalFileCount: evalFilePaths.length,
1469
+ entryCount: entries.length,
1470
+ name: project.name,
1471
+ project,
1472
+ startedAt,
1473
+ tasks
1474
+ }
1475
+ };
1476
+ } catch (error) {
1477
+ return {
1478
+ kind: "summary",
1479
+ summary: {
1480
+ caseSummary: null,
1481
+ caseFailures: [],
1482
+ discoveredEvalFileCount: 0,
1483
+ durationMs: Date.now() - startedAt,
1484
+ entryCount: 0,
1485
+ errorMessage: errorMessageFrom(error) ?? "Unknown project execution error.",
1486
+ executed: false,
1487
+ matrixSummary: null,
1488
+ name: project.name,
1489
+ result: null,
1490
+ taskCount: 0
1491
+ }
1492
+ };
1493
+ }
1494
+ }
1495
+ async function executePreparedProject(prepared, identity, cacheProjectName, reporter, counters, recordEvent) {
1496
+ const settledTaskIds = /* @__PURE__ */ new Set();
1497
+ const projectCaseCounters = {
1498
+ failed: 0,
1499
+ passed: 0,
1500
+ seenCaseIds: /* @__PURE__ */ new Set(),
1501
+ skipped: 0
1502
+ };
1503
+ const projectCaseFailures = [];
1504
+ const vitestCompatReporter = await createVievalVitestCompatReporterBridge({
1505
+ projectName: prepared.name,
1506
+ references: prepared.project.reporters
1507
+ });
1508
+ const rawTaskExecutor = prepared.project.executor ?? createAutoTaskExecutor(reporter, prepared.name, recordEvent, projectCaseCounters, projectCaseFailures, vitestCompatReporter);
1509
+ const taskExecutor = async (task, context) => {
1510
+ return {
1511
+ ...await rawTaskExecutor(task, context),
1512
+ matrix: cloneScheduledTaskMatrix(task)
1513
+ };
1514
+ };
1515
+ for (const task of prepared.tasks) await vitestCompatReporter?.onTaskQueued({ taskId: task.id });
1516
+ await vitestCompatReporter?.onRunStart();
1517
+ try {
1518
+ const aggregated = await runScheduledTasks(prepared.tasks, taskExecutor, {
1519
+ createExecutionContext(task) {
1520
+ return createCliTaskExecutionContext(task, prepared.project.models, resolve(prepared.project.root, ".vieval", "cache"), cacheProjectName ?? prepared.name, identity.workspaceId, reporter, prepared.name, recordEvent, projectCaseCounters, projectCaseFailures, vitestCompatReporter);
1521
+ },
1522
+ onTaskEnd(task, state) {
1523
+ settledTaskIds.add(task.id);
1524
+ reporter.onTaskEnd({
1525
+ state,
1526
+ taskId: task.id
1527
+ });
1528
+ vitestCompatReporter?.onTaskEnd({
1529
+ state,
1530
+ taskId: task.id
1531
+ });
1532
+ if (state === "passed") {
1533
+ counters.passedTasks += 1;
1534
+ return;
1535
+ }
1536
+ counters.failedTasks += 1;
1537
+ },
1538
+ onTaskStart(task) {
1539
+ reporter.onTaskStart({ taskId: task.id });
1540
+ vitestCompatReporter?.onTaskStart({ taskId: task.id });
1541
+ }
1542
+ });
1543
+ await vitestCompatReporter?.onRunEnd({ failed: false });
1544
+ return {
1545
+ caseSummary: {
1546
+ failed: projectCaseCounters.failed,
1547
+ passed: projectCaseCounters.passed,
1548
+ skipped: projectCaseCounters.skipped,
1549
+ total: projectCaseCounters.seenCaseIds.size
1550
+ },
1551
+ caseFailures: projectCaseFailures,
1552
+ discoveredEvalFileCount: prepared.discoveredEvalFileCount,
1553
+ durationMs: Date.now() - prepared.startedAt,
1554
+ entryCount: prepared.entryCount,
1555
+ errorMessage: null,
1556
+ executed: true,
1557
+ matrixSummary: createProjectMatrixSummary(prepared.tasks),
1558
+ name: prepared.name,
1559
+ result: aggregated,
1560
+ taskCount: prepared.tasks.length
1561
+ };
1562
+ } catch (error) {
1563
+ const failedTaskId = getFailedTaskId(error);
1564
+ if (failedTaskId != null && !settledTaskIds.has(failedTaskId)) {
1565
+ counters.failedTasks += 1;
1566
+ settledTaskIds.add(failedTaskId);
1567
+ reporter.onTaskEnd({
1568
+ state: "failed",
1569
+ taskId: failedTaskId
1570
+ });
1571
+ await vitestCompatReporter?.onTaskEnd({
1572
+ state: "failed",
1573
+ taskId: failedTaskId
1574
+ });
1575
+ }
1576
+ for (const task of prepared.tasks) {
1577
+ if (settledTaskIds.has(task.id)) continue;
1578
+ counters.skippedTasks += 1;
1579
+ settledTaskIds.add(task.id);
1580
+ reporter.onTaskEnd({
1581
+ state: "skipped",
1582
+ taskId: task.id
1583
+ });
1584
+ await vitestCompatReporter?.onTaskEnd({
1585
+ state: "skipped",
1586
+ taskId: task.id
1587
+ });
1588
+ }
1589
+ await vitestCompatReporter?.onRunEnd({ failed: true });
1590
+ return {
1591
+ caseSummary: {
1592
+ failed: projectCaseCounters.failed,
1593
+ passed: projectCaseCounters.passed,
1594
+ skipped: projectCaseCounters.skipped,
1595
+ total: projectCaseCounters.seenCaseIds.size
1596
+ },
1597
+ caseFailures: projectCaseFailures,
1598
+ discoveredEvalFileCount: prepared.discoveredEvalFileCount,
1599
+ durationMs: Date.now() - prepared.startedAt,
1600
+ entryCount: prepared.entryCount,
1601
+ errorMessage: errorMessageFrom(error) ?? "Unknown project execution error.",
1602
+ executed: false,
1603
+ matrixSummary: createProjectMatrixSummary(prepared.tasks),
1604
+ name: prepared.name,
1605
+ result: null,
1606
+ taskCount: prepared.tasks.length
1607
+ };
1608
+ }
1609
+ }
1610
+ async function writeRunReportArtifacts(output, events, identity, reportOut) {
1611
+ const projectId = deriveReportProjectId(output);
1612
+ const reportDirectory = resolve(reportOut, identity.workspaceId, projectId, identity.experimentId, identity.attemptId, identity.runId);
1613
+ await mkdir(reportDirectory, { recursive: true });
1614
+ await writeFile(resolve(reportDirectory, "run-summary.json"), `${JSON.stringify(output, null, 2)}\n`, "utf-8");
1615
+ await writeFile(resolve(reportDirectory, "events.jsonl"), events.map((event) => JSON.stringify(event)).join("\n").concat(events.length > 0 ? "\n" : ""), "utf-8");
1616
+ return reportDirectory;
1617
+ }
1618
+ /**
1619
+ * Runs vieval orchestration from config and returns project-level summaries.
1620
+ *
1621
+ * Call stack:
1622
+ *
1623
+ * {@link runVievalCli}
1624
+ * -> {@link loadVievalCliConfig}
1625
+ * -> {@link discoverEvalFiles}
1626
+ * -> {@link collectEvalEntries}
1627
+ * -> {@link createRunnerSchedule}
1628
+ * -> {@link runScheduledTasks} (optional)
1629
+ *
1630
+ * Use when:
1631
+ * - running eval collection and scheduling from a single command
1632
+ * - keeping business-agent eval files near their implementation packages
1633
+ */
1634
+ async function runVievalCli(options = {}) {
1635
+ const identity = createRunIdentity(options);
1636
+ const loadedConfig = await loadVievalCliConfig({
1637
+ configFilePath: options.configFilePath,
1638
+ cwd: options.cwd
1639
+ });
1640
+ const restoreEnvironment = applyRunEnvironment(loadedConfig.env);
1641
+ const eventRecorder = createEventRecorder(identity);
1642
+ const reporter = createReporterWithEventCapture(createRunReporter(options.reporter), eventRecorder.record);
1643
+ try {
1644
+ const selectedProjects = filterProjectsByName(loadedConfig.projects, options.project ?? []);
1645
+ const preparedProjects = await Promise.all(selectedProjects.map(async (project) => prepareProject(project)));
1646
+ const executableProjects = preparedProjects.filter((project) => project.kind === "prepared").map((project) => project.prepared);
1647
+ const totalTasks = preparedProjects.reduce((sum, project) => {
1648
+ if (project.kind === "prepared") return sum + project.prepared.tasks.length;
1649
+ return sum + project.summary.taskCount;
1650
+ }, 0);
1651
+ const skippedSummaryTasks = preparedProjects.reduce((sum, project) => {
1652
+ if (project.kind === "summary") return sum + project.summary.taskCount;
1653
+ return sum;
1654
+ }, 0);
1655
+ const reporterCounters = {
1656
+ failedTasks: 0,
1657
+ passedTasks: 0,
1658
+ skippedTasks: 0
1659
+ };
1660
+ reporter.onRunStart({ totalTasks });
1661
+ for (const project of executableProjects) for (const task of project.tasks) reporter.onTaskQueued(createTaskQueuePayload(task, project.name));
1662
+ const projectSummaries = [];
1663
+ for (const preparedProject of preparedProjects) {
1664
+ if (preparedProject.kind === "summary") {
1665
+ projectSummaries.push(preparedProject.summary);
1666
+ continue;
1667
+ }
1668
+ projectSummaries.push(await executePreparedProject(preparedProject.prepared, identity, options.cacheProjectName, reporter, reporterCounters, eventRecorder.record));
1669
+ }
1670
+ reporter.onRunEnd({
1671
+ failedTasks: reporterCounters.failedTasks,
1672
+ passedTasks: reporterCounters.passedTasks,
1673
+ skippedTasks: reporterCounters.skippedTasks + skippedSummaryTasks,
1674
+ totalTasks
1675
+ });
1676
+ const output = {
1677
+ attemptId: identity.attemptId,
1678
+ configFilePath: loadedConfig.configFilePath,
1679
+ experimentId: identity.experimentId,
1680
+ projects: projectSummaries,
1681
+ reportDirectory: null,
1682
+ runId: identity.runId,
1683
+ workspaceId: identity.workspaceId
1684
+ };
1685
+ if (options.reportOut != null) output.reportDirectory = await writeRunReportArtifacts(output, eventRecorder.events, identity, options.reportOut);
1686
+ return output;
1687
+ } finally {
1688
+ reporter.dispose();
1689
+ restoreEnvironment();
1690
+ }
1691
+ }
1692
+ /**
1693
+ * Formats CLI run output as human-readable lines.
1694
+ */
1695
+ function formatVievalCliRunOutput(output) {
1696
+ const colorEnabled = shouldUseColor();
1697
+ const colors = createColorPalette(colorEnabled);
1698
+ const lines = [];
1699
+ lines.push(` ${colors.dim("RUN")} ${colors.yellow("vieval")}`);
1700
+ lines.push(` ${colors.dim("Config")} ${output.configFilePath ?? "(not found, using defaults)"}`);
1701
+ lines.push("");
1702
+ let passedProjects = 0;
1703
+ let skippedProjects = 0;
1704
+ let failedProjects = 0;
1705
+ let totalTasks = 0;
1706
+ let executedTasks = 0;
1707
+ function formatMatrixSummary(summary) {
1708
+ if (summary == null) return null;
1709
+ const runAxesLabel = summary.runAxes.length === 0 ? "-" : summary.runAxes.join("|");
1710
+ const evalAxesLabel = summary.evalAxes.length === 0 ? "-" : summary.evalAxes.join("|");
1711
+ return `matrix run ${summary.runRows} [${runAxesLabel}] / eval ${summary.evalRows} [${evalAxesLabel}]`;
1712
+ }
1713
+ function formatScheduleBreakdown(project) {
1714
+ const summary = project.matrixSummary;
1715
+ if (summary == null) return null;
1716
+ if (project.taskCount <= 0 || project.entryCount <= 0 || summary.runRows <= 0 || summary.evalRows <= 0) return null;
1717
+ const denominator = project.entryCount * summary.runRows * summary.evalRows;
1718
+ if (denominator <= 0 || project.taskCount % denominator !== 0) return null;
1719
+ const providerCount = project.taskCount / denominator;
1720
+ return [
1721
+ colors.dim("schedule "),
1722
+ colors.yellow(String(project.entryCount)),
1723
+ colors.dim(" entries × "),
1724
+ colors.yellow(String(providerCount)),
1725
+ colors.dim(" inferenceExecutors × "),
1726
+ colors.yellow(String(summary.runRows)),
1727
+ colors.dim(" run rows × "),
1728
+ colors.yellow(String(summary.evalRows)),
1729
+ colors.dim(" eval rows = "),
1730
+ colors.green(String(project.taskCount)),
1731
+ colors.dim(" tasks")
1732
+ ].join("");
1733
+ }
1734
+ for (const project of output.projects) {
1735
+ totalTasks += project.taskCount;
1736
+ executedTasks += project.result?.overall.runCount ?? 0;
1737
+ const badge = createProjectBadge(project.name, colors, colorEnabled);
1738
+ const isFailed = project.errorMessage != null;
1739
+ const hasFailedCases = (project.caseSummary?.failed ?? 0) > 0 || (project.caseFailures?.length ?? 0) > 0;
1740
+ if (isFailed) {
1741
+ failedProjects += 1;
1742
+ lines.push(` ${colors.red("❯")} ${badge}${formatDuration(project.durationMs, colors)}`);
1743
+ lines.push(` ${project.errorMessage}`);
1744
+ continue;
1745
+ }
1746
+ if (!project.executed) {
1747
+ skippedProjects += 1;
1748
+ const countLabel = colors.dim(`(${project.taskCount} tasks)`);
1749
+ const detailsLabel = colors.dim(` ${project.discoveredEvalFileCount} files, ${project.entryCount} entries, 0 runs, hybrid n/a`);
1750
+ const matrixSummary = formatMatrixSummary(project.matrixSummary);
1751
+ lines.push(` ${colors.dim("○")} ${badge}${countLabel}${detailsLabel}${formatDuration(project.durationMs, colors)}`);
1752
+ if (matrixSummary != null) lines.push(` ${colors.dim(matrixSummary)}`);
1753
+ const scheduleBreakdown = formatScheduleBreakdown(project);
1754
+ if (scheduleBreakdown != null) lines.push(` ${scheduleBreakdown}`);
1755
+ continue;
1756
+ }
1757
+ if (hasFailedCases) failedProjects += 1;
1758
+ else passedProjects += 1;
1759
+ const hybridAverage = project.result?.overall.hybridAverage;
1760
+ const hybridAverageLabel = hybridAverage == null ? "n/a" : String(hybridAverage);
1761
+ const runCount = project.result?.overall.runCount ?? 0;
1762
+ const countLabel = colors.dim(`(${project.taskCount} tasks)`);
1763
+ const caseSummaryLabel = project.caseSummary == null ? "" : `, cases ${project.caseSummary.passed} passed | ${project.caseSummary.failed} failed`;
1764
+ const detailsLabel = colors.dim(` ${project.discoveredEvalFileCount} files, ${project.entryCount} entries, ${runCount} runs${caseSummaryLabel}, hybrid ${hybridAverageLabel}`);
1765
+ const matrixSummary = formatMatrixSummary(project.matrixSummary);
1766
+ lines.push(` ${hasFailedCases ? colors.red("❯") : colors.green("✓")} ${badge}${countLabel}${detailsLabel}${formatDuration(project.durationMs, colors)}`);
1767
+ if (matrixSummary != null) lines.push(` ${colors.dim(matrixSummary)}`);
1768
+ const scheduleBreakdown = formatScheduleBreakdown(project);
1769
+ if (scheduleBreakdown != null) lines.push(` ${scheduleBreakdown}`);
1770
+ if ((project.caseFailures?.length ?? 0) > 0) {
1771
+ lines.push(` ${colors.red("Failed cases:")}`);
1772
+ for (const failure of project.caseFailures.slice(0, 5)) {
1773
+ lines.push(` ${colors.red(`- ${failure.caseName} (${failure.taskId})`)}`);
1774
+ for (const line of failure.errorMessage.split("\n")) lines.push(` ${colors.red(line)}`);
1775
+ }
1776
+ if (project.caseFailures.length > 5) lines.push(` ${colors.dim(`... ${project.caseFailures.length - 5} more failed cases`)}`);
1777
+ }
1778
+ }
1779
+ lines.push("");
1780
+ if (failedProjects > 0 || skippedProjects > 0) {
1781
+ const summarySegments = [`${colors.green(String(passedProjects))} passed`];
1782
+ if (skippedProjects > 0) summarySegments.push(`${colors.dim(String(skippedProjects))} skipped`);
1783
+ if (failedProjects > 0) summarySegments.push(`${colors.red(String(failedProjects))} failed`);
1784
+ lines.push(` ${colors.dim("Projects")} ${summarySegments.join(" | ")} (${output.projects.length})`);
1785
+ } else lines.push(` ${colors.dim("Projects")} ${colors.green(String(passedProjects))} passed (${output.projects.length})`);
1786
+ lines.push(` ${colors.dim("Tasks")} ${executedTasks} executed / ${totalTasks} scheduled`);
1787
+ return lines.join("\n");
1788
+ }
1789
+ //#endregion
1790
+ //#region src/cli/compare.ts
1791
+ const compareHelpText = `
1792
+ Compare multiple methods on one benchmark.
1793
+
1794
+ Usage
1795
+ $ vieval compare [--config <path>] [--comparison <id>] [--output <path>] [--format <format>]
1796
+
1797
+ Options
1798
+ --config Config file path (default: nearest vieval.config.*)
1799
+ --comparison Comparison entry id from config.comparisons
1800
+ --output Optional output artifact path
1801
+ --format Console output format: table | json (default: table)
1802
+ `;
1803
+ function normalizeCliArgv$4(argv) {
1804
+ const normalizedArgv = argv[0] === "--" ? argv.slice(1) : [...argv];
1805
+ if (normalizedArgv[0] === "compare") return normalizedArgv.slice(1);
1806
+ return normalizedArgv;
1807
+ }
1808
+ function parseCompareCliArguments(argv) {
1809
+ const cli = meow(compareHelpText, {
1810
+ argv: normalizeCliArgv$4(argv),
1811
+ flags: {
1812
+ config: { type: "string" },
1813
+ comparison: { type: "string" },
1814
+ format: {
1815
+ default: "table",
1816
+ type: "string"
1817
+ },
1818
+ output: { type: "string" }
1819
+ },
1820
+ importMeta: import.meta
1821
+ });
1822
+ return {
1823
+ comparisonId: cli.flags.comparison,
1824
+ configFilePath: cli.flags.config,
1825
+ format: cli.flags.format === "json" ? "json" : "table",
1826
+ output: cli.flags.output
1827
+ };
1828
+ }
1829
+ /**
1830
+ * Runs one compare session from `vieval.config.*` comparison-mode config.
1831
+ */
1832
+ async function runCompareCli(argv) {
1833
+ const parsed = parseCompareCliArguments(argv);
1834
+ const loaded = await loadVievalComparisonConfig({
1835
+ comparisonId: parsed.comparisonId,
1836
+ configFilePath: parsed.configFilePath,
1837
+ cwd: parsed.cwd
1838
+ });
1839
+ const methodResults = [];
1840
+ for (const method of loaded.config.methods) {
1841
+ const methodWorkspace = resolve(method.workspace);
1842
+ const output = await runVievalCli({
1843
+ cacheProjectName: loaded.config.benchmark.sharedCaseNamespace,
1844
+ configFilePath: method.configFilePath ?? resolve(methodWorkspace, "vieval.config.ts"),
1845
+ cwd: methodWorkspace,
1846
+ project: [method.project],
1847
+ workspace: loaded.config.benchmark.id
1848
+ });
1849
+ const failedProject = output.projects.find((project) => project.errorMessage != null);
1850
+ if (failedProject != null) throw new Error(`Comparison method "${method.id}" failed: ${failedProject.errorMessage}`);
1851
+ methodResults.push({
1852
+ methodId: method.id,
1853
+ output
1854
+ });
1855
+ }
1856
+ const runOutput = {
1857
+ benchmarkId: loaded.config.benchmark.id,
1858
+ methods: methodResults
1859
+ };
1860
+ const artifact = buildCompareReportArtifact({
1861
+ benchmarkId: runOutput.benchmarkId,
1862
+ methods: runOutput.methods,
1863
+ reportPath: loaded.configFilePath
1864
+ });
1865
+ if (parsed.output != null) await writeCompareReportArtifact({
1866
+ artifact,
1867
+ outputPath: parsed.output
1868
+ });
1869
+ if (parsed.format === "json") process.stdout.write(`${JSON.stringify(artifact, null, 2)}\n`);
1870
+ else process.stdout.write([
1871
+ "COMPARE vieval",
1872
+ `Benchmark ${artifact.benchmarkId}`,
1873
+ ...artifact.methods.map((method, index) => {
1874
+ const hybrid = method.hybridAverage == null ? "n/a" : method.hybridAverage.toFixed(3);
1875
+ const exact = method.exactAverage == null ? "n/a" : method.exactAverage.toFixed(3);
1876
+ return `${index + 1}. ${method.methodId} hybrid=${hybrid} exact=${exact} runs=${method.runCount}`;
1877
+ })
1878
+ ].join("\n").concat("\n"));
1879
+ return runOutput;
1880
+ }
1881
+ async function runCompareCliOrExit(argv) {
1882
+ try {
1883
+ await runCompareCli(argv);
1884
+ } catch (error) {
1885
+ const errorMessage = errorMessageFrom(error) ?? "Unknown compare command failure.";
1886
+ process.stderr.write(`[vieval compare] ${errorMessage}\n`);
1887
+ process.exitCode = 1;
1888
+ }
1889
+ }
1890
+ //#endregion
1891
+ //#region package.json
1892
+ var name = "vieval";
1893
+ //#endregion
1894
+ //#region src/cli/eval-run.ts
1895
+ const evalRunHelpText = `
1896
+ Execute vieval projects from discovered or explicit config.
1897
+
1898
+ Usage
1899
+ $ vieval run [--config <path>] [--project <name>] [--json] [--report-out <path>]
1900
+
1901
+ Options
1902
+ --config Config file path
1903
+ --project Project name to execute; may be repeated
1904
+ --workspace Workspace id used in report artifacts
1905
+ --experiment Experiment id used in report artifacts
1906
+ --attempt Attempt id used in report artifacts
1907
+ --report-out Report output root directory
1908
+ --json Print machine-readable JSON output
1909
+ `;
1910
+ function normalizeCliArgv$3(argv) {
1911
+ const normalizedArgv = argv[0] === "--" ? argv.slice(1) : [...argv];
1912
+ return normalizedArgv[0] === "run" ? normalizedArgv.slice(1) : normalizedArgv;
1913
+ }
1914
+ function normalizeProjectNames(projectNames) {
1915
+ if (typeof projectNames === "string") return [projectNames];
1916
+ return projectNames ?? [];
1917
+ }
1918
+ /**
1919
+ * Parses `vieval run` CLI arguments into one normalized execution payload.
1920
+ *
1921
+ * Use when:
1922
+ * - the top-level CLI forwards `run` subcommand arguments
1923
+ * - tests need stable flag normalization without executing the runner
1924
+ *
1925
+ * Expects:
1926
+ * - argv in either direct `run` form or forwarded `-- ...` form
1927
+ *
1928
+ * Returns:
1929
+ * - normalized run options ready for {@link runVievalCli}
1930
+ */
1931
+ function parseCliArguments(argv) {
1932
+ const cli = meow(evalRunHelpText, {
1933
+ argv: normalizeCliArgv$3(argv),
1934
+ importMeta: import.meta,
1935
+ flags: {
1936
+ config: { type: "string" },
1937
+ json: {
1938
+ default: false,
1939
+ type: "boolean"
1940
+ },
1941
+ project: {
1942
+ isMultiple: true,
1943
+ type: "string"
1944
+ },
1945
+ workspace: { type: "string" },
1946
+ experiment: { type: "string" },
1947
+ attempt: { type: "string" },
1948
+ reportOut: { type: "string" }
1949
+ }
1950
+ });
1951
+ return {
1952
+ attempt: cli.flags.attempt,
1953
+ configFilePath: cli.flags.config,
1954
+ experiment: cli.flags.experiment,
1955
+ json: cli.flags.json === true,
1956
+ project: normalizeProjectNames(cli.flags.project),
1957
+ reportOut: cli.flags.reportOut,
1958
+ workspace: cli.flags.workspace
1959
+ };
1960
+ }
1961
+ /**
1962
+ * Executes the `vieval run` subcommand.
1963
+ *
1964
+ * Call stack:
1965
+ *
1966
+ * top-level `vieval` CLI
1967
+ * -> {@link runTopLevelCli} (`./index`)
1968
+ * -> {@link runEvalRunCli}
1969
+ * -> {@link parseCliArguments}
1970
+ * -> {@link runVievalCli}
1971
+ * -> `process.stdout.write(...)` / `process.stderr.write(...)`
1972
+ * -> `process.exitCode`
1973
+ *
1974
+ * Use when:
1975
+ * - the published `vieval` binary needs to execute the `run` subcommand
1976
+ * - callers want one reusable implementation without a second bundled entrypoint
1977
+ *
1978
+ * Expects:
1979
+ * - argv that belongs to the `run` subcommand only
1980
+ *
1981
+ * Returns:
1982
+ * - resolves after writing CLI output and updating `process.exitCode`
1983
+ *
1984
+ * NOTICE:
1985
+ * - `src/cli/index.ts` is the only direct-execution entrypoint for the bundled
1986
+ * CLI artifact. Keeping `eval-run.ts` reusable avoids duplicate top-level
1987
+ * await guards once tsdown inlines both modules into `dist/cli/index.mjs`.
1988
+ */
1989
+ async function runEvalRunCli(argv) {
1990
+ const parsed = parseCliArguments(argv);
1991
+ try {
1992
+ const output = await runVievalCli({
1993
+ attempt: parsed.attempt,
1994
+ configFilePath: parsed.configFilePath,
1995
+ experiment: parsed.experiment,
1996
+ project: parsed.project,
1997
+ reportOut: parsed.reportOut,
1998
+ workspace: parsed.workspace
1999
+ });
2000
+ if (parsed.json) {
2001
+ process.stdout.write(`${JSON.stringify(output, null, 2)}\n`);
2002
+ if (hasRunFailures(output)) process.exitCode = 1;
2003
+ return;
2004
+ }
2005
+ process.stdout.write(`${formatVievalCliRunOutput(output)}\n`);
2006
+ if (hasRunFailures(output)) process.exitCode = 1;
2007
+ } catch (error) {
2008
+ const errorMessage = errorMessageFrom(error) ?? "Unknown CLI failure.";
2009
+ process.stderr.write(`[${name}] ${errorMessage}\n`);
2010
+ process.exitCode = 1;
2011
+ }
2012
+ }
2013
+ //#endregion
2014
+ //#region src/cli/report-artifacts.ts
2015
+ /**
2016
+ * Resolves one or more `run-summary.json` paths from a report location.
2017
+ *
2018
+ * Use when:
2019
+ * - callers may pass a run directory, summary file path, or a report root
2020
+ *
2021
+ * Returns:
2022
+ * - sorted absolute summary file paths
2023
+ */
2024
+ async function resolveRunSummaryPaths(reportPath) {
2025
+ const absoluteReportPath = resolve(reportPath);
2026
+ const directSummaryPath = resolve(absoluteReportPath, "run-summary.json");
2027
+ if (existsSync(absoluteReportPath) && absoluteReportPath.endsWith(".json")) return [absoluteReportPath];
2028
+ if (existsSync(directSummaryPath)) return [directSummaryPath];
2029
+ return (await glob("**/run-summary.json", {
2030
+ absolute: true,
2031
+ cwd: absoluteReportPath
2032
+ })).sort((left, right) => left.localeCompare(right));
2033
+ }
2034
+ /**
2035
+ * Reads one run report artifact set from `run-summary.json` and sibling `events.jsonl`.
2036
+ *
2037
+ * Use when:
2038
+ * - report analysis needs both run aggregate output and event count metadata
2039
+ */
2040
+ function readReportRunArtifact(summaryFilePath) {
2041
+ const reportDirectory = resolve(summaryFilePath, "..");
2042
+ const summary = JSON.parse(readFileSync(summaryFilePath, "utf-8"));
2043
+ const eventsFilePath = resolve(reportDirectory, "events.jsonl");
2044
+ const events = existsSync(eventsFilePath) ? readFileSync(eventsFilePath, "utf-8").split("\n").filter((line) => line.trim().length > 0).map((line) => {
2045
+ const event = JSON.parse(line);
2046
+ return {
2047
+ caseId: event.caseId,
2048
+ data: event.data,
2049
+ event: event.event,
2050
+ taskId: event.taskId
2051
+ };
2052
+ }) : [];
2053
+ return {
2054
+ events,
2055
+ eventsCount: events.length,
2056
+ reportDirectory,
2057
+ summary,
2058
+ summaryFilePath
2059
+ };
2060
+ }
2061
+ /**
2062
+ * Reads all run artifacts found under `reportPath`.
2063
+ *
2064
+ * Use when:
2065
+ * - callers need multi-run analysis from a directory root
2066
+ */
2067
+ async function readReportArtifacts(reportPath) {
2068
+ return (await resolveRunSummaryPaths(reportPath)).map((summaryFilePath) => readReportRunArtifact(summaryFilePath));
2069
+ }
2070
+ /**
2071
+ * Creates a compact summary row for one run artifact.
2072
+ *
2073
+ * Use when:
2074
+ * - table/csv/jsonl exports should stay stable and cheap to parse
2075
+ */
2076
+ function summarizeReportRunArtifact(artifact) {
2077
+ const totalProjects = artifact.summary.projects.length;
2078
+ const failedProjects = artifact.summary.projects.filter((project) => project.errorMessage != null).length;
2079
+ const executedProjects = artifact.summary.projects.filter((project) => project.executed).length;
2080
+ const totalTasks = artifact.summary.projects.reduce((sum, project) => sum + project.taskCount, 0);
2081
+ const projectNames = artifact.summary.projects.map((project) => project.name);
2082
+ return {
2083
+ attemptId: artifact.summary.attemptId ?? null,
2084
+ eventsCount: artifact.eventsCount,
2085
+ executedProjects,
2086
+ experimentId: artifact.summary.experimentId ?? null,
2087
+ failedProjects,
2088
+ projectNames,
2089
+ reportDirectory: artifact.reportDirectory,
2090
+ runId: artifact.summary.runId ?? null,
2091
+ totalProjects,
2092
+ totalTasks,
2093
+ workspaceId: artifact.summary.workspaceId ?? null
2094
+ };
2095
+ }
2096
+ //#endregion
2097
+ //#region src/cli/report-analyze.ts
2098
+ const reportAnalyzeHelpText = `
2099
+ Analyze generated vieval report artifacts.
2100
+
2101
+ Usage
2102
+ $ vieval report analyze <reportPath> [options]
2103
+
2104
+ Options
2105
+ --format Output format: table | json | jsonl | csv (default: table)
2106
+ --workspace Workspace id filter
2107
+ --project Project name filter (exact)
2108
+ --experiment Experiment id filter
2109
+ --attempt Attempt id filter
2110
+ --run Run id filter
2111
+ --task-state Keep runs containing at least one task in this state
2112
+ --case-state Keep runs containing at least one case in this state
2113
+ --contains Keep runs containing this text in event name or payload
2114
+ --error-contains Keep runs containing this text in project errors or event payload
2115
+ --run-matrix Keep runs matching run-matrix selector "key=value[,key=value]"
2116
+ --eval-matrix Keep runs matching eval-matrix selector "key=value[,key=value]"
2117
+ `;
2118
+ function normalizeCliArgv$2(argv) {
2119
+ const normalizedArgv = argv[0] === "--" ? argv.slice(1) : [...argv];
2120
+ if (normalizedArgv[0] === "report" && normalizedArgv[1] === "analyze") return normalizedArgv.slice(2);
2121
+ if (normalizedArgv[0] === "analyze") return normalizedArgv.slice(1);
2122
+ return normalizedArgv;
2123
+ }
2124
+ function parseReportAnalyzeCliArguments(argv) {
2125
+ const cli = meow(reportAnalyzeHelpText, {
2126
+ argv: normalizeCliArgv$2(argv),
2127
+ flags: {
2128
+ attempt: { type: "string" },
2129
+ caseState: { type: "string" },
2130
+ contains: { type: "string" },
2131
+ evalMatrix: { type: "string" },
2132
+ errorContains: { type: "string" },
2133
+ experiment: { type: "string" },
2134
+ format: {
2135
+ default: "table",
2136
+ type: "string"
2137
+ },
2138
+ project: { type: "string" },
2139
+ runMatrix: { type: "string" },
2140
+ run: { type: "string" },
2141
+ taskState: { type: "string" },
2142
+ workspace: { type: "string" }
2143
+ },
2144
+ importMeta: import.meta
2145
+ });
2146
+ const reportPath = cli.input[0];
2147
+ if (reportPath == null || reportPath.length === 0) throw new Error("Missing required <reportPath> argument.");
2148
+ const normalizedFormat = cli.flags.format.toLowerCase();
2149
+ const format = normalizedFormat === "json" ? "json" : normalizedFormat === "jsonl" ? "jsonl" : normalizedFormat === "csv" ? "csv" : "table";
2150
+ return {
2151
+ attempt: cli.flags.attempt,
2152
+ caseState: normalizeStateFilter(cli.flags.caseState),
2153
+ contains: cli.flags.contains,
2154
+ evalMatrix: parseMatrixSelector(cli.flags.evalMatrix),
2155
+ errorContains: cli.flags.errorContains,
2156
+ experiment: cli.flags.experiment,
2157
+ format,
2158
+ project: cli.flags.project,
2159
+ reportPath,
2160
+ runMatrix: parseMatrixSelector(cli.flags.runMatrix),
2161
+ run: cli.flags.run,
2162
+ taskState: normalizeStateFilter(cli.flags.taskState),
2163
+ workspace: cli.flags.workspace
2164
+ };
2165
+ }
2166
+ function normalizeStateFilter(value) {
2167
+ if (value == null) return;
2168
+ const normalized = value.trim().toLowerCase();
2169
+ if (normalized === "passed" || normalized === "failed" || normalized === "skipped") return normalized;
2170
+ throw new Error(`Unsupported state filter "${value}". Expected "passed", "failed", or "skipped".`);
2171
+ }
2172
+ function parseMatrixSelector(value) {
2173
+ if (value == null) return;
2174
+ const selector = {};
2175
+ const segments = value.split(",").map((segment) => segment.trim()).filter((segment) => segment.length > 0);
2176
+ for (const segment of segments) {
2177
+ const separatorIndex = segment.indexOf("=");
2178
+ if (separatorIndex <= 0 || separatorIndex === segment.length - 1) throw new Error(`Invalid matrix selector segment "${segment}". Expected "key=value".`);
2179
+ const key = segment.slice(0, separatorIndex).trim();
2180
+ const parsedValue = segment.slice(separatorIndex + 1).trim();
2181
+ if (key.length === 0 || parsedValue.length === 0) throw new Error(`Invalid matrix selector segment "${segment}". Expected "key=value".`);
2182
+ selector[key] = parsedValue;
2183
+ }
2184
+ return selector;
2185
+ }
2186
+ function filterAnalyzeRows(rows, parsed) {
2187
+ return rows.filter((row) => {
2188
+ if (parsed.workspace != null && row.workspaceId !== parsed.workspace) return false;
2189
+ if (parsed.experiment != null && row.experimentId !== parsed.experiment) return false;
2190
+ if (parsed.attempt != null && row.attemptId !== parsed.attempt) return false;
2191
+ if (parsed.run != null && row.runId !== parsed.run) return false;
2192
+ if (parsed.project != null && !row.projectNames.includes(parsed.project)) return false;
2193
+ return true;
2194
+ });
2195
+ }
2196
+ function includesNeedle(value, needle) {
2197
+ const normalizedNeedle = needle.trim().toLowerCase();
2198
+ if (normalizedNeedle.length === 0) return true;
2199
+ return JSON.stringify(value).toLowerCase().includes(normalizedNeedle);
2200
+ }
2201
+ function hasTaskState(artifact, targetState) {
2202
+ return artifact.events.some((event) => {
2203
+ if (event.event !== "TaskEnded") return false;
2204
+ return event.data?.state === targetState;
2205
+ });
2206
+ }
2207
+ function hasCaseState(artifact, targetState) {
2208
+ return artifact.events.some((event) => {
2209
+ if (event.event !== "CaseEnded") return false;
2210
+ return event.data?.state === targetState;
2211
+ });
2212
+ }
2213
+ function matchesMatrixSelector(matrix, selector) {
2214
+ return Object.entries(selector).every(([key, expectedValue]) => String(matrix[key]) === expectedValue);
2215
+ }
2216
+ function hasRunMatrixMatch(artifact, selector) {
2217
+ return artifact.summary.projects.some((project) => project.result?.runs.some((run) => matchesMatrixSelector(run.matrix.run, selector)) === true);
2218
+ }
2219
+ function hasEvalMatrixMatch(artifact, selector) {
2220
+ return artifact.summary.projects.some((project) => project.result?.runs.some((run) => matchesMatrixSelector(run.matrix.eval, selector)) === true);
2221
+ }
2222
+ function matchesOutcomeFilters(artifact, parsed) {
2223
+ if (parsed.runMatrix != null && !hasRunMatrixMatch(artifact, parsed.runMatrix)) return false;
2224
+ if (parsed.evalMatrix != null && !hasEvalMatrixMatch(artifact, parsed.evalMatrix)) return false;
2225
+ if (parsed.taskState != null && !hasTaskState(artifact, parsed.taskState)) return false;
2226
+ if (parsed.caseState != null && !hasCaseState(artifact, parsed.caseState)) return false;
2227
+ if (parsed.contains != null) {
2228
+ if (!artifact.events.some((event) => includesNeedle({
2229
+ data: event.data,
2230
+ event: event.event
2231
+ }, parsed.contains))) return false;
2232
+ }
2233
+ if (parsed.errorContains != null) {
2234
+ if (!(artifact.summary.projects.map((project) => project.errorMessage).filter((errorMessage) => errorMessage != null).some((errorMessage) => includesNeedle(errorMessage, parsed.errorContains)) || artifact.events.some((event) => includesNeedle(event.data, parsed.errorContains)))) return false;
2235
+ }
2236
+ return true;
2237
+ }
2238
+ async function readReportAnalyzeOutput(parsed) {
2239
+ const artifacts = await readReportArtifacts(parsed.reportPath);
2240
+ const rows = artifacts.map((artifact) => summarizeReportRunArtifact(artifact));
2241
+ const identityFilteredRows = filterAnalyzeRows(rows, parsed);
2242
+ const rowByDirectory = new Map(identityFilteredRows.map((row) => [row.reportDirectory, row]));
2243
+ const filteredRows = artifacts.filter((artifact) => rowByDirectory.has(artifact.reportDirectory)).filter((artifact) => matchesOutcomeFilters(artifact, parsed)).map((artifact) => rowByDirectory.get(artifact.reportDirectory)).filter((row) => row != null);
2244
+ return {
2245
+ experimentSummaries: buildExperimentSummaries(filteredRows),
2246
+ filteredRunCount: filteredRows.length,
2247
+ runs: filteredRows,
2248
+ totalRunCount: rows.length
2249
+ };
2250
+ }
2251
+ function roundMetric(value) {
2252
+ return Number(value.toFixed(6));
2253
+ }
2254
+ function computeAverage(values) {
2255
+ if (values.length === 0) return 0;
2256
+ return values.reduce((sum, value) => sum + value, 0) / values.length;
2257
+ }
2258
+ function computeStandardDeviation(values) {
2259
+ if (values.length === 0) return 0;
2260
+ const average = computeAverage(values);
2261
+ const variance = computeAverage(values.map((value) => (value - average) ** 2));
2262
+ return Math.sqrt(variance);
2263
+ }
2264
+ function createExperimentGroupKey(row) {
2265
+ return `${row.workspaceId ?? "unknown-workspace"}::${row.experimentId ?? "unknown-experiment"}`;
2266
+ }
2267
+ /**
2268
+ * Builds experiment-level rollups from filtered run rows.
2269
+ *
2270
+ * Use when:
2271
+ * - CLI consumers need stability and reliability summaries above per-run data
2272
+ *
2273
+ * Returns:
2274
+ * - one summary row per `workspaceId + experimentId` group
2275
+ */
2276
+ function buildExperimentSummaries(rows) {
2277
+ const grouped = /* @__PURE__ */ new Map();
2278
+ for (const row of rows) {
2279
+ const groupKey = createExperimentGroupKey(row);
2280
+ const existing = grouped.get(groupKey);
2281
+ if (existing == null) {
2282
+ grouped.set(groupKey, [row]);
2283
+ continue;
2284
+ }
2285
+ existing.push(row);
2286
+ }
2287
+ return [...grouped.entries()].map(([groupKey, groupRows]) => {
2288
+ const [workspaceId, experimentId] = groupKey.split("::");
2289
+ const failedProjects = groupRows.reduce((sum, row) => sum + row.failedProjects, 0);
2290
+ const totalTasks = groupRows.reduce((sum, row) => sum + row.totalTasks, 0);
2291
+ const totalEvents = groupRows.reduce((sum, row) => sum + row.eventsCount, 0);
2292
+ const successfulRunCount = groupRows.filter((row) => row.failedProjects === 0).length;
2293
+ const successRate = groupRows.length === 0 ? 0 : successfulRunCount / groupRows.length;
2294
+ const attemptToRuns = /* @__PURE__ */ new Map();
2295
+ for (const row of groupRows) {
2296
+ const attemptId = row.attemptId ?? "unknown-attempt";
2297
+ const attemptRows = attemptToRuns.get(attemptId);
2298
+ if (attemptRows == null) {
2299
+ attemptToRuns.set(attemptId, [row]);
2300
+ continue;
2301
+ }
2302
+ attemptRows.push(row);
2303
+ }
2304
+ const attemptSummaries = [...attemptToRuns.entries()].map(([attemptId, attemptRows]) => {
2305
+ const successCount = attemptRows.filter((row) => row.failedProjects === 0).length;
2306
+ const runCount = attemptRows.length;
2307
+ const failedProjectCount = attemptRows.reduce((sum, row) => sum + row.failedProjects, 0);
2308
+ const totalTaskCount = attemptRows.reduce((sum, row) => sum + row.totalTasks, 0);
2309
+ const totalEventCount = attemptRows.reduce((sum, row) => sum + row.eventsCount, 0);
2310
+ return {
2311
+ attemptId,
2312
+ failedProjects: failedProjectCount,
2313
+ runCount,
2314
+ runIds: attemptRows.map((row) => row.runId).filter((runId) => runId != null).sort((left, right) => left.localeCompare(right)),
2315
+ successRate: roundMetric(runCount === 0 ? 0 : successCount / runCount),
2316
+ totalEvents: totalEventCount,
2317
+ totalTasks: totalTaskCount
2318
+ };
2319
+ }).sort((left, right) => left.attemptId.localeCompare(right.attemptId));
2320
+ const attemptSuccessRates = attemptSummaries.map((summary) => summary.successRate);
2321
+ const minAttemptSuccessRate = attemptSuccessRates.length === 0 ? 0 : Math.min(...attemptSuccessRates);
2322
+ const maxAttemptSuccessRate = attemptSuccessRates.length === 0 ? 0 : Math.max(...attemptSuccessRates);
2323
+ const avgAttemptSuccessRate = computeAverage(attemptSuccessRates);
2324
+ const stdevAttemptSuccessRate = computeStandardDeviation(attemptSuccessRates);
2325
+ return {
2326
+ attemptCount: attemptToRuns.size,
2327
+ attemptSummaries,
2328
+ attemptSuccessRateStats: {
2329
+ avg: roundMetric(avgAttemptSuccessRate),
2330
+ max: roundMetric(maxAttemptSuccessRate),
2331
+ min: roundMetric(minAttemptSuccessRate),
2332
+ stdev: roundMetric(stdevAttemptSuccessRate)
2333
+ },
2334
+ experimentId,
2335
+ failedProjects,
2336
+ runCount: groupRows.length,
2337
+ successRate: roundMetric(successRate),
2338
+ totalEvents,
2339
+ totalTasks,
2340
+ workspaceId
2341
+ };
2342
+ }).sort((left, right) => {
2343
+ const workspaceCompare = left.workspaceId.localeCompare(right.workspaceId);
2344
+ if (workspaceCompare !== 0) return workspaceCompare;
2345
+ return left.experimentId.localeCompare(right.experimentId);
2346
+ });
2347
+ }
2348
+ function formatTableOutput$1(output) {
2349
+ const header = "Run ID | Workspace | Experiment | Attempt | Projects(executed/total) | FailedProjects | Tasks | Events";
2350
+ const lines = output.runs.map((row) => {
2351
+ return `${row.runId ?? "n/a"} | ${row.workspaceId ?? "n/a"} | ${row.experimentId ?? "n/a"} | ${row.attemptId ?? "n/a"} | ${`${row.executedProjects}/${row.totalProjects}`} | ${row.failedProjects} | ${row.totalTasks} | ${row.eventsCount}`;
2352
+ });
2353
+ return [
2354
+ `ANALYZE vieval report: ${output.filteredRunCount}/${output.totalRunCount} runs (${output.experimentSummaries.length} experiment groups)`,
2355
+ header,
2356
+ ...lines
2357
+ ].join("\n");
2358
+ }
2359
+ function formatCsvOutput(output) {
2360
+ return [[
2361
+ "runId",
2362
+ "workspaceId",
2363
+ "experimentId",
2364
+ "attemptId",
2365
+ "totalProjects",
2366
+ "executedProjects",
2367
+ "failedProjects",
2368
+ "totalTasks",
2369
+ "eventsCount",
2370
+ "reportDirectory",
2371
+ "projectNames"
2372
+ ].join(","), ...output.runs.map((row) => {
2373
+ const escapedProjectNames = `"${row.projectNames.join("|").replaceAll("\"", "\"\"")}"`;
2374
+ const escapedDirectory = `"${row.reportDirectory.replaceAll("\"", "\"\"")}"`;
2375
+ return [
2376
+ row.runId ?? "",
2377
+ row.workspaceId ?? "",
2378
+ row.experimentId ?? "",
2379
+ row.attemptId ?? "",
2380
+ row.totalProjects.toString(),
2381
+ row.executedProjects.toString(),
2382
+ row.failedProjects.toString(),
2383
+ row.totalTasks.toString(),
2384
+ row.eventsCount.toString(),
2385
+ escapedDirectory,
2386
+ escapedProjectNames
2387
+ ].join(",");
2388
+ })].join("\n");
2389
+ }
2390
+ async function runReportAnalyzeCli(argv) {
2391
+ try {
2392
+ const parsed = parseReportAnalyzeCliArguments(argv);
2393
+ const output = await readReportAnalyzeOutput(parsed);
2394
+ if (parsed.format === "json") {
2395
+ process.stdout.write(`${JSON.stringify(output, null, 2)}\n`);
2396
+ return;
2397
+ }
2398
+ if (parsed.format === "jsonl") {
2399
+ const jsonl = output.runs.map((run) => JSON.stringify(run)).join("\n");
2400
+ process.stdout.write(`${jsonl}${jsonl.length > 0 ? "\n" : ""}`);
2401
+ return;
2402
+ }
2403
+ if (parsed.format === "csv") {
2404
+ process.stdout.write(`${formatCsvOutput(output)}\n`);
2405
+ return;
2406
+ }
2407
+ process.stdout.write(`${formatTableOutput$1(output)}\n`);
2408
+ } catch (error) {
2409
+ const errorMessage = errorMessageFrom(error) ?? "Unknown report analyze failure.";
2410
+ process.stderr.write(`[vieval report analyze] ${errorMessage}\n`);
2411
+ process.exitCode = 1;
2412
+ }
2413
+ }
2414
+ //#endregion
2415
+ //#region src/cli/report-index.ts
2416
+ const reportIndexHelpText = `
2417
+ Build report indexes from generated vieval artifacts.
2418
+
2419
+ Usage
2420
+ $ vieval report index <reportPath> [--output <path>] [--format <format>]
2421
+
2422
+ Options
2423
+ --output Output file path (default: <reportPath>/index/runs.jsonl)
2424
+ --format Console output format: table | json | jsonl (default: table)
2425
+ `;
2426
+ function normalizeCliArgv$1(argv) {
2427
+ const normalizedArgv = argv[0] === "--" ? argv.slice(1) : [...argv];
2428
+ if (normalizedArgv[0] === "report" && normalizedArgv[1] === "index") return normalizedArgv.slice(2);
2429
+ if (normalizedArgv[0] === "index") return normalizedArgv.slice(1);
2430
+ return normalizedArgv;
2431
+ }
2432
+ function parseReportIndexCliArguments(argv) {
2433
+ const cli = meow(reportIndexHelpText, {
2434
+ argv: normalizeCliArgv$1(argv),
2435
+ flags: {
2436
+ format: {
2437
+ default: "table",
2438
+ type: "string"
2439
+ },
2440
+ output: { type: "string" }
2441
+ },
2442
+ importMeta: import.meta
2443
+ });
2444
+ const reportPath = cli.input[0];
2445
+ if (reportPath == null || reportPath.length === 0) throw new Error("Missing required <reportPath> argument.");
2446
+ const normalizedFormat = cli.flags.format.toLowerCase();
2447
+ return {
2448
+ format: normalizedFormat === "json" ? "json" : normalizedFormat === "jsonl" ? "jsonl" : "table",
2449
+ output: cli.flags.output,
2450
+ reportPath
2451
+ };
2452
+ }
2453
+ async function writeIndexFile(parsed) {
2454
+ const rows = (await readReportArtifacts(parsed.reportPath)).map((artifact) => summarizeReportRunArtifact(artifact));
2455
+ const indexFilePath = resolve(parsed.output ?? resolve(parsed.reportPath, "index", "runs.jsonl"));
2456
+ await mkdir(dirname(indexFilePath), { recursive: true });
2457
+ const indexContents = rows.map((row) => JSON.stringify(row)).join("\n");
2458
+ await writeFile(indexFilePath, `${indexContents}${indexContents.length > 0 ? "\n" : ""}`, "utf-8");
2459
+ return {
2460
+ indexFilePath,
2461
+ indexedRunCount: rows.length,
2462
+ rows
2463
+ };
2464
+ }
2465
+ function formatTableOutput(output) {
2466
+ return [
2467
+ "INDEX vieval report",
2468
+ `Path ${output.indexFilePath}`,
2469
+ `Run count ${output.indexedRunCount}`
2470
+ ].join("\n");
2471
+ }
2472
+ async function runReportIndexCli(argv) {
2473
+ try {
2474
+ const parsed = parseReportIndexCliArguments(argv);
2475
+ const output = await writeIndexFile(parsed);
2476
+ if (parsed.format === "json") {
2477
+ process.stdout.write(`${JSON.stringify(output, null, 2)}\n`);
2478
+ return;
2479
+ }
2480
+ if (parsed.format === "jsonl") {
2481
+ const jsonl = output.rows.map((row) => JSON.stringify(row)).join("\n");
2482
+ process.stdout.write(`${jsonl}${jsonl.length > 0 ? "\n" : ""}`);
2483
+ return;
2484
+ }
2485
+ process.stdout.write(`${formatTableOutput(output)}\n`);
2486
+ } catch (error) {
2487
+ const errorMessage = errorMessageFrom(error) ?? "Unknown report index failure.";
2488
+ process.stderr.write(`[vieval report index] ${errorMessage}\n`);
2489
+ process.exitCode = 1;
2490
+ }
2491
+ }
2492
+ //#endregion
2493
+ //#region src/cli/index.ts
2494
+ const topLevelHelpText = `
2495
+ Execute and report evaluation projects.
2496
+
2497
+ Usage
2498
+ $ vieval <command> [options]
2499
+
2500
+ Commands
2501
+ run Discover and execute eval projects
2502
+ compare Compare multiple workspaces/methods on one benchmark
2503
+ report Analyze and index generated report artifacts
2504
+
2505
+ Examples
2506
+ $ vieval run
2507
+ $ vieval run --config vieval.config.ts --project chess --json --report-out .vieval/reports
2508
+ $ vieval compare --config vieval.config.ts --comparison agent-memory
2509
+ $ vieval report analyze .vieval/reports/my-run
2510
+ $ vieval report index .vieval/reports --output .vieval/reports/index/runs.jsonl
2511
+ `;
2512
+ function normalizeCliArgv(argv) {
2513
+ return argv[0] === "--" ? argv.slice(1) : [...argv];
2514
+ }
2515
+ /**
2516
+ * Parses top-level `vieval` CLI arguments into one command dispatch payload.
2517
+ *
2518
+ * Use when:
2519
+ * - the executable needs to resolve which subcommand should run
2520
+ * - tests need stable top-level argv normalization without invoking subcommands
2521
+ *
2522
+ * Expects:
2523
+ * - argv excludes the node executable and script path
2524
+ *
2525
+ * Returns:
2526
+ * - the normalized top-level command plus subcommand argv
2527
+ */
2528
+ function parseTopLevelCliArguments(argv) {
2529
+ const normalizedArgv = normalizeCliArgv(argv);
2530
+ const command = normalizedArgv[0];
2531
+ meow(topLevelHelpText, {
2532
+ autoHelp: false,
2533
+ autoVersion: false,
2534
+ argv: normalizedArgv,
2535
+ importMeta: import.meta
2536
+ });
2537
+ if (command == null || command === "help" || command === "--help" || command === "-h") return {
2538
+ command: "help",
2539
+ commandArgv: []
2540
+ };
2541
+ if (command !== "run" && command !== "report" && command !== "compare") throw new Error(`Unsupported vieval command "${command ?? "(none)"}". Expected "run", "compare", or "report".`);
2542
+ return {
2543
+ command,
2544
+ commandArgv: normalizedArgv.slice(1)
2545
+ };
2546
+ }
2547
+ /**
2548
+ * Dispatches the top-level `vieval` command to one concrete subcommand module.
2549
+ *
2550
+ * Call stack:
2551
+ *
2552
+ * published executable (`../bin/vieval`)
2553
+ * -> {@link runTopLevelCli}
2554
+ * -> {@link runEvalRunCli} / report CLI / compare CLI
2555
+ *
2556
+ * Use when:
2557
+ * - the executable or tests need import-safe CLI orchestration
2558
+ * - subcommands should remain reusable without process-bound startup code
2559
+ *
2560
+ * Expects:
2561
+ * - argv excludes the node executable and script path
2562
+ *
2563
+ * Returns:
2564
+ * - resolves after the selected subcommand completes
2565
+ */
2566
+ async function runTopLevelCli(argv) {
2567
+ const parsed = parseTopLevelCliArguments(argv);
2568
+ if (parsed.command === "help") {
2569
+ process.stdout.write(`${topLevelHelpText.trim()}\n`);
2570
+ return;
2571
+ }
2572
+ if (parsed.command === "report") {
2573
+ const reportSubcommand = parsed.commandArgv[0];
2574
+ if (reportSubcommand === "analyze") {
2575
+ await runReportAnalyzeCli(parsed.commandArgv);
2576
+ return;
2577
+ }
2578
+ if (reportSubcommand === "index") {
2579
+ await runReportIndexCli(parsed.commandArgv);
2580
+ return;
2581
+ }
2582
+ throw new Error(`Unsupported vieval report command "${reportSubcommand ?? "(none)"}". Expected "analyze" or "index".`);
2583
+ }
2584
+ if (parsed.command === "compare") {
2585
+ await runCompareCliOrExit(parsed.commandArgv);
2586
+ return;
2587
+ }
2588
+ await runEvalRunCli(parsed.commandArgv);
2589
+ }
2590
+ //#endregion
2591
+ export { runTopLevelCli as n, parseTopLevelCliArguments as t };
2592
+
2593
+ //# sourceMappingURL=cli-DayPXzHX.mjs.map