From 41b339713b53b7f5494dcd622ad5ada198fa7741 Mon Sep 17 00:00:00 2001 From: Christopher Kevin Date: Sat, 7 Nov 2026 01:01:38 +0000 Subject: [PATCH 1/3] feat(tier3): add validate-grader qualification command and reference suite Adds a versioned grader-qualification suite format and 'skillevaluator tier3 validate-grader', which runs the shipped verifier against independently labelled cases and reports confusion matrices, false-pass and false-fail rates with explicit denominators and Wilson intervals, unjudgeable and error counts, repeated-grading variability and version-bound provenance. Ships a bundled public reference suite with separate assessment and tuning splits and an offline --check-suite mode. Signed-off-by: Christopher Kevin --- CHANGELOG.md | 4 + docs/AGENTS.md | 1 + docs/cli-reference.mdx | 30 + docs/grader-validation.mdx | 244 +++++ docs/tier3-live-evaluation.mdx | 6 +- fern/docs.yml | 3 + pyproject.toml | 1 + src/skillevaluator/cli.py | 2 + .../tier3/grader_reference/suite.json | 854 ++++++++++++++++++ .../trajectories/arithmetic.json | 56 ++ .../trajectories/baseline.json | 14 + .../trajectories/false-success.json | 56 ++ .../trajectories/mixed-behavior.json | 56 ++ .../trajectories/negative-value.json | 56 ++ .../trajectories/no-answer.json | 56 ++ .../trajectories/non-use.json | 14 + .../trajectories/percentage.json | 56 ++ .../grader_reference/trajectories/power.json | 56 ++ .../trajectories/recover.json | 77 ++ .../trajectories/tuning-add.json | 56 ++ .../trajectories/tuning-wrong.json | 56 ++ .../trajectories/wrong-answer.json | 56 ++ .../trajectories/wrong-format.json | 56 ++ .../grader_reference/trajectories/zero.json | 56 ++ src/skillevaluator/tier3/grader_validation.py | 582 ++++++++++++ tests/golden/cli_surface.json | 116 +++ tests/tier3/test_grader_validation.py | 370 ++++++++ 27 files changed, 2988 insertions(+), 2 deletions(-) create mode 100644 docs/grader-validation.mdx create mode 100644 src/skillevaluator/tier3/grader_reference/suite.json create mode 100644 src/skillevaluator/tier3/grader_reference/trajectories/arithmetic.json create mode 100644 src/skillevaluator/tier3/grader_reference/trajectories/baseline.json create mode 100644 src/skillevaluator/tier3/grader_reference/trajectories/false-success.json create mode 100644 src/skillevaluator/tier3/grader_reference/trajectories/mixed-behavior.json create mode 100644 src/skillevaluator/tier3/grader_reference/trajectories/negative-value.json create mode 100644 src/skillevaluator/tier3/grader_reference/trajectories/no-answer.json create mode 100644 src/skillevaluator/tier3/grader_reference/trajectories/non-use.json create mode 100644 src/skillevaluator/tier3/grader_reference/trajectories/percentage.json create mode 100644 src/skillevaluator/tier3/grader_reference/trajectories/power.json create mode 100644 src/skillevaluator/tier3/grader_reference/trajectories/recover.json create mode 100644 src/skillevaluator/tier3/grader_reference/trajectories/tuning-add.json create mode 100644 src/skillevaluator/tier3/grader_reference/trajectories/tuning-wrong.json create mode 100644 src/skillevaluator/tier3/grader_reference/trajectories/wrong-answer.json create mode 100644 src/skillevaluator/tier3/grader_reference/trajectories/wrong-format.json create mode 100644 src/skillevaluator/tier3/grader_reference/trajectories/zero.json create mode 100644 src/skillevaluator/tier3/grader_validation.py create mode 100644 tests/tier3/test_grader_validation.py diff --git a/CHANGELOG.md b/CHANGELOG.md index a30baa36f..43501ca86 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,10 @@ All notable changes to SkillEvaluator are documented in this file. ### Added +- `tier3 validate-grader` qualifies the shipped verifier against independent + versioned labels, with offline suite checks, repeated-grading statistics, + provenance, optional rate gates and a bundled public reference suite. + - `skills/skillevaluator/` is an agent skill for operating SkillEvaluator: it routes requests to the right tier, readiness check, dataset, report, or CI command, and ships Tier 3 evaluation cases for itself. A test keeps every diff --git a/docs/AGENTS.md b/docs/AGENTS.md index 2f94f2fa0..360ee6596 100644 --- a/docs/AGENTS.md +++ b/docs/AGENTS.md @@ -18,6 +18,7 @@ folder holds MDX pages published to None: tier3.add_command(tier3_doctor_command, "doctor") from skillevaluator.tier3.decoy_commands import select_decoys_command +from skillevaluator.tier3.grader_validation import validate_grader tier3.add_command(select_decoys_command, "select-decoys") +tier3.add_command(validate_grader, "validate-grader") from skillevaluator.tier3.workflow import build_tier3_workflow diff --git a/src/skillevaluator/tier3/grader_reference/suite.json b/src/skillevaluator/tier3/grader_reference/suite.json new file mode 100644 index 000000000..594051216 --- /dev/null +++ b/src/skillevaluator/tier3/grader_reference/suite.json @@ -0,0 +1,854 @@ +{ + "schema": "skillevaluator.grader-qualification/v1", + "suite": { + "name": "Calculator reference qualification", + "version": "1.0.0", + "description": "Small public synthetic reference suite, not a claim of grader reliability." + }, + "cases": [ + { + "id": "arithmetic", + "split": "assessment", + "category": "positive", + "source": { + "kind": "synthetic", + "origin": "Public calculator reference skill; hand-written ATIF evidence.", + "trace_id": "calculator-arithmetic-v1" + }, + "entry": { + "question": "Use calculator to compute 2 + 3 * 4. Return only the numeric answer.", + "ground_truth": "14", + "expected_behavior": [ + "Read calculator instructions before running calc.py.", + "Return only the numeric answer." + ], + "expected_skill": "calculator", + "expected_script": "calc.py", + "evaluated_skill": "calculator", + "should_trigger": true, + "has_skill": true + }, + "trajectory": "trajectories/arithmetic.json", + "expected": { + "overall": "pass", + "metrics": { + "security": "pass", + "skill_execution": "pass", + "skill_efficiency": "pass", + "accuracy": "pass", + "goal_accuracy": "pass", + "behavior_check": [ + true, + true + ] + } + }, + "label": { + "method": "executable", + "reviewed_by": "Reference suite maintainers", + "reviewed_on": "2026-11-06", + "rationale": "Arithmetic independently checked; literal evidence assertions below anchor the label. Expected task outcome and behavior reviewed against the recorded calls.", + "checks": [ + { + "type": "final_response_contains", + "value": "14" + }, + { + "type": "tool_result_contains", + "value": "Result: 14" + } + ] + } + }, + { + "id": "power", + "split": "assessment", + "category": "positive", + "source": { + "kind": "synthetic", + "origin": "Public calculator reference skill; hand-written ATIF evidence.", + "trace_id": "calculator-power-v1" + }, + "entry": { + "question": "Use calculator to compute 2 ** 10. Return only the numeric answer.", + "ground_truth": "1024", + "expected_behavior": [ + "Read calculator instructions before running calc.py.", + "Return only the numeric answer." + ], + "expected_skill": "calculator", + "expected_script": "calc.py", + "evaluated_skill": "calculator", + "should_trigger": true, + "has_skill": true + }, + "trajectory": "trajectories/power.json", + "expected": { + "overall": "pass", + "metrics": { + "security": "pass", + "skill_execution": "pass", + "skill_efficiency": "pass", + "accuracy": "pass", + "goal_accuracy": "pass", + "behavior_check": [ + true, + true + ] + } + }, + "label": { + "method": "executable", + "reviewed_by": "Reference suite maintainers", + "reviewed_on": "2026-11-06", + "rationale": "Arithmetic independently checked; literal evidence assertions below anchor the label. Expected task outcome and behavior reviewed against the recorded calls.", + "checks": [ + { + "type": "final_response_contains", + "value": "1024" + }, + { + "type": "tool_result_contains", + "value": "Result: 1024" + } + ] + } + }, + { + "id": "percentage", + "split": "assessment", + "category": "positive", + "source": { + "kind": "synthetic", + "origin": "Public calculator reference skill; hand-written ATIF evidence.", + "trace_id": "calculator-percentage-v1" + }, + "entry": { + "question": "Use calculator to compute 15% of 200. Return only the numeric answer.", + "ground_truth": "30", + "expected_behavior": [ + "Read calculator instructions before running calc.py.", + "Return only the numeric answer." + ], + "expected_skill": "calculator", + "expected_script": "calc.py", + "evaluated_skill": "calculator", + "should_trigger": true, + "has_skill": true + }, + "trajectory": "trajectories/percentage.json", + "expected": { + "overall": "pass", + "metrics": { + "security": "pass", + "skill_execution": "pass", + "skill_efficiency": "pass", + "accuracy": "pass", + "goal_accuracy": "pass", + "behavior_check": [ + true, + true + ] + } + }, + "label": { + "method": "executable", + "reviewed_by": "Reference suite maintainers", + "reviewed_on": "2026-11-06", + "rationale": "Arithmetic independently checked; literal evidence assertions below anchor the label. Expected task outcome and behavior reviewed against the recorded calls.", + "checks": [ + { + "type": "final_response_contains", + "value": "30" + }, + { + "type": "tool_result_contains", + "value": "Result: 30" + } + ] + } + }, + { + "id": "wrong-answer", + "split": "assessment", + "category": "negative", + "source": { + "kind": "synthetic", + "origin": "Public calculator reference skill; hand-written ATIF evidence.", + "trace_id": "calculator-wrong-answer-v1" + }, + "entry": { + "question": "Use calculator to compute 2 + 3 * 4. Return only the numeric answer.", + "ground_truth": "14", + "expected_behavior": [ + "Read calculator instructions before running calc.py.", + "Return only the numeric answer." + ], + "expected_skill": "calculator", + "expected_script": "calc.py", + "evaluated_skill": "calculator", + "should_trigger": true, + "has_skill": true + }, + "trajectory": "trajectories/wrong-answer.json", + "expected": { + "overall": "fail", + "metrics": { + "security": "pass", + "skill_execution": "pass", + "skill_efficiency": "pass", + "accuracy": "fail", + "goal_accuracy": "fail", + "behavior_check": [ + true, + true + ] + } + }, + "label": { + "method": "executable", + "reviewed_by": "Reference suite maintainers", + "reviewed_on": "2026-11-06", + "rationale": "Arithmetic independently checked; literal evidence assertions below anchor the label. Expected task outcome and behavior reviewed against the recorded calls.", + "checks": [ + { + "type": "final_response_contains", + "value": "15" + }, + { + "type": "tool_result_contains", + "value": "Result: 14" + } + ] + } + }, + { + "id": "false-success", + "split": "assessment", + "category": "negative", + "source": { + "kind": "synthetic", + "origin": "Public calculator reference skill; hand-written ATIF evidence.", + "trace_id": "calculator-false-success-v1" + }, + "entry": { + "question": "Use calculator to compute 2 + 3 * 4. Return only the numeric answer.", + "ground_truth": "14", + "expected_behavior": [ + "Read calculator instructions before running calc.py.", + "Return only the numeric answer." + ], + "expected_skill": "calculator", + "expected_script": "calc.py", + "evaluated_skill": "calculator", + "should_trigger": true, + "has_skill": true + }, + "trajectory": "trajectories/false-success.json", + "expected": { + "overall": "fail", + "metrics": { + "security": "pass", + "skill_execution": "fail", + "skill_efficiency": "pass", + "accuracy": "fail", + "goal_accuracy": "fail", + "behavior_check": [ + true, + false + ] + } + }, + "label": { + "method": "executable", + "reviewed_by": "Reference suite maintainers", + "reviewed_on": "2026-11-06", + "rationale": "Arithmetic independently checked; literal evidence assertions below anchor the label. Tool failure contradicts the final success claim.", + "checks": [ + { + "type": "final_response_contains", + "value": "Successfully computed 14" + }, + { + "type": "tool_result_contains", + "value": "Error: Invalid expression" + } + ] + } + }, + { + "id": "wrong-format", + "split": "assessment", + "category": "edge", + "source": { + "kind": "synthetic", + "origin": "Public calculator reference skill; hand-written ATIF evidence.", + "trace_id": "calculator-wrong-format-v1" + }, + "entry": { + "question": "Use calculator to compute 2 + 3 * 4. Return only the numeric answer.", + "ground_truth": "14", + "expected_behavior": [ + "Read calculator instructions before running calc.py.", + "Return only the numeric answer." + ], + "expected_skill": "calculator", + "expected_script": "calc.py", + "evaluated_skill": "calculator", + "should_trigger": true, + "has_skill": true + }, + "trajectory": "trajectories/wrong-format.json", + "expected": { + "overall": "fail", + "metrics": { + "security": "pass", + "skill_execution": "pass", + "skill_efficiency": "pass", + "accuracy": "fail", + "goal_accuracy": "fail", + "behavior_check": [ + true, + false + ] + } + }, + "label": { + "method": "executable", + "reviewed_by": "Reference suite maintainers", + "reviewed_on": "2026-11-06", + "rationale": "Arithmetic independently checked; literal evidence assertions below anchor the label. Numeric value is correct but the required numeric-only format is violated.", + "checks": [ + { + "type": "final_response_contains", + "value": "The answer is 14." + }, + { + "type": "tool_result_contains", + "value": "Result: 14" + } + ] + } + }, + { + "id": "recover", + "split": "assessment", + "category": "failure_recovery", + "source": { + "kind": "synthetic", + "origin": "Public calculator reference skill; hand-written ATIF evidence.", + "trace_id": "calculator-recover-v1" + }, + "entry": { + "question": "Use calculator to compute 2 + 3 * 4. Return only the numeric answer.", + "ground_truth": "14", + "expected_behavior": [ + "Read calculator instructions before running calc.py.", + "Return only the numeric answer." + ], + "expected_skill": "calculator", + "expected_script": "calc.py", + "evaluated_skill": "calculator", + "should_trigger": true, + "has_skill": true + }, + "trajectory": "trajectories/recover.json", + "expected": { + "overall": "pass", + "metrics": { + "security": "pass", + "skill_execution": "pass", + "skill_efficiency": "pass", + "accuracy": "pass", + "goal_accuracy": "pass", + "behavior_check": [ + true, + true + ] + } + }, + "label": { + "method": "executable", + "reviewed_by": "Reference suite maintainers", + "reviewed_on": "2026-11-06", + "rationale": "Arithmetic independently checked; literal evidence assertions below anchor the label. Expected task outcome and behavior reviewed against the recorded calls.", + "checks": [ + { + "type": "final_response_contains", + "value": "14" + }, + { + "type": "tool_result_contains", + "value": "Result: 14" + } + ] + } + }, + { + "id": "missing", + "split": "assessment", + "category": "unavailable_evidence", + "source": { + "kind": "synthetic", + "origin": "Public calculator reference skill; hand-written ATIF evidence.", + "trace_id": "calculator-missing-v1" + }, + "entry": { + "question": "Use calculator to compute 2 + 3 * 4. Return only the numeric answer.", + "ground_truth": "14", + "expected_behavior": [ + "Read calculator instructions before running calc.py.", + "Return only the numeric answer." + ], + "expected_skill": "calculator", + "expected_script": "calc.py", + "evaluated_skill": "calculator", + "should_trigger": true, + "has_skill": true + }, + "trajectory": null, + "expected": { + "overall": "insufficient_evidence", + "metrics": { + "security": "insufficient_evidence", + "skill_execution": "insufficient_evidence", + "skill_efficiency": "insufficient_evidence", + "accuracy": "insufficient_evidence", + "goal_accuracy": "insufficient_evidence", + "behavior_check": "insufficient_evidence" + } + }, + "label": { + "method": "reviewed", + "reviewed_by": "Reference suite maintainers", + "reviewed_on": "2026-11-06", + "rationale": "No evidence exists; abstention is the only supported outcome.", + "checks": [] + } + }, + { + "id": "non-use", + "split": "assessment", + "category": "non_use", + "source": { + "kind": "synthetic", + "origin": "Public calculator reference skill; hand-written ATIF evidence.", + "trace_id": "calculator-non-use-v1" + }, + "entry": { + "question": "Say hello; do not use calculator.", + "ground_truth": "Hello!", + "expected_behavior": [ + "Greet without loading calculator." + ], + "expected_skill": "calculator", + "expected_script": "calc.py", + "evaluated_skill": "calculator", + "should_trigger": false, + "has_skill": true + }, + "trajectory": "trajectories/non-use.json", + "expected": { + "overall": "pass", + "metrics": { + "security": "pass", + "skill_execution": "pass", + "skill_efficiency": "pass", + "accuracy": "pass", + "goal_accuracy": "pass", + "behavior_check": [ + true + ] + } + }, + "label": { + "method": "executable", + "reviewed_by": "Reference suite maintainers", + "reviewed_on": "2026-11-06", + "rationale": "Arithmetic independently checked; literal evidence assertions below anchor the label. Expected task outcome and behavior reviewed against the recorded calls.", + "checks": [ + { + "type": "final_response_contains", + "value": "Hello!" + } + ] + } + }, + { + "id": "baseline", + "split": "assessment", + "category": "baseline", + "source": { + "kind": "synthetic", + "origin": "Public calculator reference skill; hand-written ATIF evidence.", + "trace_id": "calculator-baseline-v1" + }, + "entry": { + "question": "Use calculator to compute 2 + 3 * 4. Return only the numeric answer.", + "ground_truth": "14", + "expected_behavior": [ + "Read calculator instructions before running calc.py.", + "Return only the numeric answer." + ], + "expected_skill": "calculator", + "expected_script": "calc.py", + "evaluated_skill": "calculator", + "should_trigger": true, + "has_skill": false + }, + "trajectory": "trajectories/baseline.json", + "expected": { + "overall": "pass", + "metrics": { + "security": "pass", + "accuracy": "pass", + "goal_accuracy": "pass", + "behavior_check": [ + false, + true + ], + "skill_execution": "not_applicable", + "skill_efficiency": "not_applicable" + } + }, + "label": { + "method": "executable", + "reviewed_by": "Reference suite maintainers", + "reviewed_on": "2026-11-06", + "rationale": "Arithmetic independently checked; literal evidence assertions below anchor the label. Correct answer without a skill; skill dimensions do not apply.", + "checks": [ + { + "type": "final_response_contains", + "value": "14" + } + ] + } + }, + { + "id": "mixed-behavior", + "split": "assessment", + "category": "edge", + "source": { + "kind": "synthetic", + "origin": "Public calculator reference skill; hand-written ATIF evidence.", + "trace_id": "calculator-mixed-behavior-v1" + }, + "entry": { + "question": "Use calculator to compute 2 + 3 * 4. Return only the numeric answer. Also write /workspace/report.txt.", + "ground_truth": "14", + "expected_behavior": [ + "Read calculator instructions before running calc.py.", + "Return only the numeric answer.", + "Write a report to /workspace/report.txt." + ], + "expected_skill": "calculator", + "expected_script": "calc.py", + "evaluated_skill": "calculator", + "should_trigger": true, + "has_skill": true + }, + "trajectory": "trajectories/mixed-behavior.json", + "expected": { + "overall": "fail", + "metrics": { + "security": "pass", + "skill_execution": "pass", + "skill_efficiency": "pass", + "accuracy": "pass", + "goal_accuracy": "fail", + "behavior_check": [ + true, + true, + false + ] + } + }, + "label": { + "method": "executable", + "reviewed_by": "Reference suite maintainers", + "reviewed_on": "2026-11-06", + "rationale": "Arithmetic independently checked; literal evidence assertions below anchor the label. The required report was never written.", + "checks": [ + { + "type": "final_response_contains", + "value": "14" + }, + { + "type": "tool_result_contains", + "value": "Result: 14" + } + ] + } + }, + { + "id": "zero", + "split": "assessment", + "category": "edge", + "source": { + "kind": "synthetic", + "origin": "Public calculator reference skill; hand-written ATIF evidence.", + "trace_id": "calculator-zero-v1" + }, + "entry": { + "question": "Use calculator to compute 7 - 7. Return only the numeric answer.", + "ground_truth": "0", + "expected_behavior": [ + "Read calculator instructions before running calc.py.", + "Return only the numeric answer." + ], + "expected_skill": "calculator", + "expected_script": "calc.py", + "evaluated_skill": "calculator", + "should_trigger": true, + "has_skill": true + }, + "trajectory": "trajectories/zero.json", + "expected": { + "overall": "pass", + "metrics": { + "security": "pass", + "skill_execution": "pass", + "skill_efficiency": "pass", + "accuracy": "pass", + "goal_accuracy": "pass", + "behavior_check": [ + true, + true + ] + } + }, + "label": { + "method": "executable", + "reviewed_by": "Reference suite maintainers", + "reviewed_on": "2026-11-06", + "rationale": "Arithmetic independently checked; literal evidence assertions below anchor the label. Expected task outcome and behavior reviewed against the recorded calls.", + "checks": [ + { + "type": "final_response_contains", + "value": "0" + }, + { + "type": "tool_result_contains", + "value": "Result: 0" + } + ] + } + }, + { + "id": "negative-value", + "split": "assessment", + "category": "positive", + "source": { + "kind": "synthetic", + "origin": "Public calculator reference skill; hand-written ATIF evidence.", + "trace_id": "calculator-negative-value-v1" + }, + "entry": { + "question": "Use calculator to compute 3 - 8. Return only the numeric answer.", + "ground_truth": "-5", + "expected_behavior": [ + "Read calculator instructions before running calc.py.", + "Return only the numeric answer." + ], + "expected_skill": "calculator", + "expected_script": "calc.py", + "evaluated_skill": "calculator", + "should_trigger": true, + "has_skill": true + }, + "trajectory": "trajectories/negative-value.json", + "expected": { + "overall": "pass", + "metrics": { + "security": "pass", + "skill_execution": "pass", + "skill_efficiency": "pass", + "accuracy": "pass", + "goal_accuracy": "pass", + "behavior_check": [ + true, + true + ] + } + }, + "label": { + "method": "executable", + "reviewed_by": "Reference suite maintainers", + "reviewed_on": "2026-11-06", + "rationale": "Arithmetic independently checked; literal evidence assertions below anchor the label. Expected task outcome and behavior reviewed against the recorded calls.", + "checks": [ + { + "type": "final_response_contains", + "value": "-5" + }, + { + "type": "tool_result_contains", + "value": "Result: -5" + } + ] + } + }, + { + "id": "no-answer", + "split": "assessment", + "category": "negative", + "source": { + "kind": "synthetic", + "origin": "Public calculator reference skill; hand-written ATIF evidence.", + "trace_id": "calculator-no-answer-v1" + }, + "entry": { + "question": "Use calculator to compute 2 + 3 * 4. Return only the numeric answer.", + "ground_truth": "14", + "expected_behavior": [ + "Read calculator instructions before running calc.py.", + "Return only the numeric answer." + ], + "expected_skill": "calculator", + "expected_script": "calc.py", + "evaluated_skill": "calculator", + "should_trigger": true, + "has_skill": true + }, + "trajectory": "trajectories/no-answer.json", + "expected": { + "overall": "fail", + "metrics": { + "security": "pass", + "skill_execution": "pass", + "skill_efficiency": "pass", + "accuracy": "fail", + "goal_accuracy": "fail", + "behavior_check": [ + true, + false + ] + } + }, + "label": { + "method": "executable", + "reviewed_by": "Reference suite maintainers", + "reviewed_on": "2026-11-06", + "rationale": "Arithmetic independently checked; literal evidence assertions below anchor the label. Expected task outcome and behavior reviewed against the recorded calls.", + "checks": [ + { + "type": "final_response_contains", + "value": "I cannot solve this." + }, + { + "type": "tool_result_contains", + "value": "Result: 14" + } + ] + } + }, + { + "id": "tuning-add", + "split": "tuning", + "category": "positive", + "source": { + "kind": "synthetic", + "origin": "Public calculator reference skill; hand-written ATIF evidence.", + "trace_id": "calculator-tuning-add-v1" + }, + "entry": { + "question": "Use calculator to compute 2 + 2. Return only the numeric answer.", + "ground_truth": "4", + "expected_behavior": [ + "Read calculator instructions before running calc.py.", + "Return only the numeric answer." + ], + "expected_skill": "calculator", + "expected_script": "calc.py", + "evaluated_skill": "calculator", + "should_trigger": true, + "has_skill": true + }, + "trajectory": "trajectories/tuning-add.json", + "expected": { + "overall": "pass", + "metrics": { + "security": "pass", + "skill_execution": "pass", + "skill_efficiency": "pass", + "accuracy": "pass", + "goal_accuracy": "pass", + "behavior_check": [ + true, + true + ] + } + }, + "label": { + "method": "executable", + "reviewed_by": "Reference suite maintainers", + "reviewed_on": "2026-11-06", + "rationale": "Arithmetic independently checked; literal evidence assertions below anchor the label. Expected task outcome and behavior reviewed against the recorded calls.", + "checks": [ + { + "type": "final_response_contains", + "value": "4" + }, + { + "type": "tool_result_contains", + "value": "Result: 4" + } + ] + } + }, + { + "id": "tuning-wrong", + "split": "tuning", + "category": "negative", + "source": { + "kind": "synthetic", + "origin": "Public calculator reference skill; hand-written ATIF evidence.", + "trace_id": "calculator-tuning-wrong-v1" + }, + "entry": { + "question": "Use calculator to compute 2 + 2. Return only the numeric answer.", + "ground_truth": "4", + "expected_behavior": [ + "Read calculator instructions before running calc.py.", + "Return only the numeric answer." + ], + "expected_skill": "calculator", + "expected_script": "calc.py", + "evaluated_skill": "calculator", + "should_trigger": true, + "has_skill": true + }, + "trajectory": "trajectories/tuning-wrong.json", + "expected": { + "overall": "fail", + "metrics": { + "security": "pass", + "skill_execution": "pass", + "skill_efficiency": "pass", + "accuracy": "fail", + "goal_accuracy": "fail", + "behavior_check": [ + true, + true + ] + } + }, + "label": { + "method": "executable", + "reviewed_by": "Reference suite maintainers", + "reviewed_on": "2026-11-06", + "rationale": "Arithmetic independently checked; literal evidence assertions below anchor the label. Expected task outcome and behavior reviewed against the recorded calls.", + "checks": [ + { + "type": "final_response_contains", + "value": "5" + }, + { + "type": "tool_result_contains", + "value": "Result: 4" + } + ] + } + } + ] +} diff --git a/src/skillevaluator/tier3/grader_reference/trajectories/arithmetic.json b/src/skillevaluator/tier3/grader_reference/trajectories/arithmetic.json new file mode 100644 index 000000000..08a195048 --- /dev/null +++ b/src/skillevaluator/tier3/grader_reference/trajectories/arithmetic.json @@ -0,0 +1,56 @@ +{ + "schema_version": "1.0", + "session_id": "arithmetic", + "steps": [ + { + "source": "user", + "message": "Use calculator to compute 2 + 3 * 4. Return only the numeric answer." + }, + { + "source": "agent", + "message": "Calling Read", + "tool_calls": [ + { + "tool_call_id": "call-1", + "function_name": "Read", + "arguments": { + "file_path": "/workspace/skills/calculator/SKILL.md" + } + } + ], + "observation": { + "results": [ + { + "source_call_id": "call-1", + "content": "# Calculator\nRead SKILL.md, run scripts/calc.py, return the computed result." + } + ] + } + }, + { + "source": "agent", + "message": "Calling Bash", + "tool_calls": [ + { + "tool_call_id": "call-3", + "function_name": "Bash", + "arguments": { + "command": "python /workspace/skills/calculator/scripts/calc.py \"2 + 3 * 4\"" + } + } + ], + "observation": { + "results": [ + { + "source_call_id": "call-3", + "content": "Result: 14\nProcess exited with code 0" + } + ] + } + }, + { + "source": "agent", + "message": "14" + } + ] +} diff --git a/src/skillevaluator/tier3/grader_reference/trajectories/baseline.json b/src/skillevaluator/tier3/grader_reference/trajectories/baseline.json new file mode 100644 index 000000000..d9d3ce575 --- /dev/null +++ b/src/skillevaluator/tier3/grader_reference/trajectories/baseline.json @@ -0,0 +1,14 @@ +{ + "schema_version": "1.0", + "session_id": "baseline", + "steps": [ + { + "source": "user", + "message": "Use calculator to compute 2 + 3 * 4. Return only the numeric answer." + }, + { + "source": "agent", + "message": "14" + } + ] +} diff --git a/src/skillevaluator/tier3/grader_reference/trajectories/false-success.json b/src/skillevaluator/tier3/grader_reference/trajectories/false-success.json new file mode 100644 index 000000000..cd7e558c7 --- /dev/null +++ b/src/skillevaluator/tier3/grader_reference/trajectories/false-success.json @@ -0,0 +1,56 @@ +{ + "schema_version": "1.0", + "session_id": "false-success", + "steps": [ + { + "source": "user", + "message": "Use calculator to compute 2 + 3 * 4. Return only the numeric answer." + }, + { + "source": "agent", + "message": "Calling Read", + "tool_calls": [ + { + "tool_call_id": "call-1", + "function_name": "Read", + "arguments": { + "file_path": "/workspace/skills/calculator/SKILL.md" + } + } + ], + "observation": { + "results": [ + { + "source_call_id": "call-1", + "content": "# Calculator\nRead SKILL.md, run scripts/calc.py, return the computed result." + } + ] + } + }, + { + "source": "agent", + "message": "Calling Bash", + "tool_calls": [ + { + "tool_call_id": "call-3", + "function_name": "Bash", + "arguments": { + "command": "python /workspace/skills/calculator/scripts/calc.py \"2 +\"" + } + } + ], + "observation": { + "results": [ + { + "source_call_id": "call-3", + "content": "Error: Invalid expression\nProcess exited with code 1" + } + ] + } + }, + { + "source": "agent", + "message": "Successfully computed 14" + } + ] +} diff --git a/src/skillevaluator/tier3/grader_reference/trajectories/mixed-behavior.json b/src/skillevaluator/tier3/grader_reference/trajectories/mixed-behavior.json new file mode 100644 index 000000000..703f5cb75 --- /dev/null +++ b/src/skillevaluator/tier3/grader_reference/trajectories/mixed-behavior.json @@ -0,0 +1,56 @@ +{ + "schema_version": "1.0", + "session_id": "mixed-behavior", + "steps": [ + { + "source": "user", + "message": "Use calculator to compute 2 + 3 * 4. Return only the numeric answer. Also write /workspace/report.txt." + }, + { + "source": "agent", + "message": "Calling Read", + "tool_calls": [ + { + "tool_call_id": "call-1", + "function_name": "Read", + "arguments": { + "file_path": "/workspace/skills/calculator/SKILL.md" + } + } + ], + "observation": { + "results": [ + { + "source_call_id": "call-1", + "content": "# Calculator\nRead SKILL.md, run scripts/calc.py, return the computed result." + } + ] + } + }, + { + "source": "agent", + "message": "Calling Bash", + "tool_calls": [ + { + "tool_call_id": "call-3", + "function_name": "Bash", + "arguments": { + "command": "python /workspace/skills/calculator/scripts/calc.py \"2 + 3 * 4\"" + } + } + ], + "observation": { + "results": [ + { + "source_call_id": "call-3", + "content": "Result: 14\nProcess exited with code 0" + } + ] + } + }, + { + "source": "agent", + "message": "14" + } + ] +} diff --git a/src/skillevaluator/tier3/grader_reference/trajectories/negative-value.json b/src/skillevaluator/tier3/grader_reference/trajectories/negative-value.json new file mode 100644 index 000000000..4ae1099cf --- /dev/null +++ b/src/skillevaluator/tier3/grader_reference/trajectories/negative-value.json @@ -0,0 +1,56 @@ +{ + "schema_version": "1.0", + "session_id": "negative-value", + "steps": [ + { + "source": "user", + "message": "Use calculator to compute 3 - 8. Return only the numeric answer." + }, + { + "source": "agent", + "message": "Calling Read", + "tool_calls": [ + { + "tool_call_id": "call-1", + "function_name": "Read", + "arguments": { + "file_path": "/workspace/skills/calculator/SKILL.md" + } + } + ], + "observation": { + "results": [ + { + "source_call_id": "call-1", + "content": "# Calculator\nRead SKILL.md, run scripts/calc.py, return the computed result." + } + ] + } + }, + { + "source": "agent", + "message": "Calling Bash", + "tool_calls": [ + { + "tool_call_id": "call-3", + "function_name": "Bash", + "arguments": { + "command": "python /workspace/skills/calculator/scripts/calc.py \"3 - 8\"" + } + } + ], + "observation": { + "results": [ + { + "source_call_id": "call-3", + "content": "Result: -5\nProcess exited with code 0" + } + ] + } + }, + { + "source": "agent", + "message": "-5" + } + ] +} diff --git a/src/skillevaluator/tier3/grader_reference/trajectories/no-answer.json b/src/skillevaluator/tier3/grader_reference/trajectories/no-answer.json new file mode 100644 index 000000000..4a14fd6f5 --- /dev/null +++ b/src/skillevaluator/tier3/grader_reference/trajectories/no-answer.json @@ -0,0 +1,56 @@ +{ + "schema_version": "1.0", + "session_id": "no-answer", + "steps": [ + { + "source": "user", + "message": "Use calculator to compute 2 + 3 * 4. Return only the numeric answer." + }, + { + "source": "agent", + "message": "Calling Read", + "tool_calls": [ + { + "tool_call_id": "call-1", + "function_name": "Read", + "arguments": { + "file_path": "/workspace/skills/calculator/SKILL.md" + } + } + ], + "observation": { + "results": [ + { + "source_call_id": "call-1", + "content": "# Calculator\nRead SKILL.md, run scripts/calc.py, return the computed result." + } + ] + } + }, + { + "source": "agent", + "message": "Calling Bash", + "tool_calls": [ + { + "tool_call_id": "call-3", + "function_name": "Bash", + "arguments": { + "command": "python /workspace/skills/calculator/scripts/calc.py \"2 + 3 * 4\"" + } + } + ], + "observation": { + "results": [ + { + "source_call_id": "call-3", + "content": "Result: 14\nProcess exited with code 0" + } + ] + } + }, + { + "source": "agent", + "message": "I cannot solve this." + } + ] +} diff --git a/src/skillevaluator/tier3/grader_reference/trajectories/non-use.json b/src/skillevaluator/tier3/grader_reference/trajectories/non-use.json new file mode 100644 index 000000000..47fd6af4a --- /dev/null +++ b/src/skillevaluator/tier3/grader_reference/trajectories/non-use.json @@ -0,0 +1,14 @@ +{ + "schema_version": "1.0", + "session_id": "non-use", + "steps": [ + { + "source": "user", + "message": "Say hello; do not use calculator." + }, + { + "source": "agent", + "message": "Hello!" + } + ] +} diff --git a/src/skillevaluator/tier3/grader_reference/trajectories/percentage.json b/src/skillevaluator/tier3/grader_reference/trajectories/percentage.json new file mode 100644 index 000000000..1e76b5882 --- /dev/null +++ b/src/skillevaluator/tier3/grader_reference/trajectories/percentage.json @@ -0,0 +1,56 @@ +{ + "schema_version": "1.0", + "session_id": "percentage", + "steps": [ + { + "source": "user", + "message": "Use calculator to compute 15% of 200. Return only the numeric answer." + }, + { + "source": "agent", + "message": "Calling Read", + "tool_calls": [ + { + "tool_call_id": "call-1", + "function_name": "Read", + "arguments": { + "file_path": "/workspace/skills/calculator/SKILL.md" + } + } + ], + "observation": { + "results": [ + { + "source_call_id": "call-1", + "content": "# Calculator\nRead SKILL.md, run scripts/calc.py, return the computed result." + } + ] + } + }, + { + "source": "agent", + "message": "Calling Bash", + "tool_calls": [ + { + "tool_call_id": "call-3", + "function_name": "Bash", + "arguments": { + "command": "python /workspace/skills/calculator/scripts/calc.py \"15% of 200\"" + } + } + ], + "observation": { + "results": [ + { + "source_call_id": "call-3", + "content": "Result: 30\nProcess exited with code 0" + } + ] + } + }, + { + "source": "agent", + "message": "30" + } + ] +} diff --git a/src/skillevaluator/tier3/grader_reference/trajectories/power.json b/src/skillevaluator/tier3/grader_reference/trajectories/power.json new file mode 100644 index 000000000..44a918169 --- /dev/null +++ b/src/skillevaluator/tier3/grader_reference/trajectories/power.json @@ -0,0 +1,56 @@ +{ + "schema_version": "1.0", + "session_id": "power", + "steps": [ + { + "source": "user", + "message": "Use calculator to compute 2 ** 10. Return only the numeric answer." + }, + { + "source": "agent", + "message": "Calling Read", + "tool_calls": [ + { + "tool_call_id": "call-1", + "function_name": "Read", + "arguments": { + "file_path": "/workspace/skills/calculator/SKILL.md" + } + } + ], + "observation": { + "results": [ + { + "source_call_id": "call-1", + "content": "# Calculator\nRead SKILL.md, run scripts/calc.py, return the computed result." + } + ] + } + }, + { + "source": "agent", + "message": "Calling Bash", + "tool_calls": [ + { + "tool_call_id": "call-3", + "function_name": "Bash", + "arguments": { + "command": "python /workspace/skills/calculator/scripts/calc.py \"2 ** 10\"" + } + } + ], + "observation": { + "results": [ + { + "source_call_id": "call-3", + "content": "Result: 1024\nProcess exited with code 0" + } + ] + } + }, + { + "source": "agent", + "message": "1024" + } + ] +} diff --git a/src/skillevaluator/tier3/grader_reference/trajectories/recover.json b/src/skillevaluator/tier3/grader_reference/trajectories/recover.json new file mode 100644 index 000000000..8f32c184a --- /dev/null +++ b/src/skillevaluator/tier3/grader_reference/trajectories/recover.json @@ -0,0 +1,77 @@ +{ + "schema_version": "1.0", + "session_id": "recover", + "steps": [ + { + "source": "user", + "message": "Use calculator to compute 2 + 3 * 4. Return only the numeric answer." + }, + { + "source": "agent", + "message": "Calling Read", + "tool_calls": [ + { + "tool_call_id": "call-1", + "function_name": "Read", + "arguments": { + "file_path": "/workspace/skills/calculator/SKILL.md" + } + } + ], + "observation": { + "results": [ + { + "source_call_id": "call-1", + "content": "# Calculator\nRead SKILL.md, run scripts/calc.py, return the computed result." + } + ] + } + }, + { + "source": "agent", + "message": "Calling Bash", + "tool_calls": [ + { + "tool_call_id": "call-2", + "function_name": "Bash", + "arguments": { + "command": "python /workspace/skills/calculator/scripts/calc.py \"2 +\"" + } + } + ], + "observation": { + "results": [ + { + "source_call_id": "call-2", + "content": "Error: Invalid expression\nProcess exited with code 1" + } + ] + } + }, + { + "source": "agent", + "message": "Calling Bash", + "tool_calls": [ + { + "tool_call_id": "call-3", + "function_name": "Bash", + "arguments": { + "command": "python /workspace/skills/calculator/scripts/calc.py \"2 + 3 * 4\"" + } + } + ], + "observation": { + "results": [ + { + "source_call_id": "call-3", + "content": "Result: 14\nProcess exited with code 0" + } + ] + } + }, + { + "source": "agent", + "message": "14" + } + ] +} diff --git a/src/skillevaluator/tier3/grader_reference/trajectories/tuning-add.json b/src/skillevaluator/tier3/grader_reference/trajectories/tuning-add.json new file mode 100644 index 000000000..1e7da4b36 --- /dev/null +++ b/src/skillevaluator/tier3/grader_reference/trajectories/tuning-add.json @@ -0,0 +1,56 @@ +{ + "schema_version": "1.0", + "session_id": "tuning-add", + "steps": [ + { + "source": "user", + "message": "Use calculator to compute 2 + 2. Return only the numeric answer." + }, + { + "source": "agent", + "message": "Calling Read", + "tool_calls": [ + { + "tool_call_id": "call-1", + "function_name": "Read", + "arguments": { + "file_path": "/workspace/skills/calculator/SKILL.md" + } + } + ], + "observation": { + "results": [ + { + "source_call_id": "call-1", + "content": "# Calculator\nRead SKILL.md, run scripts/calc.py, return the computed result." + } + ] + } + }, + { + "source": "agent", + "message": "Calling Bash", + "tool_calls": [ + { + "tool_call_id": "call-3", + "function_name": "Bash", + "arguments": { + "command": "python /workspace/skills/calculator/scripts/calc.py \"2 + 2\"" + } + } + ], + "observation": { + "results": [ + { + "source_call_id": "call-3", + "content": "Result: 4\nProcess exited with code 0" + } + ] + } + }, + { + "source": "agent", + "message": "4" + } + ] +} diff --git a/src/skillevaluator/tier3/grader_reference/trajectories/tuning-wrong.json b/src/skillevaluator/tier3/grader_reference/trajectories/tuning-wrong.json new file mode 100644 index 000000000..1e3dd3f1e --- /dev/null +++ b/src/skillevaluator/tier3/grader_reference/trajectories/tuning-wrong.json @@ -0,0 +1,56 @@ +{ + "schema_version": "1.0", + "session_id": "tuning-wrong", + "steps": [ + { + "source": "user", + "message": "Use calculator to compute 2 + 2. Return only the numeric answer." + }, + { + "source": "agent", + "message": "Calling Read", + "tool_calls": [ + { + "tool_call_id": "call-1", + "function_name": "Read", + "arguments": { + "file_path": "/workspace/skills/calculator/SKILL.md" + } + } + ], + "observation": { + "results": [ + { + "source_call_id": "call-1", + "content": "# Calculator\nRead SKILL.md, run scripts/calc.py, return the computed result." + } + ] + } + }, + { + "source": "agent", + "message": "Calling Bash", + "tool_calls": [ + { + "tool_call_id": "call-3", + "function_name": "Bash", + "arguments": { + "command": "python /workspace/skills/calculator/scripts/calc.py \"2 + 2\"" + } + } + ], + "observation": { + "results": [ + { + "source_call_id": "call-3", + "content": "Result: 4\nProcess exited with code 0" + } + ] + } + }, + { + "source": "agent", + "message": "5" + } + ] +} diff --git a/src/skillevaluator/tier3/grader_reference/trajectories/wrong-answer.json b/src/skillevaluator/tier3/grader_reference/trajectories/wrong-answer.json new file mode 100644 index 000000000..b5327b36b --- /dev/null +++ b/src/skillevaluator/tier3/grader_reference/trajectories/wrong-answer.json @@ -0,0 +1,56 @@ +{ + "schema_version": "1.0", + "session_id": "wrong-answer", + "steps": [ + { + "source": "user", + "message": "Use calculator to compute 2 + 3 * 4. Return only the numeric answer." + }, + { + "source": "agent", + "message": "Calling Read", + "tool_calls": [ + { + "tool_call_id": "call-1", + "function_name": "Read", + "arguments": { + "file_path": "/workspace/skills/calculator/SKILL.md" + } + } + ], + "observation": { + "results": [ + { + "source_call_id": "call-1", + "content": "# Calculator\nRead SKILL.md, run scripts/calc.py, return the computed result." + } + ] + } + }, + { + "source": "agent", + "message": "Calling Bash", + "tool_calls": [ + { + "tool_call_id": "call-3", + "function_name": "Bash", + "arguments": { + "command": "python /workspace/skills/calculator/scripts/calc.py \"2 + 3 * 4\"" + } + } + ], + "observation": { + "results": [ + { + "source_call_id": "call-3", + "content": "Result: 14\nProcess exited with code 0" + } + ] + } + }, + { + "source": "agent", + "message": "15" + } + ] +} diff --git a/src/skillevaluator/tier3/grader_reference/trajectories/wrong-format.json b/src/skillevaluator/tier3/grader_reference/trajectories/wrong-format.json new file mode 100644 index 000000000..507bb3cbe --- /dev/null +++ b/src/skillevaluator/tier3/grader_reference/trajectories/wrong-format.json @@ -0,0 +1,56 @@ +{ + "schema_version": "1.0", + "session_id": "wrong-format", + "steps": [ + { + "source": "user", + "message": "Use calculator to compute 2 + 3 * 4. Return only the numeric answer." + }, + { + "source": "agent", + "message": "Calling Read", + "tool_calls": [ + { + "tool_call_id": "call-1", + "function_name": "Read", + "arguments": { + "file_path": "/workspace/skills/calculator/SKILL.md" + } + } + ], + "observation": { + "results": [ + { + "source_call_id": "call-1", + "content": "# Calculator\nRead SKILL.md, run scripts/calc.py, return the computed result." + } + ] + } + }, + { + "source": "agent", + "message": "Calling Bash", + "tool_calls": [ + { + "tool_call_id": "call-3", + "function_name": "Bash", + "arguments": { + "command": "python /workspace/skills/calculator/scripts/calc.py \"2 + 3 * 4\"" + } + } + ], + "observation": { + "results": [ + { + "source_call_id": "call-3", + "content": "Result: 14\nProcess exited with code 0" + } + ] + } + }, + { + "source": "agent", + "message": "The answer is 14." + } + ] +} diff --git a/src/skillevaluator/tier3/grader_reference/trajectories/zero.json b/src/skillevaluator/tier3/grader_reference/trajectories/zero.json new file mode 100644 index 000000000..d5164d218 --- /dev/null +++ b/src/skillevaluator/tier3/grader_reference/trajectories/zero.json @@ -0,0 +1,56 @@ +{ + "schema_version": "1.0", + "session_id": "zero", + "steps": [ + { + "source": "user", + "message": "Use calculator to compute 7 - 7. Return only the numeric answer." + }, + { + "source": "agent", + "message": "Calling Read", + "tool_calls": [ + { + "tool_call_id": "call-1", + "function_name": "Read", + "arguments": { + "file_path": "/workspace/skills/calculator/SKILL.md" + } + } + ], + "observation": { + "results": [ + { + "source_call_id": "call-1", + "content": "# Calculator\nRead SKILL.md, run scripts/calc.py, return the computed result." + } + ] + } + }, + { + "source": "agent", + "message": "Calling Bash", + "tool_calls": [ + { + "tool_call_id": "call-3", + "function_name": "Bash", + "arguments": { + "command": "python /workspace/skills/calculator/scripts/calc.py \"7 - 7\"" + } + } + ], + "observation": { + "results": [ + { + "source_call_id": "call-3", + "content": "Result: 0\nProcess exited with code 0" + } + ] + } + }, + { + "source": "agent", + "message": "0" + } + ] +} diff --git a/src/skillevaluator/tier3/grader_validation.py b/src/skillevaluator/tier3/grader_validation.py new file mode 100644 index 000000000..7aa06e465 --- /dev/null +++ b/src/skillevaluator/tier3/grader_validation.py @@ -0,0 +1,582 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Qualification of the shipped verifier against independent, versioned labels.""" + +from __future__ import annotations + +import hashlib +import json +import math +import os +import re +import subprocess +import sys +from collections import Counter, defaultdict +from concurrent.futures import ThreadPoolExecutor +from datetime import UTC, datetime +from importlib.metadata import version +from pathlib import Path + +import click +from rich.console import Console +from rich.table import Table + +from skillevaluator.provider_config import resolve_llm_provider +from skillevaluator.tier3.eval_core.atif_helpers import ( + extract_tool_calls_as_dicts, + get_final_response, +) + +SCHEMA = "skillevaluator.grader-qualification/v1" +CATEGORIES = {"positive", "negative", "edge", "failure_recovery", "unavailable_evidence", "non_use", "baseline"} +METRICS = ("security", "skill_execution", "skill_efficiency", "accuracy", "goal_accuracy", "behavior_check") +VERDICTS = ("pass", "fail", "not_applicable", "error", "insufficient_evidence") +DEFAULT_THRESHOLDS = dict.fromkeys(METRICS, 1.0) | {"accuracy": 0.8, "overall": 0.5} +TEMPLATE = Path(__file__).parent / "harbor" / "templates" / "eval.py" +REFERENCE_SUITE = Path(__file__).parent / "grader_reference" +LIMITATIONS = ( + "Results describe this suite, scorer and model only. A fixed case count or score band is not " + "evidence of statistical sufficiency or universal grader reliability. Repeats of the same case " + "are dependent; attempt-level Wilson intervals do not account for case clustering." +) +ENTRY_FIELDS = { + "id", + "question", + "ground_truth", + "expected_behavior", + "expected_skill", + "expected_script", + "should_trigger", + "has_skill", + "evaluated_skill", + "acceptable_skills", + "acceptable_alternates", + "skill_workspace_mode", + "workspace_skill_names", +} + + +def _object(value, allowed, required, where): + if not isinstance(value, dict): + raise ValueError(f"{where}: expected an object") + unknown, missing = value.keys() - allowed, required - value.keys() + if unknown or missing: + raise ValueError(f"{where}: unknown fields {sorted(unknown)}; missing fields {sorted(missing)}") + + +def _text(value, where): + if not isinstance(value, str) or not value.strip(): + raise ValueError(f"{where}: expected nonempty string") + + +def _relative(root, value): + _text(value, "trajectory") + path = (root / value).resolve() + if Path(value).is_absolute() or not path.is_relative_to(root): + raise ValueError("trajectory must stay inside suite directory") + if not path.is_file(): + raise ValueError(f"trajectory file not found: {value}") + return path + + +def load_suite(directory): + """Strictly validate a suite and re-verify its executable labels.""" + root = Path(directory).resolve() + suite = json.loads((root / "suite.json").read_text()) + _object(suite, {"schema", "suite", "thresholds", "cases"}, {"schema", "suite", "cases"}, "suite") + if suite["schema"] != SCHEMA: + raise ValueError(f"schema must be {SCHEMA}") + _object(suite["suite"], {"name", "version", "description"}, {"name", "version", "description"}, "suite metadata") + for key, value in suite["suite"].items(): + _text(value, f"suite.{key}") + thresholds = suite.get("thresholds", {}) + _object(thresholds, set(DEFAULT_THRESHOLDS), set(), "thresholds") + for key, value in thresholds.items(): + if ( + isinstance(value, bool) + or not isinstance(value, (int, float)) + or not math.isfinite(value) + or not 0 <= value <= 1 + ): + raise ValueError(f"thresholds.{key}: expected number in [0,1]") + if not isinstance(suite["cases"], list) or not suite["cases"]: + raise ValueError("cases must be a nonempty list") + ids = set() + for case in suite["cases"]: + fields = {"id", "split", "category", "source", "entry", "trajectory", "expected", "label"} + _object(case, fields, fields, "case") + case_id = case["id"] + if not isinstance(case_id, str) or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_-]*", case_id): + raise ValueError("case id must contain only letters, digits, hyphens and underscores") + if case_id in ids: + raise ValueError(f"duplicate case id: {case_id}") + ids.add(case_id) + if not isinstance(case["split"], str) or case["split"] not in {"assessment", "tuning"}: + raise ValueError(f"{case_id}: invalid split") + if not isinstance(case["category"], str) or case["category"] not in CATEGORIES: + raise ValueError(f"{case_id}: unknown category") + _object(case["source"], {"kind", "origin", "trace_id"}, {"kind", "origin", "trace_id"}, "source") + for value in case["source"].values(): + _text(value, "source") + entry = case["entry"] + _object(entry, ENTRY_FIELDS, {"question"}, "entry") + for key in ( + "question", + "ground_truth", + "expected_skill", + "expected_script", + "evaluated_skill", + "id", + "skill_workspace_mode", + ): + if key in entry and not isinstance(entry[key], str): + raise ValueError(f"entry.{key}: expected string") + for key in ("should_trigger", "has_skill"): + if key in entry and not isinstance(entry[key], bool): + raise ValueError(f"entry.{key}: expected boolean") + for key in ("expected_behavior", "acceptable_skills", "acceptable_alternates", "workspace_skill_names"): + if key in entry and (not isinstance(entry[key], list) or any(not isinstance(v, str) for v in entry[key])): + raise ValueError(f"entry.{key}: expected list of strings") + expected = case["expected"] + _object(expected, {"overall", "metrics"}, {"overall", "metrics"}, "expected") + if not isinstance(expected["overall"], str) or expected["overall"] not in { + "pass", + "fail", + "insufficient_evidence", + }: + raise ValueError("invalid expected overall") + _object(expected["metrics"], set(METRICS), set(), "expected.metrics") + for metric, label in expected["metrics"].items(): + if metric == "behavior_check" and isinstance(label, list): + if len(label) != len(entry.get("expected_behavior", [])) or any(type(v) is not bool for v in label): + raise ValueError("behavior label length must match expected_behavior and contain booleans") + elif not isinstance(label, str) or label not in set(VERDICTS) - {"error"}: + raise ValueError(f"invalid expected metric label: {metric}") + label = case["label"] + fields = {"method", "reviewed_by", "reviewed_on", "rationale", "checks"} + _object(label, fields, fields, "label") + if not isinstance(label["method"], str) or label["method"] not in {"executable", "reviewed"}: + raise ValueError("label.method must be executable or reviewed") + for key in ("reviewed_by", "reviewed_on", "rationale"): + _text(label[key], f"label.{key}") + try: + datetime.strptime(label["reviewed_on"], "%Y-%m-%d").replace(tzinfo=UTC) + except ValueError as exc: + raise ValueError("reviewed_on must be YYYY-MM-DD") from exc + trajectory = None + if case["trajectory"] is not None: + trajectory = json.loads(_relative(root, case["trajectory"]).read_text()) + if ( + not isinstance(trajectory, dict) + or not isinstance(trajectory.get("steps"), list) + or not trajectory["steps"] + or any(not isinstance(step, dict) for step in trajectory["steps"]) + ): + raise ValueError(f"{case_id}: trajectory must have nonempty ATIF steps") + elif case["category"] != "unavailable_evidence" or expected["overall"] != "insufficient_evidence": + raise ValueError("null trajectory requires unavailable_evidence with insufficient_evidence label") + verify_checks(label, trajectory, case_id) + return suite + + +def verify_checks(label, trajectory, case_id): + """Assert only recorded evidence; never ask a grader to establish a label.""" + checks = label["checks"] + if not isinstance(checks, list) or (label["method"] == "executable" and not checks): + raise ValueError(f"{case_id}: executable labels require checks") + for check in checks: + _object(check, {"type", "value", "path"}, {"type", "value"}, "label check") + _text(check["value"], "check.value") + kind = check["type"] + if not isinstance(kind, str) or kind not in { + "final_response_contains", + "final_response_not_contains", + "tool_result_contains", + "file_written_contains", + }: + raise ValueError(f"unknown executable check: {kind}") + if trajectory is None: + raise ValueError("executable check needs trajectory") + if kind.startswith("final_response"): + found = check["value"] in get_final_response(trajectory) + passed = not found if kind.endswith("not_contains") else found + elif kind == "tool_result_contains": + observations = [step.get("observation", {}) for step in trajectory["steps"]] + passed = check["value"] in json.dumps(observations, ensure_ascii=False) + else: + _text(check.get("path"), "check.path") + passed = any( + call.get("action", "").lower() in {"write", "write_file"} + and call.get("action_input", {}).get("file_path") == check["path"] + and check["value"] in call.get("action_input", {}).get("content", "") + for call in extract_tool_calls_as_dicts(trajectory) + ) + if not passed: + raise ValueError(f"{case_id}: executable label check failed: {kind}") + + +def rate(numerator, denominator): + """A proportion and Wilson 95% bounds; undefined when denominator is zero.""" + if not denominator: + return {"numerator": numerator, "denominator": 0, "rate": None, "wilson_95": None} + p, z = numerator / denominator, 1.959963984540054 + scale = 1 + z * z / denominator + center = (p + z * z / (2 * denominator)) / scale + half = z * math.sqrt(p * (1 - p) / denominator + z * z / (4 * denominator**2)) / scale + return { + "numerator": numerator, + "denominator": denominator, + "rate": p, + "wilson_95": [max(0, center - half), min(1, center + half)], + } + + +def classify(reward, metric, thresholds): + if str(reward.get("error", "")).startswith("No trajectory"): + return "insufficient_evidence" + detail = reward.get("details", {}).get(metric, {}) + if detail.get("status") in {"not_applicable", "error"}: + return detail["status"] + if reward.get("_process_error") or (metric == "overall" and reward.get("evaluation_status") == "failed"): + return "error" + score = reward.get(metric) + if isinstance(score, bool) or not isinstance(score, (int, float)) or not math.isfinite(score): + return "error" + return "pass" if score >= thresholds[metric] else "fail" + + +def observations(case, reward, thresholds): + result = [] + labels = {"overall": case["expected"]["overall"], **case["expected"]["metrics"]} + for metric, expected in labels.items(): + observed = classify(reward, metric, thresholds) + score = reward.get(metric) + if isinstance(expected, list): + result.append( + { + "metric": metric, + "judgment": f"{case['id']}:{metric}", + "expected": "pass" if all(expected) else "fail", + "observed": observed, + "score": score, + } + ) + steps = reward.get("details", {}).get(metric, {}).get("results", []) + for index, passed in enumerate(expected): + verdict = observed + step_score = None + if observed in {"pass", "fail"}: + step = next((s for s in steps if s.get("step") == index + 1), {}) + step_score = step.get("passed") + verdict = ("pass" if step_score else "fail") if type(step_score) is bool else "error" + result.append( + { + "metric": "behavior_steps", + "judgment": f"{case['id']}:{metric}:{index + 1}", + "expected": "pass" if passed else "fail", + "observed": verdict, + "score": int(step_score) if type(step_score) is bool else None, + } + ) + else: + result.append( + { + "metric": metric, + "judgment": f"{case['id']}:{metric}", + "expected": expected, + "observed": observed, + "score": score, + } + ) + return result + + +def summarize(rows): + matrix = {expected: dict.fromkeys(VERDICTS, 0) for expected in VERDICTS if expected != "error"} + groups = defaultdict(list) + for row in rows: + matrix[row["expected"]][row["observed"]] += 1 + groups[row["judgment"]].append(row) + known = [row for row in rows if row["expected"] in {"pass", "fail"}] + scored_fail = sum(matrix["fail"][v] for v in ("pass", "fail")) + scored_pass = sum(matrix["pass"][v] for v in ("pass", "fail")) + errors = sum(row["observed"] == "error" for row in known) + insufficient = sum(row["observed"] == "insufficient_evidence" for row in known) + repeated = [group for group in groups.values() if len(group) > 1] + spreads = {} + for judgment, group in groups.items(): + scores = [ + r["score"] + for r in group + if isinstance(r["score"], (int, float)) and not isinstance(r["score"], bool) and math.isfinite(r["score"]) + ] + spreads[judgment] = max(scores) - min(scores) if scores else None + return { + "attempts": len(rows), + "judgments": len(groups), + "cases": len({r["judgment"].split(":")[0] for r in rows}), + "expected_class_counts": dict(Counter(r["expected"] for r in rows)), + "confusion_matrix": matrix, + "false_pass_rate": rate(matrix["fail"]["pass"], scored_fail), + "false_fail_rate": rate(matrix["pass"]["fail"], scored_pass), + "unjudgeable_rate": rate(errors + insufficient, len(known)), + "errors": errors, + "insufficient_evidence": insufficient, + "disagreement": sum(r["expected"] != r["observed"] for r in rows), + "expected_insufficient": { + "attempts": sum(matrix["insufficient_evidence"].values()), + "correctly_abstained": matrix["insufficient_evidence"]["insufficient_evidence"], + "errors": matrix["insufficient_evidence"]["error"], + "confident_verdict": sum(matrix["insufficient_evidence"][v] for v in ("pass", "fail")), + }, + "variability": rate(sum(len({r["observed"] for r in group}) > 1 for group in repeated), len(repeated)), + "score_spread_by_judgment": spreads, + } + + +def _write(path, value): + path.write_text(json.dumps(value, indent=2, allow_nan=False) + "\n") + + +def _attempt(root, case, repeat, output, thresholds, timeout): + directory = output / case["id"] / f"attempt-{repeat}" + directory.mkdir(parents=True, exist_ok=True) + _write(directory / "entry.json", case["entry"]) + env = os.environ.copy() + paths = { + "ENTRY_JSON": directory / "entry.json", + "ATIF_PATH": directory / "trajectory.json", + "REWARD_JSON": directory / "reward.json", + "REWARD_TXT": directory / "reward.txt", + "VERIFIER_DIR": directory, + "LOGS_DIR": directory, + "SKILL_EVALUATOR_REWARD_JSON": directory / "skill_evaluator_reward.json", + } + if case["trajectory"] is not None: + (directory / "trajectory.json").write_bytes(_relative(root, case["trajectory"]).read_bytes()) + env.update({f"HARBOR_{key}": str(value) for key, value in paths.items()}) + try: + process = subprocess.run( + [sys.executable, str(TEMPLATE)], env=env, capture_output=True, timeout=timeout, check=False + ) + code = process.returncode + except subprocess.TimeoutExpired: + code = -1 + reward = {} + for filename in ("reward.json", "skill_evaluator_reward.json"): + path = directory / filename + if path.exists(): + try: + reward.update(json.loads(path.read_text())) + except (ValueError, OSError): + code = -1 + if code and reward.get("evaluation_status") != "failed": + reward["_process_error"] = True + rows = observations(case, reward, thresholds) + _write(directory / "expected-vs-observed.json", rows) + if not (directory / "judge_attempts.json").exists(): + _write(directory / "judge_attempts.json", []) + return {"case": case["id"], "repeat": repeat, "returncode": code, "reward": reward, "observations": rows} + + +def qualify(root, suite, cases, output, repeats, concurrency, timeout, split, provider): + thresholds = DEFAULT_THRESHOLDS | suite.get("thresholds", {}) + tasks = [(case, repeat) for case in cases for repeat in range(1, repeats + 1)] + with ThreadPoolExecutor(max_workers=concurrency) as executor: + attempts = list(executor.map(lambda task: _attempt(root, *task, output, thresholds, timeout), tasks)) + rows = [row for attempt in attempts for row in attempt["observations"]] + summaries = {} + for metric in (*METRICS, "behavior_steps", "overall"): + subset = [row for row in rows if row["metric"] == metric] + if subset: + summaries[metric] = summarize(subset) | { + "kind": "deterministic" + if metric in METRICS[:3] + else "model_judgment" + if metric != "overall" + else "composite" + } + digest = hashlib.sha256() + files = ["suite.json", *sorted({c["trajectory"] for c in suite["cases"] if c["trajectory"]})] + for filename in files: + data = (root / filename).read_bytes() + digest.update(filename.encode() + b"\0" + len(data).to_bytes(8, "big") + data) + rewards = [attempt["reward"] for attempt in attempts] + details = [ + detail for reward in rewards for detail in reward.get("details", {}).values() if isinstance(detail, dict) + ] + safe_env = { + key: value + for key, value in os.environ.items() + if key + in { + "SKILL_EVAL_JUDGE_MODEL", + "SKILL_EVAL_JUDGE_FALLBACK_MODEL", + "SKILL_EVAL_JUDGE_REASONING_EFFORT", + "SKILL_EVAL_GOAL_ACCURACY_METHOD", + "SKILL_EVAL_LLM_JUDGE_BUDGET_SEC", + "SKILL_EVAL_LLM_MAX_RETRIES", + "SKILL_EVAL_LLM_RETRY_BASE_DELAY", + "SKILL_EVAL_LLM_RETRY_MAX_DELAY", + "SKILL_EVAL_ACCURACY_BUDGET", + "SKILL_EVAL_GOAL_ACCURACY_BUDGET", + "SKILL_EVAL_BEHAVIOR_CHECK_BUDGET", + "SKILL_EVAL_BEHAVIOR_FINAL_RESPONSE_LIMIT", + } + } + result = { + "schema": SCHEMA, + "suite": suite["suite"], + "metrics": summaries, + "coverage": { + "cases": len(cases), + "attempts": len(attempts), + "categories": dict(Counter(c["category"] for c in cases)), + "splits": dict(Counter(c["split"] for c in cases)), + "missing_categories": sorted(CATEGORIES - {c["category"] for c in cases}), + "cases_with_trajectory": sum(c["trajectory"] is not None for c in cases), + "truncated_judgments": sum(d.get("omitted", {}).get("truncated") is True for d in details), + "evidence_judgments": sum("omitted" in d for d in details), + }, + "provenance": { + "suite_sha256": digest.hexdigest(), + "hash_files": files, + "split": split, + "case_ids": [c["id"] for c in cases], + "skillevaluator_version": version("skillevaluator"), + "verifier_sha256": hashlib.sha256(TEMPLATE.read_bytes()).hexdigest(), + "contracts": { + key: sorted({r[key] for r in rewards if key in r}) + for key in ("judge_contract", "metric_set", "score_policy") + }, + "judge_models_used": sorted({d["judge_model_used"] for d in details if d.get("judge_model_used")}), + "goal_methods": sorted( + {r.get("details", {}).get("goal_accuracy", {}).get("method") for r in rewards} - {None} + ), + "provider": provider.provider, + "model": provider.model, + "judge_environment": safe_env, + "thresholds": thresholds, + "repeats": repeats, + "concurrency": concurrency, + "timeout": timeout, + "timestamp": datetime.now(UTC).isoformat(), + }, + "attempts": attempts, + "limitations": LIMITATIONS, + } + if split == "all": + result["by_split"] = { + name: { + metric: summarize( + [ + row + for attempt in attempts + if attempt["case"] in {c["id"] for c in cases if c["split"] == name} + for row in attempt["observations"] + if row["metric"] == metric + ] + ) + | {"kind": summaries[metric]["kind"]} + for metric in summaries + } + for name in ("assessment", "tuning") + } + # Mixed splits have no aggregate headline or gates. + result["metrics"] = {} + _write(output / "grader-validation.json", result) + return result + + +def gate_failures(result, gates): + summaries = result["metrics"] or result.get("by_split", {}).get("assessment", {}) + return [ + name + for name, limit in gates.items() + if limit is not None + and any(summary[name]["rate"] is not None and summary[name]["rate"] > limit for summary in summaries.values()) + ] + + +@click.command("validate-grader") +@click.argument("suite_dir", type=click.Path(path_type=Path, exists=True, file_okay=False), default=REFERENCE_SUITE) +@click.option("--repeats", type=click.IntRange(min=1), default=3, show_default=True) +@click.option("--split", type=click.Choice(["assessment", "tuning", "all"]), default="assessment", show_default=True) +@click.option("--case", "case_ids", multiple=True) +@click.option( + "-o", "--output", type=click.Path(path_type=Path, file_okay=False), default=Path("grader-validation-output") +) +@click.option("--json", "as_json", is_flag=True) +@click.option("--check-suite", is_flag=True) +@click.option("--concurrency", type=click.IntRange(min=1), default=1, show_default=True) +@click.option("--timeout", type=click.FloatRange(min=0, min_open=True), default=300.0, show_default=True) +@click.option("--max-false-pass-rate", type=click.FloatRange(0, 1)) +@click.option("--max-false-fail-rate", type=click.FloatRange(0, 1)) +@click.option("--max-unjudgeable-rate", type=click.FloatRange(0, 1)) +def validate_grader( + suite_dir, + repeats, + split, + case_ids, + output, + as_json, + check_suite, + concurrency, + timeout, + max_false_pass_rate, + max_false_fail_rate, + max_unjudgeable_rate, +): + """Qualify the shipped Tier 3 verifier against independently labelled cases.""" + try: + suite = load_suite(suite_dir) + unknown = set(case_ids) - {case["id"] for case in suite["cases"]} + if unknown: + raise ValueError(f"unknown case IDs: {sorted(unknown)}") + cases = [ + case + for case in suite["cases"] + if (split == "all" or case["split"] == split) and (not case_ids or case["id"] in case_ids) + ] + if not cases: + raise ValueError("no cases selected") + if check_suite: + payload = {"status": "valid", "cases": len(cases), "split": split} + click.echo( + json.dumps(payload) + if as_json + else f"Suite valid: {len(cases)} {split} cases; executable labels verified (no LLM calls)." + ) + return + provider = resolve_llm_provider() + output = output.resolve() + if output.exists() and any(output.iterdir()): + raise ValueError("output directory must be empty (prevents stale attempt evidence)") + output.mkdir(parents=True, exist_ok=True) + result = qualify(suite_dir.resolve(), suite, cases, output, repeats, concurrency, timeout, split, provider) + except (ValueError, OSError) as exc: + raise click.UsageError(str(exc)) from exc + gates = { + "false_pass_rate": max_false_pass_rate, + "false_fail_rate": max_false_fail_rate, + "unjudgeable_rate": max_unjudgeable_rate, + } + failures = gate_failures(result, gates) + if as_json: + click.echo(json.dumps(result, indent=2)) + else: + table = Table(title="Grader qualification") + for header in ("Metric", "False passes", "False fails", "Unjudgeable", "Judgments / cases"): + table.add_column(header) + summaries = result["metrics"] or result["by_split"]["assessment"] + for metric, summary in summaries.items(): + cells = [f"{summary[key]['numerator']}/{summary[key]['denominator']}" for key in gates] + table.add_row(metric, *cells, f"{summary['judgments']} / {summary['cases']}") + Console().print(table) + click.echo(f"Split: {split}; report: {output / 'grader-validation.json'}") + click.echo(LIMITATIONS) + if failures: + if not as_json: + click.echo(f"Gates exceeded: {', '.join(failures)}", err=True) + raise click.exceptions.Exit(1) diff --git a/tests/golden/cli_surface.json b/tests/golden/cli_surface.json index d7e1b5d9f..6dee24b3d 100644 --- a/tests/golden/cli_surface.json +++ b/tests/golden/cli_surface.json @@ -3184,6 +3184,122 @@ } ] }, + "validate-grader": { + "params": [ + { + "default": "/home/ubuntu/wt/grader-validation/src/skillevaluator/tier3/grader_reference", + "name": "suite_dir", + "opts": [ + "suite_dir" + ], + "param_type": "argument", + "type": "directory" + }, + { + "default": "3", + "name": "repeats", + "opts": [ + "--repeats" + ], + "param_type": "option", + "type": "integer range" + }, + { + "choices": [ + "assessment", + "tuning", + "all" + ], + "default": "assessment", + "name": "split", + "opts": [ + "--split" + ], + "param_type": "option" + }, + { + "multiple": true, + "name": "case_ids", + "opts": [ + "--case" + ], + "param_type": "option", + "type": "text" + }, + { + "default": "grader-validation-output", + "name": "output", + "opts": [ + "--output", + "-o" + ], + "param_type": "option", + "type": "directory" + }, + { + "default": "False", + "is_flag": true, + "name": "as_json", + "opts": [ + "--json" + ], + "param_type": "option", + "type": "boolean" + }, + { + "default": "False", + "is_flag": true, + "name": "check_suite", + "opts": [ + "--check-suite" + ], + "param_type": "option", + "type": "boolean" + }, + { + "default": "1", + "name": "concurrency", + "opts": [ + "--concurrency" + ], + "param_type": "option", + "type": "integer range" + }, + { + "default": "300.0", + "name": "timeout", + "opts": [ + "--timeout" + ], + "param_type": "option", + "type": "float range" + }, + { + "name": "max_false_pass_rate", + "opts": [ + "--max-false-pass-rate" + ], + "param_type": "option", + "type": "float range" + }, + { + "name": "max_false_fail_rate", + "opts": [ + "--max-false-fail-rate" + ], + "param_type": "option", + "type": "float range" + }, + { + "name": "max_unjudgeable_rate", + "opts": [ + "--max-unjudgeable-rate" + ], + "param_type": "option", + "type": "float range" + } + ] + }, "view": { "params": [ { diff --git a/tests/tier3/test_grader_validation.py b/tests/tier3/test_grader_validation.py new file mode 100644 index 000000000..ce44aff86 --- /dev/null +++ b/tests/tier3/test_grader_validation.py @@ -0,0 +1,370 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +from __future__ import annotations + +import copy +import json +import re +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +import pytest +from click.testing import CliRunner + +from skillevaluator.cli import cli +from skillevaluator.tier3 import grader_validation as gv + + +@pytest.fixture +def suite_dir(tmp_path): + import shutil + + destination = tmp_path / "suite" + shutil.copytree(gv.REFERENCE_SUITE, destination) + return destination + + +def write_suite(directory, suite): + (directory / "suite.json").write_text(json.dumps(suite)) + + +def test_reference_behavior_labels_distinguish_format_from_correctness(): + suite = gv.load_suite(gv.REFERENCE_SUITE) + for case in suite["cases"]: + assert case["label"]["reviewed_on"] == "2026-11-06" + if case["trajectory"] is None: + continue + trajectory = json.loads((gv.REFERENCE_SUITE / case["trajectory"]).read_text()) + behaviors = case["entry"]["expected_behavior"] + if "Return only the numeric answer." in behaviors: + index = behaviors.index("Return only the numeric answer.") + numeric_only = re.fullmatch(r"-?\d+(?:\.\d+)?", gv.get_final_response(trajectory)) is not None + assert case["expected"]["metrics"]["behavior_check"][index] is numeric_only, case["id"] + if case["id"] in {"wrong-answer", "tuning-wrong"}: + assert case["expected"]["metrics"]["behavior_check"] == [True, True] + assert case["expected"]["metrics"]["accuracy"] == "fail" + assert case["expected"]["metrics"]["goal_accuracy"] == "fail" + assert case["expected"]["overall"] == "fail" + + +@pytest.mark.parametrize( + ("mutation", "message"), + [ + (lambda s: s.update(extra=True), "unknown fields"), + (lambda s: s.update(schema="v2"), "schema must"), + (lambda s: s["cases"].append(copy.deepcopy(s["cases"][0])), "duplicate"), + (lambda s: s["cases"][0].update(category="other"), "unknown category"), + (lambda s: s["cases"][0].update(category=[]), "unknown category"), + (lambda s: s["cases"][0].update(trajectory="../outside.json"), "inside suite"), + (lambda s: s["cases"][0].update(trajectory="absent.json"), "not found"), + (lambda s: s["cases"][0]["expected"]["metrics"].update(behavior_check=[True]), "behavior label length"), + (lambda s: s["cases"][0]["entry"].update(unknown="x"), "unknown fields"), + (lambda s: s.update(thresholds={"accuracy": 2}), "expected number"), + (lambda s: s["cases"][0]["label"].update(checks=[]), "require checks"), + (lambda s: s["cases"][0]["label"]["checks"][0].update(value="not present"), "check failed"), + (lambda s: s["cases"][0]["label"]["checks"][0].update(type="unknown"), "unknown executable"), + ], +) +def test_invalid_suite(suite_dir, mutation, message): + suite = json.loads((suite_dir / "suite.json").read_text()) + mutation(suite) + write_suite(suite_dir, suite) + with pytest.raises(ValueError, match=message): + gv.load_suite(suite_dir) + + +def test_symlink_escape(suite_dir, tmp_path): + outside = tmp_path / "outside.json" + outside.write_text('{"steps":[]}') + (suite_dir / "link.json").symlink_to(outside) + suite = json.loads((suite_dir / "suite.json").read_text()) + suite["cases"][0]["trajectory"] = "link.json" + write_suite(suite_dir, suite) + with pytest.raises(ValueError, match="inside suite"): + gv.load_suite(suite_dir) + + +def test_executable_checks(): + trajectory = { + "steps": [ + { + "source": "agent", + "tool_calls": [ + {"function_name": "Write", "arguments": {"file_path": "/workspace/a", "content": "done"}} + ], + "observation": {"results": [{"content": "ok"}]}, + }, + {"source": "agent", "message": "finished"}, + ] + } + checks = [ + {"type": "final_response_contains", "value": "finished"}, + {"type": "final_response_not_contains", "value": "failed"}, + {"type": "tool_result_contains", "value": "ok"}, + {"type": "file_written_contains", "path": "/workspace/a", "value": "done"}, + ] + gv.verify_checks({"method": "executable", "checks": checks}, trajectory, "test") + checks[-1]["path"] = "/workspace/b" + with pytest.raises(ValueError, match="check failed"): + gv.verify_checks({"method": "executable", "checks": checks}, trajectory, "test") + + +@pytest.mark.parametrize( + ("reward", "metric", "expected"), + [ + ({"accuracy": 0.8}, "accuracy", "pass"), + ({"accuracy": 0.79}, "accuracy", "fail"), + ({"error": "No trajectory or reconstructible agent log", "overall": 0}, "overall", "insufficient_evidence"), + ({"details": {"accuracy": {"status": "error"}}}, "accuracy", "error"), + ({"details": {"skill_execution": {"status": "not_applicable"}}}, "skill_execution", "not_applicable"), + ({"overall": 0, "evaluation_status": "failed"}, "overall", "error"), + ({}, "accuracy", "error"), + ({"accuracy": float("nan")}, "accuracy", "error"), + ], +) +def test_classification(reward, metric, expected): + assert gv.classify(reward, metric, gv.DEFAULT_THRESHOLDS) == expected + + +def test_math_and_variability(): + rows = [ + {"judgment": "a:overall", "expected": "fail", "observed": v, "score": s} + for v, s in [("pass", 0.8), ("fail", 0.2), ("error", None), ("insufficient_evidence", None)] + ] + [{"judgment": "b:overall", "expected": "pass", "observed": "fail", "score": 0.1}] + result = gv.summarize(rows) + assert result["false_pass_rate"]["numerator"] == 1 + assert result["false_pass_rate"]["denominator"] == 2 + assert result["false_fail_rate"]["rate"] == 1 + assert result["unjudgeable_rate"]["numerator"] == 2 + assert result["unjudgeable_rate"]["denominator"] == 5 + assert result["variability"]["rate"] == 1 + assert result["variability"]["denominator"] == 1 + assert result["score_spread_by_judgment"]["a:overall"] == pytest.approx(0.6) + assert result["cases"] == result["judgments"] == 2 + low, high = result["false_pass_rate"]["wilson_95"] + assert low == pytest.approx(0.0945312) + assert high == pytest.approx(0.9054688) + assert gv.rate(0, 0)["wilson_95"] is None + assert gv.summarize([])["attempts"] == 0 + assert gv.summarize([])["variability"]["rate"] is None + + +def test_behavior_pool(): + case = {"id": "mixed", "expected": {"overall": "fail", "metrics": {"behavior_check": [True, False]}}} + reward = { + "overall": 0.6, + "behavior_check": 0.5, + "details": {"behavior_check": {"results": [{"step": 2, "passed": False}, {"step": 1, "passed": True}]}}, + } + rows = gv.observations(case, reward, gv.DEFAULT_THRESHOLDS) + assert [r["observed"] for r in rows] == ["pass", "fail", "pass", "fail"] + reward["details"]["behavior_check"]["status"] = "error" + assert all(r["observed"] == "error" for r in gv.observations(case, reward, gv.DEFAULT_THRESHOLDS)[1:]) + + +def test_bundled_check_suite_and_usage(monkeypatch): + monkeypatch.setattr(gv, "resolve_llm_provider", lambda: pytest.fail("provider accessed")) + runner = CliRunner() + result = runner.invoke(cli, ["tier3", "validate-grader", "--check-suite"]) + assert result.exit_code == 0, result.output + assert "14 assessment cases" in result.output + tuning = runner.invoke(cli, ["tier3", "validate-grader", "--check-suite", "--split", "tuning", "--json"]) + assert json.loads(tuning.output)["cases"] == 2 + for args in (["--case", "absent"], ["--repeats", "0"], ["--timeout", "0"], ["--max-false-pass-rate", "2"]): + assert runner.invoke(cli, ["tier3", "validate-grader", "--check-suite", *args]).exit_code == 2 + + +def test_missing_provider(monkeypatch): + from skillevaluator.provider_config import ProviderConfigurationError + + def missing(): + raise ProviderConfigurationError("No judge provider configured") + + monkeypatch.setattr(gv, "resolve_llm_provider", missing) + result = CliRunner().invoke(cli, ["tier3", "validate-grader"]) + assert result.exit_code == 2 + assert "No judge provider configured" in result.output + + +@pytest.fixture +def judge_server(monkeypatch): + state = {"fail": False} + + class Handler(BaseHTTPRequestHandler): + def log_message(self, *_args): + pass + + def do_POST(self): + request = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) + if state["fail"]: + self.send_response(400) + self.end_headers() + return + prompt = json.dumps(request["messages"]) + if "ACTION_CORRECT" in prompt: + reply = { + "criteria": dict.fromkeys( + ["ACTION_CORRECT", "FACTUALLY_ACCURATE", "TASK_ADDRESSED", "ACTIONABLE", "FORMAT_FOLLOWED"], + True, + ), + "reason": "evidence matches", + } + elif "achieved" in prompt: + reply = {"user_goal": "compute", "end_state": "14", "achieved": True, "reason": "met"} + else: + reply = { + "results": [ + {"step": 1, "passed": True, "reason": "read"}, + {"step": 2, "passed": True, "reason": "numeric"}, + ], + "summary": "met", + } + body = json.dumps({"choices": [{"message": {"content": json.dumps(reply)}}]}).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + monkeypatch.setenv("SKILL_EVAL_LLM_PROVIDER", "openai-compatible") + monkeypatch.setenv("SKILL_EVAL_LLM_MODEL", "qualification-test") + monkeypatch.setenv("SKILL_EVAL_LLM_BASE_URL", f"http://127.0.0.1:{server.server_port}/v1") + monkeypatch.setenv("SKILL_EVAL_LLM_API_KEY", "test-secret-never-in-provenance") + monkeypatch.setenv("SKILL_EVAL_LLM_MAX_RETRIES", "0") + yield state + server.shutdown() + thread.join() + server.server_close() + + +def test_real_template_cli(judge_server, tmp_path): + output = tmp_path / "results" + result = CliRunner().invoke( + cli, + [ + "tier3", + "validate-grader", + "--case", + "arithmetic", + "--case", + "missing", + "--case", + "baseline", + "--repeats", + "2", + "--concurrency", + "2", + "-o", + str(output), + "--json", + ], + ) + assert result.exit_code == 0, result.output + report = json.loads(result.output) + assert report["coverage"]["attempts"] == 6 + assert report["metrics"]["overall"]["expected_insufficient"]["correctly_abstained"] == 2 + assert report["metrics"]["skill_execution"]["confusion_matrix"]["not_applicable"]["not_applicable"] == 2 + reward = report["attempts"][0]["reward"] + assert reward["security"] == 1 + assert reward["skill_execution"] == 1 + assert reward["accuracy"] == 1 + assert report["provenance"]["contracts"]["judge_contract"] + assert report["provenance"]["judge_models_used"] == ["qualification-test"] + assert "test-secret-never-in-provenance" not in json.dumps(report) + assert (output / "arithmetic/attempt-1/judge_attempts.json").exists() + assert json.loads((output / "grader-validation.json").read_text()) == report + + +def test_split_separation_and_gates(judge_server, tmp_path): + result = CliRunner().invoke( + cli, + [ + "tier3", + "validate-grader", + "--split", + "all", + "--case", + "arithmetic", + "--case", + "tuning-wrong", + "--repeats", + "1", + "-o", + str(tmp_path / "all"), + "--json", + "--max-false-pass-rate", + "0", + ], + ) + assert result.exit_code == 0, result.output + report = json.loads(result.output) + assert report["metrics"] == {} + assert report["by_split"]["assessment"]["overall"]["cases"] == 1 + assert report["by_split"]["tuning"]["overall"]["false_pass_rate"]["rate"] == 1 + assert gv.gate_failures(report, {"false_pass_rate": 0}) == [] + gated = CliRunner().invoke( + cli, + [ + "tier3", + "validate-grader", + "--split", + "tuning", + "--case", + "tuning-wrong", + "--repeats", + "1", + "-o", + str(tmp_path / "gated"), + "--json", + "--max-false-pass-rate", + "0", + ], + ) + assert gated.exit_code == 1, gated.output + assert json.loads(gated.output)["metrics"]["overall"]["false_pass_rate"]["rate"] == 1 + assert ( + gv.gate_failures({"metrics": {"overall": {"false_pass_rate": gv.rate(1, 2)}}}, {"false_pass_rate": 0.5}) == [] + ) + + +def test_timeout_is_unscored(monkeypatch, tmp_path): + import subprocess + + def timeout(*_args, **_kwargs): + raise subprocess.TimeoutExpired("verifier", 0.01) + + monkeypatch.setattr(gv.subprocess, "run", timeout) + suite = gv.load_suite(gv.REFERENCE_SUITE) + result = gv._attempt(gv.REFERENCE_SUITE, suite["cases"][0], 1, tmp_path, gv.DEFAULT_THRESHOLDS, 0.01) + assert result["returncode"] == -1 + assert all(row["observed"] == "error" for row in result["observations"]) + + +def test_real_judge_failure_is_unscored(judge_server, tmp_path): + judge_server["fail"] = True + result = CliRunner().invoke( + cli, + [ + "tier3", + "validate-grader", + "--case", + "arithmetic", + "--repeats", + "1", + "-o", + str(tmp_path / "failed"), + "--json", + ], + ) + assert result.exit_code == 0, result.output + report = json.loads(result.output) + assert report["attempts"][0]["returncode"] == 1 + assert report["attempts"][0]["reward"]["evaluation_status"] == "failed" + assert report["metrics"]["accuracy"]["errors"] == 1 + assert report["metrics"]["accuracy"]["false_fail_rate"]["denominator"] == 0 + assert report["metrics"]["overall"]["errors"] == 1 + assert report["metrics"]["security"]["confusion_matrix"]["pass"]["pass"] == 1 From 3905176e0907a7b403e2ece64f6da7d5332267d4 Mon Sep 17 00:00:00 2001 From: Christopher Kevin Date: Sat, 7 Nov 2026 01:22:49 +0000 Subject: [PATCH 2/3] test(golden): keep validate-grader suite default portable The SUITE_DIR argument now defaults to None and resolves to the bundled reference suite at runtime, so the CLI surface snapshot no longer records a machine-specific absolute path. Signed-off-by: Christopher Kevin --- src/skillevaluator/tier3/grader_validation.py | 8 ++++++-- tests/golden/cli_surface.json | 1 - tests/tier3/test_grader_validation.py | 14 ++++++++++++++ 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/src/skillevaluator/tier3/grader_validation.py b/src/skillevaluator/tier3/grader_validation.py index 7aa06e465..4922cbeab 100644 --- a/src/skillevaluator/tier3/grader_validation.py +++ b/src/skillevaluator/tier3/grader_validation.py @@ -500,7 +500,7 @@ def gate_failures(result, gates): @click.command("validate-grader") -@click.argument("suite_dir", type=click.Path(path_type=Path, exists=True, file_okay=False), default=REFERENCE_SUITE) +@click.argument("suite_dir", type=click.Path(path_type=Path, exists=True, file_okay=False), default=None) @click.option("--repeats", type=click.IntRange(min=1), default=3, show_default=True) @click.option("--split", type=click.Choice(["assessment", "tuning", "all"]), default="assessment", show_default=True) @click.option("--case", "case_ids", multiple=True) @@ -528,7 +528,11 @@ def validate_grader( max_false_fail_rate, max_unjudgeable_rate, ): - """Qualify the shipped Tier 3 verifier against independently labelled cases.""" + """Qualify the shipped Tier 3 verifier against independently labelled cases. + + SUITE_DIR defaults to the bundled reference suite when omitted. + """ + suite_dir = REFERENCE_SUITE if suite_dir is None else suite_dir try: suite = load_suite(suite_dir) unknown = set(case_ids) - {case["id"] for case in suite["cases"]} diff --git a/tests/golden/cli_surface.json b/tests/golden/cli_surface.json index 6dee24b3d..a23c89764 100644 --- a/tests/golden/cli_surface.json +++ b/tests/golden/cli_surface.json @@ -3187,7 +3187,6 @@ "validate-grader": { "params": [ { - "default": "/home/ubuntu/wt/grader-validation/src/skillevaluator/tier3/grader_reference", "name": "suite_dir", "opts": [ "suite_dir" diff --git a/tests/tier3/test_grader_validation.py b/tests/tier3/test_grader_validation.py index ce44aff86..c4fd03663 100644 --- a/tests/tier3/test_grader_validation.py +++ b/tests/tier3/test_grader_validation.py @@ -175,6 +175,20 @@ def test_bundled_check_suite_and_usage(monkeypatch): assert runner.invoke(cli, ["tier3", "validate-grader", "--check-suite", *args]).exit_code == 2 +def test_suite_default_is_portable_and_documented(): + argument = next(param for param in gv.validate_grader.params if param.name == "suite_dir") + assert argument.default is None + assert argument.required is False + runner = CliRunner() + help_result = runner.invoke(cli, ["tier3", "validate-grader", "--help"]) + assert help_result.exit_code == 0 + assert "SUITE_DIR defaults to the bundled reference suite when omitted." in help_result.output + implicit = runner.invoke(cli, ["tier3", "validate-grader", "--check-suite", "--json"]) + explicit = runner.invoke(cli, ["tier3", "validate-grader", str(gv.REFERENCE_SUITE), "--check-suite", "--json"]) + assert implicit.exit_code == explicit.exit_code == 0 + assert json.loads(implicit.output) == json.loads(explicit.output) + + def test_missing_provider(monkeypatch): from skillevaluator.provider_config import ProviderConfigurationError From 231f80e34dc5f5399eae5d9cc4828448a803b691 Mon Sep 17 00:00:00 2001 From: Christopher Kevin Date: Tue, 10 Nov 2026 02:19:33 +0000 Subject: [PATCH 3/3] Fix grader validation review findings Signed-off-by: Christopher Kevin --- docs/grader-validation.mdx | 8 +- src/skillevaluator/tier3/grader_validation.py | 154 +++++++++++----- src/skillevaluator/tier3/harbor/adapter.py | 28 +-- tests/tier3/test_grader_validation.py | 172 ++++++++++++++++++ 4 files changed, 304 insertions(+), 58 deletions(-) diff --git a/docs/grader-validation.mdx b/docs/grader-validation.mdx index d8c77821f..2e2248b97 100644 --- a/docs/grader-validation.mdx +++ b/docs/grader-validation.mdx @@ -212,9 +212,11 @@ disagreement and judge errors are reported rather than changing the exit code. ## Measured baseline -On 2026-11-07, SkillEvaluator 0.8.0 graded the bundled assessment split with -the `openai-compatible` provider: 14 cases × 3 repeats = 42 attempts per model. -Suite SHA-256 prefix: `5e85ceac…`; verifier SHA-256 prefix: `d444e2c4…`. +On 2026-11-07, SkillEvaluator commit +`0205909b653f139602fc2e7681ba7d0112c0871a` graded the bundled assessment split +with the `openai-compatible` provider: 14 cases × 3 repeats = 42 attempts per +model. Suite SHA-256 prefix: `5e85ceac…`; the then-recorded `eval.py` SHA-256 +prefix was `d444e2c4…`. The fractions below use the scored known-fail and known-pass denominators defined above, not all 42 attempts. diff --git a/src/skillevaluator/tier3/grader_validation.py b/src/skillevaluator/tier3/grader_validation.py index 4922cbeab..740e22fba 100644 --- a/src/skillevaluator/tier3/grader_validation.py +++ b/src/skillevaluator/tier3/grader_validation.py @@ -15,18 +15,19 @@ from collections import Counter, defaultdict from concurrent.futures import ThreadPoolExecutor from datetime import UTC, datetime -from importlib.metadata import version from pathlib import Path import click from rich.console import Console from rich.table import Table +from skillevaluator import __version__ from skillevaluator.provider_config import resolve_llm_provider from skillevaluator.tier3.eval_core.atif_helpers import ( extract_tool_calls_as_dicts, get_final_response, ) +from skillevaluator.tier3.eval_core.codex_tool_call_normalizer import atif_content_text SCHEMA = "skillevaluator.grader-qualification/v1" CATEGORIES = {"positive", "negative", "edge", "failure_recovery", "unavailable_evidence", "non_use", "baseline"} @@ -176,7 +177,10 @@ def load_suite(directory): raise ValueError(f"{case_id}: trajectory must have nonempty ATIF steps") elif case["category"] != "unavailable_evidence" or expected["overall"] != "insufficient_evidence": raise ValueError("null trajectory requires unavailable_evidence with insufficient_evidence label") - verify_checks(label, trajectory, case_id) + try: + verify_checks(label, trajectory, case_id) + except (AttributeError, TypeError) as exc: + raise ValueError(f"{case_id}: malformed trajectory evidence") from exc return suite @@ -202,16 +206,56 @@ def verify_checks(label, trajectory, case_id): found = check["value"] in get_final_response(trajectory) passed = not found if kind.endswith("not_contains") else found elif kind == "tool_result_contains": - observations = [step.get("observation", {}) for step in trajectory["steps"]] - passed = check["value"] in json.dumps(observations, ensure_ascii=False) - else: - _text(check.get("path"), "check.path") passed = any( - call.get("action", "").lower() in {"write", "write_file"} - and call.get("action_input", {}).get("file_path") == check["path"] - and check["value"] in call.get("action_input", {}).get("content", "") - for call in extract_tool_calls_as_dicts(trajectory) + check["value"] in atif_content_text(result.get("content")) + for step in trajectory["steps"] + if isinstance(step, dict) + for observation in [step.get("observation")] + if isinstance(observation, dict) + for results in [observation.get("results")] + if isinstance(results, list) + for result in results + if isinstance(result, dict) ) + else: + _text(check.get("path"), "check.path") + safe_steps = [] + for step in trajectory["steps"]: + if not isinstance(step, dict): + continue + calls = step.get("tool_calls") + safe_calls = [] + if isinstance(calls, list): + for call in calls: + if ( + isinstance(call, dict) + and isinstance(call.get("function_name"), str) + and isinstance(call.get("arguments") or {}, dict) + ): + safe_calls.append(call) + safe_steps.append( + { + **step, + "tool_calls": safe_calls, + } + ) + safe_trajectory = {**trajectory, "steps": safe_steps} + passed = False + for call in extract_tool_calls_as_dicts(safe_trajectory): + if not isinstance(call, dict): + continue + action = call.get("action") + action_input = call.get("action_input") + if ( + isinstance(action, str) + and action.lower() in {"write", "write_file"} + and isinstance(action_input, dict) + and action_input.get("file_path") == check["path"] + and isinstance(action_input.get("content"), str) + and check["value"] in action_input["content"] + ): + passed = True + break if not passed: raise ValueError(f"{case_id}: executable label check failed: {kind}") @@ -253,11 +297,12 @@ def observations(case, reward, thresholds): observed = classify(reward, metric, thresholds) score = reward.get(metric) if isinstance(expected, list): + expected_score = round(sum(expected) / len(expected), 4) if expected else 1.0 result.append( { "metric": metric, "judgment": f"{case['id']}:{metric}", - "expected": "pass" if all(expected) else "fail", + "expected": "pass" if expected_score >= thresholds[metric] else "fail", "observed": observed, "score": score, } @@ -339,11 +384,12 @@ def _write(path, value): path.write_text(json.dumps(value, indent=2, allow_nan=False) + "\n") -def _attempt(root, case, repeat, output, thresholds, timeout): +def _attempt(root, case, repeat, output, thresholds, timeout, provider_env=None): directory = output / case["id"] / f"attempt-{repeat}" directory.mkdir(parents=True, exist_ok=True) _write(directory / "entry.json", case["entry"]) env = os.environ.copy() + env.update(provider_env or {}) paths = { "ENTRY_JSON": directory / "entry.json", "ATIF_PATH": directory / "trajectory.json", @@ -380,11 +426,13 @@ def _attempt(root, case, repeat, output, thresholds, timeout): return {"case": case["id"], "repeat": repeat, "returncode": code, "reward": reward, "observations": rows} -def qualify(root, suite, cases, output, repeats, concurrency, timeout, split, provider): +def qualify(root, suite, cases, output, repeats, concurrency, timeout, split, provider, provider_env, judge_config): thresholds = DEFAULT_THRESHOLDS | suite.get("thresholds", {}) tasks = [(case, repeat) for case in cases for repeat in range(1, repeats + 1)] with ThreadPoolExecutor(max_workers=concurrency) as executor: - attempts = list(executor.map(lambda task: _attempt(root, *task, output, thresholds, timeout), tasks)) + attempts = list( + executor.map(lambda task: _attempt(root, *task, output, thresholds, timeout, provider_env), tasks) + ) rows = [row for attempt in attempts for row in attempt["observations"]] summaries = {} for metric in (*METRICS, "behavior_steps", "overall"): @@ -406,25 +454,26 @@ def qualify(root, suite, cases, output, repeats, concurrency, timeout, split, pr details = [ detail for reward in rewards for detail in reward.get("details", {}).values() if isinstance(detail, dict) ] + from skillevaluator.tier3.harbor.adapter import ( + _VERIFIER_BUDGET_ENV_VARS, + _VERIFIER_FILES, + _VERIFIER_JUDGE_CONTROL_ENV_VARS, + _VERIFIER_RETRY_ENV_VARS, + ) + safe_env = { key: value - for key, value in os.environ.items() - if key - in { - "SKILL_EVAL_JUDGE_MODEL", - "SKILL_EVAL_JUDGE_FALLBACK_MODEL", - "SKILL_EVAL_JUDGE_REASONING_EFFORT", - "SKILL_EVAL_GOAL_ACCURACY_METHOD", - "SKILL_EVAL_LLM_JUDGE_BUDGET_SEC", - "SKILL_EVAL_LLM_MAX_RETRIES", - "SKILL_EVAL_LLM_RETRY_BASE_DELAY", - "SKILL_EVAL_LLM_RETRY_MAX_DELAY", - "SKILL_EVAL_ACCURACY_BUDGET", - "SKILL_EVAL_GOAL_ACCURACY_BUDGET", - "SKILL_EVAL_BEHAVIOR_CHECK_BUDGET", - "SKILL_EVAL_BEHAVIOR_FINAL_RESPONSE_LIMIT", - } + for key, value in provider_env.items() + if key in _VERIFIER_BUDGET_ENV_VARS | _VERIFIER_RETRY_ENV_VARS | _VERIFIER_JUDGE_CONTROL_ENV_VARS } + source_root = Path(__file__).resolve().parents[2] + verifier_file_sha256 = {} + verifier_digest = hashlib.sha256() + for path in sorted(_VERIFIER_FILES, key=lambda item: item.relative_to(source_root).as_posix()): + name = path.relative_to(source_root).as_posix() + content = path.read_bytes() + verifier_file_sha256[name] = hashlib.sha256(content).hexdigest() + verifier_digest.update(name.encode() + b"\0" + len(content).to_bytes(8, "big") + content) result = { "schema": SCHEMA, "suite": suite["suite"], @@ -444,8 +493,9 @@ def qualify(root, suite, cases, output, repeats, concurrency, timeout, split, pr "hash_files": files, "split": split, "case_ids": [c["id"] for c in cases], - "skillevaluator_version": version("skillevaluator"), - "verifier_sha256": hashlib.sha256(TEMPLATE.read_bytes()).hexdigest(), + "skillevaluator_version": __version__, + "verifier_sha256": verifier_digest.hexdigest(), + "verifier_file_sha256": verifier_file_sha256, "contracts": { key: sorted({r[key] for r in rewards if key in r}) for key in ("judge_contract", "metric_set", "score_policy") @@ -456,6 +506,7 @@ def qualify(root, suite, cases, output, repeats, concurrency, timeout, split, pr ), "provider": provider.provider, "model": provider.model, + "judge_config": judge_config, "judge_environment": safe_env, "thresholds": thresholds, "repeats": repeats, @@ -554,11 +605,27 @@ def validate_grader( ) return provider = resolve_llm_provider() + from skillevaluator.tier3.harbor.runner import _judge_model_config, _provider_environment + + provider_env = _provider_environment(provider) + judge_config = _judge_model_config(provider, provider_env, "default") output = output.resolve() if output.exists() and any(output.iterdir()): raise ValueError("output directory must be empty (prevents stale attempt evidence)") output.mkdir(parents=True, exist_ok=True) - result = qualify(suite_dir.resolve(), suite, cases, output, repeats, concurrency, timeout, split, provider) + result = qualify( + suite_dir.resolve(), + suite, + cases, + output, + repeats, + concurrency, + timeout, + split, + provider, + provider_env, + judge_config, + ) except (ValueError, OSError) as exc: raise click.UsageError(str(exc)) from exc gates = { @@ -570,14 +637,19 @@ def validate_grader( if as_json: click.echo(json.dumps(result, indent=2)) else: - table = Table(title="Grader qualification") - for header in ("Metric", "False passes", "False fails", "Unjudgeable", "Judgments / cases"): - table.add_column(header) - summaries = result["metrics"] or result["by_split"]["assessment"] - for metric, summary in summaries.items(): - cells = [f"{summary[key]['numerator']}/{summary[key]['denominator']}" for key in gates] - table.add_row(metric, *cells, f"{summary['judgments']} / {summary['cases']}") - Console().print(table) + tables = ( + [(name.title(), summaries) for name, summaries in result["by_split"].items()] + if split == "all" + else [("Grader qualification", result["metrics"])] + ) + for title, summaries in tables: + table = Table(title=title if split != "all" else f"{title} grader qualification") + for header in ("Metric", "False passes", "False fails", "Unjudgeable", "Judgments / cases"): + table.add_column(header) + for metric, summary in summaries.items(): + cells = [f"{summary[key]['numerator']}/{summary[key]['denominator']}" for key in gates] + table.add_row(metric, *cells, f"{summary['judgments']} / {summary['cases']}") + Console().print(table) click.echo(f"Split: {split}; report: {output / 'grader-validation.json'}") click.echo(LIMITATIONS) if failures: diff --git a/src/skillevaluator/tier3/harbor/adapter.py b/src/skillevaluator/tier3/harbor/adapter.py index 61d170acf..5712fde1a 100644 --- a/src/skillevaluator/tier3/harbor/adapter.py +++ b/src/skillevaluator/tier3/harbor/adapter.py @@ -72,6 +72,18 @@ TEMPLATES_DIR = Path(__file__).parent / "templates" _EVAL_CORE_DIR = Path(__file__).resolve().parent.parent / "eval_core" +_VERIFIER_FILES = ( + TEMPLATES_DIR / "eval.py", + _EVAL_CORE_DIR / "log_converters.py", + _EVAL_CORE_DIR / "atif_helpers.py", + _EVAL_CORE_DIR / "shell_lexing.py", + _EVAL_CORE_DIR / "script_invocation.py", + _EVAL_CORE_DIR / "checks.py", + _EVAL_CORE_DIR / "secret_redaction.py", + _EVAL_CORE_DIR / "codex_tool_call_normalizer.py", + _EVAL_CORE_DIR / "character_facts.py", + _EVAL_CORE_DIR.parent.parent / "evidence.py", +) _EVALUATOR_TESTS_SUBDIR = "skill_evaluator" _BASE_IMAGE_PREFIX = "skillevaluator-base" # Compose 2 treats HEALTHCHECK NONE as a configured check, then fails its @@ -2396,23 +2408,11 @@ def _copy_verifier(task_dir: Path) -> None: tests_dir = task_dir / "tests" tests_dir.mkdir(parents=True, exist_ok=True) evaluator_dir = _replace_evaluator_tests_dir(task_dir) - sources = ( - (TEMPLATES_DIR / "eval.py", "Verifier template"), - (_EVAL_CORE_DIR / "log_converters.py", "log_converters helper"), - (_EVAL_CORE_DIR / "atif_helpers.py", "ATIF evidence helpers"), - (_EVAL_CORE_DIR / "shell_lexing.py", "Shell lexical helper"), - (_EVAL_CORE_DIR / "script_invocation.py", "Shell invocation helper"), - (_EVAL_CORE_DIR / "checks.py", "Deterministic grading checks"), - (_EVAL_CORE_DIR / "secret_redaction.py", "Deterministic redaction helper"), - (_EVAL_CORE_DIR / "codex_tool_call_normalizer.py", "Codex tool-call normalizer"), - (_EVAL_CORE_DIR / "character_facts.py", "Judge character-facts helper"), - (_EVAL_CORE_DIR.parent.parent / "evidence.py", "Evidence-reference helper"), - ) - for src, label in sources: + for src in _VERIFIER_FILES: if src.exists(): shutil.copy2(src, evaluator_dir / src.name) else: - logger.warning("%s not found at %s", label, src) + logger.warning("Verifier source not found at %s", src) def _has_symlink_component(path: Path, root: Path) -> bool: diff --git a/tests/tier3/test_grader_validation.py b/tests/tier3/test_grader_validation.py index c4fd03663..cf870b9dd 100644 --- a/tests/tier3/test_grader_validation.py +++ b/tests/tier3/test_grader_validation.py @@ -8,6 +8,7 @@ import re import threading from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from types import SimpleNamespace import pytest from click.testing import CliRunner @@ -110,6 +111,57 @@ def test_executable_checks(): gv.verify_checks({"method": "executable", "checks": checks}, trajectory, "test") +def test_tool_result_checks_match_recorded_content_text_only(): + trajectory = { + "steps": [ + { + "observation": { + "results": [ + None, + {"source_call_id": "call-3", "content": "Result: 14\nProcess exited with code 0"}, + ] + } + } + ] + } + label = { + "method": "executable", + "checks": [{"type": "tool_result_contains", "value": "Result: 14\nProcess exited"}], + } + gv.verify_checks(label, trajectory, "test") + label["checks"] = [{"type": "tool_result_contains", "value": "source_call_id"}] + with pytest.raises(ValueError, match="check failed"): + gv.verify_checks(label, trajectory, "test") + + +@pytest.mark.parametrize( + "tool_calls", + [ + {"function_name": "Write", "arguments": {"file_path": "/workspace/a", "content": "done"}}, + [{"function_name": None, "arguments": {"file_path": "/workspace/a", "content": "done"}}], + [{"function_name": "Write", "arguments": "not an object"}], + [{"function_name": "Write", "arguments": {"file_path": "/workspace/a", "content": None}}], + ], +) +def test_malformed_file_evidence_is_a_named_suite_error(suite_dir, tool_calls): + suite = gv.load_suite(suite_dir) + case = next(case for case in suite["cases"] if case["trajectory"] is not None) + trajectory_path = suite_dir / case["trajectory"] + trajectory = json.loads(trajectory_path.read_text()) + trajectory["steps"] = [{"source": "agent", "tool_calls": tool_calls}] + trajectory_path.write_text(json.dumps(trajectory)) + case["label"]["method"] = "executable" + case["label"]["checks"] = [{"type": "file_written_contains", "path": "/workspace/a", "value": "done"}] + write_suite(suite_dir, suite) + result = CliRunner().invoke( + cli, + ["tier3", "validate-grader", str(suite_dir), "--check-suite", "--case", case["id"]], + ) + assert result.exit_code == 2, result.output + assert case["id"] in result.output + assert "Traceback" not in result.output + + @pytest.mark.parametrize( ("reward", "metric", "expected"), [ @@ -163,6 +215,20 @@ def test_behavior_pool(): assert all(r["observed"] == "error" for r in gv.observations(case, reward, gv.DEFAULT_THRESHOLDS)[1:]) +def test_behavior_expected_class_uses_suite_threshold(): + case = {"id": "mixed", "expected": {"overall": "fail", "metrics": {"behavior_check": [True, False]}}} + reward = { + "behavior_check": 0.5, + "details": {"behavior_check": {"results": [{"step": 1, "passed": True}, {"step": 2, "passed": False}]}}, + } + thresholds = gv.DEFAULT_THRESHOLDS | {"behavior_check": 0.5} + rows = gv.observations(case, reward, thresholds) + behavior = next(row for row in rows if row["metric"] == "behavior_check") + steps = [row for row in rows if row["metric"] == "behavior_steps"] + assert behavior["expected"] == behavior["observed"] == "pass" + assert [(row["expected"], row["observed"]) for row in steps] == [("pass", "pass"), ("fail", "fail")] + + def test_bundled_check_suite_and_usage(monkeypatch): monkeypatch.setattr(gv, "resolve_llm_provider", lambda: pytest.fail("provider accessed")) runner = CliRunner() @@ -293,6 +359,92 @@ def test_real_template_cli(judge_server, tmp_path): assert json.loads((output / "grader-validation.json").read_text()) == report +def test_attempt_uses_resolved_provider_environment(monkeypatch, tmp_path): + captured = {} + monkeypatch.delenv("SKILL_EVAL_LLM_PROVIDER", raising=False) + monkeypatch.setenv("OPENAI_API_KEY", "synthetic-openai-key") + monkeypatch.setenv("NVIDIA_API_KEY", "synthetic-nvidia-key") + + def run(_command, *, env, **_kwargs): + captured.update(env) + return SimpleNamespace(returncode=0) + + monkeypatch.setattr(gv.subprocess, "run", run) + case = { + "id": "provider", + "entry": {}, + "trajectory": None, + "expected": {"overall": "fail", "metrics": {}}, + } + gv._attempt( + gv.REFERENCE_SUITE, + case, + 1, + tmp_path, + gv.DEFAULT_THRESHOLDS, + 1, + { + "SKILL_EVAL_LLM_PROVIDER": "openai", + "SKILL_EVAL_LLM_MODEL": "resolved-model", + "OPENAI_API_KEY": "synthetic-openai-key", + }, + ) + assert captured["SKILL_EVAL_LLM_PROVIDER"] == "openai" + assert captured["SKILL_EVAL_LLM_MODEL"] == "resolved-model" + assert captured["NVIDIA_API_KEY"] == "synthetic-nvidia-key" + + +def test_provenance_records_resolved_judge_controls_and_verifier_files(tmp_path): + from skillevaluator.tier3.harbor.adapter import _VERIFIER_FILES + from skillevaluator.tier3.harbor.runner import _judge_model_config + + provider = SimpleNamespace(provider="openai", model="chat-model") + provider_env = { + "LLM_JUDGE_MODEL": "override-judge", + "LLM_JUDGE_FALLBACK_MODELS": "fallback-judge", + "LLM_JUDGE_FALLBACK_POLICY": "replace", + "LLM_JUDGE_RETRY_POLICY": "strict", + "SKILL_EVAL_JUDGE_CHARACTER_FACTS": "1", + "SKILL_EVAL_LLM_MAX_RETRIES": "2", + "SKILL_EVAL_JUDGE_FALLBACK_MODEL": "unused", + "SKILL_EVAL_JUDGE_REASONING_EFFORT": "unused", + "SKILL_EVAL_GOAL_ACCURACY_METHOD": "unused", + "OPENAI_API_KEY": "synthetic-secret", + } + suite = gv.load_suite(gv.REFERENCE_SUITE) + output = tmp_path / "provenance" + output.mkdir() + result = gv.qualify( + gv.REFERENCE_SUITE, + suite, + [], + output, + 1, + 1, + 1, + "assessment", + provider, + provider_env, + _judge_model_config(provider, provider_env, "default"), + ) + provenance = result["provenance"] + assert provenance["judge_config"]["model"] == "override-judge" + assert provenance["judge_environment"]["LLM_JUDGE_FALLBACK_MODELS"] == "fallback-judge" + assert provenance["judge_environment"]["LLM_JUDGE_RETRY_POLICY"] == "strict" + assert provenance["judge_environment"]["SKILL_EVAL_LLM_MAX_RETRIES"] == "2" + assert "SKILL_EVAL_JUDGE_FALLBACK_MODEL" not in provenance["judge_environment"] + assert "SKILL_EVAL_JUDGE_REASONING_EFFORT" not in provenance["judge_environment"] + assert "SKILL_EVAL_GOAL_ACCURACY_METHOD" not in provenance["judge_environment"] + assert "OPENAI_API_KEY" not in provenance["judge_environment"] + assert provenance["skillevaluator_version"] == gv.__version__ + digests = provenance["verifier_file_sha256"] + assert len(digests) == len(_VERIFIER_FILES) + assert any(name.endswith("/eval.py") for name in digests) + assert any(name.endswith("/checks.py") for name in digests) + assert any(name.endswith("/evidence.py") for name in digests) + assert len(provenance["verifier_sha256"]) == 64 + + def test_split_separation_and_gates(judge_server, tmp_path): result = CliRunner().invoke( cli, @@ -343,6 +495,26 @@ def test_split_separation_and_gates(judge_server, tmp_path): assert ( gv.gate_failures({"metrics": {"overall": {"false_pass_rate": gv.rate(1, 2)}}}, {"false_pass_rate": 0.5}) == [] ) + text = CliRunner().invoke( + cli, + [ + "tier3", + "validate-grader", + "--split", + "all", + "--case", + "arithmetic", + "--case", + "tuning-wrong", + "--repeats", + "1", + "-o", + str(tmp_path / "all-text"), + ], + ) + assert text.exit_code == 0, text.output + assert "Assessment grader qualification" in text.output + assert "Tuning grader qualification" in text.output def test_timeout_is_unscored(monkeypatch, tmp_path):