Skip to content

A plugin marketplace for GitHub Copilot and other AI agents that provides Power Platform development plugins, including reusable skills, agents, and commands for building and deploying solutions.

Add skill evaluation framework (#7)

Priyanshu Agrawalfab07b50ddfe
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 000000000..4195fe995
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,43 @@
+# Eval artifacts (generated during test runs)
+evals/artifacts/
+evals/temp/
+
+# Eval reports (aggregated results)
+evals/reports/
+
+# Python
+__pycache__/
+*.py[cod]
+*$py.class
+*.so
+.Python
+build/
+develop-eggs/
+dist/
+downloads/
+eggs/
+.eggs/
+lib64/
+parts/
+sdist/
+var/
+wheels/
+*.egg-info/
+.installed.cfg
+*.egg
+.venv/
+venv/
+ENV/
+
+# Logs
+*.log
+
+# IDE
+.idea/
+.vscode/
+*.swp
+*.swo
+
+# OS
+.DS_Store
+Thumbs.db
diff --git a/evals/README.md b/evals/README.md
new file mode 100644
index 000000000..1da473bd9
--- /dev/null
+++ b/evals/README.md
@@ -0,0 +1,183 @@
+# Evals Framework for Claude Code Skills
+
+A Python framework for systematically evaluating Claude Code skills using a two-stage grading approach.
+
+## Quick Start
+
+```bash
+# Run a single test
+python run_eval.py --plugin power-pages --skill create-site --test test-01
+
+# Run all tests for a skill
+python run_eval.py --plugin power-pages --skill create-site --all
+
+# Run with model-assisted grading
+python run_eval.py --plugin power-pages --skill create-site --all --grade
+
+# Run all skills in a plugin
+python run_eval.py --plugin power-pages --all
+```
+
+## Folder Structure
+
+```
+evals/
+├── README.md # This file
+├── run_eval.py # Main eval runner CLI
+├── grade_eval.py # Standalone grading CLI
+├── __init__.py
+├── shared/ # Shared utilities
+│ ├── __init__.py
+│ ├── helpers.py # Data classes and helper functions
+│ ├── runner.py # EvalRunner class
+│ ├── grader.py # Grader class
+│ └── rubrics/ # Grading rubric schemas
+│ ├── skill-trigger.schema.json
+│ ├── code-quality.schema.json
+│ └── process.schema.json
+├── power-pages/ # Plugin-specific evals
+│ ├── __init__.py
+│ ├── create-site/
+│ │ └── prompts.csv
+│ ├── setup-webapi/
+│ │ └── prompts.csv
+│ ├── setup-dataverse/
+│ │ └── prompts.csv
+│ ├── setup-auth/
+│ │ └── prompts.csv
+│ ├── integrate-webapi/
+│ │ └── prompts.csv
+│ ├── add-seo/
+│ │ └── prompts.csv
+│ ├── add-tests/
+│ │ └── prompts.csv
+│ └── add-sample-data/
+│ └── prompts.csv
+├── artifacts/ # Test outputs (gitignored)
+└── reports/ # Aggregate reports (gitignored)
+```
+
+## Prompt CSV Format
+
+Each skill has a `prompts.csv` file defining test cases:
+
+```csv
+id,should_trigger,prompt,expected_skill,notes
+test-01,true,"Create a demo app using /create-site",create-site,Explicit skill invocation
+test-02,true,"Build a React Power Pages site",create-site,Implicit invocation
+test-03,false,"Add Tailwind to my existing app",create-site,Negative control
+```
+
+**Fields:**
+- `id`: Unique test identifier
+- `should_trigger`: Whether the skill should be invoked (true/false)
+- `prompt`: The user prompt to test
+- `expected_skill`: The skill expected to trigger (for positive cases)
+- `notes`: Description of what the test validates
+
+## Two-Stage Grading
+
+### Stage 1: Deterministic Checks (Fast)
+
+Automated checks parsed from the execution trace:
+- Execution success (no errors)
+- Response generated
+- Reasonable token usage (< 50k)
+- Reasonable turn count (< 20)
+
+### Stage 2: Model-Assisted Rubric (Qualitative)
+
+Claude evaluates against rubric criteria:
+- **skill_invocation**: Correct skill invoked/not invoked
+- **response_quality**: Helpful, clear, appropriate response
+- **tool_usage**: Tools used efficiently
+- **plan_mode**: Plan mode used when appropriate
+
+## CLI Reference
+
+### run_eval.py
+
+```
+python run_eval.py --plugin PLUGIN --skill SKILL --test TEST_ID
+python run_eval.py --plugin PLUGIN --skill SKILL --all [--grade]
+python run_eval.py --plugin PLUGIN --all [--grade]
+
+Arguments:
+ --plugin Plugin name (required, e.g., power-pages)
+ --skill Skill name (optional, e.g., create-site)
+ --test Specific test ID (e.g., test-01)
+ --all Run all tests
+ --grade Enable model-assisted grading
+ --timeout Timeout per test in seconds (default: 300)
+```
+
+### grade_eval.py
+
+```
+python grade_eval.py --plugin PLUGIN --skill SKILL --test TEST_ID
+python grade_eval.py --artifacts-path PATH
+
+Arguments:
+ --plugin Plugin name
+ --skill Skill name
+ --test Test ID to grade
+ --artifacts-path Direct path to artifacts (alternative)
+```
+
+## How It Works
+
+1. **Load prompts**: Read test cases from `prompts.csv`
+2. **Execute Claude**: Run `claude -p --output-format=json "<prompt>"`
+3. **Parse output**: Extract result, metrics, and tool usage
+4. **Check trigger**: Determine if skill was invoked
+5. **Grade (optional)**: Run two-stage grading
+6. **Save artifacts**: Store results in `artifacts/` directory
+
+## Output Format
+
+Claude outputs JSON in this format:
+
+```json
+{
+ "type": "result",
+ "subtype": "success",
+ "is_error": false,
+ "result": "Response text...",
+ "session_id": "...",
+ "duration_ms": 4437,
+ "num_turns": 1,
+ "total_cost_usd": 0.19,
+ "usage": {
+ "input_tokens": 2,
+ "output_tokens": 12,
+ "cache_creation_input_tokens": 30452
+ }
+}
+```
+
+## Adding New Evals
+
+1. Create a new skill folder under the plugin directory
+2. Add `prompts.csv` with test cases
+3. Run with `python run_eval.py --plugin <plugin> --skill <skill> --all`
+
+## Interpreting Results
+
+### Pass Criteria
+
+- **Skill Trigger**: Correct skill invoked (or not invoked for negative cases)
+- **Process**: Execution completed successfully without errors
+- **Quality**: Response is helpful and appropriate (model-assisted)
+
+### Score Ranges
+
+- **90-100**: Excellent - All checks pass
+- **70-89**: Good - Minor issues
+- **50-69**: Fair - Some checks fail
+- **0-49**: Poor - Major issues
+
+## Requirements
+
+- Python 3.10+
+- Claude CLI installed and configured
+- No additional Python dependencies (uses stdlib only)
diff --git a/evals/grade_eval.py b/evals/grade_eval.py
new file mode 100644
index 000000000..ce03a49fe
--- /dev/null
+++ b/evals/grade_eval.py
@@ -0,0 +1,107 @@
+#!/usr/bin/env python3
+"""
+Standalone grading script for Claude Code skill evaluations.
+
+Usage:
+ python grade_eval.py --plugin power-pages --skill create-site --test test-01
+ python grade_eval.py --artifacts-path artifacts/power-pages/create-site/test-01
+"""
+
+import argparse
+import os
+import sys
+from pathlib import Path
+
+# Add parent to path for imports
+sys.path.insert(0, str(Path(__file__).parent))
+
+from shared import Grader, load_prompts, print_colored
+
+
+def main():
+ parser = argparse.ArgumentParser(
+ description="Grade Claude Code skill evaluation results",
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ epilog="""
+Examples:
+ python grade_eval.py --plugin power-pages --skill create-site --test test-01
+ python grade_eval.py --artifacts-path artifacts/power-pages/create-site/test-01
+ """,
+ )
+
+ parser.add_argument(
+ "--plugin",
+ help="Plugin name (e.g., power-pages)",
+ )
+ parser.add_argument(
+ "--skill",
+ help="Skill name (e.g., create-site)",
+ )
+ parser.add_argument(
+ "--test",
+ help="Test ID to grade (e.g., test-01)",
+ )
+ parser.add_argument(
+ "--artifacts-path",
+ help="Direct path to artifacts directory (alternative to plugin/skill/test)",
+ )
+
+ args = parser.parse_args()
+
+ base_dir = Path(__file__).parent
+
+ # Determine artifacts path
+ if args.artifacts_path:
+ artifacts_dir = Path(args.artifacts_path)
+ if not artifacts_dir.is_absolute():
+ artifacts_dir = base_dir / artifacts_dir
+ test_id = artifacts_dir.name
+ test_metadata = None
+ elif args.plugin and args.skill and args.test:
+ artifacts_dir = base_dir / "artifacts" / args.plugin / args.skill
+ test_id = args.test
+
+ # Load test metadata
+ prompts_file = base_dir / args.plugin / args.skill / "prompts.csv"
+ if prompts_file.exists():
+ tests = load_prompts(str(prompts_file))
+ test_metadata = next((t for t in tests if t.id == test_id), None)
+ else:
+ test_metadata = None
+ else:
+ parser.error("Either --artifacts-path or (--plugin, --skill, --test) must be specified")
+
+ if not artifacts_dir.exists():
+ print_colored(f"Artifacts directory not found: {artifacts_dir}", "red")
+ sys.exit(1)
+
+ test_artifacts = artifacts_dir / test_id if not args.artifacts_path else artifacts_dir
+ if not test_artifacts.exists():
+ print_colored(f"Test artifacts not found: {test_artifacts}", "red")
+ sys.exit(1)
+
+ # Load skill-specific rubric if available
+ rubric_path = None
+ if args.plugin and args.skill:
+ rubric_file = base_dir / args.plugin / args.skill / "rubric.json"
+ if rubric_file.exists():
+ rubric_path = str(rubric_file)
+
+ print_colored("=" * 50, "cyan")
+ print_colored("CLAUDE CODE EVAL GRADING", "cyan")
+ print_colored("=" * 50, "cyan")
+ print_colored(f"Test: {test_id}", "white")
+ print_colored(f"Artifacts: {test_artifacts}", "gray")
+ if rubric_path:
+ print_colored(f"Rubric: {rubric_path}", "gray")
+ print_colored("=" * 50, "cyan")
+
+ grader = Grader(
+ artifacts_dir=str(artifacts_dir if not args.artifacts_path else test_artifacts.parent),
+ rubric_path=rubric_path,
+ )
+ grader.grade(test_id, test_metadata)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/evals/power-pages/add-sample-data/prompts.csv b/evals/power-pages/add-sample-data/prompts.csv
new file mode 100644
index 000000000..f398f5a03
--- /dev/null
+++ b/evals/power-pages/add-sample-data/prompts.csv
@@ -0,0 +1,11 @@
+id,should_trigger,prompt,expected_skill,notes
+test-01,true,"Add sample data using /add-sample-data",add-sample-data,Explicit skill invocation
+test-02,true,"Insert test data into my Dataverse tables",add-sample-data,Implicit - inserting test data
+test-03,true,"Populate the database with sample records",add-sample-data,Implicit - populating with samples
+test-04,true,"Create demo data for products and orders tables",add-sample-data,Implicit - demo data creation
+test-05,true,"I need fake data to test my portal",add-sample-data,Implicit - fake data for testing
+test-06,false,"How do I delete sample data?",add-sample-data,Negative control - deletion not creation
+test-07,false,"Export my Dataverse data to CSV",add-sample-data,Negative control - export not import
+test-08,false,"Why is my data not showing up?",add-sample-data,Negative control - troubleshooting
+test-09,true,"Generate realistic test records for my tables",add-sample-data,Implicit - generating test records
+test-10,false,"What format should my import data be in?",add-sample-data,Negative control - informational question
diff --git a/evals/power-pages/add-sample-data/rubric.json b/evals/power-pages/add-sample-data/rubric.json
new file mode 100644
index 000000000..7fdee3f94
--- /dev/null
+++ b/evals/power-pages/add-sample-data/rubric.json
@@ -0,0 +1,31 @@
+{
+ "name": "add-sample-data",
+ "description": "Evaluates the add-sample-data skill execution",
+ "checks": [
+ {
+ "id": "read_memory_bank",
+ "description": "Read memory-bank.md to understand table structure",
+ "weight": 25
+ },
+ {
+ "id": "mentioned_relationships",
+ "description": "Discussed handling foreign key relationships in sample data",
+ "weight": 20
+ },
+ {
+ "id": "mentioned_realistic_data",
+ "description": "Discussed generating realistic/meaningful test data",
+ "weight": 20
+ },
+ {
+ "id": "mentioned_pac_cli",
+ "description": "Mentioned using PAC CLI or Web API for data insertion",
+ "weight": 15
+ },
+ {
+ "id": "response_quality",
+ "description": "Response is helpful, clear, and appropriate for the request",
+ "weight": 20
+ }
+ ]
+}
diff --git a/evals/power-pages/add-seo/prompts.csv b/evals/power-pages/add-seo/prompts.csv
new file mode 100644
index 000000000..fd04909c8
--- /dev/null
+++ b/evals/power-pages/add-seo/prompts.csv
@@ -0,0 +1,11 @@
+id,should_trigger,prompt,expected_skill,notes
+test-01,true,"Add SEO using /add-seo",add-seo,Explicit skill invocation
+test-02,true,"Add meta tags and sitemap to my Power Pages site",add-seo,Implicit - SEO assets mentioned
+test-03,true,"Optimize my site for search engines",add-seo,Implicit - SEO optimization
+test-04,true,"I need robots.txt and sitemap.xml for my portal",add-seo,Implicit - specific SEO files
+test-05,true,"Add favicon and Open Graph tags",add-seo,Implicit - SEO-related assets
+test-06,false,"How does Google index Power Pages sites?",add-seo,Negative control - informational question
+test-07,false,"Why isn't my site appearing in Google search?",add-seo,Negative control - troubleshooting
+test-08,false,"Change the page title in my React component",add-seo,Negative control - component change not SEO setup
+test-09,true,"Set up search engine optimization assets",add-seo,Implicit - SEO assets setup
+test-10,false,"What meta tags should I use for my site?",add-seo,Negative control - recommendation question
diff --git a/evals/power-pages/add-seo/rubric.json b/evals/power-pages/add-seo/rubric.json
new file mode 100644
index 000000000..8397fded1
--- /dev/null
+++ b/evals/power-pages/add-seo/rubric.json
@@ -0,0 +1,31 @@
+{
+ "name": "add-seo",
+ "description": "Evaluates the add-seo skill execution",
+ "checks": [
+ {
+ "id": "mentioned_meta_tags",
+ "description": "Discussed adding meta tags (title, description, Open Graph)",
+ "weight": 25
+ },
+ {
+ "id": "mentioned_sitemap",
+ "description": "Mentioned creating sitemap.xml",
+ "weight": 20
+ },
+ {
+ "id": "mentioned_robots",
+ "description": "Mentioned creating robots.txt",
+ "weight": 15
+ },
+ {
+ "id": "mentioned_favicon",
+ "description": "Discussed adding favicon",
+ "weight": 15
+ },
+ {
+ "id": "response_quality",
+ "description": "Response is helpful, clear, and appropriate for the request",
+ "weight": 25
+ }
+ ]
+}
diff --git a/evals/power-pages/add-tests/prompts.csv b/evals/power-pages/add-tests/prompts.csv
new file mode 100644
index 000000000..985a34a9e
--- /dev/null
+++ b/evals/power-pages/add-tests/prompts.csv
@@ -0,0 +1,11 @@
+id,should_trigger,prompt,expected_skill,notes
+test-01,true,"Add tests using /add-tests",add-tests,Explicit skill invocation
+test-02,true,"Set up unit tests and E2E tests for my site",add-tests,Implicit - testing setup
+test-03,true,"Add Vitest and Playwright to my Power Pages project",add-tests,Implicit - specific testing tools
+test-04,true,"I need automated tests for my React components",add-tests,Implicit - automated testing
+test-05,true,"Configure test coverage for my portal",add-tests,Implicit - test configuration
+test-06,false,"Why is my test failing?",add-tests,Negative control - test debugging
+test-07,false,"How do I mock API calls in tests?",add-tests,Negative control - testing technique question
+test-08,false,"Run the existing tests",add-tests,Negative control - running tests not adding
+test-09,true,"Set up a testing framework for the project",add-tests,Implicit - testing framework setup
+test-10,false,"What's the difference between Vitest and Jest?",add-tests,Negative control - informational question
diff --git a/evals/power-pages/add-tests/rubric.json b/evals/power-pages/add-tests/rubric.json
new file mode 100644
index 000000000..43ef59bc3
--- /dev/null
+++ b/evals/power-pages/add-tests/rubric.json
@@ -0,0 +1,31 @@
+{
+ "name": "add-tests",
+ "description": "Evaluates the add-tests skill execution",
+ "checks": [
+ {
+ "id": "mentioned_vitest",
+ "description": "Mentioned Vitest for unit testing",
+ "weight": 25
+ },
+ {
+ "id": "mentioned_playwright",
+ "description": "Mentioned Playwright for E2E testing",
+ "weight": 25
+ },
+ {
+ "id": "mentioned_test_structure",
+ "description": "Discussed test file structure and organization",
+ "weight": 15
+ },
+ {
+ "id": "mentioned_coverage",
+ "description": "Discussed test coverage",
+ "weight": 10
+ },
+ {
+ "id": "response_quality",
+ "description": "Response is helpful, clear, and appropriate for the request",
+ "weight": 25
+ }
+ ]
+}
diff --git a/evals/power-pages/create-site/prompts.csv b/evals/power-pages/create-site/prompts.csv
new file mode 100644
index 000000000..b7bf926a5
--- /dev/null
+++ b/evals/power-pages/create-site/prompts.csv
@@ -0,0 +1,11 @@
+id,should_trigger,prompt,expected_skill,notes
+test-01,true,"Create a Power Pages site using /create-site",create-site,Explicit skill invocation with slash command
+test-02,true,"Build a React Power Pages site for customer support portal",create-site,Implicit invocation - mentions Power Pages site creation
+test-03,true,"I need to create a new portal website using Vite and React for my company",create-site,Implicit invocation - portal/website creation
+test-04,true,"Set up a new Power Pages code site with Angular framework",create-site,Explicit Power Pages code site with framework choice
+test-05,true,"Create a demo app for Power Pages showcase",create-site,Demo app creation for Power Pages
+test-06,false,"Add Tailwind CSS to my existing React application",create-site,Negative control - modifying existing app not creating new
+test-07,false,"How do I deploy my React app to Azure?",create-site,Negative control - deployment question not site creation
+test-08,false,"Fix the bug in my Power Pages site login form",create-site,Negative control - bug fix not site creation
+test-09,true,"Scaffold a new Power Pages SPA with Vue.js",create-site,Implicit invocation - scaffold SPA for Power Pages
+test-10,false,"What frameworks does Power Pages support?",create-site,Negative control - informational question only
diff --git a/evals/power-pages/create-site/rubric.json b/evals/power-pages/create-site/rubric.json
new file mode 100644
index 000000000..3bfe1758d
--- /dev/null
+++ b/evals/power-pages/create-site/rubric.json
@@ -0,0 +1,26 @@
+{
+ "name": "create-site",
+ "description": "Evaluates the create-site skill execution",
+ "checks": [
+ {
+ "id": "asked_framework",
+ "description": "Asked user about framework preference (React, Angular, Vue, Astro)",
+ "weight": 20
+ },
+ {
+ "id": "mentioned_spa_constraint",
+ "description": "Mentioned SPA-only constraint (no Next.js, Nuxt, SSR frameworks)",
+ "weight": 15
+ },
+ {
+ "id": "asked_site_purpose",
+ "description": "Asked about site purpose and target audience",
+ "weight": 15
+ },
+ {
+ "id": "response_quality",
+ "description": "Response is helpful, clear, and appropriate for the request",
+ "weight": 15
+ }
+ ]
+}
diff --git a/evals/power-pages/integrate-webapi/prompts.csv b/evals/power-pages/integrate-webapi/prompts.csv
new file mode 100644
index 000000000..471007e3a
--- /dev/null
+++ b/evals/power-pages/integrate-webapi/prompts.csv
@@ -0,0 +1,11 @@
+id,should_trigger,prompt,expected_skill,notes
+test-01,true,"Integrate Web API using /integrate-webapi",integrate-webapi,Explicit skill invocation
+test-02,true,"Connect my React components to the Web API",integrate-webapi,Implicit - connecting frontend to API
+test-03,true,"Replace mock data with real API calls",integrate-webapi,Implicit - replacing mocks with API
+test-04,true,"Hook up the product listing to fetch from Dataverse",integrate-webapi,Implicit - connecting UI to Dataverse
+test-05,true,"Add API integration to display orders from the database",integrate-webapi,Implicit - API integration for data display
+test-06,false,"Why is my API call returning empty data?",integrate-webapi,Negative control - troubleshooting not integration
+test-07,false,"How do I format the API response?",integrate-webapi,Negative control - data formatting question
+test-08,false,"Set up CORS for my Web API",integrate-webapi,Negative control - CORS is server config
+test-09,true,"Wire up the forms to submit data via Web API",integrate-webapi,Implicit - form submission via API
+test-10,false,"What's the best way to handle API errors?",integrate-webapi,Negative control - best practices question
diff --git a/evals/power-pages/integrate-webapi/rubric.json b/evals/power-pages/integrate-webapi/rubric.json
new file mode 100644
index 000000000..2436958ab
--- /dev/null
+++ b/evals/power-pages/integrate-webapi/rubric.json
@@ -0,0 +1,36 @@
+{
+ "name": "integrate-webapi",
+ "description": "Evaluates the integrate-webapi skill execution",
+ "checks": [
+ {
+ "id": "read_memory_bank",
+ "description": "Read memory-bank.md to understand existing setup",
+ "weight": 20
+ },
+ {
+ "id": "mentioned_fetch_calls",
+ "description": "Discussed making fetch/API calls to /_api endpoints",
+ "weight": 20
+ },
+ {
+ "id": "mentioned_csrf_token",
+ "description": "Mentioned CSRF token for write operations",
+ "weight": 15
+ },
+ {
+ "id": "mentioned_error_handling",
+ "description": "Discussed error handling for API calls",
+ "weight": 15
+ },
+ {
+ "id": "suggested_next_steps",
+ "description": "Suggested follow-up skills like /setup-auth",
+ "weight": 10
+ },
+ {
+ "id": "response_quality",
+ "description": "Response is helpful, clear, and appropriate for the request",
+ "weight": 20
+ }
+ ]
+}
diff --git a/evals/power-pages/setup-auth/prompts.csv b/evals/power-pages/setup-auth/prompts.csv
new file mode 100644
index 000000000..63eecc8b7
--- /dev/null
+++ b/evals/power-pages/setup-auth/prompts.csv
@@ -0,0 +1,11 @@
+id,should_trigger,prompt,expected_skill,notes
+test-01,true,"Set up authentication using /setup-auth",setup-auth,Explicit skill invocation
+test-02,true,"Add user login to my Power Pages site",setup-auth,Implicit - adding login functionality
+test-03,true,"Configure authentication for my customer portal",setup-auth,Implicit - authentication configuration
+test-04,true,"I need to implement Azure AD B2C login for my site",setup-auth,Implicit - specific auth provider setup
+test-05,true,"Set up user registration and authentication flows",setup-auth,Implicit - auth flow setup
+test-06,false,"Why can't users log into my site?",setup-auth,Negative control - troubleshooting not setup
+test-07,false,"How does Power Pages authentication work?",setup-auth,Negative control - informational question
+test-08,false,"Change the login page styling",setup-auth,Negative control - styling not auth setup
+test-09,true,"Configure local authentication with email registration",setup-auth,Implicit - local auth configuration
+test-10,false,"What authentication providers does Power Pages support?",setup-auth,Negative control - informational question
diff --git a/evals/power-pages/setup-auth/rubric.json b/evals/power-pages/setup-auth/rubric.json
new file mode 100644
index 000000000..3028efd17
--- /dev/null
+++ b/evals/power-pages/setup-auth/rubric.json
@@ -0,0 +1,36 @@
+{
+ "name": "setup-auth",
+ "description": "Evaluates the setup-auth skill execution",
+ "checks": [
+ {
+ "id": "asked_auth_provider",
+ "description": "Asked about authentication provider preference (Azure AD B2C, local, etc.)",
+ "weight": 20
+ },
+ {
+ "id": "used_plan_mode",
+ "description": "Entered plan mode to design authentication strategy",
+ "weight": 20
+ },
+ {
+ "id": "mentioned_registration",
+ "description": "Discussed user registration flow",
+ "weight": 15
+ },
+ {
+ "id": "mentioned_web_roles",
+ "description": "Mentioned assigning web roles to authenticated users",
+ "weight": 15
+ },
+ {
+ "id": "mentioned_security",
+ "description": "Discussed security considerations",
+ "weight": 15
+ },
+ {
+ "id": "response_quality",
+ "description": "Response is helpful, clear, and appropriate for the request",
+ "weight": 15
+ }
+ ]
+}
diff --git a/evals/power-pages/setup-dataverse/prompts.csv b/evals/power-pages/setup-dataverse/prompts.csv
new file mode 100644
index 000000000..0e8e2f868
--- /dev/null
+++ b/evals/power-pages/setup-dataverse/prompts.csv
@@ -0,0 +1,11 @@
+id,should_trigger,prompt,expected_skill,notes
+test-01,true,"Set up Dataverse tables using /setup-dataverse",setup-dataverse,Explicit skill invocation
+test-02,true,"Create the database schema for my Power Pages site",setup-dataverse,Implicit - database schema creation
+test-03,true,"I need to design tables for a customer portal with orders and products",setup-dataverse,Implicit - table design for portal
+test-04,true,"Set up Dataverse with tables for blog posts and categories",setup-dataverse,Implicit - Dataverse table setup
+test-05,true,"Create the data model for my Power Pages application",setup-dataverse,Implicit - data model creation
+test-06,false,"How do I query Dataverse tables?",setup-dataverse,Negative control - query question not setup
+test-07,false,"Add a lookup column to my existing table",setup-dataverse,Negative control - schema modification not initial setup
+test-08,false,"What's the difference between Dataverse and SQL Server?",setup-dataverse,Negative control - informational question
+test-09,true,"Define the database tables for event registration system",setup-dataverse,Implicit - table definition for specific use case
+test-10,false,"Export data from my Dataverse table",setup-dataverse,Negative control - data operation not schema setup
diff --git a/evals/power-pages/setup-dataverse/rubric.json b/evals/power-pages/setup-dataverse/rubric.json
new file mode 100644
index 000000000..b70b72410
--- /dev/null
+++ b/evals/power-pages/setup-dataverse/rubric.json
@@ -0,0 +1,36 @@
+{
+ "name": "setup-dataverse",
+ "description": "Evaluates the setup-dataverse skill execution",
+ "checks": [
+ {
+ "id": "asked_requirements",
+ "description": "Asked about data requirements and table structure needs",
+ "weight": 20
+ },
+ {
+ "id": "used_plan_mode",
+ "description": "Entered plan mode to design data architecture",
+ "weight": 20
+ },
+ {
+ "id": "mentioned_relationships",
+ "description": "Discussed table relationships (lookups, many-to-many)",
+ "weight": 15
+ },
+ {
+ "id": "mentioned_prefix",
+ "description": "Mentioned publisher prefix for table names",
+ "weight": 10
+ },
+ {
+ "id": "suggested_next_steps",
+ "description": "Suggested follow-up skills like /add-sample-data or /setup-webapi",
+ "weight": 15
+ },
+ {
+ "id": "response_quality",
+ "description": "Response is helpful, clear, and appropriate for the request",
+ "weight": 20
+ }
+ ]
+}
diff --git a/evals/power-pages/setup-webapi/prompts.csv b/evals/power-pages/setup-webapi/prompts.csv
new file mode 100644
index 000000000..814e582cc
--- /dev/null
+++ b/evals/power-pages/setup-webapi/prompts.csv
@@ -0,0 +1,11 @@
+id,should_trigger,prompt,expected_skill,notes
+test-01,true,"Set up Web API using /setup-webapi",setup-webapi,Explicit skill invocation
+test-02,true,"Configure table permissions for my Power Pages site",setup-webapi,Implicit - table permissions configuration
+test-03,true,"I need to set up CRUD access for my Dataverse tables",setup-webapi,Implicit - CRUD access setup
+test-04,true,"Create web roles and entity permissions for customer portal",setup-webapi,Implicit - web roles and entity permissions
+test-05,true,"Enable Web API access for products and orders tables",setup-webapi,Implicit - enabling Web API for specific tables
+test-06,false,"How do I call the Web API from JavaScript?",setup-webapi,Negative control - usage question not setup
+test-07,false,"Why is my Web API returning 403 forbidden?",setup-webapi,Negative control - troubleshooting not setup
+test-08,false,"Add a new column to my Dataverse table",setup-webapi,Negative control - schema change not API setup
+test-09,true,"Configure site settings for Webapi access",setup-webapi,Implicit - site settings for Web API
+test-10,false,"What is the difference between table permissions and web roles?",setup-webapi,Negative control - informational question
diff --git a/evals/power-pages/setup-webapi/rubric.json b/evals/power-pages/setup-webapi/rubric.json
new file mode 100644
index 000000000..e19345629
--- /dev/null
+++ b/evals/power-pages/setup-webapi/rubric.json
@@ -0,0 +1,36 @@
+{
+ "name": "setup-webapi",
+ "description": "Evaluates the setup-webapi skill execution",
+ "checks": [
+ {
+ "id": "read_memory_bank",
+ "description": "Read memory-bank.md to get table names and context",
+ "weight": 20
+ },
+ {
+ "id": "used_plan_mode",
+ "description": "Entered plan mode to design permissions strategy",
+ "weight": 20
+ },
+ {
+ "id": "asked_environment",
+ "description": "Asked which environment to upload to",
+ "weight": 15
+ },
+ {
+ "id": "mentioned_site_settings",
+ "description": "Mentioned creating Webapi enabled/fields site settings",
+ "weight": 15
+ },
+ {
+ "id": "mentioned_web_roles",
+ "description": "Mentioned web roles (Anonymous, Authenticated, custom)",
+ "weight": 15
+ },
+ {
+ "id": "response_quality",
+ "description": "Response is helpful, clear, and appropriate for the request",
+ "weight": 15
+ }
+ ]
+}
diff --git a/evals/run_eval.py b/evals/run_eval.py
new file mode 100644
index 000000000..7d3e75ee3
--- /dev/null
+++ b/evals/run_eval.py
@@ -0,0 +1,208 @@
+#!/usr/bin/env python3
+"""
+Main entry point for running Claude Code skill evaluations.
+
+Usage:
+ python run_eval.py --plugin power-pages --skill create-site --test test-01
+ python run_eval.py --plugin power-pages --skill create-site --all
+ python run_eval.py --plugin power-pages --skill create-site --all --grade
+ python run_eval.py --plugin power-pages --all
+"""
+
+import argparse
+import os
+import sys
+from pathlib import Path
+
+# Add parent to path for imports
+sys.path.insert(0, str(Path(__file__).parent))
+
+from shared import EvalRunner, Grader, load_prompts, print_colored
+
+
+def get_skill_dirs(plugin_dir: str) -> list[str]:
+ """Get all skill directories in a plugin folder."""
+ skills = []
+ for item in os.listdir(plugin_dir):
+ item_path = os.path.join(plugin_dir, item)
+ if os.path.isdir(item_path) and not item.startswith("_"):
+ prompts_file = os.path.join(item_path, "prompts.csv")
+ if os.path.exists(prompts_file):
+ skills.append(item)
+ return sorted(skills)
+
+
+def run_skill_evals(
+ plugin: str,
+ skill: str,
+ test_id: str | None,
+ run_all: bool,
+ grade: bool,
+ base_dir: str,
+) -> dict:
+ """Run evaluations for a single skill."""
+ skill_dir = os.path.join(base_dir, plugin, skill)
+ prompts_file = os.path.join(skill_dir, "prompts.csv")
+
+ if not os.path.exists(prompts_file):
+ print_colored(f"Prompts file not found: {prompts_file}", "red")
+ return {"error": "Prompts file not found"}
+
+ artifacts_dir = os.path.join(base_dir, "artifacts", plugin, skill)
+ work_dir = os.path.join(base_dir, "temp", plugin, skill)
+
+ # Project dir is the plugin directory (e.g., plugins/power-pages)
+ # This ensures Claude has access to the plugin context
+ repo_root = os.path.dirname(base_dir)
+ project_dir = os.path.join(repo_root, "plugins", plugin)
+
+ runner = EvalRunner(
+ prompts_path=prompts_file,
+ artifacts_dir=artifacts_dir,
+ work_dir=work_dir,
+ project_dir=project_dir,
+ plugin_dir=project_dir, # Same as project_dir - the plugin root
+ )
+
+ results = runner.run(test_id=test_id, run_all=run_all)
+
+ if grade:
+ # Load skill-specific rubric if available
+ rubric_path = os.path.join(skill_dir, "rubric.json")
+ if not os.path.exists(rubric_path):
+ rubric_path = None
+ print_colored(f"No rubric.json found, using default rubric", "yellow")
+
+ grader = Grader(artifacts_dir=artifacts_dir, rubric_path=rubric_path)
+ tests = load_prompts(prompts_file)
+ test_map = {t.id: t for t in tests}
+
+ for result in results:
+ if result.status not in ("timeout", "error"):
+ grader.grade(result.id, test_map.get(result.id))
+
+ return {
+ "skill": skill,
+ "total": len(results),
+ "pass": sum(1 for r in results if r.status == "pass"),
+ "fail": sum(1 for r in results if r.status == "fail"),
+ "error": sum(1 for r in results if r.status in ("error", "timeout")),
+ }
+
+
+def main():
+ parser = argparse.ArgumentParser(
+ description="Run Claude Code skill evaluations",
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ epilog="""
+Examples:
+ python run_eval.py --plugin power-pages --skill create-site --test test-01
+ python run_eval.py --plugin power-pages --skill create-site --all
+ python run_eval.py --plugin power-pages --skill create-site --all --grade
+ python run_eval.py --plugin power-pages --all
+ """,
+ )
+
+ parser.add_argument(
+ "--plugin",
+ required=True,
+ help="Plugin name (e.g., power-pages)",
+ )
+ parser.add_argument(
+ "--skill",
+ help="Skill name (e.g., create-site). Omit to run all skills.",
+ )
+ parser.add_argument(
+ "--test",
+ help="Specific test ID to run (e.g., test-01)",
+ )
+ parser.add_argument(
+ "--all",
+ action="store_true",
+ help="Run all tests",
+ )
+ parser.add_argument(
+ "--grade",
+ action="store_true",
+ help="Run model-assisted grading after tests",
+ )
+ parser.add_argument(
+ "--timeout",
+ type=int,
+ default=300,
+ help="Timeout per test in seconds (default: 300)",
+ )
+
+ args = parser.parse_args()
+
+ # Validate arguments
+ if not args.test and not args.all:
+ parser.error("Either --test or --all must be specified")
+
+ base_dir = Path(__file__).parent
+ plugin_dir = base_dir / args.plugin
+
+ if not plugin_dir.exists():
+ print_colored(f"Plugin directory not found: {plugin_dir}", "red")
+ sys.exit(1)
+
+ # Determine which skills to run
+ if args.skill:
+ skills = [args.skill]
+ else:
+ skills = get_skill_dirs(str(plugin_dir))
+ if not skills:
+ print_colored(f"No skills found in {plugin_dir}", "red")
+ sys.exit(1)
+
+ print_colored("=" * 50, "cyan")
+ print_colored("CLAUDE CODE SKILL EVALUATIONS", "cyan")
+ print_colored("=" * 50, "cyan")
+ print_colored(f"Plugin: {args.plugin}", "white")
+ print_colored(f"Skills: {', '.join(skills)}", "white")
+ print_colored("=" * 50, "cyan")
+
+ # Run evaluations
+ all_results = []
+ for skill in skills:
+ print_colored(f"\n{'='*50}", "magenta")
+ print_colored(f"SKILL: {skill}", "magenta")
+ print_colored(f"{'='*50}", "magenta")
+
+ result = run_skill_evals(
+ plugin=args.plugin,
+ skill=skill,
+ test_id=args.test,
+ run_all=args.all,
+ grade=args.grade,
+ base_dir=str(base_dir),
+ )
+ all_results.append(result)
+
+ # Print aggregate summary
+ if len(all_results) > 1:
+ print_colored(f"\n{'='*50}", "cyan")
+ print_colored("AGGREGATE SUMMARY", "cyan")
+ print_colored(f"{'='*50}", "cyan")
+
+ total_tests = sum(r.get("total", 0) for r in all_results)
+ total_pass = sum(r.get("pass", 0) for r in all_results)
+ total_fail = sum(r.get("fail", 0) for r in all_results)
+ total_error = sum(r.get("error", 0) for r in all_results)
+
+ for r in all_results:
+ if "error" not in r:
+ pass_rate = (r["pass"] / r["total"] * 100) if r["total"] > 0 else 0
+ color = "green" if pass_rate >= 80 else ("yellow" if pass_rate >= 50 else "red")
+ print_colored(
+ f"{r['skill']}: {r['pass']}/{r['total']} passed ({pass_rate:.1f}%)",
+ color,
+ )
+
+ overall_rate = (total_pass / total_tests * 100) if total_tests > 0 else 0
+ color = "green" if overall_rate >= 80 else ("yellow" if overall_rate >= 50 else "red")
+ print_colored(f"\nOVERALL: {total_pass}/{total_tests} passed ({overall_rate:.1f}%)", color)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/evals/shared/__init__.py b/evals/shared/__init__.py
new file mode 100644
index 000000000..d41b2b59e
--- /dev/null
+++ b/evals/shared/__init__.py
@@ -0,0 +1,40 @@
+"""Shared utilities for Claude Code skill evaluations."""
+
+from .helpers import (
+ TestCase,
+ ClaudeOutput,
+ TestResult,
+ GradeResult,
+ load_prompts,
+ run_claude,
+ test_skill_triggered,
+ test_plan_mode_used,
+ get_metrics,
+ run_deterministic_checks,
+ save_json,
+ load_json,
+ get_timestamp,
+ print_colored,
+)
+
+from .runner import EvalRunner
+from .grader import Grader
+
+__all__ = [
+ "TestCase",
+ "ClaudeOutput",
+ "TestResult",
+ "GradeResult",
+ "load_prompts",
+ "run_claude",
+ "test_skill_triggered",
+ "test_plan_mode_used",
+ "get_metrics",
+ "run_deterministic_checks",
+ "save_json",
+ "load_json",
+ "get_timestamp",
+ "print_colored",
+ "EvalRunner",
+ "Grader",
+]
diff --git a/evals/shared/grader.py b/evals/shared/grader.py
new file mode 100644
index 000000000..92ad406a2
--- /dev/null
+++ b/evals/shared/grader.py
@@ -0,0 +1,290 @@
+"""
+Grading utilities for Claude Code skill evaluations.
+"""
+
+import json
+import os
+import re
+from typing import Optional
+
+from .helpers import (
+ ClaudeOutput,
+ GradeResult,
+ TestCase,
+ run_claude,
+ run_deterministic_checks,
+ get_metrics,
+ save_json,
+ load_json,
+ print_colored,
+)
+
+
+class Grader:
+ """Grades Claude Code skill evaluation results."""
+
+ def __init__(
+ self,
+ artifacts_dir: str,
+ rubric_path: Optional[str] = None,
+ ):
+ """
+ Initialize the grader.
+
+ Args:
+ artifacts_dir: Path to test artifacts directory
+ rubric_path: Path to skill-specific rubric.json file
+ """
+ self.artifacts_dir = artifacts_dir
+ self.rubric_path = rubric_path
+ self.rubric = self._load_rubric()
+
+ def _load_rubric(self) -> dict:
+ """Load rubric from JSON file or return default."""
+ if self.rubric_path and os.path.exists(self.rubric_path):
+ return load_json(self.rubric_path)
+
+ # Default rubric if none provided
+ return {
+ "name": "default",
+ "description": "Default evaluation rubric",
+ "checks": [
+ {
+ "id": "skill_invocation",
+ "description": "Appropriately invoked or not invoked the skill",
+ "weight": 30,
+ },
+ {
+ "id": "response_quality",
+ "description": "Response is helpful, clear, and appropriate",
+ "weight": 40,
+ },
+ {
+ "id": "tool_usage",
+ "description": "Tools were used appropriately and efficiently",
+ "weight": 30,
+ },
+ ],
+ }
+
+ def grade(self, test_id: str, test_metadata: Optional[TestCase] = None) -> GradeResult:
+ """
+ Grade a test result using two-stage grading.
+
+ Args:
+ test_id: The test ID to grade
+ test_metadata: Optional test case metadata
+
+ Returns:
+ GradeResult with grading details
+ """
+ test_artifacts = os.path.join(self.artifacts_dir, test_id)
+
+ # Load output
+ output_path = os.path.join(test_artifacts, "output.json")
+ if not os.path.exists(output_path):
+ return GradeResult(
+ overall_pass=False,
+ score=0,
+ deterministic={"error": "No output file found"},
+ )
+
+ output_data = load_json(output_path)
+ output = ClaudeOutput.from_json(output_data)
+
+ print_colored("Grading evaluation...", "yellow")
+ print_colored(f"Artifacts: {test_artifacts}", "gray")
+ print_colored(f"Rubric: {self.rubric.get('name', 'default')}", "gray")
+
+ # Stage 1: Deterministic checks
+ print_colored("\n--- Stage 1: Deterministic Checks ---", "cyan")
+ deterministic = run_deterministic_checks(output)
+
+ for check in deterministic["checks"]:
+ status = "PASS" if check["pass"] else "FAIL"
+ color = "green" if check["pass"] else "red"
+ print_colored(f" [{status}] {check['id']}", color)
+
+ # Stage 2: Model-assisted grading with rubric
+ print_colored("\n--- Stage 2: Model-Assisted Grading ---", "cyan")
+ print_colored(f"Using {len(self.rubric['checks'])} rubric checks", "gray")
+ model_grade = self._run_model_grading(output, test_metadata, test_artifacts)
+
+ if model_grade.get("checks"):
+ for check in model_grade["checks"]:
+ status = "PASS" if check.get("pass") else "FAIL"
+ color = "green" if check.get("pass") else "red"
+ weight = self._get_check_weight(check.get("id", ""))
+ notes = check.get("notes", "")[:60] + "..." if len(check.get("notes", "")) > 60 else check.get("notes", "")
+ print_colored(f" [{status}] {check.get('id', 'unknown')} (weight: {weight}): {notes}", color)
+
+ # Calculate final grade with weighted scoring
+ det_pass_count = sum(1 for c in deterministic["checks"] if c["pass"])
+ det_total = len(deterministic["checks"])
+ det_score = (det_pass_count / det_total * 30) if det_total > 0 else 0 # 30% for deterministic
+
+ model_score = self._calculate_weighted_score(model_grade.get("checks", [])) # 70% for rubric
+
+ overall_pass = (
+ all(c["pass"] for c in deterministic["checks"]) and
+ model_grade.get("overall_pass", False)
+ )
+
+ final_score = int(det_score + model_score)
+
+ result = GradeResult(
+ overall_pass=overall_pass,
+ score=final_score,
+ deterministic=deterministic,
+ model_assisted=model_grade,
+ )
+
+ # Save grade
+ grade_path = os.path.join(test_artifacts, "grade.json")
+ save_json({
+ **result.to_dict(),
+ "rubric_used": self.rubric.get("name", "default"),
+ "metrics": get_metrics(output),
+ }, grade_path)
+
+ # Print final grade
+ print_colored("\n--- Final Grade ---", "cyan")
+ color = "green" if overall_pass else "red"
+ print_colored(f"Overall: {'PASS' if overall_pass else 'FAIL'}", color)
+
+ score_color = "green" if final_score >= 70 else ("yellow" if final_score >= 50 else "red")
+ print_colored(f"Score: {final_score}/100", score_color)
+ print_colored(f"Grade saved to: {grade_path}", "gray")
+
+ return result
+
+ def _get_check_weight(self, check_id: str) -> int:
+ """Get weight for a check from rubric."""
+ for check in self.rubric.get("checks", []):
+ if check.get("id") == check_id:
+ return check.get("weight", 0)
+ return 0
+
+ def _calculate_weighted_score(self, checks: list) -> float:
+ """Calculate weighted score from rubric checks (out of 70 points)."""
+ if not checks:
+ return 35 # Default to 50% if no checks
+
+ total_weight = sum(c.get("weight", 0) for c in self.rubric.get("checks", []))
+ if total_weight == 0:
+ return 35
+
+ earned_weight = 0
+ for check in checks:
+ if check.get("pass"):
+ weight = self._get_check_weight(check.get("id", ""))
+ earned_weight += weight
+
+ return (earned_weight / total_weight) * 70 # 70% of total score
+
+ def _run_model_grading(
+ self,
+ output: ClaudeOutput,
+ test_metadata: Optional[TestCase],
+ artifacts_dir: str,
+ ) -> dict:
+ """
+ Run model-assisted grading using Claude with skill-specific rubric.
+
+ Args:
+ output: The Claude output to grade
+ test_metadata: Optional test case metadata
+ artifacts_dir: Directory to save grading artifacts
+
+ Returns:
+ Dictionary with grading results
+ """
+ # Build test info
+ test_info = ""
+ if test_metadata:
+ test_info = f"""- Test ID: {test_metadata.id}
+- Should trigger skill: {test_metadata.should_trigger}
+- Expected skill: {test_metadata.expected_skill}
+- Prompt: {test_metadata.prompt}"""
+ else:
+ test_info = "- No test metadata available"
+
+ # Build rubric checks for prompt
+ checks_list = "\n".join([
+ f'{i+1}. **{c["id"]}**: {c["description"]} (weight: {c["weight"]})'
+ for i, c in enumerate(self.rubric.get("checks", []))
+ ])
+
+ # Build expected JSON structure
+ checks_json = ",\n ".join([
+ f'{{"id": "{c["id"]}", "pass": true/false, "notes": "explanation"}}'
+ for c in self.rubric.get("checks", [])
+ ])
+
+ grading_prompt = f"""You are evaluating a Claude Code skill execution. Grade it against the rubric criteria.
+
+## Test Information
+{test_info}
+
+## Claude's Response
+{output.result[:8000] if output.result else "No response"}
+
+## Execution Metrics
+- Duration: {output.duration_ms}ms
+- Turns: {output.num_turns}
+- Cost: ${output.total_cost_usd:.4f}
+
+## Rubric Criteria
+Evaluate each of these checks:
+
+{checks_list}
+
+For each check, determine if it passes based on the response content. A check passes if the response demonstrates or mentions the expected behavior.
+
+Respond with ONLY a JSON object in this exact format:
+{{
+ "overall_pass": true/false,
+ "score": 0-100,
+ "checks": [
+ {checks_json}
+ ]
+}}"""
+
+ print_colored("Running model-assisted grading...", "yellow")
+
+ try:
+ grade_output, exit_code, duration = run_claude(
+ grading_prompt,
+ artifacts_dir,
+ timeout=120,
+ )
+
+ if grade_output and grade_output.result:
+ # Save raw grading output
+ save_json(
+ grade_output.raw,
+ os.path.join(artifacts_dir, "grade-raw.json"),
+ )
+
+ # Extract JSON from response
+ json_match = re.search(r'\{[\s\S]*\}', grade_output.result)
+ if json_match:
+ try:
+ return json.loads(json_match.group())
+ except json.JSONDecodeError:
+ pass
+
+ return {
+ "overall_pass": False,
+ "score": 50,
+ "checks": [],
+ "notes": "Could not parse grading response",
+ }
+
+ except Exception as e:
+ return {
+ "overall_pass": False,
+ "score": 0,
+ "checks": [],
+ "error": str(e),
+ }
diff --git a/evals/shared/helpers.py b/evals/shared/helpers.py
new file mode 100644
index 000000000..1465d79dc
--- /dev/null
+++ b/evals/shared/helpers.py
@@ -0,0 +1,424 @@
+"""
+Helper functions and data classes for Claude Code skill evaluations.
+"""
+
+import csv
+import json
+import os
+import re
+import subprocess
+import time
+from dataclasses import dataclass, field
+from datetime import datetime
+from typing import Any, Optional
+
+
+@dataclass
+class TestCase:
+ """Represents a single test case from a prompts CSV."""
+ id: str
+ should_trigger: bool
+ prompt: str
+ expected_skill: str
+ notes: str = ""
+
+
+@dataclass
+class ClaudeOutput:
+ """Parsed output from `claude -p --output-format=json`."""
+ type: str = ""
+ subtype: str = ""
+ is_error: bool = False
+ result: str = ""
+ session_id: str = ""
+ duration_ms: int = 0
+ duration_api_ms: int = 0
+ num_turns: int = 0
+ total_cost_usd: float = 0.0
+ usage: dict = field(default_factory=dict)
+ raw: dict = field(default_factory=dict)
+ trace: list = field(default_factory=list) # Full conversation trace (separate from raw)
+
+ @classmethod
+ def from_json(cls, data: dict, trace: list = None) -> "ClaudeOutput":
+ """Create ClaudeOutput from parsed JSON."""
+ return cls(
+ type=data.get("type", ""),
+ subtype=data.get("subtype", ""),
+ is_error=data.get("is_error", False),
+ result=data.get("result", ""),
+ session_id=data.get("session_id", ""),
+ duration_ms=data.get("duration_ms", 0),
+ duration_api_ms=data.get("duration_api_ms", 0),
+ num_turns=data.get("num_turns", 0),
+ total_cost_usd=data.get("total_cost_usd", 0.0),
+ usage=data.get("usage", {}),
+ raw=data,
+ trace=trace or [],
+ )
+
+
+@dataclass
+class TestResult:
+ """Result of running a single test."""
+ id: str
+ status: str # "pass", "fail", "error", "timeout"
+ duration: float = 0.0
+ exit_code: int = 0
+ should_trigger: bool = False
+ skill_triggered: bool = False
+ expected_skill: str = ""
+ error: str = ""
+ output: Optional[ClaudeOutput] = None
+
+ def to_dict(self, include_response: bool = False) -> dict:
+ """Convert to dictionary for JSON serialization."""
+ result = {
+ "id": self.id,
+ "status": self.status,
+ "duration": self.duration,
+ "exit_code": self.exit_code,
+ "should_trigger": self.should_trigger,
+ "skill_triggered": self.skill_triggered,
+ "expected_skill": self.expected_skill,
+ "error": self.error,
+ }
+
+ if include_response and self.output:
+ result["response"] = {
+ "result": self.output.result,
+ "duration_ms": self.output.duration_ms,
+ "duration_api_ms": self.output.duration_api_ms,
+ "num_turns": self.output.num_turns,
+ "total_cost_usd": self.output.total_cost_usd,
+ "usage": self.output.usage,
+ "session_id": self.output.session_id,
+ "is_error": self.output.is_error,
+ "subtype": self.output.subtype,
+ }
+
+ return result
+
+
+@dataclass
+class GradeResult:
+ """Result of grading a test."""
+ overall_pass: bool
+ score: int
+ checks: list = field(default_factory=list)
+ deterministic: dict = field(default_factory=dict)
+ model_assisted: dict = field(default_factory=dict)
+
+ def to_dict(self) -> dict:
+ """Convert to dictionary for JSON serialization."""
+ return {
+ "overall_pass": self.overall_pass,
+ "score": self.score,
+ "checks": self.checks,
+ "deterministic": self.deterministic,
+ "model_assisted": self.model_assisted,
+ }
+
+
+def load_prompts(csv_path: str) -> list[TestCase]:
+ """Load test cases from a prompts CSV file."""
+ tests = []
+ with open(csv_path, "r", encoding="utf-8") as f:
+ reader = csv.DictReader(f)
+ for row in reader:
+ tests.append(TestCase(
+ id=row["id"],
+ should_trigger=row["should_trigger"].lower() == "true",
+ prompt=row["prompt"],
+ expected_skill=row["expected_skill"],
+ notes=row.get("notes", ""),
+ ))
+ return tests
+
+
+def run_claude(
+ prompt: str,
+ work_dir: str,
+ timeout: int = 300,
+ project_dir: Optional[str] = None,
+ plugin_dir: Optional[str] = None,
+ model: str = "sonnet",
+) -> tuple[Optional[ClaudeOutput], int, float]:
+ """
+ Run Claude in detached mode with JSON output.
+
+ Args:
+ prompt: The prompt to send to Claude
+ work_dir: Working directory for storing artifacts
+ timeout: Timeout in seconds
+ project_dir: Project directory to run Claude from
+ plugin_dir: Plugin directory to load skills from (--plugin-dir)
+ model: Model to use (sonnet, opus, haiku). Defaults to sonnet.
+
+ Returns:
+ Tuple of (ClaudeOutput or None, exit_code, duration_seconds)
+ """
+ os.makedirs(work_dir, exist_ok=True)
+
+ # Determine the directory to run Claude from
+ run_dir = project_dir if project_dir else work_dir
+
+ start_time = time.time()
+
+ # Build command
+ cmd = ["claude", "-p", "--verbose", "--output-format=json", "--model", model]
+
+ # Add plugin directory if specified
+ if plugin_dir:
+ cmd.extend(["--plugin-dir", plugin_dir])
+
+ # Use -- to separate options from the prompt (required when using variadic flags like --plugin-dir)
+ cmd.append("--")
+ cmd.append(prompt)
+
+ try:
+ result = subprocess.run(
+ cmd,
+ cwd=run_dir,
+ capture_output=True,
+ text=True,
+ timeout=timeout,
+ )
+
+ duration = time.time() - start_time
+
+ if result.stdout:
+ try:
+ data = json.loads(result.stdout)
+
+ # Verbose output is a JSON array of messages
+ # The last item with type="result" contains the summary
+ if isinstance(data, list):
+ # Find the result message
+ result_msg = None
+ for msg in reversed(data):
+ if msg.get("type") == "result":
+ result_msg = msg
+ break
+
+ if result_msg:
+ # Pass trace separately to avoid circular reference
+ return ClaudeOutput.from_json(result_msg, trace=data), result.returncode, duration
+
+ # Non-verbose output is a single object
+ return ClaudeOutput.from_json(data), result.returncode, duration
+ except json.JSONDecodeError:
+ return ClaudeOutput(result=result.stdout), result.returncode, duration
+
+ return None, result.returncode, duration
+
+ except subprocess.TimeoutExpired:
+ duration = time.time() - start_time
+ return None, -1, duration
+
+
+def test_skill_triggered(output: Optional[ClaudeOutput], expected_skill: str) -> bool:
+ """
+ Check if the expected skill was triggered based on Claude's output.
+
+ Uses the full conversation trace to detect:
+ 1. Skill tool calls and their results
+ 2. Tool usage patterns characteristic of the skill
+ 3. Response content (fallback)
+ """
+ if not output:
+ return False
+
+ raw = output.raw
+ trace = output.trace # Use separate trace attribute
+
+ # Signal 1: Check for Skill tool calls in the trace
+ skill_call_found = False
+ skill_call_succeeded = False
+
+ for msg in trace:
+ # Check assistant messages for Skill tool calls
+ if msg.get("type") == "assistant":
+ message = msg.get("message", {})
+ content = message.get("content", [])
+ for block in content:
+ if block.get("type") == "tool_use" and block.get("name") == "Skill":
+ skill_input = block.get("input", {})
+ skill_name = skill_input.get("skill", "")
+ # Check if this is the expected skill (with or without plugin prefix)
+ if expected_skill in skill_name or skill_name in expected_skill:
+ skill_call_found = True
+
+ # Check tool results for success/failure
+ if msg.get("type") == "user":
+ tool_result = msg.get("tool_use_result", "")
+ if isinstance(tool_result, str) and "Unknown skill" in tool_result:
+ # Skill was called but not found - this is a FAIL
+ skill_call_succeeded = False
+ elif skill_call_found and not isinstance(tool_result, str):
+ # Non-error result after skill call
+ skill_call_succeeded = True
+
+ # If skill was explicitly called and succeeded, it was triggered
+ if skill_call_found and skill_call_succeeded:
+ return True
+
+ # Signal 2: Check if Claude read the SKILL.md and followed it
+ # (fallback when skill isn't registered but Claude executes manually)
+ skill_md_read = False
+ skill_workflow_started = False
+
+ for msg in trace:
+ if msg.get("type") == "user":
+ result = msg.get("tool_use_result", {})
+ if isinstance(result, dict):
+ file_info = result.get("file", {})
+ file_path = file_info.get("filePath", "")
+ if "SKILL.md" in file_path and expected_skill.replace("-", "") in file_path.lower().replace("-", ""):
+ skill_md_read = True
+
+ # Signal 3: Check for characteristic tool usage (skill is working)
+ permission_denials = raw.get("permission_denials", [])
+ if permission_denials:
+ tool_names = [d.get("tool_name") for d in permission_denials]
+ # AskUserQuestion is characteristic of skill workflows
+ if "AskUserQuestion" in tool_names:
+ skill_workflow_started = True
+
+ # If SKILL.md was read AND workflow started, skill was triggered (manual execution)
+ if skill_md_read and skill_workflow_started:
+ return True
+
+ # Signal 4: Multiple turns with skill-related content
+ if output.num_turns >= 5 and skill_md_read:
+ return True
+
+ # Signal 5: Negative indicators - skill definitely NOT triggered
+ if output.result:
+ result = output.result.lower()
+ negative_patterns = [
+ r"need permission to access",
+ r"don't have access",
+ r"cannot access",
+ r"unable to access",
+ r"check your available skills",
+ ]
+ for pattern in negative_patterns:
+ if re.search(pattern, result):
+ return False
+
+ return False
+
+
+def test_plan_mode_used(output: Optional[ClaudeOutput]) -> bool:
+ """Check if plan mode was entered."""
+ if not output or not output.result:
+ return False
+
+ result = output.result.lower()
+ patterns = ["enterplanmode", "entering plan mode", "plan mode", "/plan"]
+
+ return any(p in result for p in patterns)
+
+
+def get_metrics(output: Optional[ClaudeOutput]) -> dict:
+ """Extract metrics from Claude's output."""
+ if not output:
+ return {}
+
+ return {
+ "duration_ms": output.duration_ms,
+ "duration_api_ms": output.duration_api_ms,
+ "num_turns": output.num_turns,
+ "total_cost_usd": output.total_cost_usd,
+ "is_error": output.is_error,
+ "subtype": output.subtype,
+ "input_tokens": output.usage.get("input_tokens", 0),
+ "output_tokens": output.usage.get("output_tokens", 0),
+ "cache_read_tokens": output.usage.get("cache_read_input_tokens", 0),
+ "cache_creation_tokens": output.usage.get("cache_creation_input_tokens", 0),
+ }
+
+
+def run_deterministic_checks(output: Optional[ClaudeOutput]) -> dict:
+ """Run stage 1 deterministic checks."""
+ checks = []
+
+ # Check 1: Execution success
+ exec_success = output is not None and not output.is_error and output.subtype == "success"
+ checks.append({
+ "id": "execution_success",
+ "pass": exec_success,
+ "notes": "Execution completed successfully" if exec_success else "Execution failed or errored",
+ })
+
+ # Check 2: Response generated
+ has_response = output is not None and output.result and len(output.result) > 0
+ response_len = len(output.result) if output and output.result else 0
+ checks.append({
+ "id": "response_generated",
+ "pass": has_response,
+ "notes": f"Response of {response_len} chars",
+ })
+
+ # Check 3: Reasonable token usage
+ token_limit = 50000
+ total_tokens = 0
+ if output and output.usage:
+ total_tokens = (
+ output.usage.get("input_tokens", 0) +
+ output.usage.get("output_tokens", 0) +
+ output.usage.get("cache_creation_input_tokens", 0)
+ )
+ reasonable_tokens = total_tokens < token_limit
+ checks.append({
+ "id": "reasonable_tokens",
+ "pass": reasonable_tokens,
+ "notes": f"Used {total_tokens} tokens (limit: {token_limit})",
+ })
+
+ # Check 4: Reasonable turn count
+ turn_limit = 20
+ num_turns = output.num_turns if output else 0
+ reasonable_turns = num_turns < turn_limit
+ checks.append({
+ "id": "reasonable_turns",
+ "pass": reasonable_turns,
+ "notes": f"Used {num_turns} turns (limit: {turn_limit})",
+ })
+
+ return {"checks": checks}
+
+
+def save_json(data: Any, path: str) -> None:
+ """Save data as JSON to a file."""
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "w", encoding="utf-8") as f:
+ json.dump(data, f, indent=2, default=str)
+
+
+def load_json(path: str) -> dict:
+ """Load JSON from a file."""
+ with open(path, "r", encoding="utf-8") as f:
+ return json.load(f)
+
+
+def get_timestamp() -> str:
+ """Get current timestamp string."""
+ return datetime.now().strftime("%Y-%m-%d-%H%M%S")
+
+
+def print_colored(text: str, color: str) -> None:
+ """Print colored text to console."""
+ colors = {
+ "red": "\033[91m",
+ "green": "\033[92m",
+ "yellow": "\033[93m",
+ "blue": "\033[94m",
+ "magenta": "\033[95m",
+ "cyan": "\033[96m",
+ "white": "\033[97m",
+ "gray": "\033[90m",
+ "reset": "\033[0m",
+ }
+ print(f"{colors.get(color, '')}{text}{colors['reset']}")
diff --git a/evals/shared/runner.py b/evals/shared/runner.py
new file mode 100644
index 000000000..07d63f3fe
--- /dev/null
+++ b/evals/shared/runner.py
@@ -0,0 +1,270 @@
+"""
+Eval runner for Claude Code skill evaluations.
+"""
+
+import os
+import shutil
+from pathlib import Path
+from typing import Optional
+
+from .helpers import (
+ TestCase,
+ TestResult,
+ ClaudeOutput,
+ load_prompts,
+ run_claude,
+ test_skill_triggered,
+ save_json,
+ get_timestamp,
+ print_colored,
+)
+
+
+class EvalRunner:
+ """Runs evaluations for Claude Code skills."""
+
+ def __init__(
+ self,
+ prompts_path: str,
+ artifacts_dir: str = "artifacts",
+ work_dir: str = "temp",
+ timeout: int = 300,
+ project_dir: Optional[str] = None,
+ plugin_dir: Optional[str] = None,
+ ):
+ """
+ Initialize the eval runner.
+
+ Args:
+ prompts_path: Path to the prompts CSV file
+ artifacts_dir: Directory for storing test artifacts
+ work_dir: Working directory for test execution
+ timeout: Timeout per test in seconds
+ project_dir: Project directory to run Claude from
+ plugin_dir: Plugin directory to load skills from (--plugin-dir)
+ """
+ self.prompts_path = prompts_path
+ self.artifacts_dir = artifacts_dir
+ self.work_dir = work_dir
+ self.timeout = timeout
+ self.project_dir = project_dir
+ self.plugin_dir = plugin_dir
+ self.tests = load_prompts(prompts_path)
+
+ def run_test(self, test: TestCase) -> TestResult:
+ """
+ Run a single test case.
+
+ Args:
+ test: The test case to run
+
+ Returns:
+ TestResult with execution details
+ """
+ print_colored(f"\n{'='*40}", "cyan")
+ print_colored(f"Running: {test.id}", "cyan")
+ print_colored(f"Prompt: {test.prompt}", "gray")
+ print_colored(f"Expected trigger: {test.should_trigger}", "gray")
+ print_colored(f"{'='*40}\n", "cyan")
+
+ # Create test-specific directories
+ test_artifacts = os.path.join(self.artifacts_dir, test.id)
+ test_work_dir = os.path.join(self.work_dir, test.id)
+
+ # Clean up previous artifacts
+ if os.path.exists(test_artifacts):
+ shutil.rmtree(test_artifacts)
+ os.makedirs(test_artifacts, exist_ok=True)
+
+ # Create fresh work directory
+ if os.path.exists(test_work_dir):
+ shutil.rmtree(test_work_dir)
+ os.makedirs(test_work_dir, exist_ok=True)
+
+ try:
+ print_colored("Executing claude...", "yellow")
+
+ output, exit_code, duration = run_claude(
+ test.prompt,
+ test_work_dir,
+ self.timeout,
+ project_dir=self.project_dir,
+ plugin_dir=self.plugin_dir,
+ )
+
+ if exit_code == -1:
+ print_colored(f"TIMEOUT after {self.timeout} seconds", "red")
+ result = TestResult(
+ id=test.id,
+ status="timeout",
+ duration=duration,
+ exit_code=-1,
+ )
+ else:
+ print_colored(
+ f"Completed in {duration:.2f}s with exit code {exit_code}",
+ "green",
+ )
+
+ # Determine if skill was triggered
+ skill_triggered = test_skill_triggered(output, test.expected_skill)
+ passes = skill_triggered == test.should_trigger
+
+ # Debug: show detection signals
+ if output:
+ print_colored(f"Turns: {output.num_turns}", "gray")
+
+ # Check for Skill tool calls in trace
+ trace = output.trace
+ skill_calls = []
+ tools_used = []
+ for msg in trace:
+ if msg.get("type") == "assistant":
+ content = msg.get("message", {}).get("content", [])
+ for block in content:
+ if block.get("type") == "tool_use":
+ tool_name = block.get("name", "")
+ tools_used.append(tool_name)
+ if tool_name == "Skill":
+ skill_calls.append(block.get("input", {}).get("skill", ""))
+
+ if skill_calls:
+ print_colored(f"Skill calls: {skill_calls}", "cyan")
+ if tools_used:
+ unique_tools = list(dict.fromkeys(tools_used)) # preserve order, remove dups
+ print_colored(f"Tools used: {unique_tools[:10]}", "gray")
+
+ # Show permission denials
+ permission_denials = output.raw.get("permission_denials", [])
+ if permission_denials:
+ denied = [d.get("tool_name") for d in permission_denials]
+ print_colored(f"Permission denied: {denied}", "yellow")
+
+ if output.result:
+ preview = output.result[:120].replace("\n", " ")
+ print_colored(f"Response: {preview}...", "gray")
+
+ result = TestResult(
+ id=test.id,
+ status="pass" if passes else "fail",
+ duration=duration,
+ exit_code=exit_code,
+ should_trigger=test.should_trigger,
+ skill_triggered=skill_triggered,
+ expected_skill=test.expected_skill,
+ output=output,
+ )
+
+ if passes:
+ print_colored("PASS - Skill trigger matched expectation", "green")
+ else:
+ print_colored(
+ f"FAIL - Expected trigger={test.should_trigger}, "
+ f"got trigger={skill_triggered}",
+ "red",
+ )
+ print_colored(
+ f" (should_trigger={test.should_trigger}, skill_triggered={skill_triggered})",
+ "gray",
+ )
+
+ except Exception as e:
+ print_colored(f"ERROR: {e}", "red")
+ result = TestResult(
+ id=test.id,
+ status="error",
+ error=str(e),
+ )
+
+ # Save test artifacts
+ save_json(result.to_dict(), os.path.join(test_artifacts, "result.json"))
+
+ if result.output:
+ # Save output (raw doesn't contain trace, so no circular reference)
+ save_json(result.output.raw, os.path.join(test_artifacts, "output.json"))
+
+ # Save full trace separately
+ if result.output.trace:
+ save_json(result.output.trace, os.path.join(test_artifacts, "trace.json"))
+
+ return result
+
+ def run(
+ self,
+ test_id: Optional[str] = None,
+ run_all: bool = False,
+ ) -> list[TestResult]:
+ """
+ Run evaluations.
+
+ Args:
+ test_id: Specific test ID to run (optional)
+ run_all: Run all tests if True
+
+ Returns:
+ List of TestResults
+ """
+ if not test_id and not run_all:
+ raise ValueError("Either test_id or run_all must be specified")
+
+ tests_to_run = self.tests
+ if test_id:
+ tests_to_run = [t for t in self.tests if t.id == test_id]
+ if not tests_to_run:
+ raise ValueError(f"Test ID not found: {test_id}")
+
+ results = []
+ for test in tests_to_run:
+ result = self.run_test(test)
+ results.append(result)
+
+ # Print summary
+ self._print_summary(results)
+
+ # Save report
+ self._save_report(results)
+
+ return results
+
+ def _print_summary(self, results: list[TestResult]) -> None:
+ """Print summary of results."""
+ print_colored(f"\n{'='*40}", "cyan")
+ print_colored("EVAL SUMMARY", "cyan")
+ print_colored(f"{'='*40}", "cyan")
+
+ pass_count = sum(1 for r in results if r.status == "pass")
+ fail_count = sum(1 for r in results if r.status == "fail")
+ error_count = sum(1 for r in results if r.status in ("error", "timeout"))
+ total = len(results)
+
+ color = "green" if fail_count == 0 and error_count == 0 else "yellow"
+ print_colored(
+ f"Total: {total} | Pass: {pass_count} | Fail: {fail_count} | Error: {error_count}",
+ color,
+ )
+
+ def _save_report(self, results: list[TestResult]) -> None:
+ """Save summary report."""
+ reports_dir = os.path.join(os.path.dirname(self.artifacts_dir), "reports")
+ os.makedirs(reports_dir, exist_ok=True)
+
+ timestamp = get_timestamp()
+ pass_count = sum(1 for r in results if r.status == "pass")
+ total = len(results)
+
+ report = {
+ "timestamp": timestamp,
+ "prompts_file": self.prompts_path,
+ "results": [r.to_dict(include_response=True) for r in results],
+ "summary": {
+ "total": total,
+ "pass": pass_count,
+ "fail": sum(1 for r in results if r.status == "fail"),
+ "error": sum(1 for r in results if r.status in ("error", "timeout")),
+ "pass_rate": round((pass_count / total) * 100, 2) if total > 0 else 0,
+ },
+ }
+
+ report_path = os.path.join(reports_dir, f"report-{timestamp}.json")
+ save_json(report, report_path)
+ print_colored(f"\nReport saved to: {report_path}", "gray")