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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
/**
 * @license
 * Copyright 2026 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import path from 'node:path';
import { execSync } from 'node:child_process';
import type {
  EvalCaseRecord,
  EvalAnalysisDiagnostic,
} from './eval-analysis.js';
import type { InventoryResult } from './eval-inventory.js';
import type { ToolRegistry } from './tool-registry.js';

export interface ValidationRule {
  id: string;
  description: string;
}

export interface ValidationViolation {
  ruleId: string;
  message: string;
  filePath: string;
  location: { line: number; column: number };
}

export interface FileValidationSummary {
  relativePath: string;
  totalCases: number;
  violationCount: number;
}

export interface ValidationResult {
  totalFiles: number;
  totalCases: number;
  totalViolations: number;
  invalidFiles: number;
  validFiles: number;
  violations: ValidationViolation[];
  fileSummaries: FileValidationSummary[];
  analyzerDiagnostics: readonly EvalAnalysisDiagnostic[];
  unmatchedFilePaths?: string[];
}

export const VALIDATION_RULES: readonly ValidationRule[] = [
  {
    id: 'file-naming',
    description:
      'Eval file relativePath must match the *.eval.ts or *.eval.tsx naming convention.',
  },
  {
    id: 'valid-policy',
    description:
      'Policy must be one of ALWAYS_PASSES, USUALLY_PASSES, or USUALLY_FAILS.',
  },
  {
    id: 'suite-metadata',
    description:
      'Both suiteName and suiteType must be present as static string literals.',
  },
  {
    id: 'prompt-presence',
    description: 'The prompt property must be present in the eval case object.',
  },
  {
    id: 'case-name-static',
    description:
      'The case name must be a static string literal, not a computed value.',
  },
  {
    id: 'invalid-tool-refs',
    description:
      'All tools referenced in assertions must be valid, existing tools in the registry.',
  },
  {
    id: 'positive-assertion',
    description:
      'Behavioral evaluation cases must assert on at least one tool call.',
  },
  {
    id: 'workspace-setup',
    description:
      'Workspace behavior evaluations must provide files or a setup function.',
  },
  {
    id: 'new-evals-policy',
    description: 'New evaluations must not use ALWAYS_PASSES policy initially.',
  },
];

const VALID_FILE_SUFFIXES = ['.eval.ts', '.eval.tsx'] as const;
const VALID_POLICIES = new Set([
  'ALWAYS_PASSES',
  'USUALLY_PASSES',
  'USUALLY_FAILS',
]);

function checkFileNaming(
  evalCase: EvalCaseRecord,
  filePath: string,
): ValidationViolation | undefined {
  // Check the relativePath because collectInventory's glob already filters by
  // *.eval.{ts,tsx}. This rule catches cases from manually constructed
  // inventories or future non-glob discovery paths.
  const checkPath = evalCase.relativePath || filePath;
  const base = path.basename(checkPath);
  if (!VALID_FILE_SUFFIXES.some((suffix) => base.endsWith(suffix))) {
    return {
      ruleId: 'file-naming',
      message: `File "${base}" does not match the required *.eval.ts or *.eval.tsx naming convention.`,
      filePath,
      location: evalCase.location,
    };
  }
  return undefined;
}

function checkValidPolicy(
  evalCase: EvalCaseRecord,
  filePath: string,
): ValidationViolation | undefined {
  if (!VALID_POLICIES.has(evalCase.policy)) {
    return {
      ruleId: 'valid-policy',
      message: `Policy "${evalCase.policy}" is not valid. Must be one of: ${[...VALID_POLICIES].join(', ')}.`,
      filePath,
      location: evalCase.location,
    };
  }
  return undefined;
}

function checkSuiteMetadata(
  evalCase: EvalCaseRecord,
  filePath: string,
): ValidationViolation[] {
  const violations: ValidationViolation[] = [];
  if (!evalCase.suiteName) {
    violations.push({
      ruleId: 'suite-metadata',
      message:
        'Missing suiteName. Add a static suiteName string to the eval case object.',
      filePath,
      location: evalCase.location,
    });
  }
  if (!evalCase.suiteType) {
    violations.push({
      ruleId: 'suite-metadata',
      message:
        'Missing suiteType. Add a static suiteType string to the eval case object.',
      filePath,
      location: evalCase.location,
    });
  }
  return violations;
}

function checkPromptPresence(
  evalCase: EvalCaseRecord,
  filePath: string,
): ValidationViolation | undefined {
  if (
    evalCase.baseHelperName === 'componentEvalTest' ||
    evalCase.suiteType === 'component-level'
  ) {
    return undefined;
  }
  if (!evalCase.hasPrompt) {
    return {
      ruleId: 'prompt-presence',
      message:
        'Eval case is missing a prompt property. Every case must include a prompt.',
      filePath,
      location: evalCase.location,
    };
  }
  return undefined;
}

function checkCaseNameStatic(
  evalCase: EvalCaseRecord,
  filePath: string,
): ValidationViolation | undefined {
  // The analyzer stores unresolved names as '<unknown>' (eval-analysis.ts L159).
  if (evalCase.name === '<unknown>') {
    return {
      ruleId: 'case-name-static',
      message:
        'Case name could not be resolved to a static string literal. Use a plain string, not a variable or template expression.',
      filePath,
      location: evalCase.location,
    };
  }
  return undefined;
}

const EXEMPT_SUITE_TYPES = new Set([
  'component-level',
  'text',
  'prose',
  'steering',
  'memory',
]);

function checkPositiveAssertion(
  evalCase: EvalCaseRecord,
  filePath: string,
): ValidationViolation | undefined {
  if (
    evalCase.baseHelperName === 'componentEvalTest' ||
    (evalCase.suiteType && EXEMPT_SUITE_TYPES.has(evalCase.suiteType))
  ) {
    return undefined;
  }

  // If case has tool references or has an assertion body (e.g. negative or custom assertions), pass
  if (evalCase.toolReferences.length > 0 || evalCase.hasAssertBody) {
    return undefined;
  }

  return {
    ruleId: 'positive-assertion',
    message:
      'Eval case assert function does not track any tool references. Use at least one positive tool assertion.',
    filePath,
    location: evalCase.location,
  };
}

function checkWorkspaceSetup(
  evalCase: EvalCaseRecord,
  filePath: string,
): ValidationViolation | undefined {
  if (
    evalCase.baseHelperName === 'componentEvalTest' ||
    (evalCase.suiteType && EXEMPT_SUITE_TYPES.has(evalCase.suiteType)) ||
    evalCase.hasFiles ||
    evalCase.hasSetup
  ) {
    return undefined;
  }

  if (
    evalCase.suiteType === 'workspace' ||
    evalCase.suiteType === 'file-system'
  ) {
    return {
      ruleId: 'workspace-setup',
      message:
        'Eval case suggests workspace interaction (files/git), but neither "files" nor a "setup" hook is specified.',
      filePath,
      location: evalCase.location,
    };
  }

  return undefined;
}

function getNewEvalFiles(repoRoot?: string): Set<string> {
  const newFiles = new Set<string>();
  const cwd = repoRoot || process.cwd();

  function addFromOutput(output: string): void {
    for (const line of output.split('\n')) {
      const trimmed = line.trim();
      if (!trimmed) continue;
      // git status --porcelain: "A  path" or "?? path"
      // git diff --name-only: bare path
      let filePath: string;
      if (trimmed.startsWith('A') || trimmed.startsWith('??')) {
        filePath = trimmed.slice(2).trim();
      } else {
        filePath = trimmed;
      }
      if (filePath.startsWith('"') && filePath.endsWith('"')) {
        filePath = filePath.slice(1, -1);
      }
      if (filePath) {
        newFiles.add(path.resolve(cwd, filePath).replace(/\\/g, '/'));
      }
    }
  }

  try {
    // Working-tree additions (useful locally)
    const status = execSync('git status --porcelain', {
      cwd,
      encoding: 'utf8',
      stdio: ['ignore', 'pipe', 'ignore'],
    });
    addFromOutput(status);
  } catch {
    // Ignore
  }

  try {
    // PR-level additions against the merge base (works in CI where working
    // tree is clean). Try origin/main, fall back to main, then HEAD~1.
    const bases = ['origin/main', 'main', 'HEAD~1'];
    for (const base of bases) {
      try {
        const mergeBase = execSync(`git merge-base HEAD ${base}`, {
          cwd,
          encoding: 'utf8',
          stdio: ['ignore', 'pipe', 'ignore'],
        }).trim();
        if (mergeBase) {
          const diff = execSync(
            `git diff --diff-filter=A --name-only ${mergeBase}`,
            {
              cwd,
              encoding: 'utf8',
              stdio: ['ignore', 'pipe', 'ignore'],
            },
          );
          addFromOutput(diff);
          break; // succeeded, no need to try next base
        }
      } catch {
        // Try next base
      }
    }
  } catch {
    // Ignore
  }

  return newFiles;
}

function checkNewEvalPolicy(
  evalCase: EvalCaseRecord,
  filePath: string,
  newFiles: Set<string>,
): ValidationViolation | undefined {
  const normalizedPath = path.resolve(filePath).replace(/\\/g, '/');
  if (newFiles.has(normalizedPath) && evalCase.policy === 'ALWAYS_PASSES') {
    return {
      ruleId: 'new-evals-policy',
      message:
        'New evaluations must not use ALWAYS_PASSES policy initially. Use USUALLY_PASSES.',
      filePath,
      location: evalCase.location,
    };
  }
  return undefined;
}

/**
 * Validates every eval case in the given inventory and returns a
 * ValidationResult. Pass `options.filePaths` to restrict to a subset of
 * files (absolute or relative to `inventory.repoRoot`).
 *
 * The `_registry` parameter is reserved for future tool-name validation rules.
 */
export function validateInventory(
  inventory: InventoryResult,
  _registry: ToolRegistry,
  options: { filePaths?: string[] } = {},
): ValidationResult {
  const { filePaths: filterPaths } = options;

  const matchedFilterSet = new Set<string>();
  const filterMap = new Map<string, string>(); // maps normalized relative path -> original filter path

  const filterSet: Set<string> | undefined = filterPaths
    ? new Set(
        filterPaths.map((p) => {
          let abs: string;
          if (path.isAbsolute(p)) {
            abs = p;
          } else {
            abs = path.resolve(inventory.repoRoot || process.cwd(), p);
          }
          const rel = inventory.repoRoot
            ? path.relative(inventory.repoRoot, abs)
            : abs;
          const normalized = rel.replace(/\\/g, '/');
          filterMap.set(normalized, p);
          return normalized;
        }),
      )
    : undefined;

  const fileSummaryMap = new Map<
    string,
    { totalCases: number; violationCount: number }
  >();
  const allViolations: ValidationViolation[] = [];
  const newFiles = getNewEvalFiles(inventory.repoRoot);

  for (const fileAnalysis of inventory.files) {
    const relativePath = fileAnalysis.relativePath;
    if (filterSet) {
      if (!filterSet.has(relativePath)) {
        continue;
      }
      matchedFilterSet.add(relativePath);
    }

    if (!fileSummaryMap.has(relativePath)) {
      fileSummaryMap.set(relativePath, { totalCases: 0, violationCount: 0 });
    }

    for (const evalCase of fileAnalysis.cases) {
      const summary = fileSummaryMap.get(relativePath)!;
      summary.totalCases += 1;
      const fp = evalCase.filePath;
      const caseViolations: ValidationViolation[] = [];

      const fn = checkFileNaming(evalCase, fp);
      if (fn) caseViolations.push(fn);

      const pol = checkValidPolicy(evalCase, fp);
      if (pol) caseViolations.push(pol);

      caseViolations.push(...checkSuiteMetadata(evalCase, fp));

      const pr = checkPromptPresence(evalCase, fp);
      if (pr) caseViolations.push(pr);

      const ns = checkCaseNameStatic(evalCase, fp);
      if (ns) caseViolations.push(ns);

      const pos = checkPositiveAssertion(evalCase, fp);
      if (pos) caseViolations.push(pos);

      const ws = checkWorkspaceSetup(evalCase, fp);
      if (ws) caseViolations.push(ws);

      const nep = checkNewEvalPolicy(evalCase, fp, newFiles);
      if (nep) caseViolations.push(nep);

      allViolations.push(...caseViolations);
      summary.violationCount += caseViolations.length;
    }
  }

  // Elevate unrecognized tool warning diagnostics to validation violations
  for (const d of inventory.diagnostics) {
    if (d.message.startsWith('Unrecognized tool name extracted:')) {
      const displayPath = resolveDisplayPath(d.filePath, inventory.repoRoot);
      if (filterSet && !filterSet.has(displayPath)) {
        continue;
      }
      allViolations.push({
        ruleId: 'invalid-tool-refs',
        message: d.message,
        filePath: d.filePath,
        location: d.location,
      });

      const summary = fileSummaryMap.get(displayPath);
      if (summary) {
        summary.violationCount += 1;
      }
    }
  }

  const fileSummaries: FileValidationSummary[] = [...fileSummaryMap.entries()]
    .map(([relativePath, s]) => ({
      relativePath,
      totalCases: s.totalCases,
      violationCount: s.violationCount,
    }))
    .sort((a, b) => a.relativePath.localeCompare(b.relativePath, 'en'));

  const totalFiles = fileSummaries.length;
  const totalCases = fileSummaries.reduce((sum, f) => sum + f.totalCases, 0);
  const totalViolations = allViolations.length;
  const invalidFiles = fileSummaries.filter((f) => f.violationCount > 0).length;

  const unmatchedFilePaths: string[] = [];
  if (filterSet) {
    for (const f of filterSet) {
      if (!matchedFilterSet.has(f)) {
        const original = filterMap.get(f);
        if (original !== undefined) {
          unmatchedFilePaths.push(original);
        }
      }
    }
  }

  return {
    totalFiles,
    totalCases,
    totalViolations,
    invalidFiles,
    validFiles: totalFiles - invalidFiles,
    violations: allViolations,
    fileSummaries,
    analyzerDiagnostics: inventory.diagnostics,
    unmatchedFilePaths,
  };
}

function resolveDisplayPath(filePath: string, repoRoot?: string): string {
  if (filePath === '<inline>') return filePath;
  if (repoRoot && path.isAbsolute(filePath)) {
    return path.relative(repoRoot, filePath).replace(/\\/g, '/');
  }
  return filePath;
}

function appendAnalyzerDiagnostics(
  lines: string[],
  diagnostics: readonly EvalAnalysisDiagnostic[],
  repoRoot?: string,
): void {
  lines.push(`Analyzer Diagnostics (${diagnostics.length})`);
  lines.push('────────────────────────');
  for (const d of diagnostics) {
    const displayPath = resolveDisplayPath(d.filePath, repoRoot);
    lines.push(
      `⚠ ${displayPath}:${d.location.line}:${d.location.column} β€” ${d.message}`,
    );
  }
  lines.push('');
}

export function formatValidationReport(
  result: ValidationResult,
  repoRoot?: string,
): string {
  const lines: string[] = [];

  lines.push('Eval Validation Report');
  lines.push('══════════════════════');
  lines.push('');
  lines.push(
    `${result.totalFiles} files Β· ${result.totalCases} cases Β· ${result.totalViolations} violations`,
  );

  if (result.totalViolations === 0) {
    lines.push('');
    lines.push('βœ“ All eval cases pass validation.');
    if (result.analyzerDiagnostics.length > 0) {
      lines.push('');
      appendAnalyzerDiagnostics(lines, result.analyzerDiagnostics, repoRoot);
    }
    return lines.join('\n');
  }

  lines.push('');

  const byFile = new Map<string, ValidationViolation[]>();
  for (const v of result.violations) {
    const displayPath = resolveDisplayPath(v.filePath, repoRoot);
    const existing = byFile.get(displayPath);
    if (existing) {
      existing.push(v);
    } else {
      byFile.set(displayPath, [v]);
    }
  }

  for (const [displayPath, violations] of [...byFile.entries()].sort(
    ([a], [b]) => a.localeCompare(b, 'en'),
  )) {
    lines.push(displayPath);
    for (const v of violations) {
      lines.push(
        `  βœ— [${v.ruleId}] ${v.location.line}:${v.location.column} β€” ${v.message}`,
      );
    }
    lines.push('');
  }

  lines.push('Summary');
  lines.push('───────');
  lines.push(`  ${result.validFiles} / ${result.totalFiles} files pass`);
  lines.push(`  ${result.totalViolations} violation(s) found`);
  lines.push('');

  if (result.analyzerDiagnostics.length > 0) {
    appendAnalyzerDiagnostics(lines, result.analyzerDiagnostics, repoRoot);
  }

  return lines.join('\n');
}

export interface ValidationJsonViolation {
  ruleId: string;
  message: string;
  filePath: string;
  location: { line: number; column: number };
}

export interface ValidationJsonOutput {
  version: 1;
  generated: string;
  summary: {
    totalFiles: number;
    totalCases: number;
    totalViolations: number;
    validFiles: number;
    invalidFiles: number;
  };
  violations: ValidationJsonViolation[];
}

export function formatValidationJson(
  result: ValidationResult,
  repoRoot?: string,
  now?: Date,
): string {
  let generatedDate = now;
  if (!generatedDate && process.env.SOURCE_DATE_EPOCH) {
    const epoch = parseInt(process.env.SOURCE_DATE_EPOCH, 10);
    if (!isNaN(epoch)) generatedDate = new Date(epoch * 1000);
  }
  if (
    !generatedDate &&
    (process.env.EVAL_VALIDATE_STABLE_DATE ||
      process.env.EVAL_INVENTORY_DETERMINISTIC)
  ) {
    generatedDate = new Date(0);
  }
  if (!generatedDate) generatedDate = new Date();

  const output: ValidationJsonOutput = {
    version: 1,
    generated: generatedDate.toISOString(),
    summary: {
      totalFiles: result.totalFiles,
      totalCases: result.totalCases,
      totalViolations: result.totalViolations,
      validFiles: result.validFiles,
      invalidFiles: result.invalidFiles,
    },
    violations: result.violations.map((v) => ({
      ruleId: v.ruleId,
      message: v.message,
      filePath: resolveDisplayPath(v.filePath, repoRoot),
      location: { line: v.location.line, column: v.location.column },
    })),
  };

  return JSON.stringify(output, null, 2);
}